[med-svn] [conquest-dicom-server] 04/05: Imported Upstream version 1.4.17c
Pablo Lorenzzoni
spectra at moszumanska.debian.org
Tue Jan 28 21:16:05 UTC 2014
This is an automated email from the git hooks/post-receive script.
spectra pushed a commit to branch master
in repository conquest-dicom-server.
commit bdb4fe6d861374e42f33122d9c3dc07011e06a24
Author: Pablo Lorenzzoni <pablo at propus.com.br>
Date: Tue Jan 28 18:55:49 2014 -0200
Imported Upstream version 1.4.17c
---
DicomConformance_FilesLST_Changes.pdf | Bin 0 -> 599714 bytes
aaac.cxx | 368 +
aaac.hpp | 103 +
aarj.cxx | 331 +
aarj.hpp | 119 +
aarq.cxx | 1191 +
aarq.hpp | 350 +
acrnema.map | 26 +
amap.cpp | 292 +
anonymize_script.cq | 1 +
array.tcc | 328 +
array.thh | 133 +
base.hpp | 76 +
buffer.cxx | 657 +
buffer.thh | 107 +
cctypes.h | 163 +
conquest-pacs.sh | 97 +
conquest.jpg | Bin 0 -> 6230 bytes
constant.h | 61 +
data/printer_files/accesstest.log | 0
dbsql.cpp | 3540 +++
deivr.cxx | 1322 +
deivr.hpp | 184 +
device.cpp | 4163 ++++
dgate.cpp | 24322 +++++++++++++++++++
dgate.dic | 4025 +++
dgate.hpp | 294 +
dgatefn.cpp | 694 +
dgatesop.lst | 133 +
dgatesop.lst.nojpg | 133 +
dgatesop.lst.withjpg | 133 +
dicom.hpp | 83 +
dicom.ini | 86 +
dicom.ini.dbase | 86 +
dicom.ini.mysql | 86 +
dicom.ini.postgres | 86 +
dicom.ini.sqlite | 86 +
dicom.ini.www | 109 +
dicom.sql | 153 +
dicom.sql.dbase | 187 +
dicom.sql.mysql | 153 +
dicom.sql.postgres | 153 +
dicom.sql.sqlite | 153 +
dimsec.cxx | 814 +
dimsec.hpp | 159 +
dimsen.cxx | 1306 +
dimsen.hpp | 236 +
dprintf.cpp | 344 +
dprintf.hpp | 57 +
endian.cpd | 103 +
endian.cxx | 121 +
endian.hpd | 53 +
endian.hpp | 107 +
farray.thh | 259 +
filepdu.cxx | 356 +
flpdu.cxx | 1027 +
flpdu.hpp | 78 +
gpps.cpp | 362 +
gpps.hpp | 27 +
jasper-1.900.1-6ct/COPYRIGHT | 2 +
jasper-1.900.1-6ct/ChangeLog | 0
jasper-1.900.1-6ct/INSTALL | 3 +
jasper-1.900.1-6ct/LICENSE | 51 +
jasper-1.900.1-6ct/Makefile.am | 91 +
jasper-1.900.1-6ct/Makefile.in | 711 +
jasper-1.900.1-6ct/NEWS | 19 +
jasper-1.900.1-6ct/README | 22 +
jasper-1.900.1-6ct/acaux/config.guess | 1411 ++
jasper-1.900.1-6ct/acaux/config.sub | 1500 ++
jasper-1.900.1-6ct/acaux/depcomp | 423 +
jasper-1.900.1-6ct/acaux/install-sh | 251 +
jasper-1.900.1-6ct/acaux/ltmain.sh | 6911 ++++++
jasper-1.900.1-6ct/acaux/missing | 336 +
jasper-1.900.1-6ct/acaux/mkinstalldirs | 99 +
jasper-1.900.1-6ct/aclocal.m4 | 7249 ++++++
jasper-1.900.1-6ct/configure | 23856 ++++++++++++++++++
jasper-1.900.1-6ct/configure.ac | 405 +
jasper-1.900.1-6ct/data/colorprofiles/README | 18 +
jasper-1.900.1-6ct/data/colorprofiles/erimm.icm | Bin 0 -> 2082 bytes
jasper-1.900.1-6ct/data/colorprofiles/esrgb.icm | Bin 0 -> 13332 bytes
.../data/colorprofiles/esrgbgrey.icm | Bin 0 -> 4472 bytes
jasper-1.900.1-6ct/data/colorprofiles/grey.icm | Bin 0 -> 454 bytes
jasper-1.900.1-6ct/data/colorprofiles/greyromm.icm | Bin 0 -> 414 bytes
jasper-1.900.1-6ct/data/colorprofiles/romm.icm | Bin 0 -> 546 bytes
jasper-1.900.1-6ct/data/colorprofiles/sgray.icm | Bin 0 -> 394 bytes
jasper-1.900.1-6ct/data/colorprofiles/srgb.icm | Bin 0 -> 3144 bytes
jasper-1.900.1-6ct/data/colorprofiles/sycc.icm | Bin 0 -> 30736 bytes
jasper-1.900.1-6ct/data/images/README | 11 +
jasper-1.900.1-6ct/data/images/example.mif | 11 +
jasper-1.900.1-6ct/data/images/example.mif0 | 11 +
jasper-1.900.1-6ct/data/images/feep.pnm | 11 +
jasper-1.900.1-6ct/data/images/feep2.pnm | 11 +
jasper-1.900.1-6ct/data/images/goldenears.bmp | Bin 0 -> 36918 bytes
jasper-1.900.1-6ct/data/images/goldenears.jpg | Bin 0 -> 2582 bytes
jasper-1.900.1-6ct/data/images/goldenears.pnm | 292 +
jasper-1.900.1-6ct/data/images/goldenears.ras | Bin 0 -> 36896 bytes
jasper-1.900.1-6ct/data/images/goldenears_gray.jpg | Bin 0 -> 2259 bytes
jasper-1.900.1-6ct/data/images/goldenears_gray.pnm | 451 +
jasper-1.900.1-6ct/data/images/goldenears_gray.ras | Bin 0 -> 13088 bytes
jasper-1.900.1-6ct/data/images/small_16x1.pnm | Bin 0 -> 28 bytes
jasper-1.900.1-6ct/data/images/small_1x1.pnm | 4 +
jasper-1.900.1-6ct/data/images/stawamuschief.pnm | 4 +
.../data/images/stawamuschief_gray.pnm | 4 +
jasper-1.900.1-6ct/data/images/test.pnm | 11 +
.../doc/Changes_for_gcc4 warnings.txt | 59 +
jasper-1.900.1-6ct/doc/Changes_for_jpeg-6c.txt | 118 +
jasper-1.900.1-6ct/doc/README | 8 +
jasper-1.900.1-6ct/jasper.spec.in | 101 +
jasper-1.900.1-6ct/jasperlib.c | 72 +
jasper-1.900.1-6ct/src/Makefile.am | 61 +
jasper-1.900.1-6ct/src/Makefile.in | 550 +
jasper-1.900.1-6ct/src/README | 1 +
jasper-1.900.1-6ct/src/appl/Makefile.am | 91 +
jasper-1.900.1-6ct/src/appl/Makefile.in | 649 +
jasper-1.900.1-6ct/src/appl/dummy.c | 0
jasper-1.900.1-6ct/src/appl/dummy2.c | 65 +
jasper-1.900.1-6ct/src/appl/imgcmp.1 | 24 +
jasper-1.900.1-6ct/src/appl/imgcmp.c | 576 +
jasper-1.900.1-6ct/src/appl/imginfo.1 | 23 +
jasper-1.900.1-6ct/src/appl/imginfo.c | 223 +
jasper-1.900.1-6ct/src/appl/jasper.1 | 19 +
jasper-1.900.1-6ct/src/appl/jasper.c | 555 +
jasper-1.900.1-6ct/src/appl/jiv.1 | 24 +
jasper-1.900.1-6ct/src/appl/jiv.c | 1086 +
jasper-1.900.1-6ct/src/appl/tmrdemo.c | 52 +
jasper-1.900.1-6ct/src/libjasper/Makefile.am | 89 +
jasper-1.900.1-6ct/src/libjasper/Makefile.in | 673 +
.../src/libjasper/Obsolete/20100119/amake.bat | 6 +
.../src/libjasper/Obsolete/20100119/jasperlib.c | 104 +
jasper-1.900.1-6ct/src/libjasper/README | 2 +
jasper-1.900.1-6ct/src/libjasper/base/Makefile.am | 76 +
jasper-1.900.1-6ct/src/libjasper/base/Makefile.in | 533 +
jasper-1.900.1-6ct/src/libjasper/base/jas_cm.c | 1283 +
jasper-1.900.1-6ct/src/libjasper/base/jas_debug.c | 137 +
jasper-1.900.1-6ct/src/libjasper/base/jas_getopt.c | 169 +
jasper-1.900.1-6ct/src/libjasper/base/jas_icc.c | 1722 ++
.../src/libjasper/base/jas_iccdata.c | 517 +
jasper-1.900.1-6ct/src/libjasper/base/jas_image.c | 1446 ++
jasper-1.900.1-6ct/src/libjasper/base/jas_init.c | 162 +
jasper-1.900.1-6ct/src/libjasper/base/jas_malloc.c | 131 +
jasper-1.900.1-6ct/src/libjasper/base/jas_seq.c | 454 +
jasper-1.900.1-6ct/src/libjasper/base/jas_stream.c | 1150 +
jasper-1.900.1-6ct/src/libjasper/base/jas_string.c | 96 +
jasper-1.900.1-6ct/src/libjasper/base/jas_tmr.c | 149 +
jasper-1.900.1-6ct/src/libjasper/base/jas_tvp.c | 237 +
.../src/libjasper/base/jas_version.c | 67 +
jasper-1.900.1-6ct/src/libjasper/bmp/Makefile.am | 67 +
jasper-1.900.1-6ct/src/libjasper/bmp/Makefile.in | 510 +
jasper-1.900.1-6ct/src/libjasper/bmp/bmp_cod.c | 135 +
jasper-1.900.1-6ct/src/libjasper/bmp/bmp_cod.h | 215 +
jasper-1.900.1-6ct/src/libjasper/bmp/bmp_dec.c | 464 +
jasper-1.900.1-6ct/src/libjasper/bmp/bmp_enc.c | 395 +
jasper-1.900.1-6ct/src/libjasper/bmp/bmp_enc.h | 72 +
jasper-1.900.1-6ct/src/libjasper/dummy.c | 3 +
.../src/libjasper/include/Makefile.am | 59 +
.../src/libjasper/include/Makefile.in | 549 +
.../src/libjasper/include/jasper/Makefile.am | 80 +
.../src/libjasper/include/jasper/Makefile.in | 508 +
.../src/libjasper/include/jasper/jas_cm.h | 266 +
.../src/libjasper/include/jasper/jas_config.h.in | 172 +
.../src/libjasper/include/jasper/jas_config2.h | 89 +
.../src/libjasper/include/jasper/jas_debug.h | 114 +
.../src/libjasper/include/jasper/jas_fix.h | 358 +
.../src/libjasper/include/jasper/jas_getopt.h | 131 +
.../src/libjasper/include/jasper/jas_icc.h | 407 +
.../src/libjasper/include/jasper/jas_image.h | 564 +
.../src/libjasper/include/jasper/jas_init.h | 83 +
.../src/libjasper/include/jasper/jas_malloc.h | 124 +
.../src/libjasper/include/jasper/jas_math.h | 117 +
.../src/libjasper/include/jasper/jas_seq.h | 301 +
.../src/libjasper/include/jasper/jas_stream.h | 464 +
.../src/libjasper/include/jasper/jas_string.h | 95 +
.../src/libjasper/include/jasper/jas_tmr.h | 103 +
.../src/libjasper/include/jasper/jas_tvp.h | 151 +
.../src/libjasper/include/jasper/jas_types.h | 228 +
.../src/libjasper/include/jasper/jas_version.h | 120 +
.../src/libjasper/include/jasper/jasper.h | 93 +
jasper-1.900.1-6ct/src/libjasper/jp2/Makefile.am | 67 +
jasper-1.900.1-6ct/src/libjasper/jp2/Makefile.in | 510 +
jasper-1.900.1-6ct/src/libjasper/jp2/jp2_cod.c | 921 +
jasper-1.900.1-6ct/src/libjasper/jp2/jp2_cod.h | 304 +
jasper-1.900.1-6ct/src/libjasper/jp2/jp2_dec.c | 603 +
jasper-1.900.1-6ct/src/libjasper/jp2/jp2_dec.h | 85 +
jasper-1.900.1-6ct/src/libjasper/jp2/jp2_enc.c | 436 +
jasper-1.900.1-6ct/src/libjasper/jpc/Makefile.am | 105 +
jasper-1.900.1-6ct/src/libjasper/jpc/Makefile.in | 568 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_bs.c | 440 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_bs.h | 231 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_cod.h | 78 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_cs.c | 1644 ++
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_cs.h | 763 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_dec.c | 2305 ++
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_dec.h | 696 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_enc.c | 2620 ++
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_enc.h | 646 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_fix.h | 144 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_flt.h | 80 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_math.c | 121 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_math.h | 99 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mct.c | 291 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mct.h | 111 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqcod.c | 179 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqcod.h | 124 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqdec.c | 306 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqdec.h | 271 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqenc.c | 392 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqenc.h | 236 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_qmfb.c | 3144 +++
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_qmfb.h | 113 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1cod.c | 497 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1cod.h | 295 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1dec.c | 923 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1dec.h | 88 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1enc.c | 959 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1enc.h | 93 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2cod.c | 684 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2cod.h | 299 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2dec.c | 581 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2dec.h | 95 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2enc.c | 655 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2enc.h | 106 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tagtree.c | 393 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tagtree.h | 167 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tsfb.c | 288 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tsfb.h | 138 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_util.c | 194 +
jasper-1.900.1-6ct/src/libjasper/jpc/jpc_util.h | 77 +
jasper-1.900.1-6ct/src/libjasper/jpg/Makefile.am | 79 +
jasper-1.900.1-6ct/src/libjasper/jpg/Makefile.in | 524 +
jasper-1.900.1-6ct/src/libjasper/jpg/README | 6 +
jasper-1.900.1-6ct/src/libjasper/jpg/jpg_cod.h | 82 +
jasper-1.900.1-6ct/src/libjasper/jpg/jpg_dec.c | 354 +
jasper-1.900.1-6ct/src/libjasper/jpg/jpg_dummy.c | 110 +
jasper-1.900.1-6ct/src/libjasper/jpg/jpg_enc.c | 435 +
jasper-1.900.1-6ct/src/libjasper/jpg/jpg_enc.h | 70 +
jasper-1.900.1-6ct/src/libjasper/jpg/jpg_jpeglib.h | 76 +
jasper-1.900.1-6ct/src/libjasper/jpg/jpg_val.c | 111 +
jasper-1.900.1-6ct/src/libjasper/mif/Makefile.am | 66 +
jasper-1.900.1-6ct/src/libjasper/mif/Makefile.in | 506 +
jasper-1.900.1-6ct/src/libjasper/mif/README | 1 +
jasper-1.900.1-6ct/src/libjasper/mif/mif_cod.c | 752 +
jasper-1.900.1-6ct/src/libjasper/mif/mif_cod.h | 123 +
jasper-1.900.1-6ct/src/libjasper/pgx/Makefile.am | 67 +
jasper-1.900.1-6ct/src/libjasper/pgx/Makefile.in | 510 +
jasper-1.900.1-6ct/src/libjasper/pgx/pgx_cod.c | 78 +
jasper-1.900.1-6ct/src/libjasper/pgx/pgx_cod.h | 118 +
jasper-1.900.1-6ct/src/libjasper/pgx/pgx_dec.c | 414 +
jasper-1.900.1-6ct/src/libjasper/pgx/pgx_enc.c | 230 +
jasper-1.900.1-6ct/src/libjasper/pgx/pgx_enc.h | 69 +
jasper-1.900.1-6ct/src/libjasper/pnm/Makefile.am | 67 +
jasper-1.900.1-6ct/src/libjasper/pnm/Makefile.in | 510 +
jasper-1.900.1-6ct/src/libjasper/pnm/pnm_cod.c | 146 +
jasper-1.900.1-6ct/src/libjasper/pnm/pnm_cod.h | 156 +
jasper-1.900.1-6ct/src/libjasper/pnm/pnm_dec.c | 565 +
jasper-1.900.1-6ct/src/libjasper/pnm/pnm_enc.c | 452 +
jasper-1.900.1-6ct/src/libjasper/pnm/pnm_enc.h | 70 +
jasper-1.900.1-6ct/src/libjasper/ras/Makefile.am | 67 +
jasper-1.900.1-6ct/src/libjasper/ras/Makefile.in | 510 +
jasper-1.900.1-6ct/src/libjasper/ras/ras_cod.c | 74 +
jasper-1.900.1-6ct/src/libjasper/ras/ras_cod.h | 164 +
jasper-1.900.1-6ct/src/libjasper/ras/ras_dec.c | 398 +
jasper-1.900.1-6ct/src/libjasper/ras/ras_enc.c | 318 +
jasper-1.900.1-6ct/src/libjasper/ras/ras_enc.h | 70 +
jasper-1.900.1-6ct/src/msvc/Makefile.am | 71 +
jasper-1.900.1-6ct/src/msvc/Makefile.in | 405 +
jasper-1.900.1-6ct/src/msvc/README | 2 +
jasper-1.900.1-6ct/src/msvc/imgcmp.dsp | 100 +
jasper-1.900.1-6ct/src/msvc/imgcmp.vcproj | 344 +
.../src/msvc/imgcmp.vcproj.paradigit.marcel.user | 93 +
jasper-1.900.1-6ct/src/msvc/imginfo.dsp | 102 +
jasper-1.900.1-6ct/src/msvc/imginfo.vcproj | 344 +
.../src/msvc/imginfo.vcproj.paradigit.marcel.user | 93 +
jasper-1.900.1-6ct/src/msvc/jasper.dsp | 102 +
jasper-1.900.1-6ct/src/msvc/jasper.dsw | 86 +
jasper-1.900.1-6ct/src/msvc/jasper.sln | 92 +
jasper-1.900.1-6ct/src/msvc/jasper.vcproj | 344 +
.../src/msvc/jasper.vcproj.paradigit.marcel.user | 93 +
jasper-1.900.1-6ct/src/msvc/jiv.dsp | 102 +
jasper-1.900.1-6ct/src/msvc/jiv.vcproj | 344 +
.../src/msvc/jiv.vcproj.paradigit.marcel.user | 93 +
jasper-1.900.1-6ct/src/msvc/libjasper.dsp | 428 +
jasper-1.900.1-6ct/src/msvc/libjasper.vcproj | 1972 ++
.../msvc/libjasper.vcproj.paradigit.marcel.user | 93 +
jpeg-6c/Darwin.rtf | 27 +
jpeg-6c/Makefile.osx | 344 +
jpeg-6c/README | 385 +
jpeg-6c/TODO | 13 +
jpeg-6c/ansi2knr.1 | 36 +
jpeg-6c/ansi2knr.c | 693 +
jpeg-6c/cderror.h | 134 +
jpeg-6c/cdjpeg.c | 181 +
jpeg-6c/cdjpeg.h | 191 +
jpeg-6c/change.log | 229 +
jpeg-6c/changes6c.txt | 4354 ++++
jpeg-6c/cjpeg.1 | 299 +
jpeg-6c/cjpeg.c | 672 +
jpeg-6c/ckconfig.c | 402 +
jpeg-6c/coderules.doc | 118 +
jpeg-6c/config.guess | 1472 ++
jpeg-6c/config.sub | 1599 ++
jpeg-6c/configure | 2011 ++
jpeg-6c/djpeg.1 | 253 +
jpeg-6c/djpeg.c | 630 +
jpeg-6c/example.c | 433 +
jpeg-6c/filelist.doc | 239 +
jpeg-6c/install-sh | 250 +
jpeg-6c/install.doc | 1064 +
jpeg-6c/jcapimin.c | 283 +
jpeg-6c/jcapistd.c | 198 +
jpeg-6c/jccoefct.c | 455 +
jpeg-6c/jccolor.c | 644 +
jpeg-6c/jcdctmgr.c | 394 +
jpeg-6c/jcdiffct.c | 410 +
jpeg-6c/jchuff.c | 273 +
jpeg-6c/jchuff.h | 56 +
jpeg-6c/jcinit.c | 57 +
jpeg-6c/jclhuff.c | 600 +
jpeg-6c/jclossls.c | 78 +
jpeg-6c/jclossy.c | 76 +
jpeg-6c/jcmainct.c | 297 +
jpeg-6c/jcmarker.c | 672 +
jpeg-6c/jcmaster.c | 654 +
jpeg-6c/jcodec.c | 53 +
jpeg-6c/jcomapi.c | 106 +
jpeg-6c/jconfig.bcc | 48 +
jpeg-6c/jconfig.cfg | 44 +
jpeg-6c/jconfig.dj | 38 +
jpeg-6c/jconfig.doc | 155 +
jpeg-6c/jconfig.mac | 43 +
jpeg-6c/jconfig.manx | 43 +
jpeg-6c/jconfig.mc6 | 52 +
jpeg-6c/jconfig.osx.h | 45 +
jpeg-6c/jconfig.sas | 43 +
jpeg-6c/jconfig.st | 42 +
jpeg-6c/jconfig.vc | 45 +
jpeg-6c/jconfig.vms | 37 +
jpeg-6c/jconfig.wat | 38 +
jpeg-6c/jcparam.c | 716 +
jpeg-6c/jcphuff.c | 851 +
jpeg-6c/jcpred.c | 298 +
jpeg-6c/jcprepct.c | 355 +
jpeg-6c/jcsample.c | 520 +
jpeg-6c/jcscale.c | 63 +
jpeg-6c/jcshuff.c | 666 +
jpeg-6c/jctrans.c | 427 +
jpeg-6c/jdapimin.c | 403 +
jpeg-6c/jdapistd.c | 386 +
jpeg-6c/jdatadst.c | 151 +
jpeg-6c/jdatasrc.c | 212 +
jpeg-6c/jdcoefct.c | 744 +
jpeg-6c/jdcolor.c | 397 +
jpeg-6c/jdct.h | 177 +
jpeg-6c/jddctmgr.c | 273 +
jpeg-6c/jddiffct.c | 399 +
jpeg-6c/jdhuff.c | 315 +
jpeg-6c/jdhuff.h | 229 +
jpeg-6c/jdinput.c | 348 +
jpeg-6c/jdlhuff.c | 291 +
jpeg-6c/jdlossls.c | 94 +
jpeg-6c/jdlossy.c | 228 +
jpeg-6c/jdmainct.c | 513 +
jpeg-6c/jdmarker.c | 1376 ++
jpeg-6c/jdmaster.c | 480 +
jpeg-6c/jdmerge.c | 401 +
jpeg-6c/jdphuff.c | 675 +
jpeg-6c/jdpostct.c | 291 +
jpeg-6c/jdpred.c | 247 +
jpeg-6c/jdsample.c | 479 +
jpeg-6c/jdscale.c | 119 +
jpeg-6c/jdshuff.c | 360 +
jpeg-6c/jdtrans.c | 139 +
jpeg-6c/jerror.c | 252 +
jpeg-6c/jerror.h | 319 +
jpeg-6c/jfdctflt.c | 168 +
jpeg-6c/jfdctfst.c | 225 +
jpeg-6c/jfdctint.c | 329 +
jpeg-6c/jidctflt.c | 243 +
jpeg-6c/jidctfst.c | 393 +
jpeg-6c/jidctint.c | 437 +
jpeg-6c/jidctred.c | 458 +
jpeg-6c/jinclude.h | 91 +
jpeg-6c/jlossls.h | 153 +
jpeg-6c/jlossy.h | 121 +
jpeg-6c/jmemansi.c | 167 +
jpeg-6c/jmemdos.c | 638 +
jpeg-6c/jmemdosa.asm | 379 +
jpeg-6c/jmemmac.c | 289 +
jpeg-6c/jmemmgr.c | 1175 +
jpeg-6c/jmemname.c | 276 +
jpeg-6c/jmemnobs.c | 109 +
jpeg-6c/jmemsys.h | 198 +
jpeg-6c/jmorecfg.h | 407 +
jpeg-6c/jpegint.h | 363 +
jpeg-6c/jpeglib.h | 1162 +
jpeg-6c/jpegtran.1 | 238 +
jpeg-6c/jpegtran.c | 624 +
jpeg-6c/jquant1.c | 865 +
jpeg-6c/jquant2.c | 1331 +
jpeg-6c/jutils.c | 180 +
jpeg-6c/jversion.h | 15 +
jpeg-6c/libjpeg.doc | Bin 0 -> 397312 bytes
jpeg-6c/ljpeg-6b.patch | 12790 ++++++++++
jpeg-6c/ltconfig | 1512 ++
jpeg-6c/ltmain.sh | 2453 ++
jpeg-6c/makcjpeg.st | 38 +
jpeg-6c/makdjpeg.st | 38 +
jpeg-6c/makeapps.ds | 828 +
jpeg-6c/makefile.ansi | 214 +
jpeg-6c/makefile.bcc | 285 +
jpeg-6c/makefile.cfg | 344 +
jpeg-6c/makefile.dj | 220 +
jpeg-6c/makefile.manx | 214 +
jpeg-6c/makefile.mc6 | 249 +
jpeg-6c/makefile.mms | 218 +
jpeg-6c/makefile.sas | 252 +
jpeg-6c/makefile.unix | 228 +
jpeg-6c/makefile.vc | 227 +
jpeg-6c/makefile.vms | 142 +
jpeg-6c/makefile.wat | 233 +
jpeg-6c/makelib.ds | 1046 +
jpeg-6c/makeproj.mac | 213 +
jpeg-6c/makljpeg.st | 70 +
jpeg-6c/maktjpeg.st | 32 +
jpeg-6c/makvms.opt | 4 +
jpeg-6c/rdbmp.c | 439 +
jpeg-6c/rdcolmap.c | 260 +
jpeg-6c/rdgif.c | 683 +
jpeg-6c/rdjpgcom.1 | 54 +
jpeg-6c/rdjpgcom.c | 496 +
jpeg-6c/rdppm.c | 654 +
jpeg-6c/rdrle.c | 387 +
jpeg-6c/rdswitch.c | 358 +
jpeg-6c/rdtarga.c | 500 +
jpeg-6c/structure.doc | 1042 +
jpeg-6c/testimg.bmp | Bin 0 -> 35050 bytes
jpeg-6c/testimg.jpg | Bin 0 -> 5756 bytes
jpeg-6c/testimg.ppm | 4 +
jpeg-6c/testimgl.jpg | Bin 0 -> 38374 bytes
jpeg-6c/testimgl.ppm | 4 +
jpeg-6c/testimgp.jpg | Bin 0 -> 5645 bytes
jpeg-6c/testorig.jpg | Bin 0 -> 5770 bytes
jpeg-6c/testprog.jpg | Bin 0 -> 5655 bytes
jpeg-6c/transupp.c | 1931 ++
jpeg-6c/transupp.h | 212 +
jpeg-6c/usage.doc | 562 +
jpeg-6c/wizard.doc | 211 +
jpeg-6c/wrbmp.c | 442 +
jpeg-6c/wrgif.c | 505 +
jpeg-6c/wrjpgcom.1 | 103 +
jpeg-6c/wrjpgcom.c | 583 +
jpeg-6c/wrppm.c | 343 +
jpeg-6c/wrrle.c | 305 +
jpeg-6c/wrtarga.c | 253 +
jpeg_encoder.cpp | 1901 ++
lex.cpp | 393 +
lex.hpp | 60 +
linuxmanual.pdf | Bin 0 -> 146456 bytes
loadddo.cpp | 464 +
lua/ChangeReturnIPAddress.lua | 26 +
lua/FixRTDicom.lua | 228 +
lua/LuaXml.lua | 119 +
lua/Plan2AlingRT.lua | 34 +
lua/anonymize_script.lua | 157 +
lua/changewedge.lua | 23 +
lua/checkbsn.lua | 80 +
lua/compressiontest.lua | 142 +
lua/deanonymize_script.lua | 73 +
lua/deletebody.lua | 30 +
lua/deletebydate.lua | 23 +
lua/distxfm.lua | 52 +
lua/filterquery.lua | 2 +
lua/importconverter.lua | 7 +
lua/livecoding.lua | 10 +
lua/makefilename.lua | 5 +
lua/mobdebug.lua | 1422 ++
lua/movepatientsfromlist.lua | 13 +
lua/nifty_test.lua | 70 +
lua/niftydicom.lua | 454 +
lua/niftytest.lua | 28 +
lua/niftyutil.lua | 115 +
lua/overview.lua | 323 +
lua/persistence.lua | 168 +
lua/query.lua | 10 +
lua/socket.lua | 133 +
lua/test.lua | 70 +
lua/test2.lua | 3 +
lua/testanon.lua | 6 +
lua/testload.lua | 26 +
lua/welcome.lua | 11 +
lua/wxsample.lua | 43 +
nkiqrsop.cpp | 9086 +++++++
nkiqrsop.hpp | 231 +
npipe.cpp | 351 +
npipe.hpp | 44 +
odbci.cpp | 5977 +++++
odbci.hpp | 401 +
parse.cpp | 390 +
pdata.cxx | 242 +
pdata.hpp | 118 +
pdu.cxx | 957 +
pdu.hpp | 238 +
pqueue.tcc | 258 +
pqueue.thh | 87 +
qrsop.cxx | 401 +
qrsop.hpp | 204 +
regen.cpp | 761 +
rtc.cxx | 796 +
rtc.hpp | 92 +
safemem.h | 55 +
sample.cq | 20 +
socket.cxx | 696 +
socket.hpp | 93 +
storage.cxx | 241 +
storage.hpp | 241 +
total.cpp | 146 +
trnsyn.cxx | 1953 ++
uniq.cxx | 90 +
unixsock.h | 50 +
util.cxx | 70 +
util.h | 43 +
verify.cxx | 170 +
verify.hpp | 48 +
version.h | 86 +
vrtosql.cpp | 2830 +++
windowsmanual.pdf | Bin 0 -> 1383178 bytes
wintypes.hpp | 30 +
xvgifwr.cpp | 1242 +
527 files changed, 268647 insertions(+)
diff --git a/DicomConformance_FilesLST_Changes.pdf b/DicomConformance_FilesLST_Changes.pdf
new file mode 100644
index 0000000..64a4e9e
Binary files /dev/null and b/DicomConformance_FilesLST_Changes.pdf differ
diff --git a/aaac.cxx b/aaac.cxx
new file mode 100644
index 0000000..2c999b0
--- /dev/null
+++ b/aaac.cxx
@@ -0,0 +1,368 @@
+/*
+MvH 19980327: Removed evaluation of Count without initialization in ReadDynamic
+mvh 20001106: Use memcpy instead of ByteCopy
+ljz 20030122: Fixed initialization of AAssociateAC
+mvh 20050108: Fixed for linux compile
+mvh 20080203: Added experimental ConfigPadAEWithZeros
+ljz 20080313: Removed some warnings
+bcb 20100619: Fix gcc4 warnings and improve speed
+mvh 20100717: Merged
+mvh 20111010: Fix reading of accepted presentation contexts: array was ot cleared and eventually overflowed
+*/
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+# include "dicom.hpp"
+# include <stdlib.h>
+
+#ifndef min
+#define min(a, b) ((a)<(b)?(a):(b))
+#endif
+
+/************************************************************************
+ *
+ * Presentation Context Accept
+ *
+ ************************************************************************/
+
+PresentationContextAccept :: PresentationContextAccept()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x21),
+Reserved1(0),
+Length(0),
+PresentationContextID(uniq8()),
+Reserved2(0),
+Result(2),
+Reserved4(0),
+TrnSyntax() {}
+#else
+ {
+ ItemType = 0x21;
+ Reserved1 = 0;
+ PresentationContextID = uniq8();
+ Reserved2 = 0;
+ Result = 2;
+ Reserved4 = 0;
+ }
+#endif
+
+PresentationContextAccept :: PresentationContextAccept(
+ //AbstractSyntax &Abs,
+ TransferSyntax &Tran)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x21),
+Reserved1(0),
+Length(0),
+PresentationContextID(uniq8()),
+Reserved2(0),
+Result(2),
+Reserved4(0),
+TrnSyntax(Tran) {}
+#else
+ {
+ //AbsSyntax = Abs;
+ TrnSyntax = Tran;
+ ItemType = 0x21;
+ Reserved1 = 0;
+ PresentationContextID = uniq8();
+ Reserved2 = 0;
+ Result = 2;
+ Reserved4 = 0;
+ }
+#endif
+
+PresentationContextAccept :: ~PresentationContextAccept()
+ {
+ //
+ }
+/*
+void PresentationContextAccept :: SetAbstractSyntax(AbstractSyntax &Abs)
+ {
+ AbsSyntax = Abs;
+ }
+*/
+void PresentationContextAccept :: SetTransferSyntax(TransferSyntax &Tran)
+ {
+ TrnSyntax = Tran;
+ }
+
+BOOL PresentationContextAccept :: Write ( Buffer &Link )
+ {
+ Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT16));
+ Link.Write((BYTE *) &PresentationContextID, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved2, sizeof(BYTE));
+ Link.Write((BYTE *) &Result, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved4, sizeof(BYTE));
+// fprintf(stderr, "Writing Presentation Contex Accept: %d bytes\n", Length);
+// AbsSyntax.Write(Link);
+ TrnSyntax.Write(Link);
+// fprintf(stderr, "ABS: %d TRN: %d\n", AbsSyntax.Size(), TrnSyntax.Size());
+
+
+ Link.Flush();
+ return ( TRUE );
+ }
+
+BOOL PresentationContextAccept :: Read (Buffer &Link)
+ {
+ Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return ( this->ReadDynamic(Link) );
+ }
+
+BOOL PresentationContextAccept :: ReadDynamic (Buffer &Link)
+ {
+// INT32 Count;
+ TransferSyntax Tran;
+
+ Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT16));
+ Link.Read((BYTE *) &PresentationContextID, sizeof(BYTE));
+ Link.Read((BYTE *) &Reserved2, sizeof(BYTE));
+ Link.Read((BYTE *) &Result, sizeof(BYTE));
+ Link.Read((BYTE *) &Reserved4, sizeof(BYTE));
+
+// Count = Length - sizeof(BYTE) - sizeof(BYTE) - sizeof(BYTE) - sizeof(BYTE);
+// AbsSyntax.Read(Link);
+// Count = Count - AbsSyntax.Size();
+ TrnSyntax.Read(Link);
+// Count = Count - TrnSyntax.Size();
+
+// if ( !Count)
+ return ( TRUE );
+// return ( FALSE );
+ }
+
+UINT32 PresentationContextAccept :: Size()
+ {
+ Length = sizeof(BYTE) + sizeof(BYTE) + sizeof(BYTE) + sizeof(BYTE);
+// Length += AbsSyntax.Size();
+ Length += TrnSyntax.Size();
+ return ( Length + sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT16));
+ }
+
+/************************************************************************
+ *
+ * AAssociateAC Packet
+ *
+ ************************************************************************/
+
+AAssociateAC :: AAssociateAC()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x02),
+Reserved1(0),
+Length(0),
+ProtocolVersion(0x0001),
+Reserved2(0),
+AppContext(),
+PresContextAccepts(),
+UserInfo()
+ {
+#else
+ {
+ ItemType = 0x02;
+ Reserved1 = 0;
+ ProtocolVersion = 0x0001;
+ Reserved2 = 0;
+#endif
+ SpaceMem(CalledApTitle, 16);
+ if (ConfigPadAEWithZeros) memset(CalledApTitle, 0, 16);
+ CalledApTitle[16] = 0;
+ SpaceMem(CallingApTitle, 16);
+ if (ConfigPadAEWithZeros) memset(CalledApTitle, 0, 16);
+ CallingApTitle[16] = 0;
+ ZeroMem(Reserved3, 32);
+ }
+
+AAssociateAC :: AAssociateAC(BYTE *CallingAp, BYTE *CalledAp)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x02),
+Reserved1(0),
+Length(0),
+ProtocolVersion(0x0001),
+Reserved2(0),
+AppContext(),
+PresContextAccepts(),
+UserInfo()
+ {
+#else
+ {
+ ItemType = 0x02;
+ Reserved1 = 0;
+ ProtocolVersion = 0x0001;
+ Reserved2 = 0;
+#endif
+ SpaceMem(CalledApTitle, 16);
+ if (ConfigPadAEWithZeros) memset(CalledApTitle, 0, 16);
+ CalledApTitle[16] = 0;
+ SpaceMem(CallingApTitle, 16);
+ if (ConfigPadAEWithZeros) memset(CalledApTitle, 0, 16);
+ CallingApTitle[16] = 0;
+ ZeroMem(Reserved3, 32);
+ memcpy(CallingApTitle, CallingAp, min(strlen((char *)CallingAp), 16u));
+ memcpy(CalledApTitle, CalledAp, min(strlen((char *)CalledAp), 16u));
+ }
+
+AAssociateAC :: ~AAssociateAC()
+ {
+ // nothing, everything should self-destruct nicely
+ }
+
+void AAssociateAC :: SetCalledApTitle(BYTE *CalledAp)
+ {
+ SpaceMem(CalledApTitle, 16);
+ if (ConfigPadAEWithZeros) memset(CalledApTitle, 0, 16);
+ memcpy(CalledApTitle, CalledAp, min(strlen((char *)CalledAp), 16u));
+ }
+
+void AAssociateAC :: SetCallingApTitle(BYTE *CallingAp)
+ {
+ SpaceMem(CallingApTitle, 16);
+ if (ConfigPadAEWithZeros) memset(CalledApTitle, 0, 16);
+ memcpy(CallingApTitle, CallingAp, min(strlen((char *)CallingAp), 16u));
+ }
+
+void AAssociateAC :: SetApplicationContext(ApplicationContext &AppC)
+ {
+ AppContext = AppC;
+ }
+
+void AAssociateAC :: AddPresentationContextAccept(PresentationContextAccept &PresContextAccept)
+ {
+ PresContextAccepts.Add(PresContextAccept);
+ }
+
+void AAssociateAC :: SetUserInformation(UserInformation &User)
+ {
+ UserInfo = User;
+ }
+
+BOOL AAssociateAC :: Write(Buffer &Link)
+ {
+ UINT Index;
+
+// fprintf(stderr, "AAssociateAC :: Write ()\n");fflush(stderr);
+ Size();
+ Link << ItemType; //Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT32));
+ Link << ProtocolVersion; //Link.Write((BYTE *) &ProtocolVersion, sizeof(UINT16));
+ Link << Reserved2; //Link.Write((BYTE *) &Reserved2, sizeof(UINT16));
+ Link.Write((BYTE *) CalledApTitle, 16);
+ Link.Write((BYTE *) CallingApTitle, 16);
+ Link.Write((BYTE *) Reserved3, 32);
+ Link.Flush();
+// fprintf(stderr, "AAssociateAC (writting App/Pre Contexts)\n");
+ AppContext.Write(Link);
+ Index = 0;
+ while(Index < PresContextAccepts.GetSize())
+ {
+ PresContextAccepts[Index].Write(Link);
+ ++Index;
+ }
+// fprintf(stderr, "AAssociateAC ( writting User info)\n");
+ UserInfo.Write(Link);
+ return ( TRUE );
+ }
+
+BOOL AAssociateAC :: Read(Buffer &Link)
+ {
+ Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return(this->ReadDynamic(Link));
+ }
+
+BOOL AAssociateAC :: ReadDynamic(Buffer &Link)
+ {
+ INT Count;
+ BYTE TempByte;
+ PresentationContextAccept PresContextAccept;
+
+ // mvh 20111010: Fix reading of accepted presentation contexts: array was ot cleared and eventually overflowed
+ while(PresContextAccepts.GetSize()) PresContextAccepts.RemoveAt(0);
+
+ Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT32));
+ Link >> ProtocolVersion; //Link.Read((BYTE *) &ProtocolVersion, sizeof(UINT16));
+ Link >> Reserved2; //Link.Read((BYTE *) &Reserved2, sizeof(UINT16));
+ Link.Read((BYTE *) CalledApTitle, 16);
+ Link.Read((BYTE *) CallingApTitle, 16);
+ Link.Read((BYTE *) Reserved3, 32);
+
+ CalledApTitle[16] = '\0';
+ CallingApTitle[16] = '\0';
+
+ Count = Length - sizeof(UINT16) - sizeof(UINT16) - 16 - 16 - 32;
+ while(Count > 0)
+ {
+ Link.Read((BYTE *) &TempByte, sizeof(BYTE));
+ switch(TempByte)
+ {
+ case 0x50: // user information
+ UserInfo.ReadDynamic(Link);
+ Count = Count - UserInfo.Size();
+ break;
+ case 0x21:
+ PresContextAccept.ReadDynamic(Link);
+ Count = Count - PresContextAccept.Size();
+ PresContextAccepts.Add(PresContextAccept);
+ break;
+ case 0x10:
+ AppContext.ReadDynamic(Link);
+ Count = Count - AppContext.Size();
+ break;
+ default:
+ Link.Kill(Count-1);
+ Count = -1;
+ }
+ }
+ if(!Count)
+ return ( TRUE );
+ return ( FALSE);
+ }
+
+UINT32 AAssociateAC :: Size()
+ {
+ UINT Index;
+
+ Length = sizeof(UINT16) + sizeof(UINT16) + 16 + 16 + 32;
+ Length += AppContext.Size();
+ Index = 0;
+
+ Index = 0;
+ while(Index < PresContextAccepts.GetSize())
+ {
+ Length += PresContextAccepts[Index].Size();
+ ++Index;
+ }
+ Length += UserInfo.Size();
+ return ( Length + sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT32) );
+ }
+
diff --git a/aaac.hpp b/aaac.hpp
new file mode 100644
index 0000000..808f64c
--- /dev/null
+++ b/aaac.hpp
@@ -0,0 +1,103 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/***********************************************************************
+ * PDU Service Classes:
+ * A-ASSOCIATE-AC Class.
+ *
+ * Base Classes:
+ *
+ * PresentationContextAccept
+ *
+ *
+ *
+ *********************************************************************/
+
+class PresentationContextAccept
+ {
+ private:
+ BYTE ItemType; // 0x21
+ BYTE Reserved1;
+ UINT16 Length;
+ public:
+ BYTE PresentationContextID;
+ private:
+ BYTE Reserved2;
+ public:
+ BYTE Result;
+ private:
+ BYTE Reserved4;
+ public:
+// AbstractSyntax AbsSyntax;
+ TransferSyntax TrnSyntax;
+ PresentationContextAccept();
+ PresentationContextAccept(/*AbstractSyntax &, */TransferSyntax &);
+ ~PresentationContextAccept();
+// void SetAbstractSyntax(AbstractSyntax &);
+ void SetTransferSyntax(TransferSyntax &);
+ void SetResult(BYTE Res) { Result = Res; };
+ BYTE GetResult() { return ( Result ); };
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+
+ };
+
+class AAssociateAC
+ {
+ private:
+ BYTE ItemType; // 0x02
+ BYTE Reserved1;
+ UINT32 Length;
+ UINT16 ProtocolVersion; // 0x01
+ UINT16 Reserved2;
+ public:
+ BYTE CalledApTitle[17]; // 16 bytes transfered
+ BYTE CallingApTitle[17]; // 16 bytes transfered
+ BYTE Reserved3[32];
+ ApplicationContext AppContext;
+ Array<PresentationContextAccept> PresContextAccepts;
+ UserInformation UserInfo;
+ public:
+ AAssociateAC();
+ AAssociateAC(BYTE *, BYTE *);
+ virtual ~AAssociateAC();
+ void SetCalledApTitle(BYTE *);
+ void SetCallingApTitle(BYTE *);
+ void SetApplicationContext(ApplicationContext &);
+ void AddPresentationContextAccept(PresentationContextAccept &);
+ void SetUserInformation(UserInformation &);
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+ };
+
+
diff --git a/aarj.cxx b/aarj.cxx
new file mode 100644
index 0000000..6ada90d
--- /dev/null
+++ b/aarj.cxx
@@ -0,0 +1,331 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/* bcb 20100619: Fix gcc4 warnings and improve speed.
+ mvh 20100717: Merged
+*/
+
+# include "dicom.hpp"
+
+
+/************************************************************************
+ *
+ * AAssociateRJ Packet
+ *
+ ************************************************************************/
+
+AAssociateRJ :: AAssociateRJ()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x03),
+Reserved1(0),
+Length(0),
+Reserved2(0),
+Result(1),
+Source(3),
+Reason(1) {}
+#else
+ {
+ ItemType = 0x03;
+ Reserved1 = 0;
+ Reserved2 = 0;
+ Result = 1;
+ Source = 3;
+ Reason = 1;
+ }
+#endif
+
+AAssociateRJ :: AAssociateRJ(BYTE Res, BYTE S, BYTE Re)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x03),
+Reserved1(0),
+Length(0),
+Reserved2(0),
+Result(Res),
+Source(S),
+Reason(Re) {}
+#else
+{
+ ItemType = 0x03;
+ Reserved1 = 0;
+ Reserved2 = 0;
+ Result = Res;
+ Source = S;
+ Reason = Re;
+ }
+#endif
+
+AAssociateRJ :: ~AAssociateRJ()
+ {
+ // nothing, everything should self-destruct nicely
+ }
+
+
+BOOL AAssociateRJ :: Write(Buffer &Link)
+ {
+ Size();
+ Link << ItemType; //Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT32));
+ Link << Reserved2; //Link.Write((BYTE *) &Reserved2, sizeof(UINT16));
+ Link << Result;
+ Link << Source;
+ Link << Reason;
+ Link.Flush();
+ return ( TRUE );
+ }
+
+BOOL AAssociateRJ :: Read(Buffer &Link)
+ {
+ Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return(this->ReadDynamic(Link));
+ }
+
+BOOL AAssociateRJ :: ReadDynamic(Buffer &Link)
+ {
+ Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT32));
+ Link >> Reserved2; //Link.Read((BYTE *) &Reserved2, sizeof(UINT16));
+ Link >> Result;
+ Link >> Source;
+ Link >> Reason;
+
+ return (TRUE);
+ }
+
+UINT32 AAssociateRJ :: Size()
+ {
+ Length = 4;
+ return ( Length + sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT32) );
+ }
+
+
+/************************************************************************
+ *
+ * AReleaseRQ Packet
+ *
+ ************************************************************************/
+
+AReleaseRQ :: AReleaseRQ()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x05),
+Reserved1(0),
+Length(0),
+Reserved2(0) {}
+#else
+ {
+ ItemType = 0x05;
+ Reserved1 = 0;
+ Reserved2 = 0;
+ }
+#endif
+
+AReleaseRQ :: ~AReleaseRQ()
+ {
+ // nothing, everything should self-destruct nicely
+ }
+
+
+BOOL AReleaseRQ :: Write(Buffer &Link)
+ {
+ Size();
+ Link << ItemType; //Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT32));
+ Link << Reserved2; //Link.Write((BYTE *) &Reserved2, sizeof(UINT16));
+ Link.Flush();
+ return ( TRUE );
+ }
+
+BOOL AReleaseRQ :: Read(Buffer &Link)
+ {
+ Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return(this->ReadDynamic(Link));
+ }
+
+BOOL AReleaseRQ :: ReadDynamic(Buffer &Link)
+ {
+ Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT32));
+ Link >> Reserved2; //Link.Read((BYTE *) &Reserved2, sizeof(UINT16));
+ return (TRUE);
+ }
+
+UINT32 AReleaseRQ :: Size()
+ {
+ Length = 4;
+ return ( Length + sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT32) );
+ }
+
+/************************************************************************
+ *
+ * AReleaseRP Packet
+ *
+ ************************************************************************/
+
+AReleaseRP :: AReleaseRP()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x06),
+Reserved1(0),
+Length(0),
+Reserved2(0) {}
+#else
+ {
+ ItemType = 0x06;
+ Reserved1 = 0;
+ Reserved2 = 0;
+ }
+#endif
+
+AReleaseRP :: ~AReleaseRP()
+ {
+ // nothing, everything should self-destruct nicely
+ }
+
+
+BOOL AReleaseRP :: Write(Buffer &Link)
+ {
+ Size();
+ Link << ItemType; //Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT32));
+ Link << Reserved2; //Link.Write((BYTE *) &Reserved2, sizeof(UINT16));
+ Link.Flush();
+ return ( TRUE );
+ }
+
+BOOL AReleaseRP :: Read(Buffer &Link)
+ {
+ Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return(this->ReadDynamic(Link));
+ }
+
+BOOL AReleaseRP :: ReadDynamic(Buffer &Link)
+ {
+ Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT32));
+ Link >> Reserved2; //Link.Read((BYTE *) &Reserved2, sizeof(UINT16));
+ return (TRUE);
+ }
+
+UINT32 AReleaseRP :: Size()
+ {
+ Length = 4;
+ return ( Length + sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT32) );
+ }
+
+/************************************************************************
+ *
+ * AAbortRQ Packet
+ *
+ ************************************************************************/
+
+AAbortRQ :: AAbortRQ()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x07),
+Reserved1(0),
+Length(0),
+Reserved2(0),
+Reserved3(0),
+Source(3),
+Reason(1) {}
+#else
+ {
+ ItemType = 0x07;
+ Reserved1 = 0;
+ Reserved2 = 0;
+ Reserved3 = 0;
+ Source = 3;
+ Reason = 1;
+ }
+#endif
+
+AAbortRQ :: AAbortRQ(BYTE S, BYTE Re)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x03),
+Reserved1(0),
+Length(0),
+Reserved2(0),
+Reserved3(0),
+Source(S),
+Reason(Re) {}
+#else
+ {
+ ItemType = 0x03;
+ Reserved1 = 0;
+ Reserved2 = 0;
+ Reserved3 = 0;
+ Source = S;
+ Reason = Re;
+ }
+#endif
+
+AAbortRQ :: ~AAbortRQ()
+ {
+ // nothing, everything should self-destruct nicely
+ }
+
+
+BOOL AAbortRQ :: Write(Buffer &Link)
+ {
+ Size();
+ Link << ItemType; //Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT32));
+ Link << Reserved2; //Link.Write((BYTE *) &Reserved2, sizeof(UINT16));
+ Link << Reserved3;
+ Link << Source;
+ Link << Reason;
+ Link.Flush();
+ return ( TRUE );
+ }
+
+BOOL AAbortRQ :: Read(Buffer &Link)
+ {
+ Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return(this->ReadDynamic(Link));
+ }
+
+BOOL AAbortRQ :: ReadDynamic(Buffer &Link)
+ {
+ Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT32));
+ Link >> Reserved2; //Link.Read((BYTE *) &Reserved2, sizeof(UINT16));
+ Link >> Reserved3;
+ Link >> Source;
+ Link >> Reason;
+
+ return ( TRUE );
+ }
+
+UINT32 AAbortRQ :: Size()
+ {
+ Length = 4;
+ return ( Length + sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT32) );
+ }
+
diff --git a/aarj.hpp b/aarj.hpp
new file mode 100644
index 0000000..ceb18d1
--- /dev/null
+++ b/aarj.hpp
@@ -0,0 +1,119 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/***********************************************************************
+ * PDU Service Classes:
+ * A-ASSOCIATE-RJ Class.
+ * A-RELEASE-RQ Class.
+ * A-RELEASE-RP Class.
+ * A-ABORT-RQ Class.
+ *
+ * Base Classes:
+ *
+ *
+ *
+ *
+ *********************************************************************/
+
+
+class AAssociateRJ
+ {
+ private:
+ BYTE ItemType; // 0x03
+ BYTE Reserved1;
+ UINT32 Length;
+ BYTE Reserved2;
+ public:
+ BYTE Result;
+ BYTE Source;
+ BYTE Reason;
+
+ AAssociateRJ();
+ AAssociateRJ(BYTE, BYTE, BYTE);
+ virtual ~AAssociateRJ();
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+ };
+
+
+class AReleaseRQ
+ {
+ private:
+ BYTE ItemType; // 0x04
+ BYTE Reserved1;
+ UINT32 Length;
+ UINT32 Reserved2;
+ public:
+ AReleaseRQ();
+ virtual ~AReleaseRQ();
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+ };
+
+class AReleaseRP
+ {
+ private:
+ BYTE ItemType; // 0x06
+ BYTE Reserved1;
+ UINT32 Length;
+ UINT32 Reserved2;
+ public:
+ AReleaseRP();
+ virtual ~AReleaseRP();
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+ };
+
+class AAbortRQ
+ {
+ private:
+ BYTE ItemType; // 0x07
+ BYTE Reserved1;
+ UINT32 Length;
+ BYTE Reserved2;
+ BYTE Reserved3;
+ public:
+ BYTE Source;
+ BYTE Reason;
+
+ AAbortRQ();
+ AAbortRQ(BYTE, BYTE);
+ virtual ~AAbortRQ();
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+ };
+
diff --git a/aarq.cxx b/aarq.cxx
new file mode 100644
index 0000000..b349e58
--- /dev/null
+++ b/aarq.cxx
@@ -0,0 +1,1191 @@
+/*
+mvh 20001106: Use memcpy instead of ByteCopy
+ljz 20001128: Removed two warnings
+ljz 20030122: Fixed initialization of AAssociateRQ
+mvh 20060618: Added definition of min()
+mvh 20080203: Added experimental ConfigPadAEWithZeros
+ljz 20080313: Removed some warnings
+bcb 20100619: Fix gcc4 warnings and improve speed.
+mvh 20100717: Merged
+*/
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+# include "dicom.hpp"
+
+#ifndef min
+#define min(a, b) ((a)<(b)?(a):(b))
+#endif
+
+/*************************************************************************
+ *
+ * Application Context Class
+ *
+ ************************************************************************/
+ApplicationContext :: ApplicationContext()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x10),
+Reserved1(0),
+Length(0),
+ApplicationContextName() {}
+#else
+ {
+ ItemType = 0x10;
+ Reserved1 = 0;
+ }
+#endif
+
+ApplicationContext :: ApplicationContext(UID &uid)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x10),
+Reserved1(0),
+Length(0),
+ApplicationContextName()
+ {
+#else
+ {
+ ItemType = 0x10;
+ Reserved1 = 0;
+#endif
+ ApplicationContextName = uid;
+ }
+
+ApplicationContext :: ApplicationContext(BYTE *name)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x10),
+Reserved1(0),
+Length(0),
+ApplicationContextName()
+ {
+#else
+ {
+ ItemType = 0x10;
+ Reserved1 = 0;
+#endif
+ ApplicationContextName.Set(name);
+ }
+
+ApplicationContext :: ~ApplicationContext()
+ {
+ // nothing to de-allocate specifically
+
+ }
+
+void ApplicationContext :: Set(UID &uid)
+ {
+ ApplicationContextName = uid;
+ }
+
+void ApplicationContext :: Set(BYTE *name)
+ {
+ ApplicationContextName.Set(name);
+ }
+
+BOOL ApplicationContext :: Write(Buffer &Link)
+ {
+ Link << ItemType; //Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link << Reserved1; //Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT16));
+ Link.Write((BYTE *) ApplicationContextName.GetBuffer(Length), Length);
+ Link.Flush();
+ return ( TRUE );
+ }
+
+BOOL ApplicationContext :: Read(Buffer &Link)
+ {
+ Link >> ItemType; //Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return ( this->ReadDynamic(Link) );
+ }
+
+BOOL ApplicationContext :: ReadDynamic(Buffer &Link)
+ {
+ Link >> Reserved1; //Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT16));
+ Link.Read((BYTE *) ApplicationContextName.GetBuffer(Length), Length);
+ ApplicationContextName.GetBuffer(Length)[Length] = '\0';
+ ApplicationContextName.SetLength(Length);
+ return ( TRUE );
+ }
+
+UINT32 ApplicationContext :: Size()
+ {
+ Length = ApplicationContextName.GetSize();
+ return ( sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT16) + Length );
+ }
+
+/*************************************************************************
+ *
+ * Abstract Syntax Class
+ *
+ ************************************************************************/
+
+AbstractSyntax :: AbstractSyntax()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x30),
+Reserved1(0),
+Length(0),
+AbstractSyntaxName() {}
+#else
+ {
+ ItemType = 0x30;
+ Reserved1 = 0;
+ }
+#endif
+
+AbstractSyntax :: AbstractSyntax(UID &uid)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x30),
+Reserved1(0),
+Length(0),
+AbstractSyntaxName()
+ {
+#else
+ {
+ ItemType = 0x30;
+ Reserved1 = 0;
+#endif
+ AbstractSyntaxName = uid;
+ }
+
+AbstractSyntax :: AbstractSyntax(BYTE *name)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x30),
+Reserved1(0),
+Length(0),
+AbstractSyntaxName()
+ {
+#else
+ {
+ ItemType = 0x30;
+ Reserved1 = 0;
+#endif
+ AbstractSyntaxName.Set(name);
+ }
+
+AbstractSyntax :: ~AbstractSyntax()
+ {
+ // nothing to de-allocate specifically
+
+ }
+
+void AbstractSyntax :: Set(UID &uid)
+ {
+ AbstractSyntaxName = uid;
+ }
+
+void AbstractSyntax :: Set(BYTE *name)
+ {
+ AbstractSyntaxName.Set(name);
+ }
+
+BOOL AbstractSyntax :: Write(Buffer &Link)
+ {
+ Link << ItemType; //Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link << Reserved1; //Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT16));
+ Link.Write((BYTE *) AbstractSyntaxName.GetBuffer(Length), Length);
+ Link.Flush();
+ return ( TRUE );
+ }
+
+BOOL AbstractSyntax :: Read(Buffer &Link)
+ {
+ Link >> ItemType; //Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return ( this->ReadDynamic(Link) );
+ }
+
+BOOL AbstractSyntax :: ReadDynamic(Buffer &Link)
+ {
+ Link >> Reserved1; //Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT16));
+ Link.Read((BYTE *) AbstractSyntaxName.GetBuffer(Length), Length);
+ AbstractSyntaxName.GetBuffer(Length)[Length] = '\0';
+ AbstractSyntaxName.SetLength(Length);
+ return ( TRUE );
+ }
+
+UINT32 AbstractSyntax :: Size()
+ {
+ Length = AbstractSyntaxName.GetSize();
+ return ( sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT16) + Length );
+ }
+
+/************************************************************************
+ *
+ * Transfer Syntax
+ *
+ ************************************************************************/
+
+TransferSyntax :: TransferSyntax()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x40),
+Reserved1(0),
+Length(0),
+TransferSyntaxName(),
+EndianType(LITTLE_ENDIAN) {}
+#else
+ {
+ ItemType = 0x40;
+ Reserved1 = 0;
+ }
+#endif
+
+TransferSyntax :: TransferSyntax(UID &uid)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x40),
+Reserved1(0),
+Length(0),
+TransferSyntaxName(),
+EndianType(LITTLE_ENDIAN)
+{
+#else
+ {
+ ItemType = 0x40;
+ Reserved1 = 0;
+#endif
+ TransferSyntaxName = uid;
+ }
+
+TransferSyntax :: TransferSyntax(BYTE *name)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x40),
+Reserved1(0),
+Length(0),
+TransferSyntaxName(),
+EndianType(LITTLE_ENDIAN)
+ {
+#else
+ {
+ ItemType = 0x40;
+ Reserved1 = 0;
+#endif
+ TransferSyntaxName.Set(name);
+ }
+
+TransferSyntax :: ~TransferSyntax()
+ {
+ // nothing to de-allocate specifically
+
+ }
+
+void TransferSyntax :: Set(UID &uid)
+ {
+ TransferSyntaxName = uid;
+ }
+
+void TransferSyntax :: Set(BYTE *name)
+ {
+ TransferSyntaxName.Set(name);
+ }
+
+BOOL TransferSyntax :: Write(Buffer &Link)
+ {
+// fprintf(stderr, "Writing Transfer Syntax: %d ItemType\n", ItemType);
+// fprintf(stderr, "Length = %d\n", Length);
+// fprintf(stderr, "UID: %s\n", TransferSyntaxName.GetBuffer(Length));
+
+ Link << ItemType; //Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link << Reserved1; //Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT16));
+ Link.Write((BYTE *) TransferSyntaxName.GetBuffer(Length), Length);
+ Link.Flush();
+ return ( TRUE );
+ }
+
+BOOL TransferSyntax :: Read(Buffer &Link)
+ {
+ Link >> ItemType; //Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ //fprintf(stderr, "Reading Transfter Syntax Magic Code: %x\n", ItemType);
+ return ( this->ReadDynamic(Link) );
+ }
+
+BOOL TransferSyntax :: ReadDynamic(Buffer &Link)
+ {
+ Link >> ItemType; //Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT16));
+ Link.Read((BYTE *) TransferSyntaxName.GetBuffer(Length), Length);
+ TransferSyntaxName.GetBuffer(Length)[Length] = '\0';
+ TransferSyntaxName.SetLength(Length);
+ return ( TRUE );
+ }
+
+UINT32 TransferSyntax :: Size()
+ {
+ Length = TransferSyntaxName.GetSize();
+ return ( sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT16) + Length );
+ }
+
+
+
+/************************************************************************
+ *
+ * Implementation Class
+ *
+ ************************************************************************/
+
+ImplementationClass :: ImplementationClass()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x52),
+Reserved1(0),
+Length(0),
+ImplementationName(),
+EndianType(LITTLE_ENDIAN) {}
+#else
+ {
+ ItemType = 0x52;
+ Reserved1 = 0;
+ }
+#endif
+
+ImplementationClass :: ImplementationClass(UID &uid)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x52),
+Reserved1(0),
+Length(0),
+ImplementationName(),
+EndianType(LITTLE_ENDIAN)
+ {
+#else
+ {
+ ItemType = 0x52;
+ Reserved1 = 0;
+#endif
+ ImplementationName = uid;
+ }
+
+ImplementationClass :: ImplementationClass(BYTE *name)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x52),
+Reserved1(0),
+Length(0),
+ImplementationName(),
+EndianType(LITTLE_ENDIAN)
+ {
+#else
+ {
+ ItemType = 0x52;
+ Reserved1 = 0;
+#endif
+ ImplementationName.Set(name);
+ }
+
+ImplementationClass :: ~ImplementationClass()
+ {
+ // nothing to de-allocate specifically
+
+ }
+
+void ImplementationClass :: Set(UID &uid)
+ {
+ ImplementationName = uid;
+ }
+
+void ImplementationClass :: Set(BYTE *name)
+ {
+ ImplementationName.Set(name);
+ }
+
+BOOL ImplementationClass :: Write(Buffer &Link)
+ {
+ Link << ItemType; //Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link << Reserved1; //Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT16));
+ Link.Write((BYTE *) ImplementationName.GetBuffer(Length), Length);
+ Link.Flush();
+ return ( TRUE );
+ }
+
+BOOL ImplementationClass :: Read(Buffer &Link)
+ {
+ Link >> ItemType; //Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return ( this->ReadDynamic(Link) );
+ }
+
+BOOL ImplementationClass :: ReadDynamic(Buffer &Link)
+ {
+ Link >> Reserved1; //Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT16));
+ Link.Read((BYTE *) ImplementationName.GetBuffer(Length), Length);
+ ImplementationName.GetBuffer(Length)[Length] = '\0';
+ ImplementationName.SetLength(Length);
+ return ( TRUE );
+ }
+
+UINT32 ImplementationClass :: Size()
+ {
+ Length = ImplementationName.GetSize();
+ return ( sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT16) + Length );
+ }
+
+
+/************************************************************************
+ *
+ * Implementation Class
+ *
+ ************************************************************************/
+
+ImplementationVersion :: ImplementationVersion()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x55),
+Reserved1(0),
+Length(0),
+Version(),
+EndianType(LITTLE_ENDIAN) {}
+#else
+ {
+ ItemType = 0x55;
+ Reserved1 = 0;
+ }
+#endif
+
+ImplementationVersion :: ImplementationVersion(UID &uid)
+#ifdef __GNUC__ //The GCC way
+:ItemType(0x55),
+Reserved1(0),
+Length(0),
+Version(uid),
+EndianType(LITTLE_ENDIAN) {}
+#else
+ {
+ ItemType = 0x55;
+ Reserved1 = 0;
+ Version = uid;
+ }
+#endif
+
+ImplementationVersion :: ImplementationVersion(BYTE *name)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x55),
+Reserved1(0),
+Length(0),
+Version(),
+EndianType(LITTLE_ENDIAN)
+ {
+#else
+ {
+ ItemType = 0x55;
+ Reserved1 = 0;
+#endif
+ Version.Set(name);
+ }
+
+ImplementationVersion :: ~ImplementationVersion()
+ {
+ // nothing to de-allocate specifically
+
+ }
+
+void ImplementationVersion :: Set(UID &uid)
+ {
+ Version = uid;
+ }
+
+void ImplementationVersion :: Set(BYTE *name)
+ {
+ Version.Set(name);
+ }
+
+BOOL ImplementationVersion :: Write(Buffer &Link)
+ {
+ Link << ItemType; //Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link << Reserved1; //Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT16));
+ Link.Write((BYTE *) Version.GetBuffer(Length), Length);
+ Link.Flush();
+ return ( TRUE );
+ }
+
+BOOL ImplementationVersion :: Read(Buffer &Link)
+ {
+ Link >> ItemType; //Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return ( this->ReadDynamic(Link) );
+ }
+
+BOOL ImplementationVersion :: ReadDynamic(Buffer &Link)
+ {
+ Link >> Reserved1; //Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT16));
+ Link.Read((BYTE *) Version.GetBuffer(Length), Length);
+ Version.GetBuffer(Length)[Length] = '\0';
+ Version.SetLength(Length);
+ return ( TRUE );
+ }
+
+UINT32 ImplementationVersion :: Size()
+ {
+ Length = Version.GetSize();
+ return ( sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT16) + Length );
+ }
+
+/************************************************************************
+ *
+ * Presentation Context
+ *
+ ************************************************************************/
+
+PresentationContext :: PresentationContext()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x20),
+Reserved1(0),
+Length(0),
+PresentationContextID(uniq8odd()),
+Reserved2(0),
+Reserved3(0),
+Reserved4(0),
+AbsSyntax(),
+TrnSyntax()
+ {
+#else
+ {
+ ItemType = 0x20;
+ Reserved1 = 0;
+ PresentationContextID = uniq8odd();
+ Reserved2 = 0;
+ Reserved3 = 0;
+ Reserved4 = 0;
+#endif
+// fprintf(stderr, "Creating PresentationContext / %d\n",
+// TrnSyntax.ClearType);
+ }
+
+PresentationContext :: PresentationContext(
+ AbstractSyntax &Abs,
+ TransferSyntax &Tran)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x20),
+Reserved1(0),
+Length(0),
+PresentationContextID(uniq8odd()),
+Reserved2(0),
+Reserved3(0),
+Reserved4(0),
+AbsSyntax(Abs),
+TrnSyntax()
+ {
+ TrnSyntax.Add ( Tran );
+#else
+ {
+ AbsSyntax = Abs;
+ TrnSyntax.Add ( Tran );
+ ItemType = 0x20;
+ Reserved1 = 0;
+ PresentationContextID = uniq8odd();
+ Reserved2 = 0;
+ Reserved3 = 0;
+ Reserved4 = 0;
+#endif
+ }
+
+PresentationContext :: ~PresentationContext()
+ {
+// fprintf (stderr, "~PresentationContext ClearType=%d\n", TrnSyntax.ClearType);
+ //TrnSyntax.FreeData ( FALSE );
+ }
+
+void PresentationContext :: SetAbstractSyntax(AbstractSyntax &Abs)
+ {
+ AbsSyntax = Abs;
+ }
+
+void PresentationContext :: AddTransferSyntax(TransferSyntax &Tran)
+ {
+ TrnSyntax.Add ( Tran );
+ }
+
+BOOL PresentationContext :: Write ( Buffer &Link )
+ {
+ UINT Index;
+
+ Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT16));
+ Link.Write((BYTE *) &PresentationContextID, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved2, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved3, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved4, sizeof(BYTE));
+ AbsSyntax.Write(Link);
+ Link.Flush();
+ Index = 0;
+ while ( Index < TrnSyntax.GetSize() )
+ {
+ TrnSyntax[ Index ].Write(Link);
+ ++Index;
+ }
+ if ( Index )
+ return ( TRUE );
+ return ( FALSE );
+ }
+
+BOOL PresentationContext :: Read (Buffer &Link)
+ {
+ Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return ( this->ReadDynamic(Link) );
+ }
+
+BOOL PresentationContext :: ReadDynamic (Buffer &Link)
+ {
+ INT32 Count;
+ TransferSyntax Tran;
+
+ Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT16));
+ Link.Read((BYTE *) &PresentationContextID, sizeof(BYTE));
+ Link.Read((BYTE *) &Reserved2, sizeof(BYTE));
+ Link.Read((BYTE *) &Reserved3, sizeof(BYTE));
+ Link.Read((BYTE *) &Reserved4, sizeof(BYTE));
+
+ Count = Length - sizeof(BYTE) - sizeof(BYTE) - sizeof(BYTE) - sizeof(BYTE);
+// fprintf(stderr, "Pres Context Length: %d\n", Length);
+// fprintf(stderr, "Reading Abstract Syntax\n");
+ AbsSyntax.Read(Link);
+ Count = Count - AbsSyntax.Size();
+ while ( Count > 0)
+ {
+// fprintf(stderr, "Reading Transfer Syntax Count = %d\n", Count);
+ Tran.Read ( Link );
+ Count = Count - Tran.Size();
+ TrnSyntax.Add ( Tran );
+ }
+// fprintf(stderr, "Read Presentation Context, ClearType = %d\n",
+// TrnSyntax.ClearType);
+ if ( !Count)
+ return ( TRUE );
+ return ( FALSE );
+ }
+
+UINT32 PresentationContext :: Size()
+ {
+ UINT Index;
+ Length = sizeof(BYTE) + sizeof(BYTE) + sizeof(BYTE) + sizeof(BYTE);
+ Length += AbsSyntax.Size();
+ Index = 0;
+ while(Index < TrnSyntax.GetSize() )
+ {
+ Length += TrnSyntax.Get(Index).Size();
+ ++Index;
+ }
+ return ( Length + sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT16));
+ }
+
+/************************************************************************
+ *
+ * Maximum Sub Length
+ *
+ ************************************************************************/
+
+MaximumSubLength :: MaximumSubLength()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x51),
+Reserved1(0),
+Length(0),
+MaximumLength(0) {}
+#else
+ {
+ ItemType = 0x51;
+ Reserved1 = 0;
+ }
+#endif
+
+MaximumSubLength :: MaximumSubLength(UINT32 Max)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x51),
+Reserved1(0),
+Length(0),
+MaximumLength(Max) {}
+#else
+ {
+ ItemType = 0x51;
+ Reserved1 = 0;
+ MaximumLength = Max;
+ }
+#endif
+
+MaximumSubLength :: ~MaximumSubLength()
+ {
+ // nothing to de-allocate
+ }
+
+void MaximumSubLength :: Set(UINT32 Max)
+ {
+ MaximumLength = Max;
+ }
+
+UINT32 MaximumSubLength :: Get()
+ {
+ return ( MaximumLength );
+ }
+
+BOOL MaximumSubLength :: Write(Buffer &Link)
+ {
+ Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT16));
+ Link << MaximumLength; //Link.Write((BYTE *) &MaximumLength, sizeof(UINT32));
+ Link.Flush();
+ return ( TRUE );
+ }
+
+BOOL MaximumSubLength :: Read(Buffer &Link)
+ {
+ Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return ( this->ReadDynamic(Link) );
+ }
+
+BOOL MaximumSubLength :: ReadDynamic(Buffer &Link)
+ {
+ Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT16));
+ Link >> MaximumLength; //Link.Read((BYTE *) &MaximumLength, sizeof(UINT32));
+
+ return ( TRUE );
+ }
+
+UINT32 MaximumSubLength :: Size()
+ {
+ Length = sizeof(UINT32);
+ return ( Length + sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT16));
+ }
+
+
+
+/******** SCP / SCU Role Select ***********/
+
+
+SCPSCURoleSelect :: SCPSCURoleSelect()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x54),
+Reserved1(0),
+Length(0),
+uid(),
+SCURole(),
+SCPRole() {}
+#else
+ {
+ ItemType = 0x54;
+ Reserved1 = 0;
+ }
+#endif
+
+SCPSCURoleSelect :: ~SCPSCURoleSelect()
+ {
+ // nothing to de-allocate
+ }
+
+
+BOOL SCPSCURoleSelect :: Write(Buffer &Link)
+ {
+ UINT16 TL;
+
+ ItemType = 0x54;
+
+ Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT16));
+ TL = uid.GetSize();
+ Link << TL; //Link.Write((BYTE *) &MaximumLength, sizeof(UINT32));
+ Link.Write((BYTE *) uid.GetBuffer(1), TL);
+ Link << SCURole;
+ Link << SCPRole;
+ Link.Flush();
+ return ( TRUE );
+ }
+
+BOOL SCPSCURoleSelect :: Read(Buffer &Link)
+ {
+ Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return ( this->ReadDynamic(Link) );
+ }
+
+BOOL SCPSCURoleSelect :: ReadDynamic(Buffer &Link)
+ {
+ UINT16 TL;
+
+ Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT16));
+ Link >> TL;
+ Link.Read((BYTE*) uid.GetBuffer(TL+1), TL);
+ uid.GetBuffer(Length)[Length] = '\0';
+ uid.SetLength(TL);
+ Link >> SCURole;
+ Link >> SCPRole;
+ return ( TRUE );
+ }
+
+UINT32 SCPSCURoleSelect :: Size()
+ {
+ Length = sizeof(UINT16) + uid.GetSize() + sizeof(BYTE) + sizeof(BYTE);
+ return ( Length + sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT16) );
+ }
+
+/************************************************************************
+ *
+ * User Information
+ *
+ ************************************************************************/
+
+UserInformation :: UserInformation()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x50),
+Reserved1(0),
+Length(0),
+UserInfoBaggage(0),
+MaxSubLength(0),
+ImpClass(),
+ImpVersion(),
+SCPSCURole() {}
+#else
+ {
+ ItemType = 0x50;
+ Reserved1 = 0;
+ UserInfoBaggage = 0;
+ }
+#endif
+
+UserInformation :: ~UserInformation()
+ {
+ // nothing to de-allocate
+ }
+
+void UserInformation :: SetMax(MaximumSubLength &Max)
+ {
+ MaxSubLength = Max;
+ }
+
+UINT32 UserInformation :: GetMax()
+ {
+ return(MaxSubLength.Get());
+ }
+
+BOOL UserInformation :: Write(Buffer &Link)
+ {
+ Link << ItemType; //Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link << Reserved1; //Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT16));
+ Link.Flush();
+ MaxSubLength.Write(Link);
+ ImpClass.Write(Link);
+ ImpVersion.Write(Link);
+ return ( TRUE );
+ }
+
+BOOL UserInformation :: Read(Buffer &Link)
+ {
+ Link >> ItemType; //Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+ return ( this->ReadDynamic(Link) );
+ }
+
+BOOL UserInformation :: ReadDynamic(Buffer &Link)
+ {
+ BYTE TempByte;
+ INT32 Count;
+
+ UserInfoBaggage = 0;
+
+ Link >> Reserved1; //Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT16));
+ Count = Length;
+// fprintf(stderr, "User Info Length: %d\n", Length);
+ while(Count > 0)
+ {
+ Link >> TempByte; //Link.Read((BYTE *) &TempByte, sizeof(BYTE));
+ switch ( TempByte )
+ {
+ case 0x51:
+// fprintf(stderr, "Reading Max Sub Length Count = %d\n", Count);
+ MaxSubLength.ReadDynamic(Link);
+ Count = Count - MaxSubLength.Size();
+ break;
+ case 0x52:
+// fprintf(stderr, "Reading Implementation Class Count = %d\n", Count);
+ ImpClass.ReadDynamic(Link);
+ Count = Count - ImpClass.Size();
+ break;
+ case 0x54: // Role selection
+ SCPSCURole.ReadDynamic(Link);
+ Count = Count - SCPSCURole.Size();
+ UserInfoBaggage += SCPSCURole.Size();
+ break;
+ case 0x55:
+// fprintf(stderr, "Reading Implemenation Version Count = %d\n", Count);
+ ImpVersion.ReadDynamic(Link);
+ Count = Count - ImpVersion.Size();
+ break;
+ default:
+ //fprintf(stderr, "Unknown Packet: %x, Count = %d\n", TempByte, Count);
+ Link.Kill(Count-1); // unknown user information packet
+ UserInfoBaggage = Count;
+ Count = -1;
+ }
+ }
+// fprintf(stderr, "ending User Info ReadD Count = %d\n", Count);
+ if(!Count)
+ return ( TRUE );
+ return ( FALSE );
+ }
+
+UINT32 UserInformation :: Size()
+ {
+ Length = MaxSubLength.Size();
+ Length += ImpClass.Size();
+ Length += ImpVersion.Size();
+ return ( Length + UserInfoBaggage + sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT16));
+ }
+
+/************************************************************************
+ *
+ * AAssociateRQ Packet
+ *
+ ************************************************************************/
+
+BOOL ConfigPadAEWithZeros = 0;
+
+AAssociateRQ :: AAssociateRQ()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x01),
+Reserved1(0),
+Length(0),
+ProtocolVersion(0x0001),
+Reserved2(0),
+AppContext(),
+PresContexts(),
+UserInfo()
+ {
+#else
+ {
+ ItemType = 0x01;
+ Reserved1 = 0;
+ ProtocolVersion = 0x0001;
+ Reserved2 = 0;
+#endif
+ SpaceMem(CalledApTitle, 16);
+ if (ConfigPadAEWithZeros) memset(CalledApTitle, 0, 16);
+ CalledApTitle[16] = 0;
+ SpaceMem(CallingApTitle, 16);
+ if (ConfigPadAEWithZeros) memset(CalledApTitle, 0, 16);
+ CallingApTitle[16] = 0;
+ ZeroMem(Reserved3, 32);
+ }
+
+AAssociateRQ :: AAssociateRQ(BYTE *CallingAp, BYTE *CalledAp)
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x01),
+Reserved1(0),
+Length(0),
+ProtocolVersion(0x0001),
+Reserved2(0),
+AppContext(),
+PresContexts(),
+UserInfo()
+ {
+#else
+ {
+ ItemType = 0x01;
+ Reserved1 = 0;
+ ProtocolVersion = 0x0001;
+ Reserved2 = 0;
+#endif
+ SpaceMem(CalledApTitle, 16);
+ if (ConfigPadAEWithZeros) memset(CalledApTitle, 0, 16);
+ CalledApTitle[16] = 0;
+ SpaceMem(CallingApTitle, 16);
+ if (ConfigPadAEWithZeros) memset(CalledApTitle, 0, 16);
+ CallingApTitle[16] = 0;
+ ZeroMem(Reserved3, 32);
+ memcpy(CallingApTitle, CallingAp, min(strlen((char *)CallingAp), 16u));
+ memcpy(CalledApTitle, CalledAp, min(strlen((char *)CalledAp), 16u));
+ }
+
+AAssociateRQ :: ~AAssociateRQ()
+ {
+ // nothing, everything should self-destruct nicely
+ while(PresContexts.GetSize())
+ {
+ PresContexts.Get ( 0 ).TrnSyntax.ClearType = TRUE;
+ PresContexts.RemoveAt ( 0 );
+ }
+
+ PresContexts.ClearType = TRUE;
+// fprintf(stderr, "~AAssociateRQ : PresContexts.ClearType = %d\n",
+// PresContexts.ClearType);
+ }
+
+void AAssociateRQ :: SetCalledApTitle(BYTE *CalledAp)
+ {
+ SpaceMem(CalledApTitle, 16);
+ if (ConfigPadAEWithZeros) memset(CalledApTitle, 0, 16);
+ memcpy(CalledApTitle, CalledAp, min(strlen((char *)CalledAp), 16u));
+ }
+
+void AAssociateRQ :: SetCallingApTitle(BYTE *CallingAp)
+ {
+ SpaceMem(CallingApTitle, 16);
+ if (ConfigPadAEWithZeros) memset(CalledApTitle, 0, 16);
+ memcpy(CallingApTitle, CallingAp, min(strlen((char *)CallingAp), 16u));
+ }
+
+void AAssociateRQ :: SetApplicationContext(ApplicationContext &AppC)
+ {
+ AppContext = AppC;
+ }
+
+void AAssociateRQ :: SetApplicationContext(UID &uid)
+ {
+ AppContext.Set(uid);
+ }
+
+void AAssociateRQ :: AddPresentationContext(PresentationContext &PresContext)
+ {
+ PresContexts.Add(PresContext);
+ PresContexts.Get(PresContexts.GetSize()-1).TrnSyntax.ClearType = TRUE;
+ }
+
+void AAssociateRQ :: SetUserInformation(UserInformation &User)
+ {
+ UserInfo = User;
+ }
+
+void AAssociateRQ :: ClearPresentationContexts()
+ {
+ while(PresContexts.GetSize())
+ PresContexts.RemoveAt ( 0 );
+ return;
+ }
+
+BOOL AAssociateRQ :: Write(Buffer &Link)
+ {
+ UINT Index;
+
+ //fprintf(stderr, "AAssociateRQ :: Write ()\n");fflush(stderr);
+ Size();
+ Link << ItemType; //Link.Write((BYTE *) &ItemType, sizeof(BYTE));
+ Link.Write((BYTE *) &Reserved1, sizeof(BYTE));
+ Link << Length; //Link.Write((BYTE *) &Length, sizeof(UINT32));
+ Link << ProtocolVersion; //Link.Write((BYTE *) &ProtocolVersion, sizeof(UINT16));
+ Link << Reserved2; //Link.Write((BYTE *) &Reserved2, sizeof(UINT16));
+ Link.Write((BYTE *) CalledApTitle, 16);
+ Link.Write((BYTE *) CallingApTitle, 16);
+ Link.Write((BYTE *) Reserved3, 32);
+ Link.Flush();
+ AppContext.Write(Link);
+ Index = 0;
+ while(Index < PresContexts.GetSize())
+ {
+ PresContexts[Index].Write(Link);
+ ++Index;
+ }
+ UserInfo.Write(Link);
+ return ( TRUE );
+ }
+
+BOOL AAssociateRQ :: Read(Buffer &Link)
+ {
+// fprintf(stderr, "Attempting to Read AAssociateRQ PDU\n");
+ Link.Read((BYTE *) &ItemType, sizeof(BYTE));
+// fprintf(stderr, "Got ItemType: %x\n", ItemType);
+ return(this->ReadDynamic(Link));
+ }
+
+BOOL AAssociateRQ :: ReadDynamic(Buffer &Link)
+ {
+ INT Count;
+ BYTE TempByte;
+ PresentationContext *PresContext;
+
+ Link.Read((BYTE *) &Reserved1, sizeof(BYTE));
+ Link >> Length; //Link.Read((BYTE *) &Length, sizeof(UINT32));
+ Link >> ProtocolVersion; //Link.Read((BYTE *) &ProtocolVersion, sizeof(UINT16));
+ Link >> Reserved2; //Link.Read((BYTE *) &Reserved2, sizeof(UINT16));
+ Link.Read((BYTE *) CalledApTitle, 16);
+ Link.Read((BYTE *) CallingApTitle, 16);
+ Link.Read((BYTE *) Reserved3, 32);
+ CalledApTitle[16] = '\0';
+ CallingApTitle[16] = '\0';
+// fprintf(stderr, "Item Length: %d\n", Length);
+// fprintf(stderr, "Protocol Version: %d\n", ProtocolVersion);
+// fprintf(stderr, "CalledApTitle: %16.16s\n", CalledApTitle);
+// fprintf(stderr, "CallingApTitle: %16.16s\n", CallingApTitle);
+
+ Count = Length - sizeof(UINT16) - sizeof(UINT16) - 16 - 16 - 32;
+ while(Count > 0)
+ {
+ Link.Read((BYTE *) &TempByte, sizeof(BYTE));
+ switch(TempByte)
+ {
+ case 0x50: // user information
+// fprintf(stderr, "Reading User Information (%d)\n", Count);
+ UserInfo.ReadDynamic(Link);
+ Count = Count - UserInfo.Size() - UserInfo.UserInfoBaggage;
+// fprintf(stderr, "Count = %d/UserInfo = %d\n", Count,
+// UserInfo.Size());
+ break;
+ case 0x20:
+// fprintf(stderr, "Reading Presentation Context (%d)\n", Count);
+ PresContext = new PresentationContext;
+ PresContext->TrnSyntax.ClearType = TRUE;
+ PresContext->ReadDynamic(Link);
+ Count = Count - PresContext->Size();
+ PresContexts.Add(*PresContext);
+ PresContext->TrnSyntax.ClearType = FALSE;
+ delete PresContext;
+
+ break;
+ case 0x10:
+// fprintf(stderr, "Reading AppContext (%d)\n", Count);
+ AppContext.ReadDynamic(Link);
+ Count = Count - AppContext.Size();
+ break;
+ default:
+ //fprintf(stderr, "unknown item: %x ending\n", TempByte);
+ Link.Kill(Count-1);
+ Count = -1;
+ }
+ }
+ if(!Count)
+ return ( TRUE );
+ return ( FALSE);
+ }
+
+UINT32 AAssociateRQ :: Size()
+ {
+ UINT Index;
+
+ Length = sizeof(UINT16) + sizeof(UINT16) + 16 + 16 + 32;
+ Length += AppContext.Size();
+ Index = 0;
+
+ while(Index < PresContexts.GetSize())
+ {
+ Length += PresContexts[Index].Size();
+ ++Index;
+ }
+ Length += UserInfo.Size();
+ return ( Length + sizeof(BYTE) + sizeof(BYTE) + sizeof(UINT32) );
+ }
+
diff --git a/aarq.hpp b/aarq.hpp
new file mode 100644
index 0000000..a131164
--- /dev/null
+++ b/aarq.hpp
@@ -0,0 +1,350 @@
+/* mvh 20001106: Use memcpy instead of ByteCopy
+ bcb 20091231: Changed char* to const char* for gcc4.2 warnings
+ mvh 20100111: Merged
+ bcb 20100619: Fix gcc4 warnings, improve speed and added UNUSED_ARGUMENT.
+ mvh 20100717: Merged; Q1 OK
+ bcb 20100728: Added PresentationContext(const PresentationContext&)
+ mvh 20100815: Merged
+ */
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/***********************************************************************
+ * PDU Service Classes:
+ * A-ASSOCIATE-RQ Class.
+ *
+ * Base Classes:
+ * UID
+ * ApplicationContext
+ * AbstractSyntax
+ * TransferSyntax
+ * PresentationContext
+ * MaximumSubLength
+ * ImplementationClass
+ * ImplementationVersion
+ * UserInformation
+ *
+ *
+ *
+ *********************************************************************/
+#ifndef UNUSED_ARGUMENT
+#define UNUSED_ARGUMENT(x) (void)x
+#endif
+
+class UID
+ {
+ UINT Length;
+ BYTE uid[65];
+
+ public:
+#ifdef __GNUC__ //Faster with member initialization.
+ UID():Length(0) { ZeroMem(uid, 64);};
+ UID(BYTE *s):Length(0) { Set ( s ); };
+ UID(const char *s):Length(0) { Set ( (BYTE*)s ); };
+#else
+ UID() { ZeroMem(uid, 64); Length = 0; };
+ UID(BYTE *s) { Set ( s ); };
+ UID(const char *s) { Set ( (BYTE*)s ); };
+#endif
+ void Set(BYTE *s)
+ {
+ if(!s)
+ return;
+ ZeroMem(uid, 64);
+ strcpy((char *) uid, (char *) s);
+ Length = strlen((char*) uid);
+ };
+ void Set(UID &u) { (*this) = u; };
+ void Set(const char *s) { this->Set((BYTE *) s); };
+ BYTE *GetBuffer(UINT Min) { UNUSED_ARGUMENT(Min); return(&uid[0]); };
+ void SetLength(UINT L) { Length = L; while (L < 65) uid[L++] = '\0'; };
+ UINT GetSize() { return ( Length ); };
+ BOOL operator == (UID &ud)
+ { //if(GetSize()!=ud.GetSize()) return(FALSE);
+ if(!strcmp((char*) GetBuffer(1), (char*) ud.GetBuffer(1)/*, (int) GetSize()*/))
+ return(TRUE);
+ return(FALSE); };
+ BOOL operator != (UID &ud) { return (!((*this)==ud)); };
+#ifndef __GNUC__ // not used (at least not in the gcc build).
+ UID operator = (UID &ud)
+ { memcpy(uid, ud.GetBuffer(1), 64);
+ SetLength(ud.GetSize());
+ return(*this);
+ }
+#endif
+ };
+
+class ApplicationContext
+ {
+ private:
+ BYTE ItemType; // 0x10
+ BYTE Reserved1;
+ UINT16 Length;
+ public:
+ UID ApplicationContextName;
+
+ ApplicationContext();
+ ApplicationContext(UID &);
+ ApplicationContext(BYTE *);
+ ~ApplicationContext();
+ void Set(UID &);
+ void Set(BYTE *);
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+ };
+
+class AbstractSyntax
+ {
+ private:
+ BYTE ItemType; // 0x30
+ BYTE Reserved1;
+ UINT16 Length;
+ public:
+ UID AbstractSyntaxName;
+ AbstractSyntax();
+ AbstractSyntax(BYTE *);
+ AbstractSyntax(UID &);
+ ~AbstractSyntax();
+ void Set(UID &);
+ void Set(BYTE *);
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+
+ };
+
+class TransferSyntax
+ {
+ private:
+ BYTE ItemType; // 0x40
+ BYTE Reserved1;
+ UINT16 Length;
+ public:
+ UID TransferSyntaxName;
+ UINT EndianType;
+ TransferSyntax();
+ TransferSyntax(BYTE *);
+ TransferSyntax(UID &);
+ ~TransferSyntax();
+ void Set(UID &);
+ void Set(BYTE *);
+ void SetType(UINT T) { EndianType = T; };
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+
+ };
+
+class ImplementationClass
+ {
+ private:
+ BYTE ItemType; // 0x52
+ BYTE Reserved1;
+ UINT16 Length;
+ public:
+ UID ImplementationName;
+ UINT EndianType;
+ ImplementationClass();
+ ImplementationClass(BYTE *);
+ ImplementationClass(UID &);
+ ~ImplementationClass();
+ void Set(UID &);
+ void Set(BYTE *);
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+
+ };
+
+
+class ImplementationVersion
+ {
+ private:
+ BYTE ItemType; // 0x55
+ BYTE Reserved1;
+ UINT16 Length;
+ public:
+ UID Version;
+ UINT EndianType;
+ ImplementationVersion();
+ ImplementationVersion(BYTE *);
+ ImplementationVersion(UID &);
+ ~ImplementationVersion();
+ void Set(UID &);
+ void Set(BYTE *);
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+
+ };
+
+
+class SCPSCURoleSelect
+ {
+ private:
+ BYTE ItemType; // 0x54
+ BYTE Reserved1;
+ UINT16 Length;
+ public:
+ UID uid;
+ BYTE SCURole;
+ BYTE SCPRole;
+ SCPSCURoleSelect();
+ ~SCPSCURoleSelect();
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+
+ };
+
+
+
+class PresentationContext
+ {
+ private:
+ BYTE ItemType; // 0x20
+ BYTE Reserved1;
+ UINT16 Length;
+ public:
+ BYTE PresentationContextID;
+ private:
+ BYTE Reserved2;
+ BYTE Reserved3;
+ BYTE Reserved4;
+ public:
+ AbstractSyntax AbsSyntax;
+ Array<TransferSyntax> TrnSyntax;
+ PresentationContext();
+ PresentationContext(AbstractSyntax &, TransferSyntax &);
+ ~PresentationContext();
+ void SetAbstractSyntax(AbstractSyntax &);
+ void AddTransferSyntax(TransferSyntax &);
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+
+// Used in PDU_Service::AddAbstractSyntaxAlias (UID &UIDSource, UID &UIDAlias)
+// in the line PresentationContext vPresContext = PresContext;
+// Since it is used, we need to control it. Current commented out.
+/* PresentationContext(const PresentationContext&):ItemType(0x20),
+ Reserved1(Reserved1), Length(Length), PresentationContextID(PresentationContextID),
+ Reserved2(Reserved2), Reserved3(Reserved3), Reserved4(Reserved4),
+ AbsSyntax(AbsSyntax), TrnSyntax(TrnSyntax) {};*/
+ private:// Prevents copying
+ PresentationContext(const PresentationContext&):ItemType(0x20),
+ Reserved1(0), Length(0), PresentationContextID(0),
+ Reserved2(0), Reserved3(0), Reserved4(0),
+ AbsSyntax(NULL), TrnSyntax() {};
+ };
+
+class MaximumSubLength
+ {
+ private:
+ BYTE ItemType; // 0x51
+ BYTE Reserved1;
+ UINT16 Length;
+ UINT32 MaximumLength;
+ public:
+ MaximumSubLength();
+ MaximumSubLength(UINT32);
+ ~MaximumSubLength();
+ void Set(UINT32);
+ UINT32 Get();
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+ };
+
+class UserInformation
+ {
+ private:
+ BYTE ItemType; // 0x50
+ BYTE Reserved1;
+ UINT16 Length;
+ public:
+ UINT32 UserInfoBaggage;
+ MaximumSubLength MaxSubLength;
+ ImplementationClass ImpClass;
+ ImplementationVersion ImpVersion;
+ SCPSCURoleSelect SCPSCURole;
+ public:
+ UserInformation();
+ ~UserInformation();
+ void SetMax(MaximumSubLength &);
+ UINT32 GetMax();
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+ };
+
+class AAssociateRQ
+ {
+ private:
+ BYTE ItemType; // 0x01
+ BYTE Reserved1;
+ UINT32 Length;
+ UINT16 ProtocolVersion; // 0x01
+ UINT16 Reserved2;
+ public:
+ BYTE CalledApTitle[17]; // 16 bytes transfered
+ BYTE CallingApTitle[17]; // 16 bytes transfered
+ BYTE Reserved3[32];
+
+ ApplicationContext AppContext;
+ Array<PresentationContext> PresContexts;
+ UserInformation UserInfo;
+ public:
+ AAssociateRQ();
+ AAssociateRQ(BYTE *, BYTE *);
+ virtual ~AAssociateRQ();
+ void SetCalledApTitle(BYTE *);
+ void SetCallingApTitle(BYTE *);
+ void SetApplicationContext(ApplicationContext &);
+ void SetApplicationContext(UID &);
+ void AddPresentationContext(PresentationContext &);
+ void ClearPresentationContexts();
+ void SetUserInformation(UserInformation &);
+ BOOL Write(Buffer &);
+ BOOL Read(Buffer &);
+ BOOL ReadDynamic(Buffer &);
+ UINT32 Size();
+ };
+
+
diff --git a/acrnema.map b/acrnema.map
new file mode 100644
index 0000000..c1baed9
--- /dev/null
+++ b/acrnema.map
@@ -0,0 +1,26 @@
+/* **********************************************************
+ * *
+ * DICOM AE (Application entity) -> IP address / Port map *
+ * (This is file ACRNEMA.MAP) *
+ * *
+ * All DICOM systems that want to retrieve images from the *
+ * Conquest DICOM server must be listed here with correct *
+ * AE name, (IP adress or hostname) and port number. *
+ * The first entry is the Conquest system as example. *
+ * *
+ * *
+ * The syntax for each entry is : *
+ * AE <IP adress|Host name> port number compression *
+ * *
+ * For compression see manual. Values are un=uncompressed; *
+ * j1,j2=lossless jpeg;j3..j6=lossy jpeg;n1..n4=nki private *
+ * jk=lossless jpeg2000;jl=lossy jpeg2000 *
+ * *
+ ********************************************************** */
+
+CONQUESTSRV1 127.0.0.1 5678 as
+SUPERMICRO 192.168.0.53 5678 as
+SKY 192.168.0.34 5678 un
+
+V* * 1234 as
+S* * 5678 un
diff --git a/amap.cpp b/amap.cpp
new file mode 100644
index 0000000..9687c06
--- /dev/null
+++ b/amap.cpp
@@ -0,0 +1,292 @@
+/* mvh 19990827: added (limited) wildcard mapping in GetACRNema: AE, port or IP may end on '*'
+ mvh 20001105: replaced m-alloc by new
+ mvh 20011109: Made AE mapping case insensitive
+ ljz 20020524: In function 'GetACRNema', first try case SENSITIVE then INSENSITIVE
+ mvh 20030701: Added compression column (with this code is this column is not optional!)
+ mvh 20030703: KNOWN BUG: number of columns may not be 3 (crashes)
+ ljz 20030709: Solved above problem; rewritten parsing of Acrnema.map
+ ljz 20030711: Fixed trailing spaces in acrnema.map
+ ljz 20031118: Fixed leak InitACRNemaAddressArray
+*/
+
+
+#ifndef WHEDGE
+# include "dgate.hpp"
+#else
+# include "master.h"
+#endif
+
+
+BYTE ACRNEMAMAP [ 256 ] = "acrnema.map";
+Array < ACRNemaAddress * > ACRNemaAddressArray;
+
+
+
+BOOL
+InitACRNemaAddressArray(void)
+{ FILE* f;
+ char* pBuffer;
+ int i, iSize;
+ char *pSrc, *pDest;
+ ACRNemaAddress* pACR;
+ int iNbAddresses;
+
+ /* Open AcrNema.map */
+ f = fopen((char*)ACRNEMAMAP, "rb");
+ if (!f)
+ return FALSE;
+
+ /* Read it in memory */
+ fseek(f, 0, SEEK_END);
+ iSize = ftell(f);
+ fseek(f, 0, SEEK_SET);
+ pBuffer = (char*)malloc(iSize + 2);
+ if (!pBuffer)
+ { fclose(f);
+ return FALSE;
+ }
+ if (fread(pBuffer, 1, iSize, f) != (unsigned int)iSize)
+ { fclose(f);
+ free(pBuffer);
+ return FALSE;
+ }
+ fclose(f);
+
+ /* Make it a CR and zero terminated string */
+ pBuffer[iSize++] = '\r';
+ pBuffer[iSize] = '\0';
+
+ /* Get rid of all comments like this one */
+ pSrc = pBuffer;
+ pDest = pBuffer;
+ i = 0;
+ while (i<iSize)
+ { if ((pSrc[i] == '/') && (pSrc[i + 1] == '*'))
+ { /* Found the start of a comment */
+ i += 2;
+ while (i<iSize)
+ { if ((pSrc[i] == '*') && (pSrc[i + 1] == '/'))
+ { i++;
+ break;
+ }
+ i++;
+ }
+ }
+ else
+ *pDest++ = pSrc[i];
+ i++;
+ }
+ *pDest = 0;
+
+ /* Replace all LF by CR, and all '\t' by ' ' */
+ iSize = strlen(pSrc);
+ for (i=0; i<iSize; i++)
+ if (pSrc[i] == '\n')
+ pSrc[i] = '\r';
+ else if (pSrc[i] == '\t')
+ pSrc[i] = ' ';
+
+ /* The characters '#', ';' and '//' are one-line comments */
+ pDest = pSrc;
+ i = 0;
+ while (i<iSize)
+ { if ((pSrc[i] == '/') && (pSrc[i + 1] == '/'))
+ { /* Found the start of a comment */
+ i += 2;
+ while (i<iSize)
+ { if (pSrc[i] == '\r')
+ break;
+ i++;
+ }
+ }
+ else if ((pSrc[i] == '#') || (pSrc[i + 1] == ';'))
+ { /* Found the start of a comment */
+ i += 1;
+ while (i<iSize)
+ { if (pSrc[i] == '\r')
+ break;
+ i++;
+ }
+ }
+ else
+ *pDest++ = pSrc[i];
+ i++;
+ }
+ *pDest = 0;
+
+ /* Eliminate empty lines, double space... */
+ iSize = strlen(pSrc);
+ pDest = pSrc;
+ i = 0;
+ while (i<iSize)
+ { if (pSrc[i] == ' ')
+ { if (pDest == pSrc)
+ { /* Skip leading space */
+ i++;
+ continue;
+ }
+ else if ((pDest[-1] == ' ') || (pDest[-1] == '\r'))
+ { /* Skip space when the previous was space or CR */
+ i++;
+ continue;
+ }
+ else if (pSrc[i+1] == '\r')
+ { /* Skip space when the next is CR */
+ i++;
+ continue;
+ }
+ }
+ else if (pSrc[i] == '\r')
+ { if (pDest == pSrc)
+ { /* Skip leading CR */
+ i++;
+ continue;
+ }
+ else if (pDest[-1] == '\r')
+ { /* Skip CR when the previous was a CR */
+ i++;
+ continue;
+ }
+ }
+ *pDest++ = pSrc[i];
+ i++;
+ }
+ *pDest = 0;
+
+ /* Count the iNbAddresses */
+ iSize = strlen(pSrc);
+ iNbAddresses = 0;
+ for (i=0; i<iSize; i++)
+ if (pSrc[i] == '\r')
+ iNbAddresses++;
+
+ /* Now fill the ACRNemaAddressArray */
+ pDest = pSrc;
+ for (i=0; i<iNbAddresses; i++)
+ { pACR = new ACRNemaAddress;
+ strcpy(pACR->Name, "");
+ strcpy(pACR->IP, "");
+ strcpy(pACR->Port, "");
+ strcpy(pACR->Compress, "un");
+
+ /* Get a line */
+ *strchr(pDest, '\r') = 0;
+ sscanf(pDest, "%s %s %s %s",
+ pACR->Name,
+ pACR->IP,
+ pACR->Port,
+ pACR->Compress);
+
+ ACRNemaAddressArray.Add(pACR);
+ pDest = pDest + strlen(pDest) + 1;
+ }
+
+ free(pBuffer);
+ return TRUE;
+}
+
+
+BOOL
+CloseACRNemaAddressArray()
+ {
+ while ( ACRNemaAddressArray.GetSize() )
+ {
+ delete ACRNemaAddressArray.Get(0);
+ ACRNemaAddressArray.RemoveAt(0);
+ }
+ return ( TRUE );
+ }
+
+
+static
+BOOL
+__iswhitespacea(char ch)
+ {
+ switch ( ch )
+ {
+ case ' ':
+ case '\t':
+ case '\r':
+ case '\n':
+ case 0:
+ return ( TRUE );
+ }
+ return ( FALSE );
+ }
+
+
+BOOL
+GetACRNema(char* ACRNema, char* ip, char* port, char* compress)
+ {
+ UINT Index;
+ char s[20];
+ char *t;
+
+ // trim the ACRNema address
+
+ memset(s, 0, 20);
+
+ strcpy(s, ACRNema);
+ if(!strlen(s))
+ return ( FALSE );
+ while(__iswhitespacea(s[strlen(s)-1]))
+ {
+ s[strlen(s)-1] = '\0';
+ if(!strlen(s))
+ return ( FALSE );
+ }
+
+
+ Index = 0;
+ while ( Index < ACRNemaAddressArray.GetSize())
+ {
+ t = ACRNemaAddressArray.Get(Index)->Name;
+
+ // try wildcard mapping, e.g., s=NG12, t=NG*, IP=101.11.11.*, Port=56*
+ if (t[strlen(t)-1] == '*')
+ {
+ if (!memicmp(t, s, strlen(t)-1))
+ {
+ strcpy(ip, ACRNemaAddressArray.Get(Index)->IP);
+ if (ip[strlen(ip)-1]=='*')
+ strcpy(ip+strlen(ip)-1, s+strlen(t)-1);
+
+ strcpy(port, ACRNemaAddressArray.Get(Index)->Port);
+ if (port[strlen(port)-1]=='*')
+ strcpy(port+strlen(port)-1, s+strlen(t)-1);
+ strcpy(compress, ACRNemaAddressArray.Get(Index)->Compress);
+ return ( TRUE );
+ }
+ }
+
+ // try exact match (case sensitive)
+ if (!strcmp(t, s))
+ {
+ strcpy(ip, ACRNemaAddressArray.Get(Index)->IP);
+ strcpy(port, ACRNemaAddressArray.Get(Index)->Port);
+ strcpy(compress, ACRNemaAddressArray.Get(Index)->Compress);
+ return ( TRUE );
+ }
+ ++Index;
+ }
+
+ Index = 0;
+ while ( Index < ACRNemaAddressArray.GetSize())
+ {
+ t = ACRNemaAddressArray.Get(Index)->Name;
+
+ // try exact match (case insensitive)
+ if (!stricmp(t, s))
+ {
+ strcpy(ip, ACRNemaAddressArray.Get(Index)->IP);
+ strcpy(port, ACRNemaAddressArray.Get(Index)->Port);
+ strcpy(compress, ACRNemaAddressArray.Get(Index)->Compress);
+ return ( TRUE );
+ }
+ ++Index;
+ }
+
+ return ( FALSE );
+ }
+
+
diff --git a/anonymize_script.cq b/anonymize_script.cq
new file mode 100644
index 0000000..bf049cb
--- /dev/null
+++ b/anonymize_script.cq
@@ -0,0 +1 @@
+lua/anonymize_script.lua
diff --git a/array.tcc b/array.tcc
new file mode 100644
index 0000000..9421a64
--- /dev/null
+++ b/array.tcc
@@ -0,0 +1,328 @@
+/*
+20050125 ljz Added 'ReplaceAt()' to the 'Array' class
+20100619 bcb Fix gcc4 warnings and improve speed.
+20130429 lsp Corrected (unused) printf format string
+20130812 mvh Removed non-thread safe caching of last value
+ Does not seem to affect speed, throughput remains
+ at 320 MB/s receive with 3 senders and receivers
+ in same dgate on 8-core machine
+20131016 mvh Merged
+ */
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/*
+template <class DATATYPE>
+ Array<DATATYPE> :: Array ()
+ {
+ ArraySize = 0;
+ first = NULL;
+ last = NULL;
+ ClearType = 1;
+ }
+*/
+
+template <class DATATYPE>
+ Array<DATATYPE> :: Array (UINT CT)
+#ifdef __GNUC__ //Faster with member initialization.
+:first(NULL),
+last(NULL),
+//LastAccess(NULL),
+//LastAccessNumber(0),
+ArraySize(0),
+ClearType(CT) {}
+#else
+ {
+ ArraySize = 0;
+ first = NULL;
+ last = NULL;
+ //LastAccess = NULL;
+ //LastAccessNumber = 0;
+ ClearType = CT;
+ }
+#endif
+
+template <class DATATYPE>
+ Array<DATATYPE> :: ~Array()
+ {
+ if(ClearType == 1)
+ {
+ while(ArraySize)
+ RemoveAt(0);
+ }
+ }
+
+template <class DATATYPE>
+DATATYPE & Array<DATATYPE> :: Add(DATATYPE &Value)
+ {
+
+ // record current end-of-chain element
+
+ DataLink<DATATYPE> *dl = last;
+
+ // chain on new element at tail of chain
+
+ last = new DataLink<DATATYPE>;
+ last->Data = Value;
+
+ // set new element's backward pointer to point to former
+ // end-of-chain element
+
+ last->prev = dl;
+
+ // set former end-of-chain's next pointer to point to new element
+
+ if(dl)
+ {
+ dl->next = last;
+ }
+ else
+ {
+ // there was previously no "last" element so the one just
+ // allocated must be the first
+
+ first = last;
+ }
+
+ ++ArraySize;
+ return ( Value );
+ }
+
+template <class DATATYPE>
+DATATYPE & Array<DATATYPE> :: Get(unsigned int Index)
+ {
+ DataLink<DATATYPE> *dl;
+ unsigned int rIndex = Index;
+
+ if ( Index >= ArraySize )
+ {
+ //fprintf(stderr, "Returning NULL Data\n");
+ //return ( NullData );
+ dl = NULL;
+ return ( (DATATYPE &) *dl ); // Invoke a seg fault
+ }
+
+ /*if ( LastAccess )
+ {
+ if ((LastAccessNumber + 1) == Index )
+ {
+ LastAccess = LastAccess->next;
+ ++LastAccessNumber;
+ return ( LastAccess->Data );
+ }
+ }
+ */
+
+ // locate requested element by following pointer chain
+ // decide which is faster -- scan from head or scan from tail
+
+ if(Index < ArraySize / 2)
+ {
+
+ // requested element closer to head -- scan forward
+
+ dl = first;
+ ++Index;
+ while(--Index > 0)
+ {
+ dl = dl->next;
+ }
+ }
+ else
+ {
+
+ // requested element closer to tail -- scan backwards
+
+ dl = last;
+ Index = (ArraySize - Index);
+ while(--Index > 0)
+ {
+ dl = dl->prev;
+ }
+ }
+
+ //LastAccess = dl;
+ //LastAccessNumber = rIndex;
+ return ( dl->Data );
+ }
+
+template <class DATATYPE>
+DATATYPE & Array<DATATYPE> :: ReplaceAt(DATATYPE &Value, unsigned int Index)
+ {
+ DataLink<DATATYPE> *dl;
+ unsigned int rIndex = Index;
+
+ if ( Index >= ArraySize )
+ {
+ //fprintf(stderr, "Returning NULL Data\n");
+ //return ( NullData );
+ dl = NULL;
+ return ( (DATATYPE &) *dl ); // Invoke a seg fault
+ }
+
+ /*if ( LastAccess )
+ {
+ if ((LastAccessNumber + 1) == Index )
+ {
+ LastAccess = LastAccess->next;
+ ++LastAccessNumber;
+ LastAccess->Data = Value;
+ return ( LastAccess->Data );
+ }
+ }
+ */
+
+ // locate requested element by following pointer chain
+ // decide which is faster -- scan from head or scan from tail
+
+ if(Index < ArraySize / 2)
+ {
+
+ // requested element closer to head -- scan forward
+
+ dl = first;
+ ++Index;
+ while(--Index > 0)
+ {
+ dl = dl->next;
+ }
+ }
+ else
+ {
+
+ // requested element closer to tail -- scan backwards
+
+ dl = last;
+ Index = (ArraySize - Index);
+ while(--Index > 0)
+ {
+ dl = dl->prev;
+ }
+ }
+
+ //LastAccess = dl;
+ //LastAccessNumber = rIndex;
+ dl->Data = Value;
+ return ( dl->Data );
+ }
+
+template <class DATATYPE>
+BOOL Array<DATATYPE> :: RemoveAt(unsigned int Index)
+ {
+ DataLink<DATATYPE> *dl;
+
+ //LastAccess = NULL;
+ //LastAccessNumber = 0;
+
+ if( Index >= ArraySize )
+ {
+ //fprintf(stderr, "Attempting to remove non-existance node\n");
+ //return ( NullData );
+ return( FALSE );
+ }
+
+ // follow pointer chain from head or tail to requested element
+ // depending upon which chain is shorter
+
+ if(Index < ArraySize / 2)
+ {
+ // element closer to head => follow chain forward from first
+ dl = first;
+ ++Index;
+ while(--Index > 0)
+ {
+ dl = dl->next;
+ }
+ }
+ else
+ {
+ // element closer to tail => follow chain backward from last
+ dl = last;
+ Index = (ArraySize - Index);
+ while(--Index > 0)
+ {
+ dl = dl->prev;
+ }
+ }
+
+ // relink chain around element to be deleted
+ // fix first or last pointer if element to delete is first or last
+
+ if(dl->prev)
+ dl->prev->next = dl->next;
+ else
+ first = dl->next;
+
+ if(dl->next)
+ dl->next->prev = dl->prev;
+ else
+ last = dl->prev;
+
+ delete dl;
+ --ArraySize;
+ return ( TRUE );
+ }
+
+/****************************************************************
+ * Test Functions
+ *
+ *
+ ****************************************************************/
+
+# ifdef BUILD_TEST_UNITS
+
+int
+testfunc()
+ {
+ unsigned int Index;
+ Array<int> AInt;
+
+ Index = 0;
+ while(Index < 10)
+ {
+ AInt.Add(Index * 2);
+ ++Index;
+ }
+ Index = 0;
+ while(Index < 10)
+ {
+ printf("Val: %d : %d\n", Index, AInt.RemoveAt(0));
+ ++Index;
+ }
+ return ( 0 );
+ }
+
+int
+main()
+ {
+ testfunc();
+ fprintf(stderr, "Display Should be like 'Val: x: 2*x' with x[0..9]\n");
+ }
+
+# endif
diff --git a/array.thh b/array.thh
new file mode 100644
index 0000000..b7fcc56
--- /dev/null
+++ b/array.thh
@@ -0,0 +1,133 @@
+/*
+20050125 ljz Added 'ReplaceAt()' to the 'Array' class
+20100617 bcb Fix gcc4 warnings, improve speed and added constructors.
+20100717 mvh Merged; QUES:6 ok; changed = operator; QUES:7 ?
+20100816 mvh Meged bcb cleanup
+20130812 mvh Removed non-thread safe caching of last value
+*/
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/*********************************************************************
+ * Array Unit Class
+ *
+ * ANSI (ARM) C++ Compatible / Templates Required
+ *
+ *
+ * usage:
+ *
+ * # include "array.thh"
+ * # include "array.tcc"
+ *
+ *
+ * Array<ClassType> VarName;
+ *
+ *
+ *********************************************************************/
+
+
+template <class DATATYPE>
+class DataLink
+ {
+ public:
+ DATATYPE Data;
+ DataLink<DATATYPE> *prev, *next;
+ DataLink(DataLink<DATATYPE> *p, DataLink<DATATYPE> *n)
+ { prev = p; next = n; };
+#ifdef __GNUC__
+ DataLink():Data(), prev(NULL), next(NULL) {};
+#else
+ DataLink()
+ { prev = NULL; next = NULL; };
+#endif
+#ifdef __GNUC__
+ private:// This will prevent it from being copied (it has pointers)
+ DataLink(const DataLink&);
+ const DataLink<DATATYPE> & operator = (const DataLink<DATATYPE>&);
+#endif
+ };
+
+template <class DATATYPE>
+class Array
+ {
+ public:
+
+ DataLink<DATATYPE> *first;
+ DataLink<DATATYPE> *last;
+ //DataLink<DATATYPE> *LastAccess;
+ //unsigned int LastAccessNumber;
+ unsigned int ArraySize;
+ public:
+ UINT ClearType;
+ DATATYPE & Add(DATATYPE &);
+ DATATYPE & Get(unsigned int);
+ DATATYPE & ReplaceAt(DATATYPE &, unsigned int);
+ BOOL RemoveAt(unsigned int);
+ BOOL Clear ()
+ {
+ first = last = /*LastAccess =*/ NULL;
+ //LastAccessNumber = 0;
+ ArraySize = 0;
+ return ( TRUE );
+ }
+#ifdef MAC
+ DATATYPE & operator [] (unsigned int Index)
+ { return(Get(Index)); };
+ unsigned int GetSize()
+ { return(ArraySize); };
+#else
+ inline DATATYPE & operator [] (unsigned int Index)
+ { return(Get(Index)); };
+ inline unsigned int GetSize()
+ { return(ArraySize); };
+#endif
+#ifdef __GNUC__
+ Array()
+ :first(NULL), last(NULL), /*LastAccess(NULL), LastAccessNumber(0),*/ ArraySize(0), ClearType(1) {};
+#else
+ Array()
+ { first = NULL; last = NULL; /*LastAccess = NULL; LastAccessNumber = 0;*/ ArraySize = 0; ClearType = 1; };
+#endif
+ Array(UINT);
+#ifdef MAC
+ ~Array();
+#else
+ virtual ~Array();
+#endif
+ const Array<DATATYPE> & operator = (Array<DATATYPE> &array)
+ { first = array.first; last = array.last; ArraySize = array.ArraySize; ClearType = FALSE; return *this; };
+
+// Used in PDU_Service::AddAbstractSyntaxAlias (UID &UIDSource, UID &UIDAlias)
+// in the line PresentationContext vPresContext = PresContext; Commented out
+// Now using the line Array<TransferSyntax> vTrnSyntax = PresContext.TrnSyntax;
+ Array(const Array & array)
+ :first(array.first), /*last(array.last),LastAccess(array.LastAccess),*/
+ /*LastAccessNumber(array.LastAccessNumber),*/ ArraySize(array.ArraySize), ClearType(FALSE) {};
+ };
diff --git a/base.hpp b/base.hpp
new file mode 100644
index 0000000..91b53b8
--- /dev/null
+++ b/base.hpp
@@ -0,0 +1,76 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/* 20100726 bcb Removed superfluous ; */
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+// Base Class Include Header
+#if __MWERKS__
+// Macintosh Compiling is a little different. We don't pass in a system/endian
+// on the "command line", hence, we detect the MetroWorks compiler.
+# define MAC
+# define NATIVE_ENDIAN 2
+#endif
+#ifdef MAC
+# include <stdio.h>
+# include <string.h>
+# include "macsock.h"
+#else
+extern "C"
+ {
+# include <stdio.h>
+# include <string.h>
+ }
+#endif
+#ifdef WINDOWS
+# include <windows.h>
+# include <winsock.h>
+# include <share.h>
+#else
+#ifdef MAC
+
+#else
+# include "unixsock.h"
+#endif
+#endif
+# include "cctypes.h"
+# include "safemem.h"
+# include "util.h"
+# include "array.thh"
+# include "array.tcc"
+# include "pqueue.thh"
+# include "pqueue.tcc"
+# include "farray.thh"
+# include "buffer.thh"
+
+// Sometimes it's easier to do something like this than guess
+// for all the various systems..
+#ifndef SEEK_SET
+# define SEEK_SET 0
+#endif
+
diff --git a/buffer.cxx b/buffer.cxx
new file mode 100644
index 0000000..08130e0
--- /dev/null
+++ b/buffer.cxx
@@ -0,0 +1,657 @@
+/* mvh 20001106: Use memcpy instead of ByteCopy */
+/* mvh 20071031: Temp printf allocation errors */
+/* mvh 20071102: Send allocation errors to DicomError */
+/* mvh 20081016: Default buffer size from 1024 to 10240 */
+/* bcb 20100619: Fix gcc4 warnings and improve speed. */
+/* mvh 20100717: Merged */
+/* mvh 20130416: Set DEFAULT_BREAK_SIZE for UNIX to 8192 to fix not understood
+ ubuntu12.04 problem with zeros tranmitted after 1st 64k
+*/
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/************************************************************
+ * Buffer Class
+ *
+ ************************************************************/
+
+
+# include "dicom.hpp"
+
+#ifdef UNIX
+# define DEFAULT_BREAK_SIZE 8192
+#else
+# define DEFAULT_BREAK_SIZE 32600
+#endif
+
+BufferSpace :: BufferSpace(UINT Alloc)
+#ifdef __GNUC__ //Faster with member initialization.
+:BufferSize(0),
+Index(0),
+isTemp(FALSE),
+Data(NULL)
+ {
+//printf("buffer allocating %d bytes\n", Alloc);
+ if ( Alloc )
+ {
+ Data = new BYTE [ Alloc ];
+ if (!Data) DicomError(DCM_ERROR_MEMORY, "Bufferspace: out of memory allocating %d bytes\n", Alloc);
+ BufferSize = Alloc;
+ }
+ }
+#else
+ {
+//printf("buffer allocating %d bytes\n", Alloc);
+ if ( Alloc )
+ {
+ Data = new BYTE [ Alloc ];
+ if (!Data) DicomError(DCM_ERROR_MEMORY, "Bufferspace: out of memory allocating %d bytes\n", Alloc);
+ }
+ else
+ Data = NULL;
+ Index = 0;
+ BufferSize = Alloc;
+ isTemp = FALSE;
+ }
+#endif
+
+BufferSpace :: BufferSpace()
+#ifdef __GNUC__ //Faster with member initialization.
+:BufferSize(0),
+Index(0),
+isTemp(FALSE),
+Data(NULL) {}
+#else
+ {
+ Data = NULL;
+ Index = 0;
+ BufferSize = 0;
+ isTemp = TRUE;
+ }
+#endif
+
+BufferSpace :: ~BufferSpace()
+ {
+ if ( !isTemp )
+ if ( Data )
+ delete Data;
+ }
+
+Buffer :: Buffer()
+#ifdef __GNUC__ //Faster with member initialization.
+:BreakSize(DEFAULT_BREAK_SIZE),
+InEndian(NATIVE_ENDIAN),
+OutEndian(NATIVE_ENDIAN),
+InSize(0),
+OutSize(0),
+Incoming(),
+Outgoing() {}
+#else
+ {
+ BreakSize = DEFAULT_BREAK_SIZE;
+ InEndian = NATIVE_ENDIAN;
+ OutEndian = NATIVE_ENDIAN;
+ InSize = 0;
+ OutSize = 0;
+ }
+#endif
+
+Buffer :: ~Buffer()
+ {
+
+ while ( Incoming.GetSize() )
+ {
+// if ( Incoming[0].Data )
+// delete Incoming[0].Data;
+// Incoming[0].Data = NULL;
+
+ delete Incoming.Get(0);
+ Incoming.RemoveAt( 0 );
+ }
+ while ( Outgoing.GetSize() )
+ {
+// if ( Outgoing[0].Data )
+// delete Outgoing[0].Data;
+// Outgoing[0].Data = NULL;
+
+ delete Outgoing.Get(0);
+ Outgoing.RemoveAt ( 0 );
+ }
+ Incoming.ClearType = 0;
+ Outgoing.ClearType = 0;
+// Incoming.dt.Data = NULL;
+// Outgoing.dt.Data = NULL;
+ InEndian = NATIVE_ENDIAN;
+ }
+
+BOOL Buffer :: SetIncomingEndian(UINT Endian)
+ {
+ InEndian = Endian;
+ return ( TRUE );
+ }
+
+BOOL Buffer :: SetOutgoingEndian(UINT Endian)
+ {
+ OutEndian = Endian;
+ return ( TRUE );
+ }
+
+BOOL Buffer :: SetBreakSize(UINT ToSize)
+ {
+ BreakSize = ToSize;
+ return ( TRUE );
+ }
+
+Buffer & Buffer :: operator >> (BYTE &x)
+ {
+ BYTE s[2];
+
+ Read(s, 1);
+ x = s[0];
+// fprintf(stderr, "%2.2x ", x);
+ return (*this);
+ }
+
+/*************************************************
+ BufferSpace BS;
+
+ if (InSize <= 0)
+ {
+ ReadBlock();
+ }
+ if (InSize <= 0)
+ {
+ x = 0;
+ return ( * this );
+ }
+ BS = Incoming.Get ( 0 );
+ if ( ! BS.Data )
+ {
+ InSize -= BS.Size;
+ Incoming.RemoveAt ( 0 );
+ x = 0;
+ return ( * this );
+ }
+ x = BS.Data[BS.Index];
+ ++BS.Index;
+ --InSize;
+ if(BS.Index == BS.Size)
+ Incoming.RemoveAt ( 0 );
+ else
+ Incoming.Get ( 0 ) = BS;
+ BS.isTemp = TRUE;
+ return ( * this );
+ }
+***************************************************/
+
+Buffer & Buffer :: operator >> (UINT16 &x)
+ {
+ BYTE b1, b2;
+ BYTE *op;
+
+ (*this) >> b1;
+ (*this) >> b2;
+
+ if(InEndian == NATIVE_ENDIAN)
+ {
+ op = (BYTE*) &x;
+ (*op) = b1;++op;
+ (*op) = b2;
+ }
+ else
+ {
+ op = (BYTE*) &x;
+ (*op) = b2;++op;
+ (*op) = b1;
+ }
+
+ return ( * this );
+ }
+/*
+static void Dump(void *vp, int size)
+ {
+ unsigned char *cvp;
+
+ cvp = (unsigned char *) vp;
+ while(size)
+ {
+ fprintf(stderr, "%2.2x ", *cvp);
+ ++cvp;
+ --size;
+ }
+ }
+*/
+
+Buffer & Buffer :: operator >> (UINT32 &x)
+ {
+ UINT16 w1, w2;
+ BYTE *op, *ip;
+
+ (*this) >> w1;
+ (*this) >> w2;
+
+ if(InEndian == NATIVE_ENDIAN)
+ {
+ op = (BYTE *) &x;
+ ip = (BYTE *) &w1;
+ (*op) = (*ip);++op;++ip;
+ (*op) = (*ip);++op;++ip;
+ ip = (BYTE *) &w2;
+ (*op) = (*ip);++op;++ip;
+ (*op) = (*ip);
+ }
+ else
+ {
+ op = (BYTE *) &x;
+ ip = (BYTE *) &w2;
+ (*op) = (*ip);++op;++ip;
+ (*op) = (*ip);++op;++ip;
+ ip = (BYTE *) &w1;
+ (*op) = (*ip);++op;++ip;
+ (*op) = (*ip);
+ }
+
+ return ( * this );
+ }
+
+Buffer & Buffer :: operator << (BYTE &x)
+ {
+ BYTE s[2];
+
+// fprintf(stderr, "Buffer :: << Byte\n");fflush(stderr);
+ s[0] = x;
+ Write(s, 1);
+// fprintf(stderr, "returning\n");fflush(stderr);
+ return (*this);
+ }
+
+/************************************************
+ BufferSpace BS;
+
+ if ( ! Outgoing.GetSize() )
+ {
+ BufferSpace ABS( BreakSize );
+ Outgoing.Add ( ABS );
+ ABS.Data = NULL;
+ }
+ BS = Outgoing.Get ( Outgoing.GetSize() - 1 );
+ if(BS.Index == BS.Size)
+ {
+ BufferSpace ABS( BreakSize );
+ Outgoing.Add ( ABS );
+ ABS.Data = NULL;
+ BS = Outgoing.Get ( Outgoing.GetSize() - 1);
+ }
+ BS.Data[BS.Index] = x;
+ ++BS.Index;
+ Outgoing.Get ( Outgoing.GetSize() - 1 ) = BS;
+ BS.isTemp = TRUE;
+ ++OutSize;
+ return (*this );
+ }
+*************************************************/
+Buffer & Buffer :: operator << (UINT16 &x)
+ {
+ BYTE b1, b2;
+ BYTE *ip;
+
+ ip = (BYTE*)&x;
+ b1 = (*ip);++ip;
+ b2 = (*ip);
+ if(OutEndian == NATIVE_ENDIAN)
+ {
+ (*this) << b1;
+ (*this) << b2;
+ }
+ else
+ {
+ (*this) << b2;
+ (*this) << b1;
+ }
+ return ( * this );
+ }
+
+Buffer & Buffer :: operator << (UINT32 &x)
+ {
+ UINT16 w1, w2;
+ UINT16 *ip;
+
+ ip = (UINT16*)&x;
+ w1 = (*ip);++ip;
+ w2 = (*ip);
+ if(OutEndian == NATIVE_ENDIAN)
+ {
+ (*this) << w1;
+ (*this) << w2;
+ }
+ else
+ {
+ (*this) << w2;
+ (*this) << w1;
+ }
+ return ( * this );
+ }
+
+BOOL Buffer :: Flush()
+ {
+ BufferSpace *BS;
+
+
+ //fprintf(stderr, "Buffer :: Flush() %d buffers\n", Outgoing.GetSize());fflush(stderr);
+ while ( Outgoing.GetSize() )
+ {
+ BS = Outgoing.Get ( 0 );
+ if(BS->Index)
+ SendBinary(BS->Data, BS->Index);
+
+ delete Outgoing.Get(0);
+ Outgoing.RemoveAt ( 0 );
+ }
+ OutSize = 0;
+// fprintf(stderr, "returning TRUE\n");fflush(stderr);
+ return ( TRUE );
+ }
+
+BOOL Buffer :: Flush(UINT Bytes)
+ {
+ BufferSpace *BS;
+
+ //fprintf(stderr, "FLUSH: OutSize=%d, Bytes=%d\n", OutSize,Bytes);
+
+ if(Bytes > OutSize)
+ return(Flush());
+
+
+ OutSize -= Bytes;
+
+ while(Bytes)
+ {
+ if(!Outgoing.GetSize())
+ {
+ //fprintf(stderr, "Attempting to flush more bytes than input, OutSize=%d Bytes=%d\n", OutSize,Bytes);
+ OutSize = 0;
+ return ( FALSE );
+ }
+
+ BS = Outgoing.Get( 0 );
+ if(BS->Index > Bytes)
+ {
+ SendBinary(BS->Data, Bytes);
+ memcpy(BS->Data, &BS->Data[Bytes], BS->Index - Bytes);
+ BS->Index = BS->Index - Bytes;
+ Bytes = 0;
+ return ( TRUE );
+ }
+ else
+ {
+ if(BS->Index)
+ {
+ SendBinary(BS->Data, BS->Index);
+ Bytes -= BS->Index;
+ delete Outgoing.Get(0);
+ Outgoing.RemoveAt ( 0 );
+ }
+ else
+ {
+ delete Outgoing.Get(0);
+ Outgoing.RemoveAt ( 0 );
+ }
+ }
+ }
+
+ return ( TRUE );
+ }
+
+
+BOOL Buffer :: Kill(UINT Bytes)
+ {
+ BOOL Ret;
+ BYTE *Data = new BYTE[Bytes+1];
+ if (!Data) DicomError(DCM_ERROR_MEMORY, "Bufferspace: out of memory allocating %d bytes\n", Bytes+1);
+
+ Ret = Read(Data, Bytes);
+ delete Data;
+ return ( Ret );
+ }
+
+/*
+ BufferSpace *BS;
+ InSize -= Bytes;
+ while ( Incoming.GetSize() )
+ {
+ BS = Incoming.Get ( 0 );
+ if ( (BS->Index + Bytes) > BS->BufferSize)
+ Bytes -= (BS->BufferSize - BS->Index);
+ else
+ {
+ // NOTE, Used to be other way around...
+ BS->Index += Bytes;
+ Bytes = 0;
+ return ( TRUE );
+ }
+ delete Incoming.Get(0);
+ Incoming.RemoveAt ( 0 );
+ }
+
+ return ( FALSE ); // not got that many bytes yet, but go negative
+ }
+*/
+
+BOOL Buffer :: Fill(UINT Bytes)
+ {
+ UINT ECount;
+
+ SetBreakSize(Bytes);
+
+ ECount = InSize + Bytes;
+ while(InSize < ECount)
+ {
+ //fprintf(stderr, "InSize: %d\n", InSize);
+ //printf("Fill %d, %d\n", ECount, Bytes);
+ SetBreakSize(ECount - InSize);
+
+ if(!ReadBlock())
+ return ( FALSE );
+ //fprintf(stderr, "InSize: %d\n", InSize);
+ }
+ SetBreakSize(DEFAULT_BREAK_SIZE);
+ return ( TRUE );
+ }
+
+
+BOOL Buffer :: Read(BYTE *Data, UINT Bytes)
+ {
+ BufferSpace *BS;
+
+ //SetBreakSize(Bytes);
+ while(InSize < Bytes)
+ if(!ReadBlock())
+ return ( FALSE );
+
+ while ( Bytes )
+ {
+ BS = Incoming.Get ( 0 );
+ if(BS->Index == BS->BufferSize)
+ {
+ delete BS;
+ Incoming.RemoveAt( 0 );
+ }
+ else
+ {
+ if((BS->Index + Bytes) <= BS->BufferSize)
+ {
+ memcpy(Data, &BS->Data[BS->Index], Bytes);
+ BS->Index += Bytes;
+ InSize -= Bytes;
+ return ( TRUE );
+ }
+ else
+ {
+ memcpy(Data, &BS->Data[BS->Index], BS->BufferSize - BS->Index);
+ Bytes -= (BS->BufferSize - BS->Index);
+ Data += (BS->BufferSize - BS->Index);
+ InSize -= (BS->BufferSize - BS->Index);
+ delete BS;
+ Incoming.RemoveAt ( 0 );
+ }
+ }
+ }
+
+ return ( FALSE ); // should not get here
+ }
+
+BOOL Buffer :: Write(BYTE *Data, UINT Bytes)
+ {
+ BufferSpace *BS;
+ UINT Count;
+
+
+ if ( !Outgoing.GetSize() )
+ {
+ BufferSpace *ABS = new BufferSpace(BreakSize);
+ Outgoing.Add ( ABS );
+ }
+ while(Bytes)
+ {
+ BS = Outgoing.Get ( Outgoing.GetSize() - 1);
+ Count = BS->BufferSize - BS->Index;
+ if ( Count )
+ {
+ if (Count <= Bytes )
+ {
+ memcpy(&BS->Data[BS->Index], Data, Count);
+ Bytes -= Count;
+ Data += Count;
+ BS->Index += Count;
+
+
+ OutSize += Count;
+ BufferSpace *ABS = new BufferSpace(BreakSize);
+ Outgoing.Add ( ABS );
+
+ }
+ else
+ {
+ memcpy(&BS->Data[BS->Index], Data, Bytes);
+ BS->Index += Bytes;
+ OutSize += Bytes;
+ Bytes = 0;
+ return ( TRUE );
+ }
+ }
+ else
+ {
+ //BufferSpace ABS(BreakSize);
+ BufferSpace *ABS = new BufferSpace(DEFAULT_BREAK_SIZE);
+ Outgoing.Add( ABS );
+
+ }
+ }
+ return ( TRUE );
+ }
+
+BOOL Buffer :: ReadBlock()
+ {
+ int Length, ILength;
+ BYTE s[10240];
+
+ if(BreakSize<10240)
+ ILength = BreakSize;
+ else
+ ILength = 10240;
+
+ //printf("ReadBlock(%d)\n", Length);
+
+ while(!(Length = ReadBinary((BYTE*)s, ILength)))
+ ;
+
+ //fprintf(stderr, "Block Size = %d\n", ABS.Size);
+ if(Length == (-1))
+ {
+ //fprintf(stderr, "Error from ReadBinary()\n");
+ //printf("ReadBinary:-1\n");
+ return (FALSE); // Error from ReadBinary()
+ }
+
+ BufferSpace *ABS = new BufferSpace(Length);
+ //fprintf(stdout, "Length=%d\n", Length);
+ memcpy((void*)ABS->Data, (void*)s, Length);
+
+ InSize += ABS->BufferSize;
+ Incoming.Add(ABS);
+
+ return ( TRUE );
+ }
+
+BOOL Buffer :: Poll()
+ {
+ /*
+ BufferSpace ABS(BreakSize);
+
+ ABS.BufferSize = ReadBinary(ABS.Data, BreakSize);
+ if(!ABS.BufferSize)
+ return ( TRUE ); // no data available
+ if(ABS.BufferSize == (-1))
+ return (FALSE); // Error from ReadBinary()
+ InSize += ABS.BufferSize;
+ Incoming.Add(ABS);
+ ABS.Data = NULL;
+ */
+ return ( TRUE );
+ }
+/*
+class TestBuffer : public Buffer
+ {
+
+ BOOL SendBinary(BYTE *Data, UINT Count)
+ {
+ UINT Index;
+ fprintf(stderr, "Sending: %d Bytes\n", Count);
+ Index = 0;
+ while ( Index < Count )
+ {
+ fprintf(stderr, "%2.2x ", Data[Index]);
+ ++Index;
+ if(!(Index%16))
+ fprintf(stderr, "\n");
+ }
+ fprintf(stderr, "\n");
+ fflush(stderr);
+ return ( TRUE );
+ }
+
+ INT ReadBinary(BYTE *Data, UINT Count)
+ {
+ fgets((char *) Data, Count, stdin);
+ return ( strlen((char*) Data));
+ }
+ };
+
+*/
diff --git a/buffer.thh b/buffer.thh
new file mode 100644
index 0000000..303c214
--- /dev/null
+++ b/buffer.thh
@@ -0,0 +1,107 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+/* 20100309 bcb Changed BufferSize, InSize and OutSize from INT to UINT
+ 20100621 bcb Added no-copy to the BufferSpace classes.
+ 20100707 mvh Merged
+*/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+
+class BufferSpace
+ {
+ public:
+ UINT BufferSize;
+ UINT Index;
+ BOOL isTemp;
+ BYTE *Data;
+
+ BufferSpace(UINT);
+ BufferSpace();
+ ~BufferSpace();
+#ifdef __GNUC__
+ private:// This will prevent it from being copied (it has a pointer)
+ BufferSpace(const BufferSpace&);
+ const BufferSpace & operator = (const BufferSpace&);
+#endif
+ };
+
+class Buffer
+ {
+ protected:
+
+ UINT BreakSize;
+ UINT InEndian;
+ UINT OutEndian;
+ UINT InSize;
+ UINT OutSize;
+ Array<BufferSpace*> Incoming;
+ Array<BufferSpace*> Outgoing;
+
+ public:
+ BOOL ReadBlock();
+ BOOL Poll();
+ public:
+ BOOL SetBreakSize(UINT);
+ BOOL SetIncomingEndian(UINT);
+ BOOL SetOutgoingEndian(UINT);
+ inline UINT GetIncomingEndian() { return ( InEndian ); };
+ inline UINT GetOutgoingEndian() { return ( OutEndian ); };
+ Buffer();
+ virtual ~Buffer();
+ Buffer & operator >> (BYTE &);
+ Buffer & operator >> (UINT16 &);
+ Buffer & operator >> (UINT32 &);
+ inline Buffer & operator >> (char &x)
+ { return ( (*this)>>(BYTE &) x); };
+ inline Buffer & operator >> (INT16 &x)
+ { return ( (*this)>>(UINT16 &) x); };
+ inline Buffer & operator >> (INT32 &x)
+ { return ( (*this)>>(UINT32 &) x); };
+
+ Buffer & operator << (BYTE &);
+ Buffer & operator << (UINT16 &);
+ Buffer & operator << (UINT32 &);
+ inline Buffer & operator << (char &x)
+ { return ( (*this)<<(BYTE &) x); };
+ inline Buffer & operator << (INT16 &x)
+ { return ( (*this)<<(UINT16 &) x); };
+ inline Buffer & operator << (INT32 &x)
+ { return ( (*this)<<(UINT32 &) x); };
+
+ inline UINT GetSize() { return ( InSize ); };
+ BOOL Flush();
+ BOOL Flush(UINT Bytes);
+ BOOL Kill(UINT);
+ BOOL Read(BYTE *, UINT);
+ BOOL Write(BYTE *, UINT);
+ BOOL Fill(UINT);
+ virtual INT ReadBinary(BYTE *, UINT) = 0;
+ virtual BOOL SendBinary(BYTE *, UINT) = 0;
+
+ };
+
diff --git a/cctypes.h b/cctypes.h
new file mode 100644
index 0000000..d0d5ee8
--- /dev/null
+++ b/cctypes.h
@@ -0,0 +1,163 @@
+/*
+???????? mvh Fixed to allow compile with BC
+20010705 ljz Fixed to allow compile with MSVC 6 (see note below)
+20040111 mvh Fix for __GNUC__
+20040117 mvh Fix for linux
+20070308 bcb Added for DARWIN apple endian defs
+20070902 mvh Changed INT32 and UINT32 from long to int for ms7/ms8 compile
+20100706 bcb Made INT32 match libjpeg if HAVE_LIBJPEG.
+20100717 mvh Merged; fixed for WIN32 64 bits
+*/
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/*
+ * Copyright (c) 1995 Regents of the University of California.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms are permitted
+ * provided that this notice is preserved and that due credit is given
+ * to the University of California at Davis. The name of the University
+ * may not be used to endorse or promote products derived from this
+ * software without specific prior written permission. This software
+ * is provided ``as is'' without express or implied warranty.
+ *
+ */
+
+/* CC Types */
+
+
+/*
+ NOTE: MSVC 5 did not have UINT32 defined. Version 6 however defines it
+ in 'BASETSD.H', but wrong!!!!!:
+
+//
+// The following types are guaranteed to be signed and 32 bits wide.
+//
+
+typedef int LONG32, *PLONG32;
+typedef int INT32, *PINT32;
+
+//
+// The following types are guaranteed to be unsigned and 32 bits wide.
+//
+
+typedef unsigned int ULONG32, *PULONG32;
+typedef unsigned int DWORD32, *PDWORD32;
+typedef unsigned int UINT32, *PUINT32;
+
+
+ The int type will in future be 64 bits or more
+*/
+
+
+#ifdef SOLARIS
+# define SYSTEM_V
+#endif
+
+#ifndef WINDOWS
+typedef unsigned int BOOL;
+#endif
+typedef unsigned int UINT;
+typedef unsigned short UINT16;
+#ifndef __BORLANDC__
+#if _MSC_VER != 1200
+#if !defined(__GNUC__) || !defined(WIN32)
+typedef unsigned int UINT32;
+#endif
+#endif
+#endif
+
+typedef unsigned char UINT8;
+#ifndef WINDOWS
+typedef unsigned char BYTE;
+#endif
+
+typedef signed char INT8;
+typedef signed short INT16;
+#ifndef WIN32
+#ifndef __BORLANDC__
+#if _MSC_VER != 1200
+#if !defined(__GNUC__)
+#ifdef HAVE_LIBJPEG
+#ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
+#if UINT_MAX == 0xffffffff
+typedef int INT32; /* Most likely */
+#elif UINT_MAX == 0xffffffffffffffff
+typedef __int32 INT32; /* Some 64 bit systems */
+#else //UINT_MAX == 0xffffffff
+typedef long INT32; /* Default */
+#endif //UINT_MAX == 0xffffffff
+#endif //XMD_H
+#endif //HAVE_LIBJPEG
+#else //!defined(__GNUC__)
+typedef signed int INT32;
+#endif //!defined(__GNUC__)
+#endif //_MSC_VER != 1200
+#endif //__BORLANDC__
+#endif //WIN32
+
+#ifndef WINDOWS
+typedef signed int INT;
+#endif
+
+#ifndef TRUE
+#define TRUE ((UINT) 1)
+#endif
+#ifndef FALSE
+#define FALSE ((UINT) 0)
+#endif
+
+
+#ifdef LITTLE_ENDIAN
+#undef LITTLE_ENDIAN
+#endif
+#ifdef BIG_ENDIAN
+#undef BIG_ENDIAN
+#endif
+
+# define LITTLE_ENDIAN 1
+# define BIG_ENDIAN 2
+// Some Mac OS X universal defines
+// Apple has both big and little endian systems
+#ifndef NATIVE_ENDIAN
+#ifdef DARWIN
+#if __BIG_ENDIAN__
+# define NATIVE_ENDIAN BIG_ENDIAN
+#endif
+#if __LITTLE_ENDIAN__
+# define NATIVE_ENDIAN LITTLE_ENDIAN
+#endif
+#endif
+#endif
+#ifndef NATIVE_ENDIAN
+# define NATIVE_ENDIAN LITTLE_ENDIAN
+#endif
+
diff --git a/conquest-pacs.sh b/conquest-pacs.sh
new file mode 100644
index 0000000..7cbf3b7
--- /dev/null
+++ b/conquest-pacs.sh
@@ -0,0 +1,97 @@
+#!/bin/bash
+#
+# conquest-pacs.sh SysV init script for Conquest PACS.
+#
+# Written by Miquel van Smoorenburg <miquels>.
+# Modified for Debian GNU/Linux by Ian Murdock <imurdock>.
+# Customized for Conquest by Mark Pearson <markp>
+#
+# HOME and PACSUSER should be the only variables that may need to be modified.
+#
+PATH=/sbin:/bin:/usr/sbin:/usr/bin
+
+# Modify HOME to suit your environment.
+HOME=/home/conquest/ConquestDICOM
+# This is the user to run as. Modify it if you don't use username conquest.
+PACSUSER=conquest
+
+DAEMON=$HOME/dgate
+INI=$HOME/dicom.ini
+NAME=conquest_pacs.sh
+
+# All defaults here will be overridden by values from $HOME/dicom.ini
+STATUSLOG=$HOME/serverstatus.log
+PORT=104
+DESC="Conquest PACS Server"
+
+STOPPACS=$HOME"/dgate --quit:"
+STARTAS=$DAEMON
+
+test -f $DAEMON || echo "Cannot find $DAEMON" exit 0
+
+test -f $INI || echo "Cannot find $INI" exit 0
+
+set -e
+
+if grep "TCPPort" $INI > /dev/null ; then
+ PORT=`egrep -i '^*TCPPort *= ' $INI | sed 's/\r//' | awk '{ print $3}'`
+fi
+
+if [ $PORT -le 1024 ]; then
+ test -f /usr/bin/authbind || echo "authbind is needed for access to ports < 1024" exit 0
+ STARTAS="/usr/bin/authbind "
+fi
+
+if grep -is "^ *StatusLog" $INI > /dev/null ; then
+ STATUSLOG=`egrep -i '^*StatusLog' $INI | sed 's/\r//' | awk '{ print $3}'`
+fi
+
+PIDFILE=/var/run/$NAME.$PORT.pid
+if [ $STARTAS = $DAEMON ]; then
+ ARGS=" -^$STATUSLOG"
+else
+ ARGS="$DAEMON -^$STATUSLOG"
+fi
+
+case "$1" in
+ start)
+ if [ -f $HOME/disable_autostart ]; then
+ echo "Not starting $DESC: disabled via $HOME/disable_autostart"
+ exit 0
+ fi
+
+ echo -n "Starting $DESC: "
+ start-stop-daemon --start --quiet --pidfile $PIDFILE \
+ --chuid $PACSUSER --chdir $HOME --exec $DAEMON \
+ --startas $STARTAS --background -- $ARGS
+ echo "$NAME."
+ ;;
+
+ stop)
+ echo -n "Stopping $DESC: "
+ cd $HOME
+ $STOPPACS
+
+ start-stop-daemon --oknodo --stop --quiet --pidfile $PIDFILE \
+ --exec $DAEMON -- $ARGS
+ echo "$NAME."
+ echo
+ ;;
+
+ restart|force-reload)
+ echo -n "Restarting $DESC: "
+ start-stop-daemon --stop --oknodo --quiet --pidfile $PIDFILE \
+ --exec $DAEMON -- $ARGS
+ sleep 1
+ start-stop-daemon --start --quiet --pidfile $PIDFILE \
+ --chuid conquest --chdir $HOME --exec $DAEMON -- $ARGS
+ echo "$NAME."
+ ;;
+ *)
+ N=/etc/init.d/$NAME
+ echo "Usage: $N {start|stop|restart|force-reload}" >&2
+ exit 1
+ ;;
+esac
+
+exit 0
diff --git a/conquest.jpg b/conquest.jpg
new file mode 100644
index 0000000..46bcad6
Binary files /dev/null and b/conquest.jpg differ
diff --git a/constant.h b/constant.h
new file mode 100644
index 0000000..ee4d00a
--- /dev/null
+++ b/constant.h
@@ -0,0 +1,61 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/* DICOM Definations */
+
+# define IsThisaCmdMsg(ccc) (ccc&0x01)
+# define IsThisaDataMsg(ccc) (!(ccc&0x01))
+# define IsThisTheLastFragment(ccc) (ccc&0x02)
+
+# define PDU_ASSOCIATE_RQ 0x01
+# define PDU_ASSOCIATE_AC 0x02
+# define PDU_ASSOCIATE_RJ 0x03
+# define PDU_PDATA 0x04
+# define PDU_RELEASE_RQ 0x05
+# define PDU_RELEASE_RP 0x06
+# define PDU_ABORT_RQ 0x07
+
+# define PDU_APPLICATION_CONTEXT 0x10
+# define PDU_PRESENTATION_CONTEXT 0x20
+# define PDU_PRESENTATION_CONTEXT_ACCEPT 0x21
+# define PDU_ABSTRACT_SYNTAX 0x30
+# define PDU_TRANSFER_SYNTAX 0x40
+# define PDU_USER_INFORMATION 0x50
+
+# define NO_REASON 0x01
+# define APPLICATION_CONTEXT_NAME_BAD 0x02
+# define CALLING_APPICATION_BAD 0x03
+# define CALLED_APPLICATION_BAD 0x07
+# define PROTOCOL_VERSION_BAD 0x02
+# define TO_MUCH_NETWORK_TRAFFIC 0x01
+# define TIME_LIMIT 0x02
+
+# define DICOM_ULS_USER 0x01
+# define DICOM_ULS_PROVIDER_ACSE 0x02
+# define DICOM_ULS_PROVIDER_PRESENTATION 0x03
diff --git a/data/printer_files/accesstest.log b/data/printer_files/accesstest.log
new file mode 100644
index 0000000..e69de29
diff --git a/dbsql.cpp b/dbsql.cpp
new file mode 100644
index 0000000..e364c13
--- /dev/null
+++ b/dbsql.cpp
@@ -0,0 +1,3540 @@
+/*
+19980321 Mvh Changed ObjectFile and DeviceName field length to 250 for dbf compatibility
+19980321 Mvh Added define TRUNCATEFIELDNAMES for DBF compatibity (apply in makefile)
+19980322 Mvh Added run-time check on DbaseIII (should also be added in parse.cpp somehow)
+19980325 Mvh Added TruncateFieldNames entry in dicom.ini to allow DBF compatibility
+19980327 Mvh Made MaxFieldLength configurable
+19980327 Mvh Set default event notification to UDP (for personal pacs)
+19980407 Mvh Added FileCompressMode config
+19980409 Mvh Check vr!=NULL in MakeSafeString,MakeSafeDate
+19990630 MvH Remove also files from MIRROR disks
+19990707 MvH Added UpdateOrAddToTable to refresh database contents without first removing
+19990707 MvH Cache Updates; and AccessTime with ~31 to allow update times to be the same
+19990707 MvH Added fix for Philips PATID; fix cleaning of MIRROR device
+19990708 MvH Added (and disabled) stress code for SQL server
+19990712 MvH Fixed FIX_PHILIPS; atoi failed sometimes because vr->data not zero termimated
+19990827 MvH Added creation of key and link indices
+19991117 ljz Added a check on ini-file value of FileCompressMode
+20000221 ljz Changed layout of this update-history
+ Fix: In 'SetString', type DT_UINT32 was treated as DT_UINT16
+ Added TroubleLogFile and UserLogFile
+ When updating PaientRecord, verify the new Name and BirthDate
+20000629 ljz Logging of trouble now starts with '***'
+20000701 mvh Remove *all* trailing spaces im MakeSafeString before enters database
+20000703 mvh Merged changes: made patient change verification table and record name
+ independent and extended to other databases as well; removed trailing
+ spaces before comparison; show patid on all error messages
+20000705 mvh refuse inconsistent update of link: show error on operatorconsole
+20000707 mvh fixed above addition
+20001104 mvh Replaced _rmdir by equaly valid rmdir
+20001106 mvh Use delete [] operation for vr->Data
+20001128 ljz Fix: protected 'GetFileName' with a critical section.
+20010415 mvh Added KeepImages flag to RemoveFromPacs: clear from DB only
+20010416 mvh Added ChangeUID routine and UIDMODS table - to allow modification of images
+20010418 mvh Changed names of database fields in UIDMODS - did not work on msaccess
+20010429 mvh Renamed genuid routine and variables to allow compile in one big file
+20010713 mvh Reduced devicename to 32 chars to space space
+20010902 mvh Improved UpdateCache to be thread safe and made it longer, no test on image db
+20011109 mvh Made MAG check and database field consistency check case insensitive
+20011115 mvh Replaced 'LIKE' by faster '=' when possible
+20011116 mvh Fixed error handling of db entry. It was possible that db entry
+ failed without any message!
+20011121 mvh Create indices on ImagePat and SeriesPat if these fields exist
+20020403 ljz Do not overrrule the PatientTable with: empty data, or birthdate xxxx0101,
+ or sex other than MmFf.
+20020409 mvh made LastPatid non-static
+20020409 mvh Removed non-thread safe caching of LastADBE
+20020409 mvh Moved entry into UpdateCache to after succesful Update
+20020412 mvh Made NCACHE configurable and changed it from 16 to 1024 (8 MB);
+ Set lastfield (limit of #fields) to 20 (was 16)
+ Added checksum code in update cache to make it faster
+20020412 mvh Made key fields unique. reversed writing of db's. In this case
+ a db write fail will still result in a valid db
+ The db write code is not multi-user safe. A new record
+ may be written at the same time by two processes -> fail
+20020413 mvh Set NCACHE to 256, enough for single thread regen
+ Modified another non-thread safe construct
+20020415 mvh Fix display of PatientID in 'Inconsistent' error message
+20020416 mvh Made UID generator configurable through UIDPrefix in dicom.ini
+ Made all instances of time unsigned
+ Note: accesstime in the db is signed int: problem around 2038
+20020418 mvh+ljz Added TimeStamp, Flags, and Spare fields on all dbs for future use
+20020430 mvh Fix in spare fields: name was reserved in some odbc implementations
+20020515 mvh Process all db fields; enter (1) Modality into StudyModality
+20020517 mvh Modality is merged into StudyModality without size limit (enforced by sql server)
+20020518 mvh Skip missing VR's again; max nr fields to 30; fix reading of NULL fields (clear s[][])
+20020519 mvh Also skip writing empty VR's (vr->Length==0); made FixPhilips configurable (default 1)
+ Remove / from date to allow writing mm/dd/yyyy into sql server
+20020522 ljz Test on empty Modality vr
+20020529 mvh Added PRIMARY KEY to key DB fields (needed for replication)
+20020529 mvh InitializeTables now has mode parameter (0=normal, 1=simple);
+ Do not make Index for primary keys (is done automatically)
+20020609 mvh Added compression modes 3 and 4
+20020802 mvh Simplified rmdir code and allow multiple subdirectories
+20020804 mvh Use PATHSEPCHAR where possible
+20020806 mvh Fix: cleanup entries of refused item in database
+20020819 mvh Added better UID generation
+20021016 mvh Use patid in SaveToDatabase and GetFileName query
+ (both test for rev5 or higher of the database)
+20021017 mvh Allow set of UIDpostfix from extern (-c option of dgate)
+ Removed creation of unused tables
+20021020 mvh Added [ to MakeSafeString; removed "
+ Note: VR's containing ', ? give spurious inconsistency warning when rewritten
+20021028 mvh Also removed dropping of unused tables; reversed table search to image..pat in FindDBE
+ Made inconsistent birtdate a severe error message (added ***)
+20021110 mvh Made date range inclusive (bug reported by Aaron Cann)
+20030113 mvh Added PatientQuerySortOrder etc overrides for sorting
+20030205 mvh Fix potential empty patient ID and SOP problems in GetFilename
+20030321 ljz Extra check on vr!=NULL in SaveToDatabase
+20031104 mvh Added \\ to MakeSafeString
+20040301 ljz Do not double \\ when allready doubled
+20030425 mvh Added DoubleBackSlashToDB control for \\
+20040528 mvh Pass patient ID in RemoveFromPacs and Enable KeyOnAll
+20040529 mvh Implemented faster delete from database
+20040530 mvh Pass a field to query in delete - obligatory for sql server
+20040601 mvh Removed enable KeyOnAll - added some more checks in NewDeleteFromDB
+20040609 mvh Check for DB revision for fast delete from database queries
+20040610 mvh Truncate too long VR's before putting into db; log to pacstrouble
+20040623 ljz Fix for non-DBASE datasources in 'UpdateOrAddToTable':
+20040626 mvh Added study and series UID to getfilename interface
+20040713 mvh Added FixKodak: replaces patid 0NNNNNNN with NNNNNNNN
+20040722 mvh Defaults for FixKodak and FixPhilips to 0 (!)
+20040930 mvh Added multiple UID matching: UID\UID\UID in BuildSearchString (list truncates at maximum length)
+ SetString now returns a char * which is newed (with lots of extra space
+ for MakeSafeString which is done in-place) if Max length is passed 0
+ DICOM2SQLQuery has no max length anymore
+20041003 mvh Trucated printfs of SqlStatement
+20041029 mvh Added MergeUIDs routine
+20041101 mvh Added NewDeleteSopFromDB
+20041220 ljz Fix: in 'RemoveFromPACS', an even PatientID was not zero-terminated !!
+20050109 mvh Adapted for linux compile
+20050111 mvh Added ctype.h (for mingw)
+20050205 mvh Added counters for database activity
+20050206 mvh Allow empty DBE in ConstructVRFromSQL: used to get ObjectFile and Device in query
+20050401 mvh Added WorkListDB and WorkListTableName
+20050404 mvh Dicom types DT_START/ENDSEQUENCE are ignored during table creation/adding to table
+20050414 mvh Allow undefined worklist database;
+ Delete patient will delete worklist entries as well (but needs at least one image)
+20050417 mvh Delete from DB will also delete worklist as patient goes
+20050826 mvh Added mode 2 for initializetables: clear/create worklist only
+20050831 mvh Mode 0 and 1 will now not delete worklist if it contains data
+20050831 mvh VerifyIsInDBE will not return DT_START/ENDSEQUENCE
+20050901 mvh Do not call FixImage in SaveToDataBase: is done in SaveToDisk before
+20051121 mvh Enabled SQLRealSize because SQLResultLength does not work in PostGres BindField
+20051123 mvh Fixed it, and only enable it when #ifdef POSTGRES
+20051204 mvh Disabled it, fixed postgres driver instead
+20051210 mvh GetFilename returns FALSE for an image that has no filename or device set
+20051212 mvh Clear update cache when any records deleted - drastic but safe
+20051216 mvh Small fix in above
+20051217 mvh Use new VR::ReAlloc method to replace data in VR
+20051218 mvh Fix study modality when DoubleBackSlashToDB=1; changed modality search
+20051228 mvh Truncate invalid trailing spaces (>1) from patient ID.
+20051228 mvh Fiximage warns to SystemDebug; Renamed DebugVRs to DebugLevel
+20060210 mvh Removed order: first remove spaces and then fix the patient ID
+ because patient ID consisting of 14 spaces caused huge troubles
+20060220 mvh Check max 50 fields when update; fix Inconsistent check for DoubleBackSlashToDB
+20060607 mvh Fix character translation for entering *?%[' into sql using MakeSafeStringValues
+ Fix consistency check for these characters as well (thanks Robert Chrzan)
+20060607 mvh Added "not null" to "PRIMARY KEY" to satisfy Sybase (thanks Marcin Litoborski)
+20060618 mvh Added not null to UIDmods as well, unified case of DICOMWorkList table name
+ (may be done for other tables as well)(thanks Marcin Litoborski)
+20060618 mvh Remove '' added by MakeSafeStringValues prior to inconsistency check (thanks Robert Chrzan)
+20060621 mvh Increased size of s from [50][255] to [51][256] in UpdateOrAddToTable fixes VirtualQuery crash
+20060628 mvh AddToDatabase has JustAdd parameter: skip one unnecessary query
+20060706 mvh Replaced faulty new vr construct when doing consistency check: faulted on Linux
+20061213 mvh Protect Clear_UpdateCache with critical section
+ Fixed nasty bug in NewDeleteFromDB. MergeUIDs, NewDeleteSopFromDB: Query without bindfield overwrites previous bound strings!
+20070123 mvh Fixed GetFileName for patientid with '
+ Recoded some of the inconsistency checking: now no failure on patient ID (link) with '
+20070131 mvh Fixed GetFileName for all patientid's ;->>>>
+20070201 mvh Fixed (unused) UpdateAccessTimes for weird patient IDs
+20070210 mvh Added CheckDuplicates to UpdateOrAddToTable: used on DicomStudies to catch inconsistent patientID
+ Enabled KeyOnAll on UpdateOrAddToTable: only delete exact records (needed if inconsistent patientID)
+20070308 bcb Changed to set patient ID to 0 for anonymized patients
+20070315 mvh Merged; also noted that changed possible use of AND at start of sql where
+20071027 mvh Also truncate too long date fields with error message; added AllowTruncate: if sql name
+ in comma separated list: warning only else ***error
+20071118 mvh Adapted for 64 bits (use SQLLEN for BindField)
+20080302 mvh Fixed case of DICOM table names
+20080319 mvh Fixed typo in above change; fixed worklist delete for patients with space in ID
+20080817 mvh Added WorkListReturnsISO_IR_100 flag (default 1)
+20080818 mvh DbaseIII check now uses DB flags, not PATHSEP in datasource name
+ Added experimental DT_MSTR: multi-value entry, e.g. query on 'PET' matches 'PET\CT'
+ if studymodality is given type DT_MSTR instead of DT_STR. Note: not implemented for DBASEIII
+20080819 mvh Added warning when querying DT_MSTR field on dbase
+20080902 mvh added EnableComputedFields (default 0)
+20080910 bcb Added create Patient ID for 0 length ID (old Picker CT)
+20080910 bcb Missing patient ID is now not filled with "0" but with PatientName + Date
+20081104 tego+mvh Fixed crash in UpdateOrAddToTable due to missing BindField (1, ...)
+20081120 mvh Strip all trailing spaces of modality prior to merging: some scanners add more than 1
+ Added UseEscapeStringConstants
+20081124 mvh Blocked RemoveFromWorld when 0 images found for safety; default SQLServer to "" = black hole
+20090216 mvh Added ChangeUIDBack and ChangeUIDTo
+20090616 mvh Create index for UIDMods on OldUID; protected UIDMod functions with ChangeUIDCritical
+ Convert ** query field to *; old efilm version seems to create those
+20090616 jf Include file stuff
+20091230 mvh Merged changes by Bruce (bitsltd)
+20091231 bcb Changed char* to const char* and cast time_t to int for gcc4.2 warnings
+20100111 mvh Merged
+20100123 mvh Added DT_FL and DT_FD types, added swapping in ConstructVRFromSQL,
+ and fix DT_UINT32 and DT_UINT16 there, size is 4 and print as %u
+20100123 mvh fixed typo for Linux compile Time -> time
+20100124 mvh fixed typo in ChangeUIDBack
+20100124 mvh Use MyGetPrivateProfileString
+20100309 bcb Added double parentheses (gcc4.2 Warnings)
+20100309 bcb Changed int to unsigned int, commented out unused variables (gcc4.2 Warnings)
+20100324 bcb swap for big endian only.
+20100619 bcb Added #ifndefs (gcc4.0 Warnings) and UNUSED_ARGUMENT
+20100717 mvh Merged; but still use deprecated atof as change would not compile
+20100726 bcb Added cast at atof to supress warning
+20100802 jd Added SUBMISSIONS table
+20100816 bcb Allow dicom.ini and other files to be moved.
+20100816 mvh removed (a) from #ifndef EnterCriticalSection(a) etc
+20100818 mvh Merged jd SUBMISSIONS table
+20100823 mvh Merged and simplified basedir logic
+20101121 mvh Do not make AccessionNumber primary key in worklist
+20101212 mvh Made FixKodak global
+20101227 mvh Added \ prior to _ in query value
+20101229 mvh Modified \_ to [_] etc; presence of [ now also forces LIKE
+20101229 mvh % -> [%]; _ -> [_]; [ -> [[]; ] -> []]
+20110105 mvh Moved local routines to vrtosql: MakeSafeString, DICOM2SQLQuery, BuildSearchString, BuildColumnString
+20110105 mvh Use MakeSafeStringValues for exact match; added DICOM2SQLValue
+20110105 mvh Removed SUBMISSIONS table
+20110106 mvh Fixed regen crash due to missing vr==NULL check in MakeSafeStringValues
+20110111 mvh Extended check for vr in MakeSafeStringValues
+20110115 mvh Added DeleteUIDChanges
+20110214 mvh MakeSafeStringValues 20110111 change broke dbextract; fixed now (return '' if vr invalid or empty)
+20110326 mvh Fixed crash in SetString on findscu --key 0010,0010 --key 0010,0020 127.0.0.1 5678
+20110419 mvh Added sequences to MakeCopy (to fix bug: "save to" did not write sequences)
+20110603 mvh Fully init vr used for MakeSafeString
+20120214 mvh Added WorkListReturnsISO_IR to also allow setting 192
+20130806 mvh Added FixID (default 1), set to 0 to disable any ID fixing,
+ data without patient ID skips write to patient table - experimental
+20130807 mvh Worked on accepting data without patient ID if AllowEmptyPatientID = 1
+20130808 mvh Added substitution of patient ID for database purpose if AllowEmptyPatientID = 1
+20131013 mvh Default TruncateFieldNames set to 10
+*/
+
+#define NCACHE 256
+
+#ifndef UNUSED_ARGUMENT
+#define UNUSED_ARGUMENT(x) (void)x
+#endif
+
+#ifdef WIN32
+#define PATHSEPCHAR '\\'
+#else
+#define PATHSEPCHAR '/'
+#endif
+
+#ifndef WHEDGE
+# include "dgate.hpp"
+#else
+# include "master.h"
+#endif
+
+#ifndef UNIX
+# include <direct.h>
+#else
+#include <unistd.h>
+#include <ctype.h>
+#define stricmp(s1, s2) strcasecmp(s1, s2)
+#ifndef EnterCriticalSection
+# define EnterCriticalSection(a) pthread_mutex_lock(a)
+#endif
+#ifndef LeaveCriticalSection
+# define LeaveCriticalSection(a) pthread_mutex_unlock(a)
+#endif
+#ifndef CRITICAL_SECTION
+# define CRITICAL_SECTION pthread_mutex_t
+#endif
+#ifndef InitializeCriticalSection
+# define InitializeCriticalSection(a) pthread_mutex_init(a, NULL);
+#endif
+#ifndef DeleteCriticalSection
+# define DeleteCriticalSection(a) pthread_mutex_destroy(a);
+#endif
+#endif
+# include <time.h>
+# include <stdlib.h>
+# include <ctype.h>
+
+#include "gpps.hpp"
+#include "dgate.hpp" //DUCKHEAD92
+
+DBENTRY *PatientDB = NULL, *StudyDB = NULL, *SeriesDB = NULL, *ImageDB = NULL, *WorkListDB = NULL;
+DBENTRY *LastADBE = NULL;
+
+UINT DebugVRs = 0;
+UINT Edition = E_WORKGROUP;
+char EditionText[128] = "Workgroup";
+char DataHost[128] = "localhost";
+char DataSource[128] = "LABRAD2";
+char UserName[128] = "Administrator";
+char Password[128] = "password";
+char PatientTableName [64] = "DICOMPatients";
+char StudyTableName [64] = "DICOMStudies";
+char SeriesTableName [64] = "DICOMSeries";
+char ImageTableName [64] = "DICOMImages";
+char WorkListTableName [64] = "DICOMWorkList";
+char DMarkTableName [64] = "DICOMAccessUpdates";
+char RegisteredMOPIDTableName [64] = "RegisteredMOPIDs";
+char UIDToMOPIDTableName [ 64 ] = "UIDToMOPID";
+char UIDToCDRIDTableName [ 64 ] = "UIDToCDRID";
+BYTE Port [ 64 ];
+
+// Later make everything MAX_PATH or similar?
+BYTE KFACTORFILE [ 256 ] = "dicom.sql";
+BYTE MYACRNEMA [ 256 ] = "none";
+char SOPClassFile [ 256 ] = "dgatecls.lst";
+char UserLogFile[256] = "PacsUser.log";
+char TroubleLogFile[256] = "PacsTrouble.log";
+
+#ifndef UNIX
+char OCPipeName[256] = "\\\\.\\pipe\\MicroPACSStatus";
+char ACPipeName[256] = "\\\\.\\pipe\\MicroPACSAccess";
+#else
+char OCPipeName[256] = "/tmp/MicroPACSStatus";
+char ACPipeName[256] = "/tmp/MicroPACSAccess";
+#endif
+char ServerName[256] = "Marks Machine";
+
+int SkippedCachedUpdates=0;
+int UpdateDatabase=0;
+int AddedDatabase=0;
+
+#ifndef DEBUG_MODE
+# define DEBUG_MODE
+#endif
+
+#ifndef RootConfig
+extern char RootConfig[];
+#endif
+#ifndef ConfigFile
+extern char ConfigFile[];
+#endif
+#ifndef BaseDir
+extern char BaseDir[];
+#endif
+
+static int TruncateFieldNames=0;
+static int MaxFieldLength=0;
+static int FixPhilips=0;
+static int AllowEmptyPatientID=0;
+int FixKodak=0;
+int DoubleBackSlashToDB=0;
+int UseEscapeStringConstants=0;
+
+int FileCompressMode=0;
+char PatientQuerySortOrder[256]="";
+char StudyQuerySortOrder[256]="";
+char SeriesQuerySortOrder[256]="";
+char ImageQuerySortOrder[256]="";
+char AllowTruncate[256]="";
+int WorkListReturnsISO_IR_100=0;
+int EnableComputedFields=0;
+
+// Forward declaration
+
+BOOL
+UpdateOrAddToTable(
+ Database &DB,
+ DBENTRY *DCMGateDB,
+ char *TableName,
+ DICOMDataObject *DDOPtr,
+ const char *ObjectFile,
+ const char *DeviceName,
+ char *Patid,
+ char *Modality,
+ BOOL *Added,
+ BOOL JustAdd,
+ BOOL CheckDuplicates);
+
+BOOL MakeSafeStringValues (VR *vr, char *string);
+
+static
+void
+ConfigDBSpecials(void)
+ {
+ char RootSC[64];
+ char Temp[128];
+
+ MyGetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig,
+ (char*) RootSC, 64, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "TruncateFieldNames", "10",
+ (char*) Temp, 128, ConfigFile);
+ TruncateFieldNames = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "MaxFieldLength", "0",
+ (char*) Temp, 128, ConfigFile);
+ MaxFieldLength = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "DoubleBackSlashToDB", "0",
+ (char*) Temp, 128, ConfigFile);
+ DoubleBackSlashToDB = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "UseEscapeStringConstants", "0",
+ (char*) Temp, 128, ConfigFile);
+ UseEscapeStringConstants = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "FixPhilips", "0",
+ (char*) Temp, 128, ConfigFile);
+ FixPhilips = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "AllowEmptyPatientID", "0",
+ (char*) Temp, 128, ConfigFile);
+ AllowEmptyPatientID = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "FixKodak", "0",
+ (char*) Temp, 128, ConfigFile);
+ FixKodak = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "WorkListReturnsISO_IR_100", "-1",
+ (char*) Temp, 128, ConfigFile);
+ if (atoi(Temp)>=0)
+ WorkListReturnsISO_IR_100 = atoi(Temp) * 100;
+ else
+ {
+ MyGetPrivateProfileString ( RootSC, "WorkListReturnsISO_IR", "100",
+ (char*) Temp, 128, ConfigFile);
+ WorkListReturnsISO_IR_100 = atoi(Temp);
+ }
+
+ MyGetPrivateProfileString ( RootSC, "EnableComputedFields", "0",
+ (char*) Temp, 128, ConfigFile);
+ EnableComputedFields = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "FileCompressMode", "0",
+ (char*) Temp, 128, ConfigFile);
+ FileCompressMode = atoi(Temp);
+ if ((FileCompressMode < 0) || (FileCompressMode > 4))
+ FileCompressMode = 0;
+
+ MyGetPrivateProfileString ( RootSC, "PatientQuerySortOrder", "",
+ (char*) PatientQuerySortOrder, 256, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "SeriesQuerySortOrder", "",
+ (char*) SeriesQuerySortOrder, 256, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "StudyQuerySortOrder", "",
+ (char*) StudyQuerySortOrder, 256, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "ImageQuerySortOrder", "",
+ (char*) ImageQuerySortOrder, 256, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "AllowTruncate", "",
+ (char*) AllowTruncate, 256, ConfigFile);
+ strcat(AllowTruncate, ",");
+ }
+
+BOOL
+ConfigDebug (
+ char *ConfigSection,
+ char *lConfigFile,
+ char *Prefix,
+ Debug *Dbg )
+ {
+ char ConfigString[128];
+ char Temp[128];
+ char Temp2[128];
+
+ strcpy(ConfigString, Prefix);
+ strcat(ConfigString, ".TransportType");
+
+ MyGetPrivateProfileString ( ConfigSection, ConfigString,
+ "UDP",
+ (char*) Temp, 64, lConfigFile);
+ if ( ! stricmp ( Temp, "File" ) )
+ {
+ strcpy(ConfigString, Prefix);
+ strcat(ConfigString, ".FileName");
+ MyGetPrivateProfileString ( ConfigSection, ConfigString,
+ "nofile.log",
+ (char*) Temp, 64, lConfigFile);
+ Dbg->On(Temp);
+
+ return ( TRUE );
+ }
+ else
+ if ( ! stricmp ( Temp, "NamedPipe") )
+ {
+ strcpy(ConfigString, Prefix);
+ strcat(ConfigString, ".NamedPipeName");
+ MyGetPrivateProfileString ( ConfigSection, ConfigString,
+ "\\\\.\\pipe\\nopipe",
+ (char*) Temp, 64, lConfigFile);
+ Dbg->OnMsgPipe(Temp);
+
+ return ( TRUE );
+ }
+ else
+ if ( ! stricmp ( Temp, "UDP" ) )
+ {
+ strcpy(ConfigString, Prefix);
+ strcat(ConfigString, ".UDPHost");
+ MyGetPrivateProfileString ( ConfigSection, ConfigString,
+ "localhost",
+ (char*) Temp, 64, lConfigFile);
+ strcpy(ConfigString, Prefix);
+ strcat(ConfigString, ".UDPPort");
+ MyGetPrivateProfileString ( ConfigSection, ConfigString,
+ "1111",
+ (char*) Temp2, 64, lConfigFile);
+ Dbg->OnUDP(Temp, Temp2);
+
+ return ( TRUE );
+ }
+ return ( FALSE );
+ }
+
+/*
+BOOL
+ConfigEventNotification (
+ char *ConfigSection,
+ char *ConfigFile )
+ {
+ ConfigDebug ( ConfigSection, ConfigFile, "MajorEvent", &MajorEvent );
+ ConfigDebug ( ConfigSection, ConfigFile, "MinorEvent", &MinorEvent );
+ return ( TRUE );
+ }
+*/
+
+BOOL ConfigMicroPACS()
+ {
+ char RootSC[64];
+ char Temp[128];
+
+ MyGetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig,
+ (char*) RootSC, 64, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "Edition", "Workgroup",
+ (char*) EditionText, 64, ConfigFile);
+
+ if ( !stricmp(EditionText, "Workgroup"))
+ Edition = E_WORKGROUP;
+ else
+ if ( !stricmp(EditionText, "Personal"))
+ Edition = E_PERSONAL;
+ else
+ if ( !stricmp(EditionText, "Enterprise"))
+ Edition = E_ENTERPRISE;
+ else
+ Edition = E_WORKGROUP;
+
+
+ MyGetPrivateProfileString ( RootSC, "TCPPort", "104",
+ (char*) Port, 64, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "DebugLevel", "0",
+ (char*) Temp, 64, ConfigFile);DebugVRs = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "MyACRNema", "none",
+ (char*) MYACRNEMA, 64, ConfigFile);
+
+ // Get config file location; using basedir if required
+
+ MyGetPrivateProfileString ( RootSC, "kFactorFile", "dicom.sql",
+ Temp, 256, ConfigFile);
+ if (strrchr(Temp, PATHSEPCHAR))
+ strcpy ((char*) KFACTORFILE, Temp);
+ else
+ {
+ strncpy ((char*) KFACTORFILE, BaseDir, 256 - strlen(Temp));
+ KFACTORFILE[256 - strlen(Temp)] = 0;
+ strcat((char*) KFACTORFILE, Temp);
+ }
+
+ MyGetPrivateProfileString ( RootSC, "ACRNemaMap", "acrnema.map",
+ Temp, 256, ConfigFile);
+ if (strrchr(Temp, PATHSEPCHAR))
+ strcpy ((char*) ACRNEMAMAP, Temp);
+ else
+ {
+ strncpy ((char*) ACRNEMAMAP, BaseDir, 256 - strlen(Temp));
+ ACRNEMAMAP[256 - strlen(Temp)] = 0;
+ strcat((char*) ACRNEMAMAP, Temp);
+ }
+
+ MyGetPrivateProfileString ( RootSC, "SOPClassList", "dgatesop.lst",
+ Temp, 256, ConfigFile);
+ if (strrchr(Temp, PATHSEPCHAR))
+ strcpy ((char*) SOPClassFile, Temp);
+ else
+ {
+ strncpy ((char*) SOPClassFile, BaseDir, 256 - strlen(Temp));
+ SOPClassFile[256 - strlen(Temp)] = 0;
+ strcat((char*) SOPClassFile, Temp);
+ }
+
+ // get log file locations
+
+ MyGetPrivateProfileString ( RootSC, "UserLog", "PacsUser.log",
+ (char*) Temp, 256, ConfigFile);
+ if (strrchr(Temp, PATHSEPCHAR))
+ strcpy ((char*) UserLogFile, Temp);
+ else
+ {
+ strncpy ((char*) UserLogFile, BaseDir, 256 - strlen(Temp));
+ UserLogFile[256 - strlen(Temp)] = 0;
+ strcat((char*) UserLogFile, Temp);
+ }
+
+ MyGetPrivateProfileString ( RootSC, "TroubleLog", "PacsTrouble.log",
+ (char*) Temp, 256, ConfigFile);
+ if (strrchr(Temp, PATHSEPCHAR))
+ strcpy ((char*) TroubleLogFile, Temp);
+ else
+ {
+ strncpy ((char*) TroubleLogFile, BaseDir, 256 - strlen(Temp));
+ TroubleLogFile[256 - strlen(Temp)] = 0;
+ strcat((char*) TroubleLogFile, Temp);
+ }
+
+ // SQL server network hostname
+
+ MyGetPrivateProfileString ( RootSC, "SQLHost", "localhost",
+ (char*) DataHost, 128, ConfigFile);
+ if(strlen(DataHost) == 0)
+ strcpy(DataHost, "localhost");
+
+ MyGetPrivateProfileString ( RootSC, "SQLServer", "",
+ (char*) DataSource, 128, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "Username", "Administrator",
+ (char*) UserName, 128, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "Password", "password",
+ (char*) Password, 128, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "PatientTableName", "DICOMPatients",
+ (char*) PatientTableName, 64, ConfigFile);
+ MyGetPrivateProfileString ( RootSC, "WorkListTableName", "DICOMWorkList",
+ (char*) WorkListTableName, 64, ConfigFile);
+ MyGetPrivateProfileString ( RootSC, "StudyTableName", "DICOMStudies",
+ (char*) StudyTableName, 64, ConfigFile);
+ MyGetPrivateProfileString ( RootSC, "SeriesTableName", "DICOMSeries",
+ (char*) SeriesTableName, 64, ConfigFile);
+ MyGetPrivateProfileString ( RootSC, "ImageTableName", "DICOMImages",
+ (char*) ImageTableName, 64, ConfigFile);
+ MyGetPrivateProfileString ( RootSC, "DMarkTableName", "DICOMAccessUpdates",
+ (char*) DMarkTableName, 64, ConfigFile);
+ MyGetPrivateProfileString ( RootSC, "RegisteredMOPIDTableName", "RegisteredMOPIDs",
+ (char*) RegisteredMOPIDTableName, 64, ConfigFile);
+ MyGetPrivateProfileString ( RootSC, "UIDToMOPIDTableName", "UIDToMOPID",
+ (char*) UIDToMOPIDTableName, 64, ConfigFile);
+ MyGetPrivateProfileString ( RootSC, "UIDToCDRIDTableName", "UIDToCDRID",
+ (char*) UIDToCDRIDTableName, 64, ConfigFile);
+ MyGetPrivateProfileString ( RootSC, "OperatorConsole",
+ "\\\\.\\pipe\\MicroPACSStatus", (char*)OCPipeName, 128, ConfigFile);
+ MyGetPrivateProfileString ( RootSC, "AccessUpdates",
+ "\\\\.\\pipe\\MicroPACSAccess", (char*)ACPipeName, 128, ConfigFile);
+ MyGetPrivateProfileString ( RootSC, "PACSName", "MicroPACS",
+ (char*) ServerName, 128, ConfigFile);
+
+// ConfigEventNotification ( RootSC, ConfigFile );
+
+ ConfigDBSpecials();
+
+ InitializeDeviceTable (RootSC);
+ return ( TRUE );
+ }
+
+BOOL DICOM2SQLValue (
+ char *s )
+ {
+ VR vr;
+ char *s1;
+
+ if(*s)
+ {
+ vr.Data = (void*)s;
+ vr.Length = strlen(s);
+ vr.Group = 0;
+ vr.Element = 0;
+ s1 = (char *)malloc(vr.Length*2 + 3);
+ MakeSafeStringValues(&vr, s1);
+ strcpy(s, s1);
+ free(s1);
+ vr.Data = NULL;
+ vr.Length = 0;
+ }
+
+ return ( TRUE );
+ }
+
+DWORD
+CurrentTime()
+ {
+ return((DWORD)time(NULL) & (~31));
+ }
+
+const char *
+UniqueKey(
+ DBENTRY *DBE)
+ {
+ if(!DBE)
+ return ("null");
+ return ( DBE[0].SQLColumn );
+ }
+
+
+const char *
+UniqueLink(
+ DBENTRY *DBE)
+ {
+ if(!DBE)
+ return( "null");
+
+ return( DBE[LastDBE(DBE)].SQLColumn );
+ }
+
+BOOL
+AddStudyInstanceUID (DICOMDataObject *DDOPtr)
+ {
+ VR *vr;
+
+ // Search for the UID elsewere
+
+ vr = DDOPtr->GetVR(0x0021, 0x1070);
+ if(vr)
+ {
+ VR *vrNew = new VR(0x0020, 0x000d, vr->Length, TRUE);
+ memcpy(vrNew->Data, vr->Data, vr->Length);
+ DDOPtr->Push(vrNew);
+ return ( TRUE );
+ }
+ // not sure what to do.
+ VR *vrNew = new VR(0x0020, 0x000d, 10, TRUE);
+ strcpy((char*)vrNew->Data, "undefined");
+ DDOPtr->Push(vrNew);
+ return ( TRUE );
+ }
+
+BOOL
+AddSeriesInstanceUID (DICOMDataObject *DDOPtr)
+ {
+ VR *vr;
+
+ // Search for the UID elsewere
+
+ vr = DDOPtr->GetVR(0x0021, 0x1071);
+ if(vr)
+ {
+ VR *vrNew = new VR(0x0020, 0x000e, vr->Length, TRUE);
+ memcpy(vrNew->Data, vr->Data, vr->Length);
+ DDOPtr->Push(vrNew);
+ return ( TRUE );
+ }
+ // not sure what to do.
+ VR *vrNew = new VR(0x0020, 0x000e, 10, TRUE);
+ strcpy((char*)vrNew->Data, "undefined");
+ DDOPtr->Push(vrNew);
+ return ( TRUE );
+ }
+
+
+// Fix possible problems in an image.
+BOOL
+FixImage(DICOMDataObject *DDOPtr)
+ {
+ // This routine fixes some deficient images (sent from outdated
+ // modalities).
+
+ VR *vr;
+ int i, count;
+
+ if (AllowEmptyPatientID) return TRUE;
+
+ vr = DDOPtr->GetVR(0x0010, 0x0010);
+ if(!vr)
+ {
+ vr = new VR(0x0010, 0x0010, 8, (BOOL)TRUE);
+ memcpy(vr->Data, (void*)"NO NAME", 8);
+ DDOPtr->Push(vr);
+ SystemDebug.printf("Fiximage: Added patient name\n");
+ }
+
+ // truncate invalid trailing spaces (more than one) from patient ID
+
+ vr = DDOPtr->GetVR(0x0010, 0x0020);
+ if(vr)
+ {
+ count=0;
+ for (i=vr->Length-1; i>=0; i--)
+ if (((char*)(vr->Data))[i]==' ') count++; else break;
+ if (count > 0)
+ {
+ vr->Length -= count;
+ if (vr->Length&1) vr->Length++, count--;
+ if (count) SystemDebug.printf("Fiximage: truncated %d trailing spaces from patient ID\n", count);
+ }
+ }
+
+ if(!vr)
+ {
+ vr = new VR(0x0010, 0x0020, 8, (BOOL)TRUE);
+ memcpy(vr->Data, (void*)"00000000", 8);
+ DDOPtr->Push(vr);
+ SystemDebug.printf("Fiximage: Added patient ID\n");
+ }
+
+ else if (vr->Length < 2)
+ {
+ int Length;
+ char *s;
+
+ s = (char*)vr->Data;
+ Length = vr->Length;
+
+ while ( Length )
+ {
+ if (s[Length] == ' ')
+ {
+ --Length;
+ continue;
+ }
+ if (s[Length] == '\0')
+ {
+ --Length;
+ continue;
+ }
+ break;
+ }
+ vr->Length = Length;
+
+ if ( vr->Length < 2)
+ {
+ vr->ReAlloc(8);
+ memcpy(vr->Data, (void*)"00000000", 8);
+ }
+ SystemDebug.printf("Fiximage: Fixed empty patient ID\n");
+ }
+
+ else if (vr->Length==10 && vr->Data && FixPhilips)
+ {
+ char patid[11];
+ int Length;
+
+ memcpy(patid, (char *)(vr->Data), 10);
+ patid[10]=0;
+
+ if ( patid[0] == '0' && patid[1] == '0' && atoi(patid)>1000000 )
+ {
+ memset(patid, 0, 10);
+ if (((char *)(vr->Data))[2]=='0') memcpy(patid, ((char *)(vr->Data)) + 3, Length=7);
+ else if (((char *)(vr->Data))[1]=='0') memcpy(patid, ((char *)(vr->Data)) + 2, Length=8);
+ else if (((char *)(vr->Data))[0]=='0') memcpy(patid, ((char *)(vr->Data)) + 1, Length=9);
+ else memcpy(patid, (char *)(vr->Data) + 0, Length=10);
+ if (Length&1) Length++;
+
+ vr->ReAlloc(Length);
+ memcpy(vr->Data, patid, Length);
+
+ SystemDebug.printf("Fiximage: Fixed Philips patient ID\n");
+ }
+ }
+
+ else if (vr->Length==8 && vr->Data && FixKodak)
+ {
+ char patid[11];
+ int Length;
+
+ memcpy(patid, (char *)(vr->Data), 8);
+ patid[8]=0;
+
+ if ( patid[0] == '0' && atoi(patid)>1000000 )
+ {
+ memset(patid, 0, 10);
+ if (((char *)(vr->Data))[0]=='0') memcpy(patid, ((char *)(vr->Data)) + 1, Length=7);
+ else memcpy(patid, (char *)(vr->Data) + 0, Length=8);
+ if (Length&1) Length++;
+
+ vr->ReAlloc(Length);
+ memcpy(vr->Data, patid, Length);
+
+ SystemDebug.printf("Fiximage: Fixed Kodak patient ID\n");
+ }
+ }
+
+ vr = DDOPtr->GetVR(0x0020, 0x000d);
+ if(!vr)
+ AddStudyInstanceUID ( DDOPtr );
+ vr = DDOPtr->GetVR(0x0020, 0x000e);
+ if(!vr)
+ AddSeriesInstanceUID ( DDOPtr );
+
+ return ( TRUE );
+ }
+
+/////////////////////////////////////////////////////////////////
+/* This code forms a cache that saves the last NCACHE entries */
+/* If the entry already exists, db writing can be skipped */
+/////////////////////////////////////////////////////////////////
+
+char UpdateCache[NCACHE][8192];
+int UpdateCheckSums[NCACHE];
+CRITICAL_SECTION UpdateCritical;
+int UpdateTop=0, UpdateBottom=0;
+
+int into_UpdateCache(char *in)
+ {
+ int i, sum, r;
+ char *p = in;
+
+ sum = 0;
+ while(*p) sum+=*p++;
+
+ if (UpdateTop==0 && UpdateBottom==0)
+ InitializeCriticalSection(&UpdateCritical);
+
+ EnterCriticalSection(&UpdateCritical);
+
+ /* clear cache if it is empty */
+ if (UpdateTop==0 && UpdateBottom==0)
+ for (i=0; i<NCACHE; i++)
+ UpdateCache[i][0]=0;
+
+ if ((UpdateTop+1)%NCACHE == UpdateBottom)
+ UpdateBottom = (UpdateBottom+1)%NCACHE; // delete oldest entry
+
+ strcpy(UpdateCache[UpdateTop], in);
+ UpdateCheckSums[UpdateTop] = sum;
+ r = UpdateTop;
+
+ UpdateTop = (UpdateTop+1)%NCACHE;
+
+ LeaveCriticalSection(&UpdateCritical);
+
+ return r;
+ }
+
+int isin_UpdateCache(char *in)
+ {
+ int i, sum;
+ char *p = in;
+
+ if (UpdateTop==0 && UpdateBottom==0) return 0;
+
+ sum = 0;
+ while(*p) sum+=*p++;
+
+ EnterCriticalSection(&UpdateCritical);
+
+ for (i=UpdateTop; i!=UpdateBottom; i=(i==0 ? NCACHE-1 : i-1))
+ {
+ if (UpdateCheckSums[i] == sum)
+ if (strcmp(UpdateCache[i], in)==0)
+ {
+ LeaveCriticalSection(&UpdateCritical);
+ return 1;
+ }
+ }
+
+ LeaveCriticalSection(&UpdateCritical);
+ return 0;
+ }
+
+// clear entire cache
+void clear_UpdateCache(void)
+ {
+ if (UpdateTop==0 && UpdateBottom==0) return;
+
+ EnterCriticalSection(&UpdateCritical);
+ for (int i=0; i<NCACHE; i++)
+ {
+ UpdateCache[i][0]=0;
+ UpdateCheckSums[i] = -1;
+ }
+ LeaveCriticalSection(&UpdateCritical);
+ }
+
+BOOL
+SaveToDataBase(
+ Database &DB,
+ DICOMDataObject *DDOPtr,
+ char *filename,
+ const char *device,
+ BOOL JustAdd)
+ {
+ char LastPatid[65], Modality[17];
+ char s1[128];
+ BOOL AddedImage, AddedStudy, AddedSeries, AddedPatient;
+ int PIDcnt, len;
+
+ VR *vr, *vr1;
+
+ memset(LastPatid, 0, 65);
+ vr = DDOPtr->GetVR(0x0010, 0x0020);
+
+ //Note: Some Anonymized patients have no Patient ID.
+ //The DICOMPatients table requires an ID.
+ if(!vr)
+ {
+ vr = new VR;
+ vr->Group = 0x0010;
+ vr->Element = 0x0020;
+ vr->Length = 0;
+ DDOPtr->Push(vr);
+ }
+
+ //Some patients can have a zero length ( Picker CT ) Patient ID, create an ID.
+ if(vr->Length == 0 && !AllowEmptyPatientID)
+ {
+ PIDcnt = 0;
+ vr1 = DDOPtr->GetVR(0x0010, 0x0010);//Patient name
+ if(vr1)
+ {
+ if(vr1->Length != 0)
+ {
+ memcpy(LastPatid, vr1->Data, vr1->Length);
+ PIDcnt = vr1->Length;
+ }
+ }
+ vr1 = DDOPtr->GetVR(0x0008, 0x0012);//Date
+ if(vr1)
+ {
+ if(vr1->Length != 0)
+ {
+ if(( PIDcnt + vr1->Length) > 62)
+ {
+ memcpy(&LastPatid[PIDcnt], vr1->Data, 62 - PIDcnt);// Get all the space left
+ PIDcnt = 62;
+ LastPatid[63] = 0;
+ }
+ else
+ {
+ memcpy(&LastPatid[PIDcnt], vr1->Data, vr1->Length);//Room for all
+ PIDcnt += vr1->Length;
+ }
+ }
+ }
+ if(PIDcnt < 2)// No patient name or date, set ID to 0.
+ {
+ PIDcnt = 2;
+ *LastPatid = 0x30;//"0"
+ }
+ PIDcnt = PIDcnt / 2;// Make it even. (should be, but better safe)
+ PIDcnt = PIDcnt * 2;
+ vr->Length = PIDcnt;
+ vr->ReAlloc(vr->Length);
+ if ( !vr->Data ) return ( FALSE ); // memory error
+ memcpy(vr->Data, LastPatid, vr->Length);
+ }
+ else memcpy(LastPatid, vr->Data, vr->Length);// Have a patient ID
+ if (vr && vr->Length)
+ if (LastPatid[vr->Length-1]==' ') LastPatid[vr->Length-1]=0;
+
+ memset(Modality, 0, 17);
+ vr = DDOPtr->GetVR(0x0008, 0x0060);
+ if(vr)
+ {
+ len = vr->Length;
+ memcpy(Modality, vr->Data, len);
+ while (len>0)
+ if (Modality[len-1]==' ')
+ {
+ Modality[len-1] = 0;
+ len--;
+ }
+ else
+ break;
+ }
+ // Modality[2] = 0; // option to truncate all RT item to save StudyModality space
+
+ // FixImage(DDOPtr);
+
+ VR *SOPInstance = DDOPtr->GetVR(0x0008, 0x0018);
+ MakeSafeStringValues(SOPInstance, s1); // mvh 20110105
+ AccessUpdate.printf("%s", s1);
+
+
+// RemoveDuplicates(DB, PatientDB, PatientTableName, DDOPtr, FALSE);
+// AddToTable(DB, PatientDB, PatientTableName, DDOPtr, NULL, NULL);
+// RemoveDuplicates(DB, StudyDB, StudyTableName, DDOPtr, FALSE);
+// AddToTable(DB, StudyDB, StudyTableName, DDOPtr, NULL, NULL);
+// RemoveDuplicates(DB, SeriesDB, SeriesTableName, DDOPtr, FALSE);
+// AddToTable(DB, SeriesDB, SeriesTableName, DDOPtr, NULL, NULL);
+// RemoveDuplicates(DB, ImageDB, ImageTableName, DDOPtr, FALSE);
+// AddToTable(DB, ImageDB, ImageTableName, DDOPtr, filename, device);
+
+ if (LastPatid[0]==0 && AllowEmptyPatientID)
+ { VR *suid = DDOPtr->GetVR(0x0020, 0x000d);
+ SQLLEN sdword;
+ strcpy(s1, "StudyInsta = ");
+ MakeSafeStringValues(suid, s1 + strlen(s1));
+
+ if (DB.Query(StudyTableName, "PatientID", s1, NULL))
+ { DB.BindField (1, SQL_C_CHAR, s1, 128, &sdword);
+ if (DB.NextRecord())
+ { strcpy(LastPatid, s1);
+ if (LastPatid[0])
+ OperatorConsole.printf("Empty patient ID in object, but database will use: %s\n", LastPatid);
+ }
+ }
+ }
+
+ if (!UpdateOrAddToTable(DB, ImageDB, ImageTableName, DDOPtr, filename, device, LastPatid, NULL, &AddedImage, JustAdd, FALSE))
+ return FALSE;
+
+ if (!UpdateOrAddToTable(DB, SeriesDB, SeriesTableName, DDOPtr, filename, NULL, LastPatid, NULL, &AddedSeries, FALSE, FALSE))
+ {
+ if (AddedImage) RemoveDuplicates(DB, ImageDB, ImageTableName, DDOPtr, TRUE);
+ return FALSE;
+ }
+
+ // check for conflicting patid -------V */
+ if (!UpdateOrAddToTable(DB, StudyDB, StudyTableName, DDOPtr, filename, NULL, LastPatid, Modality, &AddedStudy, FALSE, TRUE))
+ {
+ if (AddedSeries) RemoveDuplicates(DB, SeriesDB, SeriesTableName, DDOPtr, TRUE);
+ if (AddedImage) RemoveDuplicates(DB, ImageDB, ImageTableName, DDOPtr, TRUE);
+ return FALSE;
+ }
+
+ if (LastPatid[0] || !AllowEmptyPatientID)
+ if (!UpdateOrAddToTable(DB, PatientDB, PatientTableName, DDOPtr, filename, NULL, LastPatid, NULL, &AddedPatient, FALSE, FALSE))
+ {
+ if (AddedStudy) RemoveDuplicates(DB, StudyDB, StudyTableName, DDOPtr, TRUE);
+ if (AddedSeries) RemoveDuplicates(DB, SeriesDB, SeriesTableName, DDOPtr, TRUE);
+ if (AddedImage) RemoveDuplicates(DB, ImageDB, ImageTableName, DDOPtr, TRUE);
+ return FALSE;
+ }
+
+ return ( TRUE );
+ }
+
+#if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian like Apple power pc
+static void swap(BYTE *src, BYTE *dst, int N)
+{ for (int i=0; i<N; i++)
+ dst[i] = src[N-i-1];
+}
+
+static void swap(BYTE *buffer, int N)
+{ BYTE buf[256];
+ if (N>=256) return;
+ memcpy(buf, buffer, N);
+ swap(buf, buffer, N);
+}
+#endif
+
+char *
+SetString(VR *vr, char *s, int Max)
+ {
+ int Index;
+ UINT16 *tuint16;
+ UINT32 *tuint32;
+ DBENTRY *DBE;
+
+ // when Max = 0 passed: alloc automatically at right size; pointer returned
+
+ if (Max==0)
+ {
+ if (vr) Max = 3 * vr->Length + 20; else Max = 255; // mvh 20110105 must allow MakeSafeString in-place (!) ?E'[_]' ESCAPE '\'
+ if (Max < 255) Max = 255;
+ s = new char[Max];
+ }
+
+ memset((void*)s, 0, Max);
+
+ if(vr)
+ if(vr->Data)
+ {
+ if (Max > vr->Length) Max = vr->Length; // mvh 20110105 - move inside if 20110326
+
+ DBE = FindDBE(vr);
+ if(!DBE)
+ {
+ memcpy((void*)s, vr->Data, Max); // mvh 20110105
+ return ( s );
+ }
+ switch(DBE->DICOMType)
+ {
+ case DT_UI:
+ case DT_STR:
+ case DT_MSTR:
+ case DT_DATE:
+ memcpy((void*)s, vr->Data, Max); // mvh 20110105
+ Index = strlen(s);
+ if(Index)
+ {
+ if(s[Index-1]==' ')
+ {
+ s[Index-1]='\0';
+ }
+ }
+ return ( s );
+ case DT_UINT16:
+ tuint16 = (UINT16*)vr->Data;
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ sprintf(s, "%u", (*tuint16));
+#else //Big Endian like Apple power pc
+ sprintf(s, "%u", SwitchEndian(*tuint16));
+#endif
+ return ( s );
+ case DT_UINT32:
+ tuint32 = (UINT32*)vr->Data;
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ sprintf(s, "%u", (*tuint32));
+#else //Big Endian like Apple power pc
+ sprintf(s, "%u", SwitchEndian(*tuint32));
+#endif
+ return ( s );
+ case DT_FL:
+ {
+ float f;
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ f = *(float*)vr->Data;
+#else //Big Endian like Apple power pc
+ swap((BYTE *)&f, (BYTE *)vr->Data, 4);
+#endif
+ sprintf(s, "%.16g", f);
+ return ( s );
+ }
+ case DT_FD:
+ {
+ double d;
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ d = *(double*)vr->Data;
+#else //Big Endian like Apple power pc
+ swap((BYTE *)&d, (BYTE *)vr->Data, 8);
+#endif
+ sprintf(s, "%.16g", d);
+ return ( s );
+ }
+ default:
+ memcpy((void*)s, vr->Data, Max); // mvh 20110105
+ return ( s );
+ }
+ }
+ return ( s );
+ }
+
+
+BOOL
+AddToTable(
+ Database &DB,
+ DBENTRY *DCMGateDB,
+ char *TableName,
+ DICOMDataObject *DDOPtr,
+ char *ObjectFile,
+ char *DeviceName)
+ {
+ UINT Index, CIndex;
+ Array < VR * > VRArray;
+ VR *vr;
+ VR FakeVR;
+ char Columns [ 4096 ];
+ char Values [ 4096 ];
+ char TempString [ 512 ];
+
+
+ Index = 0;CIndex = 0;
+ Columns [ 0 ] = '\0';
+ while ( TRUE )
+ {
+ if( ! DCMGateDB[Index] . Element )
+ break;
+ if (DCMGateDB[Index].DICOMType==DT_STARTSEQUENCE || DCMGateDB[Index].DICOMType==DT_ENDSEQUENCE)
+ vr = NULL;
+ else
+ vr = DDOPtr->GetVR( DCMGateDB [ Index ] . Group,
+ DCMGateDB [ Index ] . Element );
+ LastADBE = &DCMGateDB[Index];
+ VRArray.Add(vr);
+ if(vr)
+ {
+ if(CIndex)
+ strcat(Columns, ", ");
+ strcat(Columns, DCMGateDB [ Index ] . SQLColumn);
+ ++CIndex;
+ }
+ ++Index;
+ }
+ strcat( Columns, ", AccessTime" );
+ if(ObjectFile)
+ strcat ( Columns, ", ObjectFile" );
+ if(DeviceName)
+ strcat ( Columns, ", DeviceName" );
+
+ Index = 0;CIndex = 0;
+ Values [ 0 ] = '\0';
+
+ while ( Index < VRArray.GetSize() )
+ {
+ if ( (vr = VRArray.Get ( Index ) ) )
+ {
+ if(CIndex)
+ strcat ( Values, ", ");
+ LastADBE = &DCMGateDB[Index];
+ switch(DCMGateDB[Index].SQLType)
+ {
+ case SQL_C_CHAR:
+ MakeSafeStringValues ( vr, TempString );
+ break;
+ case SQL_C_DATE:
+ MakeSafeDate ( vr, TempString );
+ break;
+ default:
+ SystemDebug.printf("Unknown SQL Type: %d\n",
+ DCMGateDB[Index].SQLType);
+ }
+ strcat ( Values, TempString );
+ ++CIndex;
+ }
+ ++Index;
+ }
+ sprintf(TempString, ", %u", (unsigned int)CurrentTime() );
+ strcat(Values, TempString );
+ if(ObjectFile)
+ {
+ LastADBE = NULL;
+ strcat(Values, ", ");
+ FakeVR.Data = (void*)ObjectFile;
+ FakeVR.Length = strlen(ObjectFile);
+ FakeVR.Group = 0;
+ FakeVR.Element = 0;
+ MakeSafeStringValues ( &FakeVR, TempString );
+ FakeVR.Data = NULL;
+ FakeVR.Length = 0;
+ strcat ( Values, TempString );
+ }
+ if(DeviceName)
+ {
+ LastADBE = NULL;
+ strcat(Values, ", ");
+ FakeVR.Data = (void*)DeviceName;
+ FakeVR.Length = strlen(DeviceName);
+ FakeVR.Group = 0;
+ FakeVR.Element = 0;
+ MakeSafeStringValues ( &FakeVR, TempString );
+ FakeVR.Data = NULL;
+ FakeVR.Length = 0;
+ strcat ( Values, TempString );
+ }
+
+ if(!DB.AddRecord(TableName, Columns, Values))
+ {
+ SystemDebug.printf ( "***Unable to DB.Add()\n");
+ SystemDebug.printf ( "***SQL: %.1000s\n", DB.SQLStatement);
+ DB.PrintLastError();
+ return ( FALSE );
+ }
+ return ( TRUE );
+ }
+
+BOOL
+UpdateOrAddToTable(
+ Database &DB,
+ DBENTRY *DCMGateDB,
+ char *TableName,
+ DICOMDataObject *DDOPtr,
+ const char *ObjectFile,
+ const char *DeviceName,
+ char *Patid,
+ char *Modality,
+ BOOL *Added,
+ BOOL JustAdd,
+ BOOL CheckDuplicates)
+ {
+ UINT Index, CIndex;
+ Array < VR * > VRArray;
+ VR *vr;
+ VR FakeVR;
+ char Columns [ 4096 ];
+ char Values [ 4096 ];
+ char Updates [ 8192 ];
+ char Where [512];
+ char TempString [ 512 ];
+ SQLLEN sdword;
+ char *pTmp;
+ char *pTmp2;
+ unsigned int i, len, lastfield=50;//, r;
+ char s[51][256];
+ int pm1=0, pm2=0, im=0, flag, j;
+ char Temp2[256], Temp3[256], dummy[256];
+ BOOL SetPatientIDStudy = false;
+
+ *Added = FALSE;
+
+ if (LastDBE(DCMGateDB) < lastfield) lastfield = LastDBE(DCMGateDB);
+
+ Index = 0; CIndex = 0;
+ Columns [ 0 ] = '\0';
+
+ while ( TRUE )
+ {
+ if( ! DCMGateDB[Index] . Element )
+ break;
+ if (DCMGateDB[Index].DICOMType==DT_STARTSEQUENCE || DCMGateDB[Index].DICOMType==DT_ENDSEQUENCE)
+ vr = NULL;
+ else
+ vr = DDOPtr->GetVR( DCMGateDB [ Index ] . Group,
+ DCMGateDB [ Index ] . Element );
+ LastADBE = &DCMGateDB[Index];
+ VRArray.Add(vr);
+ if ( vr || (DCMGateDB[Index].Group==0x0008 && DCMGateDB[Index].Element==0x0061 && Modality))
+ if ( (vr && vr->Length != 0) || (DCMGateDB[Index].Group==0x0008 && DCMGateDB[Index].Element==0x0061 && Modality) )
+ {
+ if(CIndex)
+ strcat(Columns, ", ");
+ strcat(Columns, DCMGateDB [ Index ] . SQLColumn);
+ ++CIndex;
+ }
+ if (AllowEmptyPatientID && (vr==NULL || vr->Length==0) && DCMGateDB[Index].Group==0x0010 && DCMGateDB[Index].Element==0x0020 && Patid[0])
+ {
+ if(CIndex)
+ strcat(Columns, ", ");
+ strcat(Columns, DCMGateDB [ Index ] . SQLColumn);
+ ++CIndex;
+ }
+
+ ++Index;
+ }
+
+ strcat( Columns, ", AccessTime" );
+ if(ObjectFile && DCMGateDB==ImageDB)
+ strcat ( Columns, ", ObjectFile" );
+ if(DeviceName)
+ strcat ( Columns, ", DeviceName" );
+
+ Index = 0; CIndex = 0;
+ Values [ 0 ] = '\0';
+ Updates[ 0 ] = '\0';
+ Where [ 0 ] = '\0';
+
+ VR patvr;
+
+ while ( Index < VRArray.GetSize() )
+ {
+ vr = VRArray.Get ( Index );
+
+ if (AllowEmptyPatientID && (vr==NULL || vr->Length==0) && DCMGateDB[Index].Group==0x0010 && DCMGateDB[Index].Element==0x0020 && Patid[0])
+ {
+ patvr.Data = Patid;
+ patvr.Length = strlen(Patid);
+ patvr.ReleaseMemory = false;
+
+ vr = &patvr;
+ }
+
+ if ( vr || (DCMGateDB[Index].Group==0x0008 && DCMGateDB[Index].Element==0x0061 && Modality))
+ if ( (vr && vr->Length != 0) || (DCMGateDB[Index].Group==0x0008 && DCMGateDB[Index].Element==0x0061 && Modality) )
+ {
+ if(CIndex)
+ {
+ strcat ( Values, ", ");
+ strcat ( Updates, ", ");
+ }
+
+ LastADBE = &DCMGateDB[Index];
+ switch(DCMGateDB[Index].SQLType)
+ {
+ case SQL_C_CHAR:
+ if (vr && DCMGateDB[Index].SQLLength < vr->Length)
+ {
+ int save = vr->Length;
+ char name[80];
+ vr->Length = DCMGateDB[Index].SQLLength;
+ MakeSafeStringValues ( vr, TempString );
+ vr->Length = save;
+ strcpy(name, DCMGateDB[Index].SQLColumn);
+ strcat(name, ",");
+ if (strstr(AllowTruncate, name))
+ OperatorConsole.printf("Truncated %s from %d to %d chars in file: %s\n", DCMGateDB[Index].SQLColumn, save, DCMGateDB[Index].SQLLength, ObjectFile);
+ else
+ OperatorConsole.printf("***Truncated %s from %d to %d chars in file: %s\n", DCMGateDB[Index].SQLColumn, save, DCMGateDB[Index].SQLLength, ObjectFile);
+ }
+ else
+ MakeSafeStringValues ( vr, TempString );
+ break;
+ case SQL_C_DATE:
+ if (vr && DCMGateDB[Index].SQLLength < vr->Length)
+ {
+ int save = vr->Length;
+ char name[80];
+ vr->Length = DCMGateDB[Index].SQLLength;
+ MakeSafeDate ( vr, TempString );
+ vr->Length = save;
+ strcpy(name, DCMGateDB[Index].SQLColumn);
+ strcat(name, ",");
+ if (strstr(AllowTruncate, name))
+ OperatorConsole.printf("Truncated %s from %d to %d chars in file: %s\n", DCMGateDB[Index].SQLColumn, save, DCMGateDB[Index].SQLLength, ObjectFile);
+ else
+ OperatorConsole.printf("***Truncated %s from %d to %d chars in file: %s\n", DCMGateDB[Index].SQLColumn, save, DCMGateDB[Index].SQLLength, ObjectFile);
+ }
+ else
+ MakeSafeDate ( vr, TempString );
+ break;
+ default:
+ SystemDebug.printf("Unknown SQL Type: %d\n",
+ DCMGateDB[Index].SQLType);
+ }
+
+ if (DCMGateDB[Index].Group==0x0008 && DCMGateDB[Index].Element==0x0061 && Modality)
+ {
+ if (UseEscapeStringConstants)
+ strcat ( Values, "E'" );
+ else
+ strcat ( Values, "'" );
+ strcat ( Values, Modality );
+ strcat ( Values, "'" );
+ }
+ else
+ strcat ( Values, TempString );
+
+ strcat ( Updates, " ");
+ strcat ( Updates, DCMGateDB [ Index ] . SQLColumn );
+ strcat ( Updates, " = ");
+
+ // enter incoming modality into studymodality
+ if (DCMGateDB[Index].Group==0x0008 && DCMGateDB[Index].Element==0x0061 && Modality)
+ {
+ im = Index;
+ if (UseEscapeStringConstants)
+ strcat ( Updates, "E'" );
+ else
+ strcat ( Updates, "'" );
+ pm1 = strlen(Updates);
+ strcat ( Updates, Modality );
+ strcat ( Updates, "'" );
+ pm2 = strlen(Updates);
+ }
+ else
+ strcat ( Updates, TempString );
+
+ if (Index==0)
+ {
+ strcat ( Where, DCMGateDB [ Index ] . SQLColumn );
+ strcat ( Where, " = ");
+ strcat ( Where, TempString );
+ }
+
+ // include (indexed) patient ID to query for speed (only active in rev5 db or higher) except when checking for duplicates
+ if (!CheckDuplicates && Index && DCMGateDB[Index].Group==0x0010 && DCMGateDB[Index].Element==0x0020)
+ {
+ if(Where[0] != '\0')
+ strcat ( Where, " AND "); // bcb Was putting an AND onto the beginning of Where
+ strcat ( Where, DCMGateDB [ Index ] . SQLColumn );
+ strcat ( Where, " = ");
+ strcat ( Where, TempString );
+ }
+
+ ++CIndex;
+ }
+ ++Index;
+ }
+
+ sprintf(TempString, ", %u", (unsigned int)CurrentTime() );
+ strcat( Values, TempString );
+
+ sprintf(TempString, "%u", (unsigned int)CurrentTime() );
+ strcat( Updates, ", AccessTime = " );
+ strcat( Updates, TempString );
+
+ if(ObjectFile && DCMGateDB==ImageDB)
+ {
+ LastADBE = NULL;
+ strcat(Values, ", ");
+ FakeVR.Data = (void*)ObjectFile;
+ FakeVR.Length = strlen(ObjectFile);
+ FakeVR.Group = 0;
+ FakeVR.Element = 0;
+ MakeSafeStringValues ( &FakeVR, TempString );
+ FakeVR.Data = NULL;
+ FakeVR.Length = 0;
+ strcat ( Values, TempString );
+
+ strcat ( Updates, ", ObjectFile = " );
+ strcat ( Updates, TempString );
+ }
+
+ if(DeviceName)
+ {
+ LastADBE = NULL;
+ strcat(Values, ", ");
+ FakeVR.Data = (void*)DeviceName;
+ FakeVR.Length = strlen(DeviceName);
+ FakeVR.Group = 0;
+ FakeVR.Element = 0;
+ MakeSafeStringValues ( &FakeVR, TempString );
+ FakeVR.Data = NULL;
+ FakeVR.Length = 0;
+ strcat ( Values, TempString );
+
+ strcat ( Updates, ", DeviceName = " );
+ strcat ( Updates, TempString );
+ }
+
+ // No need to keep on writing exactly the same data !
+
+ if (DCMGateDB!=ImageDB && isin_UpdateCache(Updates))
+ {
+// OperatorConsole.printf("Skipping Cached Update on Table %s\n", TableName);
+ SkippedCachedUpdates++;
+ return TRUE;
+ }
+
+
+ if (JustAdd)
+ {
+ AddedDatabase++;
+ if(DB.AddRecord(TableName, Columns, Values))
+ {
+ *Added = TRUE;
+ return ( TRUE );
+ }
+ else
+ {
+ SystemDebug.printf ( "***Unable to DB.Add()\n");
+ SystemDebug.printf ( "***SQL: %.1000s\n", DB.SQLStatement);
+ DB.PrintLastError();
+ clear_UpdateCache(); // would be invalid
+ return ( FALSE );
+ }
+ }
+
+ /* Use UPDATE if the record exists; else use INSERT
+ Check whether all existing records differ from the current update.
+ If so, log a warning, but update it anyway, showing patient ID
+ */
+
+ strcpy(TempString, DCMGateDB[0].SQLColumn);
+ for (i=1; i<=lastfield; i++)
+ {
+ strcat(TempString, ",");
+ strcat(TempString, DCMGateDB[i].SQLColumn);
+ }
+
+
+ // the following code is not multi-user safe: the record might be in process of creation
+ // in that case a query does not find it, but later there will be two records
+ // to solve this problem, keys are now unique
+
+ if(!DB.Query(TableName, TempString, Where, NULL))
+ return FALSE;
+
+ if(!DB.BindField (1, SQL_C_CHAR, dummy, 255, &sdword)) return FALSE;
+
+ for (i=1; i<=lastfield; i++)
+ {
+ if(!DB.BindField (i+1, SQL_C_CHAR, s[i-1], 255, &sdword))
+ return ( FALSE );
+ s[i-1][0] = 0;
+ }
+
+ if (DB.NextRecord())
+ {
+ // remove trailing spaces from read database field
+ for (i=1; i<=lastfield; i++)
+ {
+ len = strlen(s[i-1]);
+ for (j=len-1; j>=0; j--)
+ if (s[i-1][j]==' ') s[i-1][j] = 0;
+ else break;
+ }
+
+ // merge incoming modality with study modality
+ if (pm1)
+ {
+ if (DoubleBackSlashToDB)
+ {
+ pTmp = TempString;
+ for (i=0; i<strlen(s[im-1]); i++)
+ if (s[im-1][i]=='\\') *pTmp++ = '\\', *pTmp++ = '\\';
+ else *pTmp++ = s[im-1][i];
+ *pTmp++ = 0;
+ strcpy(s[im-1], TempString);
+ }
+ else
+ strcpy(TempString, s[im-1]);
+
+ // set flag if modality in studymodality string, but e.g., CT must not respond to RTSTRUCT
+ flag = 0;
+ if (strstr(TempString, Modality)!=NULL)
+ {
+ Temp2[0] = '\\';
+ strcpy(Temp2+1, TempString);
+ strcpy(Temp2+strlen(Temp2), "\\");
+
+ Temp3[0] = '\\';
+ strcpy(Temp3+1, Modality);
+ strcpy(Temp3+strlen(Temp3), "\\");
+
+ flag = strstr(Temp2, Temp3)!=NULL;
+ }
+
+ // modality is not present: append the new modality with the read modality string
+ if (!flag)
+ {
+ len = strlen(TempString) + 1;
+ if (DoubleBackSlashToDB) len++;
+ memmove(Updates+pm2+len-1, Updates+pm2-1, sizeof(Updates)-pm2-len);
+ Updates[pm2-1] = '\\';
+ if (DoubleBackSlashToDB) Updates[pm2++] = '\\';
+ memcpy(Updates+pm2, TempString, strlen(TempString));
+ }
+ // modality is present: re-write the read modality string
+ else
+ {
+ len = strlen(TempString) - strlen(Modality);
+ memmove(Updates+pm2+len-1, Updates+pm2-1, sizeof(Updates)-pm2-len);
+ memcpy(Updates+pm1, TempString, strlen(TempString));
+ }
+ }
+
+ for (i=1; i<=lastfield; i++)
+ {
+ // extract and compare update value
+ strcpy(TempString, " ");
+ strcat(TempString, DCMGateDB[i].SQLColumn);
+ strcat(TempString, " = '");
+ pTmp = strstr(Updates, TempString);
+ if (pTmp)
+ {
+ pTmp2 = strchr(pTmp + strlen(TempString), '\'');
+
+ while (pTmp2[1]=='\'') pTmp2 = strchr(pTmp2+2, '\''); // 20060607 skip '' in string
+
+ // check patient ID in study table is being set, need to update lower tables then
+ if (AllowEmptyPatientID && strcmp(TableName, StudyTableName) == 0 &&
+ DCMGateDB[i].Group == 0x0010 && DCMGateDB[i].Element == 0x0020 &&
+ strlen(s[i-1])==0 && strlen(pTmp + strlen(TempString))>0)
+ SetPatientIDStudy = true;
+
+ if (pTmp2 && strlen(s[i-1]))
+ {
+ *pTmp2 = 0;
+
+ if (strnicmp(s[i-1], pTmp + strlen(TempString), strlen(s[i-1])) != 0)
+ {
+
+ // convert backslashes and check again if inconsistency was found
+ char temp[512];
+// VR FakeVR;//Already declared
+
+ FakeVR.Data = (void*)&s[i-1];
+ FakeVR.Length = strlen(s[i-1]);
+ FakeVR.Group = 0;
+ FakeVR.Element = 0;
+ MakeSafeStringValues ( &FakeVR, temp );
+ FakeVR.Data = NULL;
+ FakeVR.Length = 0;
+
+ // Remove '' added by MakeSafeStringValues - 20060618
+ temp[strlen(temp)-1]=0;
+ strcpy(s[i-1], temp+1);
+
+ if (strnicmp(s[i-1], pTmp + strlen(TempString), strlen(s[i-1])) != 0)
+ {
+ // check patient table entries
+ if ((strcmp(TableName, PatientTableName) == 0) &&
+ (strlen(s[i-1]) > 0))
+ {
+ /* Do not overrule a non-empty with an empty value */
+ if (strlen(pTmp + strlen(TempString)) == 0)
+ goto cont; //return TRUE;
+ /* Do not overrule birthdate with xxxx0101 */
+ if ((DCMGateDB[i].Group == 0x0010) &&
+ (DCMGateDB[i].Element == 0x0030) &&
+ ((atoi(s[i-1]) % 10000) != 101) &&
+ ((atoi(pTmp + strlen(TempString)) % 10000) == 101))
+ goto cont; //return TRUE;
+ /* Do not overrule sex with something other than MmFf */
+ if ((DCMGateDB[i].Group == 0x0010) &&
+ (DCMGateDB[i].Element == 0x0040) &&
+ ((pTmp + strlen(TempString))[0] != 'M') &&
+ ((pTmp + strlen(TempString))[0] != 'm') &&
+ ((pTmp + strlen(TempString))[0] != 'F') &&
+ ((pTmp + strlen(TempString))[0] != 'f'))
+ goto cont; //return TRUE;
+ }
+
+ // check patient birthdate
+ if (DCMGateDB[i].Group == 0x0010 && DCMGateDB[i].Element == 0x0030)
+ {
+ OperatorConsole.printf("***Inconsistent %s in %s: PatientID = '%s' %s, Old='%s', New='%s'\n",
+ DCMGateDB[i].SQLColumn, TableName, Patid, Where, s[i-1], pTmp + strlen(TempString));
+ }
+ // check link
+ else if (i==LastDBE(DCMGateDB) && strcmp(TableName, PatientTableName) != 0)
+ {
+ OperatorConsole.printf("***Refused to enter inconsistent link %s into %s: PatientID = '%s' %s, Old='%s', Refused='%s'\n",
+ DCMGateDB[i].SQLColumn, TableName, Patid, Where, s[i-1], pTmp + strlen(TempString));
+ return FALSE; // fatal error
+ }
+ else
+ TroubleLog.printf("Inconsistent %s in %s: PatientID = '%s' %s, Old='%s', New='%s'\n",
+ DCMGateDB[i].SQLColumn, TableName, Patid, Where, s[i-1], pTmp + strlen(TempString));
+
+ }
+ }
+cont:
+ *pTmp2 = '\'';
+ }
+ }
+ }
+
+ if (CheckDuplicates)
+ if (DB.NextRecord())
+ {
+ OperatorConsole.printf("***Duplicate found in %s WHERE %s\n", TableName, Where);
+ return ( FALSE );
+ }
+
+ if(DB.UpdateRecords(TableName, Updates, Where))
+ {
+ UpdateDatabase++;
+ if (DCMGateDB!=ImageDB)
+ into_UpdateCache(Updates);
+
+ if(SetPatientIDStudy && AllowEmptyPatientID)
+ {
+ char sql[512];
+ *strchr(Updates, ',')=0;
+ sprintf(sql, "Update DicomSeries set SeriesPat = '%s' where %s",
+ Patid, Updates);
+ OperatorConsole.printf(sql);
+ DB.Exec(sql);
+
+ sprintf(sql, "Update DicomImages set ImagePat = '%s' where SeriesInst in (select SeriesInst from DicomSeries where %s)",
+ Patid, Updates);
+ OperatorConsole.printf(sql);
+ DB.Exec(sql);
+ }
+
+
+ return ( TRUE );
+ }
+ else
+ {
+ SystemDebug.printf ( "***Unable to update record\n");
+ SystemDebug.printf ( "***SQL: %.1000s\n", DB.SQLStatement);
+ DB.PrintLastError();
+ clear_UpdateCache(); // would be invalid
+ return ( FALSE );
+ }
+ }
+ else
+ {
+ AddedDatabase++;
+ if(DB.AddRecord(TableName, Columns, Values))
+ {
+ *Added = TRUE;
+ return ( TRUE );
+ }
+ else
+ {
+ SystemDebug.printf ( "***Unable to DB.Add()\n");
+ SystemDebug.printf ( "***SQL: %.1000s\n", DB.SQLStatement);
+ DB.PrintLastError();
+ clear_UpdateCache(); // would be invalid
+ return ( FALSE );
+ }
+ }
+
+ return ( FALSE );
+ }
+
+// Updates all the access times for all levels of the database, given only
+// a connected database, and an SOP Instance.
+// Called automatically from GetFileName
+
+BOOL
+UpdateAccessTimes(
+ Database &ConnectedDB,
+ char *SOPInstanceUID)
+ {
+ DWORD CurTime;
+ SQLLEN sdword;
+ char s[255];
+ char s1[255];
+ // Basic idea is we up all the access times for each level
+ sprintf(s, "AccessTime = %u", (unsigned int)(CurTime = CurrentTime()));
+ sprintf(s1, "%s = %s", UniqueKey(ImageDB), SOPInstanceUID);
+ if(!ConnectedDB.UpdateRecords(ImageTableName,s,s1))
+ {
+ SystemDebug.printf("***Could not update access time for Image level database\n");
+ return ( FALSE );
+ }
+ if(!ConnectedDB.Query(ImageTableName, UniqueLink(ImageDB), s1, NULL))
+ {
+ SystemDebug.printf("***Could not obtain Series level link\n");
+ return ( FALSE );
+ }
+ if(!ConnectedDB.BindField (1, SQL_C_CHAR,
+ s, 255,
+ &sdword))
+ return ( FALSE );
+ if(!ConnectedDB.NextRecord())
+ return ( FALSE );
+
+ // Perform search and update series level database
+ sprintf(s1, "%s = '%s'", UniqueKey(SeriesDB), s);
+ sprintf(s, "AccessTime = %u", (unsigned int)CurTime);
+ if(!ConnectedDB.UpdateRecords(SeriesTableName,s,s1))
+ {
+ SystemDebug.printf("***Could not update access time for Series level database\n");
+ return ( FALSE );
+ }
+ if(!ConnectedDB.Query(SeriesTableName, UniqueLink(SeriesDB), s1, NULL))
+ {
+ SystemDebug.printf("***Could not obtain Series level link\n");
+ return ( FALSE );
+ }
+ if(!ConnectedDB.BindField (1, SQL_C_CHAR,
+ s, 255,
+ &sdword))
+ return ( FALSE );
+ if(!ConnectedDB.NextRecord())
+ return ( FALSE );
+
+ // Study level
+ sprintf(s1, "%s = '%s'", UniqueKey(StudyDB), s);
+ sprintf(s, "AccessTime = %u", (unsigned int)CurTime);
+ if(!ConnectedDB.UpdateRecords(StudyTableName,s,s1))
+ {
+ SystemDebug.printf("***Could not update access time for Study level database\n");
+ return ( FALSE );
+ }
+ if(!ConnectedDB.Query(StudyTableName, UniqueLink(StudyDB), s1, NULL))
+ {
+ SystemDebug.printf("***Could not obtain Study level link\n");
+ return ( FALSE );
+ }
+ if(!ConnectedDB.BindField (1, SQL_C_CHAR,
+ s, 255,
+ &sdword))
+ return ( FALSE );
+ if(!ConnectedDB.NextRecord())
+ return ( FALSE );
+
+ // Patient Level
+
+ DICOM2SQLValue(s); // 20110105
+ sprintf(s1, "%s = %s", UniqueKey(PatientDB), s);
+ sprintf(s, "AccessTime = %u", (unsigned int)CurTime);
+ if(!ConnectedDB.UpdateRecords(PatientTableName,s,s1))
+ {
+ SystemDebug.printf("***Could not update access time for Patient level database\n");
+ return ( FALSE );
+ }
+ return ( TRUE );
+ }
+
+// Make a new UID for db use (prefix configurable via UIDPrefix in dicom.ini)
+int UIDPostfix=0;
+static char dbUIDPrefix[65] = "1.2.826.0.1.3680043.2.135.1066.7"; // default value
+static BOOL dbLoadRoot = TRUE;
+static BOOL
+dbGenUID(char *oString)
+ {
+ if (dbLoadRoot)
+ {
+ char szRootSC[64];
+ if (MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile))
+ {
+ if (MyGetPrivateProfileString(szRootSC, "UIDPrefix", "1.2.826.0.1.3680043.2.135.1066", dbUIDPrefix, 64, ConfigFile))
+ strcat(dbUIDPrefix, ".7");
+ }
+ dbLoadRoot = FALSE;
+ }
+
+#ifdef WIN32
+ sprintf(oString, "%s.%u.%d.%u", dbUIDPrefix, (unsigned int)time(NULL), GetTickCount()%1000, (UIDPostfix++)%100);
+#else
+ sprintf(oString, "%s.%u.%u", dbUIDPrefix, (unsigned int)time(NULL), (UIDPostfix++)%10000);
+#endif
+ return ( TRUE );
+ }
+
+// Generates a new UID from an old one, but use UIDMODs table to maintain history of changes
+// A new request to change the old UID returns the previously changed UID
+
+CRITICAL_SECTION ChangeUIDCritical;
+BOOL ChangeUIDCriticalInit=FALSE;
+
+
+BOOL
+ChangeUID(char *OldUID, const char *Type, char *NewUID)
+ {
+ char s[255];
+ char Values[1024];
+ Database DB;
+ SQLLEN sdword;
+
+ if (!ChangeUIDCriticalInit)
+ { InitializeCriticalSection(&ChangeUIDCritical);
+ ChangeUIDCriticalInit = TRUE;
+ }
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ SystemDebug.printf("***Unable to connect to SQL\n");
+ return ( FALSE );
+ }
+
+ EnterCriticalSection(&ChangeUIDCritical);
+
+ sprintf(s, "OldUID = '%s'", OldUID);
+ if(!DB.Query("UIDMODS", "NewUID", s, NULL))
+ {
+ SystemDebug.printf("***Unable to query UIDMODS table\n");
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return ( FALSE );
+ }
+
+ if(!DB.BindField (1, SQL_C_CHAR, NewUID, 255, &sdword))
+ {
+ SystemDebug.printf("***Unable to bind field of UIDMODS table\n");
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return ( FALSE );
+ }
+
+ if(!DB.NextRecord())
+ {
+ dbGenUID(NewUID);
+ SystemDebug.printf("NewUID for %s = %s\n", Type, NewUID);
+
+ sprintf(Values, "%u, '", (unsigned int)time(NULL));
+ strcat(Values, OldUID);
+ strcat(Values, "', '");
+ strcat(Values, Type);
+ strcat(Values, "', '");
+ strcat(Values, NewUID);
+ strcat(Values, "'");
+ if(!DB.AddRecord("UIDMODS", "MODTime, OldUID, MODType, NewUID", Values))
+ {
+ SystemDebug.printf("***Unable to add entry to UIDMODS table\n");
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return ( FALSE );
+ }
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return TRUE;
+ }
+ else
+ SystemDebug.printf("OldUID = %s, NewUID = %s\n", OldUID, NewUID);
+
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return ( TRUE );
+ }
+
+// replaces UID, but use UIDMODs table to maintain history of changes
+// A new request to change the old UID returns the previously changed UID
+
+BOOL
+ChangeUIDTo(char *OldUID, char *Type, char *NewUID)
+ {
+ char s[255];
+ char Values[1024];
+ Database DB;
+ SQLLEN sdword;
+
+ if (!ChangeUIDCriticalInit)
+ { InitializeCriticalSection(&ChangeUIDCritical);
+ ChangeUIDCriticalInit = TRUE;
+ }
+
+ EnterCriticalSection(&ChangeUIDCritical);
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ SystemDebug.printf("***Unable to connect to SQL\n");
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return ( FALSE );
+ }
+
+ sprintf(s, "OldUID = '%s'", OldUID);
+ if(!DB.Query("UIDMODS", "NewUID", s, NULL))
+ {
+ SystemDebug.printf("***Unable to query UIDMODS table\n");
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return ( FALSE );
+ }
+
+ if(!DB.BindField (1, SQL_C_CHAR, NewUID, 255, &sdword))
+ {
+ SystemDebug.printf("***Unable to bind field of UIDMODS table\n");
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return ( FALSE );
+ }
+
+ if(!DB.NextRecord())
+ {
+ SystemDebug.printf("NewUID for %s = %s\n", Type, NewUID);
+
+ sprintf(Values, "%u, '", (unsigned int)time(NULL));
+ strcat(Values, OldUID);
+ strcat(Values, "', '");
+ strcat(Values, Type);
+ strcat(Values, "', '");
+ strcat(Values, NewUID);
+ strcat(Values, "'");
+ if(!DB.AddRecord("UIDMODS", "MODTime, OldUID, MODType, NewUID", Values))
+ {
+ SystemDebug.printf("***Unable to add entry to UIDMODS table\n");
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return ( FALSE );
+ }
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return TRUE;
+ }
+ else
+ SystemDebug.printf("OldUID = %s, NewUID = %s\n", OldUID, NewUID);
+
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return ( TRUE );
+ }
+
+// Generates an old UID from a new one, from UIDMODs table
+BOOL
+ChangeUIDBack(char *NewUID, char *OldUID)
+ {
+ char s[255];
+// char Values[1024];
+ Database DB;
+ SQLLEN sdword;
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ SystemDebug.printf("***ChangeUIDBack: Unable to connect to SQL\n");
+ return ( FALSE );
+ }
+
+ sprintf(s, "NewUID = '%s'", NewUID);
+ if(!DB.Query("UIDMODS", "OldUID", s, NULL))
+ {
+ SystemDebug.printf("***ChangeUIDBack: Unable to query UIDMODS table\n");
+ return ( FALSE );
+ }
+
+ if(!DB.BindField (1, SQL_C_CHAR, OldUID, 255, &sdword))
+ {
+ SystemDebug.printf("***ChangeUIDBack: Unable to bind field of UIDMODS table\n");
+ return ( FALSE );
+ }
+
+ if(!DB.NextRecord())
+ {
+ SystemDebug.printf("***ChangeUIDBack: Unable to locate new UID\n");
+ return ( FALSE );
+ }
+ else
+ SystemDebug.printf("OldUID = %s, NewUID = %s\n", OldUID, NewUID);
+
+ return ( TRUE );
+ }
+
+// Remove all records belonging to one session
+BOOL
+DeleteUIDChanges(char *Reason)
+ {
+ char s[255];
+// char Values[1024];
+ Database DB;
+ SQLLEN sdword;
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ SystemDebug.printf("***DeleteUIDChanges: Unable to connect to SQL\n");
+ return ( FALSE );
+ }
+
+ sprintf(s, "MODType = '%s'", Reason);
+ if(!DB.DeleteRecord("UIDMODS", s))
+ {
+ SystemDebug.printf("***DeleteUIDChanges: Unable to delete records drom UIDMODS table\n");
+ return ( FALSE );
+ }
+
+ return ( TRUE );
+ }
+
+// Generates one new UID for multiple ones, uses UIDMODs table to maintain history of changes
+// A following request to change the old UID returns the merged NewUID
+BOOL
+MergeUIDs(char *OldUID[], int n, const char *Type, char *NewUID)
+ {
+ char s[255];
+ char Values[1024];
+ Database DB;
+ SQLLEN sdword;
+ int i;
+
+ if (!ChangeUIDCriticalInit)
+ { InitializeCriticalSection(&ChangeUIDCritical);
+ ChangeUIDCriticalInit = TRUE;
+ }
+
+ EnterCriticalSection(&ChangeUIDCritical);
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ SystemDebug.printf("***Unable to connect to SQL\n");
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return ( FALSE );
+ }
+
+ dbGenUID(NewUID);
+ SystemDebug.printf("NewUID for merging %s = %s\n", Type, NewUID);
+
+ for (i=0; i<n; i++)
+ {
+ sprintf(s, "OldUID = '%s'", OldUID[i]);
+ if(!DB.Query("UIDMODS", "NewUID", s, NULL))
+ {
+ SystemDebug.printf("***Unable to query UIDMODS table\n");
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return ( FALSE );
+ }
+
+ DB.BindField (1, SQL_C_CHAR, Values, 255, &sdword);
+
+ if(DB.NextRecord())
+ DB.DeleteRecord("UIDMODS", s);
+
+ sprintf(Values, "%u, '", (unsigned int)time(NULL));
+ strcat(Values, OldUID[i]);
+ strcat(Values, "', '");
+ strcat(Values, Type);
+ strcat(Values, "', '");
+ strcat(Values, NewUID);
+ strcat(Values, "'");
+ if(!DB.AddRecord("UIDMODS", "MODTime, OldUID, MODType, NewUID", Values))
+ {
+ SystemDebug.printf("***Unable to add entry to UIDMODS table\n");
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return ( FALSE );
+ }
+
+ SystemDebug.printf("OldUID = %s, NewUID = %s\n", OldUID[i], NewUID);
+ }
+
+ LeaveCriticalSection(&ChangeUIDCritical);
+ return ( TRUE );
+ }
+
+// for values or exact match, not queries using LIKE
+BOOL
+MakeSafeStringValues (
+ VR *vr,
+ char *string )
+ {
+ unsigned int Length;
+ char *sout;
+ char *sin;
+ char *s;
+ UINT Index;
+
+ if (!vr || vr->Length==0 || vr->Data==NULL)
+ {
+ strcpy(string, "''");
+ return FALSE;
+ }
+
+ s = SetString(vr, NULL, 0);
+ Length = strlen(s);
+ sin = (char*)s;
+ sout = string;
+
+ if (UseEscapeStringConstants)
+ if (strchr(s, '\\'))
+ (*sout++) = 'E';
+
+ (*sout++) = '\'';
+
+ Index = 0;
+ while(Index < Length)
+ {
+ switch (*sin)
+ {
+ case '\'':
+ (*sout) = '\'';++sout;
+ (*sout) = '\'';++sout;
+ break;
+ case '\\':
+ if (DoubleBackSlashToDB)
+ {
+ if ((Index > 0) && (sin[-1] != '\\'))
+ {
+ (*sout) = '\\';++sout;
+ (*sout) = '\\';++sout;
+ }
+ }
+ else
+ {
+ (*sout) = (*sin);
+ ++sout;
+ }
+ break;
+ case 0: break;
+ default:
+ (*sout) = (*sin);
+ ++sout;
+ }
+ ++sin;
+ ++Index;
+ }
+
+ /* new code removes all trailing spaces (no check on begin: sout always start with ') */
+ sout--;
+ while (*sout == ' ') sout--;
+ sout++;
+
+ (*sout) = '\'';++sout;
+ (*sout) = '\0';
+
+ delete s;
+ return ( TRUE );
+ }
+
+
+BOOL
+MakeSafeDate ( VR *vr, char *string )
+ {
+ unsigned int Length;
+ char *sout;
+ char *sin;
+ char s[256];
+ UINT Index;
+
+ (*string)='\'';
+ SetString(vr, s, 256);
+ Length = strlen(s);
+ sin = (char*)s;
+ sout = string + 1;
+
+ if (vr)
+ if(vr->Data)
+ {
+ Index = 0;
+ while(Index < Length)
+ {
+ switch (*sin)
+ {
+ case '.': // remove from ACR-NEMA v2 comp.
+ break;
+ case '/': // remove for safety
+ break;
+ case '\'':
+ (*sout) = '\'';++sout;
+ (*sout) = '\'';++sout;
+ break;
+ case '\"':
+ (*sout) = '\"';++sout;
+ (*sout) = '\"';++sout;
+ break;
+ case 0: break;
+ default:
+ (*sout) = (*sin);
+ ++sout;
+ }
+ ++sin;
+ ++Index;
+ }
+ }
+ --sout;
+ if((*sout)==' ')
+ ;
+ else
+ ++sout;
+ (*sout) = '\'';++sout;
+ (*sout) = '\0';
+
+ return ( TRUE );
+ }
+
+BOOL
+GetFileName(VR *vr, char *filename, char *dv, BOOL UpdateLRU, char *patid, char *study, char *series)
+ {
+ Database DB;
+ BOOL Ret;
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ return ( FALSE );
+
+ Ret = GetFileName(vr, filename, dv, DB, UpdateLRU, patid, study, series);
+ DB.Close();
+ return(Ret);
+ }
+
+
+BOOL
+GetFileName(VR *SOPInstance, char *filename, char *device, Database &ConnectedDB, BOOL UpdateLRU, char *patid, char *study, char *series)
+ {
+ SQLLEN sdword;
+ char s [ 256 ];
+ char s2 [ 256 ];
+ char s1[70];
+ int Index;
+
+ UNUSED_ARGUMENT(UpdateLRU);
+ MakeSafeStringValues(SOPInstance, s1); // only allow exact match
+ if (s1[0]==0) return FALSE;
+
+ sprintf(s, "SOPInstanceUID");
+ if (TruncateFieldNames)
+ s[TruncateFieldNames] = 0;
+ sprintf(s+strlen(s), " = %s", s1);
+
+ // include patid (indexed) for speed; test for rev5 or higher of the database
+ if (patid)
+ if (patid[0])
+ {
+ Index = 1;
+ while (ImageDB[Index].Element)
+ {
+ if (ImageDB[Index].Group==0x0010 && ImageDB[Index].Element==0x0020)
+ {
+ char newpatid[128];
+ strcpy(newpatid, patid);
+ DICOM2SQLValue(newpatid); // 20110105
+ sprintf(s+strlen(s), " AND ImagePat = %s", newpatid);
+ break;
+ }
+ Index++;
+ }
+ }
+
+ if (study)
+ if (study[0])
+ {
+ Index = 1;
+ while (ImageDB[Index].Element)
+ {
+ if (ImageDB[Index].Group==0x0020 && ImageDB[Index].Element==0x000d)
+ {
+ sprintf(s+strlen(s), " AND StudyInsta = '%s'", study);
+ break;
+ }
+ Index++;
+ }
+ }
+
+ if (series)
+ if (series[0])
+ sprintf(s+strlen(s), " AND SeriesInst = '%s'", series);
+
+ EnterCriticalSection(&ConnectedDB.m_Critical);
+ if(!ConnectedDB.Query(ImageTableName, "ObjectFile, DeviceName", s, NULL))
+ {
+ LeaveCriticalSection(&ConnectedDB.m_Critical);
+ return ( FALSE );
+ }
+ if(!ConnectedDB.BindField (1, SQL_C_CHAR,
+ s, 255,
+ &sdword))
+ {
+ LeaveCriticalSection(&ConnectedDB.m_Critical);
+ return ( FALSE );
+ }
+ if(!ConnectedDB.BindField (2, SQL_C_CHAR,
+ s2, 255,
+ &sdword))
+ {
+ LeaveCriticalSection(&ConnectedDB.m_Critical);
+ return ( FALSE );
+ }
+ if(!ConnectedDB.NextRecord())
+ {
+ LeaveCriticalSection(&ConnectedDB.m_Critical);
+ return ( FALSE );
+ }
+ LeaveCriticalSection(&ConnectedDB.m_Critical);
+
+ strcpy(filename, s);
+ strcpy(device, s2);
+ // Used to update the AU list
+ // AccessUpdate.printf("%s", s1);
+ //UpdateAccessTimes(ConnectedDB, s1);
+
+ if (filename[0]==0 || device[0]==0) return FALSE; // virtual image that has no filename yet
+
+ return ( TRUE );
+ }
+
+// Makes a copy of a DICOM Object
+DICOMDataObject *MakeCopy(
+ DICOMDataObject *DO)
+ {
+ DICOMDataObject DO2;
+ VR *vr;
+ VR *newVR;
+
+ DICOMDataObject *DO3 = new DICOMDataObject;
+ if(!DO3)
+ return ( NULL );
+
+ while (( vr = DO->Pop() ))
+ {
+ if (vr->SQObjectArray)
+ {
+ newVR = new VR(vr->Group, vr->Element, 0, (void *) NULL, FALSE);
+ Array < DICOMDataObject * > *ADDO = (Array<DICOMDataObject*>*) vr->SQObjectArray;
+ Array < DICOMDataObject * > *SQE = new Array <DICOMDataObject *>;
+ for (int j=0; j<ADDO->GetSize(); j++)
+ {
+ DICOMDataObject *dd = MakeCopy(ADDO->Get(j));
+ SQE->Add(dd);
+ }
+ newVR->SQObjectArray = (void*) SQE;
+ }
+ else
+ {
+ newVR = new VR(vr->Group, vr->Element, vr->Length, (BOOL) TRUE);
+ memcpy(newVR->Data, vr->Data, vr->Length);
+ }
+ DO2.Push(vr);
+ DO3->Push(newVR);
+ }
+ DO->Reset();
+ while (( vr = DO2.Pop() ))
+ {
+ DO->Push(vr);
+ }
+ return ( DO3 );
+ }
+
+// Faster delete image from database
+BOOL
+NewDeleteFromDB(DICOMDataObject *pDDO, Database &aDB)
+ {
+ char pat[256], study[256], series[256], sop[256];
+ char QueryString[512], DeleteString[512], Dum[256];
+ int ImageHasPat=0, SeriesHasPat=0, Index;
+ SQLLEN sdword;
+
+ if (!pDDO->GetVR(0x0010, 0x0020) ||
+ !pDDO->GetVR(0x0020, 0x000d) ||
+ !pDDO->GetVR(0x0020, 0x000e) ||
+ !pDDO->GetVR(0x0008, 0x0018))
+ {
+ OperatorConsole.printf("***[NewDeleteFromDB] -FAILED: DDO does not contain correct UIDs\n");
+ return ( FALSE );
+ }
+
+ // only allow exact match (use = in sql statement) // mvh 20110105
+ MakeSafeStringValues(pDDO->GetVR(0x0010, 0x0020), pat);
+ MakeSafeStringValues(pDDO->GetVR(0x0020, 0x000d), study);
+ MakeSafeStringValues(pDDO->GetVR(0x0020, 0x000e), series);
+ MakeSafeStringValues(pDDO->GetVR(0x0008, 0x0018), sop);
+
+
+ // include patid (indexed) for speed; test for presence in database at series and image level (optional)
+ Index=0;
+ while (ImageDB[Index].Element)
+ {
+ if (ImageDB[Index].Group==0x0010 && ImageDB[Index].Element==0x0020)
+ {
+ ImageHasPat=1;
+ break;
+ }
+ Index++;
+ }
+
+ Index=0;
+ while (SeriesDB[Index].Element)
+ {
+ if (SeriesDB[Index].Group==0x0010 && SeriesDB[Index].Element==0x0020)
+ {
+ SeriesHasPat=1;
+ break;
+ }
+ Index++;
+ }
+
+ // Delete entry from image database (would not remove duplicates - but these should not occur)
+ if (ImageHasPat)
+ {
+ sprintf(QueryString, "DICOMImages.SopInstanc = %s and DICOMImages.SeriesInst = %s and DICOMImages.ImagePat = %s", sop, series, pat);
+ sprintf(DeleteString, "DICOMImages.SopInstanc = %s and DICOMImages.SeriesInst = %s and DICOMImages.ImagePat = %s", sop, series, pat);
+ }
+ else
+ {
+ sprintf(QueryString, "DICOMImages.SopInstanc = %s and DICOMImages.SeriesInst = %s", sop, series);
+ sprintf(DeleteString, "DICOMImages.SopInstanc = %s and DICOMImages.SeriesInst = %s", sop, series);
+ }
+ if (!aDB.Query(ImageTableName, "DICOMImages.SopInstanc", QueryString, NULL)) return FALSE;
+ aDB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword);
+ if (aDB.NextRecord())
+ aDB.DeleteRecord(ImageTableName, DeleteString);
+
+ // Delete series if last image of series deleted (would not remove duplicates - but these should not occur)
+ if (ImageHasPat)
+ sprintf(QueryString, "DICOMImages.SeriesInst = %s and DICOMImages.ImagePat = %s", series, pat);
+ else
+ sprintf(QueryString, "DICOMImages.SeriesInst = %s", series);
+ if (SeriesHasPat)
+ sprintf(DeleteString, "DICOMSeries.SeriesInst = %s and DICOMSeries.StudyInsta = %s and DICOMSeries.SeriesPat = %s", series, study, pat);
+ else
+ sprintf(DeleteString, "DICOMSeries.SeriesInst = %s and DICOMSeries.StudyInsta = %s", series, study);
+ if (!aDB.Query(ImageTableName, "DICOMImages.SeriesInst", QueryString, NULL)) return FALSE;
+ aDB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword);
+ if (!aDB.NextRecord())
+ aDB.DeleteRecord(SeriesTableName, DeleteString);
+
+ // Delete study if last series deleted (would not remove duplicates - but these should not occur)
+ if (SeriesHasPat)
+ sprintf(QueryString, "DICOMSeries.StudyInsta = %s and DICOMSeries.SeriesPat = %s", study, pat);
+ else
+ sprintf(QueryString, "DICOMSeries.StudyInsta = %s", study);
+ sprintf(DeleteString, "DICOMStudies.StudyInsta = %s and DICOMStudies.PatientID = %s", study, pat);
+ if (!aDB.Query(SeriesTableName, "DICOMSeries.StudyInsta", QueryString, NULL)) return FALSE;
+ aDB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword);
+ if (!aDB.NextRecord())
+ aDB.DeleteRecord(StudyTableName, DeleteString);
+
+ // Delete patient/worklist if last study deleted (would not remove duplicates - but these should not occur)
+ sprintf(QueryString, "DICOMStudies.PatientID = %s", pat);
+ sprintf(DeleteString, "DICOMPatients.PatientID = %s", pat);
+ if (!aDB.Query(StudyTableName, "DICOMStudies.PatientID", QueryString, NULL)) return FALSE;
+ aDB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword);
+ if (!aDB.NextRecord())
+ {
+ aDB.DeleteRecord(PatientTableName, DeleteString);
+
+ // worklist defined ?
+ if (WorkListDB[0].Element)
+ {
+ sprintf(QueryString, "DICOMWorkList.PatientID = %s", pat);
+ sprintf(DeleteString, "DICOMWorkList.PatientID = %s", pat);
+ if (aDB.Query(WorkListTableName, "DICOMWorkList.PatientID", QueryString, NULL))
+ {
+ aDB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword);
+
+ while (aDB.NextRecord())
+ aDB.DeleteRecord(WorkListTableName, DeleteString);
+ }
+ }
+ }
+
+ clear_UpdateCache();
+ return ( TRUE );
+ }
+
+// Delete SOP from database (no image required - useful for orphaned db entries)
+BOOL
+NewDeleteSopFromDB(char *pat, char *study, char *series, char *sop, Database &aDB)
+ {
+ char QueryString[512], DeleteString[512], PatString[512], Dum[256];
+ int ImageHasPat=0, SeriesHasPat=0, Index;
+ SQLLEN sdword;
+
+ strcpy(PatString, pat);
+ DICOM2SQLValue(PatString); // mvh 20110105
+
+ // include patid (indexed) for speed; test for presence in database at series and image level (optional)
+ Index=0;
+ while (ImageDB[Index].Element)
+ {
+ if (ImageDB[Index].Group==0x0010 && ImageDB[Index].Element==0x0020)
+ {
+ ImageHasPat=1;
+ break;
+ }
+ Index++;
+ }
+
+ Index=0;
+ while (SeriesDB[Index].Element)
+ {
+ if (SeriesDB[Index].Group==0x0010 && SeriesDB[Index].Element==0x0020)
+ {
+ SeriesHasPat=1;
+ break;
+ }
+ Index++;
+ }
+
+
+
+ // Delete entry from image database (would not remove duplicates - but these should not occur)
+ if (ImageHasPat)
+ {
+ sprintf(QueryString, "DICOMImages.SopInstanc = '%s' and DICOMImages.SeriesInst = '%s' and DICOMImages.ImagePat = %s", sop, series, PatString);
+ sprintf(DeleteString, "DICOMImages.SopInstanc = '%s' and DICOMImages.SeriesInst = '%s' and DICOMImages.ImagePat = %s", sop, series, PatString);
+ }
+ else
+ {
+ sprintf(QueryString, "DICOMImages.SopInstanc = '%s' and DICOMImages.SeriesInst = '%s'", sop, series);
+ sprintf(DeleteString, "DICOMImages.SopInstanc = '%s' and DICOMImages.SeriesInst = '%s'", sop, series);
+ }
+ if (!aDB.Query(ImageTableName, "DICOMImages.SopInstanc", QueryString, NULL)) return FALSE;
+ aDB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword);
+ if (aDB.NextRecord())
+ aDB.DeleteRecord(ImageTableName, DeleteString);
+
+ // Delete series if last image of series deleted (would not remove duplicates - but these should not occur)
+ if (ImageHasPat)
+ sprintf(QueryString, "DICOMImages.SeriesInst = '%s' and DICOMImages.ImagePat = %s", series, PatString);
+ else
+ sprintf(QueryString, "DICOMImages.SeriesInst = '%s'", series);
+ if (SeriesHasPat)
+ sprintf(DeleteString, "DICOMSeries.SeriesInst = '%s' and DICOMSeries.StudyInsta = '%s' and DICOMSeries.SeriesPat = %s", series, study, PatString);
+ else
+ sprintf(DeleteString, "DICOMSeries.SeriesInst = '%s' and DICOMSeries.StudyInsta = '%s'", series, study);
+ if (!aDB.Query(ImageTableName, "DICOMImages.SeriesInst", QueryString, NULL)) return FALSE;
+ aDB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword);
+ if (!aDB.NextRecord())
+ aDB.DeleteRecord(SeriesTableName, DeleteString);
+
+ // Delete study if last series deleted (would not remove duplicates - but these should not occur)
+ if (SeriesHasPat)
+ sprintf(QueryString, "DICOMSeries.StudyInsta = '%s' and DICOMSeries.SeriesPat = %s", study, PatString);
+ else
+ sprintf(QueryString, "DICOMSeries.StudyInsta = '%s'", study);
+ sprintf(DeleteString, "DICOMStudies.StudyInsta = '%s' and DICOMStudies.PatientID = %s", study, PatString);
+ if (!aDB.Query(SeriesTableName, "DICOMSeries.StudyInsta", QueryString, NULL)) return FALSE;
+ aDB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword);
+ if (!aDB.NextRecord())
+ aDB.DeleteRecord(StudyTableName, DeleteString);
+
+ // Delete patient if last study deleted (would not remove duplicates - but these should not occur)
+ sprintf(QueryString, "DICOMStudies.PatientID = %s", PatString);
+ sprintf(DeleteString, "DICOMPatients.PatientID = %s", PatString);
+ if (!aDB.Query(StudyTableName, "DICOMStudies.PatientID", QueryString, NULL)) return FALSE;
+ aDB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword);
+ if (!aDB.NextRecord())
+ {
+ aDB.DeleteRecord(PatientTableName, DeleteString);
+
+ // worklist defined ?
+ if (WorkListDB[0].Element)
+ {
+ sprintf(QueryString, "DICOMWorkList.PatientID = %s", PatString);
+ sprintf(DeleteString, "DICOMWorkList.PatientID = %s", PatString);
+ if (aDB.Query(WorkListTableName, "DICOMWorkList.PatientID", QueryString, NULL))
+ {
+ aDB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword);
+
+ while (aDB.NextRecord())
+ aDB.DeleteRecord(WorkListTableName, DeleteString);
+ }
+ }
+ }
+
+ clear_UpdateCache();
+ return ( TRUE );
+ }
+
+BOOL
+RemoveFromWorld(
+ DICOMDataObject *DDO,
+ Database &DB) // Connected DB
+ {
+// VR *vr;
+ DICOMDataObject *TempPatientDDO, *TempStudyDDO, *TempSeriesDDO;
+ Array < DICOMDataObject * > ImageADDO;
+ Array < DICOMDataObject * > SeriesADDO;
+ Array < DICOMDataObject * > StudyADDO;
+ Array < DICOMDataObject * > PatientADDO;
+ UINT PatientIndex, StudyIndex, SeriesIndex;//, ImageIndex;
+
+ return NewDeleteFromDB(DDO, DB);
+
+ ////////////////////////////////////////////////
+ // The rest is unused - left for reference only
+ ////////////////////////////////////////////////
+
+ SystemDebug.printf("RemoveFromWorld\n");
+
+ // Step 1: Remove Image(s) from database.
+
+ RemoveDuplicates(DB, ImageDB, ImageTableName, DDO, FALSE);
+
+ // Step 2: Query on the Patient and work *down* to the image level.
+ // This is conceptually backwards from how one might think we should
+ // do this; But, it allows us to "repair" a damaged delete operation
+ // (one that failed part way though).
+
+ DICOMDataObject *DDO2 = MakeCopy(DDO);
+ QueryOnPatient(DDO, &PatientADDO);
+ if(!PatientADDO.GetSize())
+ {
+ SystemDebug.printf("PatientADDO : GetSize := 0\n");
+ QueryOnStudy(DDO2, &PatientADDO);
+ SystemDebug.printf("PatientADDO (via Study) : GetSize := %d\n",
+ PatientADDO.GetSize());
+ if(!PatientADDO.GetSize())
+ {
+ delete DDO2;
+ return ( FALSE );
+ }
+ }
+ delete DDO2;
+ PatientIndex = 0;
+ while ( PatientADDO.GetSize() )
+ {
+ if(!PatientADDO.Get(0)->GetVR(StudyDB[0].Group, StudyDB[0].Element))
+ {
+ VR *vr = new VR(StudyDB[0].Group, StudyDB[0].Element, 0, (BOOL) FALSE );
+ PatientADDO.Get(0)->Push(vr);
+ }
+ TempPatientDDO = MakeCopy(PatientADDO.Get(0));
+ QueryOnStudy(PatientADDO.Get(0), &StudyADDO);
+ if(!StudyADDO.GetSize())
+ {
+ SystemDebug.printf("Removing Patient from database\n");
+ RemoveDuplicates(DB, PatientDB, PatientTableName,
+ TempPatientDDO, FALSE);
+ SystemDebug.printf("Patient Gone!\n");
+ delete PatientADDO.Get(0);
+ PatientADDO.RemoveAt(0);
+ delete TempPatientDDO;
+ continue;
+ }
+ StudyIndex = 0;
+ while(StudyADDO.GetSize())
+ {
+ if(!StudyADDO.Get(0)->GetVR(SeriesDB[0].Group, SeriesDB[0].Element))
+ {
+ VR *vr = new VR(SeriesDB[0].Group, SeriesDB[0].Element, 0, (BOOL) FALSE );
+ StudyADDO.Get(0)->Push(vr);
+ }
+ TempStudyDDO = MakeCopy(StudyADDO.Get(0));
+ QueryOnSeries(StudyADDO.Get(0), &SeriesADDO);
+ if(!SeriesADDO.GetSize())
+ {
+ SystemDebug.printf("Removing Study from database\n");
+ RemoveDuplicates(DB, StudyDB, StudyTableName,
+ TempStudyDDO, FALSE);
+ delete StudyADDO.Get(0);
+ StudyADDO.RemoveAt(0);
+ delete TempStudyDDO;
+ continue;
+ }
+ SeriesIndex = 0;
+ while ( SeriesADDO.GetSize() )
+ {
+ if(!SeriesADDO.Get(0)->GetVR(SeriesDB[0].Group, SeriesDB[0].Element))
+ {
+ VR *vr = new VR(SeriesDB[0].Group, SeriesDB[0].Element, 0, (BOOL) FALSE );
+ SeriesADDO.Get(0)->Push(vr);
+ }
+
+ TempSeriesDDO = MakeCopy(SeriesADDO.Get(0));
+ QueryOnImage(SeriesADDO.Get(0), &ImageADDO);
+ if(!ImageADDO.GetSize())
+ {
+ SystemDebug.printf("Removing Series from database\n");
+ RemoveDuplicates(DB, SeriesDB, SeriesTableName,
+ TempSeriesDDO, FALSE);
+ delete SeriesADDO.Get(0);
+ SeriesADDO.RemoveAt(0);
+ delete TempSeriesDDO;
+ continue;
+ }
+ else
+ {
+ while ( ImageADDO.GetSize() )
+ {
+ delete ImageADDO.Get(0);
+ ImageADDO.RemoveAt(0);
+ }
+ }
+ ++SeriesIndex;
+ delete SeriesADDO.Get(0);
+ SeriesADDO.RemoveAt(0);
+ delete TempSeriesDDO;
+ }
+ if(!SeriesIndex)
+ {
+ SystemDebug.printf("Removing Study From Database\n");
+ RemoveDuplicates(DB, StudyDB, StudyTableName,
+ TempStudyDDO, FALSE);
+ delete StudyADDO.Get(0);
+ StudyADDO.RemoveAt(0);
+ delete TempStudyDDO;
+ continue;
+ }
+ ++StudyIndex;
+ delete StudyADDO.Get(0);
+ StudyADDO.RemoveAt(0);
+ delete TempStudyDDO;
+ }
+ if(!StudyIndex)
+ {
+ SystemDebug.printf("Removing Patient from database\n");
+ RemoveDuplicates(DB, PatientDB, PatientTableName,
+ TempPatientDDO, FALSE);
+ delete PatientADDO.Get(0);
+ PatientADDO.RemoveAt(0);
+ delete TempPatientDDO;
+ continue;
+ }
+ ++PatientIndex;
+ delete PatientADDO.Get(0);
+ PatientADDO.RemoveAt(0);
+ delete TempPatientDDO;
+ }
+ return ( TRUE );
+ }
+
+BOOL
+RemoveFromPACS(
+ DICOMDataObject *DDO, BOOL KeepImages)
+ {
+ Database DB;
+ Array < DICOMDataObject * > ADDO;
+ DICOMDataObject *qDDO;
+ DICOMDataObject *DDOCopy;
+ unsigned int Index;
+ VR *vr, *vr2;
+ char fn[260];
+ char dv[260];
+ char filename[260];
+ char MirrorDevice[260];
+
+ // Make sure the unique keys are in place for each hierachy of the
+ // database
+ if(!DDO->GetVR(PatientDB[0].Group, PatientDB[0].Element))
+ {
+ vr = new VR(PatientDB[0].Group, PatientDB[0].Element, 0, (BOOL) FALSE );
+ DDO->Push(vr);
+ }
+ if(!DDO->GetVR(StudyDB[0].Group, StudyDB[0].Element))
+ {
+ vr = new VR(StudyDB[0].Group, StudyDB[0].Element, 0, (BOOL) FALSE );
+ DDO->Push(vr);
+ }
+ if(!DDO->GetVR(SeriesDB[0].Group, SeriesDB[0].Element))
+ {
+ vr = new VR(SeriesDB[0].Group, SeriesDB[0].Element, 0, (BOOL) FALSE );
+ DDO->Push(vr);
+ }
+ if(!DDO->GetVR(ImageDB[0].Group, ImageDB[0].Element))
+ {
+ vr = new VR(ImageDB[0].Group, ImageDB[0].Element, 0, (BOOL) FALSE );
+ DDO->Push(vr);
+ }
+ DDOCopy = MakeCopy(DDO);
+ QueryOnImage (DDO, &ADDO);
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ SystemDebug.printf("***Unable to connect to SQL\n");
+ delete DDOCopy;
+ return ( FALSE );
+ }
+ Index = 0;
+ if (KeepImages)
+ SystemDebug.printf("RemoveFromPACS %d image database entries\n", ADDO.GetSize());
+ else
+ SystemDebug.printf("RemoveFromPACS %d images\n", ADDO.GetSize());
+
+ if(!ADDO.GetSize())
+ {
+ //20081124: RemoveFromWorld(DDOCopy,DB);
+ delete DDOCopy;
+ return ( TRUE );
+ }
+ delete DDOCopy;
+ while ( Index < ADDO.GetSize() )
+ {
+ qDDO = ADDO.Get(Index);
+ if(!qDDO)
+ return ( FALSE );
+ vr = qDDO->GetVR(0x0008, 0x0018);
+ if(!vr)
+ return ( FALSE );
+
+ char pat[66]; /* get the patient ID */
+ pat[0]=0;
+ vr2 = qDDO->GetVR(0x0010, 0x0020);
+ if (vr2)
+ {
+ memcpy(pat, vr2->Data, vr2->Length);
+ if (pat[vr2->Length-1]==' ')
+ pat[vr2->Length-1] = 0;
+ else
+ pat[vr2->Length] = 0;
+ }
+
+ if(GetFileName(vr, fn, dv, DB, FALSE, pat))
+ {
+ int sIndex, devlen;
+
+ if (!KeepImages) OperatorConsole.printf("Removed file: [%s:%s]\n", dv, fn);
+ GetPhysicalDevice(dv, filename);
+ devlen = strlen(filename);
+ strcat(filename, fn);
+
+ SystemDebug.printf("IOD File being removed: %s\n", filename);
+
+ if(!KeepImages)
+ {
+ if (remove(filename)!=0)
+ {
+ OperatorConsole.printf("***Could not remove IOD %s\n", filename);
+ }
+
+ for (sIndex = strlen(filename); sIndex>=devlen; sIndex--)
+ if (filename[sIndex]==PATHSEPCHAR)
+ {
+ filename[sIndex]='\0';
+ rmdir(filename);
+ }
+ }
+
+
+ MirrorDevice[0]=0;
+ if (memicmp(dv, "MAG", 3)==0)
+ {
+ sprintf(MirrorDevice, "MIRROR%d", atoi(dv+3));
+ if (!GetPhysicalDevice(MirrorDevice, filename))
+ MirrorDevice[0]=0;
+ else
+ {
+ devlen = strlen(filename);
+ strcat(filename, fn);
+ }
+ }
+
+
+ if (MirrorDevice[0])
+ {
+ if(!KeepImages)
+ {
+ if (remove(filename)!=0)
+ {
+ OperatorConsole.printf("***Could not remove mirror file %s\n", filename);
+ }
+
+ for (sIndex = strlen(filename); sIndex>=devlen; sIndex--)
+ if (filename[sIndex]==PATHSEPCHAR)
+ {
+ filename[sIndex]='\0';
+ rmdir(filename);
+ }
+ }
+
+ }
+
+ RemoveFromWorld(qDDO, DB);
+ }
+ else
+ SystemDebug.printf("***Unable to locate FILENAME for image\n");
+ ++Index;
+ }
+
+
+ while (ADDO.GetSize())
+ {
+ delete ADDO.Get(0);
+ ADDO.RemoveAt(0);
+ }
+
+ return ( TRUE );
+ }
+
+BOOL
+RemoveDuplicates (
+ Database &DB,
+ DBENTRY *DBE,
+ char *TableName,
+ DICOMDataObject *DDOPtr,
+ BOOL KeyOnAll)
+ {
+ UINT Index, CIndex;
+ VR *vr;
+ char s0 [ 256 ], s [ 512 ], s1[4096];
+
+ Index = 0;CIndex = 0;
+ s1[0] = '\0';
+
+ while ( TRUE )
+ {
+ if(!DBE[Index].Element)
+ {
+ DB.DeleteRecord (TableName, s1);
+ return ( TRUE );
+ }
+ vr = DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element);
+ if(vr)
+ {
+ if(CIndex)
+ {
+ // This code makes the 1st field a "key" field
+ if (!KeyOnAll)
+ {
+ DB.DeleteRecord (TableName, s1);
+ return ( TRUE );
+ }
+ strcat(s1, " and " );
+ }
+ MakeSafeStringValues(vr, s0); // only allow exact match // mvh 20110105
+ sprintf(s, " %s = %s ", DBE[Index].SQLColumn, s0);
+ strcat(s1, s);
+ ++CIndex;
+ }
+ ++Index;
+ }
+
+ clear_UpdateCache();
+ return ( FALSE );
+ }
+
+
+BOOL
+PrintTable(DBENTRY *DBT, char *name)
+ {
+ UINT Index;
+
+ if(!DBT)
+ {
+ SystemDebug.printf("(null table) %s\n", name);
+ return ( FALSE );
+ }
+ Index = 0;
+ while(DBT[Index].Group)
+ {
+ SystemDebug.printf("(%4.4x, %4.4x) %s, %d\n",
+ DBT[Index].Group, DBT[Index].Element,
+ DBT[Index].SQLColumn, DBT[Index].SQLLength);
+ ++Index;
+ }
+ return ( TRUE );
+ }
+
+BOOL
+MakeTableString ( DBENTRY *DBE, char *s, int mode )
+ {
+ UINT Index;
+ char TempString [ 128 ];
+
+ s[0] = '\0';
+
+ Index = 0;
+ while ( TRUE )
+ {
+ if(!DBE [ Index ].Element)
+ return ( TRUE );
+
+ if (DBE[Index].DICOMType!=DT_STARTSEQUENCE && DBE[Index].DICOMType!=DT_ENDSEQUENCE)
+ {
+ if(Index)
+ strcat(s, ", ");
+
+ strcat ( s, DBE [ Index ].SQLColumn);
+ }
+
+ switch ( DBE [ Index ].SQLType)
+ {
+ case SQL_C_CHAR:
+ if (DBE[Index].DICOMType==DT_STARTSEQUENCE || DBE[Index].DICOMType==DT_ENDSEQUENCE)
+ {
+ TempString[0]=0;
+ break;
+ }
+ sprintf(TempString, " varchar(%d)", DBE[Index].SQLLength);
+ strcat(s, TempString);
+ break;
+ case SQL_C_DATE:
+ sprintf(TempString, " char(8) ");
+ strcat(s, TempString);
+ break;
+ default:
+ if (DBE[Index].DICOMType==DT_STARTSEQUENCE || DBE[Index].DICOMType==DT_ENDSEQUENCE)
+ {
+ TempString[0]=0;
+ break;
+ }
+ SystemDebug.printf("Unknown SQL Type: %d\n", DBE[Index].SQLType);
+ exit(1);
+ }
+
+ if (Index==0 && mode!=1 && DBE!=WorkListDB)
+ strcat(s, " PRIMARY KEY not null");
+
+ ++Index;
+ }
+
+ return ( FALSE );
+ }
+
+
+// mode=0: default; mode=1: without indexes; mode=2: worklist only
+BOOL
+InitializeTables(int mode)
+ {
+ Database DB;
+ char s [2048];
+ int HasWorklist=0;
+ SQLLEN sdword;
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ return ( FALSE );
+
+ if (DB.Query(WorkListTableName, "DICOMWorkList.PatientID", NULL, NULL))
+ {
+ DB.BindField (1, SQL_C_CHAR, s, 255, &sdword);
+ if (DB.NextRecord())
+ HasWorklist = 1;
+ }
+
+ fprintf(stderr, "Dropping Existing tables (if-any)\n");
+
+ if (!HasWorklist)
+ fprintf(stderr, "Worklist is empty\n");
+ else
+ fprintf(stderr, "Worklist contains data\n");
+
+ if (!HasWorklist || mode==2)
+ {
+ fprintf(stderr, "Dropping worklist\n");
+ DB.DeleteTable ( WorkListTableName );
+ }
+
+ if (mode!=2)
+ {
+ fprintf(stderr, "Dropping other tables\n");
+ DB.DeleteTable ( PatientTableName );
+ DB.DeleteTable ( StudyTableName );
+ DB.DeleteTable ( SeriesTableName );
+ DB.DeleteTable ( ImageTableName );
+#if 0
+ DB.DeleteTable ( RegisteredMOPIDTableName );
+ DB.DeleteTable ( UIDToMOPIDTableName );
+ DB.DeleteTable ( UIDToCDRIDTableName );
+#endif
+ DB.DeleteTable ( "UIDMODS" );
+ }
+
+ if (!HasWorklist || mode==2)
+ if (WorkListDB && WorkListDB[0].Group )
+ {
+ fprintf(stderr, "WorkList Database\n");
+ MakeTableString ( WorkListDB, s, mode );
+ strcat(s, ", AccessTime int" );
+ strcat(s, ", qTimeStamp int" );
+ strcat(s, ", qFlags int" );
+ strcat(s, ", qSpare varchar(64)" );
+ DB.CreateTable ( WorkListTableName, s );
+ }
+ if (mode==2) return FALSE;
+
+ fprintf(stderr, "Patient Database\n");
+ MakeTableString ( PatientDB, s, mode );
+ strcat(s, ", AccessTime int" );
+ strcat(s, ", qTimeStamp int" );
+ strcat(s, ", qFlags int" );
+ strcat(s, ", qSpare varchar(64)" );
+ DB.CreateTable ( PatientTableName, s );
+
+ fprintf(stderr, "Study Database\n");
+ MakeTableString ( StudyDB, s, mode );
+ strcat(s, ", AccessTime int" );
+ strcat(s, ", qTimeStamp int" );
+ strcat(s, ", qFlags int" );
+ strcat(s, ", qSpare varchar(64)" );
+ DB.CreateTable ( StudyTableName, s );
+ if (mode==0)
+ {
+ DB.CreateIndex ( StudyTableName, "study_lnk", UniqueLink(StudyDB));
+ }
+
+ fprintf(stderr, "Series Database\n");
+ MakeTableString ( SeriesDB, s, mode );
+ strcat(s, ", AccessTime int" );
+ strcat(s, ", qTimeStamp int" );
+ strcat(s, ", qFlags int" );
+ strcat(s, ", qSpare varchar(64)" );
+ DB.CreateTable ( SeriesTableName, s );
+ if (mode==0)
+ {
+ DB.CreateIndex ( SeriesTableName, "series_lnk", UniqueLink(SeriesDB));
+ if (strstr(s, " SeriesPat "))
+ DB.CreateIndex ( SeriesTableName, "series_pat", "SeriesPat");
+ }
+
+ fprintf(stderr, "Image Database\n");
+ MakeTableString ( ImageDB, s, mode);
+ strcat(s, ", AccessTime int" );
+ strcat(s, ", qTimeStamp int" );
+ strcat(s, ", qFlags int" );
+ strcat(s, ", qSpare varchar(64)" );
+
+ if (MaxFieldLength==0 || MaxFieldLength>255)
+ strcat(s, ", ObjectFile varchar(255)");
+ else
+ sprintf(s+strlen(s), ", ObjectFile varchar(%d)", MaxFieldLength);
+
+ strcat(s, ", DeviceName varchar(32)");
+
+ if(!DB.CreateTable ( ImageTableName, s ))
+ {
+ DB.PrintLastError();
+ }
+
+ if (mode==0)
+ {
+ DB.CreateIndex ( ImageTableName, "images_lnk", UniqueLink(ImageDB));
+ if (strstr(s, " ImagePat "))
+ DB.CreateIndex ( ImageTableName, "images_pat", "ImagePat");
+ }
+
+#if 0
+ // Create Registered MOP Device Table
+ sprintf(s, "MOPID varchar(20), MOPTotalSize varchar(20), MOPUsedSize varchar(20)");
+ DB.CreateTable ( RegisteredMOPIDTableName, s );
+
+ // Create SOPInstanceUID => MOPID Table
+ sprintf(s, "SOPInstanceUID");
+ if (TruncateFieldNames)
+ s[TruncateFieldNames] = 0;
+ sprintf(s+strlen(s), " varchar(64), MOPID varchar(20)");
+ DB.CreateTable ( UIDToMOPIDTableName, s );
+
+ // Create SOPInstanceUID => CDR Table
+ sprintf(s, "SOPInstanceUID");
+ if (TruncateFieldNames)
+ s[TruncateFieldNames] = 0;
+ sprintf(s+strlen(s), " varchar(64), CDRID varchar(20)");
+ DB.CreateTable ( UIDToCDRIDTableName, s );
+#endif
+
+ // Create table to register UID modifications
+ if (mode==0)
+ DB.CreateTable ( "UIDMODS", "MODTime int, OldUID varchar(64) PRIMARY KEY not null, MODType varchar(32), NewUID varchar(64)" );
+ else
+ DB.CreateTable ( "UIDMODS", "MODTime int, OldUID varchar(64), MODType varchar(32), NewUID varchar(64)" );
+
+ if (mode==0)
+ {
+ DB.CreateIndex ( "UIDMODS", "mods_old", "OldUID");
+ }
+
+ // Create table to schedule transfers
+ //strcpy(s, DataSource);
+ //strcat(s, "\\SUBMISSIONS.DBF");
+ //strcpy(s, "HostDicom varchar(64)" );
+ //strcat(s, ", PortDicom int" );
+ //strcat(s, ", HostWebsrv varchar(64)" );
+ //strcat(s, ", PortWebSrv int" );
+ //strcat(s, ", ModeSubmit varchar(10)" );
+ //strcat(s, ", HostSubmit varchar(32)" );
+ //strcat(s, ", PortSubmit int" );
+ //strcat(s, ", Ident varchar(64)" );
+ //strcat(s, ", PatientID varchar(64)" );
+ //strcat(s, ", StudyUID varchar(64)" );
+ //strcat(s, ", SeriesUID varchar(64)" );
+ //strcat(s, ", ObjInstUID varchar(64)" );
+
+ //DB.CreateTable ( "SUBMISSIONS", s);
+
+ return ( FALSE );
+ }
+
+BOOL VerifyIsInDBE(
+ VR *vr,
+ DBENTRY *DBE,
+ DBENTRY * &TempDBEPtr
+ )
+ {
+ UINT Index;
+
+ TempDBEPtr = NULL;
+
+ Index = 0;
+ if(!vr)
+ return ( FALSE );
+
+ while ( TRUE )
+ {
+ if (!DBE[Index].Element)
+ return ( FALSE );
+ if(DBE[Index].Group == vr->Group)
+ if(DBE[Index].Element == vr->Element)
+ if (DBE[Index].DICOMType!=DT_STARTSEQUENCE && DBE[Index].DICOMType!=DT_ENDSEQUENCE)
+ {
+ LastADBE = &DBE[Index];
+
+ // NOT THREAD SAFE:
+ // TempDBEPtr = LastADBE;
+ TempDBEPtr = &DBE[Index];
+ return ( TRUE );
+ }
+ ++Index;
+ }
+ return ( FALSE );
+ }
+
+UINT
+LastDBE(DBENTRY *DBE)
+ {
+ UINT Index;
+
+ Index = 0;
+ while ( TRUE )
+ {
+ if ( !DBE[Index].Element )
+ {
+ if(Index)
+ return(Index-1);
+ }
+ ++Index;
+ }
+ return ( 0 );
+ }
+
+UINT
+DBEIndex(DBENTRY *DBE, VR *vr)
+ {
+ UINT Index = 0;
+
+ while ( TRUE )
+ {
+ if(!DBE[Index].Element)
+ return ( 0 );
+ if(DBE[Index].Group == vr->Group)
+ if(DBE[Index].Element == vr->Element)
+ return ( Index );
+ ++Index;
+ }
+ return ( 0 );
+ }
+
+DBENTRY *
+FindDBE(VR *vr)
+ {
+ UINT Index;
+
+// NOT THREAD SAFE! :
+// if(LastADBE)
+// {
+// if(LastADBE->Group==vr->Group)
+// if(LastADBE->Element==vr->Element)
+// return(LastADBE);
+// }
+
+ Index = DBEIndex(ImageDB, vr);
+ if(Index)
+ return (&ImageDB[Index]);
+ else
+ {
+ if(ImageDB[Index].Group == vr->Group)
+ if(ImageDB[Index].Element == vr->Element)
+ return ( &ImageDB[Index] );
+ }
+
+ Index = DBEIndex(SeriesDB, vr);
+ if(Index)
+ return (&SeriesDB[Index]);
+ else
+ {
+ if(SeriesDB[Index].Group == vr->Group)
+ if(SeriesDB[Index].Element == vr->Element)
+ return ( &SeriesDB[Index] );
+ }
+
+ Index = DBEIndex(StudyDB, vr);
+ if(Index)
+ return (&StudyDB[Index]);
+ else
+ {
+ if(StudyDB[Index].Group == vr->Group)
+ if(StudyDB[Index].Element == vr->Element)
+ return ( &StudyDB[Index] );
+ }
+
+ Index = DBEIndex(PatientDB, vr);
+ if(Index)
+ return (&PatientDB[Index]);
+ else
+ {
+ if(PatientDB[Index].Group == vr->Group)
+ if(PatientDB[Index].Element == vr->Element)
+ return ( &PatientDB[Index] );
+ }
+
+ return ( NULL );
+ }
+
+
+VR *
+ConstructVRFromSQL (
+ DBENTRY *DBE,
+ UINT16 Group,
+ UINT16 Element,
+ UINT32 Length,
+ char *SQLResultString )
+ {
+ LE_UINT16 tuint16;
+ LE_UINT32 tuint32;
+ VR *vr = NULL;
+
+ SQLResultString[Length] = '\0';
+
+ if(Length&0x01)
+ ++Length;
+
+
+ switch ( DBE?DBE->DICOMType:DT_STR )
+ {
+ case DT_UI:
+ vr = new VR (Group, Element, Length, (BOOL) TRUE );
+ if(Length)
+ {
+ memset(vr->Data, 0, vr->Length);
+ memcpy(vr->Data, (void*)SQLResultString, strlen(SQLResultString));
+ }
+ break;
+ case DT_STR:
+ case DT_MSTR:
+ case DT_DATE:
+ vr = new VR (Group, Element, Length, (BOOL) TRUE );
+ if(Length)
+ {
+ memset(vr->Data, ' ', vr->Length);
+ memcpy(vr->Data, (void*)SQLResultString, strlen(SQLResultString));
+ }
+ break;
+ case DT_UINT16:
+ vr = new VR (Group, Element, 2, (BOOL) TRUE );
+ tuint16 = (LE_UINT16) atoi(SQLResultString);
+ memcpy(vr->Data, (void*)&tuint16, 2);
+#if NATIVE_ENDIAN != LITTLE_ENDIAN
+ swap((BYTE *)vr->Data, 2); // added swaps on 20100123
+#endif
+ break;
+ case DT_UINT32:
+ vr = new VR (Group, Element, 2, (BOOL) TRUE );
+ tuint32 = (LE_UINT32) atoi(SQLResultString);
+ memcpy(vr->Data, (void*)&tuint32, 4); // fix, was 2 before 20100123
+#if NATIVE_ENDIAN != LITTLE_ENDIAN
+ swap((BYTE *)vr->Data, 4);
+#endif
+ break;
+ case DT_FL:
+ {
+ vr = new VR (Group, Element, 2, (BOOL) TRUE );
+ float f = (float)atof(SQLResultString);//64 to 32 converstion, atof deprecated 1993.
+// float f = strtof(SQLResultString, (char **)NULL);
+ memcpy(vr->Data, (void*)&f, 4);
+#if NATIVE_ENDIAN != LITTLE_ENDIAN
+ swap((BYTE *)vr->Data, 4);
+#endif
+ break;
+ }
+ case DT_FD:
+ {
+ vr = new VR (Group, Element, 2, (BOOL) TRUE );
+ double d = atof(SQLResultString);
+ memcpy(vr->Data, (void*)&d, 8);
+#if NATIVE_ENDIAN != LITTLE_ENDIAN
+ swap((BYTE *)vr->Data, 8);
+#endif
+ break;
+ }
+ }
+ return ( vr );
+ }
+
+VR *
+ConstructAE ()
+ {
+ VR *vr = new VR( 0x0008, 0x0054, 16, (BOOL) TRUE );
+
+ memset(vr->Data, ' ', 16);
+ memcpy(vr->Data, MYACRNEMA, strlen((char*)MYACRNEMA)%16);
+ return ( vr );
+ }
+
diff --git a/deivr.cxx b/deivr.cxx
new file mode 100644
index 0000000..9c4e536
--- /dev/null
+++ b/deivr.cxx
@@ -0,0 +1,1322 @@
+/*
+19990318 ljz Added 'DICOMObject::DeleteVR'
+20001106 mvh Used delete [] operator for vr->Data
+20010426 ljz Fixed small leaks in 'DICOMObject::DeleteVR'
+20010730 ljz Added 'DICOMObject::ReplaceVR'. Is able to replace VRs inside
+ sequences.
+20010802 ljz Added 'VR::GetSpecialValueCodeOfVR'
+20011121 ljz Added VR_SPECIAL_RGB_TO_MONO. Used by a conversion-tool to change
+ ultrasound Kretz RGB images to monochrome that VariSeed (brachytherapy)
+ understands.
+20011121 ljz Added VR_SPECIAL_RGB_TO_MONO_PLUS. Same as above, but tries to preserve
+ colored drawings.
+20051217 mvh Added 'VR::ReAlloc'
+20051217 mvh Use malloc/free instead of new char[] and delete []
+20051229 mvh Removed unnecessary reset() in DeleteVR
+20071031 mvh Temp printf memory error messages
+20071102 mvh Send allocation errors to DicomError
+20080313 ljz Removed some warnings
+20080910 bcb Added VR::VR(UINT16 g, UINT16 e, UINT32 l, LE_UINT16 *d) &
+ VR::VR(UINT16 g, UINT16 e, UINT32 l, LE_UINT16 *d, BOOL mFlag)
+ for big endian.
+20081016 mvh Fix for WC: new of 0 gives NULL (check Length in error message)
+20090620 jf Added <stdlib.h>
+20091230 mvh Merged bcb bigendian change
+20100110 mvh And const change
+20100309 bcb Added double parentheses (gcc4.2 Warnings)
+20100619 bcb Fix gcc4 warnings and improve speed and added questions.
+20100717 mvh Merged except keep default ReleaseMemory to TRUE and check data when adjusitn length
+20100728 bcb Removed unused AutoMakeDO, added Get's to VR and DICOMObject.
+ Added ChangeVR's. Fixed LastVR & LastVRG?
+20100815 mvh Merged; fix VR constructors for failed malloc; added max parameter to GetCstring function
+ Moved defaults from implementation to header files
+20100826 mvh bcb moved another default, size_t
+20100901 mvh bcb changed alloc of US to 2
+20110231 mvh DicomError returns FALSE when handler not installed - to allow some errors to pass
+*/
+
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+# include "dicom.hpp"
+# include <stdlib.h> //DUCKHEAD92
+
+/********************************
+ *
+ * Error handler
+ *
+ ********************************/
+
+DeepErrorCall DicomErrorHandler = NULL;
+
+void SetDicomErrorHandler(DeepErrorCall handler)
+ {
+ DicomErrorHandler = handler;
+ }
+
+BOOL DicomError(int error, const char *message, int info)
+ {
+ if (DicomErrorHandler)
+ {
+ DicomErrorHandler(error, message, info);
+ return TRUE;
+ }
+ else
+ {
+ printf("DICOM ERROR ");
+ printf(message, info);
+ return FALSE;
+ }
+ }
+
+/********************************
+ *
+ * Base VR Type
+ *
+ ********************************/
+VR :: VR(UINT16 g, UINT16 e, UINT32 l, BOOL Alloc)
+#ifdef __GNUC__ //Faster with member initialization.
+:Group(g), Element(e), Length(l), Data(NULL), ReleaseMemory(TRUE),
+Valid(FALSE), SQObjectArray(NULL), ReferentialIntegrityDatabase(), TypeCode(0)
+{
+ BOOL cLast = FALSE;
+
+ if ( Length & 0x01 )
+ {
+ ++Length;
+ cLast = TRUE;
+ }
+
+ if(Alloc && Length)
+ {
+ Data = malloc(Length);
+ if (!Data) DicomError(DCM_ERROR_MEMORY, "VR: out of memory allocating %d bytes\n", Length);
+ if ( Data && cLast ) ((BYTE*)Data)[Length-1] = '\0';
+ }
+}
+#else
+{
+ BYTE *bptr = NULL;
+ BOOL cLast = FALSE;
+
+ if ( l & 0x01 )
+ {
+ ++l;
+ cLast = TRUE;
+ }
+
+
+ Group = g;
+ Element = e;
+ Length = l;
+ if(Alloc && Length)
+ {
+ Data = malloc(Length);
+ if (!Data) DicomError(DCM_ERROR_MEMORY, "VR: out of memory allocating %d bytes\n", Length);
+ if ( Data && cLast ) ((BYTE*)Data)[Length-1] = '\0';
+ }
+ else
+ Data = NULL;
+
+ ReleaseMemory = TRUE;
+ SQObjectArray = NULL;
+ TypeCode = 0;
+ Valid = FALSE;
+ }
+#endif
+
+VR :: VR(UINT16 g, UINT16 e, UINT32 l, LE_UINT16 *d)
+#ifdef __GNUC__ //Faster with member initialization.
+:Group(g), Element(e), Length(l), Data(d), ReleaseMemory(TRUE),
+Valid(FALSE), SQObjectArray(NULL), ReferentialIntegrityDatabase(), TypeCode(0)
+{
+#if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian like Apple power pc
+ *d = SwitchEndian((UINT16)*d);
+#endif //BigEndian
+}
+#else
+{
+ Group = g;
+ Element = e;
+ Length = l;
+ Data = d;
+#if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian like Apple power pc
+ *d = SwitchEndian((UINT16)*d);
+#endif //BigEndian
+ ReleaseMemory = TRUE;
+ SQObjectArray = NULL;
+ TypeCode = 0;
+ Valid = FALSE;
+}
+#endif
+
+VR :: VR(UINT16 g, UINT16 e, UINT32 l, LE_UINT16 *d, BOOL mFlag)
+#ifdef __GNUC__ //Faster with member initialization.
+:Group(g), Element(e), Length(l), Data(d), ReleaseMemory(mFlag),
+Valid(FALSE), SQObjectArray(NULL), ReferentialIntegrityDatabase(), TypeCode(0)
+{
+#if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian like Apple power pc
+ *d = SwitchEndian((UINT16)*d);
+#endif //BigEndian
+}
+#else
+{
+ Group = g;
+ Element = e;
+ Length = l;
+ Data = d;
+#if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian like Apple power pc
+ *d = SwitchEndian((UINT16)*d);
+#endif //BigEndian
+ ReleaseMemory = mFlag;
+ SQObjectArray = NULL;
+ TypeCode = 0;
+ Valid = FALSE;
+}
+#endif
+
+VR :: VR(UINT16 g, UINT16 e, UINT32 l, void *d)
+#ifdef __GNUC__ //Faster with member initialization.
+:Group(g), Element(e), Length(l), Data(d), ReleaseMemory(TRUE),
+Valid(FALSE), SQObjectArray(NULL), ReferentialIntegrityDatabase(), TypeCode(0)
+{
+}
+#else
+{
+
+ BYTE *bptr = NULL;
+ BOOL cLast = FALSE;
+
+/* if ( l & 0x01 )
+ {
+ ++l;
+ cLast = TRUE;
+ }*/
+
+ Group = g;
+ Element = e;
+ Length = l;
+// if(Length&1)
+// ++Length;
+ Data = d;
+ if ( cLast )
+ {
+ bptr = (BYTE*)Data;
+ bptr[Length-1] = '\0';
+ }
+ ReleaseMemory = TRUE;
+ SQObjectArray = NULL;
+ TypeCode = 0;
+ Valid = FALSE;
+}
+#endif
+
+VR :: VR(UINT16 g, UINT16 e, UINT32 l, void *d, BOOL mFlag)
+#ifdef __GNUC__ //Faster with member initialization.
+:Group(g), Element(e), Length(l), Data(d), ReleaseMemory(mFlag),
+Valid(FALSE), SQObjectArray(NULL), ReferentialIntegrityDatabase(), TypeCode(0)
+{
+}
+#else
+{
+ Group = g;
+ Element = e;
+ Length = l;
+ Data = d;
+ ReleaseMemory = mFlag;
+ SQObjectArray = NULL;
+ TypeCode = 0;
+ Valid = FALSE;
+}
+#endif
+VR :: ~VR()
+{
+ Array<DICOMObject *> *ArrayDO;
+/*
+ printf("~VR()\n\tGroup = %4.4x Element = %4.4x Data = %x Length = %d\n",
+ Group, Element, Data, Length);
+ printf("\tReleasememory = %d, SQObjectArray = %x, RID = %x Valid = %d\n",
+ ReleaseMemory, SQObjectArray, ReferentialIntegrityDatabase, Valid);
+ fflush(stdout);
+*/
+ if(ReleaseMemory)
+ if(Data)
+// delete [] Data;
+ free(Data);
+ if(SQObjectArray)
+ {
+ ArrayDO = (Array<DICOMObject *> *) SQObjectArray;
+ while(ArrayDO->GetSize())
+ {
+ delete ArrayDO->Get(0);
+ ArrayDO->RemoveAt(0);
+ }
+ delete ArrayDO;
+ SQObjectArray = NULL;
+ }
+}
+
+UINT VR :: operator > (VR &vr)
+{
+ if(Group > vr.Group)
+ return ( 1 );
+ if(Group == vr.Group)
+ {
+ if(Element > vr.Element)
+ return ( 1 );
+ }
+ return ( 0 );
+}
+
+UINT VR :: operator < (VR &vr)
+{
+ if(Group < vr.Group)
+ return ( 1 );
+ if(Group == vr.Group)
+ {
+ if(Element < vr.Element)
+ return ( 1 );
+ }
+ return ( 0 );
+}
+
+UINT VR :: operator == (VR &vr)
+{
+ if(Group == vr.Group)
+ if(Element == vr.Element)
+ return ( 1 );
+ return ( 0 );
+}
+
+/*****************************************************
+ *
+ * VR Group P-Queues
+ *
+ *****************************************************/
+
+BOOL VRGroupPQueue :: Push(VR *vr)
+{
+// printf("[VRGroupPQueue : Push(%x)]\n", vr);
+ if(vr->Group!=Group)
+ return ( FALSE );
+ Length += vr->Length + sizeof(UINT16) + sizeof(UINT16) + sizeof(UINT32);
+ if(vr->Length&0x01)
+ ++Length; // Transfer Syntax Encodeder will +1 here
+ PQueueOfPtr<VR *> :: Push ( vr );
+ return ( TRUE );
+}
+
+VR * VRGroupPQueue :: Pop()
+{
+ VR *tv;
+
+// printf("[VRGroupPQueue : Pop()]\n");
+ if ( !PQueueOfPtr<VR *> :: GetSize())
+ return ( (VR *) NULL );
+ tv = PQueueOfPtr<VR *> :: Pop ();
+ if(!tv)
+ return ( tv );
+ Length -= (tv->Length + sizeof(UINT16) + sizeof(UINT16) + sizeof(UINT32));
+ if(tv->Length&0x01)
+ --Length; // See Push
+ return ( tv );
+}
+
+VR * VRGroupPQueue :: GroupLength()
+{
+ LE_UINT32 *puint32;
+
+ Element0 = new VR ( Group, 0x0000, 4, TRUE);
+ if(!Element0)
+ return ( NULL );
+ puint32 = (LE_UINT32 *) Element0->Data;
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ (*puint32) = (LE_UINT32) Length;// + sizeof(UINT16) + sizeof(UINT16) + sizeof(UINT32) + sizeof(UINT32);
+#else //Big Endian like Apple power pc
+ (*puint32) = (LE_UINT32)SwitchEndian((UINT32) Length);// + sizeof(UINT16) + sizeof(UINT16) + sizeof(UINT32) + sizeof(UINT32);
+#endif
+ Element0->TypeCode = 'UL';
+ return ( Element0 );
+}
+
+UINT VRGroupPQueue :: operator > (VRGroupPQueue &vrgroup)
+{
+ if(Group > vrgroup.Group)
+ return ( 1 );
+ return ( 0 );
+}
+
+UINT VRGroupPQueue :: operator < (VRGroupPQueue &vrgroup)
+{
+ if(Group < vrgroup.Group)
+ return ( 1 );
+ return ( 0 );
+}
+
+UINT VRGroupPQueue :: operator == (VRGroupPQueue &vrgroup)
+{
+ if(Group == vrgroup.Group)
+ return ( 1 );
+ return ( 0 );
+}
+
+/*****************************************************
+ *
+ * DICOM Objects
+ *
+ *****************************************************/
+
+DICOMObject :: DICOMObject()
+#ifdef __GNUC__ //Faster with member initialization.
+:CurrentGroup(), LastVRG(NULL), LastVR(NULL), LastGroup(0), LastElement(0),
+Length(0), Packaged(FALSE), VRGroupPQueues(),SQObjectArray(NULL),
+FreeSQObjectSize(0), FixedSize(0), UseFixedSize(FALSE)
+{
+ VRGroupPQueues.ClearType = FALSE;
+}
+#else
+{
+ Packaged = FALSE;
+ Length = 0;
+ VRGroupPQueues.ClearType = FALSE;
+ SQObjectArray = NULL;
+ LastVR = NULL;
+ LastVRG = NULL;
+ FreeSQObjectSize = 0;
+ FixedSize = 0;
+ UseFixedSize = FALSE;
+}
+#endif
+
+DICOMObject :: ~DICOMObject()
+{
+ VR *VRPtr;
+
+ if ( !Packaged)
+ if ( !Package() )
+ return;
+
+ if ( Packaged )
+ {
+ while (( VRPtr = this->Pop()))
+ delete VRPtr;
+ return;
+ }
+ while ( VRGroupPQueues.GetSize() )
+ VRGroupPQueues.RemoveAt(0);
+}
+
+//Only used in ParseRaw and unused Morph functions, LastVR & LastVRG should be valid at this point.
+BOOL DICOMObject :: Push(DICOMObject *SQDO)
+{
+ Array<DICOMObject *> *ArrayPtr;
+
+ if ( Packaged )
+ return ( FALSE );
+
+ if ( ! LastVR || !LastVRG )//bcb Both used, check both.
+ {
+ return ( FALSE ); // not-supported yet
+ if (!SQObjectArray)
+ {
+ SQObjectArray = new Array<DICOMObject *>;
+ if ( !SQObjectArray )
+ return ( FALSE );
+ }
+ SQObjectArray->Add ( SQDO );
+ FreeSQObjectSize += SQDO->Length;
+ return ( TRUE );
+ }
+ if (!LastVR->SQObjectArray)
+ {
+ ArrayPtr = new Array<DICOMObject *>;
+ if (!ArrayPtr)
+ return ( FALSE );
+ LastVR->SQObjectArray = (void *) ArrayPtr;
+ // "new sequence"
+ LastVRG->Length += (2 * (sizeof(UINT16) + sizeof(UINT16) +
+ sizeof(UINT32) ));
+ Length += (2 * (sizeof(UINT16) + sizeof(UINT16) +
+ sizeof(UINT32) ));
+ }
+ ArrayPtr = (Array<DICOMObject *> *) LastVR->SQObjectArray;
+ ArrayPtr->Add ( SQDO );
+ LastVRG->Length += SQDO->Length +
+ (2 * (sizeof(UINT16) + sizeof(UINT16) + sizeof(UINT32)));
+ Length += SQDO->Length +
+ (2 * (sizeof(UINT16) + sizeof(UINT16) + sizeof(UINT32)));
+ return ( TRUE );
+}
+
+BOOL DICOMObject :: Push(VR *vr)
+{
+ UINT Index;
+ VRGroupPQueue *VRGroupPQueuePtr;
+
+// printf("[Push]\n");
+ if ( Packaged )
+ return ( FALSE ); // already Pop() from this object
+
+ if(vr->Length == 0xffffffff)
+ {
+// fprintf(stdout, "Attemping to push -1 length\n");
+ vr->Length = 0;
+ }
+
+ Index = 0;
+ if(vr->Element == 0x0000)
+ {
+// fprintf(stderr, "Attemping to push GLC: %d\n",
+// (*((UINT32 *) vr->Data)));
+ delete vr;
+ return ( TRUE ); // ignore Group Length Codes (auto calculated)
+ }
+ LastVR = vr;
+
+ if(LastVRG)
+ if(LastVRG->Group == vr->Group) // Faster, no need to search again
+ {
+ Length += vr->Length + sizeof(UINT16) + sizeof(UINT16) +
+ sizeof(UINT32);
+ if(vr->Length&0x01)
+ ++Length;
+ return ( LastVRG->Push ( vr ));
+ }
+ while ( Index < VRGroupPQueues.GetSize())
+ {
+ VRGroupPQueuePtr = VRGroupPQueues.Get(Index);
+ if(!VRGroupPQueuePtr)
+ return ( FALSE );
+ if(VRGroupPQueuePtr->Group == vr->Group)
+ {
+ LastVRG = VRGroupPQueuePtr; // If we do the same group again, faster.
+ Length += vr->Length + sizeof(UINT16) + sizeof(UINT16) +
+ sizeof(UINT32);
+ if(vr->Length&0x01)
+ ++Length;
+// printf("[VRGroupPQueuePtr->Group : %d]\n", VRGroupPQueuePtr->Group);
+ return ( VRGroupPQueuePtr->Push ( vr ));
+ }
+ ++Index;
+ }
+
+ VRGroupPQueuePtr = new VRGroupPQueue(vr->Group);
+ if(!VRGroupPQueuePtr)
+ return ( FALSE );
+
+ Length += sizeof(UINT16) + sizeof(UINT16) + sizeof(UINT32) +
+ sizeof(UINT32);
+ Length += vr->Length + sizeof(UINT16) + sizeof(UINT16) +
+ sizeof(UINT32);
+ if(vr->Length&0x01)
+ ++Length;
+ LastVRG = VRGroupPQueuePtr;
+// printf("[VRGroupPQueues.Push]\n");
+ VRGroupPQueues.Add(VRGroupPQueuePtr);
+ return ( VRGroupPQueuePtr->Push(vr) );
+}
+
+VR * DICOMObject :: Pop()
+{
+ VR *VRPtr;
+
+ //return ( (VR *) NULL );
+
+ if(!Packaged)
+ if(!Package())
+ return ( (VR *) NULL );
+ if(!Packaged)
+ return ( (VR *) NULL );
+
+ if ( ! CurrentGroup )
+ {
+// printf("[Pop : CurrentGroup = NULL]\n");
+ if ( !PQueueOfPtr<VRGroupPQueue *>::GetSize())
+ {
+ Packaged = FALSE;
+ LastVRG = NULL;
+ LastVR = NULL;
+ return ( (VR *) NULL );
+ }
+ CurrentGroup = PQueueOfPtr<VRGroupPQueue *>::Pop();
+ if ( ! CurrentGroup )
+ return ( (VR *) NULL );
+ Length -= ( sizeof(UINT16) + sizeof(UINT16) + sizeof(UINT32) +
+ sizeof(UINT32) );
+
+ return ( CurrentGroup->GroupLength() );
+ }
+ if ( ! ( VRPtr = CurrentGroup->Pop() ) )
+ {
+ delete CurrentGroup;
+ CurrentGroup = NULL;
+ return ( this->Pop() );
+ }
+ Length -= (VRPtr->Length + sizeof(UINT16) + sizeof(UINT16) +
+ sizeof(UINT32) );
+ if(VRPtr->Length&0x01)
+ --Length; // See Push
+ return ( VRPtr );
+}
+
+// this needs to be replaced with a more efficient algorithm in the
+// future, but it will do for now.
+VR *DICOMObject :: GetVR(UINT16 g, UINT16 e)
+{
+ VR *vr;
+ UINT Index,Index2;
+ VRGroupPQueue *VRGroupPQueuePtr;
+
+ Index = 0;
+
+ while ( Index < VRGroupPQueues.GetSize())
+ {
+ VRGroupPQueuePtr = VRGroupPQueues.Get(Index);
+ if(!VRGroupPQueuePtr)
+ return ( FALSE );
+ if(VRGroupPQueuePtr->Group == g)
+ {
+ Index2 = 0;
+ while ( Index2 < VRGroupPQueuePtr->GetSize() )
+ {
+ vr = VRGroupPQueuePtr->Get(Index2);
+ if(!vr)
+ return ( 0 );
+ if(vr->Element == e)
+ {
+ return ( vr );
+ }
+ ++Index2;
+ }
+ return ( NULL );
+ }
+ ++Index;
+ }
+ return ( NULL );
+}
+
+/* bcb replaced by byte order independent versions
+LE_UINT16 DICOMObject :: GetUINT16(UINT16 g, UINT16 e)
+{
+ VR *vr;
+ LE_UINT16 Val;
+
+ vr = this->GetVR ( g, e );
+ if(!vr)
+ return(0);
+
+ if ( vr->Data )
+ if(vr->Length == sizeof(UINT16))
+ {
+ memcpy(&Val, vr->Data, 2);
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ return ( Val );
+#else //Big Endian like Apple power pc
+ return (SwitchEndian((UINT16) Val ));
+#endif //Big Endian
+ }
+ return ( 0 );
+}*/
+
+// Will return the first byte from LE data, independent of vr->Length
+UINT8 DICOMObject :: GetBYTE(UINT16 g, UINT16 e)
+{
+ VR *vr;
+ UINT8 value = 0;
+
+ vr = this->GetVR ( g, e );
+ if(!vr || !vr->Length) return(0);
+
+ if(vr->Data) value = ((unsigned char *)vr->Data)[0];
+ return(value);
+}
+
+// Will return a short from LE data, independent of vr->Length
+UINT16 DICOMObject :: GetUINT16(UINT16 g, UINT16 e)
+{
+ VR *vr;
+ UINT16 value = 0;
+
+ vr = this->GetVR ( g, e );
+ if(!vr || !vr->Length) return(0);
+
+ if(vr->Data)
+ {
+ if (vr->Length > 1) value = ((unsigned char *)vr->Data)[1] << 8;
+ value += ((unsigned char *)vr->Data)[0];
+ }
+ return(value);
+}
+
+// Will return a 32 bit integer from LE data, independent of vr->Length
+UINT DICOMObject :: GetUINT(UINT16 g, UINT16 e)
+{
+ VR *vr;
+ INT cnt;
+ UINT value = 0;
+
+ vr = this->GetVR ( g, e );
+ if(!vr || !vr->Length) return(0);
+
+ cnt = vr->Length - 1;
+
+ if(vr->Data)
+ {
+ if (cnt > 3) cnt = 3;
+ for(;cnt >= 0;--cnt)
+ {
+ value <<= 8;
+ value += ((unsigned char *)vr->Data)[cnt];
+ }
+ }
+ return(value);
+}
+
+// Will return a 64 bit integer from LE data, independent of vr->Length
+unsigned long long DICOMObject :: GetULongLong(UINT16 g, UINT16 e)
+{
+ VR *vr;
+ unsigned long long value = 0;
+ INT cnt;
+
+ vr = this->GetVR ( g, e );
+ if(!vr || !vr->Length) return(0);
+
+ cnt = vr->Length - 1;
+
+ if(vr->Data)
+ {
+ if (cnt > 7) cnt = 7;
+ for(;cnt >= 0;--cnt)
+ {
+ value <<= 8;
+ value += ((unsigned char *)vr->Data)[cnt];
+ }
+ }
+ return(value);
+}
+
+// Will return a 32 bit integer from Ascii, with integer vr->Length the first 10 chars (max for 32 bits anyway).
+INT DICOMObject :: Getatoi(UINT16 g, UINT16 e)
+{
+ VR *vr;
+ INT cnt, value = 0;
+ char s[11];
+
+ vr = this->GetVR ( g, e );
+ if(!vr || !vr->Length) return(0);
+
+ cnt = vr->Length;
+ if(cnt > 10) cnt = 10;
+
+ if(vr->Data)
+ {
+ strncpy(s, (const char*)vr->Data, cnt);
+ s[cnt] = 0;
+ value = atoi(s);
+ }
+ return(value);
+}
+
+
+// This will allocate this string, do not forget to free it.
+char * DICOMObject :: GetCString(UINT16 g, UINT16 e, size_t max)
+{
+ VR *vr;
+ size_t cnt;
+ char *s;
+
+ vr = this->GetVR ( g, e );
+ if(!vr || !vr->Length || !vr->Data) return(NULL);
+
+ cnt = vr->Length - 1;
+ if(((char*)vr->Data)[cnt] != 0 || ((char*)vr->Data)[cnt] != ' ') cnt++;
+
+ if(cnt > max) cnt = max;// Long enough
+
+ if(!(s = (char*)malloc(cnt + 1))) return(NULL);// Maybe return -1?
+ strncpy(s, (const char*)vr->Data, cnt);
+ s[cnt] = 0;// End the string
+
+ return(s);
+}
+
+//Fixed LastVR & LastVRG, still worry about CurrentGroup.
+BOOL DICOMObject::DeleteVR(VR* pVR)
+{
+ VR *vr;
+ UINT Index,Index2;
+ VRGroupPQueue *VRGroupPQueuePtr;
+
+ if ( Packaged )
+ return ( FALSE ); // already Pop() from this object
+
+ /* Search the pVR */
+ Index = 0;
+ while ( Index < VRGroupPQueues.GetSize())
+ { VRGroupPQueuePtr = VRGroupPQueues.Get(Index);
+ if(!VRGroupPQueuePtr)
+ return FALSE;
+
+ if(VRGroupPQueuePtr->Group == pVR->Group)
+ { Index2 = 0;
+ while ( Index2 < VRGroupPQueuePtr->GetSize() )
+ { vr = VRGroupPQueuePtr->Get(Index2);
+ if(!vr)
+ return FALSE;
+
+ if(vr->Element == pVR->Element)
+ { /* OK, the pVR has been found.
+ Remove from Array of VrPointers */
+ VRGroupPQueuePtr->RemoveAt(Index2);
+
+ VRGroupPQueuePtr->Length -= (pVR->Length + sizeof(UINT16) + sizeof(UINT16) +
+ sizeof(UINT32) );
+ if (VRGroupPQueuePtr->Length & 0x01)
+ VRGroupPQueuePtr->Length--;
+
+ Length -= (pVR->Length + sizeof(UINT16) + sizeof(UINT16) +
+ sizeof(UINT32) );
+ if (Length & 0x01)
+ Length--;
+
+ // Maybe remove from Array of GroupPointers.
+ if (!VRGroupPQueuePtr->Length)
+ { VRGroupPQueues.RemoveAt(Index);
+ delete VRGroupPQueuePtr; // LJ: leak
+ Length -= (sizeof(UINT16) + sizeof(UINT16) + sizeof(UINT32));
+ LastVRG = NULL; // bcb: Fix invalid pointer
+ }
+
+ // Get rid of the data.
+ delete vr; // LJ: leak
+ LastVR = NULL; // bcb: Crash fix.
+ return TRUE;
+ }
+ ++Index2;
+ }
+ return FALSE;
+ }
+ ++Index;
+ }
+ return FALSE;
+}
+
+BOOL DICOMObject::ReplaceVR(VR* pVR)
+{
+ VR* vr;
+ UINT Index, Index1, Index2;
+ VRGroupPQueue* VRGroupPQueuePtr;
+ Array<DICOMDataObject*>* pADDO;
+
+ if ( Packaged )
+ return ( FALSE ); // already Pop() from this object
+ /* Search the pVR */
+ Index = 0;
+ while ( Index < VRGroupPQueues.GetSize())
+ { VRGroupPQueuePtr = VRGroupPQueues.Get(Index);
+ if(!VRGroupPQueuePtr)
+ return FALSE;
+ Index1 = 0;
+ while ( Index1< VRGroupPQueuePtr->GetSize() )
+ { vr = VRGroupPQueuePtr->Get(Index1);
+ if(!vr)
+ return FALSE;
+ if (vr->SetIf(pVR))
+ { /* OK, the pVR has been found */
+ }
+ else if (vr->SQObjectArray)
+ { /* Loop over all DICOMDataObjects in this sequence */
+ pADDO = (Array<DICOMDataObject*>*)vr->SQObjectArray;
+ Index2 = 0;
+ while (Index2< pADDO->GetSize())
+ { pADDO->Get(Index2)->ReplaceVR(pVR);
+ ++Index2;
+ }
+ }
+ ++Index1;
+ }
+ ++Index;
+ }
+ return FALSE;
+}
+// The ChangeVRs are cleaner than the ReplaceVR and do not require delete vr,
+// they return a 0 if failed,
+// a 1 if replaced,
+// a 2 if created.
+// For a string, it must end in a 0 ( standard c string ).
+INT DICOMObject :: ChangeVR(UINT16 g, UINT16 e, const char * str, UINT16 type, BOOL space)
+{
+ VR *vr;
+ UINT slen;
+ INT rc = 1;
+
+ slen = strlen(str);// Remove the end
+ vr = this->GetVR( g, e );
+ if(!vr)
+ {
+ vr = new VR( g, e, slen, TRUE);
+ if(!vr)return(0);
+ rc = 2;
+ vr->TypeCode = type;
+ this->Push(vr);
+ }
+ else
+ {
+ if(!vr->ReAlloc(slen))return(0);
+ }
+ memcpy(vr->Data, str, slen);
+ if(slen & 1)
+ {
+ if(space) ((char *)vr->Data)[slen] = ' ';
+ else ((char *)vr->Data)[slen] = 0;
+ }
+ return(rc);
+}
+
+INT DICOMObject :: ChangeVR(UINT16 g, UINT16 e, UINT8 val, UINT16 type = 0)
+{
+ VR *vr;
+ INT rc = 1;
+
+ vr = this->GetVR( g, e );
+ if(!vr)
+ {
+ vr = new VR( g, e, 2, TRUE);
+ if(!vr)return(0);
+ rc = 2;
+ vr->TypeCode = type;
+ this->Push(vr);
+ }
+ else
+ {
+ if(vr->Length != 2 || !vr->ReAlloc(2))return(0);
+ }
+
+ *(UINT8 *)vr->Data = val;
+ ((UINT8 *)vr->Data)[1] = 0;
+ return(rc);
+}
+
+INT DICOMObject :: ChangeVR(UINT16 g, UINT16 e, UINT16 val, UINT16 type = 0)
+{
+ VR *vr;
+ INT rc = 1;
+
+ vr = this->GetVR( g, e );
+ if(!vr)
+ {
+ vr = new VR( g, e, 2, TRUE);
+ if(!vr)return(0);
+ rc = 2;
+ vr->TypeCode = type;
+ this->Push(vr);
+ }
+ else
+ {
+ if(vr->Length != 2 || !vr->ReAlloc(2))return(0);
+ }
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ *(UINT16 *)vr->Data = val;
+#else //Big Endian like Apple power pc
+ *(UINT16 *)vr->Data = SwitchEndian(val);
+#endif
+ return(rc);
+}
+
+INT DICOMObject :: ChangeVR(UINT16 g, UINT16 e, UINT val, UINT16 type = 0)
+{
+ VR *vr;
+ INT rc = 1;
+
+ vr = this->GetVR( g, e );
+ if(!vr)
+ {
+ vr = new VR( g, e, 4, TRUE);
+ if(!vr)return(0);
+ vr->TypeCode = type;
+ rc = 2;
+ this->Push(vr);
+ }
+ else
+ {
+ if(vr->Length != 4 || !vr->ReAlloc(4))return(0);
+ }
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ *(UINT *)vr->Data = val;
+#else //Big Endian like Apple power pc
+ *(UINT *)vr->Data = SwitchEndian(val);
+#endif
+ return(rc);
+}
+
+
+BOOL DICOMObject :: Reset()
+{
+ VR *vr;
+
+ while (( vr = Pop() ))
+ delete vr;
+
+ LastVRG = NULL;
+ LastVR = NULL;
+
+ return ( TRUE );
+}
+
+
+BOOL DICOMObject :: Package()
+{
+ UINT Index;
+
+ CurrentGroup = NULL;
+ Index = 0;
+// printf("[start: Package()]\n");
+ while ( Index < VRGroupPQueues.GetSize())
+ {
+ PQueueOfPtr<VRGroupPQueue *> :: Push (VRGroupPQueues.Get(Index) );
+ ++Index;
+ }
+ while ( VRGroupPQueues.GetSize() )
+ VRGroupPQueues.RemoveAt(0);
+
+// printf("[Packaged : %d Groups]\n", Index);
+ Packaged = TRUE;
+ if ( Index )
+ return ( TRUE );
+ Packaged = FALSE;
+ return ( FALSE );
+}
+
+
+#define VR_SPECIAL_NONE 0x00
+#define VR_SPECIAL_FIX_TMS 0x01
+#define VR_SPECIAL_RGB_TO_MONO 0x02
+#define VR_SPECIAL_RGB_TO_MONO_PLUS 0x03
+#define VR_SPECIAL_UNKNOWN 0xFF
+
+int VR::GetSpecialValueCodeOfVR(VR* pVR)
+{ char* pcData;
+
+ /* This private function is called by SetIf.
+ It analyzes the data of the VR. If it contains a special code, a string between
+ '[[' and ']]', it will return the code; otherwise zero.
+ */
+ if ((pVR->Length < 4) || (!pVR->Data))
+ return VR_SPECIAL_NONE;
+ pcData = (char*)pVR->Data;
+ if ((pcData[0] != '[') || (pcData[1] != '['))
+ return VR_SPECIAL_NONE;
+
+ if ((pVR->Length == 12) && (strncmp(pcData, "[[FIX_TMS]]", 11) == 0))
+ return VR_SPECIAL_FIX_TMS;
+ if ((pVR->Length == 20) && (strncmp(pcData, "[[RGB_TO_MONO_PLUS]]", 20) == 0))
+ return VR_SPECIAL_RGB_TO_MONO_PLUS;
+ if ((pVR->Length == 16) && (strncmp(pcData, "[[RGB_TO_MONO]]", 15) == 0))
+ return VR_SPECIAL_RGB_TO_MONO;
+
+ return VR_SPECIAL_UNKNOWN;
+}
+
+
+BOOL VR::SetIf(VR *vr)
+{ Array<DICOMObject*> *ArrayDO;
+ int i, iSecialCodeOfVR;
+ BOOL rc = FALSE;
+ char* pCopy;
+ unsigned char* pRGB;
+ unsigned char* pMono;
+ int iNewLength;
+ int iNewValue, iPad = 0;
+
+ if (!vr)
+ return rc;
+ if ((vr->Group==Group) && (vr->Element==Element))
+ {
+ iSecialCodeOfVR = GetSpecialValueCodeOfVR(vr);
+ switch (iSecialCodeOfVR)
+ { case VR_SPECIAL_NONE:
+ /* Just replace the VR */
+ if(ReleaseMemory)
+// delete [] Data;
+ free(Data);
+ if(SQObjectArray)
+ { ArrayDO = (Array<DICOMObject *> *) SQObjectArray;
+ while(ArrayDO->GetSize())
+ { delete ArrayDO->Get(0);
+ ArrayDO->RemoveAt(0);
+ }
+ delete ArrayDO;
+ SQObjectArray = NULL;
+ }
+ Length = vr->Length;
+ if (vr->Length)
+ { Data = malloc(vr->Length);
+ if (!Data) DicomError(DCM_ERROR_MEMORY, "VR:SetIf out of memory allocating %d bytes\n", Length);
+ memcpy(Data, vr->Data, vr->Length);
+ ReleaseMemory = TRUE;
+ }
+ else
+ ReleaseMemory = FALSE;
+ rc = TRUE;
+ break;
+
+ case VR_SPECIAL_FIX_TMS:
+ /* Change PatientName like 'LastName^FirstName^MiddleName' into
+ 'LastName,FirstName,MiddleName'.
+ */
+ if (Length > 0)
+ { pCopy = (char*)malloc(Length+2);
+ if (!pCopy) DicomError(DCM_ERROR_MEMORY, "VR:SetIf out of memory allocating %d bytes\n", Length+2);
+ memcpy(pCopy, (char*)Data, Length);
+ pCopy[Length] = 0;
+ /* Maybe padded with a space */
+ if ((pCopy[Length-1] == ' ') || (pCopy[Length-1] == '^'))
+ pCopy[Length-1] = 0;
+ if ((Length > 1) && (pCopy[Length-2] == '^'))
+ pCopy[Length-2] = 0;
+ for (i=0; i<(int)(strlen(pCopy)); i++)
+ if (pCopy[i] == '^')
+ pCopy[i] = ',';
+ /* May pad it again */
+ if (strlen(pCopy) & 0x01)
+ strcat(pCopy, " ");
+ strncpy((char*)Data, pCopy, strlen(pCopy));
+ Length = strlen(pCopy);
+ free(pCopy);
+ }
+ rc = TRUE;
+ break;
+
+ case VR_SPECIAL_RGB_TO_MONO:
+ /* Convert triplets of bytes to just bytes (the mean of the RGB channels) */
+ if (Length >= 3)
+ { iNewLength = Length / 3;
+ if (iNewLength & 0x01)
+ iPad = 1;
+ pMono = (unsigned char*)malloc(iNewLength + iPad);
+ if (!pMono) DicomError(DCM_ERROR_MEMORY, "VR:SetIf out of memory allocating %d bytes\n", iNewLength + iPad);
+ pRGB = (unsigned char*)Data;
+ for (i=0; i<iNewLength; i++)
+ { iNewValue = (pRGB[i * 3] + pRGB[i * 3 + 1] + pRGB[i * 3 + 2]) / 3;
+ pMono[i] = (unsigned char)iNewValue;
+ }
+ if (iPad)
+ pMono[iNewLength] = 0;
+ Length = iNewLength + iPad;
+ free(Data);
+ Data = pMono;
+ }
+ rc = TRUE;
+ break;
+
+ case VR_SPECIAL_RGB_TO_MONO_PLUS:
+ /* Convert triplets of bytes to just bytes only when the value of those three
+ are equal (a B&W image). However, 'real' color (contours e.g.) are converted
+ to very white (255).
+ */
+ if (Length >= 3)
+ { iNewLength = Length / 3;
+ if (iNewLength & 0x01)
+ iPad = 1;
+ pMono = (unsigned char*)malloc(iNewLength + iPad);
+ if (!pMono) DicomError(DCM_ERROR_MEMORY, "VR:SetIf out of memory allocating %d bytes\n", iNewLength + iPad);
+ pRGB = (unsigned char*)Data;
+ for (i=0; i<iNewLength; i++)
+ { if ((pRGB[i * 3] == pRGB[i * 3 + 1]) && (pRGB[i * 3] == pRGB[i * 3 + 2]))
+ pMono[i] = pRGB[i * 3];
+ else
+ pMono[i] = 255;
+ }
+ if (iPad)
+ pMono[iNewLength] = 0;
+ Length = iNewLength + iPad;
+ free(Data);
+ Data = pMono;
+ }
+ rc = TRUE;
+ break;
+ }
+ }
+ return rc;
+}
+
+
+/* Just not used
+BOOL
+VR :: Morph (
+ DICOMObject *DDO)
+ {
+ Array<DICOMObject *> *ArrayDO;
+
+ if (!Length)
+ if(!Valid)
+ return ( FALSE );
+
+ VR *vr = new VR(Group, Element, 0, (BOOL) FALSE);
+ vr->Length = Length;
+ vr->Data = Data;
+ vr->ReleaseMemory = ReleaseMemory;
+ Length = 0;
+ Data = NULL;
+ ReleaseMemory = FALSE;
+ DDO->Push(vr);
+
+ if(SQObjectArray)
+ {
+ ArrayDO = (Array<DICOMObject *> *) SQObjectArray;
+ while(ArrayDO->GetSize())
+ {
+ DDO->Push(ArrayDO->Get(0));
+ ArrayDO->RemoveAt(0);
+ }
+ delete ArrayDO;
+ SQObjectArray = NULL;
+ }
+ return ( TRUE );
+ }*/
+
+BOOL
+VR :: Reset ()
+ {
+ Array<DICOMObject *> *ArrayDO;
+
+ if(ReleaseMemory)
+ if(Data)
+// delete [] Data;
+ free(Data);
+ if(SQObjectArray)
+ {
+ ArrayDO = (Array<DICOMObject *> *) SQObjectArray;
+ while(ArrayDO->GetSize())
+ {
+ delete ArrayDO->Get(0);
+ ArrayDO->RemoveAt(0);
+ }
+ delete ArrayDO;
+ SQObjectArray = NULL;
+ }
+ ReleaseMemory = FALSE;
+ Data = NULL;
+ Length = 0;
+ return ( TRUE );
+ }
+
+
+BOOL
+VR :: ReAlloc (UINT32 N)
+ {
+ Reset();
+
+ if (N&1) N++;
+ ReleaseMemory = TRUE;
+ Data = malloc(N);
+ if (!Data) DicomError(DCM_ERROR_MEMORY, "VR:ReAlloc out of memory allocating %d bytes\n", N);
+ Length = N;
+ return ( Data!=NULL );
+ }
+
+// Will return an unsigned short from LE data, independent of vr->Length
+UINT16
+VR :: GetUINT16()
+{
+ UINT16 value;
+
+ value = 0;
+
+ if(Data)
+ {
+ if (Length > 1)value = ((unsigned char *)Data)[1] << 8;
+ value += ((unsigned char *)Data)[0];
+ }
+ return(value);
+}
+
+// Will return a 32 bit interger from LE data, independent of vr->Length
+UINT
+VR :: GetUINT()
+{
+ INT cnt;
+ UINT value = 0;
+
+ cnt = Length - 1;
+
+ if(Data)
+ {
+ if (cnt > 3) cnt = 3;
+ for(;cnt >= 0;--cnt)
+ {
+ value <<= 8;
+ value += ((unsigned char *)Data)[cnt];
+ }
+ }
+ return(value);
+}
+
+// Will return an unsigned 64 bit interger from LE data, independent of vr->Length
+unsigned long long
+VR :: GetULongLong()
+{
+ unsigned long long value;
+ INT cnt;
+
+ cnt = Length - 1;
+ value = 0;
+
+ if(Data)
+ {
+ if (cnt > 7) cnt = 7;
+ for(;cnt >= 0;--cnt)
+ {
+ value <<= 8;
+ value += ((unsigned char *)Data)[cnt];
+ }
+ }
+ return(value);
+}
+
+// Will return an 32 bit interger from Ascii, with interger vr->Length or shorter.
+INT
+VR :: Getatoi()
+{
+ INT cnt, value = 0;
+ char s[11];
+
+ cnt = Length;
+ if(cnt > 10) cnt = 10;
+
+ if(cnt && Data)
+ {
+ strncpy(s, (const char*)Data,cnt);
+ s[cnt] = 0;
+ value = atoi(s);
+ }
+ return(value);
+}
diff --git a/deivr.hpp b/deivr.hpp
new file mode 100644
index 0000000..851befe
--- /dev/null
+++ b/deivr.hpp
@@ -0,0 +1,184 @@
+/*
+19990318 ljz Added 'DICOMObject::DeleteVR'
+20010730 ljz Added 'DICOMObject::ReplaceVR'
+20010802 ljz Added 'VR::GetSpecialValueCodeOfVR'
+20051217 mvh Added 'VR::ReAlloc'
+20080910 bcb Added VR::VR(UINT16 g, UINT16 e, UINT32 l, LE_UINT16 *d) &
+ VR::VR(UINT16 g, UINT16 e, UINT32 l, LE_UINT16 *d, BOOL mFlag)
+ for big endian.
+20100619 bcb Fix gcc4 warnings and improve speed,
+ and prevented coping of clases with pointers.
+20100717 mvh Merged
+20100728 bcb Removed unused AutoMakeDO, added Get's to VR and DICOMObject.
+ Added ChangeVR's.
+20100815 mvh Merged; added max to GetCstring
+ Moved defaults from implementation to header files
+20100823 mvh bcb moved default parameter here
+*/
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+
+class DICOMObject;
+
+class VR
+ {
+ private:
+ int GetSpecialValueCodeOfVR(VR* pVR);
+
+ public:
+ UINT16 Group;
+ UINT16 Element;
+ UINT32 Length;
+ void *Data;
+ BOOL ReleaseMemory;
+ BOOL Valid;
+ // void pointers for historical reasons. SQObjectArray
+ // is problem best moved to an Array < DICOMObject * > * in
+ // the future once the various system compilers work around
+ // the linking problems... ReferentialIntegrityDatabase should
+ // remain void because it is not defined unless the (optional)
+ // IOD library is linked in.
+ void *SQObjectArray;
+ void *ReferentialIntegrityDatabase;
+ UINT16 TypeCode;
+#ifdef __GNUC__
+ VR() : Group(0), Element(0), Length(0), Data(NULL),
+ ReleaseMemory(TRUE), Valid(FALSE), SQObjectArray(NULL),
+ ReferentialIntegrityDatabase(NULL),TypeCode(0) {};
+#else
+ VR() { Data = NULL; Length = 0; ReleaseMemory = TRUE; TypeCode = 0;
+ SQObjectArray = NULL; Valid = FALSE; };
+#endif
+ VR(UINT16 g, UINT16 e, UINT32 l, BOOL Alloc);
+ VR(UINT16 g, UINT16 e, UINT32 l, LE_UINT16 *d);
+ VR(UINT16 g, UINT16 e, UINT32 l, LE_UINT16 *d, BOOL mFlag);
+ VR(UINT16 g, UINT16 e, UINT32 l, void *d);
+ VR(UINT16 g, UINT16 e, UINT32 l, void *d, BOOL);
+ ~VR();
+ UINT operator > (VR &vr);
+ UINT operator < (VR &vr);
+ UINT operator == (VR &vr);
+ BOOL ReAlloc (UINT32);
+ UINT16 GetUINT16();
+ UINT GetUINT();
+ unsigned long long GetULongLong();
+ INT Getatoi();
+
+ // To support SetIf/Morph
+
+ BOOL SetIf(VR *);
+// BOOL Morph(DICOMObject *);
+ BOOL Reset ();
+#ifdef __GNUC__
+ private:// This will prevent it from being copied (it has pointers)
+ VR(const VR&);
+ VR & operator = (const VR&);
+#endif
+ };
+
+class VRGroupPQueue :
+ public PQueueOfPtr<VR *>
+ {
+ public:
+ UINT16 Group;
+ UINT32 Length;
+ VR *Element0;
+ public:
+ BOOL Push(VR *vr);
+ VR *Pop();
+ VR *GroupLength();
+ UINT operator > (VRGroupPQueue &vrgroup);
+ UINT operator < (VRGroupPQueue &vrgroup);
+ UINT operator == (VRGroupPQueue &vrgroup);
+#ifdef __GNUC__
+ VRGroupPQueue(UINT16 G):Group(G),Length(0),Element0(NULL) {};
+ private:// This will prevent it from being copied (it has a pointer)
+ VRGroupPQueue(const VRGroupPQueue&);
+ VRGroupPQueue & operator = (const VRGroupPQueue&);
+#else
+ VRGroupPQueue(UINT16 G) { Group = G; Length = 0; };
+#endif
+ };
+
+class DICOMObject :
+ public PQueueOfPtr<VRGroupPQueue *>
+ {
+ VRGroupPQueue *CurrentGroup, *LastVRG;
+ VR *LastVR;
+
+ UINT16 LastGroup;
+ UINT16 LastElement;
+
+ public:
+ UINT32 Length;
+ BOOL Packaged;
+ Array<VRGroupPQueue *> VRGroupPQueues;
+ Array<DICOMObject *> *SQObjectArray;
+ UINT32 FreeSQObjectSize;
+// DICOMObject *AutoMakeDO; //bcb Always NULL.
+ UINT32 FixedSize;
+ BOOL UseFixedSize;
+ private:
+ BOOL Package();
+#ifdef __GNUC__ // This will prevent it from being copied (it has pointers)
+ DICOMObject(const DICOMObject&);
+ DICOMObject & operator = (const DICOMObject&);
+#endif
+ public:
+ virtual BOOL Push(VR *vr);
+ virtual BOOL Push(DICOMObject *); // Sequence Embedding
+ virtual VR *Pop();
+ UINT8 GetBYTE(UINT16, UINT16);
+ UINT16 GetUINT16(UINT16, UINT16);
+ UINT GetUINT(UINT16, UINT16);
+ unsigned long long GetULongLong(UINT16, UINT16);
+ INT Getatoi(UINT16, UINT16);
+ char *GetCString(UINT16, UINT16, size_t max = 1023);
+ VR *GetVR(UINT16, UINT16);
+ BOOL DeleteVR(VR* pVR);
+ BOOL ReplaceVR(VR* pNewVR);
+ INT ChangeVR(UINT16, UINT16, const char *, UINT16 type = 0, BOOL space = FALSE);
+ INT ChangeVR(UINT16, UINT16, UINT8, UINT16);
+ INT ChangeVR(UINT16, UINT16, UINT16, UINT16);
+ INT ChangeVR(UINT16, UINT16, UINT, UINT16);
+ virtual BOOL Reset();
+ DICOMObject();
+ ~DICOMObject();
+ };
+
+class DICOMCommandObject :
+ public DICOMObject
+ {
+ };
+
+class DICOMDataObject :
+ public DICOMObject
+ {
+ };
diff --git a/device.cpp b/device.cpp
new file mode 100644
index 0000000..02cf3cd
--- /dev/null
+++ b/device.cpp
@@ -0,0 +1,4163 @@
+/*
+19980620 mvh Setting MAGDeviceThreshHold to 0 causes out of disk error below 10 MB without cleanup
+19980620 mvh Implemented PanicKillOff thread here as alternative to spawning killer.exe
+19980702 mvh Started support functions for maintaining/determining amount of used space on device
+19980704 mvh NOTE: JukeBox code only TruncateFieldNames compatible for now; used mp's filecopy
+19980709 mvh Finished first version of archive options: prepare,undo,copy,compare,delete
+19980721 mvh Set default # cache and jukebox devices to 0
+19990110 mvh Made strings longer since got truncated, fixed some messages
+19990110 mvh Archive one MAG device or MAG?; fixed SQL syntax for update; speeded 0x7fffffff
+ return False if SelectLRUForarchival selects no data
+19990111 mvh Reset archive flag reports to operator console; protected against illegal device#
+19990113 mvh Run up to 10 patient further to try and fill CD more exact; max patients = 10000
+19990114 mvh Added quick routine MakeListOfPatientsOnDevice and used instead of 0x7fffffff
+19990117 mvh Accept any, not only *.v2, for computing patient size, assume max file size=30 MB
+19990630 mvh Added support for MIRROR devices (e.g., try MIRROR1 if MAG1 fails)
+19990707 mvh Fixed default MIRRORDevices (now 0)
+19990708 mvh NOTE: archiving should make use of mirror device if required as well!
+19990712 mvh Fixed that MagRampage thread was started over and over again (fixed for WIN32 only)
+19990831 ljz Fix: Several BOOL functions returned -1, which is TRUE !!
+20000221 ljz Changed layout of this update-history
+20000629 ljz Logging of trouble now starts with '***'
+20001104 mvh Fixed aDB.Close -> should be aDB.Close(); added WINAPI to MagRampage thread
+20010328 mvh Added verify mirror disk
+20010329 mvh DeleteBunchAfterBurning also deletes data on MIRROR0 if it exists
+ verify mirror disk keeps on going after error but does return error
+20010312 mvh Check if we already selected some patients for archiving from the device
+20010509 mvh Added RenameDevice
+20010522 mvh+ljz Do not call RestoreMagFlags if something goes in wrong in PrepareBunchForBurning
+20011114 ljz+mvh Replaced slow updates for magdevice by much faster ones
+ The update that now no longer has the IN part might not work for ACCESS or DBF
+ So: for jukebox purposes, SQL server is required
+20011115 ljz+mvh Replaced 'LIKE' by faster '=' in query strings; fixed previous fix
+20020412 mvh PanicKilloff will delete now delete 5 MB data at a time. (high water = low water + 5)
+20020415 mvh Added TestImages: sanity check of images on disk
+20020416 mvh Reversed read order for TestImages and VerifyMirrorDisk: MRU first
+20020802 mvh Allow multiple subdirectories in rmdir and mkdir code
+20020804 mvh Cleaned up a bit
+20021018 mvh GenerateFileName has NoKill option (for interactive dgate tasks); moved ALERT warning
+20021020 mvh Simplified and speeded queries for archiving using ImagePat field (requires rev5+ of db)
+ Removed " and added [ in MakeSafeString; hand-code one query for built-in dbase driver
+ Changed SQL construct in SelectLRUForArchival for compatibility with built-in driver
+20030120 ljz Added FreeDeviceTables
+20030702 mvh Start on ArchiveCompression; for now KB is specified -before!- compression
+20030705 mvh Replaced ProcessDDO by more correct DecompressNKI to check pixel data
+20030706 mvh Attach VRType to PDU's for implicit little endian support
+20030724 ljz Fix in GetKBUsedForPatient: missing %s in printf
+20030819 mvh Allow longer filenames
+20030905 mvh Allow longer filenames when reading device paths
+20030921 mvh Added DEVICE_TYPE_MIRROR in GetDevice; allow PanicKillOff to be called with variable treshold
+20031217 ljz Fix: Support harddisks bigger than 2 GigaByte!!! in CalcMegsOnDevice (Thanks to Clifford Sweet)
+20040403 mvh Moved ArchiveCompression to SelectLRUForArchival -> fills disks correctly
+20040614 mvh Added MoveDataToDevice
+20050107 mvh Adapted for linux compile (no threads yet, no check of disk space on device)
+20050109 mvh Added threads for linux
+20050118 mvh Detach thread after starting it to avoid leaks
+20050119 mvh GetKBUsedOnDevice is not used --> no problem to return -1 under linux
+20050119 mvh GetKBUsedOnDevice is not used --> no problem to return -1 under linux
+20050414 mvh Fix CalcMegsOnDevice for relative path
+20050421 mvh Fix: MAGThreshHold is space for largest file != space for cleanup
+ Now set to 30 MB independent of MAGDeviceThreshHold
+20050901 mvh Fix free space check for unc paths (error counting \)
+20060311 mvh When GetDiskFreeSpaceEx fails allow storing data anyway (fix for Marius Petruc)
+20061213 mvh Fixed nasty bug in MakeListOfPatientsOnDevice: Query without bindfield overwrites previous bound strings!
+20070316 mvh Cleanup now starts at MAGDeviceThreshHold to MAGDeviceThreshHold+1000, was start on 30 to MAGDeviceThreshHold
+ Allow both MAG0 and MAG0.Archiving as input for PrepareBunchForBurning
+20071027 mvh Protect MakeListOfPatientsOnDevice on MAXPATIENTS; LRU selection now configurable using routine
+ MakeListOfOldestPatientsOnDevice. E.g. if LRUSort = StudyDate, deletes or archives least recent
+ scanned patients first. The default "" means that the original sort order on db entry date is kept
+20071031 mvh Catch out of memory errors and return error status if so
+20071118 mvh Adapted for 64 bits (use SQLLEN for BindField)
+20071128 mvh Fix by kamil.krasnik of Cache device disk space test for UNIX
+ mvh Also fix Cache and Mirror for UNC paths
+20080126 mvh Fixed bug reported by Ali: second move to MAG1 of more data if same patient would fail on delete
+ Added new logic: attempt to delete file from MAG0 that is not in MAG0 but is in MAG1 is OK
+ Similar attempt to delete file from MAG0 that is in MAG0 but not in MAG1 is an error
+20080302 mvh Fixed case of DICOM table names
+20080317 mvh Fixed deletebunchafterburning change (Ali)
+20080604 mvh Modified device searching order when file not found: JUKEBOX now also searches other JUKEBOX
+20080617 mvh Fixed bug in above: second jukebox not accessed correctly
+20080818 mvh DbaseIII check now uses DB flags, not PATHSEP in datasource name
+20081016 mvh Fix check of max patients in MakeListofOldestPatientsOnDevice
+20081120 mvh Added UseEscapeStringConstants and DoubleBackSlashToDB
+20081124 mvh restrict PanicKillOff to 10 runs (to stop when no patients left)
+20090821 mvh Added new FileExists function that uses stat; maybe does not try to mount tape or disk to early
+20090926 mvh MakeListOfOldestPatientsOnDevice returns newest if Max<0
+ SelectLRUForArchival always use new code (use KB<0 to select MRU);
+ Default MakeListOfOldestPatientsOnDevice use AccessTime to emulate old code
+20091231 bcb Changed char* to const char* for gcc4.2 warnings
+20100111 mvh Merged
+20100120 mvh Fixed two const issues detected with ms8
+20100124 mvh Use MyGetPrivateProfileString
+20100309 bcb Added double parentheses (gcc4.2 Warnings)
+20100309 bcb Changed int to unsigned int, commented out unused variables and routines (gcc4.2 Warnings)
+20100619 bcb Added UNUSED_ARGUMENT.
+20100717 mvh Merged
+20100901 mvh Added IgnoreMAGDeviceThreshHold
+20101121 mvh Added ArchiveConverter0 (1900)
+20110105 mvh Do not stop deleting on single error; added MoveDeviceConverter0 (2000)
+20110105 mvh SelectSeriesForArchival: selects data older than age days (age>0) or younger (age<0) from device
+20110106 mvh added kb limit to SelectSeriesForArchival; Added moveseriestodevice
+20110106 mvh fixes in series code and new MakeSafeString; #if code to allow select on AccessTime instead of SeriesDate
+20110119 mvh Pass PDU to some archiving code as script context
+20110320 mvh Added MAGDeviceFullThreshHold, system will only write to device if more than # MB avail (def 30)
+20110603 mvh Fully init vr used for MakeSafeString
+20110606 mvh RecompressPatient also changes filename if script (ArchiveConverter0, MoveDeviceConverter0) passed
+20110904 mvh Fixed leak in InitializeDeviceTable (occurs in read_ini command)
+20120723 mvh Fixed string overflow found by bcb in MakeListOfLRUPatients
+20130817 mvh TestFile will uncompress all read data to test it
+*/
+
+#ifndef UNUSED_ARGUMENT
+#define UNUSED_ARGUMENT(x) (void)x
+#endif
+
+#ifndef WHEDGE
+# include "dgate.hpp"
+#else
+# include "master.h"
+#endif
+
+#ifndef UNIX
+# include <direct.h>
+# include <io.h>
+#define PATHSEPSTR "\\"
+#define PATHSEPCHAR '\\'
+#else // UNIX
+#define PATHSEPSTR "/"
+#define PATHSEPCHAR '/'
+#define stricmp(s1, s2) strcasecmp(s1, s2)
+#define memicmp(s1, s2, n) strncasecmp(s1, s2, n)
+#define strnicmp(s1, s2, n) strncasecmp(s1, s2, n)
+#define memicmp(s1, s2, n) strncasecmp(s1, s2, n)
+#define O_BINARY 0
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <sys/statvfs.h>
+#endif
+
+#include <stdio.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <time.h>
+
+#include "gpps.hpp"
+#include "nkiqrsop.hpp"
+
+// Device level support for MAG & System support
+
+UINT MAGDevices = 0,
+ MIRRORDevices = 0,
+ MOPDevices = 0,
+ CDRDevices = 0,
+ CACHEDevices = 0,
+ JUKEBOXDevices = 0;
+
+UINT MAGDeviceThreshHold = 40;
+UINT MAGDeviceFullThreshHold = 30;
+int IgnoreMAGDeviceThreshHold = 0;
+
+char **MAGDeviceTable = NULL, // on-line storage (load distributed)
+ **MIRRORDeviceTable = NULL, // mirror devices, e.g., MIRROR1 mirrors MAG1
+ **MOPDeviceTable = NULL, // not used
+ **CDRDeviceTable = NULL, // not used
+ **CACHEDeviceTable = NULL, // data to burn CDs from (each subdirectory is a disk)
+ **JUKEBOXDeviceTable = NULL; // CD-ROM towers (each subdirectory is a disk)
+
+int *MAGDeviceSpace = NULL; // to maintain used disk space (for later chunk mode)
+int *MIRRORDeviceSpace = NULL; // to maintain used disk space (for later chunk mode)
+
+#ifndef ConfigFile
+extern char ConfigFile[];
+#endif
+
+// prototypes
+
+int GetKBUsedOnDevice (char *Device);
+int MakeListOfOldestPatientsOnDevice(char **PatientIDList, int Max, const char *Device, char *Sort);
+
+
+////////////////////////////////////////////////////////////////////////
+// Cleanup device tables
+void FreeDeviceTables(void)
+{ int i;
+
+ for (i=0; i<(int)MAGDevices; i++)
+ delete MAGDeviceTable[i];
+ delete MAGDeviceTable;
+
+ for (i=0; i<(int)MIRRORDevices; i++)
+ delete MIRRORDeviceTable[i];
+ delete MIRRORDeviceTable;
+
+ for (i=0; i<(int)MOPDevices; i++)
+ delete MOPDeviceTable[i];
+ delete MOPDeviceTable;
+
+ for (i=0; i<(int)CDRDevices; i++)
+ delete CDRDeviceTable[i];
+ delete CDRDeviceTable;
+
+ for (i=0; i<(int)CACHEDevices; i++)
+ delete CACHEDeviceTable[i];
+ delete CACHEDeviceTable;
+
+ for (i=0; i<(int)JUKEBOXDevices; i++)
+ delete JUKEBOXDeviceTable[i];
+ delete JUKEBOXDeviceTable;
+
+ delete MAGDeviceSpace;
+
+ delete MIRRORDeviceSpace;
+}
+
+
+
+////////////////////////////////////////////////////////////////////////
+// Delete least recently accessed patients to make free disk space
+
+char LRUSort[64] = "StudyDate";
+unsigned int HasArchiveConverter=0;
+unsigned int HasMoveDeviceConverter=0;
+
+BOOL
+PanicKillOff(unsigned int MAGThreshHold)
+ {
+ // Query the patient table, and sort it by access time
+ SQLLEN sdword,sdword1;
+ DWORD iTime;
+ Database DB;
+// char s[255];
+ char PID[256];
+ int i;
+
+ if(MAGThreshHold==0) MAGThreshHold = 10;
+
+
+ // new code that deletes patients with oldest most recent study first
+
+ if (LRUSort[0])
+ {
+ char *PatientIDList;
+ int Patients;
+ int MAXPATIENTS = 1000;
+
+ Patients = MakeListOfOldestPatientsOnDevice(&PatientIDList, MAXPATIENTS, "MAG0", LRUSort);
+
+ for (i=0; i<Patients; i++)
+ {
+ strncpy(PID, PatientIDList + 256*i, 255);
+ PID[255]=0;
+
+ VR *vr = new VR(0x0010, 0x0020, strlen(PID), (void*)PID, (BOOL) FALSE );
+ DICOMDataObject DDO;
+
+ OperatorConsole.printf("DISK SPACE: %d MB / NEED %d MB - Deleting patient on %s: %s\n", LargestFreeMAG(), MAGThreshHold, LRUSort, PID);
+ DDO.Push(vr);
+ RemoveFromPACS(&DDO);
+ if(LargestFreeMAG()>MAGThreshHold + 5) // make 5 MB extra room
+ break;
+ else
+ continue;
+ }
+
+ free(PatientIDList);
+ return TRUE;
+ }
+
+
+ // original code that deletes patient on db order
+
+ for (i=0; i<10; i++)
+ {
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ return ( FALSE );
+
+ if (!DB.Query(PatientTableName, "AccessTime, PatientID", NULL, "AccessTime"))
+ return (FALSE);
+
+ if(!DB.BindField (1, SQL_C_ULONG,
+ &iTime, 4,
+ &sdword1))
+ return ( FALSE );
+
+ if(!DB.BindField (2, SQL_C_CHAR,
+ PID, 255,
+ &sdword))
+ return ( FALSE );
+
+ while(DB.NextRecord())
+ {
+ VR *vr = new VR(0x0010, 0x0020, strlen(PID), (void*)PID, (BOOL) FALSE );
+ DICOMDataObject DDO;
+
+ OperatorConsole.printf("DISK SPACE: %d MB / NEED %d MB - Deleting patient: %s\n", LargestFreeMAG(), MAGThreshHold, PID);
+ DDO.Push(vr);
+ RemoveFromPACS(&DDO);
+ if(LargestFreeMAG()>MAGThreshHold + 5) // make 5 MB extra room
+ {
+ DB.Close();
+ return ( TRUE );
+ }
+ else
+ continue;
+ }
+ }
+ DB.Close();
+ OperatorConsole.printf("DISK SPACE: %d MB / NEED %d MB - but stopping\n", LargestFreeMAG(), MAGThreshHold);
+ return ( TRUE );
+ }
+
+
+////////////////////////////////////////////////////////////////////////
+// start a killer to make some space by deleting LRU patients
+
+#ifndef UNIX
+ static HANDLE ThreadHandle=NULL;
+#endif
+
+BOOL
+#ifndef UNIX
+WINAPI
+#endif
+MAGRampage()
+ {
+ PanicKillOff(MAGDeviceThreshHold+1000);
+
+#ifndef UNIX
+ CloseHandle(ThreadHandle);
+ ThreadHandle = NULL;
+#endif
+
+ return ( TRUE );
+ }
+
+////////////////////////////////////////////////////////////////////////
+// find amount of space on disk with most space
+UINT
+LargestFreeMAG()
+ {
+ unsigned int Index;
+ UINT Max = 0, iMax;
+ Index = 0;
+
+ while ( Index < MAGDevices)
+ {
+ iMax = CheckFreeStoreOnMAGDevice(Index);
+ if(iMax>Max)
+ Max = iMax;
+ ++Index;
+ }
+ return ( Max );
+ }
+
+
+////////////////////////////////////////////////////////////////////////
+// find magnetic device with largest amount of space
+UINT
+MaxMagDevice ()
+ {
+ unsigned int Index;
+ UINT Max = 0, iMax, Device = 0;
+ Index = 0;
+
+ while ( Index < MAGDevices)
+ {
+ iMax = CheckFreeStoreOnMAGDevice(Index);
+ if(iMax>Max)
+ {
+ Max = iMax;
+ Device = Index;
+ }
+ ++Index;
+ }
+ return ( Device );
+ }
+
+////////////////////////////////////////////////////////////////////////
+// find cache device with largest amount of space
+int
+MaxCACHEDevice
+ (UINT NeededSpace)
+ {
+ unsigned int Max = 0, iMax, Index;
+ int Device = -1;
+ Index = 0;
+
+ while ( Index < CACHEDevices)
+ {
+ iMax = CheckFreeStoreOnCACHEDevice(Index);
+ if(iMax>Max)
+ {
+ Max = iMax;
+ Device = Index;
+ }
+ ++Index;
+ }
+
+ if (Max < NeededSpace)
+ return -1;
+ else
+ return Device;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// read device table from dicom.ini
+BOOL
+InitializeDeviceTable(
+ char *SCRoot)
+ {
+ UINT Index;
+ char iTemp[128];
+ char Temp[512];
+
+ ///////////////////// Threshold for panic kill off /////////////////////
+
+ MyGetPrivateProfileString ( SCRoot, "MAGDeviceThreshHold", "40",
+ (char*)Temp, 64, ConfigFile);
+ MAGDeviceThreshHold = atoi(Temp);
+
+ MyGetPrivateProfileString ( SCRoot, "MAGDeviceFullThreshHold", "30",
+ (char*)Temp, 64, ConfigFile);
+ MAGDeviceFullThreshHold = atoi(Temp);
+
+ MyGetPrivateProfileString ( SCRoot, "IgnoreMAGDeviceThreshHold", "0",
+ (char*)Temp, 64, ConfigFile);
+ IgnoreMAGDeviceThreshHold = atoi(Temp);
+
+ ///////////////////// sort order for panic kill off and archival /////////////////////
+
+ MyGetPrivateProfileString ( SCRoot, "LRUSort", "",
+ (char*)LRUSort, 64, ConfigFile);
+
+ ///////////////////// on-line storage /////////////////////
+
+ MyGetPrivateProfileString ( SCRoot, "MAGDevices", "1",
+ (char*) Temp, 64, ConfigFile);
+ MAGDevices = atoi(Temp);
+
+ if (MAGDeviceTable)
+ FreeDeviceTables();
+
+ MAGDeviceTable = new char*[MAGDevices];
+ MAGDeviceSpace = new int[MAGDevices];
+
+ Index = 0;
+ while ( Index < MAGDevices )
+ {
+ sprintf(iTemp, "MAGDevice%d", Index);
+ MyGetPrivateProfileString ( SCRoot, iTemp, "NULL",
+ (char*) Temp, 500, ConfigFile);
+ MAGDeviceTable[Index] = new char[strlen(Temp)+1];
+ strcpy(MAGDeviceTable[Index], Temp);
+
+ // sprintf(iTemp, "MAG%d", Index);
+ // MAGDeviceSpace[Index] = GetKBUsedOnDevice (iTemp);
+
+ MAGDeviceSpace[Index] = 0;
+
+ ++Index;
+ }
+
+ ///////////////////// mirror storage /////////////////////
+
+ MyGetPrivateProfileString ( SCRoot, "MIRRORDevices", "0",
+ (char*) Temp, 64, ConfigFile);
+ MIRRORDevices = atoi(Temp);
+
+ MIRRORDeviceTable = new char*[MIRRORDevices];
+ MIRRORDeviceSpace = new int[MIRRORDevices];
+
+ Index = 0;
+ while ( Index < MIRRORDevices )
+ {
+ sprintf(iTemp, "MIRRORDevice%d", Index);
+ MyGetPrivateProfileString ( SCRoot, iTemp, "NULL",
+ (char*) Temp, 500, ConfigFile);
+ MIRRORDeviceTable[Index] = new char[strlen(Temp)+1];
+ strcpy(MIRRORDeviceTable[Index], Temp);
+
+ // sprintf(iTemp, "MIRROR%d", Index);
+ // MIRRORDeviceSpace[Index] = GetKBUsedOnDevice (iTemp);
+
+ MIRRORDeviceSpace[Index] = 0;
+
+ ++Index;
+ }
+
+ ///////////////////// cache to off-line storage /////////////////////
+
+ MyGetPrivateProfileString ( SCRoot, "CACHEDevices", "0",
+ (char*) Temp, 64, ConfigFile);
+ CACHEDevices = atoi(Temp);
+
+ CACHEDeviceTable = new char*[CACHEDevices];
+
+ Index = 0;
+ while ( Index < CACHEDevices )
+ {
+ sprintf(iTemp, "CACHEDevice%d", Index);
+ MyGetPrivateProfileString ( SCRoot, iTemp, "NULL",
+ (char*) Temp, 500, ConfigFile);
+ CACHEDeviceTable[Index] = new char[strlen(Temp)+1];
+ strcpy(CACHEDeviceTable[Index], Temp);
+ ++Index;
+ }
+
+ ///////////////////// off-line storage /////////////////////
+
+ MyGetPrivateProfileString ( SCRoot, "JUKEBOXDevices", "0",
+ (char*) Temp, 64, ConfigFile);
+ JUKEBOXDevices = atoi(Temp);
+
+ JUKEBOXDeviceTable = new char*[JUKEBOXDevices];
+
+ Index = 0;
+ while ( Index < JUKEBOXDevices )
+ {
+ sprintf(iTemp, "JUKEBOXDevice%d", Index);
+ MyGetPrivateProfileString ( SCRoot, iTemp, "NULL",
+ (char*) Temp, 500, ConfigFile);
+ JUKEBOXDeviceTable[Index] = new char[strlen(Temp)+1];
+ strcpy(JUKEBOXDeviceTable[Index], Temp);
+ ++Index;
+ }
+
+ MyGetPrivateProfileString ( SCRoot, "ArchiveConverter0", "",
+ (char*) Temp, 512, ConfigFile);
+ HasArchiveConverter = strlen(Temp);
+
+ MyGetPrivateProfileString ( SCRoot, "MoveDeviceConverter0", "",
+ (char*) Temp, 512, ConfigFile);
+ HasMoveDeviceConverter = strlen(Temp);
+
+ return ( TRUE );
+ }
+
+
+////////////////////////////////////////////////////////////////////////
+// find amount of free space on a disk
+
+#ifndef UNIX
+
+UINT
+CalcMegsOnDevice(
+ char *RootDirectory)
+/*
+ {
+ DWORD SectorsPerCluster;
+ DWORD BytesPerSector;
+ DWORD FreeClusters;
+ DWORD TotalClusters;
+ DWORD SP;
+ if(GetDiskFreeSpace(RootDirectory,
+ &SectorsPerCluster,
+ &BytesPerSector,
+ &FreeClusters,
+ &TotalClusters))
+ {
+ SP = (SectorsPerCluster * FreeClusters) / 1024;
+ SP = (SP * BytesPerSector) / 1024;
+ SystemDebug.printf("FreeStore Left %d on %s (%d,%d,%d,%d)\n", SP, RootDirectory,
+ SectorsPerCluster, BytesPerSector, FreeClusters, TotalClusters);
+ return ( SP );
+ }
+ SystemDebug.printf("***Error getting free store for device %s\n", RootDirectory);
+ return(0);
+ }
+*/
+ /* Following code works correctly for harddisks with capacity above 2 GigaByte.
+ (thanks to Clifford Sweet)
+ */
+ {
+ ULARGE_INTEGER FreeBytesAvailable;
+ ULARGE_INTEGER TotalNumberOfBytes;
+ ULARGE_INTEGER TotalNumberOfFreeBytes;
+ DWORD SP;
+ char *rd;
+
+ if (IgnoreMAGDeviceThreshHold) return 10000;
+
+ // UNC paths and drive: are OK, but use NULL (cur drive) to fix for relative paths
+ rd = RootDirectory;
+ if (rd[1]!=':' && (rd[0]!='\\' || rd[1]!='\\')) rd=NULL;
+
+ if(GetDiskFreeSpaceEx(rd,
+ &FreeBytesAvailable,
+ &TotalNumberOfBytes,
+ &TotalNumberOfFreeBytes))
+ {
+ SP = (DWORD) (FreeBytesAvailable.QuadPart >> 20);
+ SystemDebug.printf("FreeStore Left %d on %s\n", SP, RootDirectory);
+ return ( SP );
+ }
+
+ SystemDebug.printf("***Error getting free store for device %s\n", RootDirectory);
+ return(1000);
+ }
+
+
+#else // UNIX
+
+UINT
+CalcMegsOnDevice(const char *theRootDirectory)
+ {
+ size_t aFreeSpace = 0;
+ struct statvfs aStat;
+
+ // statvfs() takes any path name and returns info on the device
+ // containing that path (file or directory)
+
+ if (IgnoreMAGDeviceThreshHold) return 10000;
+
+ if(!statvfs(theRootDirectory, &aStat))
+ {
+ aFreeSpace =
+ (size_t)(((double)aStat.f_bavail * (double)aStat.f_frsize) /
+ ((double)1024 * (double)1024));
+
+ SystemDebug.printf("FreeStore Left %d on %s\n", aFreeSpace,
+ theRootDirectory);
+ }
+ else
+ {
+ SystemDebug.printf("***Error getting free store for device %s\n",
+ theRootDirectory);
+ }
+ return aFreeSpace;
+}
+
+#endif // UNIX
+
+////////////////////////////////////////////////////////////////////////
+// Find amount of space on MAG device N
+#ifndef UNIX
+UINT
+CheckFreeStoreOnMAGDevice(
+ UINT MagNumber)
+ {
+ int Index;
+ char s[1024];
+
+ if (MagNumber >= MAGDevices || MagNumber < 0) return 0;
+
+ strcpy(s, MAGDeviceTable[MagNumber]);
+ // Check for UNC style name
+ if(!strncmp(s, "\\\\", 2))
+ {
+ // UNC Name
+ Index = 2;
+ while(1)
+ {
+ if(s[Index]=='\\')
+ break;
+ ++Index;
+ }
+ ++Index; // mvh 20050901
+ while(s[Index])
+ {
+ if(s[Index]=='\\')
+ {
+ s[Index]='\0';
+ return(CalcMegsOnDevice(s));
+ }
+ ++Index;
+ }
+ return(CalcMegsOnDevice(s));
+ }
+ s[3] = '\0';
+ return(CalcMegsOnDevice(s));
+ }
+#else
+// UNIX version...
+UINT
+CheckFreeStoreOnMAGDevice(
+ UINT MagNumber)
+ {
+ if (MagNumber >= MAGDevices || MagNumber < 0) return 0;
+ return(CalcMegsOnDevice(MAGDeviceTable[MagNumber]));
+ }
+#endif
+
+////////////////////////////////////////////////////////////////////////
+// Find amount of space on MIRROR device N
+#ifndef UNIX
+UINT
+CheckFreeStoreOnMIRRORDevice(
+ UINT MIRRORNumber)
+ {
+ int Index;
+ char s[1024];
+
+ if (MIRRORNumber >= MIRRORDevices || MIRRORNumber < 0) return 0;
+
+ strcpy(s, MIRRORDeviceTable[MIRRORNumber]);
+ // Check for UNC style name
+ if(!strncmp(s, "\\\\", 2))
+ {
+ // UNC Name
+ Index = 2;
+ while(1)
+ {
+ if(s[Index]=='\\')
+ break;
+ ++Index;
+ }
+ ++Index; // mvh 20071128
+ while(s[Index])
+ {
+ if(s[Index]=='\\')
+ {
+ s[Index]='\0';
+ return(CalcMegsOnDevice(s));
+ }
+ ++Index;
+ }
+ return(CalcMegsOnDevice(s));
+ }
+ s[3] = '\0';
+ return(CalcMegsOnDevice(s));
+ }
+#else
+// UNIX version...
+UINT
+CheckFreeStoreOnMIRRORDevice(
+ UINT MIRRORNumber)
+ {
+ if (MIRRORNumber >= MIRRORDevices || MIRRORNumber < 0) return 0;
+ return(CalcMegsOnDevice(MIRRORDeviceTable[MIRRORNumber]));
+ }
+#endif
+
+////////////////////////////////////////////////////////////////////////
+// Find amount of space on CACHE device N
+#ifndef UNIX
+UINT
+CheckFreeStoreOnCACHEDevice(
+ UINT CACHENumber)
+ {
+ int Index;
+ char s[1024];
+
+ if (CACHENumber > CACHEDevices || CACHENumber < 0) return 0;
+
+ strcpy(s, CACHEDeviceTable[CACHENumber]);
+ // Check for UNC style name
+ if(!strncmp(s, "\\\\", 2))
+ {
+ // UNC Name
+ Index = 2;
+ while(1)
+ {
+ if(s[Index]=='\\')
+ break;
+ ++Index;
+ }
+ ++Index; // mvh 20071128
+ while(s[Index])
+ {
+ if(s[Index]=='\\')
+ {
+ s[Index]='\0';
+ return(CalcMegsOnDevice(s));
+ }
+ ++Index;
+ }
+ return(CalcMegsOnDevice(s));
+ }
+ s[3] = '\0';
+ return(CalcMegsOnDevice(s));
+ }
+#else
+// UNIX version...
+UINT
+CheckFreeStoreOnCACHEDevice(
+ UINT CACHENumber)
+ {
+ char s[1024];
+ char* chp;
+
+ if (CACHENumber >= CACHEDevices || CACHENumber < 0) return 0;
+
+ strncpy(s, CACHEDeviceTable[CACHENumber], 1023);
+
+ if ((chp = strchr(s, '%')))
+ {
+ chp[0] = '\0';
+ if ((chp = strrchr(s, '/')))
+ {
+ chp[0] = '\0';
+ }
+ }
+
+ return(CalcMegsOnDevice(s));
+ }
+#endif
+
+////////////////////////////////////////////////////////////////////////
+// Locate a device that is suitable to store a new image on
+// Note: Assumes that 30 MB is enough to store a single image
+
+BOOL
+GetDevice(
+ char *DeviceName,
+ UINT DeviceFlags)
+ {
+ UINT Index;
+ //UINT MAGThreshHold = 30;
+
+#ifndef UNIX
+ DWORD ThreadID;
+#else
+ pthread_t ThreadID;
+#endif
+
+// mvh 20050421: MAGThreshHold is space for largest file != space for cleanup MAGDeviceThreshHold
+// if(MAGDeviceThreshHold) MAGThreshHold = MAGDeviceThreshHold;
+
+ if(DeviceFlags&DEVICE_TYPE_MAG)
+ {
+ Index = 0;
+ while ( Index < MAGDevices )
+ {
+ unsigned int c = CheckFreeStoreOnMAGDevice(Index);
+ if( c > MAGDeviceFullThreshHold)
+ {
+ sprintf(DeviceName, "MAG%d", Index);
+ if (c < MAGDeviceThreshHold && MAGDeviceThreshHold!=0)
+ goto cleanup;
+ return ( TRUE );
+ }
+ ++Index;
+ }
+
+ if (DeviceFlags&DEVICE_TYPE_MIRROR)
+ {
+ Index = 0;
+ while ( Index < MIRRORDevices )
+ {
+ if(CheckFreeStoreOnMIRRORDevice(Index) > MAGDeviceFullThreshHold)
+ {
+ sprintf(DeviceName, "MIRROR%d", Index);
+ return ( TRUE );
+ }
+ ++Index;
+ }
+ }
+
+ // Report out of disk without attempt to cleanup if MAGDeviceThreshHold==0 or when not a server
+ if(!MAGDeviceThreshHold || (DeviceFlags & DEVICE_TYPE_NOKILL) ) return FALSE;
+
+ // god help us; no disk found with enough space
+ sprintf(DeviceName, "MAG%d", MaxMagDevice ());
+
+cleanup:
+
+#ifndef UNIX
+ if (!ThreadHandle)
+ {
+ OperatorConsole.printf("***ALERT: RUNNING OUT OF FREE SPACE\n");
+ ThreadHandle = CreateThread(NULL, 0x0000f000,
+ (LPTHREAD_START_ROUTINE) MAGRampage, NULL, 0, &ThreadID);
+ }
+#else // UNIX
+ OperatorConsole.printf("***ALERT: RUNNING OUT OF FREE SPACE\n");
+ pthread_create(&ThreadID, NULL, (void*(*)(void*))MAGRampage, NULL);
+ pthread_detach(ThreadID);
+#endif
+ return ( TRUE );
+ }
+ else
+ return ( FALSE );
+ }
+
+
+////////////////////////////////////////////////////////////////////////
+// Test if a directory exists
+BOOL
+DirectoryExists(
+ char *path)
+ {
+ char temp[1024];
+ struct stat statbuf;
+
+ int lc= strlen(path) - 1; /* index for last char in path */
+ strcpy(temp, path);
+
+ if (temp[lc] == '\\' || temp[lc] == '/')
+ temp[lc] = 0;
+
+ if (stat(temp, &statbuf) == -1) return FALSE; /* file or path not found */
+
+ /* only directory allowed */
+ if ((statbuf.st_mode & (S_IFCHR | S_IFREG)) == 0)
+ return TRUE;
+ else
+ return FALSE;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// Get directory for given device (MAG, MIRROR, CACHE, or JUKEBOX)
+BOOL
+GetPhysicalDevice(
+ const char *Device,
+ char *Physical)
+ {
+ int Num;
+
+ Physical[0] = 0;
+
+ // Check for MAG devices
+ // Example: MAG0 = main data storage
+
+ if(strnicmp(Device, "MAG", 3)==0)
+ {
+ Num = atoi(&Device[3]);
+ if (Num >= (signed int)MAGDevices || Num < 0) return FALSE;
+
+ strcpy(Physical, MAGDeviceTable[Num]);
+
+ // ensure that Physical string ends with a path separator
+ int aLength = (int)strlen(Physical);
+ if(aLength <= 0)
+ return(FALSE);
+ if(Physical[aLength - 1] != PATHSEPCHAR)
+ {
+ Physical[aLength++] = PATHSEPCHAR;
+ Physical[aLength] = '\0';
+ }
+ return ( TRUE );
+ }
+
+ if(strnicmp(Device, "MIRROR", 6)==0)
+ {
+ Num = atoi(&Device[6]);
+ if (Num >= (signed int)MIRRORDevices || Num < 0) return FALSE;
+
+ strcpy(Physical, MIRRORDeviceTable[Num]);
+
+ // ensure that Physical string ends with a path separator
+ int aLength = (int)strlen(Physical);
+ if(aLength <= 0)
+ return(FALSE);
+ if(Physical[aLength - 1] != PATHSEPCHAR)
+ {
+ Physical[aLength++] = PATHSEPCHAR;
+ Physical[aLength] = '\0';
+ }
+ return ( TRUE );
+ }
+
+ // Check CACHE device for images that has been copied for archival
+ // Example: CACHE0.1.123 = On cache 0, data for jukebox 1, cd 123
+
+ if(strnicmp(Device, "CACHE", 5)==0)
+ {
+ int JUKEBOXDevice=0;
+ int CDNumber =0;
+ const char *p;
+ char Temp[1024];
+
+ Num = atoi(&Device[5]);
+ if (Num >= (signed int)CACHEDevices || Num < 0) return FALSE;
+
+ strcpy(Physical, CACHEDeviceTable[Num]);
+
+ p = strchr(Device, '.');
+ if (p)
+ {
+ JUKEBOXDevice = atoi(p+1);
+ p = strchr(p+1, '.');
+ if (p) CDNumber = atoi(p+1);
+ }
+ sprintf(Temp, Physical, JUKEBOXDevice, CDNumber);
+ strcpy(Physical, Temp);
+
+ int aLength = (int)strlen(Physical);
+ if(aLength <= 0)
+ return(FALSE);
+ if(Physical[aLength - 1] != PATHSEPCHAR)
+ {
+ Physical[aLength++] = PATHSEPCHAR;
+ Physical[aLength] = '\0';
+ }
+ return ( TRUE );
+ }
+
+
+ // Check for data on a jukebox
+ // Example: JUKEBOX1.123 = jukebox 1, cd 123
+
+ if(strnicmp(Device, "JUKEBOX", 7)==0)
+ {
+ int CDNumber =0;
+ const char *p;
+ char Temp[1024];
+
+ Num = atoi(&Device[7]);
+ if (Num >= (signed int)JUKEBOXDevices || Num < 0) return FALSE;
+
+ strcpy(Physical, JUKEBOXDeviceTable[Num]);
+
+ p = strchr(Device, '.');
+ if (p) CDNumber = atoi(p+1);
+ sprintf(Temp, Physical, CDNumber);
+ strcpy(Physical, Temp);
+
+ // ensure that Physical string ends with a path separator
+ int aLength = (int)strlen(Physical);
+ if(aLength <= 0)
+ return(FALSE);
+ if(Physical[aLength - 1] != PATHSEPCHAR)
+ {
+ Physical[aLength++] = PATHSEPCHAR;
+ Physical[aLength] = '\0';
+ }
+ return ( TRUE );
+ }
+
+ return(FALSE);
+ }
+
+////////////////////////////////////////////////////////////////////////
+// Test if a file exists
+/*static BOOL
+FileExistsOld(char *Path)
+ {
+ FILE *f;
+// int res;
+
+ f = fopen(Path, "rb");
+ if (f==NULL) return FALSE;
+
+ fclose(f);
+ return TRUE;
+ }
+*/
+static BOOL
+FileExists(
+ char *path)
+ {
+ struct stat statbuf;
+
+ if (stat(path, &statbuf) == -1) return FALSE; // file or path not found
+
+ // regular file
+ if (statbuf.st_mode & S_IFREG)
+ return TRUE;
+ else
+ return FALSE;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// Find directory that contains a given image file on all MAG, CACHE, or JUKEBOX devices
+BOOL
+FindPhysicalDevice(
+ char *Device,
+ char *Physical,
+ char *ObjectFile)
+ {
+ char FileName[1024], Temp[1024];
+ int number=-1, sub1=-1, sub2=-1;
+ unsigned int i;
+ char *p;
+
+ SystemDebug.printf("Locating file:%s %s\n", Device, ObjectFile);
+
+ // interpret the device name
+ if(strnicmp(Device, "MAG", 3)==0)
+ number = atoi(Device + 3);
+ else if(strnicmp(Device, "MIRROR", 6)==0)
+ number = atoi(Device + 6);
+ else if(strnicmp(Device, "CACHE", 5)==0)
+ number = atoi(Device + 5);
+ else if(strnicmp(Device, "JUKEBOX", 7)==0)
+ number = atoi(Device + 7);
+
+ // try listed device first (it may be right !)
+
+ GetPhysicalDevice(Device, Physical);
+ strcpy(FileName, Physical);
+ strcat(FileName, ObjectFile);
+ if (FileExists(FileName))
+ return TRUE;
+
+ // get device sub-numbers
+
+ p = strchr(Device, '.');
+ if (p)
+ {
+ sub1 = atoi(p+1);
+ p = strchr(p+1, '.');
+ if (p) sub2 = atoi(p+1);
+ }
+
+ // for MAG try MIRROR device (disk may be corrupt or not updated yet from slow mirror server)
+
+ if(strnicmp(Device, "MAG", 3)==0)
+ {
+ sprintf(Temp, "MIRROR%d", number);
+ GetPhysicalDevice(Temp, Physical);
+ strcpy(FileName, Physical);
+ strcat(FileName, ObjectFile);
+ if (FileExists(FileName))
+ {
+ SystemDebug.printf("***Located file on mirror device:%s instead of %s\n", Temp, Device);
+ return TRUE;
+ }
+ }
+
+ // for a jukebox device: try all other jukeboxes
+
+ if(strnicmp(Device, "JUKEBOX", 7)==0)
+ {
+ for (i=0; i<JUKEBOXDevices; i++)
+ {
+ if (i==(unsigned int)number) continue;
+
+ sprintf(Temp, "JUKEBOX%d", i);
+ if (sub1 >= 0) sprintf(Temp+strlen(Temp), ".%d", sub1);
+
+ GetPhysicalDevice(Temp, Physical);
+
+ strcpy(FileName, Physical);
+ strcat(FileName, ObjectFile);
+ if (FileExists(FileName))
+ {
+ SystemDebug.printf("***Located file on wrong device:%s instead of %s\n", Temp, Device);
+ return TRUE;
+ }
+ }
+ }
+
+
+ // for JUKEBOX try CACHE devices with jukebox number and sub1, e.g., from JUKEBOX1.123 tries CACHE0.1.123
+ if(strnicmp(Device, "JUKEBOX", 7)==0)
+ {
+ for (i=0; i<CACHEDevices; i++)
+ {
+ sprintf(Temp, "CACHE%d", i);
+ if (number>= 0) sprintf(Temp+strlen(Temp), ".%d", number);
+ if (sub1 >= 0) sprintf(Temp+strlen(Temp), ".%d", sub1);
+
+ GetPhysicalDevice(Temp, Physical);
+
+ strcpy(FileName, Physical);
+ strcat(FileName, ObjectFile);
+ if (FileExists(FileName))
+ {
+ SystemDebug.printf("***Located file on wrong device:%s instead of %s\n", Temp, Device);
+ return TRUE;
+ }
+ }
+ }
+
+ // for CACHE try JUKEBOX devices with cache sub2, e.g., from 'CACHE0.1.123' tries JUKEBOX0.123
+ if(strnicmp(Device, "CACHE", 5)==0)
+ {
+ for (i=0; i<JUKEBOXDevices; i++)
+ {
+ sprintf(Temp, "JUKEBOX%d", i);
+ if (sub2 >= 0) sprintf(Temp+strlen(Temp), ".%d", sub2);
+
+ GetPhysicalDevice(Temp, Physical);
+
+ strcpy(FileName, Physical);
+ strcat(FileName, ObjectFile);
+ if (FileExists(FileName))
+ {
+ SystemDebug.printf("***Located file on wrong device:%s instead of %s\n", Temp, Device);
+ return TRUE;
+ }
+ }
+ }
+
+ // try all MAG devices
+ for (i=0; i<MAGDevices; i++)
+ {
+ sprintf(Temp, "MAG%d", i);
+ GetPhysicalDevice(Temp, Physical);
+ strcpy(FileName, Physical);
+ strcat(FileName, ObjectFile);
+ if (FileExists(FileName))
+ {
+ SystemDebug.printf("***Located file on wrong device:%s instead of %s\n", Temp, Device);
+ return TRUE;
+ }
+ }
+
+ // try all MIRROR devices
+ for (i=0; i<MIRRORDevices; i++)
+ {
+ sprintf(Temp, "MIRROR%d", i);
+ GetPhysicalDevice(Temp, Physical);
+ strcpy(FileName, Physical);
+ strcat(FileName, ObjectFile);
+ if (FileExists(FileName))
+ {
+ SystemDebug.printf("***Located file on wrong device:%s instead of %s\n", Temp, Device);
+ return TRUE;
+ }
+ }
+
+ Physical[0] = 0;
+ return FALSE;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// Compute size of a file
+static int
+FileSize(char *Path)
+ {
+ FILE *f;
+ int res;
+
+ f = fopen(Path, "rb");
+ if (f==NULL) return -1;
+
+ fseek(f, 0, 2);
+ res = ftell(f); /* ask position */
+ fclose(f);
+
+ return res;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// move a file (must remain on same drive)
+static BOOL
+FileMove(char *oldname, char *newname)
+ {
+ if (rename(oldname, newname)) return FALSE;
+ return TRUE;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// copy a file (possibly opening as shared file)
+static BOOL
+FileCopy(char *source, char *target, int smode)
+{
+ BOOL err_status = TRUE; /* Error status */
+ char *copybuffer; /* The copy buffer */
+ int inhandle, outhandle; /* Handle of input, output files */
+ unsigned bufsize; /* Size of copy buffer */
+ unsigned bytes; /* Actual transferred bytes */
+
+ /* Open input file for read-only. parser error if operation fails. */
+
+#ifdef WIN32
+ if (!smode)
+ inhandle = open( source, O_RDONLY | O_BINARY, S_IREAD);
+ else
+ inhandle = sopen( source, O_RDONLY | O_BINARY, SH_DENYNO, S_IREAD);
+#else
+ UNUSED_ARGUMENT(smode);
+ inhandle = open( source, O_RDONLY);
+#endif
+
+ if( inhandle == -1) return FALSE;
+
+ /* Ok, open output file. Parser error on permission failure: */
+
+ outhandle = open( target, O_CREAT | O_TRUNC | O_BINARY | O_RDWR, 0666);
+
+ if( outhandle == -1)
+ {
+ close(inhandle);
+ return FALSE;
+ }
+
+ /* get a large buffer */
+ bufsize = 0xF000;
+
+ copybuffer = (char *)malloc(bufsize);
+ if (copybuffer == NULL)
+ {
+ close(inhandle);
+ close(outhandle);
+ return FALSE;
+ }
+
+#ifdef WIN32
+ while( !eof(inhandle) && err_status)
+#else
+ while( err_status)
+#endif
+ {
+ bytes= (unsigned)read( inhandle, copybuffer, bufsize);
+
+ if (bytes == (unsigned) -1)
+ {
+ err_status= FALSE;
+ break;
+ }
+
+#ifndef WIN32
+ if (bytes == 0)
+ break;
+#endif
+
+ if (bytes != (unsigned)write(outhandle, copybuffer, bytes))
+ {
+ err_status= FALSE;
+ break;
+ }
+ }
+
+ free(copybuffer);
+
+
+ close(outhandle);
+ close(inhandle);
+
+ /* Clean up mess in case of error : */
+ if(err_status != TRUE)
+ unlink(target);
+
+ return err_status;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// compare two files (possibly opening as shared file)
+static BOOL
+FileCompare(char *source, char *target, int smode)
+{
+ BOOL err_status = TRUE; /* Error status */
+ char *buffer1, *buffer2; /* The compare buffers */
+ int handle1, handle2; /* Handle files */
+ unsigned bufsize; /* Size of copy buffer */
+ unsigned bytes1, bytes2; /* Actual transferred bytes */
+
+ /* Open input file for read-only. parser error if operation fails. */
+
+#ifdef WIN32
+ if (!smode)
+ handle1 = open( source, O_RDONLY | O_BINARY, S_IREAD);
+ else
+ handle1 = sopen( source, O_RDONLY | O_BINARY, SH_DENYNO, S_IREAD);
+#else
+ UNUSED_ARGUMENT(smode);
+ handle1 = open( source, O_RDONLY, S_IREAD);
+#endif
+
+ if( handle1 == -1) return FALSE;
+
+ /* Open other file for read-only. parser error if operation fails. */
+
+#ifdef WIN32
+ if (!smode)
+ handle2 = open( target, O_RDONLY | O_BINARY, S_IREAD);
+ else
+ handle2 = sopen( target, O_RDONLY | O_BINARY, SH_DENYNO, S_IREAD);
+#else
+ handle2 = open( target, O_RDONLY, S_IREAD);
+#endif
+
+ if( handle2 == -1)
+ {
+ close(handle1);
+ return FALSE;
+ }
+
+ /* get a large buffer */
+ bufsize = 0xF000;
+
+ buffer1 = (char *)malloc(bufsize);
+ buffer2 = (char *)malloc(bufsize);
+ if (buffer1 == NULL || buffer2 == NULL)
+ {
+ close(handle1);
+ close(handle2);
+ free (buffer1);
+ free (buffer2);
+ return FALSE;
+ }
+
+#ifdef WIN32
+ while( !eof(handle1))
+#else
+ while( TRUE)
+#endif
+
+ {
+ bytes1= (unsigned)read( handle1, buffer1, bufsize);
+
+ if (bytes1 == (unsigned) -1)
+ {
+ err_status= FALSE;
+ break;
+ }
+
+ bytes2= (unsigned)read( handle2, buffer2, bufsize);
+
+ if (bytes2 == (unsigned) -1)
+ {
+ err_status= FALSE;
+ break;
+ }
+
+ if (bytes1 != bytes2)
+ {
+ err_status= FALSE;
+ break;
+ }
+
+#ifndef WIN32
+ if (bytes1 == 0)
+ break;
+#endif
+
+#ifdef WIN32
+ if (eof(handle1) != eof(handle2))
+ {
+ err_status= FALSE;
+ break;
+ }
+#endif
+
+ if (memcmp(buffer1, buffer2, bytes1))
+ {
+ err_status= FALSE;
+ break;
+ }
+ }
+
+ free(buffer1);
+ free(buffer2);
+
+ close(handle1);
+ close(handle2);
+
+ return err_status;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// Add size of a file to the total KB for a device (not used yet)
+BOOL
+RegisterUsedSpace(
+ char *Device,
+ int Kbytes)
+ {
+ if(strnicmp(Device, "MAG", 3))
+ return FALSE;
+
+ MAGDeviceSpace[atoi(&Device[3])] += Kbytes;
+ return TRUE;
+ }
+
+//////////////////////////////////////////////////////////////////////////////////////////////
+// compute total space used by a device (may also be computed by GetKBUsedForPatient with ID=*)
+// Implementation only correct for simple filenamesyntaxes with 1 level of subdirs
+
+int
+GetKBUsedOnDevice (char *Device)
+ {
+#ifdef WIN32
+ int itemp;
+ double result;
+ HANDLE fdHandle, ffHandle;
+ WIN32_FIND_DATA FileData;
+ char PathString[1024], TempPath[1024], s[1024], FileString[1024];
+ char BasePath[1024];
+
+ result = 0.0;
+
+ // convert device specification to a path
+
+ GetPhysicalDevice(Device, PathString);
+ itemp = strlen(PathString);
+ if(!itemp)
+ return -1;
+
+ // add a '/' to end of directory name if not yet present
+
+ if(PathString[itemp-1] != PATHSEPCHAR)
+ strcat(PathString, PATHSEPSTR);
+
+ // PathString now contains Image file storage root directory path
+
+ strcpy(TempPath, PathString);
+ strcat(TempPath, "*.*");
+
+ fdHandle = FindFirstFile(TempPath, &FileData);
+
+ if(fdHandle == INVALID_HANDLE_VALUE)
+ return -1;
+
+
+ while ( TRUE )
+ {
+
+ /* Filter out INCOMING and BIN directories */
+ if(stricmp(FileData.cFileName, "INCOMING"))
+ if(strcmp(FileData.cFileName, "."))
+ if(strcmp(FileData.cFileName, ".."))
+ if(stricmp(FileData.cFileName, "BIN"))
+ {
+ strcpy(TempPath, PathString);
+ strcat(TempPath, FileData.cFileName);
+ strcat(TempPath, PATHSEPSTR);
+ strcat(TempPath, "*.*");
+
+ strcpy(FileString, FileData.cFileName);
+ ffHandle = FindFirstFile(TempPath, &FileData);
+ if(ffHandle!=INVALID_HANDLE_VALUE)
+ {
+ while ( TRUE )
+ {
+ strcpy(TempPath, PathString);
+ strcat(TempPath, FileString);
+ strcat(TempPath, PATHSEPSTR);
+ strcat(TempPath, FileData.cFileName);
+
+ strcpy(BasePath, FileString);
+ strcat(BasePath, PATHSEPSTR);
+ strcat(BasePath, FileData.cFileName);
+
+ if(strcmp(FileData.cFileName, "."))
+ if(strcmp(FileData.cFileName, ".."))
+ result += FileSize(TempPath);
+
+ if(!FindNextFile(ffHandle, &FileData))
+ break;
+ }
+ FindClose(ffHandle);
+ }
+ }
+
+ if(!FindNextFile(fdHandle, &FileData))
+ break;
+ }
+ FindClose ( fdHandle );
+
+ return (int)(result/1024 + 0.5);
+#else
+ // Not implemented under linux
+ UNUSED_ARGUMENT(Device);
+ return -1;
+#endif
+ }
+
+////////////////////////////////////////////////////////////////////////
+// Make a SQL safe string from a character string (how about the '_' ?)
+// uses MakeSafeString from VRTOSQL.CPP (is database type dependent)
+
+BOOL MakeSafeString (VR *vr, char *string, Database *db);
+
+BOOL MakeSafeString (const char *in, char *string, Database *db)
+ {
+ VR vr;
+ char *s1;
+ char s[512];
+
+ vr.Data = (void*)in;
+ vr.Length = strlen(in);
+ vr.Group = 0;
+ vr.Element = 0;
+ MakeSafeString(&vr, s, db);
+ vr.Data = NULL;
+ vr.Length = 0;
+
+ if (s[0]=='?') sprintf(string, "LIKE %s", s+1);
+ else sprintf(string, "= %s", s);
+
+ return TRUE;
+ }
+
+/////////////////////////////////////////////////////////////////////
+// compute total space used or number of files for a patient on a device
+int
+GetKBUsedForPatient (char *Device, char *PatientID, int ComputeSpace)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[1024], FileName[1024];
+ char QueryString[512], PatientIDValue[512], DeviceValue[512];
+ SQLLEN SQLResultLength;
+ double TotalSize;
+ int Size;
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return -1;
+ }
+
+ MakeSafeString(PatientID, PatientIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.ImagePat %s and "
+ "DICOMImages.DeviceName %s",
+ PatientIDValue, DeviceValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to compute total size\n");
+ aDB.Close();
+ return -1;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ TotalSize = 0;
+ while (aDB.NextRecord())
+ {
+ if (ComputeSpace)
+ {
+ GetPhysicalDevice(DeviceName, FileName);
+ strcat(FileName, ObjectFile);
+ Size = FileSize(FileName);
+ if (Size<0)
+ OperatorConsole.printf("***Unable to determine size of file: '%s'\n", FileName);
+ else
+ {
+ SystemDebug.printf("%s = %d KB\n", FileName, FileSize(FileName)/1024);
+ TotalSize += Size / 1024.0;
+ }
+ }
+ else
+ TotalSize++;
+ }
+
+ aDB.Close();
+
+ if(TotalSize>0)
+ {
+ if (ComputeSpace)
+ SystemDebug.printf("Total Size = %d KB\n", (int)(TotalSize + 0.512));
+ else
+ SystemDebug.printf("Total files = %d\n", (int)(TotalSize + 0.5));
+ }
+
+ return (int)(TotalSize + 0.512);
+ }
+
+/////////////////////////////////////////////////////////////////////
+// compute total space used or number of files for a patient on a device
+int
+GetKBUsedForSeries (char *Device, char *SeriesUID, int ComputeSpace)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[1024], FileName[1024];
+ char QueryString[512], DeviceValue[512];
+ SQLLEN SQLResultLength;
+ double TotalSize;
+ int Size;
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return -1;
+ }
+
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.SeriesInst = '%s' and "
+ "DICOMImages.DeviceName %s",
+ SeriesUID, DeviceValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to compute total size\n");
+ aDB.Close();
+ return -1;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ TotalSize = 0;
+ while (aDB.NextRecord())
+ {
+ if (ComputeSpace)
+ {
+ GetPhysicalDevice(DeviceName, FileName);
+ strcat(FileName, ObjectFile);
+ Size = FileSize(FileName);
+ if (Size<0)
+ OperatorConsole.printf("***Unable to determine size of file: '%s'\n", FileName);
+ else
+ {
+ SystemDebug.printf("%s = %d KB\n", FileName, FileSize(FileName)/1024);
+ TotalSize += Size / 1024.0;
+ }
+ }
+ else
+ TotalSize++;
+ }
+
+ aDB.Close();
+
+ if(TotalSize>0)
+ {
+ if (ComputeSpace)
+ SystemDebug.printf("Total Size = %d KB\n", (int)(TotalSize + 0.512));
+ else
+ SystemDebug.printf("Total files = %d\n", (int)(TotalSize + 0.5));
+ }
+
+ return (int)(TotalSize + 0.512);
+ }
+
+/////////////////////////////////////////////////////////////////////
+// Recompress all files of a patient on device (unless Compression "as" "is" or "")
+// Use some ArchiveConverter0 e.g., "nop" to modify filename when syntax changed
+
+BOOL ModifyImageFile(char *filename, char *script, ExtendedPDU_Service *PDU);
+
+void
+RecompressPatient (char *Device, char *PatientID, char *Compression, ExtendedPDU_Service *PDU)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[1024], FileName[1024];
+ char QueryString[512], PatientIDValue[512], DeviceValue[512];
+ SQLLEN SQLResultLength;
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s for archive recompression\n",
+ DataSource, UserName, DataHost);
+ return;
+ }
+
+ MakeSafeString(PatientID, PatientIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.ImagePat %s and "
+ "DICOMImages.DeviceName %s",
+ PatientIDValue, DeviceValue);
+
+ if (HasArchiveConverter)
+ {
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to modify for archival\n");
+ aDB.Close();
+ return;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ GetPhysicalDevice(DeviceName, FileName);
+ strcat(FileName, ObjectFile);
+
+ ModifyImageFile(FileName, "1900", PDU);
+ }
+ }
+
+ if (stricmp(Compression, "")==0 || stricmp(Compression, "as")==0 || stricmp(Compression, "is")==0)
+ {
+ aDB.Close();
+ return;
+ }
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to recompress for archival\n");
+ aDB.Close();
+ return;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ GetPhysicalDevice(DeviceName, FileName);
+ strcat(FileName, ObjectFile);
+
+ recompressFile(FileName, Compression, PDU);
+ }
+
+ aDB.Close();
+ }
+
+/////////////////////////////////////////////////////////////////////
+// Run move script on all files of a patient on selected device
+// Use some MoveDeviceConverter0 e.g., "nop" to force modify filename when syntax changed
+
+void
+ProcessMoveDevicePatient (char *Device, char *PatientID)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[1024], FileName[1024];
+ char QueryString[512], PatientIDValue[512], DeviceValue[512];
+ SQLLEN SQLResultLength;
+ ExtendedPDU_Service PDU;
+
+ if (!HasMoveDeviceConverter) return;
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return;
+ }
+
+ MakeSafeString(PatientID, PatientIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.ImagePat %s and "
+ "DICOMImages.DeviceName %s",
+ PatientIDValue, DeviceValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to run move script\n");
+ aDB.Close();
+ return;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ GetPhysicalDevice(DeviceName, FileName);
+ strcat(FileName, ObjectFile);
+ ModifyImageFile(FileName, "2000", &PDU);
+ }
+
+ aDB.Close();
+ }
+
+/////////////////////////////////////////////////////////////////////
+// Run move script on all files of a series on selected device
+
+void
+ProcessMoveDeviceSeries (char *Device, char *SeriesUID)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[1024], FileName[1024];
+ char QueryString[512], SeriesUIDValue[512], DeviceValue[512];
+ SQLLEN SQLResultLength;
+ ExtendedPDU_Service PDU;
+
+ if (!HasMoveDeviceConverter) return;
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return;
+ }
+
+ MakeSafeString(SeriesUID, SeriesUIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.SeriesInst %s and "
+ "DICOMImages.DeviceName %s",
+ SeriesUIDValue, DeviceValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to run move script\n");
+ aDB.Close();
+ return;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ GetPhysicalDevice(DeviceName, FileName);
+ strcat(FileName, ObjectFile);
+ ModifyImageFile(FileName, "2000", &PDU);
+ }
+
+ aDB.Close();
+ }
+
+/////////////////////////////////////////////////////////////////////
+// Modify device name for patient on specific device
+BOOL
+ModifyDeviceNameForPatient (char *Device, const char *PatientID, char *UpdateString)
+ {
+ Database aDB;
+ char Table[256], QueryString[512], PatientIDValue[256], DeviceValue[256], SetString[512];
+
+ sprintf(Table, "%s", ImageTableName);
+ strcpy(SetString, UpdateString);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return FALSE;
+ }
+
+ MakeSafeString(PatientID, PatientIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+
+ if (strlen(PatientID))
+ sprintf(QueryString, "DICOMImages.DeviceName %s and "
+ "DICOMImages.ImagePat %s",
+ DeviceValue, PatientIDValue);
+ else
+ {
+ sprintf(QueryString, "DICOMImages.DeviceName %s", DeviceValue);
+ }
+
+ if(!aDB.UpdateRecords(Table, SetString, QueryString))
+ {
+ OperatorConsole.printf("***Unable to update image records to new device\n");
+ aDB.Close();
+ return FALSE;
+ }
+
+ aDB.Close();
+ return TRUE;
+ }
+
+/////////////////////////////////////////////////////////////////////
+// Modify device name for study on specific device
+BOOL
+ModifyDeviceNameForSeries (char *Device, const char *SeriesUID, char *UpdateString)
+ {
+ Database aDB;
+ char Table[256], QueryString[512], SeriesUIDValue[256], DeviceValue[256], SetString[512];
+
+ sprintf(Table, "%s", ImageTableName);
+
+ strcpy(SetString, UpdateString);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return FALSE;
+ }
+
+ MakeSafeString(SeriesUID, SeriesUIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.DeviceName %s and "
+ "DICOMImages.SeriesInst %s",
+ DeviceValue, SeriesUIDValue);
+
+ if(!aDB.UpdateRecords(Table, SetString, QueryString))
+ {
+ OperatorConsole.printf("***Unable to update image records to new device\n");
+ aDB.Close();
+ return FALSE;
+ }
+
+ aDB.Close();
+ return TRUE;
+ }
+
+/////////////////////////////////////////////////////////////////////
+// move files of a patient specified to be on a device from / to a directory
+
+BOOL
+MovePatientData (char *Device, char *PatientID, char *From, char *To)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[512], FileNameFrom[1024], FileNameTo[1024];
+ char QueryString[512], PatientIDValue[512], DeviceValue[512], Temp[512];
+ SQLLEN SQLResultLength;
+ BOOL Status=TRUE;
+ unsigned int i;
+ int j;
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return FALSE;
+ }
+
+ MakeSafeString(PatientID, PatientIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.ImagePat %s and "
+ "DICOMImages.DeviceName %s",
+ PatientIDValue, DeviceValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to move data\n");
+ aDB.Close();
+ return FALSE;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ strcpy(FileNameFrom, From);
+ strcat(FileNameFrom, ObjectFile);
+
+ strcpy(FileNameTo, To);
+ strcat(FileNameTo, ObjectFile);
+
+ // make patient directory and any required subdirectories
+
+ for (i=strlen(To); i<strlen(FileNameTo); i++)
+ {
+ if (FileNameTo[i] == PATHSEPCHAR)
+ {
+ strcpy(Temp, FileNameTo);
+ Temp[i] = 0;
+#ifdef WIN32
+ mkdir(Temp);
+#else
+ mkdir(Temp, 0777);
+#endif
+ }
+ }
+
+ SystemDebug.printf("Moving file: %s to %s\n", FileNameFrom, FileNameTo);
+ if (!FileMove(FileNameFrom, FileNameTo))
+ {
+ OperatorConsole.printf("***Unable to move file: %s to %s\n", FileNameFrom, FileNameTo);
+ Status = FALSE;
+ break;
+ }
+
+ // attempt to remove source directory and any subdirectories (ignore fail if not empty)
+
+ strcpy(Temp, FileNameFrom);
+ for (j=strlen(FileNameFrom)-1; j>=(signed int)strlen(From); j--)
+ {
+ if (Temp[j] == PATHSEPCHAR)
+ {
+ Temp[j] = 0;
+ rmdir(Temp);
+ }
+ }
+ }
+
+ aDB.Close();
+
+ return Status;
+ }
+
+/////////////////////////////////////////////////////////////////////
+// copy files of a patient specified to be on a device from / to a directory
+BOOL
+CopyPatientData (char *Device, char *PatientID, char *From, char *To)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[512], FileNameFrom[1024], FileNameTo[1024];
+ char QueryString[512], PatientIDValue[512], DeviceValue[512], Temp[512];
+ SQLLEN SQLResultLength;
+ BOOL Status=TRUE;
+ unsigned int i;
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return FALSE;
+ }
+
+ MakeSafeString(PatientID, PatientIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.ImagePat %s and "
+ "DICOMImages.DeviceName %s",
+ PatientIDValue, DeviceValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to copy data\n");
+ aDB.Close();
+ return FALSE;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ strcpy(FileNameFrom, From);
+ strcat(FileNameFrom, ObjectFile);
+
+ strcpy(FileNameTo, To);
+ strcat(FileNameTo, ObjectFile);
+
+
+ // make patient directory and any required subdirectories
+
+ for (i=strlen(To); i<strlen(FileNameTo); i++)
+ {
+ if (FileNameTo[i] == PATHSEPCHAR)
+ {
+ strcpy(Temp, FileNameTo);
+ Temp[i] = 0;
+#ifdef WIN32
+ mkdir(Temp);
+#else
+ mkdir(Temp, 0777);
+#endif
+ }
+ }
+
+ SystemDebug.printf("Copying file: %s to %s\n", FileNameFrom, FileNameTo);
+ if (!FileCopy(FileNameFrom, FileNameTo, 0))
+ {
+ OperatorConsole.printf("***Unable to copy file: %s to %s\n", FileNameFrom, FileNameTo);
+ Status = FALSE;
+ break;
+ }
+ }
+
+ aDB.Close();
+
+ return Status;
+ }
+
+/////////////////////////////////////////////////////////////////////
+// copy files of a patient specified to be on a device from / to a directory
+BOOL
+CopySeriesData (char *Device, char *SeriesUID, char *From, char *To)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[512], FileNameFrom[1024], FileNameTo[1024];
+ char QueryString[512], SeriesUIDValue[512], DeviceValue[512], Temp[512];
+ SQLLEN SQLResultLength;
+ BOOL Status=TRUE;
+ unsigned int i;
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return FALSE;
+ }
+
+ MakeSafeString(SeriesUID, SeriesUIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.SeriesInst %s and "
+ "DICOMImages.DeviceName %s",
+ SeriesUIDValue, DeviceValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to copy data\n");
+ aDB.Close();
+ return FALSE;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ strcpy(FileNameFrom, From);
+ strcat(FileNameFrom, ObjectFile);
+
+ strcpy(FileNameTo, To);
+ strcat(FileNameTo, ObjectFile);
+
+
+ // make patient directory and any required subdirectories
+
+ for (i=strlen(To); i<strlen(FileNameTo); i++)
+ {
+ if (FileNameTo[i] == PATHSEPCHAR)
+ {
+ strcpy(Temp, FileNameTo);
+ Temp[i] = 0;
+#ifdef WIN32
+ mkdir(Temp);
+#else
+ mkdir(Temp, 0777);
+#endif
+ }
+ }
+
+ SystemDebug.printf("Copying file: %s to %s\n", FileNameFrom, FileNameTo);
+ if (!FileCopy(FileNameFrom, FileNameTo, 0))
+ {
+ OperatorConsole.printf("***Unable to copy file: %s to %s\n", FileNameFrom, FileNameTo);
+ Status = FALSE;
+ break;
+ }
+ }
+
+ aDB.Close();
+
+ return Status;
+ }
+
+/////////////////////////////////////////////////////////////////////
+// compare files of a patient specified to be on a device between two directories
+BOOL
+ComparePatientData (char *Device, char *PatientID, char *From, char *To)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[512], FileNameFrom[1024], FileNameTo[1024];
+ char QueryString[512], PatientIDValue[512], DeviceValue[512];
+ SQLLEN SQLResultLength;
+ BOOL Status=TRUE;
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return FALSE;
+ }
+
+ MakeSafeString(PatientID, PatientIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.ImagePat %s and "
+ "DICOMImages.DeviceName %s",
+ PatientIDValue, DeviceValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to compare data\n");
+ aDB.Close();
+ return FALSE;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ strcpy(FileNameFrom, From);
+ strcat(FileNameFrom, ObjectFile);
+
+ strcpy(FileNameTo, To);
+ strcat(FileNameTo, ObjectFile);
+
+ SystemDebug.printf("Comparing files: %s and %s\n", FileNameFrom, FileNameTo);
+ if (!FileCompare(FileNameFrom, FileNameTo, 0))
+ {
+ OperatorConsole.printf("***Comparison failed for files: %s and %s\n", FileNameFrom, FileNameTo);
+ Status = FALSE;
+ break;
+ }
+ }
+
+ aDB.Close();
+
+ return Status;
+ }
+
+
+/////////////////////////////////////////////////////////////////////
+// compare files of a patient specified to be on a device between two directories
+BOOL
+CompareSeriesData (char *Device, char *SeriesUID, char *From, char *To)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[512], FileNameFrom[1024], FileNameTo[1024];
+ char QueryString[512], SeriesUIDValue[512], DeviceValue[512];
+ SQLLEN SQLResultLength;
+ BOOL Status=TRUE;
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return FALSE;
+ }
+
+ MakeSafeString(SeriesUID, SeriesUIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.SeriesInst %s and "
+ "DICOMImages.DeviceName %s",
+ SeriesUIDValue, DeviceValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to compare data\n");
+ aDB.Close();
+ return FALSE;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ strcpy(FileNameFrom, From);
+ strcat(FileNameFrom, ObjectFile);
+
+ strcpy(FileNameTo, To);
+ strcat(FileNameTo, ObjectFile);
+
+ SystemDebug.printf("Comparing files: %s and %s\n", FileNameFrom, FileNameTo);
+ if (!FileCompare(FileNameFrom, FileNameTo, 0))
+ {
+ OperatorConsole.printf("***Comparison failed for files: %s and %s\n", FileNameFrom, FileNameTo);
+ Status = FALSE;
+ break;
+ }
+ }
+
+ aDB.Close();
+
+ return Status;
+ }
+
+/////////////////////////////////////////////////////////////////////
+// test read single file
+BOOL TestFile(char *FullFilename, char *status)
+ {
+ int len = strlen(FullFilename);
+ PDU_Service PDU;
+ int UseChapter10 = 0;
+ DICOMDataObject *DDOOut;
+ VR *vr;
+
+ PDU.AttachRTC(&VRType);
+
+ if (len>4)
+ UseChapter10 = (stricmp(FullFilename+len-4, ".dcm")==0);
+
+ if (!UseChapter10)
+ DDOOut = LoadImplicitLittleEndianFile(FullFilename, 0xffffffffu);
+ else
+ DDOOut = PDU.LoadDICOMDataObject(FullFilename);
+
+ // can we read the file ?
+ if (!DDOOut)
+ {
+ strcpy(status, "failed to read");
+ return FALSE;
+ }
+
+ // expect PatientID
+ vr = DDOOut->GetVR(0x0010, 0x0020);
+ if(!vr)
+ {
+ strcpy(status, "PatientID missing");
+ delete DDOOut;
+ return FALSE;
+ }
+
+ // expect StudyInstanceUID
+ vr = DDOOut->GetVR(0x0020, 0x000d);
+ if(!vr)
+ {
+ strcpy(status, "StudyInstanceUID missing");
+ delete DDOOut;
+ return FALSE;
+ }
+
+ // expect SeriesInstanceUID
+ vr = DDOOut->GetVR(0x0020, 0x000e);
+ if(!vr)
+ {
+ strcpy(status, "SeriesInstanceUID missing");
+ delete DDOOut;
+ return FALSE;
+ }
+
+ // expect SOPInstanceUID
+ vr = DDOOut->GetVR(0x0008, 0x0018);
+ if(!vr)
+ {
+ strcpy(status, "SOPInstanceUID missing");
+ delete DDOOut;
+ return FALSE;
+ }
+
+ // This will try to decompress the pixel data and check the CRC
+
+ if (!recompress(&DDOOut, "un", "", FALSE, NULL))
+ //if (!DecompressNKI(DDOOut))
+ {
+ strcpy(status, "decompression or CRC error");
+ delete DDOOut;
+ return FALSE;
+ }
+
+ delete DDOOut;
+ return TRUE;
+ }
+
+/////////////////////////////////////////////////////////////////////
+// test files of a patient specified to be on a device
+BOOL
+TestPatientData (char *Device, char *PatientID, char *From)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[1024], FileNameFrom[1024];
+ char QueryString[512], PatientIDValue[512], DeviceValue[512];
+ SQLLEN SQLResultLength;
+ BOOL Status=TRUE;
+ char error[256];
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return FALSE;
+ }
+
+ MakeSafeString(PatientID, PatientIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.ImagePat %s and "
+ "DICOMImages.DeviceName %s",
+ PatientIDValue, DeviceValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to compare data\n");
+ aDB.Close();
+ return FALSE;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ strcpy(FileNameFrom, From);
+ strcat(FileNameFrom, ObjectFile);
+
+ SystemDebug.printf("Testing file: %s\n", FileNameFrom);
+ if (!TestFile(FileNameFrom, error))
+ {
+ OperatorConsole.printf("***Test read failed for file: %s (%s)\n", FileNameFrom, error);
+ Status = FALSE;
+ }
+ }
+
+ aDB.Close();
+
+ return Status;
+ }
+
+/////////////////////////////////////////////////////////////////////
+// test files of a patient specified to be on a device
+BOOL
+TestSeriesData (char *Device, char *SeriesUID, char *From)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[1024], FileNameFrom[1024];
+ char QueryString[512], SeriesUIDValue[512], DeviceValue[512];
+ SQLLEN SQLResultLength;
+ BOOL Status=TRUE;
+ char error[256];
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return FALSE;
+ }
+
+ MakeSafeString(SeriesUID, SeriesUIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.SeriesInst %s and "
+ "DICOMImages.DeviceName %s",
+ SeriesUIDValue, DeviceValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to compare data\n");
+ aDB.Close();
+ return FALSE;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ strcpy(FileNameFrom, From);
+ strcat(FileNameFrom, ObjectFile);
+
+ SystemDebug.printf("Testing file: %s\n", FileNameFrom);
+ if (!TestFile(FileNameFrom, error))
+ {
+ OperatorConsole.printf("***Test read failed for file: %s (%s)\n", FileNameFrom, error);
+ Status = FALSE;
+ }
+ }
+
+ aDB.Close();
+
+ return Status;
+ }
+
+/////////////////////////////////////////////////////////////////////
+// Delete files of a patient specified to be on a device from a given directory
+// but only if the file is present in To (may be NULL to disable this check)
+
+BOOL
+DeletePatientData (char *Device, char *PatientID, char *From, char *To)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[1024], FileNameFrom[1024], FileNameTo[1024];
+ char QueryString[512], PatientIDValue[512], DeviceValue[512], Temp[512];
+ SQLLEN SQLResultLength;
+ BOOL Status=TRUE;
+ int i;
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return FALSE;
+ }
+
+ MakeSafeString(PatientID, PatientIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.ImagePat %s and "
+ "DICOMImages.DeviceName %s",
+ PatientIDValue, DeviceValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to delete data\n");
+ aDB.Close();
+ return FALSE;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ BOOL t, f;
+
+ strcpy(FileNameFrom, From);
+ strcat(FileNameFrom, ObjectFile);
+
+ if (To)
+ {
+ strcpy(FileNameTo, To);
+ strcat(FileNameTo, ObjectFile);
+
+ t = FileExists(FileNameTo);
+ f = FileExists(FileNameFrom);
+
+ // it is already copied but there is no source file - ignore
+ if (t && !f) continue;
+
+ // it is not copied but we want to delete the source file - this is an error
+ if (!t && f)
+ {
+ OperatorConsole.printf("***Attempt to delete file that was not copied: %s\n", FileNameFrom);
+ Status = FALSE;
+ break;
+ }
+ }
+
+ SystemDebug.printf("Deleting file: %s\n", FileNameFrom);
+ if (unlink(FileNameFrom))
+ {
+ OperatorConsole.printf("***Unable to delete file: %s\n", FileNameFrom);
+ Status = FALSE;
+ // break; mvh 20110105: do not stop deleting on single error
+ }
+
+ // attempt to remove source directory and any subdirectories (ignore fail if not empty)
+
+ strcpy(Temp, FileNameFrom);
+ for (i=strlen(FileNameFrom)-1; i>=(signed int)strlen(From); i--)
+ {
+ if (Temp[i] == PATHSEPCHAR)
+ {
+ Temp[i] = 0;
+ rmdir(Temp);
+ }
+ }
+ }
+
+ aDB.Close();
+
+ return Status;
+ }
+
+/////////////////////////////////////////////////////////////////////
+// Delete files of a patient specified to be on a device from a given directory
+// but only if the file is present in To (may be NULL to disable this check)
+
+BOOL
+DeleteSeriesData (char *Device, char *SeriesUID, char *From, char *To)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[1024], FileNameFrom[1024], FileNameTo[1024];
+ char QueryString[512], SeriesUIDValue[512], DeviceValue[512], Temp[512];
+ SQLLEN SQLResultLength;
+ BOOL Status=TRUE;
+ int i;
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return FALSE;
+ }
+
+ MakeSafeString(SeriesUID, SeriesUIDValue, &aDB);
+ MakeSafeString(Device, DeviceValue, &aDB);
+
+ sprintf(QueryString, "DICOMImages.SeriesInst %s and "
+ "DICOMImages.DeviceName %s",
+ SeriesUIDValue, DeviceValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records to delete data\n");
+ aDB.Close();
+ return FALSE;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ BOOL t, f;
+
+ strcpy(FileNameFrom, From);
+ strcat(FileNameFrom, ObjectFile);
+
+ if (To)
+ {
+ strcpy(FileNameTo, To);
+ strcat(FileNameTo, ObjectFile);
+
+ t = FileExists(FileNameTo);
+ f = FileExists(FileNameFrom);
+
+ // it is already copied but there is no source file - ignore
+ if (t && !f) continue;
+
+ // it is not copied but we want to delete the source file - this is an error
+ if (!t && f)
+ {
+ OperatorConsole.printf("***Attempt to delete file that was not copied: %s\n", FileNameFrom);
+ Status = FALSE;
+ break;
+ }
+ }
+
+ SystemDebug.printf("Deleting file: %s\n", FileNameFrom);
+ if (unlink(FileNameFrom))
+ {
+ OperatorConsole.printf("***Unable to delete file: %s\n", FileNameFrom);
+ Status = FALSE;
+ // break; mvh 20110105: do not stop deleting on single error
+ }
+
+ // attempt to remove source directory and any subdirectories (ignore fail if not empty)
+
+ strcpy(Temp, FileNameFrom);
+ for (i=strlen(FileNameFrom)-1; i>=(signed int)strlen(From); i--)
+ {
+ if (Temp[i] == PATHSEPCHAR)
+ {
+ Temp[i] = 0;
+ rmdir(Temp);
+ }
+ }
+ }
+
+ aDB.Close();
+
+ return Status;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// assume DeviceTo = 'JUKEBOX1.123' and CACHEDevice0 = d:\davis\cache_%d_04d
+// then this routine sets PhysicalCache to d:\davis\cache_1_0123 (if this directory exists)
+
+BOOL
+FindCacheDirectory(char *DeviceTo, char *PhysicalCache)
+ {
+ unsigned int i;
+ char Temp[1024];
+ char *p;
+ int JUKEBOXDevice=-1, CDNumber=-1;//, CacheNumber=-1;
+
+ if(strnicmp(DeviceTo, "JUKEBOX", 7)==0)
+ {
+ JUKEBOXDevice = atoi(DeviceTo + 7);
+ p = strchr(DeviceTo, '.');
+ if (p)
+ CDNumber = atoi(p+1);
+ if (CDNumber < 0)
+ {
+ OperatorConsole.printf("Archival: *** to-device (%s) has no CD number specified\n", DeviceTo);
+ return FALSE;
+ }
+ }
+ else
+ {
+ OperatorConsole.printf("Archival: *** to-device (%s) should have been a JUKEBOX device\n", DeviceTo);
+ return FALSE;
+ }
+
+ for (i=0; i<CACHEDevices; i++)
+ {
+ sprintf(Temp, "CACHE%d.%d.%d", i, JUKEBOXDevice, CDNumber);
+ GetPhysicalDevice(Temp, PhysicalCache);
+ if (DirectoryExists(PhysicalCache))
+ {
+ SystemDebug.printf("Located cache directory: %s\n", PhysicalCache);
+ return TRUE;
+ }
+ }
+
+ PhysicalCache[0] = 0;
+ OperatorConsole.printf("Archival: *** could not find cache directory for: %s\n", DeviceTo);
+ return FALSE;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// Make list of least recently accessed patients up to specified KB (allocates
+// list and returns amount). If KB=0x7fffffff, all patients are selected (slowly).
+// Maximal 10 LRU patients are inspected more to try and fill exactly the specified KB
+// This routine will also recompress the data for archival. Note: up to 10 patients
+// more are compressed as will be archived.
+// KB<0 select most recent patients
+
+static int
+MakeListOfLRUPatients(char *Device, int KB, char **PatientIDList, char *LRUSort, ExtendedPDU_Service *PDU)
+ {
+ // Query the patient table, and sort it by access time
+ SQLLEN sdword,sdword1;
+ DWORD iTime;
+ Database DB;
+// char s[255];
+ char PatientID[256];
+ int KBTotal, KBPatient, Patients, RunOver=0, Result=0, i;
+ int MAXPATIENTS = 10000;
+
+ // new code that sorts on e.g. studydate (but default on accesstime)
+ // now also use this code
+
+ if (LRUSort[0] || 1)
+ {
+ Patients = MakeListOfOldestPatientsOnDevice(PatientIDList, KB>0 ? MAXPATIENTS : -MAXPATIENTS, Device, LRUSort);
+ KBTotal = 0;
+
+ for (i=0; i<Patients; i++)
+ {
+ strncpy(PatientID, *PatientIDList + 256*i, 255);
+ PatientID[255]=0;
+
+ RecompressPatient (Device, PatientID, ArchiveCompression, PDU);
+
+ KBPatient = GetKBUsedForPatient (Device, PatientID, KB!=0x7fffffff);
+ if (KBPatient + KBTotal > abs(KB))
+ {
+ RunOver++;
+ if (RunOver==10)
+ break;
+ else
+ continue;
+ }
+
+ KBTotal += KBPatient;
+ strcpy(*PatientIDList + 256*Result, PatientID);
+
+ if (KBPatient>0) Result++;
+ }
+
+ return Result;
+ }
+
+ // original code that sorts on database order (no longer used)
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ return -1;
+
+ if (!DB.Query(PatientTableName, "AccessTime, PatientID", NULL, "AccessTime"))
+ return -1;
+
+ if(!DB.BindField (1, SQL_C_ULONG, &iTime, 4, &sdword1))
+ return -1;
+
+ if(!DB.BindField (2, SQL_C_CHAR, PatientID, 255, &sdword))
+ return -1;
+
+ *PatientIDList = (char *)malloc(256 * MAXPATIENTS);
+ if (*PatientIDList==NULL) return -1;
+
+ KBTotal = 0;
+ Patients = 0;
+
+ while(DB.NextRecord())
+ {
+ if (Patients == MAXPATIENTS)
+ break;
+
+ RecompressPatient (Device, PatientID, ArchiveCompression, PDU);
+
+ KBPatient = GetKBUsedForPatient (Device, PatientID, KB!=0x7fffffff);
+ if (KBPatient + KBTotal > KB)
+ {
+ RunOver++;
+ if (RunOver==10)
+ break;
+ else
+ continue;
+ }
+
+ KBTotal += KBPatient;
+
+ strcpy(*PatientIDList + 256*Patients, PatientID);
+
+ if (KBPatient>0) Patients++;
+ }
+
+ DB.Close();
+ return Patients;
+ }
+
+
+////////////////////////////////////////////////////////////////////////
+// Make list of all patients which have at least one image on a given device
+// The list is sorted on accesstime
+
+int
+MakeListOfPatientsOnDevice(char *Device, char **PatientIDList)
+ {
+ // Query the patient table, and sort it by access time
+ SQLLEN sdword,sdword1;
+ DWORD iTime;
+ Database DB;
+ char s[256], DeviceValue[256];
+ char Tables[256], PatientID[256], QueryString[512], Dum[256];
+ int Patients, NPat, MAXPATIENTS = 10000, i;
+ char *PatList;
+
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ return -1;
+
+ MakeSafeString(Device, DeviceValue, &DB);
+
+ // query is hand-written since built-in dbase driver cannot handle the original one
+
+ if (DB.db_type == DT_DBASEIII)
+ {
+ // count #patients
+ if (!DB.Query(PatientTableName, "PatientID", "", "DICOMPatients.AccessTime"))
+ return -1;
+
+ DB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword);
+
+ NPat = 0;
+ while(DB.NextRecord())
+ {
+ NPat++;
+ }
+
+ // some new patients may recently have come in!
+ PatList = (char *)malloc(68 * (NPat + 100));
+ if (PatList==NULL) return -1;
+
+ if (!DB.QueryDistinct(PatientTableName, "PatientID", "", "DICOMPatients.AccessTime"))
+ return -1;
+
+ if(!DB.BindField (1, SQL_C_CHAR, PatientID, 68, &sdword))
+ return -1;
+
+ NPat = 0;
+ while(DB.NextRecord())
+ {
+ strcpy(PatList + 68*NPat, PatientID);
+ NPat++;
+ }
+
+ // now we have the list all patients, query the image table for each of them and return those on the selected device
+ *PatientIDList = (char *)malloc(256 * MAXPATIENTS);
+ if (*PatientIDList==NULL)
+ {
+ free(PatList);
+ return -1;
+ }
+
+ Patients = 0;
+
+ for (i=0; i<NPat; i++)
+ {
+ if (Patients==MAXPATIENTS)
+ break;
+
+ MakeSafeString(PatList + 68*i, s, &DB);
+
+ sprintf(QueryString, "DICOMImages.DeviceName %s and "
+ "DICOMImages.ImagePat %s",
+ DeviceValue, s);
+
+ if (!DB.Query(ImageTableName, "ImagePat", QueryString, ""))
+ {
+ free (PatList);
+ free (PatientIDList);
+ return -1;
+ }
+
+ DB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword);
+
+ if (DB.NextRecord())
+ {
+ strcpy(*PatientIDList + 256*Patients, PatList + 68 * i);
+ Patients++;
+ }
+ }
+
+ free (PatList);
+ DB.Close();
+ return Patients;
+ }
+
+
+ // This original query cannot be handled by the built-in driver !
+
+ sprintf(Tables, "%s, %s, %s, %s",
+ ImageTableName, SeriesTableName, StudyTableName, PatientTableName);
+
+ sprintf(QueryString, "DICOMImages.DeviceName %s and "
+ "DICOMStudies.PatientID = DICOMPatients.PatientID and "
+ "DICOMImages.SeriesInst = DICOMSeries.SeriesInst and "
+ "DICOMSeries.StudyInsta = DICOMStudies.StudyInsta",
+ DeviceValue);
+
+ if (!DB.QueryDistinct(Tables, "DICOMPatients.PatientID, DICOMPatients.AccessTime", QueryString, "DICOMPatients.AccessTime"))
+ return -1;
+
+ if(!DB.BindField (1, SQL_C_CHAR, PatientID, 255, &sdword))
+ return -1;
+
+ if(!DB.BindField (2, SQL_C_ULONG, &iTime, 4, &sdword1))
+ return -1;
+
+ *PatientIDList = (char *)malloc(256 * MAXPATIENTS);
+ if (*PatientIDList==NULL) return -1;
+
+ Patients = 0;
+
+ while(DB.NextRecord())
+ {
+ if (Patients == MAXPATIENTS)
+ break;
+
+ strcpy(*PatientIDList + 256*Patients, PatientID);
+
+ Patients++;
+ }
+
+ DB.Close();
+ return Patients;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// This routine replaces devicenames like 'MAG0.xxxxx' in database by 'MAG0' (undo archiving)
+// Works for all MAG devices
+
+BOOL RestoreMAGFlags()
+ {
+ unsigned int DeviceNo;
+ char FromName[20], ToString[256];
+
+ for (DeviceNo=0; DeviceNo<MAGDevices; DeviceNo++)
+ {
+ sprintf(FromName, "MAG%d.*", DeviceNo);
+ sprintf(ToString, "DeviceName = 'MAG%d'", DeviceNo);
+
+ OperatorConsole.printf("Resetting archive flag on device: MAG%d\n", DeviceNo);
+ if (!ModifyDeviceNameForPatient (FromName, "", ToString))
+ {
+ OperatorConsole.printf("Archival: *** could not restore device name (%s)\n", ToString);
+ }
+ }
+
+ return TRUE;
+ }
+
+
+////////////////////////////////////////////////////////////////////////
+// Select LRU patients from a single device up to the specified amount of KB
+// and set their flags to archival; if KB is smaller than 0 this routine selects MRU
+
+BOOL
+SelectLRUForArchival(char *Device, int KB, ExtendedPDU_Service *PDU)
+ {
+ int i, NPatients, Size, Total;
+ char *PatientIDList, *PatientID;
+ char DeviceArchiving[256], DeviceString[256];
+
+ // process input parameters
+
+ sprintf(DeviceArchiving, "%s.Archiving", Device);
+ sprintf(DeviceString, "DeviceName = '%s.Archiving'", Device);
+
+ // check if we already selected some patients for archiving from this device
+
+ NPatients = MakeListOfPatientsOnDevice(DeviceArchiving, &PatientIDList);
+ if (NPatients > 0)
+ {
+ OperatorConsole.printf("Archival: *** Patients were already selected for archiving\n");
+ free (PatientIDList);
+ return FALSE;
+ }
+ free (PatientIDList);
+
+ // make list of patients that are not yet archived (also recompresses)
+
+ NPatients = MakeListOfLRUPatients(Device, KB, &PatientIDList, LRUSort, PDU);
+ if (NPatients < 0)
+ {
+ OperatorConsole.printf("Archival: *** could not create patient list\n");
+ return FALSE;
+ }
+
+ // set flags from e.g., MAG0 to MAG0.Archiving
+
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+ if (!ModifyDeviceNameForPatient (Device, PatientID, DeviceString))
+ {
+ OperatorConsole.printf("Archival: *** could not set device name to archiving for patient: %s\n", PatientID);
+ free (PatientIDList);
+ RestoreMAGFlags();
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: set archive flag for patient: %s\n", PatientID);
+ }
+
+ // compute amount for double check
+
+ Total = 0;
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+ Size = GetKBUsedForPatient (DeviceArchiving, PatientID, 1);
+ if (Size < 0)
+ {
+ OperatorConsole.printf("Archival: *** could not compute KB used for patient: %s\n", PatientID);
+ free (PatientIDList);
+ RestoreMAGFlags();
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: %6d KB will be written for patient: %s\n", Size, PatientID);
+
+ Total += Size;
+ }
+
+ if (Total==0)
+ {
+ OperatorConsole.printf("Archival: nothing to do\n");
+ free (PatientIDList);
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: total archive amount: %d KB\n", Total);
+
+
+ free (PatientIDList);
+ return TRUE;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// Make list of all series on a given device older than age (>0) or younger (age<0) days
+// limit to a maximum size of kb (if >0) passed
+// The list is sorted on studydate
+
+int
+MakeListOfSeriesOnDevice(char *Device, char **SeriesList, int age, int kb)
+ {
+ // Query the patient table, and sort it by access time
+ SQLLEN sdword,sdword1,sdword2;
+ Database DB;
+ char DeviceValue[256];
+ char Tables[256], SeriesInst[256], SeriesDate[256], AccessTime[256], QueryString[512];
+ int Series, MAXSERIES = 10000, i, Size;
+ struct tm tmbuf1;
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ return -1;
+
+ MakeSafeString(Device, DeviceValue, &DB);
+
+ sprintf(Tables, "%s, %s", ImageTableName, SeriesTableName);
+
+ sprintf(QueryString, "DICOMImages.DeviceName %s and "
+ "DICOMImages.SeriesInst = DICOMSeries.SeriesInst",
+ DeviceValue);
+
+ if (!DB.QueryDistinct(Tables, "DICOMSeries.SeriesInst, DICOMSeries.SeriesDate, DICOMSeries.AccessTime", QueryString, "DICOMSeries.SeriesDate"))
+ return -1;
+
+ if(!DB.BindField (1, SQL_C_CHAR, SeriesInst, 255, &sdword))
+ return -1;
+
+ if(!DB.BindField (2, SQL_C_CHAR, SeriesDate, 255, &sdword1))
+ return -1;
+
+ if(!DB.BindField (3, SQL_C_CHAR, AccessTime, 255, &sdword2))
+ return -1;
+
+ *SeriesList = (char *)malloc(256 * MAXSERIES);
+ if (*SeriesList==NULL) return -1;
+
+ Series = 0;
+ Size = 0;
+
+ while(DB.NextRecord())
+ {
+ if (Series == MAXSERIES) break;
+
+#if 1
+ memset(&tmbuf1, 0, sizeof(tmbuf1));
+ sscanf(SeriesDate, "%04d%02d%02d", &tmbuf1.tm_year, &tmbuf1.tm_mon, &tmbuf1.tm_mday);
+ tmbuf1.tm_year -= 1900;
+ time_t t = mktime(&tmbuf1);
+#else
+ time_t t = (time_t)atoi(AccessTime);
+#endif
+
+ if (age>0 && t>time(NULL)-age*24*3600) continue;
+ if (age<0 && t<time(NULL)+age*24*3600) continue;
+
+ strcpy(*SeriesList + 256*Series, SeriesInst);
+ Series++;
+
+ if (kb>0)
+ {
+ Size += GetKBUsedForSeries (Device, SeriesInst, 1);
+ if (Size>kb) break;
+ }
+ }
+
+ DB.Close();
+ return Series;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// Select series from a single device older than a specified age
+
+BOOL
+SelectSeriesForArchival(char *Device, int age, int kb)
+ {
+ int i, NSeries, Size, Total;
+ char *SeriesList, *SeriesUID;
+ char DeviceArchiving[256], DeviceString[256];
+
+ // process input parameters
+
+ sprintf(DeviceArchiving, "%s.Archiving", Device);
+ //strcpy (DeviceString, "DeviceName = DeviceName + '.Archiving'");
+ sprintf(DeviceString, "DeviceName = '%s.Archiving'", Device);
+
+ // make list of patients that are not yet archived
+
+ NSeries = MakeListOfSeriesOnDevice(Device, &SeriesList, age, kb);
+ if (NSeries < 0)
+ {
+ OperatorConsole.printf("Archival: *** could not create series list\n");
+ return FALSE;
+ }
+
+ // set flags from e.g., MAG0 to MAG0.Archiving
+
+ for (i=0; i<NSeries; i++)
+ {
+ SeriesUID = SeriesList + i*256;
+ if (!ModifyDeviceNameForSeries (Device, SeriesUID, DeviceString))
+ {
+ OperatorConsole.printf("Archival: *** could not set device name to archiving for series: %s\n", SeriesUID);
+ free (SeriesList);
+ RestoreMAGFlags();
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: set archive flag for series: %s\n", SeriesUID);
+ }
+
+ free (SeriesList);
+ return TRUE;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// example: assume DeviceFrom=MAG0 (or MAG0.Archiving), DeviceTo = 'JUKEBOX1.123' and
+// CACHEDevice0 = d:\davis\cache_%d_%04d then this routine creates and fills directory
+// 'd:\davis\cache_1_0123' from MAG0 and deletes the original data. The DeviceNames in
+// the database is set to 'JUKEBOX1.123' which works both before and after burning.
+
+BOOL
+PrepareBunchForBurning(char *DeviceFrom, char *DeviceTo)
+ {
+ int i, NPatients, Size, Total;
+ char *PatientIDList, *PatientID, *p;
+ char PhysicalFrom[1024], PhysicalTo[1024], CacheDevice[1024], Temp[1024], PhysicalCache[1024];
+ int JUKEBOXDevice=-1, CDNumber=-1, CacheNumber=-1;
+ char DeviceFromArchiving[256], DeviceToString[256];
+
+
+ // process input parameters
+
+ strcpy(DeviceFromArchiving, DeviceFrom);
+ if (!strstr(DeviceFromArchiving, ".Archiving"))
+ strcat(DeviceFromArchiving, ".Archiving");
+
+ sprintf(DeviceToString, "DeviceName = '%s'", DeviceTo);
+
+ if (!GetPhysicalDevice(DeviceFrom, PhysicalFrom))
+ {
+ OperatorConsole.printf("Archival: *** invalid from-device: %s\n", DeviceFrom);
+ return FALSE;
+ }
+
+ if (!GetPhysicalDevice(DeviceTo, PhysicalTo))
+ {
+ OperatorConsole.printf("Archival: *** invalid to-device: %s\n", DeviceTo);
+ return FALSE;
+ }
+
+ if(strnicmp(DeviceTo, "JUKEBOX", 7)==0)
+ {
+ JUKEBOXDevice = atoi(DeviceTo + 7);
+ p = strchr(DeviceTo, '.');
+ if (p)
+ CDNumber = atoi(p+1);
+ if (CDNumber < 0)
+ {
+ OperatorConsole.printf("Archival: *** to-device (%s) has no CD number specified\n", DeviceTo);
+ return FALSE;
+ }
+ }
+ else
+ {
+ OperatorConsole.printf("Archival: *** to-device (%s) should have been a JUKEBOX device\n", DeviceTo);
+ return FALSE;
+ }
+
+ // check if the CD is unique: exit if it has been burnt before !
+
+ NPatients = MakeListOfPatientsOnDevice(DeviceTo, &PatientIDList);
+ if (NPatients > 0)
+ {
+ OperatorConsole.printf("Archival: *** jukebox device has been used before: %s\n", DeviceTo);
+ free (PatientIDList);
+ return FALSE;
+ }
+ free (PatientIDList);
+
+
+ // make list of patients that are busy with archiving
+
+ NPatients = MakeListOfPatientsOnDevice(DeviceFromArchiving, &PatientIDList);
+ if (NPatients < 0)
+ {
+ OperatorConsole.printf("Archival: *** could not create patient list\n");
+ return FALSE;
+ }
+
+ // compute amount for double check
+
+ Total = 0;
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+ Size = GetKBUsedForPatient (DeviceFromArchiving, PatientID, 1);
+ if (Size < 0)
+ {
+ OperatorConsole.printf("Archival: *** could not compute KB used for patient: %s\n", PatientID);
+ free (PatientIDList);
+ // RestoreMAGFlags();
+ return FALSE;
+ }
+
+ Total += Size;
+ }
+
+ // something to do ?
+
+ if (Total==0)
+ {
+ OperatorConsole.printf("Archival: Nothing to do\n");
+ free (PatientIDList);
+ // RestoreMAGFlags();
+ return FALSE;
+ }
+
+ // find cache drive with enough space to store the data
+ // NOTE: SPACE CHECK IS IN PRINCIPLE NOT NECESSARY IF DATA IS MOVED !
+
+ CacheNumber = MaxCACHEDevice((Total+10000)/1000);
+ if (CacheNumber < 0)
+ {
+ OperatorConsole.printf("Archival: *** could not find cache drive with enough space (%d KB)\n", Total+10000);
+ free (PatientIDList);
+ // RestoreMAGFlags();
+ return FALSE;
+ }
+
+ sprintf(CacheDevice, "CACHE%d.%d.%d", CacheNumber, JUKEBOXDevice, CDNumber);
+
+ if (!GetPhysicalDevice(CacheDevice, PhysicalCache))
+ {
+ OperatorConsole.printf("Archival: *** invalid cache-device: %s\n", PhysicalCache);
+ free (PatientIDList);
+ // RestoreMAGFlags();
+ return FALSE;
+ }
+
+ // attemp to make the cache directory
+
+ OperatorConsole.printf("Archival: writing to cache-device: %s\n", PhysicalCache);
+
+ strcpy(Temp, PhysicalCache);
+ Temp[strlen(Temp)-1]=0;
+#ifdef WIN32
+ mkdir(Temp);
+#else
+ mkdir(Temp, 0777);
+#endif
+
+ // Same device: move the data (fast) and set the devicename to the CD in the jukebox
+ // NOTE: does not check UNC names; only drive letters!
+
+ if (PhysicalCache[1] == ':' && memicmp(PhysicalCache, PhysicalFrom, 2)==0)
+ {
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+ if (!MovePatientData (DeviceFromArchiving, PatientID, PhysicalFrom, PhysicalCache))
+ {
+ OperatorConsole.printf("Archival: *** could not move image data for patient: %s\n", PatientID);
+ free (PatientIDList);
+ // RestoreMAGFlags();
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: moved data of patient: %s\n", PatientID);
+ }
+
+ if (!ModifyDeviceNameForPatient (DeviceFromArchiving, "", DeviceToString))
+ {
+ OperatorConsole.printf("Archival: *** could not set new device name\n");
+ free (PatientIDList);
+ // RestoreMAGFlags();
+ return FALSE;
+ }
+ }
+
+ // different device: copy the data, compare it, set devicename to jukebox and delete source data
+
+ else
+ {
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+ if (!CopyPatientData (DeviceFromArchiving, PatientID, PhysicalFrom, PhysicalCache))
+ {
+ OperatorConsole.printf("Archival: *** could not copy image data for patient: %s\n", PatientID);
+ free (PatientIDList);
+ // RestoreMAGFlags();
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: copied image data for patient: %s\n", PatientID);
+ }
+
+ // check of copy
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+ if (!ComparePatientData (DeviceFromArchiving, PatientID, PhysicalFrom, PhysicalCache))
+ {
+ OperatorConsole.printf("Archival: *** error comparing data for patient: %s\n", PatientID);
+ free (PatientIDList);
+ // RestoreMAGFlags();
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: compared image data for patient: %s\n", PatientID);
+ }
+
+ if (!ModifyDeviceNameForPatient (DeviceFromArchiving, "", DeviceToString))
+ {
+ OperatorConsole.printf("Archival: *** could not set new device name\n");
+ free (PatientIDList);
+ // RestoreMAGFlags();
+ return FALSE;
+ }
+
+
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+
+ SystemDebug.printf("To delete: %s %s from %s\n", DeviceTo, PatientID, PhysicalFrom);
+
+ // extra check: file must be copied
+ if (!DeletePatientData (DeviceTo, PatientID, PhysicalFrom, PhysicalCache))
+ {
+ OperatorConsole.printf("Archival: *** error deleting data for patient: %s\n", PatientID);
+ free (PatientIDList);
+ // RestoreMAGFlags();
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: deleted on-line image data for patient: %s\n", PatientID);
+ }
+ }
+
+ free (PatientIDList);
+ return TRUE;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// example: assume DeviceFrom=MAG0.Archiving, DeviceTo = MAG1 then this routine
+// moves all data selected for archiving to MAG1 and sets the DeviceName to MAG1
+
+BOOL
+MoveDataToDevice(char *DeviceFrom, char *DeviceTo)
+ {
+ int i, NPatients, Size, Total;
+ char *PatientIDList, *PatientID;
+ char PhysicalFrom[1024], PhysicalTo[1024], Temp[1024];
+ char DeviceToString[256];
+
+ // process input parameters
+
+ sprintf(DeviceToString, "DeviceName = '%s'", DeviceTo);
+
+ if (!GetPhysicalDevice(DeviceFrom, PhysicalFrom))
+ {
+ OperatorConsole.printf("MoveDataToDevice: *** invalid from-device: %s\n", DeviceFrom);
+ return FALSE;
+ }
+
+ if (!GetPhysicalDevice(DeviceTo, PhysicalTo))
+ {
+ OperatorConsole.printf("MoveDataToDevice: *** invalid to-device: %s\n", DeviceTo);
+ return FALSE;
+ }
+
+ // make list of patients that are on DeviceFrom
+
+ NPatients = MakeListOfPatientsOnDevice(DeviceFrom, &PatientIDList);
+ if (NPatients < 0)
+ {
+ OperatorConsole.printf("MoveDataToDevice: *** could not create patient list\n");
+ return FALSE;
+ }
+
+ // compute amount of data to move
+
+ Total = 0;
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+
+ ProcessMoveDevicePatient (DeviceFrom, PatientID);
+ Size = GetKBUsedForPatient (DeviceFrom, PatientID, 1);
+ if (Size < 0)
+ {
+ OperatorConsole.printf("MoveDataToDevice: *** could not compute KB used for patient: %s\n", PatientID);
+ free (PatientIDList);
+ return FALSE;
+ }
+
+ Total += Size;
+ }
+
+ // something to do ?
+
+ if (Total==0)
+ {
+ OperatorConsole.printf("MoveDataToDevice: Nothing to do\n");
+ free (PatientIDList);
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("MoveDataToDevice: moving %d MB to: %s\n", (Total+512)/1024, PhysicalTo);
+
+ // attemp to make the destination directory (it might not exist yet) - will fail silently if already exists
+
+ strcpy(Temp, PhysicalTo);
+ Temp[strlen(Temp)-1]=0;
+#ifdef WIN32
+ mkdir(Temp);
+#else
+ mkdir(Temp, 0777);
+#endif
+
+ // copy the data
+
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+ if (!CopyPatientData (DeviceFrom, PatientID, PhysicalFrom, PhysicalTo))
+ {
+ OperatorConsole.printf("MoveDataToDevice: *** could not copy image data for patient: %s\n", PatientID);
+ free (PatientIDList);
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("MoveDataToDevice: copied image data for patient: %s\n", PatientID);
+ }
+
+ // verify copy
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+ if (!ComparePatientData (DeviceFrom, PatientID, PhysicalFrom, PhysicalTo))
+ {
+ OperatorConsole.printf("MoveDataToDevice: *** error comparing data for patient: %s\n", PatientID);
+ free (PatientIDList);
+ // RestoreMAGFlags();
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("MoveDataToDevice: compared image data for patient: %s\n", PatientID);
+ }
+
+ if (!ModifyDeviceNameForPatient (DeviceFrom, "", DeviceToString))
+ {
+ OperatorConsole.printf("MoveDataToDevice: *** could not set new device name\n");
+ free (PatientIDList);
+ return FALSE;
+ }
+
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+
+ SystemDebug.printf("To delete: %s %s from %s\n", DeviceTo, PatientID, PhysicalFrom);
+
+ // extra check: file must be copied
+ // no error if file already copied before and cannot be deleted
+ if (!DeletePatientData (DeviceTo, PatientID, PhysicalFrom, PhysicalTo))
+ {
+ OperatorConsole.printf("MoveDataToDevice: *** error deleting data for patient: %s\n", PatientID);
+ // free (PatientIDList);
+ //return FALSE; // mvh 20110105
+ }
+ else
+ OperatorConsole.printf("MoveDataToDevice: deleted source data for patient: %s\n", PatientID);
+ }
+
+ free (PatientIDList);
+ return TRUE;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// example: assume DeviceFrom=MAG0.Archiving, DeviceTo = MAG1 then this routine
+// moves all data selected for archiving to MAG1 and sets the DeviceName to MAG1
+
+BOOL
+MoveSeriesToDevice(char *DeviceFrom, char *DeviceTo)
+ {
+ int i, NSeries, Size, Total;
+ char *SeriesUIDList, *SeriesUID;
+ char PhysicalFrom[1024], PhysicalTo[1024], Temp[1024];
+ char DeviceToString[256];
+
+ // process input parameters
+
+ sprintf(DeviceToString, "DeviceName = '%s'", DeviceTo);
+
+ if (!GetPhysicalDevice(DeviceFrom, PhysicalFrom))
+ {
+ OperatorConsole.printf("MoveSeriesToDevice: *** invalid from-device: %s\n", DeviceFrom);
+ return FALSE;
+ }
+
+ if (!GetPhysicalDevice(DeviceTo, PhysicalTo))
+ {
+ OperatorConsole.printf("MoveSeriesToDevice: *** invalid to-device: %s\n", DeviceTo);
+ return FALSE;
+ }
+
+ // make list of patients that are on DeviceFrom
+
+ NSeries = MakeListOfSeriesOnDevice(DeviceFrom, &SeriesUIDList, 0, 0);
+ if (NSeries < 0)
+ {
+ OperatorConsole.printf("MoveSeriesToDevice: *** could not create series list\n");
+ return FALSE;
+ }
+
+ // compute amount of data to move and run move script
+
+ Total = 0;
+ for (i=0; i<NSeries; i++)
+ {
+ SeriesUID = SeriesUIDList + i*256;
+
+ ProcessMoveDeviceSeries (DeviceFrom, SeriesUID);
+ Size = GetKBUsedForSeries (DeviceFrom, SeriesUID, 1);
+ if (Size < 0)
+ {
+ OperatorConsole.printf("MoveSeriesToDevice: *** could not compute KB used for series: %s\n", SeriesUID);
+ free (SeriesUIDList);
+ return FALSE;
+ }
+
+ Total += Size;
+ }
+
+ // something to do ?
+
+ if (Total==0)
+ {
+ OperatorConsole.printf("MoveSeriesToDevice: Nothing to do\n");
+ free (SeriesUIDList);
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("MoveSeriesToDevice: moving %d MB to: %s\n", (Total+512)/1024, PhysicalTo);
+
+ // attemp to make the destination directory (it might not exist yet) - will fail silently if already exists
+
+ strcpy(Temp, PhysicalTo);
+ Temp[strlen(Temp)-1]=0;
+#ifdef WIN32
+ mkdir(Temp);
+#else
+ mkdir(Temp, 0777);
+#endif
+
+ // copy the data
+
+ for (i=0; i<NSeries; i++)
+ {
+ SeriesUID = SeriesUIDList + i*256;
+ if (!CopySeriesData (DeviceFrom, SeriesUID, PhysicalFrom, PhysicalTo))
+ {
+ OperatorConsole.printf("MoveSeriesToDevice: *** could not copy image data for series: %s\n", SeriesUID);
+ free (SeriesUIDList);
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("MoveSeriesToDevice: copied image data for series: %s\n", SeriesUID);
+ }
+
+ // verify copy
+ for (i=0; i<NSeries; i++)
+ {
+ SeriesUID = SeriesUIDList + i*256;
+ if (!CompareSeriesData (DeviceFrom, SeriesUID, PhysicalFrom, PhysicalTo))
+ {
+ OperatorConsole.printf("MoveSeriesToDevice: *** error comparing data for series: %s\n", SeriesUID);
+ free (SeriesUIDList);
+ // RestoreMAGFlags();
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("MoveSeriesToDevice: compared image data for series: %s\n", SeriesUID);
+ }
+
+ if (!ModifyDeviceNameForPatient (DeviceFrom, "", DeviceToString))
+ {
+ OperatorConsole.printf("MoveSeriesToDevice: *** could not set new device name\n");
+ free (SeriesUIDList);
+ return FALSE;
+ }
+
+ for (i=0; i<NSeries; i++)
+ {
+ SeriesUID = SeriesUIDList + i*256;
+
+ SystemDebug.printf("To delete: %s %s from %s\n", DeviceTo, SeriesUID, PhysicalFrom);
+
+ // extra check: file must be copied
+ // no error if file already copied before and cannot be deleted
+ if (!DeleteSeriesData (DeviceTo, SeriesUID, PhysicalFrom, PhysicalTo))
+ {
+ OperatorConsole.printf("MoveSeriesToDevice: *** error deleting data for series: %s\n", SeriesUID);
+ // free (SeriesUIDList);
+ //return FALSE; // mvh 20110105
+ }
+ else
+ OperatorConsole.printf("MoveSeriesToDevice: deleted source data for series: %s\n", SeriesUID);
+ }
+
+ free (SeriesUIDList);
+ return TRUE;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// assume DeviceTo = 'JUKEBOX1.123' and CACHEDevice0 = d:\davis\cache_%d_04d and JUKEBOXDevice0 = y:\CD%04d
+// then this routine compares directory 'd:\davis\cache_1_0123' with 'y:\CD0123'
+
+BOOL
+CompareBunchAfterBurning(char *DeviceTo)
+ {
+ int i, NPatients;//, Total, Size
+ char *PatientIDList, *PatientID;//, *p;
+ char PhysicalTo[1024], PhysicalCache[1024];//, CacheFrom[512], CacheDevice[512], Temp[512];
+// int JUKEBOXDevice=-1, CDNumber=-1, CacheNumber=-1;
+
+ // process input parameters
+
+ if (!GetPhysicalDevice(DeviceTo, PhysicalTo))
+ {
+ OperatorConsole.printf("Archival: *** invalid jukebox device: %s\n", DeviceTo);
+ return FALSE;
+ }
+
+ if (!FindCacheDirectory(DeviceTo, PhysicalCache))
+ {
+ OperatorConsole.printf("Archival: *** could not find cache device for: %s\n", DeviceTo);
+ return FALSE;
+ }
+
+ // make list of patients that are busy with archiving
+
+ NPatients = MakeListOfPatientsOnDevice(DeviceTo, &PatientIDList);
+ if (NPatients < 0)
+ {
+ OperatorConsole.printf("Archival: *** could not create patient list\n");
+ return FALSE;
+ }
+
+
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+ if (!ComparePatientData (DeviceTo, PatientID, PhysicalCache, PhysicalTo))
+ {
+ OperatorConsole.printf("Archival: *** error comparing data for patient: %s\n", PatientID);
+ free (PatientIDList);
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: verified jukebox data for patient: %s\n", PatientID);
+ }
+
+ free (PatientIDList);
+ return TRUE;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// assume DeviceTo = 'JUKEBOX1.123' and CACHEDevice0 = d:\davis\cache_%d_04d and JUKEBOXDevice0 = y:\CD%04d
+// then this routine deletes the contents of directory 'd:\davis\cache_1_0123' but only after the comparison
+// between 'd:\davis\cache_1_0123' and 'y:\CD0123' has been succesful !
+// Also deletes same images from MIRROR0 if MIRROR0 is defined
+
+BOOL
+DeleteBunchAfterBurning(char *DeviceTo)
+ {
+ int i, NPatients;//, Size, Total;
+ char *PatientIDList, *PatientID;
+ char PhysicalTo[1024], Temp[512], PhysicalCache[1024];//, CacheFrom[512], CacheDevice[512];
+ char Mirror[512], PhysicalMirror[1024];
+// int JUKEBOXDevice=-1, CDNumber=-1, CacheNumber=-1;
+
+ // process input parameters
+
+ if (!GetPhysicalDevice(DeviceTo, PhysicalTo))
+ {
+ OperatorConsole.printf("Archival: *** invalid jukebox device: %s\n", DeviceTo);
+ return FALSE;
+ }
+
+ if (!FindCacheDirectory(DeviceTo, PhysicalCache))
+ {
+ OperatorConsole.printf("Archival: *** could not find cache device for: %s\n", DeviceTo);
+ return FALSE;
+ }
+
+ sprintf(Mirror, "MIRROR0");
+ if (!GetPhysicalDevice(Mirror, PhysicalMirror))
+ {
+ Mirror[0] = 0;
+ }
+
+ // make list of patients that are busy with archiving
+
+ NPatients = MakeListOfPatientsOnDevice(DeviceTo, &PatientIDList);
+ if (NPatients < 0)
+ {
+ OperatorConsole.printf("Archival: *** could not create patient list\n");
+ return FALSE;
+ }
+
+
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+ if (!ComparePatientData (DeviceTo, PatientID, PhysicalCache, PhysicalTo))
+ {
+ OperatorConsole.printf("Archival: *** error comparing data for patient: %s\n", PatientID);
+ free (PatientIDList);
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: verified jukebox data for patient: %s\n", PatientID);
+ }
+
+ for (i=0; i<NPatients; i++)
+ {
+ PatientID = PatientIDList + i*256;
+ if (!DeletePatientData (DeviceTo, PatientID, PhysicalCache, NULL))
+ {
+ OperatorConsole.printf("Archival: *** error deleting cache data for patient: %s\n", PatientID);
+ free (PatientIDList);
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: deleted cache data for patient: %s\n", PatientID);
+
+ if (Mirror[0])
+ {
+ if (!DeletePatientData (DeviceTo, PatientID, PhysicalMirror, NULL))
+ {
+ OperatorConsole.printf("Archival: *** error deleting mirror data for patient: %s\n", PatientID);
+ free (PatientIDList);
+ return FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: deleted mirror data for patient: %s\n", PatientID);
+ }
+ }
+
+ free (PatientIDList);
+
+ // attemp to remove cache directory (ignore fail if not empty)
+
+ strcpy(Temp, PhysicalCache);
+ Temp[strlen(Temp)-1]=0;
+ rmdir(Temp);
+
+ return TRUE;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// this routine compares patients from a MAG0 device (or e.g., MAG0.Archiving) to its MIRROR device
+
+BOOL
+VerifyMirrorDisk(char *DeviceFrom)
+ {
+ int i, NPatients, number;
+ char *PatientIDList, *PatientID;
+ char PhysicalFrom[1024], DeviceTo[512], PhysicalTo[1024];
+ BOOL status=TRUE;
+
+ // process input parameters
+
+ if (!GetPhysicalDevice(DeviceFrom, PhysicalFrom))
+ {
+ OperatorConsole.printf("Archival: *** invalid main device: %s\n", DeviceFrom);
+ return FALSE;
+ }
+
+ if(strnicmp(DeviceFrom, "MAG", 3)==0)
+ {
+ number = atoi(DeviceFrom + 3);
+ sprintf(DeviceTo, "MIRROR%d", number);
+
+ if (!GetPhysicalDevice(DeviceTo, PhysicalTo))
+ {
+ OperatorConsole.printf("Archival: *** invalid mirror device: %s\n", DeviceTo);
+ return FALSE;
+ }
+ }
+ else
+ {
+ OperatorConsole.printf("Archival: *** main device must be a MAG device: %s\n", DeviceFrom);
+ return FALSE;
+ }
+
+ // make list of patients that are busy with archiving
+
+ NPatients = MakeListOfPatientsOnDevice(DeviceFrom, &PatientIDList);
+ if (NPatients < 0)
+ {
+ OperatorConsole.printf("Archival: *** could not create patient list\n");
+ return FALSE;
+ }
+
+
+ for (i=NPatients-1; i>=0; i--)
+ {
+ PatientID = PatientIDList + i*256;
+ if (!ComparePatientData (DeviceFrom, PatientID, PhysicalFrom, PhysicalTo))
+ {
+ OperatorConsole.printf("Archival: *** error comparing mirror data for patient: %s\n", PatientID);
+ status = FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: verified mirror data for patient: %s\n", PatientID);
+ }
+
+ free (PatientIDList);
+ return status;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// this routine test reads all images of a MAG device (or e.g., MAG0.Archiving)
+
+BOOL
+TestImages(char *DeviceFrom)
+ {
+ int i, NPatients;//, number;
+ char *PatientIDList, *PatientID;
+ char PhysicalFrom[1024];//, DeviceTo[512], PhysicalTo[1024];
+ BOOL status=TRUE;
+
+ // process input parameters
+
+ if (!GetPhysicalDevice(DeviceFrom, PhysicalFrom))
+ {
+ OperatorConsole.printf("Archival: *** invalid device to test read: %s\n", DeviceFrom);
+ return FALSE;
+ }
+
+ // make list of patients on the device to test
+
+ NPatients = MakeListOfPatientsOnDevice(DeviceFrom, &PatientIDList);
+ if (NPatients < 0)
+ {
+ OperatorConsole.printf("Archival: *** could not create patient list\n");
+ return FALSE;
+ }
+
+
+ for (i=NPatients-1; i>=0; i--)
+ {
+ PatientID = PatientIDList + i*256;
+ if (!TestPatientData(DeviceFrom, PatientID, PhysicalFrom))
+ {
+ OperatorConsole.printf("Archival: *** error test reading data for patient: %s\n", PatientID);
+ status = FALSE;
+ }
+ else
+ OperatorConsole.printf("Archival: test read all data for patient: %s\n", PatientID);
+ }
+
+ free (PatientIDList);
+ return status;
+ }
+
+////////////////////////////////////////////////////////////////////////
+// change device name in database for all images on that device
+// useful to restore from optical disk or to repare a database
+
+BOOL
+RenameDevice(char *DeviceFrom, char *DeviceTo)
+ {
+ char DeviceToString[256];
+
+ sprintf(DeviceToString, "DeviceName = '%s'", DeviceTo);
+
+ if (!ModifyDeviceNameForPatient (DeviceFrom, "", DeviceToString))
+ {
+ OperatorConsole.printf("Archival: *** could not set new device name %s\n", DeviceToString);
+ return FALSE;
+ }
+ else
+ {
+ OperatorConsole.printf("Archival: set new device name %s\n", DeviceToString);
+ }
+
+ return TRUE;
+ }
+
+
+static int SortP(const void* pElem1, const void* pElem2)
+ {
+ int i = strnicmp((char *)pElem1, (char *)pElem2, 128);
+ if (i==0) return -strnicmp((char *)pElem1+128, (char *)pElem2+128, 128);
+ else return i;
+ }
+
+static int SortD(const void* pElem1, const void* pElem2)
+ {
+ return strnicmp((char *)pElem1+128, (char *)pElem2+128, 128);
+ }
+
+// example: Max=10, Device = "MAG0", Sort = "StudyDate" -->
+// gives 10 least recent scanned patients on MAG0
+// Sort can typically be StudyDate, PatientBir, AccessTime
+// If Max<0 give most recently used patients
+// If Sort is empty sorts on AccessTime
+
+int
+MakeListOfOldestPatientsOnDevice(char **PatientIDList, int Max, const char *Device, char *Sort)
+ {
+ // Query the patient table, and sort it by access time
+ SQLLEN sdword,sdword1;
+ Database DB;
+ char s[256], DeviceValue[256];
+ char PatientID[128], StudyDate[128], QueryString[512];
+ int Patients, NStudy, i, Result;
+ char *StudyList;
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ return -1;
+
+ // count #studies
+
+ if (!DB.Query(StudyTableName, "PatientID", "", NULL))
+ return -1;
+
+ DB.BindField (1, SQL_C_CHAR, PatientID, 128, &sdword);
+ NStudy = 0;
+ while(DB.NextRecord())
+ NStudy++;
+
+ // list patientID and sort field for all studies
+ // some new patients may recently have come in!
+ StudyList = (char *)malloc(256 * (NStudy + 100));
+ if (StudyList==NULL) return -1;
+
+ strcpy(s, "PatientID");
+ if (Sort && Sort[0])
+ {
+ strcat(s, ", ");
+ strcat(s, Sort);
+ }
+ else
+ strcat(s, ", AccessTime");
+
+ if (!DB.Query(StudyTableName, s, "", NULL))
+ {
+ free(StudyList);
+ return -1;
+ }
+
+ if(!DB.BindField (1, SQL_C_CHAR, PatientID, 128, &sdword))
+ {
+ free(StudyList);
+ return -1;
+ }
+
+ if(!DB.BindField (2, SQL_C_CHAR, StudyDate, 128, &sdword1))
+ {
+ free(StudyList);
+ return -1;
+ }
+
+ NStudy = 0;
+ while(DB.NextRecord())
+ {
+ strncpy(StudyList + 256*NStudy, PatientID, 128);
+ strncpy(StudyList + 256*NStudy + 128, StudyDate, 128);
+ NStudy++;
+ }
+
+ // sort list of patients (ascending), sorted on descending study date per patient
+ // then delete all but newest entry per patient
+
+ qsort(StudyList, NStudy, 256, SortP);
+
+ Patients = 0;
+ const char *prevpat="";
+ char *p=StudyList;
+ for (i=0; i<NStudy; i++)
+ {
+ if (strnicmp(prevpat, StudyList + 256*i, 128)==0)
+ continue; // same patient
+
+ prevpat = StudyList + 256*i;
+ memcpy(p, prevpat, 256);
+ p += 256;
+ Patients++;
+ }
+
+
+ // sort patients on ascending newest study date
+ // then test for each patient if it occurs on device
+
+ qsort(StudyList, Patients, 256, SortD);
+
+ // return the list: either testing on device or not
+
+ *PatientIDList = (char *)malloc(256 * abs(Max));
+ if (*PatientIDList==NULL)
+ {
+ free (StudyList);
+ return -1;
+ }
+
+ Result = 0;
+
+ if (Device && Device[0])
+ {
+ MakeSafeString(Device, DeviceValue, &DB);
+
+ for (i=0; i<Patients && Result<abs(Max); i++)
+ {
+ MakeSafeString(StudyList + 256*i, s, &DB);
+
+ sprintf(QueryString, "DICOMImages.DeviceName %s and "
+ "DICOMImages.ImagePat %s",
+ DeviceValue, s);
+
+ if (!DB.Query(ImageTableName, "ImagePat", QueryString, ""))
+ {
+ free (StudyList);
+ return -1;
+ }
+
+ DB.BindField (1, SQL_C_CHAR, PatientID, 128, &sdword);
+
+ if (DB.NextRecord())
+ {
+ if (Max>0) strcpy(*PatientIDList + 256*Result, StudyList + 256 * i);
+ else strcpy(*PatientIDList + 256*Result, StudyList + 256 * (Patients-1-i));
+ Result++;
+ }
+ }
+ }
+ else
+ {
+ for (i=0; i<Patients && i<abs(Max); i++)
+ {
+ if (Max>0) strcpy(*PatientIDList + 256*Patients, StudyList + 256 * i);
+ else strcpy(*PatientIDList + 256*Patients, StudyList + 256 * (Patients-1-i));
+ Result++;
+ }
+ }
+
+ free (StudyList);
+ DB.Close();
+ return Result;
+ }
+
diff --git a/dgate.cpp b/dgate.cpp
new file mode 100644
index 0000000..20c6e3f
--- /dev/null
+++ b/dgate.cpp
@@ -0,0 +1,24322 @@
+/*
+MvH 19980327: Disable logfile for speed and save disk
+MvH 19980327: -! Enables logging to Personal pacs console; RunServer works; -p breaks
+MvH 19980327: All printf's to systemdebug
+MvH 19980320: Integrated dumppacs code here for convenience
+MvH 19980320: Fixed -p option; SaveToDisk returns filename, printed in stats
+MvH 19980320: Documented and added print of usage
+MvH 19980404: Added test options, SQL config option and command line specified console pipe/udp
+MvH 19980409: added FileCompressMode option; use local save to disk code instead of pdu member
+MvH+LJZ 19980409: Return on failed GenerateFileName in SaveToDisk
+MvH 19980409: Cleaned up nki private compression code and allow >15 bit differences
+MvH 19980410: Added run length encoding for equal pixels to compressor; fix 3-byte case
+MvH 19980415: Cleaned up the messages; -! does not enable debug; do not enable accessupdates (use aroute)
+MvH 19980618: Some work on manual and database layout listing
+MvH 19980621: Added -z option: zap patient
+MvH 19980624: Comm test also produces systemdebug and long text output; added \n to some output
+MvH 19980625: SaveDicomDataObject in loadddo.cpp supports NKI compression
+MvH 19980704: Added some test code for counting disk space and renaming device for patient
+MvH 19980705: Added CACHE devices in free store check; added FindPhysicalDevice (searches for file)
+MvH 19980709: Added archiving options: -as, -au, -ab, -ac, -ad
+MvH 19981217: Temporary use PDU.Save... code for testing DICOM objects (does not compress)
+MvH 19981218: Temp use Pdu.Load as well (no compression)
+MvH 19981228: Disabled ljz's code until it has been completed
+ljz 19990108: Reenabled ljz's code: Replace uncompressed by compressed pixeldata VR in
+ SaveToDisk (it seemed to work anyway...)
+MvH 19990109: Removed some commented out code; added comments for alternative load and save routines
+ Added Regen of specified device
+MvH 19990110: Added n, for MAGn, as parameter in -as and -ab archiving options (default all)
+ exit(1) on failure
+MvH 19990111: Fixed exit code on -ar option
+MvH 19990117: If the filename is *.dcm (depends on FileNameSyntax) use uncompressed chapter 10 format
+ljz 19990317: Added NKI-private stuff
+MvH 19990628: Temporary enabled debug in -!nnnn option
+MvH 19990630: Added MIRROR option; disabled debug in -!nnnn option
+MvH 19990707: Fixed MIRROR option; added MIRROR message; added check on FindPhysicalDevice result
+ljz 19990817: Added ability to spawn ExportConverters at the end of SaveToDisk
+MvH 19990827: Optimized read of slices: cache a DB to pass to GetFileName (10% faster)
+ljz 19991117: Added parameter FileCompressMode to in nki_private_compress call
+mvh 20000318: Added private command object 9999, 0300 = print to console
+ Added private command object 9999, 0400 = force C-Echo to be 'silent' (no log)
+ Display C-Move Destination; print time info about threads
+ljz 20000323: Serious fix: MainThread 'hangs' when several associations occur simultaneously, caused
+ by compiler-optimisation. Solution: DriverApp.Lock should be 'volatile'.
+mvh 20000329: On request by ljz: designed crash of server if silent VR receives 'DEAD'
+ljz 20000501: Compare dicom modality with UPPER-case ini-file setting (ExportConverters)
+ljz 20000221: Initialize TroubleLogFile and UserLogFile; log C-STORE and C-MOVE
+ljz 20000703: Logging of trouble now starts with '***'
+mvh 20000703: Exclude archival messages from trouble log; removed force dcm code
+mvh 20001104: Added WINAPI to thread routines
+mvh 20001105: Replaced malloc by new where a mix could occur (vr->data)
+ Made compilable for MSC and BC and WC using some #ifdefs
+ Changed order of verification and store; better localized new/delete DDO more
+mvh 20001106: Run-time load odbcinst routine for BC and WC, use spawn... i/s/o _spawn...
+mvh 20001106: Use delete [] operation for vr->Data
+mvh 20010328: Added -av: verify mirror disk
+mvh 20010415: Added DeleteSeries, DeleteStudy and DeleteImage routines and -f options
+mvh 20010416: Added -f options: -feFile = enter MAGN file into DB, -fdFile = delete file from DB
+ -faFile = add (also makes copy) file into server, -f?=ask UID of file,
+ -fu = generate UID, -fcNEWPATID,file = modify patient ID of image file (moves file!)
+ NOTE: -fc is irreversible in the sense that if a portion of a study/series is changed
+ and changed back it winds up as a different study/series. This occurs because the
+ UIDs must be changed for each image modification. This problem does not occur when
+ a whole series or study is changed
+mvh 20010417: Simplified code to change uids to allow easy extension to referenced SOPs
+ Check after load on common UIDs to avoid accepting dropped non-dicom files
+ NOTE: ChangeUIDinDDO should also change sequences and referenced SOPs (0008,1155)
+mvh 20010418: Fix in above change
+mvh 20010418: Changed names of database fields in UIDMODS - did not work on msaccess
+mvh 20010419: Added -fk option: copy image file to other patient ID (as -fc but no delete)
+ Added version number 1.3.9 to command line help
+mvh 20010429: Added -fz option: zap file from server and database
+mvh 20010430: Some work on read ahead thread: note that thread must not use any pointer copy!
+mvh 20010502: Made read ahead thread working; fixed thread counter; fix odbc option: strings too short
+mvh 20020506: Fixed handle leak in read ahead thread
+mvh 20020507: Fixed memory leak in read ahead thread; kbhit() test #ifdef DO_LEAK_DETECTION
+mvh 20010509: Added RenameDevice is -ae option
+ljz 20010730: Replaced parameter argv[0] of ExportConverters to proper value
+mvh 20010829: Added ExportStationName as export filter; default Export... value set to "*"
+ Made export comparisons case insensitive; added special 'forward to AE' ExportConverter
+ Version to 1.3.10
+mvh 20010831: Added extended syntax for exportconverters with %f=filename, %m=modality,
+ %s=stationname, %b=file base name, %p=file path;
+ Also allows 'copy %f destination', but for windows NT only (uses cmd.exe)
+ Added ExportFilter option that uses an SQL statement to filter.
+mvh 20010901: Added a simple queue to process exportconverters asynchroniously
+mvh 20010901: Create a queue for each converter; queue mirror copy requests
+mvh 20010902: Added %o = SOP; %n = newline; added the following hard coded converters:
+ append "text" to file; write "text" to file; copy file to file; copy file to dir
+ljz 20010904: Re-entered change of 20010730
+ljz 20010905: Fix: After 'SaveToDisk', do not free pDDO
+mvh 20011109: Fix: made ExportConverter stuff case insensitive
+ Note: empty filter tests for empty contents - this is not the same as '*'
+ Released 1.3.10
+mvh 20011110: Note: in release 1.3.10, the " to " in e.g., write "%f%n" to file must be lowercase
+mvh 20011115: Made " to" case insensitive; Added *** before some error messages for better logging
+ Removed cache db: would hang the server if SQL has gone down and up.
+ Now use one DB per thread which is passed to the read ahead thread = fast too!
+ljz 20011207: Added extra errormessage when creation of datasource fails
+mvh 20020109: Disabled this code for watcom or borland (instead of run-time loading an address)
+mvh 20020314: Implemented ignore of C-CANCEL request for ADAC NM (was error before)
+ Blocked out SQLInstallerError call; does not compile on clinical MS4.2
+mvh 20020413: Added some notes about thread safety and db's: The serverchild is not thread
+ safe when reading and writing is done on the same association.
+mvh 20020415: Added -atDEVICE option: sanity check of images on disk; version to 1.3.11
+mvh 20020416: Made UID generator configurable through UIDPrefix in dicom.ini; made time print unsigned
+mvh 20020422: Sleazy fix of ModifyPatID: time(null) created same UID: now wait 1 s per changed file
+mvh 20020426: Generate filename no longer gives an error: is done at higher level
+mvh 20020428: Only serious error messages use *** in message
+mvh 20020428: Added FAILSAFE_STORAGE: tries to save incoming files even when DB errors occur
+mvh 20020429: Put SaveToDisk in myUnknownStorage: pass DB failures to caller
+ Disabled FAILSAFE_STORAGE: any storage failures should now be detected by client
+mvh 20020508: Do not rewrite image not on MAG but it is not an error (warning is generated earlier)
+mvh 20020520: Added -gSERVER,DATE option: grab images on date from remote server
+mvh 20020521: fix displaying junk filename when rewriting image not on MAG
+ljz 20020522: Fix in SetStringVR: strings must be padded with a space
+mvh 20020529: -i and -r now have mode parameter (0=normal and default, 1=simple, e.g., for DBASEIII)
+ljz 20020531: In 'QualifyOn', support case-sensitive call to 'GetACRNema', but make AE-Title
+ uppercase after retrieving IP and port.
+ljz 20020613: Better handling of Compression ON/OFF in 'SaveToDisk'
+ Fixed crash in DeleteImageFile (twice free of VR->Data)
+mvh 20020613: compress to specified mode, check (de)compress result, decompresses data before
+ forward; added 'export compressed to AE' export; -fa has optional ,NEWPATID syntax;
+mvh 20020802: Simplified rmdir code and allow multiple subdirectories in rmdir and mkdir code
+ Version to 1.3.12 (unreleased)
+mvh 20020804: Use PATHSEPCHAR where possible
+mvh 20020807: Changed SaveToDisk order: only make patientdir when DB save succeeded
+mvh 20020812: Added skeleton of printer support
+mvh 20020816: Added color imagebox; Save incoming print DDO as file
+mvh 20020819: UIDs of imageboxes end on rows.cols.position for easy print handling
+mvh 20020819: Fix in delete unexistent mirror files for changepatientUID
+ Extract pixel data from sequence in ImageBox; added sleep(10) in -fk option
+mvh 20020819: Added better UID generation (but gets close to 64 chars)
+mvh 20020821: Fix printer UID generation; display page orientation and film #; shorter info
+mvh 20021016: Added (indexed) patid to exportfilter query and getfilename for speed;
+ The option tests for rev5 db or higher; increase 64 strings to 66;
+ Note: the GrabImagesFromServer option does not yet pass patid to the query
+ (i.e., will be slow with non-odbc driver)
+mvh 20021017: Control NeedPack from here; added -c option: set UID counter at startup
+ Removed Sleep from anonimize options; do not re-create UIDMODS
+mvh 20021018: Pass NoKill through GenerateFilename for interactive DGATE
+mvh 20021028: Fix query on study in PatientStudyOnlyQuery (did an image query)
+mvh 20021105: Revamped read-ahead thread logic to try fix rare crash where ratd->DDOOutPtr became NULL
+mvh 20021115: Use Generic style retrieve classes with NKIqrsop code instead of older qrsop code
+ Advantages: read ahead thread used, and allows print of error messages from C-MOVE
+ Required changes such that ratd->pcdo can be NULL.
+mvh 20021121: Disabled read-ahead thread for time being
+mvh 20021212: Also loop ServerApp.Server(Port) in threaded mode server
+mvh 20021213: Re-entered fix by Hanne Kooy: compressed forwarding had extra ;
+mvh 20021213: Re-enabled use of generic query classes with read-ahead thread;
+ but made read-ahead thread configurable with "EnableReadAheadThread"
+ Made grab query faster by including date - note grab is independent of FixPhilips
+mvh 20021215: Found read-ahead thread problem reported by Aaron Cann - missing Sleep in wait for slices
+mvh 20021223: Version to 1.4.1 pre-release; added in dgatefn forbidden filename chars suggest by Thomas Buerer
+mvh 20030113: Removed loop ServerApp.Server(Port): gave endless loop error messages
+ljz 20030120: Added cleanup-code when DO_LEAK_DETECTION is defined for easy leak checking
+mvh+ljz 20030205: Fix bug found by Frank-Andre Siebert: read ahead thread crashed when ID or SOP is missing
+ Also fix 2 other potential missing VR problems
+mvh 20030228: Fixed bug reported by Jeff Bacbcock: series retrieve from E-film crashed (patid not passed)
+ljz 20030424: Version to 1.3.12
+ Changed calls to obsolete PDU.Write(&DDO)
+ In 'SaveToDisk' the call to PDU.SaveDICOMDataObject now has parameterDICOM_CHAPTER_10_EXPLICIT
+ (which in writes IMPLICIT files iff not compressed)
+ljz 20030606: Fixed incremental counter when creating UIDs or generating filenames
+ Fix: QueryRetrieveLevel is mandatory for a QueryResponse
+mvh 20030625: Fix NGET of BasicPrinterSOPClass
+ljz 20030625: Fix in above fix
+mvh 20030627: Adapted for MSC4.2; Finally really fix NGET of BasicPrinterSOPClass (wrong UID used)
+mvh 20030629: Added -nd, -nc, -jd and -jc options: (de)compress NKI; (de)compress JPEG (used OFFIS executables)
+mvh 20030630: Started on compression for dropped, incoming, transmitted; NKI vr 0x9999,0x700=custom compression
+ Added 'forward compressed as xx to ...'
+mvh 20030701: QualifyOn now also has compression parameter
+mvh 20030703: Moved compression code to nkiqrsop; dgate -j-xx and -j*xx = test compression options
+ Removed "forward compressed to" because "forward compressed as .. to" is better.
+ Note that FileCompressMode is now obsolete. KNOWN BUG: JPEG compressed images may be
+ rewritten as V2 (when written originally as NKI) which are then not correctly read.
+mvh 20030704: Made that FileCompressMode parameter still works even though is obsolete
+ Moved faulty delete DDO after SOPUnknownStorage.Read
+mvh 20030705: Added check of Tranfer Syntax next to extension for save type; ProcessDDO takes **DDO
+mvh 20030706: Use dgate.dic; Attach VRType to PDU's for implicit little endian support; small fix in dump code
+mvh 20030709: Printer support fix; version to 1.4.2; added SendUpperCaseAE parameter (default 0)
+ljz 20030730: Force ImplicitLittleEndian, ExplicitLittleEndian and ExplicitBigEndian objects that must
+ be stored in Chapter10 format, to ImplicitLittleEndian.
+mvh 20030815: Version to 1.4.3
+mvh 20030905: Allow longer filenames
+mvh 20030910: Added check on rights to write (trouble) log file and printer_files in MAG0
+mvh 20030921: Allow write to any MIRROR if MAG is full; added -ff# option: delete until # MB free
+mvh 20030922: Added StorageFailedErrorCode (default 0x110 = 272 decimal = failed processing)
+ Added ExportCallingAE and ExportCalledAE export filters (also %u=SCU, %c=calledAE in converter)
+mvh 20040401: Version to 1.4.4; pass status pointer to compress routines
+mvh 20040402: Delete DDOptr when SaveToDisk cannot write but does not give an error
+ Added "Cannot rewrite jpeg/rle image in v2 format" check
+ Use system DSN for ODBC (easier login)
+mvh 20040406: Always use EXPLICIT syntax for jpeg, fix v2 always use DUMP
+mvh 20040426: Version to 1.4.4a
+mvh 20040520: Version to 1.4.4b
+mvh 20040523: Added patient ID to speed GetFileName for single slice move
+ljz 20040602: Fix: 'forward compressed as' always failed
+mvh 20040528: Set NeedPack (controls DbaseIII indexing) for regen, archive, maintenance; Version to 1.4.4c
+mvh 20040528: Added built-in maintenance commands through silent VR in ECHO; pass patid in DeleteImageFile
+mvh 20040530: extract (DBF only) to database like XDicomImages in same directory; Version to 1.4.5
+mvh 20040601: Added deletestudy, deleteseries and packdbf maintenance commands
+mvh 20040605: packdbf maintenance command sets NeedPack to 3: forces pack
+mvh 20040606: fix rewrite to not MAG (JUKEBOX) was NOT ignored
+mvh 20040607: Merged fix ljz 20040602; do not allow rename and delete with empty name
+mvh 20040610: Added maintenance server tasks for archival and regeneration
+mvh 20040612: Added indexdbf maintenance server task
+mvh 20040614: dgate command line maintenance options use NeedPack=5: non-threaded index generation
+ Added -am option: move (all) device data; to move selected data use -amMAG0.Archiving,MAG1
+mvh 20040624: Version to 1.4.5a
+mvh 20040626: Pass study and series UID to getfilename; version to 1.4.5b; Fixed leak of pats array
+mvh 20040713: Version to 1.4.6
+mvh 20040805: Fix in C-MOVE for single file (fix from ljz); version to 1.4.6b
+ljz 20040909: Increased length of ExportFilter (was 64, now 510)
+mvh 20041020: Added mergeseries(file) and mergestudy(file) maintenance commands, silenttext to 1024
+mvh 20041101: Added deletesopfromdb maintenance command; version to 1.4.7
+mvh 20041103: called, e.g., AE~nj overrides IncomingCompression to nj
+mvh 20041108: Added $c test compression mode (alt-drop files with $c as patient ID tests compression modes)
+mvh 20041109: Added $tSERVER test compressed forward; some fixes in forward compressed to (server name read wrong)
+ $s tests all filename syntaxes
+mvh 20041112: Added $rN N times repeated entry test, and $tN which enters image N time each on its own thread
+mvh 20041128: Added -^file: log to file (timestamped) instead of to server console; -#file: same with debug
+mvh 20041129: Added silent commands debuglog_on and log_on to set logging to UDP or file
+ Added silent command read_amap to re-read acrnema.map without restarting the server
+mvh 20050102: Small modifications to allow compile through total.cxx
+mvh 20050107: Added code to hold and retry queued forwards and mirror copies when failed:
+ After failed export/copy, start storing entries in file ExportFailuresN (CopyFailures)
+ if a new export/copy is requested >1 minute after last failed one, try again
+ if queue is empty, >100 seconds after last fail, try export/copy stored ones
+ processing queued entries has priority over processing stored entries
+mvh 20050107: Version to 1.4.8; modifications for linux compile
+mvh 20050108: Added server PORT# to fail files, so that multiple servers on different ports do not share files
+mvh 20050109: Added configurable TCPIPTimeOut, FailHoldOff, RetryDelay and QueueSize
+mvh 20050109: Adapted thread code for linux; still need to implement WaitForSingleObject
+mvh 20050111: Added ctype.h (for mingw)
+mvh 20050118: Linux: crudely implemented WaitForSingleObject; detach pthreads to avoid leaks;
+ crudely implemented export converter apps
+mvh 20050119: Added grabimagesfromserver, regendir and makespace server commands
+ dgate -- sends server commands to other running server; adapted manual
+mvh 20050121: Small updates to manual
+mvh 20050124: Replaced BackGroundExec with simpler system() for Linux; added query server command, e.g.,
+ dgate "--query:DICOMpatients|patientid,patientname,patientsex|patientsex='F'|%s %s %s|t.t"
+ Added read_ini: server command to reread dicom.ini; changes most config except:
+ TCPPort (busy), UseBuiltInDecompressor (cached) and FileNameSyntax (cached)
+mvh 20050130: added get_param, get_freestore, get_amap, get_sqldef that respond through echo-response
+ also: get_sop, get_transfer, get_application, get_localae, get_remoteae, get_dic, forward
+ added: dump_header (to file), convert_to_gif (to file); adapted query (to file)
+ where file="cgi" for stdout in cgi/mime mode, file="" to send to stdout as is
+ most GUI commands can now pass PatientID|SOPInstanceUID instead of filename of dicom object
+ added put_amap, write_amap, put_sop, put_transfer, put_application, put_localae, put_remoteae,
+ put_param. Note: get/put_param work through disk (read_ini activates), get/put_amap through
+ memory (write_amap writes to disk), get/put_sop etc read from memory and write to mem and disk.
+mvh 20050204: Added delete_param, delete_amap and fix cgi output (double \n)
+mvh 20050204 most GUI commands can now pass PatientID|?*:SOPInstanceUID; added delete sop etc commands
+ More fixes in cgi data passing VR vr() is mostly wrong; use VR *vr=new VR()
+mvh 20050205: Allow up to 16 output fields in query:, repeat queried fields over all 16 outputs
+ Added counters for server status; start on display_status server command
+mvh 20050206: More work at display_status, renamed testtable to xtesttable: default not opened
+ Access ObjectFile and DeviceName through query instead of with GetFileName up to 3 x faster!!
+ Also fixes potential leak in read ahead thread: pats, series and studies not always freed
+ Allow up to 32 cgi query outputs, tidied dump layout, start on web interface (put dgate and ini in cgi-bin)
+mvh 20050207: Added query2 option: limits number of output rows as asked; gui command not counted as association
+ Some more work for web interface
+mvh 20050210: Adapted web interface queries such that they run on sql server
+mvh 20050212: Removed need for thread local storage; automatically adapt dgate extension in cgi scripts depending in OS
+mvh 20050213: Added more parameters to server configuration web page
+mvh 20050214: Added update button to server config (updateconfig page to be implemented)
+ljz 20050215: Fix in LoadForGUI: Drag 'n' drop of files in the server did not work anymore
+ Fixed dgate crash in case of failure in 'recompress()' (pDDO=NULL when OFFIS failes)
+ mvh merged
+mvh 20050327: Added rudimentary gz unzip support for dropped files (uses 7za.exe)
+mvh 20050401: Start on Modality WorkList Support
+mvh 20050404: List End/Start sequence db types (only supported for worklist)
+mvh 20050411: Fix incorrect space after filename and device in C-MOVE internal query
+mvh 20050414: Added addrecord server command: for now only option to enter worklist entries
+mvh 20050603: Fix servercommand query(2) for empty where part
+mvh 20050825: Fix web interface queries for sql server (were OK for dbase)
+mvh 20050826: More work on web interface and added worklist there; deleterecord command
+mvh 20050827: Fixes in addrecord and query commands, editworklist,saveworklist,deleteworklist
+mvh 20050829: More fixes in web interface, disable caching for most/all? of it
+mvh 20050831: Allow command line length of up to 4096, allow edit all worklist database fields
+mvh 20050901: Removed invalid cache-control: cache; added WorkListMode:0= off, 1=optional, 2=compulsory
+mvh 20050902: Read db config for worklist edit page in web interface; use generic webpages for db edit
+ Added HL7Tag in DumpDD
+mvh 20050903: Added 'simple' loadhl7: server task implementation and HL7->DICOM translation
+ Also addimagefile will enter HL7 files into the server, i.e., drag and drop works
+ Fix some web queries for sql server with denormalized tables
+mvh 20050904: Some more tweaks to hl7 code; max query formats to 48; max format to 8192
+mvh 20050905: Auto split HL7 subfields and repeats without using a list
+mvh 20050907: Merged change by Hans-Peter Hellemann: fixes extension problem for linux web
+ interface for some browsers
+mvh 20050908: Protect convert_to_gif when file not found
+mvh 20051121: Recompute SQLResultLength because it does not work in PostGres BindField
+mvh 20051123: put in #ifdef POSTGRES
+mvh 20051208: put in #if 0 (fixed in odbci.cpp); start on virtual server: will grab images from
+ other server as needed in read-ahead thread: when in db but not on disk; for now
+ use rat also for single image access to avoid code duplication
+mvh 20051209: Start on virtual query: image (!) query is passed to other server, results populate db
+mvh 20051210: Added "vX" incomingcompression (stores dbf but not image; forwarding disabled)
+ Added virtual queries on all queries and moves: now works as transparant file cache
+ Added VirtualServerFor0..9 configuration entries: server merges own data with these AE's
+ Added CacheVirtualData control; if set data not deleted after use (db kept for now)
+mvh 20051211: Fix: override query level in virtual query
+mvh 20051212: Store virtual server # in device; saved on query, used when retrieving, stripped when storing
+mvh 20051214: Use different sleep lenghts under linux - not all sleep(0); small fix in virtual server
+mvh 20051215: Implemented a linux version of Sleep using nanosleep
+mvh 20051217: Use new VR::ReAlloc method to replace data in VR; added quit: command
+mvh 20051218: Use ReplaceVR instead of Push in anonymize etc; also changes in sequences
+ Version to 1.4.10; show version and exe date in startup log
+ Do not start mirror copy queue unless it is needed; show some thread startup info
+ Added -b = NOTHREAD: run server as single process, useful for debugging and profiling
+ Fixed doc of --regendir: command
+mvh 20051219: Fixed several small leaks - as tested with Linux malloc_stats
+mvh 20051222: Started on bypass server for virtual query - not functional yet (cleanup required)
+ Removed debugVR logic: errors should now list DCO
+mvh 20051228: Fix virtual device logic for VirtualServerFor0;
+ Cleanup vr's and duplicates when bypassing server for virtual query, seems functional
+mvh 20051229: NonDestructiveDumpDICOMObject now also list sequences;
+ DebugLevel>0 lists DCO, >1 lists query DDO; fixed leaks in virtual query and some others
+mvh 20051230: Added --debuglevel: command, small fix in NonDestructiveDumpDICOMObject
+mvh 20060103: Small fix in virtual query; disabled virtual query for worklist; debuglevel 3 shows some query results
+mvh 20060123: Added patient/study/seriesfinder (server parameter ignored for now, later for virtual servers etc)
+mvh 20060125: Added serieslister (server parameter ignored for now, later for virtual servers etc)
+mvh 20060128: Renamed to imagelister, added serieslister
+mvh 20060131: Sort filenames from imagelister on ImageNumber (0020,0013)
+mvh 20060226: Version to 1.4.11
+mvh 20060228: Small fix in isxdigit thanks to ljz
+mvh 20060311: Use ReplaceVR in virtual query - level was sent twice (thanks David Lang)
+ Added WEBReadOnly flag
+mvh 20060317: Support calledae and callingae in filenamesyntax - for virtualquery called is always MYACRNEMA
+mvh 20060324: Strip group 2 from outgoing c-stores if not compression "as" or "is"
+mvh 20060328: Improved forwarder, always propose Verification and use IsAbstractSyntaxAccepted(iUID) to test if host accepts image
+mvh 20060402: Fix hang condition when a file failed to read in the read-ahead thread
+mvh 20060402: Do not remove transfer syntax prior to dcmdjpeg/dcmcjpeg (here in test recompress only)
+mvh 20060405: Tried fix for multiple moves on same assoc (thanks Andrej Savelov)
+mvh 20060405: Added message when IOD fails to read
+mvh 20060603: Fix crash when started as dgate -v: empty statbuf
+mvh 20060607: Finally fixed multiple moves on same assoc (thanks Andrej Savelov and Fred Roener)
+mvh 20060618: Renamed dfilecopy and define ODBC_ADD_SYS_DSN if needed
+mvh 20060619: Set version to 1.4.12alpha1
+mvh 20060621: Added clonedb: command; transfer FULL db from other server to this one using virtualquery
+mvh 20060628: AddToDatabase has JustAdd parameter: skip one unnecessary query
+mvh 20060701: Speeded filter string handling
+mvh 20060702: Pass DB to GenerateFilename to avoid zillions of db open and closes
+mvh 20060704: Print number of records found in all queries
+mvh 20060708: Set version to 1.4.12alpha
+mvh 20061126: Moved servertask temporary files to MAG0/printer_files; protected query: and query2 against empty input
+mvh 20061126: Experimental forwarding on same association: close unused association after 5 seconds
+ Clean collected sopclasses after one hour of inactivity
+ Note 1: there is a problem with AReleaseRQ: do not use in this task
+ Note 2: maximal 20 forwarders have a remaining association
+mvh 20061127: Added ForwardAssociationLevel (PATIENT, SERIES, STUDY, IMAGE, SOPCLASS; default STUDY),
+ ForwardAssociationRefreshDelay (default 3600 s), and ForwardAssociationCloseDelay (default 5 s)
+ Limit maximum number of ExportConverters to MAXExportConverters=20 (for static arrays used in forwarders)
+ Forwarders keep association open as long as UID at ForwardAssociationLevel does not change.
+ Show filename in forward log; document where fixkodak should operate for virtual queries
+mvh 20061128: Added ForwardAssociationLevel GLOBAL: use association until timout or incompatible
+ Close ForwardAssociation after send when ForwardAssociationLevel is IMAGE
+mvh 20061129: VirtualServerForN may be "server,FIXKODAK" to clean queries (add 0) and their response (remove 0)
+ Hardcoded filters for exportconverters (modality, called, calling, station) can now match e.g., RT*
+mvh 20061130: Pass series and study in virtualserver outgoing c-move
+mvh 20061213: Fixed nasty bug in query2 and TestFilter: Query without bindfield overwrites previous bound strings!
+ Maybe was problem causing crash on linux with query2: and problem with option -g reportedly stopping incorrectly
+mvh 20061219: Version to 1.4.12
+mvh 20061231: Added ForwardAssociationRelease to allow testing reconnect problem (default 0 = just hangup)
+mvh 20070103: FixKodak blocks *xxxx wildcard virtual queries on date (not allowed in Kodak)
+mvh 20070103: Version to 1.4.12b; start on ImportConverters e.g., <set 0008,1040 to "%V0008,0080">
+mvh 20070104: ImportConverters %QP %QS %QE %QW; <destroy> <delete xxxx,yyyy> <save to filename>
+ Added %% and %i to Export and Import converters
+mvh 20070105: <set 0008,1040 if "...">, <setifempty 0008,1040 to "...">, <setifempty 0008,1040 if "...">
+ Import/export converters only report when syntax OK and report when action is void
+ Added %Vxxxx,yyyy to export converters and %d(date/time) to import and export converters
+ An import/export converter can thus be used to extensively log incoming images
+ Added import converters: <stop>, <if "string">, <ifempty "string">, <nop> (also export)
+ Added general purpose variables x, y, z (read as %x, %y, %z) to import converters
+ Definition of number of ImportConverters now unnecessary.
+ Note: importconverter and exportconverter strings may be changed run-time in dicom.ini
+mvh 20070105: Some fixes in dgate --archiving options manual; fixed dgate --restoremagflags:
+mvh 20070107: Fix web access broken by change in odbci for dbaseIII; query must now always include spaces around =
+mvh 20070113: Do not store NKI compressed data in v2 format: decompress and give error message
+ Recompress to NKI format now enables StripGroup2; Tested with $c server debug command
+mvh 20070117: Allow multiple rules per Export or ImportConverter separated by ; and zero or more spaces
+ <nop> statement prints itself on console: useful for logging anything that follows
+mvh 20070117: Now maintain multiple connections per ExportConverter line (max 20x20 forwards)
+ Added <stop>, <silentstop>, <if> and <ifempty> to ExportConverters; but they only affect single rule
+ (while these would cross over to the subsequent rules in ImportConverters)
+mvh 20070122: Now also show free space on mirror devices
+mvh 20070123: Fixed TestFilter for patientid with '
+mvh 20070125: Removed <if> and added <ifnotempty>, <ifequal>, <ifnotequal>, <ifmatch>, <ifnotmatch>,
+ <ifnumequal>, <ifnumnotequal>, <ifnumgreater>, <ifnumless> as im/exportconverters
+ Added %xxx[first,last] substring operator; and protect it against overrange
+ <ifxxx> no longer crosses over importconverters; added {} block for im/exportconverters
+ E.g.: ifequal "%V0008,0020[0,3]", "2004"; { forward to CONQUESTSRV3; forward to CONQUESTSRV4; } nop test
+ Note: 1) all (also ifxxxx) statements end with ; 2) statements may begin with { or };
+ 3) extra spaces only allowed after ;{} and single space after ,
+mvh 20070127: Fix {} in exportconverters.
+ Release 1.4.12b to fix more or less critical odbci error
+mvh 20070131: Fix in TestFilter (quotes double); Version to 1.4.12c
+mvh 20070201: Added <storage MAGn> import converter: sets device to store this (new) image to (default MAG0)
+ Fixed importconverters stop and destroy: did not break current line
+mvh 20070204: Added extra format starting with # to ImageFileLister: e.g. #%s:%s prints MAG0:filename
+mvh 20070206: Added create database: dgate -esapw name user password
+mvh 20070207: Fix query string bug on applyworklist found by capolan1
+mvh 20070207: dgate -e name root <blank> works for mysql: root is used as admin and login
+ Also implemented dgate -esapw name sa sapw where sapw may be empty
+mvh 20070210: Added CheckDuplicates to UpdateOrAddToTable; added @ in imagefilelister: replace \ by /
+ Start on ocx based viewer integrated in cgi interface; used dicom over http:
+ Small change in gif export; added * as separator in query/2
+mvh 20070211: Added WebScriptAddress (default http://server/cgi-bin/dgate), WebMAG0Address (defaults http://server/mag0)
+ and WebServerFor (default 127.0.0.1). Fix in cgi query parser: now loads dsize and size correctly
+ Version to 1.4.12d
+mvh 20070212: Added WebCodeBase, show version in status_display, added config of which dicom server the web server
+ connects to, added [webdefaults] section, added iconsize parameter
+mvh 20070213: Added : as format in imagefilelister: use to list pat:sopuid
+ Fixed sorting problem by using adapted imagefilelister for seriesviewer
+ Fixed default for WebCodebase; Version to 1.4.12e;
+ Use correct case of sql table names in cgi interface: required by mysql on linux
+ Unsolved: n3 does not always decompress correctly in dview.pas see p20401977:i47, changed default to n4
+mvh 20070215: Fixed logging and added *** Association rejected message when association is rejected
+mvh 20070304: Added <defer> exportconverter: retry later as if connection unavailable
+mvh 20070305: Note: n3 problem fixed in dview.pas, version to 1.4.13alpha
+ Allow merging of up to 1000 UIDs: set SilentText to 64000 and *uids[1000] (thanks mp)
+ Allow named pipes for log_on and debuglog_on
+mvh 20070307: Work on extending extract: allow e.g. SQlite -> dbaseIII
+bcb 20070308: Made changes for big endian and Apple's DARWIN
+mvh 20070314: Fisished extract: allow e.g. SQlite -> dbaseIII in directory MAGO dbase
+mvh 20070315: Merged DARWIN stuff; Set TCPIPTimeOut for PDU that moves images
+mvh 20070316: Display defer import converter; Clumsily added <compression> import converter and
+ improved <storage> import converter; Made <storage> thread safe
+ Failed recompress() no longer reason to fail drag and drop; add convert_to_bmp
+ Use | instead of , to separate patientid from file in addimagefile:
+ Distributed , code to each of the server commands to make it more , safe
+ Note: it is NOT a good idea to use a , in a flexible filenamesyntax
+ Added level & window to convert_to_gif and convert_to_bmp; longer log lines for dump VR
+mvh 20070317: <prefetch> using new prefetch_queue, mayprocess and into_queue_unique, <preforward>, <preget>
+mvh 20070324: preget now <preretrieve> and avoids looping by checking orgmessageid!=0xfbad
+ I.e., data collected by <preretrieve> does not go through import/exportconverters
+ Added delayed exportconverters <forward patient>, <forward study>, <forward series> with optional compression
+ Removed "forward compressed to" (without as section) as is never used
+ Version to 1.4.13beta; delay to 10 minutes
+mvh 20070326: Fixed leak in <forward patient> etc. preretrieve also checking orgmoveae
+mvh 20070330: Change by Mark Pearson: read dicom.ini from same dir as exe in unix mode; merged more Darwin stuff
+ Also taken over bcb's fix for the finder: studymodality was asked at patient level
+ Also put in a more ENxxxx as command and messageid
+ljz 20070404: Added CommaInFilenameWorkAround()
+mvh 20070407: Use reentrant ctime_r when available; moved static SOPPatientRootQuery etc to stack to fix
+ reentrancy problem: concurrent outgoing c-move of CT and MRI on different associations would
+ share PDU causing sopclass not accepted on one. Also seems to reduce linux crash problems on
+ multiple inbound (4 or more) C-stores. Also moved CreateBasicFilmSessionRequest etc to fix
+ potential reentrance problem for printing.
+mvh 20070410: Merged CommaInFilenameWorkAround()
+mvh 20070413: "extract:" will just create dbase III clone of full patient DB; added "prefetch" server command
+mvh 20070415: Added Prefetcher option to dicom.ini: is set will aggresively preread queried patient or studies
+mvh 20070416: Prefetcher prints more information; use windows calls in windows for faster preread
+mvh 20070705: extract: uses DT_DBASEIIINOINDEX to disable indexing and packing when extracting from e.g. sqlite to dbaseiii
+ Note: extract: non dbaseIII goes to MAG0\dbase, dbaseIII goes to DataSource
+mvh 20070706: Added <between "9", "17"> (9:00 to 16:59) or <between "17", "9"> (17:00 to 08:59) import/exportconverter
+mvh 20070709: Fixed print of clone db done
+mvh 20070720: Fixed problem where waiting "forward ... to " task caused high CPU load
+mvh 20070901: Added dgate --checklargestmalloc:
+mvh 20071027: Added ForwardCollectDelay for delayed forwarding (default 600 sec)
+mvh 20071030: Fill in called and calling AE for SaveToDisk for e.g., dropped files etc
+ Fix %u and %c in Export and ImportConverters: called and calling AE
+ Log flow control Export and ImportConverters only in debug mode
+ Added retrying to delayed forwards or prefetches
+mvh 20071102: SetDicomErrorHandler: orderly shutdown of server on serious DICOM library errors
+ Fixed a bug in ForwardAssociationLevel: last UID was lost when reading INI file to szTemp
+ Added MaximumExportRetries and MaximumDelayedFetchForwardRetries (default=0 is no maximum)
+mvh 20071103: Version to 1.4.13; defer resets queue fails -> keeps on retrying
+mvh 20071104: Use local as AE for imagelister in web page instead of CONQUESTSRV1
+ Enable remote servers (use AE instead of 'local') in finder and lister commands
+ Fix crash when dgate -- option gets empty filename: now lists to stdout
+mvh 20071114: Put --checklargestmalloc: in dgate -?
+mvh 20071118: Adapted for 64 bits (use SQLLEN for BindField)
+mvh 20071120: Fixed KodakFixer for empty patient ID (crashed on 64 bits only)
+ Added [modality xx] and [date yyyymmdd-yyyymmdd] clauses to export [patient|study|series] to AE
+mvh 20071121: Added %V*GGGG,EEEE: search VR in any sequence; version to 1.4.13a
+ Added [now -ddd+ddd] and [age -ddd+ddd] clauses to export [patient|study|series] to AE
+ No retry on remote dicom error in forward xxx to: would retry zero records response
+ Use study date for data, age and now clauses
+mvh 20071123: Made forward command case insensitive; added forward image; added get [patient|study|series|image] from AE
+ The latter option makes preretrieve obsolete
+mvh 20071124: Added [sop xxx] clause to [forward|get]
+ Reorganized exportconverter code: all converters now do % substitution; reduced code duplication
+ Added reading of sequence items like in %V/300c,0060.0/0008,1155 or %V/300c,0060/0008,1155
+ Real life example (must all be one one line, max 512 characters):
+ ifnotequal "%m", "RTPLAN"; stop; nop "tests modality = RTPLAN";
+ ifnotequal "%V*300a,00b2[0,1]", "A2"; stop; nop "test machine name = A2"
+ forward to XVI_A2; nop "forwards the current recieved RTPLAN";
+ get study modality CT from NKIPACS; nop "collects associated CT";
+ get study modality RTSTRUCT sop %V/300c,0060.0/0008,1155 from NKIPACS; nop "collects associated RTSTRUCT";
+ forward study modality CT imagetype *AXIAL* to XVI_A2; nop "forwards associated CT";
+ forward study modality CT series %V(/300c,0060/0008,1155)/3006,0010/3006,0012/3006,0014/0020,000e
+ forward study modality RTSTRUCT sop %V/300c,0060.0/0008,1155 to XVI_A2; nop "forwards associated RTSTUCT";
+mvh 20071125: Fixed syntax for %V/gggg,eeee.i/ *gggg,eeee (search all groups under a specified one)
+mvh 20071126: Start on StorageCommitment
+mvh 20080103: Switched to ms7 compiler; fixed forward and get date, modality, sop filters: would not supress the UIDs
+mvh 20080107: Fixed malformed web viewer header: worked for IE but not for other browsers
+ Check presence of dicom.sql in web pages that need it
+ Deal with spaces in patient IDs in web pages
+mvh 20080126: Check presence of dgate.dic when starting server
+mvh 20080129: Fix KodakFixer: wrote one byte outside VR data (pr)
+mvh 20080129: Added [imagetype xxxx] clause to [forward|get] (pr)
+mvh 20080130: Small fix in above
+mvh 20080205: Added experimental PadAEWithZeros flag; version to 1.4.14alpha
+mvh 20080210: Added experimental IgnoreOutOfMemoryErrors;
+ Added "delete [patient|study|series|image] [date yyyymmdd-yyyymmdd] [now -ddd+ddd] [age -ddd+ddd]
+ [modality mm] [sop xxxx] [imagetype xxxx]" export converter
+mvh 20080221: Added [seriesdesc xxxxx] filter and "process [patient|study|series|image] [by command]"
+mvh 20080222: Small fix in imagetype filter code; process by clause not part of unique check
+mvh 20080302: Fixed case of DICOM table names
+mvh 20080316: Added dgate --deletestudies:date(range) and dgate --movepatient/study/studies/series
+mvh 20080318: Added [series xxxx] and [study xxxxx] filters; work on web page
+ --deleteseries/study and --moveseries/study allow patid:uid as parameter
+ Web interface can now push and delete on series and study level, but
+ delete is disabled in readonly web interface
+ Version to 1.4.14beta
+mvh 20080319: Delete in browsers fixed?; added %v(desc)desc: search VR in given sop of same patient
+ Example: %V(/300c,0060/0008,1155)/3006,0010/3006,0012/3006,0014/0020,000e
+ Gives referenced CT series UID in referenced structure set from forwarded RTPLAN
+mvh 20080321: Fixes in browser; added graphic web setting; may be gif or bmp for now;
+ Fix %V for non-existing items
+mvh 20080322: Added dgate --anonymize that uses general scripting
+mvh 20080323: Small fix in (local) for DcmMove: overwrote destination
+mvh+pr 20080404: Fixes in series and study filter (rethink naming)
+ pr added value* match for in match() routine
+mvh 20080618: Added extra logging in IARQ()
+mvh 20080620: Only show extra logging in IARQ when assoc rejected
+mvh 20080816: IARQ shows which sops are accepted; and differentiates no sop from connection terminated
+mvh 20080817: Small layout fixes; <process with> import converter; show PDU length in log
+ Check saving of file succeeded (thanks Jeff Bellamy and Alberto Smulders)
+mvh 20080819: Added experimental DT_MSTR: multi-value entry, e.g. query on 'PET' matches 'PET\CT'
+map 20080819: added --get_ini_param (same as get_param) and get_ini_num to list parameter by index
+map 20080819: Added get_ini to list all parameters in DICOM.INI
+mvh 20080819: Added code by map but kept original get_param for old web cgi client compatibility
+ Version to 1.4.14
+mvh 20080820: Solaris 10 fixes, and general UNIX fixes (map): configfiles may not be in current dir
+mvh 20080821: Default of ForwardAssociationRelease to 1; added sleep export converter
+mvh 20080823: Added study UID search to PatientStudyFinder; fixed DcmMove: would call local when remote adressed
+ Added rudimentary query/move web pages
+mvh 20080825: query/move looks better; added "thumbs" column to local series lister; config patched to readonly
+ added background color and display of icon (to be placed in WebCodeBase)
+mvh 20080826: One more fix in DcmMove, still called wrong server sometimes
+ Do not use 0xfbad as message ID for DcmMove from web page; webreadonly defaults to true
+ CGI viewer configurable: seriesviewer, seriesviewer2, noviewer, aiviewer
+mvh 20080827: Added slice number and repeat output data in ImagefileLister and SeriesUIDLister for more flexible formatting
+ Added flexviewer: reads code from dicom.ini in web server directory
+mvh 20080831: Translate yyyy and yyyymm to date range in finder; further only accept valid date and date ranges
+ Added dgate --get_amaps: lists all non wildcard entries from acrnema.map
+ Fixed handling of patient ID with spaces in ImageFileLister mode :
+ All undefined cgi modes can come from the cgi dicom.ini; added special and cgi script variables
+ Lines can start with -- to start dgate, with # as comment, any other passed as HTML
+ Added source parameter: flex pages can be read from script file
+ Added serversideviewer: requires javascript only, nothing to install
+mvh 20080901: Fixed some leaks in printing and --commands; fixed --get_ini: formatting
+mvh 20080902: Added header option for web scripts; added some CGI environment variables
+bcb 20080905: Made new changes for big endian and undid some old ones.
+mvh 20080908: Index in filelister format is now a string (%s), and added next string that gives index+1 (is1)
+ Fixed manual of --modifypatid: and --anonymize:; dicom mime to application/dicom
+ Added modes imagelisthttp, imagelisturls and imagelistfiles; added ? format for imagelister: gives #files
+mvh 20080909: Added studyuid option to moveseries; pass it studyuid in seriesmover call from seriesfinder
+ Added --modifyimage:file,script (uses import converter scripting language, where you can use ' instead of ")
+mvh 20080910: In modifyimage only replace ' with " conditionally; version to 1.4.14a;
+mvh 20080910: Forbid patid, studuid and seruid change in modifyimage; medged bcb Mac stuff
+mvh 20080913: Modified and use SetStringVR to correctly send UIDs with padded 0
+mvh 20081016: Show bitness on startup
+mvh 20081104: Attach dictionary to DcmMove PDU
+mvh 20081105: Fixed display of bitness in web page
+mvh 20081116: Adapted for very large objects (use unsigned int for length); remove extra 0 byte in HTML generator; fixed CheckLargestMalloc
+mvh 20081121: Added create database for PostGres
+mvh 20081123: Skip export converters for dropped, modpatid, modimage, merging
+mvh 20081124: show database type on startup; Temp version to 1.4.14a1; fix many scripting crashes
+mvh 20081129: start on better patient ID change: process all UIDs; fix drag/drop error introduced in 1.4.14a1
+mvh 20081129: Removed double access of SOPInstanceUID in SaveToDisk; fix: do not free ddo after SaveToDisk;
+ added <newuids> and <newuids except > import converters; added --genuid, --changeuid and --checksum commands
+ Version back to 1.4.14a; modifyimage can change patient ID and study/seriesUID if newuids used as well
+ set can now also work in exactly one deep sequence: set gggg,eeee/gggg,eeee to "string"
+mvh 20081130: Added --attachrtplantortstruct:planfile,structfile command using script; also --attachanytopatient/study/series
+ stop now stops one importconverter- not the chain; added <call file> and <return> statements to return from file
+ Added optional anonymize_script.cq: overrules fixed anonymizer;
+ added %A = %V but then gives CRC32 of data and %E = %V but gives new UID for given UID
+mvh 20081201: added --convert_to_jpg and web page use (experimental)
+mvh 20081203: If jpg graphic: list options as jpg, yes, no; fix slice number display is serversideviewer
+ Added frame control to convert_to_jpg etc as l/w/frame; add optional frame control to
+ convert_to_dicom; added frame control in serversideviewer
+mvh 20090203: Removed DNS reversing (you can use wildcard AE instead); work on zip loading
+mvh 20090204: Finished zip loading (to be tested on linux), uses now waiting BackgroundExec
+mvh 20090206: Added QueryConverter0, WorkListQueryConverter0, RetrieveConverter0: can read called (%c),
+ calling (%u), and c-move destination for retrieve (in %s), as well as all data in data object
+mvh 20090209: Made compiling under linux
+mvh 20090211: Export MyDcmError; only DCM_ERROR_MEMORY is fatal
+mvh 20090212: Recoded virtual server (kept old code), to provide better grouping of move requests
+mvh 20090215: Added VirtualServerPerSeries..9 flags: determines if virtual gets are per image (default) or per entire series
+mvh 20090216: Added %Rgggg,eeee: gives restored UID for newly generated one
+ Prepare for RetrieveResultConverter0
+mvh 20090411: Added simple wildcard matching in match(), accept *text*
+mvh 20090411: Version to 1.4.15alpha
+mvh 20090513: Added CompressionConverter0 .. 9: called from recompress to 's0' to 's9'
+ Added <fixkodak> and <unfixkodak> import converters; added <after NN> clause to <forward study> etc
+ Blocked out StorageCommitment
+mvh 20090514: %QXgggg,eeee reads aliasfileqX.txt with lines like old<tab>new<return> to map VR to new value
+mvh 20090616: Add ^/~ after % command to convert to upper/lowercase, %^ %~ %[; fixed leak when save to sql fails
+20090616 jf Include file stuff; fixes to Unix 7z stuff
+20090618 mvh VirtualServerPerSeries is now a limit: if set to N, more than N images go per series
+20090620 mvh Version to 1.4.15beta
+20090802 mvh Support DCM_ERROR_DEBUG (debug messages from library) that print only if debuglevel>0
+20090821 mvh Removed need to specify "delete series modality *" instead of "delete series"
+ Fixed "process by " command; now uses all command string upto ;
+20090824 mvh Version to 1.4.15beta1
+20090921 mvh Added extract_frames: command
+20090922 mvh Tried to fix <compression> import converter; added <reject> import converter
+20090924 mvh Restructured manual; fix crash of studyfinder without search string
+ Note: on vista, commands like dgate --imagelister wont give large lists (does when piping)
+20090926 mvh %t = tab in scripts; fixed failed storage error message; added RetryForwardFailed flag (default 0)
+20090929 mvh Added ImportExportDragAndDrop
+20090929 mvh Version to 1.4.15
+20090930 mvh Version to 1.4.15a
+20091005 mvh Version to 1.4.15b
+20091012 mvh Optimized preprocessing of read-ahead thread by saving tt
+20091108 mvh Started on <merge study> import converter
+20091120 mvh Started on <forward> import(!) converter
+20091229 mvh Version to 1.4.15c
+20091230 mvh Merged bcb changes: DGATE_VERSION, PATH_MAX, const char, bigendian fixes
+20091231 bcb Defined PATH_MAX for Apple's Snow Leopard,endian fixes, &
+ fixed gcc4.2 warnings (char to const char, VERSION, DEBUG and char* to program memory)
+ Added jpeg2k stuff (HAVE_LIBJASPER)
+20100111 mvh Merged; but keep cgi formats local (less changes)
+20100113 mvh Fixed one signed/unsigned mix in dump routines
+20100119 mvh cast %d print to (int), %ud to (unsigned int); one more const issue
+20100120 mvh Fixed two const issues detected with ms8
+20100122 mvh fixed: %ud should be %u
+20100122 mvh DcmMove uses study-root query when UID passed to fix move to osirix from web interface
+20100123 mvh Fixed rare crash in function VirtualServer2; started on DT_FL and DT_FD; version to 1.4.16alpha
+20100123 mvh Added counters for jpeg2000; put info about jpeg libraries into serverstatus display
+20100124 mvh Blocked old VirtualServer(); rephrased cancel message; changeuidback and count_frames commands
+ Optimized DcmError call to gpps
+20100124 mvh Use much faster MyGetPrivateProfileString: profiled as followed:
+ Installed C:\Program Files\Microsoft SDKs\Windows\v6.1\Bin\xperf_x64.msi
+ set _NT_SYMBOL_PATH=e:\quirt\comps\exe\dgate;srv*c:\symbols*http://msdl.microsoft.com/download/symbols
+ set _NT_SYMCACHE_PATH=C:\symbols
+ xperf -on latency -stackwalk profile; run dgate; xperf -d out4.etl
+ xperfview out4.etl; select time range; select trace-load symbols;
+ right click selection; summary table (takes very long the first time - downloads all symbols!)
+20100207 mvh Added uncompress command; version to 1.4.16alpha2
+20100209 mvh Fixed another rare crash in function VirtualServer2 (thanks PR)
+20100227 mvh Fixed Scotts modifyimage problem: http://forum.image-systems.biz/viewtopic.php?f=33&t=2143
+20100227 mvh Added -q option to set target address of dgate -- command; version to 1.4.16alpha3
+ pass DCO also for non-nki clients: used in %s for RetrieveResultConverter
+ Added more extensive printer activity logging
+20100228 bcb Changed HAVE_LIBJASPER to HAVE_J2K so Jasper or OpenJPEG can be used
+20100309 bcb Added double parentheses (gcc4.2 Warnings)
+20100309 bcb Changed int to unsigned int, commented out unused variables and routine (gcc4.2 Warnings)
+20100619 bcb Added #ifndefs and fixed shadowed variables(gcc4.0 Warnings)
+20100723 mvh Merged: Reread all changed; agreed with all but two in checklargestmalloc and cgi; 1.4.16alpha4
+20100728 bcb Added delete vr's after ->ReplaceVR's
+20100802 jd Added scheduletransfer
+20100815 mvh Merged; version to 1.4.16alpha5
+20100815 mvh Fixed bug 32 in t=2127: seriesdesc filter
+20100816 mvh Added QueryResultConverter and ModalityWorkListQueryResultConverter
+20100816 mvh Fixed bug in VirtualQuery introduced by only partly renaming shadowed variable
+20100816 bcb Allow dicom.ini and other files to be moved; fixed / as cmd line option
+20100816 mvh removed (a) from #ifndef EnterCriticalSection(a) etc
+20100819 mvh Added system export converter; added "get study" etc import converter.
+ Allow "set" in sequence items; Allow "set" to add sequence items.
+20100823 mvh Extended virtualservermask; pass server directly to VirtualServer to override server list
+20100823 mvh Merged and simplified bcbs basedir code; use exe dir as default basedir
+ Fixed overlap in ImportConverter number; Made %xyz variables local; Version to 1.4.16beta
+20100824 mvh Use dFileSize to test if file is written correctly: catched 0 byte files with full disk
+20100827 mvh Fixed two typos in warning fix extract: command
+20100901 mvh Fixed empty virtual query sent if no images there
+20100905 mvh Removed file functions: now use RecompressFile; document -j* and -j-
+ WIP: added testmode: function to allow internal file comparison
+20100914 bcb Fixed leak in PrinterSupport
+20101017 mvh Added MergeSeriesConverter and MergeStudyConverter
+20100918 mvh Merged; version to 1.4.16beta2; testmode does not affect LoadForGUI direct filenames
+ Fixed that changing patid etc in importconverter breaks exportconverter data
+20100919 mvh Added <format> clause to <set> importconverter command
+20100920 mvh Fixed [,fromend] operator
+20100924 mvh Started on error handling in virtualserver
+20100925 mvh Fixed problem in <forward> IMPORT converter; only worked as first command in line
+ SearchDicomObject now checks on buffer overflow; ; # lines are comment in script file
+ note: <system> converter should run hidden; <call> now passed called and calling
+20100925 mvh Version to 1.4.16beta3
+20100926 mvh Added <mkdir> and <rm> IE converters
+20100927 mvh Added <save frame> and <save bmp/gif/jpg> IE converters, <save to> E converter
+20100928 mvh Fixed in delayed <merge>, <delete>; fixed MergeSeriesConverter and MergeStudyConverter crash
+ Fixed 1.4.16beta2 introduced bug: patientid was passed incorrectly into importconverter
+20101003 mvh Added seriesdesc filter and script to DcmMerge, script to DcmMove
+20101003 mvh --browsepatient command; fixed that split/merge series generated new study
+20101003 mvh Version to 1.4.16beta4; merged jd scheduletransfer
+20101003 mvh ImageFileLister now internally also takes study and sop
+20101003 mvh Added dgate --submit:patid,studyuid,seriesuid,sopuid,username at machine:folder,password
+ Requires 7za.exe and pscp.exe
+20101003 mvh Modified dgate --scheduletransfer:patid,studyuid,seriesuid,sopuid,username at machine:folder,password
+ Added IE <submit> command with target and password clause
+ Added next slice and frame buttons in serversideviewer
+20101005 mvh Fixed ? imagefilelister (count), added $ imagefilelister (#frames), started on passing frames
+ to serversideviewer
+20101005 mvh Started on WADO
+20101006 mvh Enabled WADO; do not try to remove images from failed virtualserver request (double messages)
+20101008 mvh Started on rudimentary WADO client (PatientStudyFinder now also lists images)
+20101009 mvh Enabled rudimentary VirtualServer for WADO client: loadforgui will try virtualservers
+20101009 mvh Tried to speedup query result processsing; implemented POST method (no multipart yet)
+20101009 mvh WADO server and client function; upload button, not functional yet as requires multipart parser
+20101010 mvh Set default WADO correct for conquest; finished (single file) upload fuctionality;
+20101010 mvh Scan incoming folder once per second (thread starts when incoming folder exists on startup);
+ Some fixes in serversideviewer; started on VirtualQueryCached
+20101013 ljz Fix : CreateDatabase "root", used UserName as Password for postgres
+20101014 mvh Fix in virtualserver for LoadForGUI
+20101016 mvh Improved virtualserver for LoadForGUI; Cached queries start to work; virtual queries now return computed fields
+ use e.g., VirtualServerFor0 = AE,CACHESERIES or AE,CACHESTUDIES
+20101017 mvh Added OverlapVirtualGet parameter: controls interleaving of recieve and send of virtualserver (suggest: 16)
+20101018 mvh Limited memory use of OverlapVirtualGet, tried out of order processing but this failed; dated folders for querycache
+ Submit and scheduletransfer call submit.cq if exists to anonymize
+20101020 mvh Small fix in querycache: query file sometimes not stored; and study cache did not read date
+20101108 mvh Added --loadanddeletedir command
+20101116 bcb Warnings
+20101120 mvh Fix reading of FIXKODAK in virtualserver if e.g., CACHESERIES appended;
+ merged bcb warnings (and fixed introduced errors); version to 1.4.16releasecandidate
+ Added warning if cached virtualserver does not provide computed fields
+ Added NONVIRTUAL flag to allow block recursive virtualserver connections
+ Do not forward transfer syntax to virtual queries data object
+20101121 mvh Fixed NONVIRTUAL flag for non-cached queries if caching is ON
+ Added dgate --export: command to zip/7z/tar selected data
+ Added dgate --safequit: command and OpenThreadCount; prepare for ArchiveConverter0 (1900)
+ Show in log when a file is rewritten; Added [wadoservers] section in cgi config
+ Document ul, ub, and ue in acrnema.map
+20101122 mvh Pass script to export: command; added ZIP thread that runs when the system is a service
+ Fix for spaces in zipfilename for export; background exe for 7za
+20101124 mvh Fix compile and 2 warnings for linux;
+ drop zip file extracts with paths to avoid overlapping filenames
+20101209 mvh Fixed FIXKODAK parameter detection of virtualservers
+20101212 mvh Warn if FIXKODAK paramater set in virtualquery does not match FixKodak global
+ Fix rewrite message for virtual server data
+20101212 mvh Correct file formats listed and accepted for 7za decompression
+20101212 mvh Version to 1.4.16
+20101213 mvh Implemented NightlyCleanThreshhold here for Linux and Windows (if logging to file)
+20101220 mvh newuids will change empty uids into a new one
+20101222 mvh Fix for empty cached query that crashed
+20101227 mvh Fixed some delete NULL crashes on failures
+20101227 mvh Added org clause to forward <compressed as xx> to AE org AE
+20101227 mvh ImportConverters now also use ForwardAssociationLevel
+20101228 mvh Added \n after cloning db message
+20110105 mvh Use MakeSafeStringValues for exact match; Added MoveDeviceScript0
+20110105 mvh Added --echo and --selectseriestomove commands
+20110105 mvh Version to 1.4.16rc1
+20110106 mvh Added --moveseriestodevice; changed --selectseriestomove syntax
+20110106 mvh Todo: NightlyMoveSource, NightlyMoveDest, NightlyMoveAmount, NightlyMoveAge, NightlyTestAge
+20110106 mvh Version to 1.4.16rc2
+20110110 mvh Note: mergestudiesconverter called for series and other way around
+20110111 mvh Check for empty patient ID in virtual query and for other empty VRs
+20110111 mvh merge study converter merges series: now calls MergeSeriesConverter.
+ Merging studies now calls MergeStudiesConverter
+20110111 mvh changed logic of converters passing study or series uid to be consistent
+20110111 mvh reject or destroy in merge script stops object from being merged
+20110113 mvh fix script clause in merge study, call also tries line in [scripts] in dicom.ini
+20110113 mvh Allow script clause without "" as well; unrecognized line attempts call
+20110114 mvh "" in script string; script command evaluates string as script
+20110115 mvh delete changed UIDs after merge study (remerge will create new series)
+20110115 mvh fixed "script" converter and substitution of ""; experimental "lua" command
+20110116 mvh fixed error message for incorrect script commands; first lua functions built-in
+20110116 mvh SearchDicomObject now supports %VName; allow setting/reading more than 10 sequence items
+20110116 mvh The set command now accepts names, e.g., set PatientID to "9999"; nop %VPatientID
+20110116 mvh Lua now allows, e.g., Data.PatientID = 'aap'; print(Data.PatientID)
+20110117 mvh Started on lua Global, Association, Command
+20110118 mvh Primary PDU is Extended to allow embedding lua state in it
+20110119 mvh Added a global PDU as script context; associations add new contexts
+20110120 mvh Fix in Association.Calling/Called; for now each thread has an isolated lua state
+ Fix in speed of query results (were all processed by ImportConverter). Added lua
+ startup/command/QueryConverter0 etc; count all threads including gui threads
+20110121 mvh Added prefetcherPDU for delayed forwards and such
+20110122 mvh Fixed lua print, added lua error handling; added %f %b %p to ImportConverter
+20110122 mvh Fixed SearchDicomObject for US,SS,UL,SL tags (note: 'set to' not fixed yet)
+20110124 mvh bug fixes in new code; implemented reject in lua
+20110125 mvh Put UID changes into debuglog
+20110127 mvh Added lua getpixel and setpixel (takes 3-5 microseconds)
+20110129 mvh Added lua getrow, setrow, getcolumn, setcolumn, readdicom, writedicom; sd.ddo leaks
+20110201 mvh Lua: R/W sequence e.g., print('0 implied', Data.InstitutionCodeSequence.InstitutionName)
+ or Data.InstitutionCodeSequence[2].InstitutionName = 'write for now max one level deep'
+20110203 mvh Lua: Unified reading and writing of Data/Command/Sequences;
+ Allow write at any depth in existing sequences
+20110204 mvh Allow creating sequence in script and in Lua: Data.xxxx = {}
+20110205 mvh Added newdicomobject and deletedicomobject
+20110206 mvh Fix for set .. to ""; added set .. to nil for simple VR;
+ create sequence will not overwrite existing sequence;
+ lua web page creation: CGI(), HTML(), <?lua ?> <%= %> source=xx.lua
+20110207 mvh Added lua: get_amap(N) -- N starts at 1, dbquery(db, flds, query, sort) { returns table of tables starting at 1)
+20110208 mvh lua gc for dicomobject; lua dicomarray and dicomquery; allow virtualquery without setting level in DDO
+20110208 mvh 1.4.16rc4
+20110214 mvh Fixed lua Data access; fixed "" in exportconverter; 1.4.16rc4a
+20110216 mvh Fixed calling and called in ExportConverter; fixed %f etc in ImportConverter
+ mkdir IE converter also creates subdirs; 1.4.16rc4b
+20110228 mvh Added Write, Read and Dump methods to lua dicomobject as closure with passed method name
+20110320 mvh Fixed Association.Calling in lua; Added RejectedImageConverter0; added t_1500 checks to all queries
+20110320 mvh 1.4.16rc5
+20110326 mvh 1.4.16rc6
+20110328 mvh Fix crash when setting lua Filename for import file
+20110331 mvh Added NoDICOMCheck option: if set, do not stop parsing DICOM stream on error
+ FlushPrivateProfileStringCache after writing to dicom.ini
+20110331 mvh 1.4.16
+20110404 mvh Fix in CGI behavior for IIS (check REQUEST_METHOD); version to 1.4.16a (unreleased)
+20110413 mvh NoDICOMCheck also forces use of sequence enabled reader (allows JPEG compressed V2 file)
+20110419 mvh Added lua getvr(Object, g, e), Object:GetVR(g, e), setvr(Object, g, e, data), Object:SetVR(g, e, data)
+ full lua webpage now basically works and gives error messages to web page
+20110419 mvh version 1.4.16a
+20110501 mvh added heapinfo() in lua; version 1.4.16b
+20110502 mvh Made DcmMove almost always work on study level
+ added lua dicommove(source, dest, obj, patroot) and sql(statement)
+20110603 mvh loadkfactor now required for dgate -a commands; added -h option (wait for getkey)
+20110604 mvh lua endassociation and clienterror events; added retry command for rejectedImageConverter0
+20110604 mvh implemented/fixed size (may be %)/dsize for sliceviewer/serversideviewer/seriesviewer; version 1.4.16c
+ also allow size='': use original size or 80% for those requiring a fixed size
+20110605 mvh Added zip download of series/study through push page
+20110606 mvh Added --modifystudy and --modifyseries commands, e.g., dgate "--modifystudy:20000321,,compression j2"
+20110628 lsp Set PDU.Link.Connected to FALSE on !PDU.Read(&DCO)) in
+ StorageApp::ServerChild() to avoid subsequent use of a closed socket in
+ AReleaseRQ::Write() and AReleaseRP::Read() in PDU_Service::Close()
+ (called in destructor of PDU_Service)
+20110710 mvh Added RejectedImageWorkListConverter0; fixed retry for RejectedImageWorkList and RejectedImage
+20110710 mvh Fixed WADO application/dicom mime header
+20110710 mvh zip from web page calls zip.cq script on each file; also forces DCM extension
+20110710 mvh Fix compile of getch and heapinfo linux
+20110710 mvh Version to 1.4.16d
+20110904 mvh Clear address (0010,1040) in default anonymizer; Fixed lua deletedicmobject, leak in readdicomobject
+ Create empty sequence is really empty, # operator for DICOM sequence in lua
+ Version to 1.4.16e
+20110904 mvh Fix read of %i, %s, %m in lua not from ImportConverter;
+ protect getpixel etc against missing pixel data
+ Fix crash of %QX if file does not exist
+20110905 mvh Fixed leak in %QP etc; fixed leaks in ADDO cleaning in web interface
+20110906 mvh Added optional script instead of submit.cq to dgate --scheduletransfer: and dgate --submit:
+20110907 mvh Added script clause to forward; e.g., forward to PACS001fir org SELF script fixkodak
+20110927 mvh Added "crop x1,x2,y1,y2" and "tomono" importconverters
+20110928 mvh Added the DEST clause to e.g., "forward to AE org CALLING dest CALLED script nop"
+20110930 mvh Fixed crash forwarding from lua
+ Version to 1.4.16f
+20111009 mvh Fixed sequence writing problem; make it one long when first writing
+ Fixed AliasFile reading issue: i index into command updated incorrectly
+ Fixed lua dbquery issue due to typo
+ Added channel clause to forward import converter; use PDU[19,channel] from lua
+ fix forward org dest clauses; fixed forward to HOST:PORT
+20111010 mvh Protect channel clause againt incorrect values
+ Version to 1.4.16g
+20111015 mvh Fixed wado dcm compression (incorrect extension)
+20111018 mvh Added TempDir ini file option
+20111114 mvh Version to 1.4.16h
+20111120 mvh Default size in convert_to_gif etc is now 0: as is
+20120112 mvh+jd Fix in passing script to submit command
+20120211 mvh Allow passing optional DDO as first arg to set/getpixel set/getrow
+ Object:SetPixel, Object:GetPixel, Object:SetRow, Object:GetRow
+20120212 mvh Fixed uncompress WADO; fix POST code for SOAP serving; export globals to lua in CGI mode
+20120212 mvh Fixed POST for IIS (read len, not len+1)
+20120213 mvh Small fix in x:GetRow etc; Setting Dictionary and ACRNemaMap for CGI enables moves and queries
+20120213 mvh Moved some set and virtualquery logging to SystemDebug
+20120214 mvh Allow any file to be POSTed, saves as xxx.dat; Added DefaultPage and AnyPage items
+20120215 mvh Reversed CGI key test to allow query string where e.g., mode= appears twice, hit on first
+20120215 mvh Added optional markseries and markstudy pages if passing value 'key' down into them
+20120217 mvh Added shoppingcart option; enabled if configured and passing value 'key'
+20120218 mvh Added DefaultPage to make own top and AnyPage to totally disable built-in CGI server
+20120219 mvh Disabled WEB push to self, and zip from remote server (which was invalid anyway)
+20120220 mvh Added WebPush configuration to allow disabling push options; show more config items
+20120220 mvh Version to 1.4.16i
+20120221 mvh lua can run script on any dicom object; empty tag does not return NIL to lua; lua dictionary(); fix uploadedfile
+20120222 mvh Fix webpush and crash on IIS for empty QUERY_STRING
+20120229 mvh Extended number of possible columns in PatientStudyFinder
+20120302 mvh Added gpps lua function; DefaultPage may be e.g., *.lua; any mode is that mapped to mode.lua
+20120304 mvh Implemented region and anonymize options to wado
+20120304 mvh Made DefaultPage and AnyPage sections; Fixed WADO text output; Version to 1.4.16j
+20120305 mvh Added statusstring for simple web feedback of dicommove and submit (not multiuser safethough)
+20120306 mvh Added lua callback to dcmmove2; added statusstring: server command
+20120306 mvh A failed virtualserver request will now not wait until a timeout and log error messages
+20120307 mvh Added bridge=AE option to make local WADO server a proper bridge (see MyBridgeStorage and LoadForBridge and 0x2bad)
+20120317 mvh Documented imagefinder; added process study|series with xxxx.lua (just command_line is passed)
+20120318 mvh Allow "file.lua" directly as importconverter instead of lua "dofile('file.lua')"
+20120319 mvh Implemented lua: filenamesyntax; e.g. lua:dofile('generatefilename.lua') or lua:Data.SOPInstanceUID..'.dcm'
+20120320 mvh Added [wadoservers] bridge = AE to force wadoserver by default to bridge for one given AE
+20120325 mvh "lua" and [lua] ExportConverter, "copy" ImportConverter and "defer" ImportConverter (for lua ExportConverter)
+20120327 mvh Document status_string: command
+20120402 mvh Improved OverlapVirtualGet: allow to reverse operation - give slices out mainly in incoming order
+ Avoid deadlock by conflicting requirements; SystemDebug some status messages in OverlapVirtualGet and ReadAheadThread
+20120402 mvh Released 1.4.16j
+20120525 mvh When retrieve from virtualserver is ready cancel outstanding c-move requests
+ Increased virtualserver timeout to 200 sec
+20120601 mvh Implemented WORKLIST query from lua
+20120621 ljz Fix readahead crash when client hangs up in the middle of the transfer
+20120624 mvh Limit virtualserver to 64 per move; virtualserverperseries obsolete; fixes crash when series larger than move
+20120624 mvh move mkdir etc defines in dgate.cpp up to line 2220
+20120624 mvh Keep move object intact in lua dicommove and dicomquery; report fail for lua sql and readdicom functions
+20120624 mvh Prerelease 1.4.16k
+20120630 mvh Allow compression to be e.g. JL etc or JLNN, J3NN, J4NN, J5NN, J6NN: NN is quality factor
+20120630 mvh Reverse .dcm check: all is assumed .DCM except .V2
+20120701 mvh Added dicomdelete; note: tried to make heapinfo() thread safe but failed;
+ added [lua]nightly script that runs at 03:00; and [lua]background that runs every second
+20120701 mvh release 1.4.16k
+20120702 mvh Protect lua_setvar against NULL string
+20120721 mvh Fixed CGI code that got extension wrong on unix with . in folder name
+20120722 mvh Added LUA_5_2 compatibility by bcb; removed unneeded buf[1024]
+20120723 mvh Fixed *count-- --> (*count)--
+20120829 mvh "mkdir " script command no longer requires a trailing / or \
+20120829 mvh Force even text/plain output; first pad ' '; then strip when odd
+20120829 mvh Version to 1.4.17
+20120905 mvh Fixed bug found by Bruce Barton in [lua] ExportConverter
+20120908 mvh Added fix for virtualserver on imagetype and NOIMAGETYPEFIX flag
+ VirtualServerForN may be e.g., "server,NOIMAGETYPEFIX,FIKKODAK"
+20120914 mvh Changed default of above fix to off: flag is now IMAGETYPEFIX
+20120914 mvh Attempt to use VirtualQueryCached to build list of images to be retrieved in VirtualQuery
+ Filter response in virtualquery(for virtualserver) for
+ incorrect response of carestream to IMAGETYPE query
+20120916 mvh Cleaned up code; split in VirtualQuery and VirtualQueryToDB (that uses VirtualQueryCached)
+ Renamed option IMAGETYPEFIX to send only 3rd element of ImageType to IMAGETYPEFIX3
+ IMAGETYPEFIX just tests each received record for a match against queried ImageType
+20120917 mvh Move dumps response in case of error; finished IMAGETYPEFIX
+20120922 mvh IMAGETYPEFIX also works on EchoNumbers
+20121015 mvh Fixed check on V2 filename extension to enable NKI compression again
+20121016 mvh 1.4.17alpha release
+20121201 mvh Added and disabled code to link optional socket.core library
+20121208 mvh Added __tostring method to lua representation of dicom objects;
+ fix luaGlobalNewIndex: writes dicom.ini as well as direct variables
+ Blocked delayed export converters of non-existent objects
+ Added WatchFolder parameter (second monitored incoming folder)
+20121214 mvh Enabled socket.core; use .zip for submit version to 1.4.17beta
+ Fixed 'forward compressed as ' in import and export converter (viewtopic.php?f=33&t=15588)
+ Added lua Association.ConnectedIP member (WIP)
+20121216 mvh Added DicomObject as class factory with new and newarray, added :free(), fixed ConnectedIP
+20130125 mvh Added changeuid and changeuidback to lua interface;
+ Anonymizer accepts anonymize_script.lua as well as anonymize_script.cq
+ Added ImportConverters "olduids" and "olduids except"
+20130127 mvh Added dgate --luastart: (returns immediate)
+20130128 mvh Added crc to lua interface
+20130202 mvh Added getimage, setimage, :GetImage, :SetImage to string
+ GetVr has extra parameter (binary), SetVR accepts (binary) string
+ Added "pack" library hardcoded; lua genuid; protect lua :Read filename
+20130210 mvh Fixed e.g. process study after 5 with test.lua %i:%o
+ Note: there must be arguments passed to command_line
+20130215 mvh Fixed source = xxx.lua cgi starter
+20130218 mvh re-allow readdicom on empty Data object;
+ header now works for lua cgi script (default disabled)
+20130218 mvh Report move failure in dgate -- commands
+20130218 mvh Added studyviewer (default disabled); added dgate --dolua:
+ Documented lua command line options; socket.core only for win32 now
+20130219 mvh 1.4.17beta released as update
+20130320 mvh Added lua system() call; fix BackGroundExec with spaces in path
+20130321 mvh Add BaseDir\clibs to path; added missing logs for converters such as rm
+20130417 mvh fix lua dicommove parameter 5; fixed 'webscriptad(d)ress'
+20130417 mvh Unescape % in luaSeqnewindex generated "set ..@ script
+20130502 mvh Added \nAccess-Control-Allow-Origin: * or \nAccess-Control-Allow-Origin:*
+ to all WADO generated messages, the space is omitted to force header EVEN
+20130502 mvh 1.4.17beta2 update
+20130522 mvh Added options to pass command line to submit data (dgate --submit2:, IE submit2 ..)
+20130522 mvh Fixed incorrect case of dicomworklist name found by marek
+20130523 mvh Reset dummyddo to avoid incorrect freeing of what it points to
+20130523 mvh Fixed bug introduced 20130417 with unescaping Data.xxx = nil or {} no longer worked
+20130523 mvh In ModifyPATIDofImageFile change PatientID after running script (assumed changes uids)
+20130523 mvh 1.4.17 release
+20130606 mvh Fixed crash in headerdump of RTSTRUCT (buffer overrun)
+20130709 mvh Added float to short conversion in luasetimage
+20130709 mvh Added support for setting simple US and UL items with e.g. set Rows to 256
+20130711 mvh Fixed luasetimage, fixed some lua return values, version to 1.4.17a
+20130716 mvh Added dgate --moveaccession: using 7777 magic number
+20130804 mvh dgate --lua: and --luastart: now run in local environment
+20130806 mvh dcmmove callback and process with lua now thread safe
+20130806 mvh fixed setimage(frame, string), version to 1.4.17b
+20130808 mvh Enabled logging of process series by command
+20130808 mvh Fixed importconverter command that used patid in memory; failed after anonymization
+20130808 mvh Added import_critical and export_critical to make "forward to xxx" thread safe
+20130810 mvh Removed export_critical (is serialized), added channel * to importconverter forward to
+20130810 mvh Added closing of importconverter forward to PDU after ForwardAssociationCloseDelay
+20130811 mvh Fixed that missing images were removed from db even of no virtualserver is defined
+20130812 mvh Fixed deadlock of closing of importconverter
+20130812 mvh added lua sleep() in ms; removed unused TransmitCompression
+20130813 mvh Removed unnecesary double N checks in forward import converter;
+ added lua addimage() and :AddImage()
+ added VirtualServerQueryConverter and VirtualServerQueryResultConverter
+ Pass file.lua(command) and patient ID of anonymizer to command_line
+20130820 mvh Fixed forward compressed as XX to IP:PORT
+20130826 mvh Test presence of lua file with same name as exe, if exists run that passing arg[]
+ Pass arg[] for dgate --dolua:; allow dgate --dolua:filename, searched in . and lua/.
+20130829 mvh Version to 1.4.17c
+20130903 mvh Greatly improved read speed for very large c-moves by reordering if statement in search loop
+20130912 mvh Documented where the merge of virtual query computed fields should be added
+ The field should also not be stripped and there are other issues as well
+20131013 mvh Set rc to 1 for [lua] converters; should fix QueryResultConverter0; added quality to ToJPG
+20131030 mvh Fix in virtual server if c-move callback occurs less than once per image;
+ test did not generate proper filenames and error message was given improperly
+20131103 mvh Fix in VirtualServerPerSeries when exact #images, would omit SOP tag but set level to IMAGE
+20131104 mvh Reversed logic: 1 image gives IMAGE move and SOP uid
+20131107 mvh Added quality clause to save jpg; Release 1.4.17c
+
+ENDOFUPDATEHISTORY
+*/
+
+#define DGATE_VERSION "1.4.17c"
+
+//#define DO_LEAK_DETECTION 1
+//#define DO_VIOLATION_DETECTION 1
+//#define FAILSAFE_STORAGE
+
+// max ExportConverters lines AND max forwards per line
+#define MAXExportConverters 20
+#define DEFAULT_LOSSY "95"
+
+#ifndef UNUSED_ARGUMENT
+#define UNUSED_ARGUMENT(x) (void)x
+#endif
+
+#ifndef max
+inline int max(int a, int b) { return a > b ? a : b; }
+#endif
+
+#include <stdarg.h>
+
+# include "dgate.hpp"
+# include "nkiqrsop.hpp"
+# include <time.h>
+#ifdef WIN32
+# include <io.h>
+# include <process.h>
+# include <conio.h>
+#else
+# include <unistd.h>
+# include <pthread.h>
+# include <dirent.h>
+#ifndef DARWIN
+# include <malloc.h>
+#endif //DARWIN
+#endif
+# include <stdio.h>
+# include <ctype.h>
+# include <fcntl.h>
+# include <sys/stat.h>
+
+#ifdef WIN32
+#if !defined(__BORLANDC__) && !defined(__WATCOMC__)
+# include <odbcinst.h>
+#endif
+
+#if defined(DO_LEAK_DETECTION) || defined(DO_VIOLATION_DETECTION)
+# include <crtdbg.h>
+#endif
+
+#endif
+
+#ifndef ODBC_ADD_SYS_DSN
+#define ODBC_ADD_SYS_DSN 4 // add a system DSN
+#endif
+
+BOOL NoThread=FALSE; // debug non-threaded
+
+#ifndef UNIX // Win32...
+# include <process.h>
+# define THREAD_RETURN_FALSE FALSE
+# define THREAD_RETURN_TRUE TRUE
+ typedef BOOL ThreadRoutineType;
+ typedef int ThreadRoutineArgType;
+#else // UNIX...
+# include <pthread.h>
+# include <unistd.h>
+# include <stdlib.h>
+# include <string.h>
+# include <signal.h>
+# include <sys/types.h>
+# include <sys/stat.h>
+//# include <fstream.h>
+# include "npipe.hpp"
+#ifndef PATH_MAX
+# define PATH_MAX FILENAME_MAX
+#endif
+# define THREAD_RETURN_FALSE ((void *)NULL)
+# define THREAD_RETURN_TRUE ((void *)1)
+//# define closesocket(s) close(s)
+# define CloseHandle(h)
+void Sleep(int h)
+{ struct timespec t;
+ if (NoThread) return;
+ t.tv_sec =(h/1000);
+ t.tv_nsec=(h%1000)*1000000;
+ nanosleep(&t, NULL);
+}
+# define eof(h) FALSE
+ typedef void * ThreadRoutineType;
+ typedef void * ThreadRoutineArgType;
+#endif
+
+#include "gpps.hpp" //DUCKHEAD92
+
+// This file compiles into two different "modes". The first (DEBUG_MODE) defined will
+// compile into a Windows NT console application. Just run this exactly like
+// any other NT console app (it provides everything the service does). The second
+// mode (DEBUG_MODE undefined) is the service.
+
+#ifndef DEBUG_MODE
+# define DEBUG_MODE
+#endif
+
+// IPC Block is a block of data which is passed from parent to child with the socket#
+#define IPCBlockMagic 0xafaced0a
+typedef struct _IPCBlock
+ {
+#ifdef UNIX
+ int Magic;
+#endif
+ int Socketfd;
+ } IPCBlock;
+
+BOOL RunServer = TRUE; // reset for regen etc
+
+char RootConfig[64] = "sscscp"; // main entry in ini file
+
+// Later make everything MAX_PATH or similar?
+char BaseDir[256] = ""; // where the files are
+
+#ifndef UNIX
+char ConfigFile[256] = ".\\dicom.ini"; // name ini file
+char DicomDict[256] = ".\\dgate.dic"; // name dicomdictionary file
+#else
+char ConfigFile[512] = "dicom.ini";
+char DicomDict[256] = "dgate.dic";
+#endif
+
+#ifndef UNIX // for routing IODs
+char AutoRoutePipe[128] = "\\\\.\\pipe\\AutoRoutePipe";
+char AutoRouteExec[128] = "aroute.exe";
+#else
+char AutoRoutePipe[128] = "/tmp/AutoRoutePipe";
+char AutoRouteExec[128] = "aroute";
+#endif
+
+extern Array < ACRNemaAddress * > ACRNemaAddressArray; // for -a listing
+int DebugLevel = 0; // increased after error
+RTC VRType(TRUE); // VR translation table
+extern int FileCompressMode;
+extern unsigned int gl_iFileCounter;
+
+int ThreadCount = 0; // Counts total number of associations
+int OpenThreadCount = 0; // Counts total number of open associations
+int EnableReadAheadThread=1; // to enable/disable read ahead thread
+int WorkListMode = 0; // use worklist to update incoming data
+
+char DroppedFileCompression[16]; // compression of dropped files
+char IncomingCompression[16]; // compression of incoming images
+char ArchiveCompression[16]; // compression of images to be archived
+char TestMode[16]=""; // if set, appended to filename for comparison
+char StatusString[256]=""; // status of submission and move for web i/f
+
+int StorageFailedErrorCode = 0x110; // returned when C-STORE fails (default failed processing)
+int FailHoldOff = 60; // holdoff in seconds aftre last export/copy failure
+int RetryDelay = 100; // delay in seconds aftre last export/copy failure for retry
+int QueueSize = 128; // number of entries in export/copy queue (2k per entry in memory)
+int ForwardCollectDelay = 600; // delay for forward patient to etc ....
+
+char VirtualServerFor[11][48]; // AE's of servers providing data for this one (cache function) + parameters
+BOOL VirtualServerPerSeries[11]; // If set, get images at SERIES level instead of at IMAGE level
+int CacheVirtualData=1; // if set, keep (cache) passed through data
+
+// jpeg, jpeg2k global stuff
+int gJpegQuality=95; // The quality of the lossy jpeg or j2k image
+int gUseOpenJpeg=0; // If we have both Jasper and OpenJPEG, it lets the dicom.ini choose.
+
+extern int FixKodak;
+extern int NumIndexing; // from odbci.cpp: is -1 on startup, >0 during DBF indexing
+extern int DoubleBackSlashToDB;
+extern int UseEscapeStringConstants;
+extern int EnableComputedFields;
+extern int FileCompressMode;
+
+// counters for status display
+int StartTime; // when dgate is started
+int TotalTime=0; // total run time in s
+int LoadTime=0; // total time loading
+int ProcessTime=0; // total time processing (downsize)
+int SaveTime=0; // total time saving
+
+int ImagesSent=0; // how many images were sent
+int ImagesReceived=0; // idem recieved
+int ImagesSaved=0; // idem saved
+int ImagesForwarded=0; // idem forwarded
+int ImagesExported=0; // executable as export converted
+int ImagesCopied=0; // copy as export converter
+
+int IncomingAssociations=0; // accepted incoming associations (start thread)
+int EchoRequest=0; // c-echo requests
+int C_Find_PatientRoot=0;
+int C_Move_PatientRootNKI=0;
+int C_Move_PatientRoot=0;
+int C_Find_StudyRoot=0;
+int C_Move_StudyRootNKI=0;
+int C_Move_StudyRoot=0;
+int C_Find_PatientStudyOnly=0;
+int C_Find_ModalityWorkList=0;
+int C_Move_PatientStudyOnlyNKI=0;
+int C_Move_PatientStudyOnly=0;
+int UnknownRequest=0;
+
+int CreateBasicFilmSession=0; // printer actions
+int DeleteBasicFilmSession=0;
+int ActionBasicFilmSession=0;
+int SetBasicFilmSession=0;
+int CreateBasicFilmBox=0;
+int ActionBasicFilmBox=0;
+int SetBasicFilmBox=0;
+int DeleteBasicFilmBox=0;
+int SetBasicGrayScaleImageBox=0;
+int SetBasicColorImageBox=0;
+
+int GuiRequest=0; // server command requests from GUI
+int ImagesToGifFromGui=0;
+int ImagesToDicomFromGui=0;
+int ExtractFromGui=0;
+int QueryFromGui=0;
+int DeleteImageFromGui=0;
+int DeletePatientFromGui=0;
+int DeleteStudyFromGui=0;
+int DeleteStudiesFromGui=0;
+int DeleteSeriesFromGui=0;
+int MovePatientFromGui=0;
+int MoveStudyFromGui=0;
+int MoveStudiesFromGui=0;
+int MoveSeriesFromGui=0;
+int AddedFileFromGui=0;
+int DumpHeaderFromGui=0;
+int ForwardFromGui=0;
+int GrabFromGui=0;
+int NoDicomCheck=0;
+
+extern int DatabaseOpen; // database activity
+extern int DatabaseClose;
+extern int DatabaseQuery;
+extern int DatabaseAddRecord;
+extern int DatabaseDeleteRecord;
+extern int DatabaseNextRecord;
+extern int DatabaseCreateTable;
+extern int DatabaseUpdateRecords;
+extern int QueryTime;
+
+extern int SkippedCachedUpdates; // entering into database levels
+extern int UpdateDatabase;
+extern int AddedDatabase;
+
+extern int NKIPrivateCompress; // compression activity
+extern int NKIPrivateDecompress;
+extern int DownSizeImage;
+extern int DecompressJpeg;
+extern int CompressJpeg;
+extern int DecompressJpeg2000;
+extern int CompressJpeg2000;
+extern int DecompressedRLE;
+extern int DePlaned;
+extern int DePaletted;
+extern int RecompressTime;
+extern int gpps, gppstime;
+
+//These tables define parameters to be exported to lua for a global object
+
+#define def(a) #a, &a,
+#define def2(a) #a, a, sizeof(a),
+
+struct iglobal {char *name; int *data; };
+struct sglobal {char *name; char *data; int len; };
+
+struct iglobal iglobals[]=
+{
+def(StartTime)
+def(TotalTime)
+def(LoadTime)
+def(ProcessTime)
+def(SaveTime)
+def(ImagesSent)
+def(ImagesReceived)
+def(ImagesSaved)
+def(ImagesForwarded)
+def(ImagesExported)
+def(ImagesCopied)
+def(IncomingAssociations)
+def(EchoRequest)
+def(C_Find_PatientRoot)
+def(C_Move_PatientRootNKI)
+def(C_Move_PatientRoot)
+def(C_Find_StudyRoot)
+def(C_Move_StudyRootNKI)
+def(C_Move_StudyRoot)
+def(C_Find_PatientStudyOnly)
+def(C_Find_ModalityWorkList)
+def(C_Move_PatientStudyOnlyNKI)
+def(C_Move_PatientStudyOnly)
+def(UnknownRequest)
+def(CreateBasicFilmSession)
+def(DeleteBasicFilmSession)
+def(ActionBasicFilmSession)
+def(SetBasicFilmSession)
+def(CreateBasicFilmBox)
+def(ActionBasicFilmBox)
+def(SetBasicFilmBox)
+def(DeleteBasicFilmBox)
+def(SetBasicGrayScaleImageBox)
+def(SetBasicColorImageBox)
+def(GuiRequest)
+def(ImagesToGifFromGui)
+def(ImagesToDicomFromGui)
+def(ExtractFromGui)
+def(QueryFromGui)
+def(DeleteImageFromGui)
+def(DeletePatientFromGui)
+def(DeleteStudyFromGui)
+def(DeleteStudiesFromGui)
+def(DeleteSeriesFromGui)
+def(MovePatientFromGui)
+def(MoveStudyFromGui)
+def(MoveStudiesFromGui)
+def(MoveSeriesFromGui)
+def(AddedFileFromGui)
+def(DumpHeaderFromGui)
+def(ForwardFromGui)
+def(GrabFromGui)
+def(DatabaseOpen)
+def(DatabaseClose)
+def(DatabaseQuery)
+def(DatabaseAddRecord)
+def(DatabaseDeleteRecord)
+def(DatabaseNextRecord)
+def(DatabaseCreateTable)
+def(DatabaseUpdateRecords)
+def(QueryTime)
+def(SkippedCachedUpdates)
+def(UpdateDatabase)
+def(AddedDatabase)
+def(NKIPrivateCompress)
+def(NKIPrivateDecompress)
+def(DownSizeImage)
+def(DecompressJpeg)
+def(CompressJpeg)
+def(DecompressJpeg2000)
+def(CompressJpeg2000)
+def(DecompressedRLE)
+def(DePlaned)
+def(DePaletted)
+def(RecompressTime)
+def(gpps)
+def(gppstime)
+def(NoDicomCheck)
+
+def(DebugLevel)
+def(ThreadCount)
+def(OpenThreadCount)
+def(EnableReadAheadThread)
+def(WorkListMode)
+def(StorageFailedErrorCode)
+def(FailHoldOff)
+def(RetryDelay)
+def(QueueSize)
+def(ForwardCollectDelay)
+def(CacheVirtualData)
+
+def(gJpegQuality)
+def(gUseOpenJpeg)
+
+def(FixKodak)
+def(NumIndexing)
+def(DoubleBackSlashToDB)
+def(UseEscapeStringConstants)
+def(EnableComputedFields)
+def(FileCompressMode)
+
+"", NULL
+};
+
+struct sglobal sglobals[]=
+{
+def2(RootConfig)
+def2(BaseDir)
+def2(ConfigFile)
+def2(DicomDict)
+def2(AutoRoutePipe)
+def2(AutoRouteExec)
+
+def2(DroppedFileCompression)
+def2(IncomingCompression)
+def2(ArchiveCompression)
+def2(TestMode)
+def2(StatusString)
+
+"", NULL
+};
+
+#ifndef ctime_r
+#define ctime_r(a, b) ctime(a)
+#endif
+
+#ifndef localtime_r
+#define localtime_r(a, b) memcpy(b, localtime(a), sizeof(struct tm))
+#endif
+
+void ConfigDgate(void);
+BOOL ToGif(DICOMDataObject* pDDO, char *filename, int size, int append, int level, int window, unsigned int frame);
+BOOL ToBMP(DICOMDataObject* pDDO, char *filename, int size, int append, int level, int window, unsigned int frame);
+BOOL ToJPG(DICOMDataObject* pDDO, char *filename, int size, int append, int level, int window, unsigned int frame, int quality);
+int MaybeDownsize(DICOMDataObject* pDDO, DICOMCommandObject* pDCO, int size);
+BOOL ExtractFrame(DICOMDataObject* pDDO, unsigned int Frame);
+BOOL ExtractFrames(DICOMDataObject* pDDO, unsigned int FirstFrame, unsigned int LastFrame, int skip);
+int GetNumberOfFrames(DICOMDataObject* pDDO);
+
+/* error handling for out of memory and such */
+
+void MyDcmError(int error, const char *message, int count)
+ {
+ char buffer[300];
+ char szRootSC[64];
+
+ if (error==DCM_ERROR_DEBUG)
+ {
+ if (DebugLevel==0) return;
+ sprintf(buffer, message, count);
+ strcat(buffer, "\n");
+ SystemDebug.printf(buffer);
+ }
+ else
+ {
+ strcpy(buffer, "***");
+ sprintf(buffer+3, message, count);
+ strcat(buffer, "\n");
+ OperatorConsole.printf(buffer);
+ }
+
+ if (error==DCM_ERROR_MEMORY)
+ {
+ if (MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile))
+ {
+ MyGetPrivateProfileString(szRootSC, "IgnoreOutOfMemoryErrors", "0", buffer, 64, ConfigFile);
+ if (atoi(buffer)) return;
+ }
+ OperatorConsole.printf("***A fatal error occurred (out of memory) - closing server\n");
+ exit(1);
+ }
+ }
+
+void StatusDisplay(FILE *f)
+{ char TimeString[80], buf[64];
+ time_t T=StartTime;
+ Database DB;
+ unsigned int i;
+ int libjasper=0;
+ int libjpeg=0;
+ int intjpeg=1;
+
+ UNUSED_ARGUMENT(buf);// Added for unused variable warning. bcb
+
+#ifdef HAVE_J2K
+ libjasper=1;
+#endif
+#ifdef HAVE_LIBJPEG
+ libjpeg=1;
+ intjpeg=0;
+#endif
+#ifdef NOINTJPEG
+ intjpeg=0;
+#endif
+
+ strcpy(TimeString, ctime_r(&T, buf));
+ TimeString[strlen(TimeString)-1] = '\0';
+
+ fprintf(f, "DICOM server '%s' (version %s, port %s, bits %d) was started on %s\n", MYACRNEMA, DGATE_VERSION, Port, (int)(8*sizeof(void *)), TimeString);
+ fprintf(f, "Old JPEG decoder=%d, JPEGLIB jpeg codec=%d, LIBJASPER jpeg2000 codec=%d\n", intjpeg, libjpeg, libjasper);
+
+ fprintf(f, "Run time (s) total %d, query %d, load %d, save %d, compress %d, process %d, gpps %d\n", TotalTime, QueryTime/1000, LoadTime, SaveTime, RecompressTime, ProcessTime, gppstime);
+ fprintf(f, "Associations=%d; Threads=%d (%d open); Images sent=%d, recieved=%d, forwarded=%d\n", IncomingAssociations, ThreadCount, OpenThreadCount, ImagesSent, ImagesReceived, ImagesForwarded);
+ fprintf(f, "Images printed=%d, in color=%d\n", SetBasicGrayScaleImageBox+SetBasicColorImageBox, SetBasicColorImageBox);
+ fprintf(f, "Activity: Echo:%d, Find:%d, Move:%d, Unknown:%d, gpps:%d\n", EchoRequest, C_Find_PatientRoot+C_Find_StudyRoot+C_Find_PatientStudyOnly+C_Find_ModalityWorkList,
+ C_Move_PatientRootNKI+C_Move_PatientRoot+C_Move_StudyRootNKI+C_Move_StudyRoot+C_Move_PatientStudyOnlyNKI+C_Move_PatientStudyOnly, UnknownRequest, gpps);
+ fprintf(f, "Images (de)compressed: NKI %d, JPEG %d, JPEG2000 %d, RLE %d, Planes removed %d, Palettes removed %d, Downsize %d\n",
+ NKIPrivateCompress+NKIPrivateDecompress, DecompressJpeg+CompressJpeg, DecompressJpeg2000+CompressJpeg2000,
+ DecompressedRLE, DePlaned, DePaletted, DownSizeImage);
+ for (i=0; i<MAGDevices; i++)
+ fprintf (f, "Space on MAG%d : %d MByte\n", i, CheckFreeStoreOnMAGDevice(i));
+ for (i=0; i<CACHEDevices; i++)
+ fprintf (f, "Space on CACHE%d: %d MByte\n", i, CheckFreeStoreOnCACHEDevice(i));
+ if (DB.Open ( DataSource, UserName, Password, DataHost ) )
+ { switch(DB.db_type)
+ { case DT_ODBC: fprintf(f, "Database type: ODBC connection\n"); break;
+ case DT_POSTGRES: fprintf(f, "Database type: native PostGres connection\n"); break;
+ case DT_MYSQL: fprintf(f, "Database type: native MySQL connection\n"); break;
+ case DT_SQLITE: fprintf(f, "Database type: built-in SQLite driver\n"); break;
+ case DT_DBASEIII: fprintf(f, "Database type: built-in Dbase driver\n"); break;
+ case DT_DBASEIIINOINDEX: fprintf(f, "Database type: built-in Dbase driver (indices disabled)\n"); break;
+ case DT_NULL: fprintf(f, "Database type: NULL driver (black hole)\n"); break;
+ }
+ for (i=0; i<10; i++)
+ if (DB.dbase_handles[i])
+ fprintf(f, "Database %s has %d records\n", DB.dbase_handles[i]->filename, DB.dbase_handles[i]->reccount);
+ };
+}
+
+// Dump an association request for the status display
+
+static BOOL AbstractSyntaxEnabled(CheckedPDU_Service &p, AbstractSyntax &AbsSyntax)
+ {
+ UINT Index;
+
+ if ( ! p.SOPUIDListCount )
+ return ( TRUE );
+
+ Index = 0;
+ while ( Index < p.SOPUIDListCount )
+ {
+ if ( UID ( p.SOPUIDList [ Index ] ) ==
+ AbsSyntax.AbstractSyntaxName)
+ return ( TRUE );
+ ++Index;
+ }
+ return ( FALSE );
+ }
+
+
+void
+IARQ (AAssociateRQ &ARQ, BOOL showall)
+ {
+ char s[128];
+
+ SystemDebug.printf("A-ASSOCIATE-RQ Packet Dump\n");
+
+ memset(s, 0, 64);
+ memcpy(s, ARQ.CallingApTitle, 16);
+ OperatorConsole.printf("\tCalling Application Title : \"%s\"\n", s);
+
+ memset(s, 0, 64);
+ memcpy(s, ARQ.CalledApTitle, 16);
+ OperatorConsole.printf("\tCalled Application Title : \"%s\"\n", s);
+
+ memset(s, 0, 64);
+ memcpy(s, ARQ.AppContext.ApplicationContextName.GetBuffer(1),
+ ARQ.AppContext.ApplicationContextName.GetSize() );
+ OperatorConsole.printf("\tApplication Context : \"%s\", PDU length: %d\n", s, ARQ.UserInfo.GetMax());
+
+ SystemDebug.printf("\tNumber of Proposed Presentation Contexts: %d\n",
+ ARQ.PresContexts.GetSize());
+
+ unsigned int Index = 0;
+ while (Index < ARQ.PresContexts.GetSize() )
+ {
+ PresentationContext PC;
+
+ PC = ARQ.PresContexts.Get(Index);
+ PC.TrnSyntax.ClearType = FALSE;
+
+ memset(s, 0, 64);
+ memcpy(s,
+ PC.AbsSyntax.AbstractSyntaxName.GetBuffer(1),
+ PC.AbsSyntax.AbstractSyntaxName.GetSize()%64 );
+
+ OperatorConsole.printf("\tPresentation Context %d \"%s\" %d\n", Index, s, AbstractSyntaxEnabled(*(CheckedPDU_Service*)(&ARQ), PC.AbsSyntax));
+ ++Index;
+
+ if (showall)
+ {
+ unsigned int IndexTrn = 0;
+ while ( IndexTrn < PC.TrnSyntax.GetSize())
+ {
+ UID uid;
+
+ TransferSyntax TrnSyntax = PC.TrnSyntax.Get(IndexTrn);
+ memset(s, 0, 64);
+ memcpy(s,
+ TrnSyntax.TransferSyntaxName.GetBuffer(1),
+ TrnSyntax.TransferSyntaxName.GetSize()%64 );
+
+ uid = TrnSyntax.TransferSyntaxName;
+
+ OperatorConsole.printf("\t\tTransfer Syntax %d \"%s\" %d\n", IndexTrn, s,
+ ((CheckedPDU_Service*)&ARQ)->CanYouHandleTransferSyntax(TrnSyntax));
+
+ IndexTrn++;
+ }
+ }
+ }
+ }
+
+// Help routines to allow dumping of logs after an error occurs
+// Test if character is alphanumerical
+
+BOOL IsAlpha(BYTE c)
+ {
+ if((c >= ' ')&&(c <= 125))
+ return ( TRUE );
+ if(!c)
+ return ( TRUE );
+ return ( FALSE );
+ }
+
+// Test if all of string is alphanumerical
+
+BOOL IsDataAlpha(UINT Size, BYTE *data)
+ {
+ if(Size > 16)
+ Size = 16;
+ if(!Size)
+ return ( FALSE );
+ --Size;
+ while(Size)
+ {
+ if(!IsAlpha(data[Size]))
+ return ( FALSE );
+ --Size;
+ }
+ return ( TRUE );
+ }
+
+static void TranslateText(char* pSrc, char* pDest, int iSize)
+{
+ int i;
+
+ /* Translate CR, LF and FF to escape sequences */
+ for (i=0; i<iSize; i++)
+ switch (*pSrc)
+ {
+ case '\\':
+ *pDest++ = *pSrc;
+ *pDest++ = *pSrc++;
+ break;
+ case '\n':
+ *pDest++ = '\\';
+ *pDest++ = 'n';
+ pSrc++;
+ break;
+ case '\r':
+ *pDest++ = '\\';
+ *pDest++ = 'r';
+ pSrc++;
+ break;
+ case '\f':
+ *pDest++ = '\\';
+ *pDest++ = 'f';
+ pSrc++;
+ break;
+ default:
+ *pDest++ = *pSrc++;
+ break;
+ }
+ *pDest = 0;
+}
+
+// Print data from a single dicom object
+BOOL PrintUDATA(UINT Size, void *data, UINT16 TypeCode, char *dest)
+ {
+ UINT Index = 0;
+ unsigned char *c;
+ UINT16 tint16;
+ UINT32 tint32;
+ BYTE *b;
+ LE_UINT16 *w;
+ char Str[512];
+ LE_UINT32 *l32 = (LE_UINT32*)data;
+ LE_UINT16 *l16 = (LE_UINT16*)data;
+ LE_INT32 *s32 = (LE_INT32*)data;
+ LE_INT16 *s16 = (LE_INT16*)data;
+
+ if(!data)
+ {
+ if ( TypeCode == 'SQ' )
+ {
+ sprintf(dest, "Sequence Item");
+ return ( TRUE );
+ }
+
+ sprintf(dest, "(empty)");
+ return ( TRUE );
+ }
+
+ if ( ! TypeCode || TypeCode == 'UN' )
+ {
+ switch ( Size )
+ {
+ case 2:
+ tint16 = (*((UINT16 *) data));
+ sprintf(dest, "(%d|%x)", (UINT) tint16, (UINT) tint16);
+ break;
+ case 4:
+ tint32 = (*((UINT32 *) data));
+ sprintf(dest, "[%d|%x]", (UINT) tint32, (UINT) tint32);
+ break;
+ default:
+ if(IsDataAlpha(Size, (BYTE*) data))
+ {
+ if(Size > 256) Size = 256;
+ TranslateText((char*)data, Str, Size);
+ sprintf(dest, "\"%s\"", Str);
+ break;
+ }
+ Index = 0;
+ while(Index < Size)
+ {
+ if(Index >= 16)
+ break;
+ c = (unsigned char*)data;
+ c += Index;
+ if (isprint(*c))
+ sprintf(dest, "%2.2x(%c)", *c, *c);
+ else
+ sprintf(dest, "%2.2x", *c);
+ ++Index;
+ }
+ }
+ }
+ else
+ {
+ switch ( TypeCode )
+ {
+ case 'AE':
+ case 'AS':
+ case 'CS':
+ case 'DA':
+ case 'DS':
+ case 'DT':
+ case 'IS':
+ case 'LO':
+ case 'LT':
+ case 'PN':
+ case 'SH':
+ case 'ST':
+ case 'TM':
+ case 'UI':
+ if(Size > 256) Size = 256;
+ TranslateText((char*)data, Str, Size);
+ sprintf(dest, "\"%s\" ", Str);
+ break;
+
+ case 'FL':
+ case 'FD':
+ break;
+
+ case 'AT':
+ Index = 0;
+ while ( Index < Size )
+ {
+ UINT16 Grp, Elm;
+ Grp = (*l16);++l16;
+ Elm = (*l16);++l16;
+ sprintf(dest, "(%4.4x, %4.4x) ", Grp, Elm);
+ Index += 4;
+ }
+ break;
+
+ case 'OB':
+ b = (BYTE*)data;
+ while ( Index < Size )
+ {
+ if ( Index > 10 ) break;
+ sprintf(dest, "%2.2x ", *b);
+ ++b;
+ ++Index;
+ }
+ break;
+
+ case 'OW':
+ w = (LE_UINT16*)data;
+ while(Index < Size )
+ {
+ if ( Index > 20 ) break;
+ sprintf(dest, "%4.4x ", (UINT16)(*w));
+ ++w;
+ ++Index;
+ ++Index;
+ }
+ break;
+
+ case 'UL':
+ while ( Index < Size )
+ {
+ if ( Index > 40 ) break;
+ sprintf(dest, "%u ", (unsigned int)(*l32));
+ ++l32;
+ Index += 4;
+ }
+ break;
+
+ case 'US':
+ while ( Index < Size )
+ {
+ if ( Index > 20 ) break;
+ sprintf(dest, "%u ", (unsigned int)(*l16));
+ ++l16;
+ Index += 2;
+ }
+ break;
+
+ case 'SL':
+ while ( Index < Size )
+ {
+ if ( Index > 40 ) break;
+ sprintf(dest, "%d ", (int)(*s32));
+ ++s32;
+ Index += 4;
+ }
+ break;
+
+ case 'SS':
+ while ( Index < Size )
+ {
+ if ( Index > 20 ) break;
+ sprintf(dest, "%d ", (int)(*s16));
+ ++s16;
+ Index += 2;
+ }
+ break;
+
+ }
+ }
+ return ( TRUE );
+ }
+
+// Print a single dicom object
+BOOL DumpVR(VR *vr, FILE *f, int iDepth)
+ {
+ INT Index;
+ UINT16 TypeCode;
+ char b[256];
+ char s[256];
+ char d[514]; // "\n\n\n...."
+
+ if (DebugLevel<1 && f==NULL)
+ return ( TRUE );
+
+ if (vr->Element==0) return TRUE;
+
+ for (Index=0; Index<iDepth; Index++) b[Index]='>';
+ b[iDepth]=0;
+
+ s[0] = '\0';
+ TypeCode = VRType.RunTimeClass(vr->Group, vr->Element, s);
+
+ PrintUDATA ( vr->Length, vr->Data, TypeCode, d );
+
+ if (f)
+ {
+ if(TypeCode)
+ fprintf(f, "%s%4.4x,%4.4x %6u %c%c %-20.20s %s\n",
+ b, vr->Group, vr->Element, vr->Length,
+ TypeCode>>8, TypeCode&0x00ff, s, d);
+ else
+ fprintf(f, "%s%4.4x,%4.4x %6d UN %-20.20s %s\n",
+ b, vr->Group, vr->Element, vr->Length, "", d);
+ }
+ else
+ {
+ if(TypeCode)
+ SystemDebug.printf("%s%4.4x,%4.4x %6u %c%c %-20.20s %s\n",
+ b, vr->Group, vr->Element, vr->Length,
+ TypeCode>>8, TypeCode&0x00ff, s, d);
+ else
+ SystemDebug.printf("%s%4.4x,%4.4x %6u UN %-20.20s %s\n",
+ b, vr->Group, vr->Element, vr->Length, "", d);
+ }
+ return(TRUE);
+ }
+
+
+// Print a composite dicom object + sequences
+BOOL
+NonDestructiveDumpDICOMObject(
+ DICOMObject *DO, FILE *f = NULL, int iDepth=0)
+ {
+ DICOMObject DO2;
+ VR *vr;
+ int i;
+ unsigned int Index;
+
+ if(DebugLevel<1 && f==NULL)
+ return ( TRUE );
+
+ while((vr=DO->Pop()))
+ {
+ DumpVR(vr, f, iDepth);
+ if ( vr->SQObjectArray )
+ {
+ Array < DICOMDataObject * > *ADDO =
+ (Array<DICOMDataObject*>*) vr->SQObjectArray;
+
+ Index = 0;
+ while ( Index < ADDO->GetSize() )
+ {
+ NonDestructiveDumpDICOMObject(ADDO->Get(Index), f, iDepth+1);
+
+ ++Index;
+ if (Index == ADDO->GetSize()) break;
+
+ for (i=0; i<iDepth+1; i++)
+ if (f) fprintf(f, "-");
+ else SystemDebug.printf("-");
+ if (f) fprintf(f, "\n");
+ else SystemDebug.printf("\n");
+ }
+ }
+ DO2.Push(vr);
+ }
+ DO->Reset();
+ while((vr=DO2.Pop()))
+ {
+ DO->Push(vr);
+ }
+ return ( TRUE );
+ }
+
+
+
+// Check code from dumppacs pasted here for convenience
+// List status of mag devices (free space)
+BOOL
+PrintFreeSpace()
+ {
+ unsigned int Index;
+
+ OperatorConsole.printf("** MAG DEVICE CHECK\n");
+ OperatorConsole.printf("\n");
+ Index = 0;
+ while ( Index < MAGDevices )
+ {
+ OperatorConsole.printf ( "Free space on MAG Device %d := %d MByte\n", Index,
+ CheckFreeStoreOnMAGDevice(Index));
+ ++Index;
+ }
+
+ Index = 0;
+ while ( Index < MIRRORDevices )
+ {
+ OperatorConsole.printf ( "Free space on MIRROR Device %d := %d MByte\n", Index,
+ CheckFreeStoreOnMIRRORDevice(Index));
+ ++Index;
+ }
+
+ Index = 0;
+ while ( Index < CACHEDevices )
+ {
+ OperatorConsole.printf ( "Free space on CACHE Device %d := %d MByte\n", Index,
+ CheckFreeStoreOnCACHEDevice(Index));
+ ++Index;
+ }
+
+ return ( TRUE );
+ }
+
+// Print Out A-MAP data struct (used for outgoing C-MOVES)
+BOOL
+PrintAMap()
+ {
+ UINT Index = 0;
+ OperatorConsole.printf( "** AE / IP-PORT Map dump\n");
+ OperatorConsole.printf("\n");
+
+
+ while ( Index < ACRNemaAddressArray.GetSize() )
+ {
+ ACRNemaAddress *AAPtr = ACRNemaAddressArray.Get(Index);
+
+ OperatorConsole.printf("%-17s %-30s %-10s %-16s\n",
+ AAPtr->Name,
+ AAPtr->IP,
+ AAPtr->Port,
+ AAPtr->Compress);
+ ++Index;
+ }
+ return ( TRUE );
+ }
+
+// Help routine for listing SQL database configuation; sql field type string
+const char *
+SQLTypeSymName(
+ int SQLType)
+ {
+ switch ( SQLType )
+ {
+ case SQL_C_CHAR: return("SQL_C_CHAR");
+ case SQL_C_DATE: return("SQL_C_DATE");
+ default: return("--bad--");
+ }
+ return("--bad--");
+ }
+
+// Help routine for listing SQL database configuration; dicom object type string
+const char *
+DICOMTypeSymName(
+ int DICOMType)
+ {
+ switch ( DICOMType )
+ {
+ case DT_STR: return("DT_STR");
+ case DT_MSTR: return("DT_MSTR");
+ case DT_DATE: return("DT_DATE (DA)");
+ case DT_UINT16: return("DT_UINT16 (US)");
+ case DT_UINT32: return("DT_UINT32 (UL)");
+ case DT_UI: return("DT_UI (UI)");
+ case DT_FL: return("DT_FL (FL)");
+ case DT_FD: return("DT_FD (FD)");
+ case DT_STARTSEQUENCE: return("Start sequence");
+ case DT_ENDSEQUENCE: return("End sequence");
+ default: return ("--bad--");
+ }
+ return("--bad--");
+ }
+
+// Help routine for listing SQL database configuration; list one table
+BOOL
+DumpDD (
+ DBENTRY *DBE)
+ {
+ UINT Index = 0;
+
+ while ( DBE[Index].Group )
+ {
+ OperatorConsole.printf("0x%4.4x,0x%4.4x %10s %4d %10s %14s %10s\n",
+ DBE[Index].Group,
+ DBE[Index].Element,
+ DBE[Index].SQLColumn,
+ DBE[Index].SQLLength,
+ SQLTypeSymName(DBE[Index].SQLType),
+ DICOMTypeSymName(DBE[Index].DICOMType),
+ DBE[Index].HL7Tag);
+ ++Index;
+ }
+ return ( TRUE );
+ }
+
+// List full SQL database configuration
+BOOL
+PrintKFactorFile()
+ {
+// UINT Index = 0;
+ OperatorConsole.printf( "** Database Description dump\n");
+ OperatorConsole.printf("\n");
+
+ OperatorConsole.printf ("--Patient Database: %s\n", PatientTableName);
+ DumpDD(PatientDB);
+ OperatorConsole.printf ("--Study Database: %s\n", StudyTableName);
+ DumpDD(StudyDB);
+ OperatorConsole.printf ("--Series Database: %s\n", SeriesTableName);
+ DumpDD(SeriesDB);
+ OperatorConsole.printf ("--Image Database: %s\n", ImageTableName);
+ DumpDD(ImageDB);
+ OperatorConsole.printf ("--WorkList Database: %s\n", WorkListTableName);
+ DumpDD(WorkListDB);
+ return ( TRUE );
+ }
+
+
+// Delete everything of selected patient, optionally DB only
+BOOL
+DeletePatient(char *PID, BOOL KeepImages)
+ {
+ VR *vr = new VR(0x0010, 0x0020, strlen(PID), (void*)PID, (BOOL) FALSE );
+ DICOMDataObject DDO;
+
+ if (PID==NULL || *PID==0) return FALSE;
+
+ if (!KeepImages)
+ OperatorConsole.printf("Deleting patient: %s\n", PID);
+ else
+ OperatorConsole.printf("Deleting database entries for patient: %s\n", PID);
+ DDO.Push(vr);
+ RemoveFromPACS(&DDO, KeepImages);
+
+ return ( TRUE );
+ }
+
+
+void SetStringVR(VR **vr, int g, int e, const char *String);
+
+// Delete study
+BOOL
+DeleteStudy(char *ID, BOOL KeepImages)
+ {
+ VR *vr;
+ DICOMDataObject DDO;
+
+ if (ID==NULL || *ID==0) return FALSE;
+
+ char *p = strchr(ID, ':');
+
+ if (p==0)
+ {
+// vr = new VR(0x0020, 0x000d, (strlen(ID)+1)&0xfe, (void*)ID, (BOOL) FALSE );
+ SetStringVR(&vr, 0x0020, 0x000d, ID);
+ DDO.Push(vr);
+ }
+ else
+ {
+ *p=0;
+// vr = new VR(0x0020, 0x000d, (strlen(p+1)+1)&0xfe, (void*)(p+1), (BOOL) FALSE );
+ SetStringVR(&vr, 0x0020, 0x000d, p+1);
+ DDO.Push(vr);
+// vr = new VR(0x0010, 0x0020, strlen(ID), (void*)ID, (BOOL) FALSE );
+ SetStringVR(&vr, 0x0010, 0x0020, ID);
+ DDO.Push(vr);
+ }
+
+
+ if (!KeepImages)
+ OperatorConsole.printf("Deleting study: %s\n", ID);
+ else
+ OperatorConsole.printf("Deleting database entries for study: %s\n", ID);
+
+ RemoveFromPACS(&DDO, KeepImages);
+
+ return ( TRUE );
+ }
+
+// Delete studies on date (wildcards or range allowed)
+BOOL
+DeleteStudies(char *date, BOOL KeepImages)
+ {
+
+ VR *vr;
+ DICOMDataObject DDO;
+
+ if (date==NULL || *date==0) return FALSE;
+
+ if (!KeepImages)
+ OperatorConsole.printf("Deleting studies on date: %s\n", date);
+ else
+ OperatorConsole.printf("Deleting database entries for studies on date: %s\n", date);
+
+ SetStringVR(&vr, 0x0008, 0x0020, date);
+ DDO.Push(vr);
+ RemoveFromPACS(&DDO, KeepImages);
+
+ return ( TRUE );
+ }
+
+// Delete series
+BOOL
+DeleteSeries(char *ID, BOOL KeepImages)
+ {
+ VR *vr;
+ DICOMDataObject DDO;
+
+ if (ID==NULL || *ID==0) return FALSE;
+
+ char *p = strchr(ID, ':');
+
+ if (p==0)
+ {
+// vr = new VR(0x0020, 0x000e, (strlen(ID)+1)&0xfe, (void*)ID, (BOOL) FALSE );
+ SetStringVR(&vr, 0x0020, 0x000e, ID);
+ DDO.Push(vr);
+ }
+ else
+ {
+ *p=0;
+// vr = new VR(0x0020, 0x000e, (strlen(p+1)+1)&0xfe, (void*)(p+1), (BOOL) FALSE );
+ SetStringVR(&vr, 0x0020, 0x000e, p+1);
+ DDO.Push(vr);
+// vr = new VR(0x0010, 0x0020, strlen(ID), (void*)ID, (BOOL) FALSE );
+ SetStringVR(&vr, 0x0010, 0x0020, ID);
+ DDO.Push(vr);
+ }
+
+ if (!KeepImages)
+ OperatorConsole.printf("Deleting series: %s\n", ID);
+ else
+ OperatorConsole.printf("Deleting database entries for series: %s\n", ID);
+
+ RemoveFromPACS(&DDO, KeepImages);
+
+ return ( TRUE );
+ }
+
+// Delete image
+BOOL
+DeleteImage(char *ID, BOOL KeepImages)
+ {
+ VR *vr;// = new VR(0x0008, 0x0018, (strlen(ID)+1)&0xfe, (void*)ID, (BOOL) FALSE );
+ DICOMDataObject DDO;
+
+ if (ID==NULL || *ID==0) return FALSE;
+
+ if (!KeepImages)
+ OperatorConsole.printf("Deleting image: %s\n", ID);
+ else
+ OperatorConsole.printf("Deleting database entry for image: %s\n", ID);
+
+ SetStringVR(&vr, 0x0008, 0x0018, ID);
+ DDO.Push(vr);
+ RemoveFromPACS(&DDO, KeepImages);
+
+ return ( TRUE );
+ }
+
+// Compute size of a file
+static unsigned int
+DFileSize(char *Path)
+ {
+ FILE *f;
+ unsigned int res;
+
+ f = fopen(Path, "rb");
+ if (f==NULL) return 0;
+
+ fseek(f, 0, SEEK_END);
+ res = ftell(f); /* ask position */
+ fclose(f);
+
+ return res;
+ }
+
+// Test file exists
+static BOOL
+DFileExists(char *Path)
+ {
+ FILE *f;
+
+ f = fopen(Path, "rb");
+ if (f==NULL) return FALSE;
+
+ fclose(f);
+ return TRUE;
+ }
+
+static int DcmMove(const char *patid, char* pszSourceAE, char* pszDestinationAE, const char *studyuid, const char *seriesuid, const char *compress, const char *modality, const char *date,
+ const char *sop, const char *imagetype, const char *seriesdesc, int id, char *script);
+
+// Load DICOM object for GUI given with filename or patientID|sopInstanceUID or studyInstanceUID\seriesInstanceUID\sopInstanceUID
+DICOMDataObject *LoadForGUI(char *filename)
+ {
+ char FullFilename[1024], Filename[1024];
+ char Device[32];
+ char *sop, *pat, *stud, *ser;
+ PDU_Service PDU;
+ DICOMDataObject DDO;
+ VR *vr;
+
+ PDU.AttachRTC(&VRType);
+
+ sop = strchr(filename, '|');
+ if (!sop) sop = strchr(filename, '?');
+ if (!sop) sop = strchr(filename, '*');
+ if (!sop) sop = strchr(filename, ':');
+ if (sop && (sop[1] != '\\'))
+ {
+ *sop++= 0;
+ pat = filename;
+
+ // vr = new VR(0x0008, 0x0018, (strlen(sop)+1)&0xfe, (void*)sop, FALSE );
+ SetStringVR(&vr, 0x0008, 0x0018, sop);
+
+ if(!GetFileName(vr, Filename, Device, TRUE, pat))
+ {
+ delete vr;
+ return NULL; // not in database ?
+ }
+
+ if (!FindPhysicalDevice(Device, FullFilename, Filename))
+ {
+ OperatorConsole.printf("***GUI could not find file:%s\n", Filename);
+ delete vr;
+ return NULL;
+ }
+
+ strcat(FullFilename, Filename);
+
+ delete vr;
+ if (*TestMode) strcat(FullFilename, TestMode);
+ return PDU.LoadDICOMDataObject(FullFilename);
+ }
+
+ sop = NULL;
+ ser = strchr(filename, '\\');
+ if (ser) sop = strchr(ser+1, '\\');
+ if (ser && sop && (sop-ser)>8 && !DFileExists(filename))
+ {
+ *sop++= 0;
+ *ser++= 0;
+ stud = filename;
+
+ SetStringVR(&vr, 0x0008, 0x0018, sop);
+ if(!GetFileName(vr, Filename, Device, TRUE, NULL, stud, ser))
+ {
+ delete vr;
+ SystemDebug.printf("Attempting to locate %s on virtualservers", Filename);
+ DcmMove("", (char *)MYACRNEMA, (char *)MYACRNEMA, stud, ser, "", "", "", sop, "", "", 7, "");
+
+ /*for (int i=0; i<10; i++)
+ {
+ if (*VirtualServerFor[i])
+ {
+ char *q, tmp[64];
+ strcpy(tmp, VirtualServerFor[i]);
+ q = strchr(tmp, ',');
+ if (q) *q=0;
+ if (!DcmMove("", tmp, (char *)MYACRNEMA, stud, ser, "", "", "", sop, "", "", 7, "")) break;
+ }
+ }
+ */
+
+ SetStringVR(&vr, 0x0008, 0x0018, sop);
+ if(!GetFileName(vr, Filename, Device, TRUE, NULL, stud, ser))
+ {
+ SystemDebug.printf("Object %s is still not in database", filename);
+ delete vr;
+ return NULL; // still not in database
+ }
+ }
+
+ if (!FindPhysicalDevice(Device, FullFilename, Filename))
+ {
+ OperatorConsole.printf("***GUI could not find file:%s\n", Filename);
+ delete vr;
+ return NULL;
+ }
+
+ strcat(FullFilename, Filename);
+
+ delete vr;
+ if (*TestMode) strcat(FullFilename, TestMode);
+ return PDU.LoadDICOMDataObject(FullFilename);
+ }
+
+ strcpy(FullFilename, filename);
+ return PDU.LoadDICOMDataObject(filename);
+ }
+
+// external reference from nkiqrsop.cxx
+void SaveDICOMDataObject(char *Filename, DICOMDataObject* pDDO);
+
+#ifndef WIN32
+#ifndef EnterCriticalSection
+# define EnterCriticalSection(a) pthread_mutex_lock(a)
+#endif
+#ifndef LeaveCriticalSection
+# define LeaveCriticalSection(a) pthread_mutex_unlock(a)
+#endif
+#ifndef CRITICAL_SECTION
+# define CRITICAL_SECTION pthread_mutex_t
+#endif
+#ifndef InitializeCriticalSection
+# define InitializeCriticalSection(a) pthread_mutex_init(a, NULL);
+#endif
+#define mkdir(a) mkdir(a, 0777)
+#endif
+
+#ifndef __SearchDICOMObject
+int SearchDICOMObject(DICOMObject *DDO, const char *desc, char *result, Array < DICOMDataObject * > **A = NULL, DICOMDataObject **O = NULL);
+#endif
+
+// This class handles temporary storage of a recieved object named with SOP
+class MyBridgeStorage : public UnknownStorage
+ {
+ public:
+ // called for each incoming DDO
+ UINT16 CheckObject(DICOMDataObject *DDO, PDU_Service *PDU)
+ {
+ char Filename[1024];
+ char Called[20], Calling[20];
+ char *Compression;
+ int rc, i;
+
+ ImagesReceived++;
+
+ // If the called AE looks like SERVER~j2, then the last 2 characters override IncomingCompression
+ strcpy(Called, (char *)(((AAssociateAC *)PDU)->CalledApTitle));
+ while (Called[strlen(Called)-1]==' ') Called[strlen(Called)-1] = 0;
+
+ strcpy(Calling, (char *)(((AAssociateAC *)PDU)->CallingApTitle));
+ while (Calling[strlen(Calling)-1]==' ') Calling[strlen(Calling)-1] = 0;
+
+ Compression = strchr(Called, '~');
+ if (!Compression) Compression = IncomingCompression; else Compression++;
+
+ // Recompress (e.g., leave as is or decompress) incoming files
+ recompress(&DDO, Compression, "", Compression[0]=='n' || Compression[0]=='N', (ExtendedPDU_Service *)PDU);
+
+ char szTemp[256], szRootSC[256];
+ MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile);
+ MyGetPrivateProfileString(szRootSC, "TempDir", "", szTemp, 64, ConfigFile);
+ if (szTemp[0]==0)
+ {
+ Filename[0]=0;
+ GetPhysicalDevice("MAG0", Filename);
+ strcat(Filename, "printer_files");
+ }
+ else
+ strcpy(Filename, szTemp);
+
+ mkdir(Filename);
+
+ i = strlen(Filename);
+ Filename[i] = PATHSEPCHAR;
+ Filename[i+1] = 0;
+ SearchDICOMObject(DDO, "0008,0018", Filename+i+1);
+
+ SaveDICOMDataObject(Filename, DDO);
+ DDO->Reset();
+
+ return 0;
+ }
+ };
+
+DICOMDataObject *LoadForBridge(char *stsesop, char *ae)
+ {
+ char *sop, *stud, *ser;
+ char Filename[1024];
+ DICOMDataObject *p;
+ PDU_Service PDU;
+ PDU.AttachRTC(&VRType);
+ int i;
+
+ sop = NULL;
+ ser = strchr(stsesop, '\\');
+ if (ser) sop = strchr(ser+1, '\\');
+ if (ser && sop)
+ {
+ *sop++= 0;
+ *ser++= 0;
+ stud = stsesop;
+ SystemDebug.printf("Attempting to locate %s for bridge from %s", stsesop, ae);
+ DcmMove("", ae, (char *)MYACRNEMA, stud, ser, "", "", "", sop, "", "", 0x2bad, "");
+ char szTemp[256], szRootSC[256];
+ MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile);
+ MyGetPrivateProfileString(szRootSC, "TempDir", "", szTemp, 64, ConfigFile);
+ if (szTemp[0]==0)
+ {
+ Filename[0]=0;
+ GetPhysicalDevice("MAG0", Filename);
+ strcat(Filename, "printer_files");
+ }
+ else
+ strcpy(Filename, szTemp);
+
+ i = strlen(Filename);
+ Filename[i] = PATHSEPCHAR;
+ Filename[i+1] = 0;
+ strcat(Filename, sop);
+ p=PDU.LoadDICOMDataObject(Filename);
+ unlink(Filename);
+ return p;
+ }
+ return NULL;
+ }
+
+// Delete image from database, where only filename is given
+BOOL
+DeleteImageFile(char *filename, BOOL KeepImages)
+ {
+ DICOMDataObject *pDDO;
+ VR *vrSOPInstanceUID, *vrPat;
+ DICOMDataObject DDO;
+ VR *pVR;
+
+ pDDO = LoadForGUI(filename);
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[DeleteImageFile] %s -FAILED: Error on Load\n", filename);
+ return ( FALSE );
+ }
+
+ if (!pDDO->GetVR(0x0010, 0x0020) ||
+ !pDDO->GetVR(0x0020, 0x000d) ||
+ !pDDO->GetVR(0x0020, 0x000e) ||
+ !pDDO->GetVR(0x0008, 0x0018))
+ {
+ OperatorConsole.printf("***[DeleteImageFile] %s -FAILED: file does not contain correct UIDs\n", filename);
+ delete pDDO;
+ return ( FALSE );
+ }
+
+ pVR = pDDO->GetVR(0x0008, 0x0018);
+ vrSOPInstanceUID = new VR(0x0008, 0x0018, pVR->Length, pVR->Data, (BOOL) FALSE );
+ DDO.Push(vrSOPInstanceUID);
+
+ pVR = pDDO->GetVR(0x0010, 0x0020);
+ vrPat = new VR(0x0010, 0x0020, pVR->Length, pVR->Data, (BOOL) FALSE );
+ DDO.Push(vrPat);
+
+ OperatorConsole.printf("Deleting database entry for image: %s\n", filename);
+ RemoveFromPACS(&DDO, KeepImages);
+
+ delete pDDO;
+
+ return ( TRUE );
+ }
+
+// Ask image UID
+BOOL
+GetImageFileUID(char *filename, char *UID)
+ {
+ DICOMDataObject* pDDO;
+ VR *vrSOPInstanceUID;
+
+ pDDO = LoadForGUI(filename);
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[GetImageFileUID] %s -FAILED: Error on Load\n", filename);
+ return ( FALSE );
+ }
+
+ if (!pDDO->GetVR(0x0010, 0x0020) ||
+ !pDDO->GetVR(0x0020, 0x000d) ||
+ !pDDO->GetVR(0x0020, 0x000e) ||
+ !pDDO->GetVR(0x0008, 0x0018))
+ {
+ OperatorConsole.printf("***[GetImageFileUID] %s -FAILED: file does not contain correct UIDs\n", filename);
+ return ( FALSE );
+ }
+
+ vrSOPInstanceUID = pDDO->GetVR(0x0008, 0x0018);
+ memset(UID, 0, 255);
+ memcpy(UID, vrSOPInstanceUID->Data, vrSOPInstanceUID->Length);
+
+ delete pDDO;
+
+ return ( TRUE );
+ }
+
+// Change UID of given DDO
+/* Commented out everywhere it was used, why build?
+static BOOL
+ChangeUIDinDDO(DICOMDataObject *pDDO, int group, int element, char *name)
+ {
+ char s[255], NewUID[255];
+ VR *vr;
+ int len;
+
+ vr = pDDO->GetVR(group, element);
+ if (!vr) return ( FALSE);
+
+ memset(s, 0, 255);
+ memcpy(s, vr->Data, vr->Length);
+
+ if (!ChangeUID(s, name, NewUID))
+ {
+ OperatorConsole.printf("***[ChangeUIDinDDO] FAILED to change %s\n", name);
+ return ( FALSE );
+ }
+
+ len = strlen(NewUID); if (len&1) len++;
+ vr->ReAlloc(len);
+ memcpy(vr->Data, NewUID, len);
+
+ return ( TRUE );
+ }
+*/
+// Change any VR of given DDO
+/* Not used anywhere, why build?
+static BOOL
+ChangeVRinDDO(DICOMDataObject *pDDO, int group, int element, char *text)
+ {
+ char s[255];
+ VR *vr;
+ int len;
+
+ vr = pDDO->GetVR(group, element);
+ if (!vr)
+ {
+ vr = new VR(group, element, 10, TRUE);
+ }
+
+ memset(s, 0, 255);
+ memcpy(s, vr->Data, vr->Length);
+
+ len = strlen(text); if (len&1) len++;
+ vr->ReAlloc(len);
+ memcpy(vr->Data, text, len);
+
+ pDDO->ReplaceVR(vr); // also works in sequences
+ delete vr;
+
+ return ( TRUE );
+ }
+*/
+
+
+// Modify all UIDs in a DICOM object, except those in the passed string as given; and replace given VR's
+// UID|UID|UID|g,e|UID|g,e|g,e=PASSUID|
+
+static BOOL
+NewUIDsInDICOMObject(DICOMObject *DO, const char *Exceptions, const char *Reason=NULL)
+ {
+ DICOMObject DO2;
+ VR *vr;
+ int TypeCode;//, i;
+ unsigned int Index;
+ char desc[64], name[20];
+ char *p;
+ char s[66], NewUID[255];
+ int len;
+ const char *cp, *Desc;
+
+ while((vr=DO->Pop()))
+ {
+ sprintf(name, "%04x,%04x=", vr->Group, vr->Element);
+ cp = strstr(Exceptions, name);
+ if (cp)
+ {
+ strncpy(NewUID, cp+10, 65);
+ p = strchr(NewUID, '|');
+ if (p) *p=0;
+ OperatorConsole.printf("[NewUIDsInDICOMObject] setting %04x,%04x\n", vr->Group, vr->Element);
+ len = strlen(NewUID); if (len&1) len++;
+ vr->ReAlloc(len);
+ memcpy(vr->Data, NewUID, len);
+ }
+ else
+ {
+ TypeCode = VRType.RunTimeClass(vr->Group, vr->Element, desc);
+ if (Reason) Desc = Reason; else Desc = desc;
+
+ if (TypeCode=='UI' && strstr(desc, "Class")==NULL && strcmp(desc, "TransferSyntaxUID"))
+ {
+ memcpy(s, vr->Data, vr->Length);
+ s[vr->Length]=0;
+ if (strlen(s)==0) GenUID(s);
+ strcat(s, ";");
+ sprintf(name, "%04x,%04x|", vr->Group, vr->Element);
+
+ if (!strstr(Exceptions, s))
+ if (!strstr(Exceptions, name))
+ {
+ s[strlen(s)-1]=0;
+ if (!ChangeUID(s, Desc, NewUID))
+ OperatorConsole.printf("***[NewUIDsInDICOMObject] FAILED to change %04x,%04x (%s)\n", vr->Group, vr->Element, desc);
+ else
+ {
+ SystemDebug.printf("[NewUIDsInDICOMObject] changing %04x,%04x (%s)\n", vr->Group, vr->Element, desc);
+ len = strlen(NewUID); if (len&1) len++;
+ vr->ReAlloc(len);
+ memcpy(vr->Data, NewUID, len);
+ }
+ }
+ }
+ }
+
+ if ( vr->SQObjectArray )
+ {
+ Array < DICOMDataObject * > *ADDO =
+ (Array<DICOMDataObject*>*) vr->SQObjectArray;
+
+ Index = 0;
+ while ( Index < ADDO->GetSize() )
+ {
+ NewUIDsInDICOMObject(ADDO->Get(Index), Exceptions, Reason);
+ ++Index;
+ }
+ }
+ DO2.Push(vr);
+ }
+ DO->Reset();
+ while((vr=DO2.Pop()))
+ {
+ DO->Push(vr);
+ }
+ return ( TRUE );
+ }
+
+
+// restore all UIDs in a DICOM object, except those in the passed string as given; and replace given VR's
+// UID|UID|UID|g,e|UID|g,e|g,e=PASSUID|
+
+// From dbsql.cpp
+
+BOOL ChangeUIDBack(char *NewUID, char *OldUID);
+BOOL ChangeUIDTo(char *OldUID, char *Type, char *NewUID);
+void KodakFixer(DICOMDataObject *DDOPtr, BOOL tokodak);
+
+static BOOL
+OldUIDsInDICOMObject(DICOMObject *DO, const char *Exceptions)
+ {
+ DICOMObject DO2;
+ VR *vr;
+ int TypeCode;//, i;
+ unsigned int Index;
+ char desc[64], name[20];
+ char *p;
+ char s[66], NewUID[255];
+ int len;
+ const char *cp, *Desc;
+
+ while((vr=DO->Pop()))
+ {
+ sprintf(name, "%04x,%04x=", vr->Group, vr->Element);
+ cp = strstr(Exceptions, name);
+ if (cp)
+ {
+ strncpy(NewUID, cp+10, 65);
+ p = strchr(NewUID, '|');
+ if (p) *p=0;
+ OperatorConsole.printf("[OldUIDsInDICOMObject] setting %04x,%04x\n", vr->Group, vr->Element);
+ len = strlen(NewUID); if (len&1) len++;
+ vr->ReAlloc(len);
+ memcpy(vr->Data, NewUID, len);
+ }
+ else
+ {
+ TypeCode = VRType.RunTimeClass(vr->Group, vr->Element, desc);
+
+ if (TypeCode=='UI' && strstr(desc, "Class")==NULL && strcmp(desc, "TransferSyntaxUID"))
+ {
+ memcpy(s, vr->Data, vr->Length);
+ s[vr->Length]=0;
+ if (strlen(s)==0) GenUID(s);
+ strcat(s, ";");
+ sprintf(name, "%04x,%04x|", vr->Group, vr->Element);
+
+ if (!strstr(Exceptions, s))
+ if (!strstr(Exceptions, name))
+ {
+ s[strlen(s)-1]=0;
+ if (!ChangeUIDBack(s, NewUID))
+ OperatorConsole.printf("***[OldUIDsInDICOMObject] FAILED to change %04x,%04x (%s)\n", vr->Group, vr->Element, desc);
+ else
+ {
+ SystemDebug.printf("[OldUIDsInDICOMObject] restoring %04x,%04x (%s)\n", vr->Group, vr->Element, desc);
+ len = strlen(NewUID); if (len&1) len++;
+ vr->ReAlloc(len);
+ memcpy(vr->Data, NewUID, len);
+ }
+ }
+ }
+ }
+
+ if ( vr->SQObjectArray )
+ {
+ Array < DICOMDataObject * > *ADDO =
+ (Array<DICOMDataObject*>*) vr->SQObjectArray;
+
+ Index = 0;
+ while ( Index < ADDO->GetSize() )
+ {
+ OldUIDsInDICOMObject(ADDO->Get(Index), Exceptions);
+ ++Index;
+ }
+ }
+ DO2.Push(vr);
+ }
+ DO->Reset();
+ while((vr=DO2.Pop()))
+ {
+ DO->Push(vr);
+ }
+ return ( TRUE );
+ }
+
+// Change patient ID of pDDO in memory
+static BOOL
+ModifyPATIDofDDO(DICOMDataObject *pDDO, char *NewPATID, char *Reason=NULL)
+ {
+ int len;
+ PDU_Service PDU;
+ DICOMDataObject DDO;
+ Database DB;
+ char s[255];
+ BOOL ok;
+ VR *vr;
+
+ PDU.AttachRTC(&VRType);
+
+
+ if (NewPATID==NULL || *NewPATID==0)
+ {
+ OperatorConsole.printf("***[ModifyPATIDofDDO] Empty patient ID not allowed\n");
+ return ( FALSE );
+ }
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ OperatorConsole.printf("***[ModifyPATIDofDDO] Error Connecting to SQL\n");
+ return ( FALSE );
+ }
+
+ // Just to make sure the table exists
+ // DB.CreateTable ( "UIDMODS", "MODTime int, OldUID varchar(64), MODType varchar(32), NewUID varchar(64)" );
+
+ // check image in memory
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[ModifyPATIDofDDO] -FAILED: No image passed\n");
+ return ( FALSE );
+ }
+
+ if (!pDDO->GetVR(0x0010, 0x0020) ||
+ !pDDO->GetVR(0x0020, 0x000d) ||
+ !pDDO->GetVR(0x0020, 0x000e) ||
+ !pDDO->GetVR(0x0008, 0x0018))
+ {
+ OperatorConsole.printf("***[ModifyPATIDofDDO] -FAILED: image does not contain correct UIDs\n");
+ return ( FALSE );
+ }
+
+/* ok = ChangeUIDinDDO(pDDO, 0x0020, 0x000d, "StudyUID");
+ ok &= ChangeUIDinDDO(pDDO, 0x0020, 0x000e, "SeriesUID");
+ ok &= ChangeUIDinDDO(pDDO, 0x0008, 0x0018, "SOPInstanceUID");
+*/
+ // let off of the transfer syntax
+ ok = NewUIDsInDICOMObject(pDDO, "0002,0010|", Reason);
+
+ if (!ok)
+ {
+ OperatorConsole.printf("***[ModifyPATIDofDDO] -FAILED: could not change all UIDs\n");
+ return ( FALSE );
+ }
+
+ // change patient ID
+ vr = pDDO->GetVR(0x0010, 0x0020);
+ memset(s, 0, 255);
+ memcpy(s, vr->Data, vr->Length);
+
+ len = strlen(NewPATID); if (len&1) len++;
+ vr->ReAlloc(len);
+ memcpy(vr->Data, NewPATID, len);
+
+ OperatorConsole.printf("Modified patient ID to: %s\n", NewPATID);
+ return ( TRUE );
+ }
+
+// Merge (SeriesUID or StudyUID {given in type}) of pDDO in memory
+BOOL
+MergeUIDofDDO(DICOMDataObject *pDDO, const char *type, const char *Reason)
+ {
+// int len;
+ PDU_Service PDU;
+ DICOMDataObject DDO;
+ Database DB;
+// char s[255];
+ BOOL ok;
+// VR *vr;
+
+ PDU.AttachRTC(&VRType);
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ OperatorConsole.printf("***[MergeUIDofDDO] Error Connecting to SQL\n");
+ return ( FALSE );
+ }
+
+ // check image in memory
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[MergeUIDofDDO] -FAILED: No image passed\n");
+ return ( FALSE );
+ }
+
+ if (!pDDO->GetVR(0x0010, 0x0020) ||
+ !pDDO->GetVR(0x0020, 0x000d) ||
+ !pDDO->GetVR(0x0020, 0x000e) ||
+ !pDDO->GetVR(0x0008, 0x0018))
+ {
+ OperatorConsole.printf("***[MergeUIDofDDO -FAILED: image does not contain correct UIDs\n");
+ return ( FALSE );
+ }
+
+// ok = TRUE;
+// if (strcmp(type, "StudyUID")==0)
+// ok &= ChangeUIDinDDO(pDDO, 0x0020, 0x000d, "StudyUID");
+// ok = ChangeUIDinDDO(pDDO, 0x0020, 0x000e, "SeriesUID");
+// ok &= ChangeUIDinDDO(pDDO, 0x0008, 0x0018, "SOPInstanceUID");
+
+ if (strcmp(type, "SeriesUID")==0)
+ // let off of the transfer syntax and study UID
+ ok = NewUIDsInDICOMObject(pDDO, "0002,0010|0020,000d|", Reason);
+ else
+ // let off of the transfer syntax
+ ok = NewUIDsInDICOMObject(pDDO, "0002,0010|", Reason);
+
+ if (!ok)
+ {
+ OperatorConsole.printf("***[MergeUIDofDDO] -FAILED: could not change all UIDs\n");
+ return ( FALSE );
+ }
+
+ return ( TRUE );
+ }
+
+// forward references
+int
+SaveToDisk(Database &DB, DICOMDataObject *DDOPtr, char *Filename, BOOL NoKill, ExtendedPDU_Service *PDU, int Syntax=0, BOOL nopreget=FALSE);
+
+void TestCompress(char *filename, const char *modes, ExtendedPDU_Service *PDU);
+void TestForward(char *filename, const char *mode, char *server, ExtendedPDU_Service *PDU);
+void TestSyntax(char *filename, int syntax, ExtendedPDU_Service *PDU);
+void TestThreadedSave(char *filename);
+void ProcessHL7Data(char *data);
+static void NewTempFile(char *name, const char *ext);
+BOOL AddImageFile(char *filename, char *NewPatid, ExtendedPDU_Service *PDU);
+
+static BOOL dgate_IsDirectory(char *TempPath)
+{
+ struct stat results;
+ if (stat(TempPath, &results) == 0)
+ {
+#ifdef WIN32
+ return (results.st_mode & S_IFDIR)!=0;
+#else
+ return S_ISDIR(results.st_mode);
+#endif
+ }
+ else
+ return 0;
+}
+
+#ifdef WIN32
+BOOL LoadAndDeleteDir(char *dir, char *NewPatid, ExtendedPDU_Service *PDU)
+ {
+ HANDLE fdHandle;
+ WIN32_FIND_DATA FileData;
+ char TempPath[512];
+
+ strcpy(TempPath, dir);
+ strcat(TempPath, "*.*");
+
+ // Traverse first level of subdirectories
+
+ fdHandle = FindFirstFile(TempPath, &FileData);
+ if(fdHandle == INVALID_HANDLE_VALUE)
+ return ( FALSE );
+
+ while ( TRUE )
+ {
+ if (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
+ {
+ if
+ (
+ strcmp(FileData.cFileName, ".") != 0 &&
+ strcmp(FileData.cFileName, "..") != 0
+ )
+ {
+ strcpy(TempPath, dir);
+ strcat(TempPath, FileData.cFileName);
+ strcat(TempPath, "\\");
+ LoadAndDeleteDir(TempPath, NewPatid, PDU);
+ rmdir(TempPath);
+ }
+ }
+ else
+ {
+ strcpy(TempPath, dir);
+ strcat(TempPath, FileData.cFileName);
+
+ FILE *f = fopen(TempPath, "at");
+ if (f)
+ {
+ fclose(f);
+ AddImageFile (TempPath, NewPatid, PDU);
+ unlink(TempPath);
+ }
+ //else
+ // OperatorConsole.printf("waiting for file %s to close\n", TempPath);
+ }
+
+ if(!FindNextFile(fdHandle, &FileData))
+ break;
+ }
+
+ FindClose(fdHandle);
+
+ return TRUE;
+ }
+
+#else
+
+BOOL LoadAndDeleteDir(char *dir, char *NewPatid, ExtendedPDU_Service *PDU)
+ {
+ DIR *dird;
+ dirent *diren;
+
+ char TempPath[PATH_MAX];
+ char *n;
+
+ strcpy(TempPath, dir);
+ TempPath[strlen(TempPath)-1]=0;
+
+ // Traverse first level of subdirectories
+
+ dird = opendir(TempPath);
+ if(dird == NULL)
+ return ( FALSE );
+
+ while ( TRUE )
+ {
+ diren = readdir(dird);
+ if (diren)
+ {
+ n = diren->d_name;
+ strcpy(TempPath, dir);
+ strcat(TempPath, n);
+
+ if (dgate_IsDirectory(TempPath))
+ {
+ if
+ (
+ strcmp (n, "." ) != 0 &&
+ strcmp (n, ".." ) != 0
+#ifdef DARWIN //A Macintosh OS X file.
+ && stricmp(n, ".DS_Store" ) != 0
+#endif //DARWIN
+ )
+ {
+ long length=strlen(TempPath);
+ TempPath[length] = PATHSEPCHAR;
+ TempPath[length+1] = '\0';
+ LoadAndDeleteDir(TempPath, NewPatid, PDU);
+ rmdir(TempPath);
+ }
+ }
+ else
+ {
+ AddImageFile (TempPath, NewPatid, PDU);
+ unlink(TempPath);
+ }
+ }
+ else
+ break;
+ }
+
+ closedir(dird);
+
+ return TRUE;
+ }
+#endif
+
+BOOL BackgroundExec(char *ProcessBinary, char *Args);
+extern "C" void lua_setvar(ExtendedPDU_Service *pdu, char *name, char *value);
+
+// Add image file to server (also copies file!); optional changes patient ID before entering file
+BOOL
+AddImageFile(char *filename, char *NewPatid, ExtendedPDU_Service *PDU)
+ {
+ DICOMDataObject* pDDO;
+ int i;//, len;
+// VR *vrSOPInstanceUID;
+ DICOMDataObject DDO;
+ Database DB;
+ char rFilename[1024];
+ BOOL rc;
+ char szRootSC[64], szTemp[64];
+
+
+ MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile);
+ MyGetPrivateProfileString(szRootSC, "ImportExportDragAndDrop", "0", szTemp, 64, ConfigFile);
+
+ if (NewPatid)
+ {
+ if (NewPatid[0]=='$' && NewPatid[1]=='c')
+ {
+#ifdef HAVE_J2K
+ TestCompress(filename, "unasn1n2n3n4j1j2j3j4j5j6jkjlk1k2k4k8", PDU);
+#else
+ TestCompress(filename, "unasn1n2n3n4j1j2j3j4j5j6k1k2k4k8", PDU);
+#endif
+ return TRUE;
+ }
+ if (NewPatid[0]=='$' && NewPatid[1]=='t')
+ {
+ TestForward(filename, "un", NewPatid+2, PDU);
+ TestForward(filename, "as", NewPatid+2, PDU);
+ TestForward(filename, "n1", NewPatid+2, PDU);
+ TestForward(filename, "n2", NewPatid+2, PDU);
+ TestForward(filename, "n3", NewPatid+2, PDU);
+ TestForward(filename, "n4", NewPatid+2, PDU);
+ TestForward(filename, "j1", NewPatid+2, PDU);
+ TestForward(filename, "j2", NewPatid+2, PDU);
+ TestForward(filename, "j3", NewPatid+2, PDU);
+ TestForward(filename, "j4", NewPatid+2, PDU);
+ TestForward(filename, "j5", NewPatid+2, PDU);
+ TestForward(filename, "j6", NewPatid+2, PDU);
+#ifdef HAVE_J2K
+ TestForward(filename, "jk", NewPatid+2, PDU);
+ TestForward(filename, "jl", NewPatid+2, PDU);
+#endif
+ TestForward(filename, "k1", NewPatid+2, PDU);
+ TestForward(filename, "k2", NewPatid+2, PDU);
+ TestForward(filename, "k4", NewPatid+2, PDU);
+ TestForward(filename, "k8", NewPatid+2, PDU);
+ return TRUE;
+ }
+ if (NewPatid[0]=='$' && NewPatid[1]=='s')
+ {
+ TestSyntax(filename, 1, PDU);
+ TestSyntax(filename, 2, PDU);
+ TestSyntax(filename, 3, PDU);
+ TestSyntax(filename, 4, PDU);
+ TestSyntax(filename, 5, PDU);
+ TestSyntax(filename, 6, PDU);
+ TestSyntax(filename, 7, PDU);
+ TestSyntax(filename, 8, PDU);
+ TestSyntax(filename, 9, PDU);
+ TestSyntax(filename, 10, PDU);
+ return TRUE;
+ }
+ if (NewPatid[0]=='$' && NewPatid[1]=='r')
+ {
+ for (i=0; i<atoi(NewPatid+2); i++)
+ TestSyntax(filename, 0, PDU);
+ return TRUE;
+ }
+ if (NewPatid[0]=='$' && NewPatid[1]=='t')
+ {
+ for (i=0; i<atoi(NewPatid+2); i++)
+ TestThreadedSave(filename);
+ return TRUE;
+ }
+ }
+
+ // rudimentary hl7 support
+ if (strlen(filename)>4 && stricmp(filename+strlen(filename)-4, ".hl7")==0)
+ {
+ unsigned int len = DFileSize(filename);
+ if (len)
+ {
+ char *p=(char*) malloc(len+1);
+ FILE *f;
+ f = fopen(filename, "rb");
+ fread(p, 1, len, f);
+ p[len]=0;
+ fclose(f);
+ ProcessHL7Data(p);
+ free(p);
+ OperatorConsole.printf("[AddImageFile] loaded HL7 file: %s\n", filename);
+ return TRUE;
+ }
+ else
+ {
+ OperatorConsole.printf("*** [AddImageFile] could not open HL7 file: %s\n", filename);
+ return FALSE;
+ }
+ }
+
+ char *p = strrchr(filename, '.');
+
+ // compressed file support using 7za.exe
+ if (p && strstr(".gz.GZ.zip.ZIP.tar.TAR.7z.7Z", p))
+ {
+ char line[1000], dir[512];
+
+ NewTempFile(dir, "");
+ mkdir(dir);
+
+#ifdef WIN32
+ sprintf(line, "-y -o\"%s\" x \"%s\"", dir, filename);
+ BackgroundExec("7za.exe", line);
+ strcat(dir, "\\");
+#else
+ sprintf(line, "7za -y -o\"%s\" x \"%s\"", dir, filename);
+ system(line);
+ strcat(dir, "/");
+#endif
+ LoadAndDeleteDir(dir, NewPatid, PDU);
+ rmdir(dir);
+
+ return TRUE;
+ }
+
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ OperatorConsole.printf("***Error Connecting to SQL\n");
+ return ( FALSE );
+ }
+
+ pDDO = LoadForGUI(filename);
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[AddImageFile] %s -FAILED: Error on Load\n", filename);
+ return ( FALSE );
+ }
+
+ lua_setvar(PDU, "Filename", filename);
+
+ if (NewPatid)
+ {
+ if (!ModifyPATIDofDDO(pDDO, NewPatid))
+ {
+ OperatorConsole.printf("***[AddImageFile] Error changing patient ID for file: %s\n", filename);
+ delete pDDO;
+ return FALSE;
+ }
+ }
+
+ if (!pDDO->GetVR(0x0010, 0x0020) ||
+ !pDDO->GetVR(0x0020, 0x000d) ||
+ !pDDO->GetVR(0x0020, 0x000e) ||
+ !pDDO->GetVR(0x0008, 0x0018))
+ {
+ OperatorConsole.printf("***[AddImageFile] %s -FAILED: file does not contain correct UIDs\n", filename);
+ delete pDDO;
+ return ( FALSE );
+ }
+
+ // recompress dropped files
+ rc = recompress(&pDDO, DroppedFileCompression, "", DroppedFileCompression[0]=='n' || DroppedFileCompression[0]=='N', PDU);
+ rc = TRUE; // failed compression leaves original object
+
+ // if ((rc == FALSE) || (!SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"dropped", (unsigned char *)"dropped", 0, !atoi(szTemp))))
+ if ((rc == FALSE) || (!SaveToDisk(DB, pDDO, rFilename, TRUE, PDU, 0, !atoi(szTemp))))
+ {
+ OperatorConsole.printf("***[AddImageFile] Error entering object into server: %s\n", filename);
+// if (pDDO)
+// delete pDDO;
+ return FALSE;
+ }
+
+ OperatorConsole.printf("Added file: %s\n", rFilename);
+ return ( TRUE );
+ }
+
+
+// Make a new UID for external use (prefix configurable via UIDPrefix in dicom.ini)
+extern int UIDPostfix;
+static char UIDPrefix[65] = "1.2.826.0.1.3680043.2.135.1066.6"; // default value
+static BOOL dgLoadRoot = TRUE;
+BOOL
+GenUID(char *oString)
+ {
+ if (dgLoadRoot)
+ {
+ char szRootSC[64];
+ if (MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile))
+ {
+ if (MyGetPrivateProfileString(szRootSC, "UIDPrefix", "1.2.826.0.1.3680043.2.135.1066", UIDPrefix, 64, ConfigFile))
+ strcat(UIDPrefix, ".6");
+ }
+ dgLoadRoot = FALSE;
+ }
+
+#ifdef WIN32
+ sprintf(oString, "%s.%u.%d.%u", UIDPrefix, (unsigned int)time(NULL), GetTickCount()%1000, (UIDPostfix++)%100);
+#else
+ sprintf(oString, "%s.%u.%u", UIDPrefix, (unsigned int)time(NULL), (UIDPostfix++)%10000);
+#endif
+ return ( TRUE );
+ }
+
+int CallImportConverterN(DICOMDataObject *DDO, int N, char *pszModality, char *pszStationName, char *pszSop, char *patid, ExtendedPDU_Service *PDU, char *Storage, char *Script);
+
+// Change patient ID of image file (must already be loaded in the database); or similar run script: if script is number use defined scripts
+BOOL
+ModifyPATIDofImageFile(char *filename, char *NewPATID, BOOL DelFile, char *script, ExtendedPDU_Service *PDU)
+ {
+ DICOMDataObject* pDDO;
+ int sIndex, len;
+ unsigned int Index;
+ DICOMDataObject DDO;
+ Database DB;
+ char rFilename[1024], s[255];
+ char MirrorFile[1024], Device[255], Physical[1024];
+// BOOL ok;
+// VR *vr;
+ int devlen, mirrordevlen, rc;
+
+#ifdef __GNUC__ //Warnings
+ devlen = 0;
+ mirrordevlen = 0;
+#endif
+
+ if (NewPATID!=NULL && *NewPATID==0)
+ {
+ OperatorConsole.printf("***[ModifyPATIDofImageFile] Empty patient ID not allowed\n");
+ return ( FALSE );
+ }
+
+ // try to locate the mirror file because that one has to change too
+ MirrorFile[0] = 0;
+ Index = 0;
+ while ( Index < MAGDevices )
+ {
+ sprintf(Device, "MAG%d", Index);
+ GetPhysicalDevice(Device, Physical);
+ devlen = strlen(Physical);
+ if (memicmp(Physical, filename, strlen(Physical))==0)
+ {
+ sprintf(Device, "MIRROR%d", Index);
+ if (GetPhysicalDevice(Device, MirrorFile))
+ {
+ mirrordevlen = strlen(MirrorFile);
+ strcat(MirrorFile, filename + strlen(Physical));
+ }
+ break;
+ }
+ ++Index;
+
+ if (Index == MAGDevices)
+ {
+ OperatorConsole.printf("***File to modify does not exist or is not on a MAG device\n");
+ return ( FALSE );
+ }
+ }
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ OperatorConsole.printf("***Error Connecting to SQL\n");
+ return ( FALSE );
+ }
+
+ // Just to make sure the table exists
+ // DB.CreateTable ( "UIDMODS", "MODTime int, OldUID varchar(64), MODType varchar(32), NewUID varchar(64)" );
+
+ // load image into memory
+ pDDO = LoadForGUI(filename);
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[ModifyPATIDofImageFile] %s -FAILED: Error on Load\n", filename);
+ return ( FALSE );
+ }
+
+ // no script: change patient ID of object file in memory - changes UIDs
+ if (NewPATID && script==NULL)
+ if (!ModifyPATIDofDDO(pDDO, NewPATID))
+ {
+ delete pDDO;
+ return FALSE;
+ }
+
+ // assume script changes UIDs; leave modifying patientID to script
+ if (script)
+ {
+ if (atoi(script)>1000)
+ rc = CallImportConverterN(pDDO, atoi(script), NULL, NULL, NULL, NULL, PDU, NULL, NULL);
+ else
+ rc = CallImportConverterN(pDDO, -1, NULL, NULL, NULL, NULL, PDU, NULL, script);
+
+ if(rc==2 || rc==6)
+ {
+ OperatorConsole.printf("[ModifyPATIDofImageFile] %s rejected by script\n", filename);
+ return ( FALSE );
+ }
+
+ /*if (NewPATID)
+ {
+ // change patient ID
+ VR *vr = pDDO->GetVR(0x0010, 0x0020);
+ memset(s, 0, 255);
+ memcpy(s, vr->Data, vr->Length);
+
+ len = strlen(NewPATID); if (len&1) len++;
+ vr->ReAlloc(len);
+ memcpy(vr->Data, NewPATID, len);
+ }
+ */
+ }
+
+ // remove image file from database
+ if (DelFile)
+ if (!DeleteImageFile(filename, TRUE))
+ {
+ OperatorConsole.printf("***Could not remove image file from database\n");
+ return ( FALSE );
+ }
+
+ // add the image in memory to the server, also makes a copy of the image
+ // if (!SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"modpatid", (unsigned char *)"modpatid", 0, 1))
+ if (!SaveToDisk(DB, pDDO, rFilename, TRUE, PDU, 0, 1))
+ {
+ //delete pDDO;
+ OperatorConsole.printf("***Error entering object into server: %s\n", filename);
+ return ( FALSE );
+ }
+ OperatorConsole.printf("Modified image: %s\n", rFilename);
+
+ if (!DelFile)
+ {
+ return ( TRUE );
+ }
+
+ // delete the original image since it would show up with original PATID after regen
+ if (stricmp(filename, rFilename))
+ {
+ unlink(filename);
+ OperatorConsole.printf("Deleting file: %s\n", filename);
+ }
+
+ // delete the mirror image since it would show up with original PATID after regen
+ if (strlen(MirrorFile))
+ if (stricmp(MirrorFile, rFilename))
+ {
+ unlink(MirrorFile);
+ OperatorConsole.printf("Deleting mirror file: %s\n", MirrorFile);
+ }
+
+
+ // remove the source directory and any required subdirectories (just fails quietly if directory not yet empty)
+ strcpy(s, filename);
+ for (sIndex = strlen(s)-1; sIndex>=devlen; sIndex--)
+ if (s[sIndex]==PATHSEPCHAR)
+ {
+ s[sIndex]='\0';
+ rmdir(s);
+ }
+
+ // remove the mirror source directory and any required subdirectories (just fails quietly if directory not yet empty)
+ if (strlen(MirrorFile))
+ {
+ strcpy(s, MirrorFile);
+ for (sIndex = strlen(s)-1; sIndex>=mirrordevlen; sIndex--)
+ if (s[sIndex]==PATHSEPCHAR)
+ {
+ s[sIndex]='\0';
+ rmdir(s);
+ }
+ }
+
+ return ( TRUE );
+ }
+
+// Change image file through a script (warning: do NOT change patient ID or uids without newuids command)
+// works on images in the database
+BOOL
+ModifyImageFile(char *filename, char *script, ExtendedPDU_Service *PDU)
+ {
+// DICOMDataObject* pDDO;
+ Database DB;
+// char rFilename[1024];
+
+ if (script==NULL) return FALSE;
+ if (script[0]==0) return FALSE;
+
+ return ModifyPATIDofImageFile(filename, NULL, TRUE, script, PDU);
+ }
+
+BOOL ImageFileLister(const char *server, char *pat, char *study, char *series, char *sop, char *fmt, FILE *f);
+
+// modify all data of selected patient, study or series
+int ModifyData(char *pat, char *study, char *series, char *script, ExtendedPDU_Service *PDU)
+ {
+ char tempfile[512], temp[512];
+ FILE *f;
+
+ NewTempFile(tempfile, ".txt");
+
+ f = fopen(tempfile, "wt");
+ char formt[]="%s\n";
+ ImageFileLister("local", pat, study, series, NULL, formt, f);
+ fclose(f);
+
+ f = fopen(tempfile, "rt");
+ while(fgets(temp, sizeof(temp), f) != NULL)
+ { if (temp[strlen(temp)-1]=='\n') temp[strlen(temp)-1]=0;
+ ModifyImageFile(temp, script, PDU);
+ }
+ fclose(f);
+ unlink(tempfile);
+
+ return TRUE;
+ }
+
+// The attach functions load a (copy) the input (plan/any) data into the dicom server
+BOOL AttachFile(char *filename, char *script, char *rFilename, ExtendedPDU_Service *PDU)
+ {
+ DICOMDataObject* pDDO;
+ Database DB;
+ int rc;
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ OperatorConsole.printf("***Error Connecting to SQL\n");
+ return ( FALSE );
+ }
+
+ // load image into memory
+ pDDO = LoadForGUI(filename);
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[AttachFile] %s -FAILED: Error on Load (input) \n", filename);
+ return ( FALSE );
+ }
+
+ rc = CallImportConverterN(pDDO, -1, NULL, NULL, NULL, NULL, PDU, NULL, script);
+
+ if(rc==2 || rc==6)
+ {
+ delete pDDO;
+ OperatorConsole.printf("[AttachFile] %s rejected by script\n", filename);
+ return ( FALSE );
+ }
+
+ //if (!SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"AttachFile", (unsigned char *)"AttachFile", 0, 1))
+ if (!SaveToDisk(DB, pDDO, rFilename, TRUE, PDU, 0, 1))
+ {
+ //delete pDDO;
+ OperatorConsole.printf("***[AttachFile] Error entering object into server: %s\n", filename);
+ return ( FALSE );
+ }
+
+ return ( TRUE );
+ }
+
+BOOL
+AttachRTPLANToRTSTRUCT(char *planfilename, char *structfilename, ExtendedPDU_Service *PDU)
+ {
+ DICOMDataObject* pDDO2;
+ char rFilename[1024];
+ char Sop[66], Study[66], Pat[66], Name[66], Sex[66], Birth[66], script[1024];
+
+ // load image into memory
+ pDDO2 = LoadForGUI(structfilename);
+ if(!pDDO2)
+ {
+ OperatorConsole.printf("***[AttachRTPLANToRTSTRUCT] %s -FAILED: Error on Load (struct)\n", structfilename);
+ return ( FALSE );
+ }
+
+ SearchDICOMObject(pDDO2, "0010,0010", Name);
+ SearchDICOMObject(pDDO2, "0010,0020", Pat);
+ SearchDICOMObject(pDDO2, "0010,0030", Birth);
+ SearchDICOMObject(pDDO2, "0010,0040", Sex);
+ SearchDICOMObject(pDDO2, "0020,000d", Study);
+ SearchDICOMObject(pDDO2, "0008,0018", Sop);
+
+ sprintf(script, "newuids except 0020,000d; set 0010,0010 to \"%s\"; set 0010,0020 to \"%s\"; set 0010,0030 to \"%s\"; set 0010,0040 to \"%s\"; "
+ "set 0020,000d to \"%s\"; set 0008,1110/0008,1155 to \"%s\"; "
+ "set 300c,0060/0008,1155 to \"%s\"",
+ Name, Pat, Birth, Sex, Study, Study, Sop);
+
+ AttachFile(planfilename, script, rFilename, PDU);
+ OperatorConsole.printf("Attached rtplan to rtstruct: %s\n", rFilename);
+ delete pDDO2;
+
+ return ( TRUE );
+ }
+
+BOOL
+AttachAnyToPatient(char *anyfilename, char *samplefilename, ExtendedPDU_Service *PDU)
+ {
+ DICOMDataObject* pDDO2;
+ char rFilename[1024], Pat[66], Name[66], Birth[66], Sex[66], script[1024];//, Study[66], Sop[66];
+
+ // load image into memory
+ pDDO2 = LoadForGUI(samplefilename);
+ if(!pDDO2)
+ {
+ OperatorConsole.printf("***[AttachAnyToPatient] %s -FAILED: Error on Load (sample)\n", samplefilename);
+ return ( FALSE );
+ }
+
+ SearchDICOMObject(pDDO2, "0010,0010", Name);
+ SearchDICOMObject(pDDO2, "0010,0020", Pat);
+ SearchDICOMObject(pDDO2, "0010,0030", Birth);
+ SearchDICOMObject(pDDO2, "0010,0040", Sex);
+
+ sprintf(script, "newuids; set 0010,0010 to \"%s\"; set 0010,0020 to \"%s\"; set 0010,0030 to \"%s\"; set 0010,0040 to \"%s\"",
+ Name, Pat, Birth, Sex);
+
+ AttachFile(anyfilename, script, rFilename, PDU);
+ OperatorConsole.printf("Attached image to patient: %s\n", rFilename);
+ delete pDDO2;
+
+ return ( TRUE );
+ }
+
+BOOL
+AttachAnyToStudy(char *anyfilename, char *samplefilename, ExtendedPDU_Service *PDU)
+ {
+ DICOMDataObject* pDDO2;
+ char rFilename[1024], Study[66], Pat[66], Name[66], Birth[66], Sex[66], script[1024];//, Sop[66];
+
+ // load image into memory
+ pDDO2 = LoadForGUI(samplefilename);
+ if(!pDDO2)
+ {
+ OperatorConsole.printf("***[AttachAnyToStudy] %s -FAILED: Error on Load (sample)\n", samplefilename);
+ return ( FALSE );
+ }
+
+ SearchDICOMObject(pDDO2, "0010,0010", Name);
+ SearchDICOMObject(pDDO2, "0010,0020", Pat);
+ SearchDICOMObject(pDDO2, "0010,0030", Birth);
+ SearchDICOMObject(pDDO2, "0010,0040", Sex);
+ SearchDICOMObject(pDDO2, "0020,000d", Study);
+
+ sprintf(script, "newuids except 0020,000d; set 0010,0010 to \"%s\"; set 0010,0020 to \"%s\"; set 0010,0030 to \"%s\"; set 0010,0040 to \"%s\"; "
+ "set 0020,000d to \"%s\"",
+ Name, Pat, Birth, Sex, Study);
+
+ AttachFile(anyfilename, script, rFilename, PDU);
+ OperatorConsole.printf("Attached image to study: %s\n", rFilename);
+ delete pDDO2;
+
+ return ( TRUE );
+ }
+
+BOOL
+AttachAnyToSeries(char *anyfilename, char *samplefilename, ExtendedPDU_Service *PDU)
+ {
+ DICOMDataObject* pDDO2;
+ char rFilename[1024], Study[66], Series[66], Pat[66], Name[66], Birth[66], Sex[66], script[1024];//, Sop[66];
+
+ // load image into memory
+ pDDO2 = LoadForGUI(samplefilename);
+ if(!pDDO2)
+ {
+ OperatorConsole.printf("***[AttachAnyToSeries] %s -FAILED: Error on Load (sample)\n", samplefilename);
+ return ( FALSE );
+ }
+
+ SearchDICOMObject(pDDO2, "0010,0010", Name);
+ SearchDICOMObject(pDDO2, "0010,0020", Pat);
+ SearchDICOMObject(pDDO2, "0010,0030", Birth);
+ SearchDICOMObject(pDDO2, "0010,0040", Sex);
+ SearchDICOMObject(pDDO2, "0020,000d", Study);
+ SearchDICOMObject(pDDO2, "0020,000e", Series);
+
+ sprintf(script, "newuids except 0020,000d|0020,000e; set 0010,0010 to \"%s\"; set 0010,0020 to \"%s\"; set 0010,0030 to \"%s\"; set 0010,0040 to \"%s\"; "
+ "set 0020,000d to \"%s\"; set 0020,000e to \"%s\"",
+ Name, Pat, Birth, Sex, Study, Series);
+
+ AttachFile(anyfilename, script, rFilename, PDU);
+ OperatorConsole.printf("Attached image to series: %s\n", rFilename);
+ delete pDDO2;
+
+ return ( TRUE );
+ }
+
+// Merge SeriesUID or StudyUID (passed in type) of image file
+static BOOL
+MergeUIDofImageFile(char *filename, BOOL DelFile, const char *type, char *script, char *Reason, ExtendedPDU_Service *PDU)
+ {
+ DICOMDataObject* pDDO;
+ int sIndex;// len;
+ unsigned int Index;
+ DICOMDataObject DDO;
+ Database DB;
+ char rFilename[1024], s[255];
+ char MirrorFile[1024], Device[255], Physical[1024];
+// BOOL ok;
+// VR *vr;
+ int devlen, mirrordevlen, rc;
+
+#ifdef __GNUC__ //Warnings
+ devlen = 0;
+ mirrordevlen = 0;
+#endif
+
+ // try to locate the mirror file because that one has to change too
+ MirrorFile[0] = 0;
+ Index = 0;
+ while ( Index < MAGDevices )
+ {
+ sprintf(Device, "MAG%d", Index);
+ GetPhysicalDevice(Device, Physical);
+ devlen = strlen(Physical);
+ if (memicmp(Physical, filename, strlen(Physical))==0)
+ {
+ sprintf(Device, "MIRROR%d", Index);
+ if (GetPhysicalDevice(Device, MirrorFile))
+ {
+ mirrordevlen = strlen(MirrorFile);
+ strcat(MirrorFile, filename + strlen(Physical));
+ }
+ break;
+ }
+ ++Index;
+
+ if (Index == MAGDevices)
+ {
+ OperatorConsole.printf("***File to merge does not exist or is not on a MAG device\n");
+ return ( FALSE );
+ }
+ }
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ OperatorConsole.printf("***Error Connecting to SQL\n");
+ return ( FALSE );
+ }
+
+ // load image into memory
+ pDDO = LoadForGUI(filename);
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[MergeUIDofImageFile] %s -FAILED: Error on Load\n", filename);
+ return ( FALSE );
+ }
+
+ // change patient ID of object file in memory
+ if (!MergeUIDofDDO(pDDO, type, Reason))
+ {
+ OperatorConsole.printf("***[MergeUIDofImageFile] %s -FAILED: merging UID\n", filename);
+ delete pDDO;
+ return FALSE;
+ }
+
+ if (strcmp(type, "SeriesUID")==0)
+ //rc=CallImportConverterN(pDDO, 1700, NULL, NULL, NULL, NULL, "merging", "merging", NULL, NULL, VariableVRs);
+ rc=CallImportConverterN(pDDO, 1700, NULL, NULL, NULL, NULL, PDU, NULL, NULL);
+ else
+ //rc=CallImportConverterN(pDDO, 1800, NULL, NULL, NULL, NULL, "merging", "merging", NULL, NULL, VariableVRs);
+ rc=CallImportConverterN(pDDO, 1800, NULL, NULL, NULL, NULL, PDU, NULL, NULL);
+
+ if (rc==2 || rc==6)
+ {
+ OperatorConsole.printf("[MergeUIDofImageFile] %s script rejected merge\n", filename);
+ delete pDDO;
+ return FALSE;
+ }
+
+ if (*script)
+ //rc=CallImportConverterN(pDDO, -1, NULL, NULL, NULL, NULL, "merging", "merging", NULL, script, VariableVRs);
+ rc=CallImportConverterN(pDDO, -1, NULL, NULL, NULL, NULL, PDU, NULL, script);
+
+ if (rc==2 || rc==6)
+ {
+ OperatorConsole.printf("[MergeUIDofImageFile] %s script rejected merge\n", filename);
+ delete pDDO;
+ return FALSE;
+ }
+
+ // remove image file from database
+ if (DelFile)
+ if (!DeleteImageFile(filename, TRUE))
+ {
+ OperatorConsole.printf("***Could not remove image file from database\n");
+ return ( FALSE );
+ }
+
+ // add the image in memory to the server, also makes a copy of the image
+ //if (!SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"merging", (unsigned char *)"merging", 0, 1))
+ if (!SaveToDisk(DB, pDDO, rFilename, TRUE, PDU, 0, 1))
+ {
+ //delete pDDO;
+ OperatorConsole.printf("***Error entering object into server: %s\n", filename);
+ return ( FALSE );
+ }
+ OperatorConsole.printf("Merged image: %s\n", rFilename);
+
+ if (!DelFile)
+ return ( TRUE );
+
+ // delete the original image since it would show up with original series UID after regen
+ if (stricmp(filename, rFilename))
+ {
+ unlink(filename);
+ OperatorConsole.printf("Deleting file: %s\n", filename);
+ }
+
+ // delete the mirror image since it would show up with original series UID after regen
+ if (strlen(MirrorFile))
+ if (stricmp(MirrorFile, rFilename))
+ {
+ unlink(MirrorFile);
+ OperatorConsole.printf("Deleting mirror file: %s\n", MirrorFile);
+ }
+
+
+ // remove the source directory and any required subdirectories (just fails quietly if directory not yet empty)
+ strcpy(s, filename);
+ for (sIndex = strlen(s)-1; sIndex>=devlen; sIndex--)
+ if (s[sIndex]==PATHSEPCHAR)
+ {
+ s[sIndex]='\0';
+ rmdir(s);
+ }
+
+ // remove the mirror source directory and any required subdirectories (just fails quietly if directory not yet empty)
+ if (strlen(MirrorFile))
+ {
+ strcpy(s, MirrorFile);
+ for (sIndex = strlen(s)-1; sIndex>=mirrordevlen; sIndex--)
+ if (s[sIndex]==PATHSEPCHAR)
+ {
+ s[sIndex]='\0';
+ rmdir(s);
+ }
+ }
+
+ return ( TRUE );
+ }
+
+// Help routine for spawning a process on WIN32 or UNIX
+
+#ifndef UNIX // Win32...
+
+BOOL
+BackgroundExec(
+ char *ProcessBinary, // name of executable
+ char *Args) // arguments
+ {
+ PROCESS_INFORMATION PINFO;
+ STARTUPINFO SINFO;
+ SECURITY_ATTRIBUTES SA;
+ HANDLE hMap;
+ char CommandLine[1024];
+ char quote[10];
+
+ memset((void*)&SINFO, 0, sizeof(STARTUPINFO));
+ SINFO.cb = sizeof(STARTUPINFO);
+
+ SA.nLength = sizeof (SECURITY_ATTRIBUTES);
+ SA.lpSecurityDescriptor = NULL;
+ SA.bInheritHandle = TRUE;
+
+ if (strchr(ProcessBinary, ' '))
+ { quote[0]='"';
+ quote[1]=0;
+ }
+ else
+ quote[0]=0;
+
+ if (Args[0])
+ sprintf(CommandLine, "%s%s%s %s", quote, ProcessBinary, quote, Args);
+ else
+ sprintf(CommandLine, "%s%s%s", quote, ProcessBinary, quote);
+
+ if(!CreateProcess(ProcessBinary, CommandLine, NULL, NULL, TRUE,
+ DETACHED_PROCESS, NULL, NULL, &SINFO, &PINFO))
+ {
+ OperatorConsole.printf("***Failed to create process %s: %d\n", ProcessBinary, GetLastError());
+ return FALSE;
+ }
+ else
+ {
+ WaitForSingleObject(PINFO.hProcess, INFINITE);
+ CloseHandle(PINFO.hThread);
+ CloseHandle(PINFO.hProcess);
+ }
+
+ return ( TRUE );
+ }
+
+#else // UNIX...
+
+BOOL
+BackgroundExec(
+ char *theExecName,
+ char *theArg)
+ {
+
+ if (theArg[0]==0)
+ {
+ system(theExecName);
+ return TRUE;
+ }
+
+ // fork and exec a new process... (just replicate 1 thread...)
+
+ pid_t aPID = fork();
+
+ if(aPID == 0)
+ {
+ // this is the child process...
+ // lose controlling tty
+
+ setsid();
+
+ // close all open files, except standard I/O
+ // (could close those also, and attach them to /dev/console)
+ // like:
+ // fd = open("/dev/console", 1);
+ // if(fd != 1)
+ // {
+ // dup2(fd, 1);
+ // close(fd);
+ // fd = 1;
+ // }
+ // dup2(1, 2);
+
+ int anIndex;
+ int anOpenFileMax;
+
+ for(anIndex = 3, anOpenFileMax = sysconf(_SC_OPEN_MAX); anIndex < anOpenFileMax; ++anIndex)
+ {
+ close(anIndex);
+ }
+
+ // reset signals
+
+ for(anIndex = 1; anIndex <= SIGUSR2; ++anIndex)
+ {
+ (void)signal(anIndex, SIG_DFL);
+ }
+
+ // do the exec()
+
+ if(execlp(theExecName, theExecName, theArg, NULL))
+ {
+ SystemDebug.printf(
+ "DriverApp::ServerChildInit(): failed to execlp(%s)\n",
+ theExecName);
+ //_exit(255);
+ }
+ }
+ return ( TRUE );
+ }
+
+#endif
+
+////////////////////////////////////////////////////////////////////////
+// copy a file (possibly opening as shared file)
+
+static BOOL
+DFileCopy2(char *source, char *target, int smode)
+{
+ BOOL err_status = TRUE; /* Error status */
+ char *copybuffer; /* The copy buffer */
+ int inhandle, outhandle; /* Handle of input, output files */
+ unsigned bufsize; /* Size of copy buffer */
+ unsigned bytes; /* Actual transferred bytes */
+
+ /* Open input file for read-only. parser error if operation fails. */
+
+ if (!smode)
+ inhandle = open( source, O_RDONLY | O_BINARY, S_IREAD);
+ else
+ inhandle = sopen( source, O_RDONLY | O_BINARY, SH_DENYNO, S_IREAD);
+
+ if( inhandle == -1) return FALSE;
+
+ /* Ok, open output file. Parser error on permission failure: */
+
+ outhandle = open( target, O_CREAT | O_TRUNC | O_BINARY | O_RDWR, 0666);
+ if( outhandle == -1)
+ {
+ close(inhandle);
+ return FALSE;
+ }
+
+ /* get a large buffer */
+ bufsize = 0xF000;
+
+ copybuffer = (char *)malloc(bufsize);
+ if (copybuffer == NULL)
+ {
+ close(inhandle);
+ close(outhandle);
+ return FALSE;
+ }
+
+ while( !eof(inhandle) && err_status)
+ {
+ bytes= (unsigned)read( inhandle, copybuffer, bufsize);
+
+#ifndef WIN32
+ if (bytes == 0)
+ break;
+#endif
+
+ if (bytes == (unsigned) -1)
+ {
+ err_status= FALSE;
+ break;
+ }
+
+ if (bytes != (unsigned)write(outhandle, copybuffer, bytes))
+ {
+ err_status= FALSE;
+ break;
+ }
+ }
+
+ free(copybuffer);
+
+
+ close(outhandle);
+ close(inhandle);
+
+ /* Clean up mess in case of error : */
+ if(err_status != TRUE)
+ unlink(target);
+
+ return err_status;
+ }
+
+// Special RunTime-Classing Storage mechanism. Used for "Generic"
+// Unknown outgoing C-Store requests from the Query / Retrieve Engine
+// Defined here because needed in forward code
+
+class RunTimeClassStorage :
+ public StandardStorage
+ {
+ UID MyUID;
+
+ public:
+ // is not used anymore and would not be thread safe (db's may not be shared)
+ // Database DB;
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ BOOL GetUID(UID &);
+ BOOL SetUID(UID &);
+ BOOL SetUID(VR *);
+ BOOL SetUID(DICOMDataObject *);
+#ifdef __GNUC__
+ RunTimeClassStorage():MyUID() {};
+#endif
+
+ };
+
+// This routine is used as a filter for export converter.
+// It works by combining a given filter string with a query
+// for a given SOP, and returning TRUE if a record is found.
+// maxname is used to truncate fieldnames to fit with the DB spec.
+// limitations: PatientID, SeriesInstanceUID and StudyInstanceUID
+// cannot be queried. All other DB fields can be queried.
+
+BOOL DICOM2SQLValue (char *s);
+
+int TestFilter(char *query, char *sop, int maxname, char *patid=NULL)
+{ Database aDB;
+ char Tables[512], QueryString[512], Dum[256];
+ int result, instring=0, inword=0, i, L, Index;
+// char *p;
+ SQLLEN sdword;
+
+ if (*query)
+ sprintf(Tables, "%s, %s, %s, %s",
+ ImageTableName, SeriesTableName, StudyTableName, PatientTableName);
+ else
+ sprintf(Tables, "%s",
+ ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Filter: Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return 0;
+ }
+
+ // truncate the identifiers in the query to 10 characters
+ // this is our default maximum field name length for the DB
+ L = strlen(query);
+ for (i=0; i<L; i++)
+ { if (instring)
+ { if (query[i]=='\'')
+ { instring = 0;
+ }
+ continue;
+ }
+ else if (inword)
+ { if (query[i]==' ')
+ { inword = 0;
+ }
+ else
+ { inword++;
+ if (inword>maxname) query[i] = ' ';
+ }
+ }
+ else
+ { if (query[i]=='\'')
+ { instring = 1;
+ }
+ else if (isalpha(query[i]))
+ { inword = 1;
+ }
+ }
+ }
+
+ if (*query)
+ sprintf(QueryString, "(%s) and "
+ "DICOMImages.SopInstanc = '%s' and "
+ "DICOMStudies.PatientID = DICOMPatients.PatientID and "
+ "DICOMImages.SeriesInst = DICOMSeries.SeriesInst and "
+ "DICOMSeries.StudyInsta = DICOMStudies.StudyInsta",
+ query, sop);
+ else
+ sprintf(QueryString, "DICOMImages.SopInstanc = '%s'", sop);
+
+ // include patid (indexed) for speed; test for rev5 or higher of the database
+ if (patid)
+ {
+ Index = 1;
+ while (ImageDB[Index].Element)
+ {
+ if (ImageDB[Index].Group==0x0010 && ImageDB[Index].Element==0x0020)
+ {
+ char newpatid[128];
+ strcpy(newpatid, patid);
+ DICOM2SQLValue(newpatid); // allow exact match only
+ sprintf(QueryString+strlen(QueryString), " AND DICOMImages.ImagePat = %s", newpatid);
+ break;
+ }
+ Index++;
+ }
+ }
+
+ if (!aDB.Query(Tables, "DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Filter: Unable to query for image record\n");
+ aDB.Close();
+ return 0;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword);
+ result = aDB.NextRecord();
+
+ aDB.Close();
+
+ return result;
+ }
+
+/* The following function is called at the end of 'SaveToDisk' or through a queue
+ that is filled from SaveToDisk. After the arrival and storage of each DicomObject,
+ several executables may be invoked, to perform further processing.
+*/
+
+#ifdef WIN32
+#include "shellapi.h"
+#endif
+
+// forward references
+static int htoin(const char *value, int len);
+static int isxdig(char ch);
+BOOL prefetch_queue(const char *operation, char *patientid, const char *server, const char *studyuid, const char *seriesuid, const char *compress,
+ const char *modality, const char *date, const char *sop, const char *imagetype, const char *seriesdesc, int delay=0, const char *script=NULL);
+void reset_queue_fails(int N);
+
+static BOOL match(const char *source, char *target)
+{ if (strlen(target)==1 && target[0]=='*') return TRUE;
+
+ char Source[512];
+ strcpy(Source, source);
+ while (strlen(Source)>0 && Source[strlen(Source)-1]==' ') Source[strlen(Source)-1] = 0;
+
+ if (strlen(target)> 1 && target[0]=='*' && target[strlen(target)-1]=='*')
+ { char sub[512];
+
+ strcpy(sub, target+1);
+ sub[strlen(sub)-1]=0;
+ strlwr(sub);
+
+ strlwr(Source);
+
+ if (strstr(Source, sub)==0) return FALSE;
+ }
+ else
+ if (strlen(target)> 1 && target[strlen(target)-1]=='*')
+ { if (memicmp(Source, target, strlen(target)-1)) return FALSE;
+ }
+ else
+ if (strlen(target)> 1 && target[0]=='*')
+ { if (memicmp(Source+strlen(Source)-strlen(target)+1, target+1, strlen(target)-1)) return FALSE;
+ }
+ else
+ if (stricmp(Source, target)) return FALSE;
+
+ return TRUE;
+}
+
+// Search a composite dicom object:
+// desc=gggg,eeee plain element
+// desc=PatientID plain element (name from dgate.dic may be used everywhere instead of gggg,eeee)
+// desc=*gggg,eeee search in all sequences
+// desc=/*gggg,eeee idem
+// desc=/gggg,eeee.i.. search specified in sequence, ith element (recursive)
+// desc=/gggg,eeee.. idem, first element
+// e.g. /gggg,eeee.0/gggg,eeee/*gggg,eeee: to search specified sequences
+//
+// desc=(desc1)desc2 search desc1 in DICOM object which sop is specified in (desc1), patient ID taken from 0010,0020
+// e.g. %V(/300c,0060.0/0008,1155)/gggg,eeee.0/gggg,eeee
+//
+// returns length of parsed desc string
+// if passed *A is set with the sequence array or
+// if passed *O is set with the embedding dicom object
+
+int SearchDICOMObject(DICOMObject *DDO, const char *desc, char *result, Array < DICOMDataObject * > **A, DICOMDataObject **O)
+ {
+ DICOMObject DDO2;
+ VR *vr;
+ int i, g, e, len;
+ unsigned int Index;
+// char *p;
+ BOOL seq=FALSE, wild=FALSE;
+
+ if (A) *A = NULL;
+ if (O) *O = NULL;
+
+ result[0]=0;
+ result[1]=0; // indicates VR not found
+ i =0;
+
+ if (desc[i]=='(')
+ {
+ i++;
+ char r[300];
+ DICOMObject *pDDO;
+
+ SearchDICOMObject(DDO, "0010,0020", r);
+ strcat(r, ":");
+ i += SearchDICOMObject(DDO, desc+i, r+strlen(r));
+ if (desc[i]==')') i++;
+ //else OperatorConsole.printf("***Syntax error in %V(desc)desc statement %s at %d\n", desc, i);
+ pDDO = LoadForGUI(r);
+ i += SearchDICOMObject(pDDO, desc+i, result); // no use to allow write to A or O
+ delete pDDO;
+ return i;
+ }
+
+ if (desc[i]=='/') i++, seq=TRUE;
+ if (desc[i]=='*') i++, seq=FALSE, wild=TRUE;
+
+ if (isxdig(desc[i]) && desc[i+4]==',')
+ { g = htoin(desc+i, 4);
+ e = htoin(desc+i+5, 4);
+ i +=9;
+ }
+ else if (isalpha(desc[i]))
+ { char d[256];
+ int j;
+ RTCElement Entry;
+ strcpy(d, desc+i);
+ j=0; while (isalpha(d[j])) j++;
+ d[j]=0;
+ Entry.Description = d;
+ if (VRType.GetGroupElement(&Entry))
+ { g = Entry.Group;
+ e = Entry.Element;
+ i += j;
+ }
+ else
+ return i;
+ }
+ else
+ return i;
+
+ // get plain element
+ if (!seq && !wild)
+ {
+ if (!DDO) return i;
+ vr = DDO->GetVR(g, e);
+ if (vr)
+ {
+ if (vr->SQObjectArray)
+ {
+ if (A) *A = (Array<DICOMDataObject*>*) vr->SQObjectArray;
+ strcpy(result, "(sequence)");
+ }
+ else if (vr->Length>255)
+ strcpy(result, "(too long)");
+ else
+ {
+ UINT16 TypeCode = VRType.RunTimeClass(g, e, NULL);
+ if (TypeCode== 'UL') sprintf(result, "%u", (unsigned int)(*(UINT32*)(vr->Data)));
+ else if (TypeCode== 'US') sprintf(result, "%u", (unsigned int)(*(UINT16*)(vr->Data)));
+ else if (TypeCode== 'SL') sprintf(result, "%d", (int)(*(INT32*)(vr->Data)));
+ else if (TypeCode== 'SS') sprintf(result, "%d", (int)(*(INT16*)(vr->Data)));
+ else
+ { strncpy(result, (char*)vr->Data, vr->Length);
+ result[vr->Length] = 0;
+ if (vr->Length==0) result[vr->Length+1] = 1; // indicates empty string
+ }
+ len = vr->Length - 1;
+ while(len>0)
+ {
+ if (result[len] == ' ')
+ result[len] = 0;
+ else
+ break;
+ len--;
+ }
+ }
+ }
+
+ return i;
+ }
+
+ // get specified sequence element
+ else if (seq)
+ {
+ int j=0;
+
+ if (desc[i]=='.')
+ {
+ i++;
+ Index = atoi(desc+i);
+ while (isdigit(desc[i])) i++;
+ }
+ else
+ Index = 0;
+
+ vr = NULL;
+ if (DDO) vr = DDO->GetVR(g, e);
+ if (vr)
+ {
+ if ( vr->SQObjectArray )
+ {
+ Array < DICOMDataObject * > *ADDO =
+ (Array<DICOMDataObject*>*) vr->SQObjectArray;
+
+ j = 0;
+ if (desc[i]==0)
+ {
+ strcpy(result, "(sequence)");
+ if (A) *A = ADDO;
+ }
+ else if (Index<ADDO->GetSize())
+ {
+ if (O) *O = ADDO->Get(Index);
+ j = SearchDICOMObject(ADDO->Get(Index), desc+i, result, A, O);
+ }
+ }
+ else
+ {
+ if (vr->Length>255)
+ strcpy(result, "(too long)");
+ else
+ {
+ UINT16 TypeCode = VRType.RunTimeClass(g, e, NULL);
+ if (TypeCode== 'UL') sprintf(result, "%u", (unsigned int)(*(UINT32*)(vr->Data)));
+ else if (TypeCode== 'US') sprintf(result, "%u", (unsigned int)(*(UINT16*)(vr->Data)));
+ else if (TypeCode== 'SL') sprintf(result, "%d", (int)(*(INT32*)(vr->Data)));
+ else if (TypeCode== 'SS') sprintf(result, "%d", (int)(*(INT16*)(vr->Data)));
+ else
+ { strncpy(result, (char*)vr->Data, vr->Length);
+ result[vr->Length] = 0;
+ if (vr->Length==0) result[vr->Length+1] = 1; // indicates empty string
+ }
+ len = vr->Length - 1;
+ while(len>0)
+ {
+ if (result[len] == ' ')
+ result[len] = 0;
+ else
+ break;
+ len--;
+ }
+ }
+ }
+ }
+ else
+ {
+ // ignore rest of desc
+ char dum[1024];
+ j = SearchDICOMObject(DDO, desc+i, dum);
+ }
+
+ return i+j;
+ }
+
+ // wild: search all sequences
+ if (!DDO) return i;
+ while((vr=DDO->Pop()))
+ {
+ if (*result==0)
+ {
+ if ( vr->SQObjectArray )
+ {
+ Array < DICOMDataObject * > *ADDO =
+ (Array<DICOMDataObject*>*) vr->SQObjectArray;
+
+ Index = 0;
+ while ( Index < ADDO->GetSize() )
+ {
+ SearchDICOMObject(ADDO->Get(Index), desc, result);
+ if (*result) break;
+ ++Index;
+ }
+ }
+ else if (vr->Group==g && vr->Element==e)
+ {
+ if (vr->Length>255)
+ strcpy(result, "(too long)");
+ else
+ {
+ UINT16 TypeCode = VRType.RunTimeClass(g, e, NULL);
+ if (TypeCode== 'UL') sprintf(result, "%u", (unsigned int)(*(UINT32*)(vr->Data)));
+ else if (TypeCode== 'US') sprintf(result, "%u", (unsigned int)(*(UINT16*)(vr->Data)));
+ else if (TypeCode== 'SL') sprintf(result, "%d", (int)(*(INT32*)(vr->Data)));
+ else if (TypeCode== 'SS') sprintf(result, "%d", (int)(*(INT16*)(vr->Data)));
+ else
+ { strncpy(result, (char*)vr->Data, vr->Length);
+ result[vr->Length] = 0;
+ if (vr->Length==0) result[vr->Length+1] = 1; // indicates empty string
+ }
+ len = vr->Length - 1;
+ while(len>0)
+ {
+ if (result[len] == ' ')
+ result[len] = 0;
+ else
+ break;
+ len--;
+ }
+ }
+ }
+ }
+
+ DDO2.Push(vr);
+ }
+
+ DDO->Reset();
+ while((vr=DDO2.Pop()))
+ {
+ DDO->Push(vr);
+ }
+
+ return i;
+ }
+
+
+struct scriptdata
+{ ExtendedPDU_Service *PDU;
+ DICOMCommandObject *DCO;
+ DICOMDataObject *DDO;
+ int N;
+ char *pszModality;
+ char *pszStationName;
+ char *pszSop;
+ char *patid;
+ char *Storage;
+ int rc;
+ unsigned int ConnectedIP;
+} sd1;
+
+const char *do_lua(lua_State **L, char *cmd, struct scriptdata *sd);
+
+// operates asynchronously on images AFTER it they are stored in the database
+// return TRUE if it worthwile to retry (connection or write failed)
+// For general scripting use:
+// CallExportConverterN(FileName, -1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, script)
+
+BOOL CallExportConverterN(char *pszFileName, int N, char *pszModality, char *pszStationName, char *pszSop, char *patid, ExtendedPDU_Service *PDU, char *ForwardLastUID, char *calling, char *called)
+{ char szRootSC[64];
+ char szEntry[32];
+ char szTemp[66];
+ int i1, rc, MaxLength, part, skipping;
+ char szExecName[512], szNext[512];
+ char szExecModality[66];
+ char szExecStationName[66];
+ char szExecFilter[512];
+ char ExportCalledAE[18], ExportCallingAE[18], Called[18], Calling[18];
+ BOOL StripGroup2;
+
+ PDU->SetLocalAddress ( (BYTE *)calling );
+ PDU->SetRemoteAddress ( (BYTE *)called );
+
+ DICOMDataObject *DDO = NULL;
+ ExtendedPDU_Service PDU2; // not used as script context
+
+ PDU2.AttachRTC(&VRType);
+
+ if (!MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig,
+ szRootSC, 64, ConfigFile)) return FALSE;
+
+ // [lua] ExportConverterN: has all ImportConverter functionality + script("defer")
+ sprintf(szEntry, "ExportConverter%d", N);
+ MyGetPrivateProfileString("lua", szEntry, "", szExecName, 512, ConfigFile);
+ if (szExecName[0])
+ { if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+ struct scriptdata sd1 = {PDU, NULL, DDO, N, pszModality, pszStationName, pszSop, patid, NULL, 0, 0};
+
+ do_lua(&(PDU->L), szExecName, &sd1);
+ if (sd1.rc==8)
+ { SystemDebug.printf("Exportconverter%d.%d: defer\n", N, -1);
+ reset_queue_fails(N);
+ if (DDO) delete DDO;
+ return TRUE; // retry later
+ }
+
+ if (DDO) delete DDO;
+ return FALSE;
+ }
+
+ /* filter using modality, stationname, calling and called */
+
+ if (pszModality)
+ { sprintf(szEntry, "ExportModality%d", N);
+ if (!MyGetPrivateProfileString(szRootSC, szEntry, "*", szExecModality, 64, ConfigFile)) return FALSE;
+ if (!match(pszModality, szExecModality)) return FALSE;
+ }
+
+ if (pszStationName)
+ { sprintf(szEntry, "ExportStationName%d", N);
+ if (!MyGetPrivateProfileString(szRootSC, szEntry, "*", szExecStationName, 64, ConfigFile)) return FALSE;
+ if (!match(pszStationName, szExecStationName)) return FALSE;
+ }
+
+ if (calling)
+ { sprintf(szEntry, "ExportCallingAE%d", N);
+ if (!MyGetPrivateProfileString(szRootSC, szEntry, "*", ExportCallingAE, 18, ConfigFile)) return FALSE;
+ if (!match(calling, ExportCallingAE)) return FALSE;
+ }
+
+ if (called)
+ { sprintf(szEntry, "ExportCalledAE%d", N);
+ if (!MyGetPrivateProfileString(szRootSC, szEntry, "*", ExportCalledAE, 18, ConfigFile)) return FALSE;
+ if (!match(called, ExportCalledAE)) return FALSE;
+ }
+
+ /* apply database filter */
+
+ if (called && calling)
+ { sprintf(szEntry, "ExportFilter%d", N);
+ if (!MyGetPrivateProfileString(szRootSC, szEntry, "*", szExecFilter, 510, ConfigFile)) return FALSE;
+ if (szExecFilter[0]!='*')
+ { if (!MyGetPrivateProfileString(szRootSC, "TruncateFieldNames", "255", szTemp, 32, ConfigFile)) return FALSE;
+ MaxLength = atoi(szTemp);
+
+ if (!TestFilter(szExecFilter, pszSop, MaxLength, patid)) return FALSE;
+ }
+ }
+
+ /* get the export converter name: empty is none */
+
+ if (called && calling)
+ { sprintf(szEntry, "ExportConverter%d", N);
+ if (!MyGetPrivateProfileString(szRootSC, szEntry, "",
+ szExecName, 512, ConfigFile)) return FALSE;
+ if (szExecName[0]==0) return FALSE;
+ }
+ else
+ strcpy(szExecName, ForwardLastUID);
+
+ rc = 1; // status for if statement and stop
+ part = 0;
+ skipping = 0;
+
+ while(1)
+ { szNext[0] = 0;
+
+ if (skipping || rc==4) // {} block being skipped
+ { if (szExecName[0]=='{') skipping++, rc=0;
+ else if (szExecName[0]=='}') skipping--, rc=0;
+ }
+
+ // remove {} for all export converters (not only those with a %)
+ i1 = 0;
+ if (szExecName[0] == '{') {i1++; while(szExecName[i1]==' ')i1++; memmove(szExecName, szExecName+i1, strlen(szExecName+i1)+1); }
+ else if (szExecName[0] == '}') {i1++; while(szExecName[i1]==' ')i1++; memmove(szExecName, szExecName+i1, strlen(szExecName+i1)+1); }
+
+ // find ; not in string: splits export commands
+ int instring=0;
+ int L1 = strlen(szExecName);
+ for (int k=0; k<L1; k++)
+ { if (szExecName[k]=='"') instring = !instring;
+ if (szExecName[k]==';' && instring==0)
+ { szExecName[k] = 0; // split command
+ while (szExecName[k+1]==' ') k++; // skip spaces after ;
+ strcpy(szNext, szExecName+k+1); // remaining for next
+ break;
+ }
+ }
+
+ if (skipping) // {} block being skipped
+ { SystemDebug.printf("Exportconverter%d.%d skipped\n", N, part);
+ }
+
+ else if (szExecName[0]==0) // leftover of { or }
+ {
+ }
+
+ else if (rc==4) // ifxxxx statement causes a skip
+ { rc = 0;
+ SystemDebug.printf("Exportconverter%d.%d not executed because of previous statement\n", N, part);
+ }
+
+ /* for all export converters: first substitute % variables */
+
+ else
+ { char line[1000];
+
+ if (1 || strchr(szExecName, '%'))
+ { int i=0, l, L;// len;
+ char *p;
+// VR *pVR;
+// char vr[256];
+
+ /* substitute %x variables and remove possible { and } at begin of statement */
+
+ line[0] = 0;
+ instring = 0;
+
+ L = strlen(szExecName);
+ while (i<L)
+ { if (i==0 && szExecName[i] == '{') {i++; while(szExecName[i]==' ')i++;}
+ else if (i==0 && szExecName[i] == '}') {i++; while(szExecName[i]==' ')i++;}
+ else if (szExecName[i] == '"')
+ { if (instring && szExecName[i+1]=='"')
+ { strcat(line, """");
+ i+=2;
+ }
+ else
+ { l = strlen(line);
+ line[l] = szExecName[i++];
+ line[l+1] = 0;
+ }
+ instring = !instring;
+ }
+ else if (szExecName[i] == '%')
+ { char *ps = line + strlen(line);
+
+ switch(tolower(szExecName[i+1]))
+ { case 'f': strcat(line, pszFileName); // %f=filename
+ break;
+ case 'b': p = strrchr(pszFileName, PATHSEPCHAR);
+ if (p) // %b=file base name
+ { strcat(line, p+1);
+ p = strrchr(line, '.');
+ if (p) *p=0;
+ }
+ break;
+ case 'p': strcat(line, pszFileName); // %p=file path
+ p = strrchr(line, PATHSEPCHAR);
+ if (p) *p=0;
+ break;
+ case 'm': if (pszModality)
+ strcat(line, pszModality); // %m=modality
+ else
+ { char result[256];
+ if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+ SearchDICOMObject(DDO, "0008,0060", result);
+ strcat(line, result);
+ }
+ break;
+ case 's': if (pszStationName)
+ strcat(line, pszStationName); // %s=stationname
+ else
+ { char result[256];
+ if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+ SearchDICOMObject(DDO, "0008,1010", result);
+ strcat(line, result);
+ }
+ break;
+ case 'o': if (pszSop)
+ strcat(line, pszSop); // %o=object instance
+ else
+ { char result[256];
+ if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+ SearchDICOMObject(DDO, "0008,0018", result);
+ strcat(line, result);
+ }
+ break;
+ case 'i': if (patid)
+ strcat(line, patid); // %i=patient ID
+ else
+ { char result[256];
+ if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+ SearchDICOMObject(DDO, "0010,0020", result);
+ strcat(line, result);
+ }
+ break;
+ case 'u': Calling[0]=0;
+ if (calling) strcpy(Calling, calling);
+ while (strlen(Calling)>0 && Calling[strlen(Calling)-1]==' ') Calling[strlen(Calling)-1] = 0;
+ strcat(line, Calling); // %u=SCU
+ break;
+ case 'c': Called[0]=0;
+ if (called) strcpy(Called, called);
+ while (strlen(Called)>0 && Called[strlen(Called)-1]==' ') Called[strlen(Called)-1] = 0;
+ strcat(line, Called); // %c=calledAE = scp
+ break;
+ case 'd': time_t TimeOfDay; // %d=date and time
+ char TimeString[128], buf[64];
+ UNUSED_ARGUMENT(buf);//Stop gcc4.2 warning bcb
+ TimeOfDay = time(NULL);
+ strcpy(TimeString, ctime_r(&TimeOfDay, buf));
+ TimeString[strlen(TimeString)-1] = '\0';
+ strcat(line, TimeString);
+ break;
+ case 'n': strcat(line, "\n"); // %n=newline
+ break;
+ case 't': strcat(line, "\t"); // %t=tab
+ break;
+ case '%': strcat(line, "%"); // %%=%
+ break;
+ case '^': strcat(line, "^"); // %^=^
+ break;
+ case '~': strcat(line, "~"); // %~=~
+ break;
+ case '[': strcat(line, "["); // %[=[
+ break;
+ case 'v': // %Vxxxx,yyyy=any vr (group and element must have 4 digits)
+ char result[256]; // %V*xxxx,yyyy=any vr in any sequence
+ if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+ i += SearchDICOMObject(DDO, szExecName+i+2, result);
+ strcat(line, result);
+ break;
+ case 'a': { // %Axxxx,yyyy=crc of any vr (group and element must have 4 digits)
+ char result2[256];
+ if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+ i += SearchDICOMObject(DDO, szExecName+i+2, result2);
+ unsigned int crc = ComputeCRC(result2, strlen(result2));
+ sprintf(result2, "%u", crc);
+ strcat(line, result2);
+ break;
+ }
+ case 'e': { // %Exxxx,yyyy= changed UID for any UID
+ char result2[256], result3[256];
+ if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+ i += SearchDICOMObject(DDO, szExecName+i+2, result2);
+ ChangeUID(result2, "percente", result3);
+ strcat(line, result3);
+ break;
+ }
+ case 'r': { // %Rxxxx,yyyy= old UID for any changed UID
+ char result2[256], result3[256];
+ if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+ i += SearchDICOMObject(DDO, szExecName+i+2, result2);
+ ChangeUIDBack(result2, result3);
+ strcat(line, result3);
+ break;
+ }
+
+ // case 'q': not (yet) supported for export converters - probably no need
+ }
+ i += 2;
+
+ // get substring of variable [start, end] or [,fromend]
+ if (szExecName[i]=='[')
+ { int a=0, b=-1;
+ if (szExecName[i+1]==',')
+ sscanf(szExecName+i, "[,%d]", &b), a=-1;
+ else
+ sscanf(szExecName+i, "[%d,%d]", &a, &b);
+ for (;i<L;i++) if (szExecName[i-1]==']') break;
+ if (a>(signed int)strlen(ps)) a=strlen(ps);
+ if (a<0) { a = strlen(ps)-b; b = strlen(ps); }
+ if (a<0) a = 0;
+ if (b>(signed int)strlen(ps)) b=strlen(ps);
+ if (b>=a) {memmove(ps, ps+a, b-a+1); ps[b-a+1]=0;}
+ }
+
+ // convert to uppercase
+ if (szExecName[i]=='^')
+ { i++;
+ strupr(ps);
+ }
+ // convert to lowercase
+ else if (szExecName[i]=='~')
+ { i++;
+ strlwr(ps);
+ }
+ }
+ else
+ { l = strlen(line);
+ line[l] = szExecName[i++];
+ line[l+1] = 0;
+ }
+ }
+
+ // if (DDO) delete DDO;
+ }
+ else
+ strcpy(line, szExecName);
+
+ /* converter: direct forward of received object */
+
+ if (memicmp(line, "forward to", 10)==0 ||
+ memicmp(line, "forward compressed", 18)==0
+ )
+ { char host[512], port[64], compress[64], dummy[64], Level[64], Temp[66];
+ char *p, *q, *c;
+ RunTimeClassStorage RTCStorage;
+ UID AppUID ("1.2.840.10008.3.1.1.1");
+ UID iUID, uid;
+ VR *vr;
+ int offset = 11, level;
+ BYTE org[512], dest[512];
+ char script[512];
+
+ // fallback if none passed: forces one association per image
+ if (!PDU) PDU = &PDU2;
+
+ // preprocess the forwarder string
+ if (memicmp(line, "forward compressed as ", 22)==0) offset = 28;
+ // xx to where xx = 'is', 'un', 'n0'..'n4', or 'jl', 'jk', 'j0'..'j6'
+ // xxNN same as above but NN is lossy quality
+
+ // offer transfer syntax (compression) from forward string
+ compress[0]=0;
+ if (offset==28)
+ { compress[0] = line[22];
+ compress[1] = line[23];
+ compress[2] = 0;
+ if (line[24] != ' ')
+ { compress[2] = line[24];
+ compress[3] = line[25];
+ compress[4] = 0;
+ offset = 30;
+ }
+ }
+
+ // get the script clause (to process), must be last
+ script[0] = 0;
+ p = strstr(line + offset, " script ");
+ if (p)
+ { strcpy((char *)script, p+8);
+ p[8] = 0;
+ }
+
+ // get the org clause (originator)
+ strcpy((char *)org, (char *)MYACRNEMA);
+ p = strstr(line + offset, " org ");
+ if (p)
+ { strcpy((char *)org, p+5);
+ q = strchr((char *)org, ' '); if (q) *q=0;
+ }
+
+ // get the dest clause (called AE)
+ dest[0] = 0;
+ p = strstr(line + offset, " dest ");
+ if (p)
+ { strcpy((char *)dest, p+6);
+ q = strchr((char *)dest, ' '); if (q) *q=0;
+ }
+
+ // get the to AE
+ q = strchr(line+offset, ' '); if (q) *q=0;
+ c=compress;
+ if (compress[0]) c=dummy;
+ if(!GetACRNema(line+offset, (char *)host, (char *)port, (char *)c))
+ { // it does not exist: get host:port
+ strcpy(host, line+offset);
+ p = strchr(host, ':');
+ if (p)
+ { *p=0;
+ strcpy(port, p+1);
+ }
+ else
+ strcpy(port, "5678");
+ strcpy(compress, "UN");
+ }
+
+ OperatorConsole.printf("ExportConverter%d.%d: forward %s to %s\n", N, part, pszFileName, line+offset);
+
+ // load and check the data
+ if (!DDO)
+ DDO = PDU2.LoadDICOMDataObject(pszFileName);
+
+ if (!DDO)
+ { OperatorConsole.printf("*** ExportConverter%d.%d: Forward failed to load DICOM object %s\n", N, part, pszFileName);
+ return FALSE;
+ }
+
+ // get UID at selected ForwardAssociationLevel into szTemp
+ vr = NULL;
+ level = 0;
+ MyGetPrivateProfileString(szRootSC, "ForwardAssociationLevel", "STUDY", Level, 64, ConfigFile);
+ if (strncmp(Level, "PATIENT", 7)==0) level=1;
+ else if (strncmp(Level, "STUDY", 5)==0) level=2;
+ else if (strncmp(Level, "SERIES", 6)==0) level=3;
+ else if (strncmp(Level, "IMAGE", 5)==0) level=4;
+ else if (strncmp(Level, "SOPCLASS",8)==0) level=5, PDU[part].ClearAbstractSyntaxs();
+ else if (strncmp(Level, "GLOBAL", 6)==0) level=6;
+ szTemp[0] = 0;
+ if (level==1) vr = DDO->GetVR(0x0010, 0x0020);
+ if (level==2) vr = DDO->GetVR(0x0020, 0x000d);
+ if (level==3) vr = DDO->GetVR(0x0020, 0x000e);
+ if (level==4) vr = DDO->GetVR(0x0008, 0x0018);
+ if (level==5) vr = DDO->GetVR(0x0008, 0x0016);
+ if (vr) memcpy(szTemp, vr->Data, vr->Length);
+ if (vr) szTemp[vr->Length]=0;
+
+ // get sopclass (to check whether it is accepted at the current connection)
+ vr = DDO -> GetVR(0x0008, 0x0016);
+ if (!vr)
+ { OperatorConsole.printf("*** ExportConverter%d.%d: Forward failed because SopClass is missing in %s\n", N, part, pszFileName);
+ delete DDO;
+ return FALSE;
+ }
+
+ // does the existing link accept images of this type - if not then hang up to force a reconnect
+ // also hang up when UID at ForwardAssociationLevel changes to start a new association
+ if (PDU[part].Link.Connected)
+ { SetUID ( iUID, vr );
+ if (!PDU[part].IsAbstractSyntaxAccepted(iUID) || strcmp(ForwardLastUID+part*66, szTemp)!=0 )
+ { //OperatorConsole.printf("!!! ExportConverter%d.%d: attempt to reconnect %s \n", N, part, szTemp);
+ MyGetPrivateProfileString(szRootSC, "ForwardAssociationRelease", "1", Temp, 64, ConfigFile);
+ if (atoi(Temp)) PDU[part].Close();
+ else PDU[part].Link.Close();
+ }
+ }
+
+ // for new check of UID at ForwardAssociationLevel
+ strcpy(ForwardLastUID+part*66, szTemp);
+
+ // (re)connect
+ if (!PDU[part].Link.Connected)
+ { PDU[part].AttachRTC(&VRType);
+ PDU[part].SetRequestedCompressionType(compress);
+
+ PDU[part].SetApplicationContext ( AppUID );
+ PDU[part].SetLocalAddress ( org );
+ if (dest[0])
+ PDU[part].SetRemoteAddress ( (unsigned char *)(dest) );
+ else
+ PDU[part].SetRemoteAddress ( (unsigned char *)(line+offset) );
+ PDU[part].SetTimeOut(TCPIPTimeOut);
+
+ vr = DDO -> GetVR(0x0008, 0x0016);
+ SetUID ( iUID, vr );
+ PDU[part].AddAbstractSyntax ( iUID ); // adds type of this image to presentation contexts
+
+ uid.Set("1.2.840.10008.1.1"); // This one should always accept: verification
+ PDU[part].AddAbstractSyntax(uid); // assures connect will not return FALSE because image is not accepted
+
+ if (!PDU[part].Connect((unsigned char *)&host, (unsigned char *)&port))
+ { OperatorConsole.printf("*** ExportConverter%d.%d: Forward failed to connect to host %s\n", N, part, line+offset);
+ delete DDO;
+ return TRUE; // may be good idea to retry later
+ }
+ }
+
+ vr = DDO -> GetVR(0x0008, 0x0016);
+ SetUID ( iUID, vr );
+ if (!PDU[part].IsAbstractSyntaxAccepted(iUID))
+ { OperatorConsole.printf("*** ExportConverter%d.%d: DICOM server %s does not accept type of forwarded image\n", N, part, line+offset);
+ PDU[part].Close();
+ delete DDO;
+ return FALSE;
+ }
+
+ // process data
+ if (script)
+ CallImportConverterN(DDO, -1, NULL, NULL, NULL, NULL, PDU+part, NULL, script);
+
+ // recompress data to be forwarded here according to accepted compression mode; strip group 2 unless "as" or "is"
+ p = PDU[part].GetAcceptedCompressionType(iUID);
+ StripGroup2 = memicmp(p, "as", 2)!=0 && memicmp(p, "is", 2)!=0;
+ recompress(&DDO, p, "", StripGroup2, PDU);
+
+ RTCStorage.SetUID(iUID);
+
+ if (!RTCStorage.Write(PDU+part, DDO))
+ { OperatorConsole.printf("*** ExportConverter%d.%d: Forward failed to send DICOM image to %s\n", N, part, line+offset);
+ PDU[part].Close();
+ delete DDO;
+ MyGetPrivateProfileString(szRootSC, "RetryForwardFailed", "0", Temp, 64, ConfigFile);
+ if (atoi(Temp)) return TRUE;
+ else return FALSE; // NOT a good idea to retry later
+ }
+
+ ImagesForwarded++;
+ if (level==4)
+ { MyGetPrivateProfileString(szRootSC, "ForwardAssociationRelease", "1", Temp, 64, ConfigFile);
+ if (atoi(Temp)) PDU[part].Close();
+ else PDU[part].Link.Close();
+ }
+
+ delete DDO; // write was destructive
+ DDO = NULL;
+ }
+
+ /* converter: write "string" to file - uses text file, use %n for newline */
+
+ else if (memicmp(line, "write \"", 7)==0)
+ { char string[256];
+ char *file;
+ FILE *f;
+ char *p;
+
+ strcpy(string, line+7);
+ p = strstr(string, "\" to ");
+ if (!p) p = strstr(string, "\" TO ");
+ if (p)
+ { *p=0;
+
+ OperatorConsole.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+
+ file = p+5;
+ f = fopen(file, "wt");
+ if (f)
+ { fputs(string, f);
+ fclose(f);
+ }
+ else
+ OperatorConsole.printf("*** Exportconverter%d.%d: Failed to write to file %s\n", N, part, file);
+ }
+ }
+
+ /* converter: append "string" to file - uses text file, use %n for newline */
+
+ else if (memicmp(line, "append \"", 8)==0)
+ { char string[256];
+ char *file;
+ FILE *f;
+ char *p;
+
+ strcpy(string, line+8);
+ p = strstr(string, "\" to ");
+ if (!p) p = strstr(string, "\" TO ");
+ if (p)
+ { *p=0;
+
+ OperatorConsole.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+
+ file = p+5;
+ f = fopen(file, "at");
+ if (f)
+ { fputs(string, f);
+ fclose(f);
+ }
+ else
+ OperatorConsole.printf("*** Exportconverter%d.%d: Failed to append to file %s\n", N, part, file);
+ }
+ }
+
+ /* converter: copy file to file; copy file to directory */
+
+ else if (memicmp(line, "copy ", 5)==0)
+ { char string[1024];
+ char *file;
+ struct stat statbuf;
+ char *p;
+
+ strcpy(string, line+5);
+ p = strstr(string, " to ");
+ if (!p) p = strstr(string, " TO ");
+ if (p)
+ { *p=0;
+
+ OperatorConsole.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+
+ file = p+4;
+
+ /* if the destination a directory then append the source filename to it */
+
+ stat(file, &statbuf);
+ if (statbuf.st_mode & S_IFDIR)
+ { p = strrchr(pszFileName, PATHSEPCHAR);
+ if (p)
+ { if (file[strlen(file)-1]==PATHSEPCHAR)
+ file[strlen(file)-1]=0;
+ strcat(file, p);
+ }
+ }
+
+ if (!DFileCopy2(string, file, 0))
+ OperatorConsole.printf("*** Exportconverter%d.%d: Failed to copy %s to %s\n", N, part, string, file);
+ else
+ ImagesCopied++;
+ }
+ }
+
+ /* converter: save to filename (filename can be generated using all % tricks) */
+
+ else if (memicmp(line, "save to ", 8)==0)
+ { char *file = line+8;
+
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", "Export", N, part, line);
+
+ if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+ SaveDICOMDataObject(file, DDO);
+ delete DDO;
+ DDO=NULL;
+ }
+
+ /* converter: save frame N to filename (filename can be generated using all % tricks) */
+
+ else if (memicmp(line, "save frame ", 11)==0)
+ { char *p1 = strstr(line, " to ");
+ char *file = p1 + 4;
+ int frame = atoi(line+11);
+
+ if (p1)
+ { OperatorConsole.printf("%sconverter%d.%d executes: %s\n", "Export", N, part, line);
+
+ if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+ ExtractFrame(DDO, frame);
+ SaveDICOMDataObject(file, DDO);
+ delete DDO;
+ DDO=NULL;
+ }
+ }
+
+ /* converter: save bmp [frame N] [size N] filename (filename can be generated using all % tricks) */
+
+ else if (memicmp(line, "save bmp ", 9)==0 ||
+ memicmp(line, "save gif ", 9)==0 ||
+ memicmp(line, "save jpg ", 9)==0)
+ { int level=0, window=0, frame=0, size=0, quality=95;
+ char *file=NULL, *p1;
+ p1 = strstr(line, " to ");
+ if (p1) file = p1 + 4;
+ p1 = strstr(line, " as ");
+ if (p1) file = p1 + 4;
+ p1 = strstr(line, " level ");
+ if (p1) level = atoi(p1+7);
+ p1 = strstr(line, " window ");
+ if (p1) window = atoi(p1+8);
+ p1 = strstr(line, " quality ");
+ if (p1) quality = atoi(p1+9);
+ p1 = strstr(line, " frame ");
+ if (p1) frame = atoi(p1+7);
+ p1 = strstr(line, " size ");
+ if (p1) size = atoi(p1+6);
+ if (size<10) size = 4096;
+
+ if (file)
+ { OperatorConsole.printf("%sconverter%d.%d executes: %s\n", "Export", N, part, line);
+ if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+
+ if (memicmp(line + 5, "bmp ", 4)==0) ToBMP(DDO, file, size, 0, level, window, frame);
+ else if (memicmp(line + 5, "gif ", 4)==0) ToGif(DDO, file, size, 0, level, window, frame);
+ else ToJPG(DDO, file, size, 0, level, window, frame, quality);
+ }
+ }
+
+ // lua "" export converter: has all ImportConverter functionality + script("defer")
+
+ else if (memicmp(line, "lua \"", 5)==0)
+ { char cmd[1024];
+ if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+
+ // note; threadnum and dco not implemented
+ struct scriptdata sd = {PDU, NULL, DDO, N, pszModality, pszStationName, pszSop, patid, NULL, 0, 0};
+ strcpy(cmd, line+5);
+ cmd[strlen(cmd)-1]=0;
+ do_lua(&(PDU->L), cmd, &sd);
+ rc = sd.rc;
+ if (rc==8)
+ { SystemDebug.printf("Exportconverter%d.%d: defer\n", N, part);
+ reset_queue_fails(N);
+ if (DDO) delete DDO;
+ return TRUE; // retry later
+ }
+ }
+
+ /* converter: ifnotempty "string" (only execute next converter if string not empty) */
+
+ else if (memicmp(line, "ifnotempty \"", 12)==0)
+ { char string[1024];
+ char *p;
+
+ strcpy(string, line+12);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+
+ int len = strlen(string);
+ if (len==0) rc = 4;
+ }
+ }
+
+ /* converter: ifempty "string" (only execute next converter if string empty) */
+
+ else if (memicmp(line, "ifempty \"", 9)==0)
+ { char string[1024];
+ char *p;
+
+ strcpy(string, line+9);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+
+ int len = strlen(string);
+ if (len!=0) rc = 4;
+ }
+ }
+
+ /* converter: ifequal "string1","string2" (only execute next converter if string1 equals string2) */
+
+ else if (memicmp(line, "ifequal \"", 9)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+9);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+ int cmp = strcmp(string, string2);
+ if (cmp!=0) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifnotequal "string1","string2" (only execute next converter if string1 not equals string2) */
+
+ else if (memicmp(line, "ifnotequal \"", 12)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+12);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+ int cmp = strcmp(string, string2);
+ if (cmp==0) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifmatch "string1","string2" (only execute next converter if string1 matches string2 - case insensitive) */
+
+ else if (memicmp(line, "ifmatch \"", 9)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+9);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+ if (!match(string, string2)) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifnotmatch "string1","string2" (only execute next converter if string1 not matches string2 - case insensitive) */
+
+ else if (memicmp(line, "ifnotmatch \"", 12)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+12);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+ if (match(string, string2)) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifnumequal "string1","string2" (only execute next converter if string1 num equals string2 - integer) */
+
+ else if (memicmp(line, "ifnumequal \"", 12)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+12);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+ if (atoi(string)!=atoi(string2)) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifnumnotequal "string1","string2" (only execute next converter if string1 num not equals string2 - integer) */
+
+ else if (memicmp(line, "ifnumnotequal \"", 15)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+15);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+ if (atoi(string)==atoi(string2)) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifnumgreater "string1","string2" (only execute next converter if string1 num greater than string2 num - integer) */
+
+ else if (memicmp(line, "ifnumgreater \"", 14)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+14);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+ if (atoi(string)<=atoi(string2)) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifnumless "string1","string2" (only execute next converter if string1 num less than string2 num - integer) */
+
+ else if (memicmp(line, "ifnumless \"", 11)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+11);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+ if (atoi(string)>=atoi(string2)) rc = 4;
+ }
+ }
+ }
+
+ /* converter: between "string1","string2" (execute next converter on time in hours: between "9", "17"; defer) */
+
+ else if (memicmp(line, "between \"", 9)==0)
+ { char string[1024];
+ char *p, *string2;
+ int h1, h2, h;
+ struct tm tmbuf;
+ time_t t = time(NULL);
+
+ localtime_r(&t, &tmbuf);
+ h = tmbuf.tm_hour;
+
+ strcpy(string, line+9);
+ h1 = atoi(string);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ h2 = atoi(string2);
+ SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+ if (h2>=h1 && (h <h1 || h>=h2)) rc = 4; // between "9", "17": skip if h<9 or h>=17
+ if (h2< h1 && (h <h1 && h>=h2)) rc = 4; // between "17", "9": skip if h<=17 and h>=9
+ }
+ }
+ }
+
+ /* converter: prefetch */
+
+ else if (memicmp(line, "prefetch", 8)==0)
+ { if (prefetch_queue("prefetch", patid, "", "", "", "", "", "", "", "", "", 0, ""))
+ OperatorConsole.printf("Exportconverter%d.%d: queued prefetch %s\n", N, part, patid);
+ }
+
+ /* converter: delayed "[forward|get] [patient|study|series|image] [after nn] [compressed as xx]
+ [date yyyymmdd-yyyymmdd] [now -ddd+ddd] [age -ddd+ddd]
+ [modality mm] [sop xxxx] [imagetype xxxx] [seriesdesc xxxx] [to/from AE]"
+ and: delayed "delete [patient|study|series|image] [date yyyymmdd-yyyymmdd] [now -ddd+ddd]
+ [age -ddd+ddd] [modality mm] [sop xxxx] [imagetype xxxx] [seriesdesc xxxx]"
+ and: delayed "process [patient|study|series|image] [by command]"
+ and: delayed "merge study [modality mm] [after nn]"
+
+ Will process data only from the current patient, but filters 'now, age, modality, sop, imagetype, seriesdesc'
+ will read from other studies and series
+ */
+
+ else if (memicmp(line, "forward patient ", 16)==0 ||
+ memicmp(line, "forward study ", 14)==0 ||
+ memicmp(line, "forward series ", 15)==0 ||
+ memicmp(line, "forward image ", 14)==0 ||
+ memicmp(line, "get patient ", 12)==0 ||
+ memicmp(line, "get study ", 10)==0 ||
+ memicmp(line, "get series ", 11)==0 ||
+ memicmp(line, "get image ", 10)==0 ||
+ memicmp(line, "delete patient ", 15)==0 ||
+ memicmp(line, "delete study ", 13)==0 ||
+ memicmp(line, "delete series ", 14)==0 ||
+ memicmp(line, "delete image ", 13)==0 ||
+ memicmp(line, "delete patient", 15)==0 ||
+ memicmp(line, "delete study", 12)==0 ||
+ memicmp(line, "delete series", 13)==0 ||
+ memicmp(line, "delete image", 12)==0 ||
+ memicmp(line, "process patient ", 16)==0 ||
+ memicmp(line, "process study ", 14)==0 ||
+ memicmp(line, "process series ", 15)==0 ||
+ memicmp(line, "process image ", 14)==0 ||
+ memicmp(line, "merge study ", 12)==0 ||
+ memicmp(line, "submit patient ", 15)==0 ||
+ memicmp(line, "submit study ", 13)==0 ||
+ memicmp(line, "submit series ", 14)==0 ||
+ memicmp(line, "submit image ", 13)==0 ||
+ memicmp(line, "submit2 patient ", 16)==0 ||
+ memicmp(line, "submit2 study ", 14)==0 ||
+ memicmp(line, "submit2 series ", 15)==0 ||
+ memicmp(line, "submit2 image ", 14)==0)
+ { char *p = strchr(line, ' ')+1; const char *compress="", *dest="", *date="", *modality="", *sop="", *imagetype="", *seriesdesc="", *script="";
+ char studyuid[65], seriesuid[65], vr[200], dat[200];
+ VR *pVR;
+ int len, delay=0;
+
+ studyuid[0]=0;
+ seriesuid[0]=0;
+
+ if (!DDO)
+ DDO = PDU2.LoadDICOMDataObject(pszFileName);
+
+ const char *level=p;
+ p = strchr(p, ' ');
+ while(p)
+ { *p=0;
+ p++;
+
+ if (memicmp(p, "compressed as ", 14)==0)
+ { compress = p+14;
+ p = strchr(p+14, ' ');
+ }
+ else if (memicmp(p, "to ", 3)==0)
+ { dest = p+3;
+ p = strchr(p+3, ' ');
+ }
+ else if (memicmp(p, "after ", 6)==0)
+ { delay = atoi(p+6);
+ p = strchr(p+6, ' ');
+ }
+ else if (memicmp(p, "by ", 3)==0)
+ { dest = p+3;
+ p = NULL; // strchr(p+3, ' ');
+ }
+ else if (memicmp(p, "from ", 5)==0)
+ { dest = p+5;
+ p = strchr(p+5, ' ');
+ }
+ else if (memicmp(p, "date ", 5)==0) // all series date yyyymmdd or yyyymmdd-yyyymmdd
+ { date = p+5;
+ p = strchr(p+5, ' ');
+ level = "selection"; // causes that no study or series UID are passed to query
+ }
+ else if (memicmp(p, "now ", 4)==0) // now -365+365: within one year from now (+/- compulsory)
+ { struct tm tmbuf1, tmbuf2; // also works on all series within date range
+ char *q;
+ int from=0, to=0;
+ from=atoi(p+4);
+ q = strchr(p+5, '+'); if (!q) q = strchr(p+5, '-'); if (q) to=atoi(q);
+
+ time_t t1 = time(NULL)+24*3600*from;
+ time_t t2 = time(NULL)+24*3600*to;
+ localtime_r(&t1, &tmbuf1);
+ localtime_r(&t2, &tmbuf2);
+
+ sprintf(dat, "%04d%02d%02d-%04d%02d%02d", tmbuf1.tm_year+1900, tmbuf1.tm_mon, tmbuf1.tm_mday, tmbuf2.tm_year+1900, tmbuf2.tm_mon, tmbuf2.tm_mday);
+ date = dat;
+
+ p = strchr(p+4, ' ');
+ level = "selection"; // causes that no study or series UID passed to query
+ }
+ else if (memicmp(p, "age ", 4)==0) // age -365+365: within one year from series date (+/- compulsory)
+ { struct tm tmbuf1, tmbuf2; // also works on all series within date range
+ char *q;
+ int from=0, to=0;
+ from=atoi(p+4);
+ q = strchr(p+5, '+'); if (!q) q = strchr(p+5, '-'); if (q) to=atoi(q);
+
+ SearchDICOMObject(DDO, "0008,0020", dat);
+ memset(&tmbuf1, 0, sizeof(tmbuf1));
+ sscanf(dat, "%04d%02d%02d", &tmbuf1.tm_year, &tmbuf1.tm_mon, &tmbuf1.tm_mday);
+ tmbuf1.tm_year -= 1900;
+
+ time_t t = mktime(&tmbuf1);
+ time_t t1 = t+24*3600*from;
+ time_t t2 = t+24*3600*to;
+ localtime_r(&t1, &tmbuf1);
+ localtime_r(&t2, &tmbuf2);
+
+ sprintf(dat, "%04d%02d%02d-%04d%02d%02d", tmbuf1.tm_year+1900, tmbuf1.tm_mon, tmbuf1.tm_mday, tmbuf2.tm_year+1900, tmbuf2.tm_mon, tmbuf2.tm_mday);
+ date = dat;
+
+ p = strchr(p+4, ' ');
+ level = "selection"; // causes that no study or series UID passed to query
+ }
+ else if (memicmp(p, "modality ", 9)==0)
+ { modality = p+9;
+ p = strchr(p+9, ' ');
+ level = "selection"; // causes that no study or series UID is passed to query
+ }
+ else if (memicmp(p, "sop ", 4)==0)
+ { sop = p+4;
+ p = strchr(p+4, ' ');
+ level = "selection"; // causes that no study or series UID is passed to query except the given SOP
+ }
+ else if (memicmp(p, "imagetype ", 10)==0)
+ { imagetype = p+10;
+ p = strchr(p+10, ' ');
+ level = "study"; // causes that no series UID is passed to query
+ }
+ else if (memicmp(p, "target ", 7)==0) // for DcmSubmit only
+ { imagetype = p+7;
+ p = strchr(p+7, ' ');
+ }
+ else if (memicmp(p, "seriesdesc ", 11)==0)
+ { seriesdesc = p+11;
+ p = strchr(p+11, ' ');
+ level = "study"; // causes that no series UID is passed to query
+ }
+ else if (memicmp(p, "password ", 9)==0) // for submit only
+ { seriesdesc = p+9;
+ p = strchr(p+9, ' ');
+ }
+ else if (memicmp(p, "command ", 8)==0) // for submit2 only
+ { seriesdesc = p+8;
+ p = strchr(p+8, ' ');
+ }
+ else if (memicmp(p, "script \"", 8)==0)
+ { if (p[strlen(p)-1]=='"') p[strlen(p)-1]=0;
+ script = p+8; // must be last parameter
+ p = NULL;
+ break;
+ }
+ else if (memicmp(p, "script ", 7)==0) // script without ""
+ { script = p+7; // must be last parameter
+ p = NULL;
+ break;
+ }
+ else if (memicmp(p, "series ", 7)==0)
+ { char *a=p+7;
+ p = strchr(p+7, ' ');
+ *p=0;
+ strcpy(seriesuid, a);
+ level = "selection"; // causes that no study UID is passed and given series
+ }
+ else if (memicmp(p, "study ", 6)==0)
+ { char *a=p+6;
+ p = strchr(p+6, ' ');
+ *p=0;
+ strcpy(studyuid, a);
+ level = "selection"; // causes that no series UID is passed and give study
+ }
+ }
+
+ if (DDO)
+ { pVR = DDO->GetVR(0x0020, 0x000d);
+ if (pVR && (memicmp(level, "stu", 3)==0 || memicmp(level, "ser", 3)==0) || memicmp(level, "ima", 3)==0)
+ { strncpy(vr, (char*)pVR->Data, pVR->Length);
+ vr[pVR->Length] = 0;
+ len = pVR->Length - 1;
+ while(len>0)
+ { if (vr[len] == ' ')
+ vr[len] = 0;
+ else
+ break;
+ len--;
+ }
+ strcpy(studyuid, vr);
+ }
+
+ pVR = DDO->GetVR(0x0020, 0x000e);
+ if (pVR && (memicmp(level, "ser", 3)==0 || memicmp(level, "ima", 3)==0))
+ { strncpy(vr, (char*)pVR->Data, pVR->Length);
+ vr[pVR->Length] = 0;
+ len = pVR->Length - 1;
+ while(len>0)
+ { if (vr[len] == ' ')
+ vr[len] = 0;
+ else
+ break;
+ len--;
+ }
+ strcpy(seriesuid, vr);
+ }
+
+ pVR = DDO->GetVR(0x0008, 0x0018);
+ if (pVR && memicmp(level, "ima", 3)==0)
+ { strncpy(vr, (char*)pVR->Data, pVR->Length);
+ vr[pVR->Length] = 0;
+ len = pVR->Length - 1;
+ while(len>0)
+ { if (vr[len] == ' ')
+ vr[len] = 0;
+ else
+ break;
+ len--;
+ }
+ sop = vr;
+ }
+ }
+
+ line[11]=0;
+ if (sop) level = "single object";
+ if (DDO)
+ if (prefetch_queue(line, patid, dest, studyuid, seriesuid, compress, modality, date, sop, imagetype, seriesdesc, delay, script))
+ OperatorConsole.printf("Exportconverter%d.%d: queued %s - (%s %s %s of %s) to %s\n", N, part, line, level, modality, date, patid, dest);
+ }
+
+ /* converter: preretrieve */
+
+ else if (memicmp(line, "preretrieve ", 12)==0)
+ { if (prefetch_queue("preretrieve", patid, line+12, "", "", "", "", "", "", "", "", 0, ""))
+ OperatorConsole.printf("Exportconverter%d.%d: queued preretrieve of patient %s from %s\n", N, part, patid, line+12);
+ }
+
+ /* converter: system (command line can be generated using all % tricks) */
+
+ else if (memicmp(line, "system ", 7)==0)
+ { char cline[512];
+ strcpy(cline, line+7);
+ system(cline);
+ //BackgroundExec(cline, "");
+ SystemDebug.printf("Exportconverter%d.%d: %s\n", N, part, line);
+ }
+
+ /* converter: mkdir (command line can be generated using all % tricks) */
+
+ else if (memicmp(line, "mkdir ", 6)==0)
+ { char cline[512], s[512];
+ strcpy(cline, line+6);
+ for (int sIndex = 0; sIndex<=strlen(cline); sIndex++)
+ if (cline[sIndex]==PATHSEPCHAR)
+ { strcpy(s, cline);
+ s[sIndex]='\0';
+ mkdir(s);
+ }
+ mkdir(cline); // 20120829
+ SystemDebug.printf("Exportconverter%d.%d: %s\n", N, part, line);
+ }
+
+ /* converter: rm (command line can be generated using all % tricks) */
+
+ else if (memicmp(line, "rm ", 3)==0)
+ { char cline[512];
+ strcpy(cline, line+3);
+ unlink(cline);
+ SystemDebug.printf("Exportconverter%d.%d: %s\n", N, part, line);
+ }
+
+ else if (memicmp(line, "testmode ", 9)==0)
+ { OperatorConsole.printf("Exportconverter%d.%d: sets testmode to %s\n", N, part, patid, line+9);
+ strcpy(TestMode, line+9);
+ }
+
+ /* converter: nop with % item */
+
+ else if (memicmp(line, "nop", 3)==0)
+ { OperatorConsole.printf("Exportconverter%d.%d: %s\n", N, part, line);
+ }
+
+ else if (memicmp(line, "stop", 4)==0)
+ { SystemDebug.printf("Exportconverter%d.%d: stop\n", N, part);
+ rc = 3;
+ }
+
+ else if (memicmp(line, "return", 6)==0)
+ { SystemDebug.printf("Exportconverter%d.%d: return\n", N, part);
+ rc = 5;
+ }
+
+ else if (memicmp(line, "call ", 5)==0)
+ { FILE *f;
+ int ret;
+ char cmd[1024];
+
+ if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName);
+
+ cmd[0]=0;
+ MyGetPrivateProfileString ( "scripts", line+5, cmd, cmd, 1024, ConfigFile);
+ if (*cmd)
+ ret = CallImportConverterN(DDO, -1, NULL, NULL, NULL, NULL, PDU, NULL, cmd);
+ else
+ { f = fopen(line+5, "rt");
+ if (f)
+ { SystemDebug.printf("%sconverter%d.%d: %s\n", "Export", N, part, line);
+ while(fgets(cmd, sizeof(cmd), f) != NULL)
+ { if (cmd[strlen(cmd)-1]=='\n') cmd[strlen(cmd)-1]=0;
+ if (cmd[0]!='#' && cmd[0]!=';')
+ { // ret = CallImportConverterN(DDO, -1, NULL, NULL, NULL, NULL, NULL, NULL, Storage, cmd, vars);
+ ret = CallImportConverterN(DDO, -1, NULL, NULL, NULL, NULL, PDU, NULL, cmd);
+ if (ret==5 || ret==2 || ret==6) break; // return or destroy or reject
+ }
+ }
+ fclose(f);
+ }
+ else
+ OperatorConsole.printf("*** %sconverter%d.%d script not found: %s\n", "Export", N, part, line+5);
+ }
+ rc = ret;
+ }
+
+ else if (memicmp(line, "silentstop", 10)==0)
+ { rc = 3;
+ }
+
+ else if (memicmp(line, "defer", 5)==0)
+ { SystemDebug.printf("Exportconverter%d.%d: defer\n", N, part);
+ reset_queue_fails(N);
+ if (DDO) delete DDO;
+ return TRUE; // retry later
+ }
+
+ /* converter: prefetch */
+
+ else if (memicmp(line, "prefetch", 8)==0)
+ { if (prefetch_queue("prefetch", patid, "", "", "", "", "", "", "", "", "", 0, ""))
+ OperatorConsole.printf("Exportconverter%d.%d: queued prefetch %s\n", N, part, patid);
+ }
+
+ /* default: execute the command */
+
+ else if (strchr(szExecName, '%'))
+ {
+ OperatorConsole.printf("Exportconverter%d.%d executes: %s\n", N, part, line);
+
+ #ifdef WIN32
+ WinExec(line, SW_MINIMIZE);
+ #else
+ // char *s=strchr(line, ' ');
+ // *s=0;
+ // BackgroundExec(line, s+1);
+ system(line);
+ #endif
+ ImagesExported++;
+ }
+
+ /* for backwards compatibility: execute executable with single parameter */
+
+ else
+#ifdef WIN32
+ { int r = spawnlpe(_P_WAIT, szExecName,
+ szExecName, /* argv[0] */
+ pszFileName, /* argv[1] */
+ NULL, /* Allways NULL */
+ NULL); /* Environment */
+ if (r == -1)
+ OperatorConsole.printf("***Exportconverter%d: Spawning '%s' failed (argv=%s)\n", N, szExecName, pszFileName);
+ ImagesExported++;
+ }
+#else
+ // BackgroundExec(szExecName, pszFileName);
+ { char line1[1000];
+ sprintf(line1, "%s %s", szExecName, pszFileName);
+ system(line1);
+ ImagesExported++;
+ }
+#endif
+ }
+
+ // process next command
+ if (szNext[0]==0) break;
+ strcpy(szExecName, szNext);
+ part++;
+
+ if (rc==3 || rc==5) break;
+ }
+
+ if (DDO) delete DDO;
+ return FALSE;
+}
+
+/*
+void CallExportConverters(char *pszFileName, char *pszModality, char *pszStationName, char *pszSop, char *patid, char *calling, char *called)
+{ char szRootSC[64];
+ char szTemp[32];
+ int i, iNbConverters;
+
+ if (!MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig,
+ szRootSC, 64, ConfigFile)) return;
+ if (!MyGetPrivateProfileString(szRootSC, "ExportConverters", "0",
+ szTemp, 128, ConfigFile)) return;
+ iNbConverters = atoi(szTemp);
+ if (iNbConverters>MAXExportConverters) iNbConverters=MAXExportConverters;
+
+ // Loop over all converters
+ for(i=0; i<iNbConverters; i++)
+ CallExportConverterN(pszFileName, i, pszModality, pszStationName, pszSop, patid, calling, called, NULL, NULL);
+}
+*/
+
+static BOOL SendServerCommand(const char *NKIcommand1, const char *NKIcommand2, int con, char *buf=NULL, BOOL html=TRUE, BOOL upload=FALSE);
+
+#ifndef VirtualQuery
+int VirtualQuery(DICOMDataObject *DDO, const char *Level, int N, Array < DICOMDataObject *> *pADDO, char *ae=NULL);
+#endif
+
+/////////////////////////////////////////////////////////////////////////////////////////////////
+// lua integration
+/////////////////////////////////////////////////////////////////////////////////////////////////
+
+char *heapinfo( void );
+static BOOL DcmMove2(char* pszSourceAE, const char* pszDestinationAE, BOOL patroot, int id, DICOMDataObject *DDO, const char *callback);
+DICOMDataObject *dummyddo;
+
+#include "lua.hpp"
+
+extern "C"
+{ struct scriptdata *getsd(lua_State *L)
+ { lua_getglobal(L, "scriptdata");
+ struct scriptdata *sd = (struct scriptdata *)lua_topointer(L, -1);
+ lua_pop(L, 1);
+ return sd;
+ }
+ static void luaCreateObject(lua_State *L, DICOMDataObject *pDDO, Array < DICOMDataObject *> *A, BOOL owned);
+
+ static int _luaprint(lua_State *L, Debug *d)
+ { int i, n=lua_gettop(L);
+ char text[2000]; text[0]=0;
+ for (i=1; i<=n; i++)
+ { if (i>1) sprintf(text + strlen(text), "\t");
+ if (lua_isstring(L,i)) sprintf(text + strlen(text), "%s",lua_tostring(L,i));
+ else if (lua_isnil(L,i)) sprintf(text + strlen(text), "%s","nil");
+ else if (lua_isboolean(L,i)) sprintf(text + strlen(text), "%s",lua_toboolean(L,i) ? "true" : "false");
+ else sprintf(text + strlen(text), "%s:%p",luaL_typename(L,i),lua_topointer(L,i));
+ }
+ d->printf("%s\n", text);
+ return 0;
+ }
+ static int luaprint(lua_State *L) { return _luaprint(L, &OperatorConsole); }
+ static int luadebuglog(lua_State *L) { return _luaprint(L, &SystemDebug); }
+ static int luaservercommand(lua_State *L)
+ { int n=lua_gettop(L);
+ char buf[2000];
+ buf[0]=0;
+ if (lua_isstring(L,1)) SendServerCommand("", lua_tostring(L,1), 0, buf);
+ if (buf[0]) { lua_pushstring(L, buf); return 1; }
+ return 0;
+ }
+ static int luadictionary(lua_State *L)
+ { if (lua_gettop(L)==2)
+ { int g = lua_tointeger(L,1);
+ int e = lua_tointeger(L,2);
+ char s[256]; s[0] = '\0';
+ if (VRType.RunTimeClass(g, e, s))
+ { lua_pushstring(L, s);
+ return 1;
+ }
+ }
+ else if (lua_gettop(L)==1)
+ { RTCElement Entry;
+ char s[256];
+ strcpy(s, lua_tostring(L, 1));
+ Entry.Description = s;
+ if (VRType.GetGroupElement(&Entry))
+ { lua_pushinteger(L, Entry.Group);
+ lua_pushinteger(L, Entry.Element);
+ return 2;
+ }
+ }
+ return 0;
+ }
+ static int luachangeuid(lua_State *L)
+ { if (lua_gettop(L)==1)
+ { char from[256], to [256];
+ strcpy(from, lua_tostring(L, 1));
+ if (ChangeUID(from, "lua", to))
+ { lua_pushstring(L, to);
+ return 1;
+ }
+ }
+ if (lua_gettop(L)==2)
+ { char from[256], to[256], result[256];
+ strcpy(from, lua_tostring(L, 1));
+ strcpy(to, lua_tostring(L, 2));
+ if (ChangeUIDTo(from, "lua", to))
+ { lua_pushstring(L, to);
+ return 1;
+ }
+ }
+ lua_pushnil(L);
+ return 1;
+ }
+ static int luachangeuidback(lua_State *L)
+ { if (lua_gettop(L)==1)
+ { char from[256], to [256];
+ strcpy(from, lua_tostring(L, 1));
+ if (ChangeUIDBack(from, to))
+ { lua_pushstring(L, to);
+ return 1;
+ }
+ }
+ lua_pushnil(L);
+ return 1;
+ }
+ static int luacrc(lua_State *L)
+ { if (lua_gettop(L)==1)
+ { char from[256];
+ strcpy(from, lua_tostring(L, 1));
+ unsigned int crc = ComputeCRC(from, strlen(from));
+ sprintf(from, "%u", crc);
+ lua_pushstring(L, from);
+ return 1;
+ }
+ lua_pushnil(L);
+ return 1;
+ }
+ static int luagenuid(lua_State *L)
+ { char n[80];
+ GenUID(n);
+ lua_pushstring(L, n);
+ return 1;
+ }
+ static int luascript(lua_State *L)
+ { struct scriptdata *sd = getsd(L);
+ int n=lua_gettop(L);
+ char cmd[2000]="";
+ DICOMDataObject *pDDO;
+ pDDO = sd->DDO;
+ if (n>0)
+ { if (lua_isuserdata(L, 1))
+ { lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "DDO"); pDDO = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+ }
+ else if (lua_isstring(L,1))
+ strcpy(cmd, lua_tostring(L,1));
+ }
+ if (n>1 && lua_isstring(L,2))
+ strcpy(cmd, lua_tostring(L,2));
+ sd->rc = CallImportConverterN(pDDO, -1, sd->pszModality, sd->pszStationName, sd->pszSop, sd->patid, sd->PDU, sd->Storage, cmd);
+ return 0;
+ }
+ static int luaget_amap(lua_State *L)
+ { int r = lua_tointeger(L, 1);
+ if (r < ACRNemaAddressArray.GetSize())
+ { ACRNemaAddress *AAPtr = ACRNemaAddressArray.Get(r);
+ lua_pushstring(L, AAPtr->Name);
+ lua_pushstring(L, AAPtr->IP);
+ lua_pushstring(L, AAPtr->Port);
+ lua_pushstring(L, AAPtr->Compress);
+ return 4;
+ }
+ return 0;
+ }
+ static int luaget_sqldef(lua_State *L)
+ { int r = lua_tointeger(L, 1);
+ int s = lua_tointeger(L, 2);
+ DBENTRY *DBE = NULL;
+ if (r==0) DBE = PatientDB;
+ if (r==1) DBE = StudyDB;
+ if (r==2) DBE = SeriesDB;
+ if (r==3) DBE = ImageDB;
+ if (r==4) DBE = WorkListDB;
+ if (DBE)
+ { if (DBE[s].Group)
+ { lua_pushinteger(L, DBE[s].Group);
+ lua_pushinteger(L, DBE[s].Element);
+ lua_pushstring(L, DBE[s].SQLColumn);
+ lua_pushinteger(L, DBE[s].SQLLength);
+ lua_pushstring(L, SQLTypeSymName(DBE[s].SQLType));
+ lua_pushstring(L, DICOMTypeSymName(DBE[s].DICOMType));
+ return 6;
+ }
+ }
+ return 0;
+ }
+ static int luadbquery(lua_State *L)
+ { unsigned int i, N, flds=1;
+ const char *items[4];
+ SQLLEN SQLResultLength;
+ for (i=0; i<4; i++) items[i]=lua_tostring(L,i+1);
+ if (items[1]) for (i=0; i<strlen(items[1]); i++) if (items[1][i]==',') flds++;
+ if (items[2]) if (*items[2]==0) items[2]=NULL;
+ if (items[3]) if (*items[3]==0) items[3]=NULL;
+ if (items[4]) if (*items[4]==0) items[4]=NULL;
+
+ Database DB;
+ if (DB.Open ( DataSource, UserName, Password, DataHost ) )
+ { char fld[48][256]; memset(fld, 0, sizeof(fld));
+ DB.Query(items[0], items[1], items[2], items[3]);
+ for (i=0; i<flds; i++) DB.BindField (i+1, SQL_C_CHAR, fld[i], 255, &SQLResultLength);
+ N = 1; lua_newtable(L);
+ while (DB.NextRecord())
+ { lua_newtable(L);
+ for (i=0; i<flds; i++) { lua_pushstring(L, fld[i]); lua_rawseti(L, -2, i+1); }
+ lua_rawseti(L, -2, N++);
+ memset(fld, 0, sizeof(fld));
+ }
+ DB.Close();
+ QueryFromGui++;
+ return 1;
+ }
+ return 0;
+ }
+ static int luasql(lua_State *L)
+ { const char *sql = lua_tostring(L,1);
+ BOOL f;
+
+ Database DB;
+ if (DB.Open ( DataSource, UserName, Password, DataHost ) )
+ { f = DB.Exec(sql);
+ DB.Close();
+ QueryFromGui++;
+ }
+ if (f)
+ { lua_pushinteger(L, 1);
+ return 1;
+ }
+ else
+ return 0;
+ }
+ static int luadicomquery(lua_State *L)
+ { const char *ae = lua_tostring(L,1);
+ const char *level = lua_tostring(L,2);
+ if (lua_isuserdata(L, 3))
+ { DICOMDataObject *O = NULL;
+ lua_getmetatable(L, 3);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+ Array < DICOMDataObject * > *A = new Array < DICOMDataObject * >;
+ luaCreateObject(L, NULL, A, TRUE);
+ if (O)
+ { DICOMDataObject *P = MakeCopy(O);
+ VirtualQuery(P, level, 0, A, (char *)ae);
+ delete P;
+ }
+ return 1;
+ }
+ return 0;
+ }
+ static int luadicommove(lua_State *L)
+ { const char *source = lua_tostring(L,1);
+ const char *dest = lua_tostring(L,2);
+ if (lua_isuserdata(L, 3))
+ { DICOMDataObject *O = NULL;
+ lua_getmetatable(L, 3);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+ if (O)
+ { DICOMDataObject *P = MakeCopy(O);
+ DcmMove2((char *)source, dest, lua_tointeger(L,4), 0x555, P, lua_tostring(L,5));
+ delete P;
+ }
+ }
+ return 0;
+ }
+ static int luadicomdelete(lua_State *L)
+ { if (lua_isuserdata(L, 1))
+ { DICOMDataObject *O = NULL;
+ lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+ Array < DICOMDataObject * > *A = new Array < DICOMDataObject * >;
+ luaCreateObject(L, NULL, A, TRUE);
+ if (O)
+ { DICOMDataObject *P = MakeCopy(O);
+ RemoveFromPACS(P, FALSE);
+ delete P;
+ }
+ return 1;
+ }
+ return 0;
+ }
+
+ static int getptr(lua_State *L, unsigned int *ptr, int *veclen, int *bytes, int *count, int *step, VR **vr, int mode)
+ { struct scriptdata *sd = getsd(L); //mode:0,1,2,3=pixel,row,col,image
+ int pars=lua_gettop(L), n, x=0, y=0, z=0, rows, cols, frames, vec;
+ Array < DICOMDataObject *> *pADDO;
+ DICOMDataObject *pDDO;
+ *veclen = 0;
+ n=1;
+ pDDO = sd->DDO;
+
+ if (pars>0)
+ { if (lua_isuserdata(L, n))
+ { lua_getmetatable(L, n);
+ lua_getfield(L, -1, "DDO"); pDDO = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+ n++; pars--;
+ }
+ }
+
+ if (pars>0 && (mode==0 || mode==2)) x = lua_tointeger(L,n++), pars--;
+ if (pars>0 && (mode==0 || mode==1)) y = lua_tointeger(L,n++), pars--;
+ if (pars>0 ) z = lua_tointeger(L,n++), pars--;
+
+ vec = pDDO->GetUINT16(0x0028,0x0002);
+ rows = pDDO->GetUINT16(0x0028, 0x0010); if (!rows) return 0;
+ cols = pDDO->GetUINT16(0x0028, 0x0011); if (!cols) return 0;
+ if (pDDO->GetUINT16(0x0028, 0x0006)>1) return 0;
+ frames= pDDO->Getatoi(0x0028, 0x0008);
+ *bytes = (pDDO->GetUINT16(0x0028, 0x0101)+7)/8;
+ *ptr = (y * cols + x) * vec;
+ DecompressNKI(pDDO);
+ *vr = pDDO->GetVR(0x7fe0, 0x0010); if (!vr) return 0;
+ pADDO = (Array<DICOMDataObject*>*)(*vr)->SQObjectArray;
+ if (pADDO==NULL)
+ { *ptr += z*rows * cols * vec;
+ if (*ptr * *bytes > (*vr)->Length) return 0;
+ }
+ else
+ { if (z>=pADDO->GetSize()-1) return 0;
+ *vr = pADDO->Get(z+1)->GetVR(0x7fe0, 0x0010);
+ if (*ptr * *bytes > (*vr)->Length) return 0;
+ }
+ if (mode!=2) *step = 1; else *step = cols;
+ if (mode>=2) *count= rows; else *count = cols;
+ if (mode==3) *count *= cols;
+ *veclen = vec;
+ return n;
+ }
+ static int luagetpixel(lua_State *L)
+ { int veclen, count, step, bytes;
+ unsigned int ptr;
+ VR *vr;
+ getptr(L, &ptr, &veclen, &bytes, &count, &step, &vr, 0);
+ if (veclen==0) return 0;
+ switch(bytes)
+ { case 1: for (int i=0; i<veclen; i++) lua_pushinteger(L, *((BYTE *)(vr->Data)+ptr+i*step)); break;
+ case 2: for (int i=0; i<veclen; i++) lua_pushinteger(L, *((UINT16 *)(vr->Data)+ptr+i*step)); break;
+ case 4: for (int i=0; i<veclen; i++) lua_pushinteger(L, *((INT32 *)(vr->Data)+ptr+i+step)); break;
+ default:for (int i=0; i<veclen; i++) lua_pushinteger(L, 0); break;
+ }
+ return veclen;
+ }
+ static int luasetpixel(lua_State *L)
+ { int pars=lua_gettop(L), veclen, count, step, bytes, n;
+ unsigned int ptr;
+ VR *vr;
+ n=getptr(L, &ptr, &veclen, &bytes, &count, &step, &vr, 0);
+ if (veclen==0) return 0;
+ if (veclen>pars-n+1) veclen=pars-n+1;
+ switch(bytes)
+ { case 1: for (int i=0; i<veclen; i++) *((BYTE *)(vr->Data)+ptr+i*step) = lua_tointeger(L,n++); break;
+ case 2: for (int i=0; i<veclen; i++) *((UINT16 *)(vr->Data)+ptr+i*step) = lua_tointeger(L,n++); break;
+ case 4: for (int i=0; i<veclen; i++) *((INT32 *)(vr->Data)+ptr+i*step) = lua_tointeger(L,n++); break;
+ }
+ return 0;
+ }
+ static int luagetrow(lua_State *L)
+ { int veclen, count, step, bytes;
+ unsigned int ptr;
+ VR *vr;
+ getptr(L, &ptr, &veclen, &bytes, &count, &step, &vr, 1);
+ if (veclen==0) return 0;
+ lua_newtable(L);
+ for(int x=0; x<count; x++)
+ { switch(bytes)
+ { case 1: for (int i=0; i<veclen; i++) {lua_pushinteger(L, *((BYTE *)(vr->Data)+ptr+i)); lua_rawseti(L, -2, x*veclen+i);} break;
+ case 2: for (int i=0; i<veclen; i++) {lua_pushinteger(L, *((UINT16 *)(vr->Data)+ptr+i)); lua_rawseti(L, -2, x*veclen+i);} break;
+ case 4: for (int i=0; i<veclen; i++) {lua_pushinteger(L, *((INT32 *)(vr->Data)+ptr+i)); lua_rawseti(L, -2, x*veclen+i);} break;
+ }
+ ptr += step*veclen;
+ }
+ return 1;
+ }
+ static int luagetcolumn(lua_State *L)
+ { int veclen, count, step, bytes;
+ unsigned int ptr;
+ VR *vr;
+ getptr(L, &ptr, &veclen, &bytes, &count, &step, &vr, 2);
+ if (veclen==0) return 0;
+ lua_newtable(L);
+ for(int x=0; x<count; x++)
+ { switch(bytes)
+ { case 1: for (int i=0; i<veclen; i++) {lua_pushinteger(L, *((BYTE *)(vr->Data)+ptr+i)); lua_rawseti(L, -2, x*veclen+i);} break;
+ case 2: for (int i=0; i<veclen; i++) {lua_pushinteger(L, *((UINT16 *)(vr->Data)+ptr+i)); lua_rawseti(L, -2, x*veclen+i);} break;
+ case 4: for (int i=0; i<veclen; i++) {lua_pushinteger(L, *((INT32 *)(vr->Data)+ptr+i)); lua_rawseti(L, -2, x*veclen+i);} break;
+ }
+ ptr += step*veclen;
+ }
+ return 1;
+ }
+ static int luasetrow(lua_State *L)
+ { int pars=lua_gettop(L), veclen, count, step, bytes, n;
+ unsigned int ptr;
+ VR *vr;
+ n=getptr(L, &ptr, &veclen, &bytes, &count, &step, &vr, 1);
+ if (veclen==0 || n>pars) return 0;
+ for(int x=0; x<count; x++)
+ { switch(bytes)
+ { case 1: for (int i=0; i<veclen; i++) {lua_rawgeti(L, pars, x*veclen+i); *((BYTE *)(vr->Data)+ptr+i) = lua_tointeger(L,-1); lua_pop(L, 1); } break;
+ case 2: for (int i=0; i<veclen; i++) {lua_rawgeti(L, pars, x*veclen+i); *((UINT16 *)(vr->Data)+ptr+i) = lua_tointeger(L,-1); lua_pop(L, 1); } break;
+ case 4: for (int i=0; i<veclen; i++) {lua_rawgeti(L, pars, x*veclen+i); *((INT32 *)(vr->Data)+ptr+i) = lua_tointeger(L,-1); lua_pop(L, 1); } break;
+ }
+ ptr += step*veclen;
+ }
+ return 0;
+ }
+ static int luasetcolumn(lua_State *L)
+ { int pars=lua_gettop(L), veclen, count, step, bytes, n;
+ unsigned int ptr;
+ VR *vr;
+ n=getptr(L, &ptr, &veclen, &bytes, &count, &step, &vr, 2);
+ if (veclen==0 || n>pars) return 0;
+ for(int x=0; x<count; x++)
+ { switch(bytes)
+ { case 1: for (int i=0; i<veclen; i++) {lua_rawgeti(L, pars, x*veclen+i); *((BYTE *)(vr->Data)+ptr+i) = lua_tointeger(L,-1); lua_pop(L, 1); } break;
+ case 2: for (int i=0; i<veclen; i++) {lua_rawgeti(L, pars, x*veclen+i); *((UINT16 *)(vr->Data)+ptr+i) = lua_tointeger(L,-1); lua_pop(L, 1); } break;
+ case 4: for (int i=0; i<veclen; i++) {lua_rawgeti(L, pars, x*veclen+i); *((INT32 *)(vr->Data)+ptr+i) = lua_tointeger(L,-1); lua_pop(L, 1); } break;
+ }
+ ptr += step*veclen;
+ }
+ return 0;
+ }
+ static int luagetimage(lua_State *L)
+ { int veclen, count, step, bytes;
+ unsigned int ptr;
+ VR *vr;
+ getptr(L, &ptr, &veclen, &bytes, &count, &step, &vr, 3);
+ if (veclen==0) return 0;
+ lua_pushlstring(L, (char *)(vr->Data)+ptr, count*bytes);
+ return 1;
+ }
+ static int luasetimage(lua_State *L)
+ { int pars=lua_gettop(L), veclen, count, step, bytes, n;
+ size_t len; unsigned int ptr;
+ VR *vr; const char *data;
+ n=getptr(L, &ptr, &veclen, &bytes, &count, &step, &vr, 3);
+ if (veclen==0 || n>pars) return 0;
+ data = lua_tolstring (L, n, &len);
+ if (data && vr->Length!=count*bytes)
+ vr->ReAlloc(count*bytes);
+ if (data && len==count*bytes)
+ memcpy((BYTE *)(vr->Data)+ptr, (BYTE *)data, len);
+ else if (data && bytes==2 && len==2*count*bytes)
+ { float scale=0;
+ if(pars>n) scale=lua_tonumber(L, n+1);
+ else scale = 1;
+ for(int i=0; i<count; i++)
+ ((short *)(vr->Data))[i] = scale * ((float *)data)[i];
+ }
+ else
+ { luaL_error(L, "Failed to set image, data and image dimensions incompatible");
+ }
+ return 0;
+ }
+
+ // getvr(Object, group, element) returns table for normal VR, addo for sequence
+ static int luagetvr(lua_State *L)
+ { VR *vr;
+ if (lua_isuserdata(L,1))
+ { DICOMDataObject *O = NULL;
+ lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+ int g = lua_tointeger(L,2);
+ int e = lua_tointeger(L,3);
+ int b = lua_toboolean(L,4);
+ vr = O->GetVR(g, e);
+ if (vr)
+ { if (vr->SQObjectArray)
+ luaCreateObject(L, NULL, (Array < DICOMDataObject * > *)vr->SQObjectArray, FALSE);
+ else if (b==0)
+ { lua_newtable(L);
+ for(int i=0; i<vr->Length; i++)
+ { lua_pushinteger(L, *((BYTE *)(vr->Data)+i)); lua_rawseti(L, -2, i);
+ }
+ }
+ else
+ { lua_pushlstring(L, (char *)(vr->Data), vr->Length);
+ }
+ return 1;
+ }
+ }
+ return 0;
+ }
+ // setvr(Object, group, element, data); if data is a table sets a simple VR, if it is an ADDO sets a sequence
+ static int luasetvr(lua_State *L)
+ { VR *vr;
+ if (lua_isuserdata(L,1))
+ { DICOMDataObject *O = NULL;
+ Array < DICOMDataObject * > *A = NULL;
+ lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+ int g = lua_tointeger(L,2);
+ int e = lua_tointeger(L,3);
+ if (lua_isuserdata(L, 4) && O)
+ { lua_getmetatable(L, 4);
+ lua_getfield(L, -1, "ADDO"); A = (Array < DICOMDataObject * > *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+ if (A)
+ { vr = new VR(g, e, 0, (void *) NULL, FALSE);
+ O->DeleteVR(vr);
+ delete vr;
+ vr = new VR(g, e, 0, (void *) NULL, FALSE);
+ Array < DICOMDataObject * > *SQE = new Array <DICOMDataObject *>;
+ for (int j=0; j<A->GetSize(); j++)
+ { DICOMDataObject *dd = MakeCopy(A->Get(j));
+ SQE->Add(dd);
+ }
+ vr->SQObjectArray = SQE;
+ O->Push(vr);
+ }
+ }
+ else if (lua_istable(L, 4) && O)
+ { int llen;
+ vr = O->GetVR(g, e);
+ if (!vr)
+ { vr = new VR(g, e, 0, (void *) NULL, FALSE);
+ O->Push(vr);
+ }
+#ifdef LUA_5_2
+ llen = lua_rawlen(L, 4);
+#else
+ llen = lua_objlen(L, 4);
+#endif
+ vr->ReAlloc(llen+1);
+ for(int i=0; i<=lua_objlen(L, 4); i++)
+ { lua_rawgeti(L, 4, i); *((BYTE *)(vr->Data)+i) = lua_tointeger(L,-1); lua_pop(L, 1);
+ }
+ }
+ else if (lua_isstring(L, 4) && O)
+ { size_t llen;
+ const char *data;
+ vr = O->GetVR(g, e);
+ if (!vr)
+ { vr = new VR(g, e, 0, (void *) NULL, FALSE);
+ O->Push(vr);
+ }
+ data = lua_tolstring (L, 4, &llen);
+ vr->ReAlloc(llen);
+ if (data && llen) memcpy((BYTE *)(vr->Data), (BYTE *)data, llen);
+ }
+ }
+ return 0;
+ }
+
+ // readdicom(filename) into Data, or readdicom(x, filename)
+ static int luareaddicom(lua_State *L)
+ { struct scriptdata *sd = getsd(L);
+ DICOMDataObject *O, *P;
+ if (lua_isstring(L,1))
+ { char name[512];
+ strcpy(name, (char *)lua_tostring(L,1));
+ O = LoadForGUI(name);
+ if (!O) return 0;
+ if (sd->DDO && sd->DDO!=dummyddo) delete (sd->DDO);
+ sd->DDO = O;
+ lua_getglobal (L, "Data");
+ lua_getmetatable(L, -1);
+ lua_pushlightuserdata(L, sd->DDO); lua_setfield(L, -2, "DDO");
+ lua_pop(L, 2);
+ }
+ else if (lua_isuserdata(L,1))
+ { lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "DDO"); P = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ char name[512];
+ strcpy(name, (char *)lua_tostring(L,2));
+ O = LoadForGUI(name);
+ if (!O)
+ { lua_pop(L, 1);
+ return 0;
+ }
+ if (P) delete P;
+ lua_pushlightuserdata(L, O); lua_setfield(L, -2, "DDO");
+ lua_pop(L, 1);
+ }
+ lua_pushinteger(L, 1);
+ return 1;
+ }
+ // writedicom(filename), writedicom(Data, filename); Data:writedicom(filename)
+ static int luawritedicom(lua_State *L)
+ { struct scriptdata *sd = getsd(L);
+ if (lua_isstring(L,1) && sd->DDO)
+ { DICOMDataObject *pDDO = MakeCopy(sd->DDO);
+ SaveDICOMDataObject((char *)lua_tostring(L,1), pDDO);
+ delete pDDO;
+ }
+ else if (lua_isuserdata(L,1))
+ { DICOMDataObject *O = NULL;
+ lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+
+ if (O)
+ { DICOMDataObject *pDDO = MakeCopy(O);
+ SaveDICOMDataObject((char *)lua_tostring(L,2), pDDO);
+ delete pDDO;
+ }
+ }
+ return 0;
+ }
+
+ // Data:writeheader(filename) or writeheader(filename)
+ static int luawriteheader(lua_State *L)
+ { struct scriptdata *sd = getsd(L);
+ if (lua_isuserdata(L,1))
+ { DICOMDataObject *O = NULL;
+ lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+
+ if (O)
+ { FILE *f = fopen(lua_tostring(L, 2), "wt");
+ if (f)
+ { NonDestructiveDumpDICOMObject(O, f);
+ fclose(f);
+ }
+ }
+ }
+ else if (lua_isstring(L,1))
+ { FILE *f = fopen(lua_tostring(L, 1), "wt");
+ if (f)
+ { if (sd->DDO) NonDestructiveDumpDICOMObject(sd->DDO, f);
+ fclose(f);
+ }
+ }
+ return 0;
+ }
+
+ // newdicomobject()
+ static int luanewdicomobject(lua_State *L)
+ { DICOMDataObject *O = new DICOMDataObject;
+ luaCreateObject(L, O, NULL, TRUE);
+ return 1;
+ }
+
+ // newdicomarray()
+ static int luanewdicomarray(lua_State *L)
+ { Array < DICOMDataObject * > *A = new Array < DICOMDataObject * >;
+ luaCreateObject(L, NULL, A, TRUE);
+ return 1;
+ }
+
+ // deletedicomobject()
+ static int luadeletedicomobject(lua_State *L)
+ { struct scriptdata *sd = getsd(L);
+ DICOMDataObject *O = NULL;
+ int owned;
+ Array < DICOMDataObject * > *A = NULL;
+ if (lua_isuserdata(L,1))
+ { lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_getfield(L, -1, "ADDO"); A = (Array < DICOMDataObject * > *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_getfield(L, -1, "owned"); owned = lua_tointeger(L, -1); lua_pop(L, 1);
+ lua_pushlightuserdata(L, NULL); lua_setfield(L, -2, "DDO");
+ lua_pushlightuserdata(L, NULL); lua_setfield(L, -2, "ADDO");
+ lua_pop(L, 1);
+ }
+ if (owned)
+ { if (O && O!=(DICOMDataObject *)(sd->DCO) && O!=sd->DDO)
+ delete O;
+ if (A)
+ { for (int i=0; i<A->GetSize(); i++) delete (DICOMDataObject *)(A->Get(i));
+ delete A;
+ }
+ }
+ return 0;
+ }
+
+ // heap information for leak debugging
+ static int luaheapinfo(lua_State *L)
+ { lua_pushstring(L, heapinfo());
+ return 1;
+ }
+
+// system does a backgroundexec
+ static int luasystem(lua_State *L)
+ { if (lua_isstring(L,1))
+ { int r;
+#ifdef WIN32
+ char command[512], arg[10], *p;
+ strcpy(command, lua_tostring(L,1));
+ if (command[0]=='\'' || command[0]=='"')
+ { arg[0] = command[0];
+ arg[1] = ' ';
+ arg[2] = 0;
+ p = strstr(command, arg);
+ if (p)
+ { *p=0;
+ r = (int)BackgroundExec(command+1, p+2);
+ }
+ else
+ r = (int)BackgroundExec(command+1, "");
+ }
+ else
+ { p = strchr(command, ' ');
+ if (p)
+ { *p=0;
+ r = (int)BackgroundExec(command, p+1);
+ }
+ else
+ r = (int)BackgroundExec(command, "");
+ }
+#else
+ r = system((char *)lua_tostring(L,1));
+#endif
+ lua_pushinteger(L, r);
+ return 1;
+ }
+ return 0;
+ }
+
+ // sleep in milliseconds
+ static int luasleep(lua_State *L)
+ { if (lua_isnumber(L,1))
+ Sleep(lua_tointeger(L,1));
+ return 0;
+ }
+
+ static int luaaddimage(lua_State *L)
+ { if (lua_isuserdata(L,1))
+ { DICOMDataObject *O = NULL;
+ lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+
+ if (O)
+ { Database DB;
+ char rFilename[1024];
+ ExtendedPDU_Service PDU;
+ PDU.AttachRTC(&VRType);
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ { OperatorConsole.printf("***Error Connecting to SQL\n");
+ return ( FALSE );
+ }
+
+ DICOMDataObject *P = MakeCopy(O);
+ int rc = SaveToDisk(DB, P, rFilename, TRUE, &PDU, 0, TRUE);
+ if (!rc)
+ { OperatorConsole.printf("***[lua addimage] Error entering object into server%s\n");
+ }
+ else
+ { if (rc==2) OperatorConsole.printf("Lua script rewritten file: %s\n", rFilename);
+ else OperatorConsole.printf("Lua script written file: %s\n", rFilename);
+ }
+ }
+ }
+ return 0;
+ }
+
+
+static void HTML(const char *string, ...);
+static int CGI(char *out, const char *name, const char *def);
+
+ static int luaHTML(lua_State *L)
+ { // char buf[1000];
+ int n=lua_gettop(L);
+ switch(n)
+ { case 1: HTML(lua_tostring(L, 1)); break;
+ case 2: HTML(lua_tostring(L, 1), lua_tostring(L, 2)); break;
+ case 3: HTML(lua_tostring(L, 1), lua_tostring(L, 2), lua_tostring(L, 3)); break;
+ case 4: HTML(lua_tostring(L, 1), lua_tostring(L, 2), lua_tostring(L, 3), lua_tostring(L, 4)); break;
+ case 5: HTML(lua_tostring(L, 1), lua_tostring(L, 2), lua_tostring(L, 3), lua_tostring(L, 4), lua_tostring(L, 5)); break;
+ }
+ return 0;
+ }
+ static int luaCGI(lua_State *L)
+ { char buf[1000];
+ int n=lua_gettop(L);
+ switch(n)
+ { case 1: CGI(buf, lua_tostring(L, 1), ""); break;
+ case 2: CGI(buf, lua_tostring(L, 1), lua_tostring(L,2)); break;
+ }
+ lua_pushstring(L, buf);
+ return 1;
+ }
+ static int luagpps(lua_State *L)
+ { char buf[1000];
+ int n=lua_gettop(L);
+ switch(n)
+ { case 1: MyGetPrivateProfileString ( "sscscp", lua_tostring(L,1), "", buf, 256, ConfigFile);
+ case 2: MyGetPrivateProfileString ( lua_tostring(L,1), lua_tostring(L,2),"", buf, 256, ConfigFile);
+ case 3: MyGetPrivateProfileString ( lua_tostring(L,1), lua_tostring(L,2), lua_tostring(L,3), buf, 256, ConfigFile);
+ }
+ lua_pushstring(L, buf);
+ return 1;
+ }
+
+//todo (now read/write directly from dicom.ini):
+//IgnoreOutOfMemoryErrors, ImportExportDragAndDrop, TruncateFieldNames, ForwardAssociationRelease,
+//RetryForwardFailed, UIDPrefix, ForwardAssociationLevel, ForwardAssociationRefreshDelay
+//ForwardAssociationCloseDelay, ForwardAssociationRelease, MaximumExportRetries,
+//MaximumDelayedFetchForwardRetries, ziptime, NightlyCleanThreshhold, NightlyCleanThreshhold
+//OverlapVirtualGet, SendUpperCaseAE, TCPIPTimeOut, PadAEWithZeros
+//acrnema.map, dicom.sql, dgatesop.lst, dgate.dic, Database, Patient, Study[i], Series[i], Image[i]
+
+ static int luaGlobalIndex(lua_State *L)
+ { int n;
+ int *idata=NULL;
+ char *sdata=NULL;
+ char szRootSC[64], Parameter[512];
+ for (n=0;;n++)
+ { if (!iglobals[n].data) break;
+ if (stricmp(lua_tostring(L,2), iglobals[n].name)==0) idata = iglobals[n].data;
+ }
+ for (n=0;;n++)
+ { if (!sglobals[n].data) break;
+ if (stricmp(lua_tostring(L,2), sglobals[n].name)==0) sdata = sglobals[n].data;
+ }
+ if (MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile))
+ MyGetPrivateProfileString(szRootSC, lua_tostring(L,2), "", Parameter, 512, ConfigFile);
+
+ if (idata) { lua_pushinteger(L, *idata); return 1; }
+ if (sdata) { lua_pushstring (L, sdata); return 1; }
+ if (*Parameter) { lua_pushstring (L, Parameter); return 1; }
+ return 0;
+ }
+ static int luaGlobalNewIndex(lua_State *L)
+ { int n, slen;
+ int *idata=NULL;
+ char *sdata=NULL;
+ char szRootSC[64], Parameter[512], script[1024];
+ for (n=0;;n++)
+ { if (!iglobals[n].data) break;
+ if (stricmp(lua_tostring(L,2), iglobals[n].name)==0) idata = iglobals[n].data;
+ }
+ for (n=0;;n++)
+ { if (!sglobals[n].data) break;
+ if (stricmp(lua_tostring(L,2), sglobals[n].name)==0) sdata = sglobals[n].data, slen = sglobals[n].len;
+ }
+ if (MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile))
+ MyGetPrivateProfileString(szRootSC, lua_tostring(L,2), "", Parameter, 512, ConfigFile);
+ if (*Parameter)
+ { sprintf(script, "put_param:%s,%s", lua_tostring(L,2), lua_tostring(L,3));
+ SendServerCommand("", script, 0, NULL);
+ SendServerCommand("", "read_ini:", 0, NULL);
+ }
+ if (idata) *idata = lua_tointeger(L,3);
+ if (sdata) strncpy(sdata, lua_tostring(L,3), slen-1), sdata[slen-1]=0;
+ return 0;
+ }
+
+ static int luaAssociationIndex(lua_State *L)
+ { struct scriptdata *sd = getsd(L);
+ char *cdata=NULL;
+ int *idata=NULL;
+ BYTE buf[64]; buf[0]=0;
+ if (strcmp(lua_tostring(L,2), "Calling")==0) { cdata = (char *)buf; sd->PDU->GetLocalAddress (buf); }
+ else if (strcmp(lua_tostring(L,2), "Called")==0) { cdata = (char *)buf; sd->PDU->GetRemoteAddress(buf); }
+ else if (strcmp(lua_tostring(L,2), "ConnectedIP")==0)
+ { unsigned int ip = (unsigned int) sd->ConnectedIP;
+ sprintf((char *)buf, "%d.%d.%d.%d", ip&255, (ip>>8)&255, (ip>>16)&255, (ip>>24)&255);
+ cdata = (char *)buf;
+ }
+
+ if (cdata) while (strlen(cdata)>0 && cdata[strlen(cdata)-1]==' ') cdata[strlen(cdata)-1] = 0;
+
+ if (strcmp(lua_tostring(L,2), "Thread")==0) idata = &(sd->PDU->ThreadNum);
+
+ if (cdata) { lua_pushstring (L, cdata); return 1; }
+ if (idata) { lua_pushinteger(L, *idata); return 1; }
+ return 0;
+ }
+
+ static int luaSeqClosure(lua_State *L)
+ { const char *s = lua_tostring(L, lua_upvalueindex(1));
+ if (strcmp(s, "Read" )==0) return luareaddicom(L);
+ if (strcmp(s, "Write")==0) return luawritedicom(L);
+ if (strcmp(s, "Dump" )==0) return luawriteheader(L);
+ if (strcmp(s, "SetVR")==0) return luasetvr(L);
+ if (strcmp(s, "GetVR")==0) return luagetvr(L);
+ if (strcmp(s, "GetPixel")==0) return luagetpixel(L);
+ if (strcmp(s, "SetPixel")==0) return luasetpixel(L);
+ if (strcmp(s, "GetRow")==0) return luagetrow(L);
+ if (strcmp(s, "SetRow")==0) return luasetrow(L);
+ if (strcmp(s, "GetColumn")==0)return luagetcolumn(L);
+ if (strcmp(s, "SetColumn")==0)return luasetcolumn(L);
+ if (strcmp(s, "GetImage")==0) return luagetimage(L);
+ if (strcmp(s, "SetImage")==0) return luasetimage(L);
+ if (strcmp(s, "Script")==0) return luascript(L);
+ if (strcmp(s, "AddImage")==0) return luaaddimage(L);
+
+ if (strcmp(s, "new")==0) return luanewdicomobject(L);
+ if (strcmp(s, "newarray")==0) return luanewdicomarray(L);
+ if (strcmp(s, "free")==0) return luadeletedicomobject(L);
+ return 0;
+ }
+ static int luaSeqnewindex(lua_State *L)
+ { struct scriptdata *sd = getsd(L);
+ char script[1024];
+
+ Array < DICOMDataObject * > *A = NULL;
+ DICOMDataObject *O = NULL;
+ lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "ADDO"); A = (Array < DICOMDataObject * > *)lua_topointer(L, -1); lua_pop(L, 1);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+
+ // Data.Sequence, e.g., need to write into Data.Sequence.Item
+ if (A)
+ { if (A->GetSize()>0)
+ O=A->Get(0);
+ else
+ { O = new DICOMDataObject;
+ A->Add(O);
+ }
+ }
+
+ // write into Data.Storage
+ if (O==sd->DDO && strcmp(lua_tostring(L,2), "Storage")==0)
+ { sprintf(script, "storage %s", lua_tostring(L,3));
+ CallImportConverterN(O, -1, sd->pszModality, sd->pszStationName, sd->pszSop, sd->patid, sd->PDU, sd->Storage, script);
+ }
+ // write into Data.Item, Data.Sequence.Item, or Data.Sequence[N].Item
+ else if (O)
+ { // write table: creates empty! sequence
+ if (lua_istable(L, 3))
+ sprintf(script, "set %s to \"\"", lua_tostring(L,2));
+ // write nil: deletes item
+ else if (lua_isnil(L, 3))
+ sprintf(script, "set %s to nil", lua_tostring(L,2));
+ // write string: creates item
+ else
+ { // sprintf(script, "set %s to \"%s\"", lua_tostring(L,2), lua_tostring(L,3));
+ char temp[1024];
+ int i,j;
+ strcpy(temp, lua_tostring(L,3));
+ sprintf(script, "set %s to \"", lua_tostring(L,2));
+ for (i=0, j=strlen(script); i<strlen(temp); i++)
+ { if (temp[i]=='%')
+ { script[j++] = '%';
+ script[j++] = '%';
+ }
+ else
+ script[j++] = temp[i];
+ }
+ script[j++] = '"';
+ script[j++] = 0;
+ }
+
+ CallImportConverterN(O, -1, sd->pszModality, sd->pszStationName, sd->pszSop, sd->patid, sd->PDU, sd->Storage, script);
+ }
+ return 0;
+ }
+ static int luaSeqindex(lua_State *L)
+ { struct scriptdata *sd = getsd(L);
+ Array < DICOMDataObject * > *A, *A2;
+ DICOMDataObject *O, *O2;
+ char buf[2000]; buf[0]=0;
+
+ lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "ADDO"); A = (Array < DICOMDataObject * > *)lua_topointer(L, -1); lua_pop(L, 1);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+
+ // Address sequence
+ if (A)
+ { // push table for selected element (Data.Sequence[N], allow new elements in sequence)
+ if (isdigit(*lua_tostring(L,2)))
+ { int N = lua_tonumber(L, 2);
+ if (N >A->GetSize())
+ { O2=NULL;
+ A2=NULL;
+ }
+ else
+ { if (N==A->GetSize())
+ { DICOMDataObject *D = new DICOMDataObject; A->Add(D);
+ }
+ O2=A->Get(N);
+ A2=NULL;
+ }
+ }
+ // Address default element 0 (Data.Sequence.Item)
+ else if (A->GetSize()>0)
+ SearchDICOMObject(A->Get(0), lua_tostring(L,2), buf, &A2, &O2);
+ }
+ // Address Data.Storage
+ // Address listed methods by name, e.g., Data:Write('c:\\x.dcm')
+ // or get selected item (Data.Item, Data.Sequence[N].Item)
+ else if (O)
+ { if (O==sd->DDO && strcmp(lua_tostring(L,2), "Storage")==0)
+ { lua_pushstring(L, sd->Storage);
+ return 1;
+ }
+ else if (strstr("Write|Read|Dump|GetVR|SetVR|GetPixel|SetPixel|GetRow|SetRow|GetColumn|SetColumn|GetImage|SetImage|Script|new|newarray|free|AddImage", lua_tostring(L,2)))
+ { lua_pushvalue(L, 2);
+ lua_pushcclosure(L, luaSeqClosure, 1);
+ return 1;
+ }
+ else
+ SearchDICOMObject(O, lua_tostring(L,2), buf, &A2, &O2);
+ }
+ else
+ { A2=NULL; O2=NULL;
+ if (strstr("new|newarray", lua_tostring(L,2)))
+ { lua_pushvalue(L, 2);
+ lua_pushcclosure(L, luaSeqClosure, 1);
+ return 1;
+ }
+ }
+
+ // The item is a sequence or sequence element: return a new table (non-gc'd)
+ if (A2 || O2)
+ { luaCreateObject(L, O2, A2, FALSE);
+ return 1;
+ }
+
+ // return a read string: empty string coded as \00\01; non-existing element as \00\00
+ if (buf[0]) { lua_pushstring(L, buf); return 1; }
+ if (buf[1]) { lua_pushstring(L, buf); return 1; }
+ return 0;
+ }
+ static int luaSeqgc(lua_State *L)
+ { struct scriptdata *sd = getsd(L);
+ DICOMDataObject *O = NULL;
+ Array < DICOMDataObject * > *A = NULL;
+ int owned;
+ lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_getfield(L, -1, "ADDO"); A = (Array < DICOMDataObject * > *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_getfield(L, -1, "owned"); owned = lua_tointeger(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+
+ if (owned)
+ { if (O && O!=(DICOMDataObject *)(sd->DCO) && O!=sd->DDO) delete O;
+ if (A)
+ { for (int i=0; i<A->GetSize(); i++) delete (DICOMDataObject *)(A->Get(i));
+ delete A;
+ }
+ }
+ return 0;
+ }
+
+ static int luaSeqlen(lua_State *L)
+ { struct scriptdata *sd = getsd(L);
+ DICOMDataObject *O = NULL;
+ Array < DICOMDataObject * > *A = NULL;
+ lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_getfield(L, -1, "ADDO"); A = (Array < DICOMDataObject * > *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+
+ if (O) lua_pushinteger(L, 1);
+ else if (A) lua_pushinteger(L, A->GetSize());
+ return 1;
+ }
+
+ static int luaSeqToString(lua_State *L)
+ { struct scriptdata *sd = getsd(L);
+ char text[80];
+ DICOMDataObject *O = NULL;
+ Array < DICOMDataObject * > *A = NULL;
+ lua_getmetatable(L, 1);
+ lua_getfield(L, -1, "DDO"); O = (DICOMDataObject *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_getfield(L, -1, "ADDO"); A = (Array < DICOMDataObject * > *) lua_topointer(L, -1); lua_pop(L, 1);
+ lua_pop(L, 1);
+
+ if (O) lua_pushstring(L, "Dicom Data Object");
+ else if (A)
+ { sprintf(text, "Dicom sequence with %d entries", A->GetSize());
+ lua_pushstring(L, text);
+ }
+ return 1;
+ }
+
+ static void luaCreateObject(lua_State *L, DICOMDataObject *pDDO, Array < DICOMDataObject *> *A, BOOL owned)
+ { lua_newuserdata(L, 0);
+ lua_createtable(L, 0, 0);
+ lua_pushcfunction(L, luaSeqindex); lua_setfield(L, -2, "__index");
+ lua_pushcfunction(L, luaSeqnewindex); lua_setfield(L, -2, "__newindex");
+ lua_pushcfunction(L, luaSeqgc); lua_setfield(L, -2, "__gc");
+ lua_pushcfunction(L, luaSeqlen); lua_setfield(L, -2, "__len");
+ lua_pushcfunction(L, luaSeqToString); lua_setfield(L, -2, "__tostring");
+ lua_pushlightuserdata(L, A); lua_setfield(L, -2, "ADDO");
+ lua_pushlightuserdata(L, pDDO); lua_setfield(L, -2, "DDO");
+ lua_pushinteger (L, (int)owned); lua_setfield(L, -2, "owned");
+ lua_setmetatable(L, -2);
+ }
+}
+
+ExtendedPDU_Service globalPDU; // for global script context
+
+/*
+* lpack.c
+* a Lua library for packing and unpacking binary data
+* Luiz Henrique de Figueiredo <lhf at tecgraf.puc-rio.br>
+* 29 Jun 2007 19:27:20
+* This code is hereby placed in the public domain.
+* with contributions from Ignacio Casta�o <castanyo at yahoo.es> and
+* Roberto Ierusalimschy <roberto at inf.puc-rio.br>.
+*/
+
+#define OP_ZSTRING 'z' /* zero-terminated string */
+#define OP_BSTRING 'p' /* string preceded by length byte */
+#define OP_WSTRING 'P' /* string preceded by length word */
+#define OP_SSTRING 'a' /* string preceded by length size_t */
+#define OP_STRING 'A' /* string */
+#define OP_FLOAT 'f' /* float */
+#define OP_DOUBLE 'd' /* double */
+#define OP_NUMBER 'n' /* Lua number */
+#define OP_CHAR 'c' /* char */
+#define OP_BYTE 'b' /* byte = unsigned char */
+#define OP_SHORT 'h' /* short */
+#define OP_USHORT 'H' /* unsigned short */
+#define OP_INT 'i' /* int */
+#define OP_UINT 'I' /* unsigned int */
+#define OP_LONG 'l' /* long */
+#define OP_ULONG 'L' /* unsigned long */
+#define OP_LITTLEENDIAN '<' /* little endian */
+#define OP_BIGENDIAN '>' /* big endian */
+#define OP_NATIVE '=' /* native endian */
+
+#include <ctype.h>
+#include <string.h>
+
+#include "lua.h"
+#include "lualib.h"
+#include "lauxlib.h"
+
+static void badcode(lua_State *L, int c)
+{
+ char s[]="bad code `?'";
+ s[sizeof(s)-3]=c;
+ luaL_argerror(L,1,s);
+}
+
+static int doendian(int c)
+{
+ int x=1;
+ int e=*(char*)&x;
+ if (c==OP_LITTLEENDIAN) return !e;
+ if (c==OP_BIGENDIAN) return e;
+ if (c==OP_NATIVE) return 0;
+ return 0;
+}
+
+static void doswap(int swap,void *p, size_t n)
+{
+ if (swap)
+ {char *a=(char *)p;
+ int i,j;
+ for (i=0, j=n-1, n=n/2; n--; i++, j--)
+ {
+ char t=a[i]; a[i]=a[j]; a[j]=t;
+ }
+ }
+}
+
+#define UNPACKNUMBER(OP,T) \
+ case OP: \
+ { \
+ T a; \
+ int m=sizeof(a); \
+ if (i+m>len) goto done; \
+ memcpy(&a,s+i,m); \
+ i+=m; \
+ doswap(swap,&a,m); \
+ lua_pushnumber(L,(lua_Number)a); \
+ ++n; \
+ break; \
+ }
+
+#define UNPACKSTRING(OP,T) \
+ case OP: \
+ { \
+ T l; \
+ int m=sizeof(l); \
+ if (i+m>len) goto done; \
+ memcpy(&l,s+i,m); \
+ doswap(swap,&l,m); \
+ if (i+m+l>len) goto done; \
+ i+=m; \
+ lua_pushlstring(L,s+i,l); \
+ i+=l; \
+ ++n; \
+ break; \
+ }
+
+static int l_unpack(lua_State *L) /** unpack(s,f,[init]) */
+{
+ size_t len;
+ const char *s=luaL_checklstring(L,1,&len);
+ const char *f=luaL_checkstring(L,2);
+ int i=luaL_optnumber(L,3,1)-1;
+ int n=0;
+ int swap=0;
+ lua_pushnil(L);
+ while (*f)
+ {
+ int c=*f++;
+ int N=1;
+ if (isdigit(*f))
+ {
+ N=0;
+ while (isdigit(*f)) N=10*N+(*f++)-'0';
+ if (N==0 && c==OP_STRING) { lua_pushliteral(L,""); ++n; }
+ }
+ while (N--) switch (c)
+ {
+ case OP_LITTLEENDIAN:
+ case OP_BIGENDIAN:
+ case OP_NATIVE:
+ {
+ swap=doendian(c);
+ N=0;
+ break;
+ }
+ case OP_STRING:
+ {
+ ++N;
+ if (i+N>len) goto done;
+ lua_pushlstring(L,s+i,N);
+ i+=N;
+ ++n;
+ N=0;
+ break;
+ }
+ case OP_ZSTRING:
+ {
+ size_t l;
+ if (i>=len) goto done;
+ l=strlen(s+i);
+ lua_pushlstring(L,s+i,l);
+ i+=l+1;
+ ++n;
+ break;
+ }
+ UNPACKSTRING(OP_BSTRING, unsigned char)
+ UNPACKSTRING(OP_WSTRING, unsigned short)
+ UNPACKSTRING(OP_SSTRING, size_t)
+ UNPACKNUMBER(OP_NUMBER, lua_Number)
+ UNPACKNUMBER(OP_DOUBLE, double)
+ UNPACKNUMBER(OP_FLOAT, float)
+ UNPACKNUMBER(OP_CHAR, char)
+ UNPACKNUMBER(OP_BYTE, unsigned char)
+ UNPACKNUMBER(OP_SHORT, short)
+ UNPACKNUMBER(OP_USHORT, unsigned short)
+ UNPACKNUMBER(OP_INT, int)
+ UNPACKNUMBER(OP_UINT, unsigned int)
+ UNPACKNUMBER(OP_LONG, long)
+ UNPACKNUMBER(OP_ULONG, unsigned long)
+ case ' ': case ',':
+ break;
+ default:
+ badcode(L,c);
+ break;
+ }
+ }
+done:
+ lua_pushnumber(L,i+1);
+ lua_replace(L,-n-2);
+ return n+1;
+}
+
+#define PACKNUMBER(OP,T) \
+ case OP: \
+ { \
+ T a=(T)luaL_checknumber(L,i++); \
+ doswap(swap,(void *)&a,sizeof(a)); \
+ luaL_addlstring(&b,(const char *)&a,sizeof(a)); \
+ break; \
+ }
+
+#define PACKSTRING(OP,T) \
+ case OP: \
+ { \
+ size_t l; \
+ const char *a=luaL_checklstring(L,i++,&l); \
+ T ll=(T)l; \
+ doswap(swap,(void *)&ll,sizeof(ll)); \
+ luaL_addlstring(&b,(const char *)&ll,sizeof(ll)); \
+ luaL_addlstring(&b,a,l); \
+ break; \
+ }
+
+static int l_pack(lua_State *L) /** pack(f,...) */
+{
+ int i=2;
+ const char *f=luaL_checkstring(L,1);
+ int swap=0;
+ luaL_Buffer b;
+ luaL_buffinit(L,&b);
+ while (*f)
+ {
+ int c=*f++;
+ int N=1;
+ if (isdigit(*f))
+ {
+ N=0;
+ while (isdigit(*f)) N=10*N+(*f++)-'0';
+ }
+ while (N--) switch (c)
+ {
+ case OP_LITTLEENDIAN:
+ case OP_BIGENDIAN:
+ case OP_NATIVE:
+ {
+ swap=doendian(c);
+ N=0;
+ break;
+ }
+ case OP_STRING:
+ case OP_ZSTRING:
+ {
+ size_t l;
+ const char *a=luaL_checklstring(L,i++,&l);
+ luaL_addlstring(&b,a,l+(c==OP_ZSTRING));
+ break;
+ }
+ PACKSTRING(OP_BSTRING, unsigned char)
+ PACKSTRING(OP_WSTRING, unsigned short)
+ PACKSTRING(OP_SSTRING, size_t)
+ PACKNUMBER(OP_NUMBER, lua_Number)
+ PACKNUMBER(OP_DOUBLE, double)
+ PACKNUMBER(OP_FLOAT, float)
+ PACKNUMBER(OP_CHAR, char)
+ PACKNUMBER(OP_BYTE, unsigned char)
+ PACKNUMBER(OP_SHORT, short)
+ PACKNUMBER(OP_USHORT, unsigned short)
+ PACKNUMBER(OP_INT, int)
+ PACKNUMBER(OP_UINT, unsigned int)
+ PACKNUMBER(OP_LONG, long)
+ PACKNUMBER(OP_ULONG, unsigned long)
+ case ' ': case ',':
+ break;
+ default:
+ badcode(L,c);
+ break;
+ }
+ }
+ luaL_pushresult(&b);
+ return 1;
+}
+
+static const luaL_reg R[] =
+{
+ {"pack", l_pack},
+ {"unpack", l_unpack},
+ {NULL, NULL}
+};
+
+int luaopen_pack(lua_State *L)
+{
+#ifdef USE_GLOBALS
+ lua_register(L,"bpack",l_pack);
+ lua_register(L,"bunpack",l_unpack);
+#else
+ luaL_openlib(L, LUA_STRLIBNAME, R, 0);
+#endif
+ return 0;
+}
+
+// endof pack library
+
+extern "C" int luaopen_socket_core(lua_State *L);
+
+const char *do_lua(lua_State **L, char *cmd, struct scriptdata *sd)
+{ if (!*L)
+ {
+#ifdef LUA_5_2
+ *L = luaL_newstate();
+#else
+ *L = lua_open();
+#endif
+ luaL_openlibs (*L);
+
+ lua_register (*L, "print", luaprint);
+ lua_register (*L, "script", luascript);
+ lua_register (*L, "get_amap", luaget_amap);
+ lua_register (*L, "get_sqldef", luaget_sqldef);
+ lua_register (*L, "dbquery", luadbquery);
+ lua_register (*L, "sql", luasql);
+ lua_register (*L, "dicomquery", luadicomquery);
+ lua_register (*L, "dicommove", luadicommove);
+ lua_register (*L, "dicomdelete", luadicomdelete);
+ lua_register (*L, "debuglog", luadebuglog);
+ lua_register (*L, "servercommand", luaservercommand);
+ lua_register (*L, "setpixel", luasetpixel);
+ lua_register (*L, "getpixel", luagetpixel);
+ lua_register (*L, "getrow", luagetrow);
+ lua_register (*L, "setrow", luasetrow);
+ lua_register (*L, "getcolumn", luagetcolumn);
+ lua_register (*L, "setcolumn", luasetcolumn);
+ lua_register (*L, "getimage", luagetimage);
+ lua_register (*L, "setimage", luasetimage);
+ lua_register (*L, "readdicom", luareaddicom);
+ lua_register (*L, "writedicom", luawritedicom);
+ lua_register (*L, "writeheader", luawriteheader);
+ lua_register (*L, "newdicomobject",luanewdicomobject);
+ lua_register (*L, "newdicomarray", luanewdicomarray);
+ lua_register (*L, "deletedicomobject",luadeletedicomobject);
+ lua_register (*L, "getvr", luagetvr);
+ lua_register (*L, "setvr", luasetvr);
+ lua_register (*L, "HTML", luaHTML);
+ lua_register (*L, "CGI", luaCGI);
+ lua_register (*L, "gpps", luagpps);
+ lua_register (*L, "heapinfo", luaheapinfo);
+ lua_register (*L, "dictionary", luadictionary);
+ lua_register (*L, "changeuid", luachangeuid);
+ lua_register (*L, "changeuidback", luachangeuidback);
+ lua_register (*L, "genuid", luagenuid);
+ lua_register (*L, "crc", luacrc);
+ lua_register (*L, "system", luasystem);
+ lua_register (*L, "sleep", luasleep);
+ lua_register (*L, "addimage", luaaddimage);
+
+ lua_createtable (*L, 0, 0);
+ lua_createtable (*L, 0, 0);
+ lua_pushcfunction (*L, luaGlobalIndex); lua_setfield (*L, -2, "__index");
+ lua_pushcfunction (*L, luaGlobalNewIndex); lua_setfield (*L, -2, "__newindex");
+ lua_setmetatable (*L, -2);
+ lua_setglobal (*L, "Global");
+
+ lua_createtable(*L, 0, 0);
+ lua_createtable(*L, 0, 0);
+ lua_pushcfunction(*L, luaAssociationIndex); lua_setfield(*L, -2, "__index");
+ lua_setmetatable(*L, -2);
+ lua_setglobal(*L, "Association");
+
+ lua_getfield(*L, LUA_GLOBALSINDEX, "package");
+ lua_getfield(*L, -1, "preload");
+#ifdef WIN32
+ lua_pushcfunction(*L, luaopen_socket_core);
+ lua_setfield(*L, -2, "socket.core");
+#endif
+ lua_pushcfunction(*L, luaopen_pack);
+ lua_setfield(*L, -2, "pack");
+ }
+
+ if (!sd->DDO)
+ { sd->DDO = dummyddo = new(DICOMDataObject);
+ }
+ else
+ dummyddo = NULL;
+
+
+ luaCreateObject(*L, (DICOMDataObject *)sd->DCO, NULL, FALSE); lua_setglobal(*L, "Command");
+ luaCreateObject(*L, sd->DDO, NULL, FALSE); lua_setglobal(*L, "Data");
+ luaCreateObject(*L, NULL, NULL, FALSE); lua_setglobal(*L, "DicomObject");
+
+ lua_pushlightuserdata(*L, sd);
+ lua_setglobal(*L, "scriptdata");
+
+ if (cmd[0])
+ { if (luaL_loadstring(*L, cmd))
+ { OperatorConsole.printf("*** lua syntax error %s in '%s'\n", lua_tostring(*L, -1), cmd);
+ if (sd->DDO == dummyddo)
+ { sd->DDO = NULL;
+ delete dummyddo;
+ dummyddo = NULL;
+ }
+ lua_pop(*L, 1);
+ return NULL;
+ }
+ else
+ {
+#ifdef LUA_5_2
+ if (lua_pcallk(*L, 0, 1, 0, 0, NULL))
+#else
+ if (lua_pcall(*L, 0, 1, 0))
+#endif
+ { OperatorConsole.printf("*** lua run error %s in '%s'\n", lua_tostring(*L, -1), cmd);
+ if (sd->DDO == dummyddo)
+ { sd->DDO = NULL;
+ delete dummyddo;
+ dummyddo = NULL;
+ }
+ lua_pop(*L, 1);
+ return NULL;
+ }
+ else
+ { if (sd->DDO == dummyddo)
+ { sd->DDO = NULL;
+ delete dummyddo;
+ dummyddo = NULL;
+ }
+ if (lua_isstring(*L, -1))
+ return lua_tostring(*L, -1);
+ else
+ lua_pop(*L, 1);
+ }
+ }
+ }
+ return NULL;
+}
+
+void lua_setvar(ExtendedPDU_Service *pdu, char *name, char *value)
+{ struct scriptdata sd = {pdu, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, 0, 0};
+ do_lua(&(pdu->L), "", &sd);
+ if (value)
+ lua_pushstring(pdu->L, value);
+ else
+ lua_pushstring(pdu->L, "NULL");
+ lua_setglobal (pdu->L, name);
+}
+
+void lua_getstring(ExtendedPDU_Service *pdu, DICOMCommandObject *dco, DICOMDataObject *ddo, char *cmd, char *result)
+{ char script[1000];
+ struct scriptdata sd1 = {pdu, dco, ddo, -1, NULL, NULL, NULL, NULL, NULL, 0, 0};
+ strcpy(script, "return ");
+ strcat(script, cmd);
+ strcpy(result, do_lua(&(pdu->L), script, &sd1));
+}
+
+// support stuff for ImportConverters
+
+int DcmConvertPixelData(DICOMDataObject*pDDO, bool bConvertToMono, bool bCrop,
+ int iStartX, int iEndX, int iStartY, int iEndY,
+ float fPixelSizeX, float fPixelSizeY, float fPixelSizeZ);
+
+static BOOL import_c_init[MAXExportConverters][MAXExportConverters];
+static CRITICAL_SECTION import_critical[MAXExportConverters][MAXExportConverters];
+static ExtendedPDU_Service import_forward_PDU[MAXExportConverters * MAXExportConverters]; // for direct forwards, not script context
+static time_t import_forward_PDU_time[MAXExportConverters][MAXExportConverters];
+static BOOL import_forward_active[MAXExportConverters][MAXExportConverters];
+
+static BOOL WINAPI import_forward_PDU_close_thread(char *folder)
+{ while (TRUE)
+ { char szTemp[128];
+ char szRootSC[64];
+
+ MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile);
+ MyGetPrivateProfileString(szRootSC, "ForwardAssociationCloseDelay", "5", szTemp, 128, ConfigFile);
+ int closedelay = atoi(szTemp);
+ time_t t = time(NULL);
+
+ for (int i=0; i<MAXExportConverters; i++)
+ for (int j=0; j<MAXExportConverters; j++)
+ if (t-import_forward_PDU_time[i][j] > closedelay && !import_forward_active[i][j] && import_c_init[i][j])
+ if (import_forward_PDU[i*MAXExportConverters+j].Link.Connected)
+ import_forward_PDU[i*MAXExportConverters+j].Close();
+
+ Sleep(1000);
+ }
+ return TRUE;
+}
+
+void Startimport_forward_PDU_close_thread(void)
+{ static BOOL started = false;
+ if (started) return;
+ started = TRUE;
+
+ #ifdef WIN32
+ unsigned long ThreadID;
+ CreateThread(NULL, 0x000ff000, (LPTHREAD_START_ROUTINE) import_forward_PDU_close_thread, NULL, 0, &ThreadID);
+#else
+ pthread_t ThreadID;
+ pthread_create(&ThreadID, NULL, (void*(*)(void*))import_forward_PDU_close_thread, (void *)NULL);
+ pthread_detach(ThreadID);
+#endif
+}
+
+// operates synchronously on image BEFORE it is stored in the database
+// For general scripting use:
+// CallImportConverterN (pDDO, -1, NULL, NULL, NULL, NULL, NULL, NULL, script);
+
+int CallImportConverterN(DICOMDataObject *DDO, int N, char *pszModality, char *pszStationName, char *pszSop, char *patid, ExtendedPDU_Service *PDU, char *Storage, char *Script)
+{ char szRootSC[64];
+ char szEntry[32];
+ char szTemp[66];
+ char szExecName[512], szNext[512];
+ char szExecModality[66];
+ char szExecStationName[66];
+ char ImportCalledAE[18], ImportCallingAE[18], Called[18], Calling[18];
+ int rc, part, skipping;
+ char ininame[30];
+ static char ForwardUIDS[66 * MAXExportConverters * MAXExportConverters];
+ char pszFileName[512];
+
+ char *calling = (char *)((AAssociateAC *)PDU)->CallingApTitle;
+ char *called = (char *)((AAssociateAC *)PDU)->CalledApTitle;
+ int threadnum = 0;
+ if (PDU) threadnum = PDU->ThreadNum;
+ pszFileName[0]=0;
+
+ if (DDO==NULL)
+ { if (N>=0 && N<MAXExportConverters)
+ for (int i=0; i<MAXExportConverters; i++) import_forward_PDU[N*MAXExportConverters+i].Close();
+ return FALSE;
+ }
+
+ if (N==1000) strcpy(ininame, "Query");
+ else if (N==1100) strcpy(ininame, "WorkListQuery");
+ else if (N==1200) strcpy(ininame, "Retrieve");
+ else if (N==1300) strcpy(ininame, "RetrieveResult");
+ else if (N==1500) strcpy(ininame, "QueryResult");
+ else if (N==1600) strcpy(ininame, "ModalityWorkListQueryResult");
+ else if (N==1700) strcpy(ininame, "MergeSeries");
+ else if (N==1800) strcpy(ininame, "MergeStudies");
+ else if (N==1900) strcpy(ininame, "Archive");
+ else if (N==2000) strcpy(ininame, "MoveDevice");
+ else if (N==2100) strcpy(ininame, "RejectedImage");
+ else if (N==2200) strcpy(ininame, "RejectedImageWorkList");
+ else if (N==2300) strcpy(ininame, "VirtualServerQuery");
+ else if (N==2400) strcpy(ininame, "VirtualServerQueryResult");
+ else if ((N/100)==14) strcpy(ininame, "Compression"); // 1400-1499
+ else strcpy(ininame, "Import");
+
+ if (N>=0)
+ { N = N%100;
+ sprintf(szEntry, "%sConverter%d", ininame, N);
+
+ if (!MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile)) return FALSE;
+
+ MyGetPrivateProfileString("lua", szEntry, "", szExecName, 512, ConfigFile);
+ if (szExecName[0])
+ { struct scriptdata sd1 = {PDU, NULL, DDO, N, pszModality, pszStationName, pszSop, patid, Storage, 0, 0};
+ sd1.rc = 1;
+ do_lua(&(PDU->L), szExecName, &sd1);
+ //if (!MyGetPrivateProfileString(szRootSC, szEntry, "", szExecName, 512, ConfigFile))
+ return sd1.rc;
+ }
+
+ /* filter using modality, stationname, calling and called */
+
+ if (pszModality)
+ { sprintf(szEntry, "%sModality%d", ininame, N);
+ if (!MyGetPrivateProfileString(szRootSC, szEntry, "*", szExecModality, 64, ConfigFile)) return FALSE;
+ if (!match(pszModality, szExecModality)) return FALSE;
+ }
+
+ if (pszStationName)
+ { sprintf(szEntry, "%sStationName%d", ininame, N);
+ if (!MyGetPrivateProfileString(szRootSC, szEntry, "*", szExecStationName, 64, ConfigFile)) return FALSE;
+ if (!match(pszStationName, szExecStationName)) return FALSE;
+ }
+
+ if (calling)
+ { sprintf(szEntry, "%sCallingAE%d", ininame, N);
+ if (!MyGetPrivateProfileString(szRootSC, szEntry, "*", ImportCallingAE, 18, ConfigFile)) return FALSE;
+ if (!match(calling, ImportCallingAE)) return FALSE;
+ }
+
+ if (called)
+ { sprintf(szEntry, "%sCalledAE%d", ininame, N);
+ if (!MyGetPrivateProfileString(szRootSC, szEntry, "*", ImportCalledAE, 18, ConfigFile)) return FALSE;
+ if (!match(called, ImportCalledAE)) return FALSE;
+ }
+
+ /* get the import converter name */
+
+ if (called && calling)
+ { sprintf(szEntry, "%sConverter%d", ininame, N);
+ if (!MyGetPrivateProfileString(szRootSC, szEntry, "", // changed default to ""
+ szExecName, 512, ConfigFile)) return FALSE;
+ }
+ else
+ { strcpy(szExecName, Script);
+ }
+ }
+ else
+ strcpy(szExecName, Script);
+
+ /* only import converters using %x syntax are allowed */
+
+ rc = 1; // status for if statement, destroy and stop
+ part = 0;
+ skipping = 0;
+
+ while(1)
+ { char line[1000], vr1[256];
+ int i=0, l, L, len1;
+ unsigned int g, e;
+ char *p1;//, *q;
+ VR *pVR, *newVR;
+ DICOMDataObject DDO2;
+ Array < DICOMDataObject * > ADDO;
+ char level1;
+
+ szNext[0] = 0;
+
+ if (skipping || rc==4) // {} block being skipped
+ { if (szExecName[0]=='{') skipping++, rc=0;
+ else if (szExecName[0]=='}') skipping--, rc=0;
+ }
+
+ // find ; not in string: splits import commands
+ int instring=0;
+ L = strlen(szExecName);
+ for (int k=0; k<L; k++)
+ { if (szExecName[k]=='"') instring = !instring;
+ if (szExecName[k]==';' && instring==0)
+ { szExecName[k] = 0; // split command
+ while (szExecName[k+1]==' ') k++; // skip spaces after ;
+ strcpy(szNext, szExecName+k+1); // remaining for next
+ break;
+ }
+ }
+
+ /* substitute %x variables and remove possible { and } at begin of statement */
+
+ line[0] = 0;
+ instring = 0;
+ L = strlen(szExecName);
+ while (i<L)
+ { if (i==0 && szExecName[i] == '{') {i++; while(szExecName[i]==' ')i++;}
+ else if (i==0 && szExecName[i] == '}') {i++; while(szExecName[i]==' ')i++;}
+ else if (szExecName[i] == '"')
+ { if (instring && szExecName[i+1]=='"')
+ { strcat(line, """");
+ i+=2;
+ }
+ else
+ { l = strlen(line);
+ line[l] = szExecName[i++];
+ line[l+1] = 0;
+ }
+ instring = !instring;
+ }
+ else if (szExecName[i] == '%')
+ { char *ps = line + strlen(line);
+
+ switch(tolower(szExecName[i+1]))
+ { case 'f': if (pszFileName[0]==0)
+ { Database DB; char dum[512], mag[64];
+ if (DB.Open ( DataSource, UserName, Password, DataHost ))
+ { GenerateFileName(DDO, mag, dum, pszFileName, TRUE, 0, called, calling, &DB);
+ if (memcmp(pszFileName, "lua:", 4)==0) lua_getstring(PDU, NULL, DDO, pszFileName+4, pszFileName);
+ GetPhysicalDevice(mag, dum);
+ strcat(dum, pszFileName);
+ strcpy(pszFileName, dum);
+ }
+ }
+ strcat(line, pszFileName); // %f=filename
+ break;
+ case 'b': if (pszFileName[0]==0)
+ { Database DB; char dum[512], mag[64];
+ if (DB.Open ( DataSource, UserName, Password, DataHost ))
+ { GenerateFileName(DDO, mag, dum, pszFileName, TRUE, 0, called, calling, &DB);
+ if (memcmp(pszFileName, "lua:", 4)==0) lua_getstring(PDU, NULL, DDO, pszFileName+4, pszFileName);
+ GetPhysicalDevice(mag, dum);
+ strcat(dum, pszFileName);
+ strcpy(pszFileName, dum);
+ }
+ }
+ p1 = strrchr(pszFileName, PATHSEPCHAR);
+ if (p1) // %b=file base name
+ { strcat(line, p1+1);
+ p1 = strrchr(line, '.');
+ if (p1) *p1=0;
+ }
+ break;
+ case 'p': if (pszFileName[0]==0)
+ { Database DB; char dum[512], mag[64];
+ if (DB.Open ( DataSource, UserName, Password, DataHost ))
+ { GenerateFileName(DDO, mag, dum, pszFileName, TRUE, 0, called, calling, &DB);
+ if (memcmp(pszFileName, "lua:", 4)==0) lua_getstring(PDU, NULL, DDO, pszFileName+4, pszFileName);
+ GetPhysicalDevice(mag, dum);
+ strcat(dum, pszFileName);
+ strcpy(pszFileName, dum);
+ }
+ }
+ strcat(line, pszFileName); // %p=file path
+ p1 = strrchr(line, PATHSEPCHAR);
+ if (p1) *p1=0;
+ break;
+
+ case 'm': if (pszModality)
+ strcat(line, pszModality); // %m=modality
+ else
+ { char result[256];
+ SearchDICOMObject(DDO, "0008,0060", result);
+ strcat(line, result);
+ }
+ break;
+ case 's': if (pszStationName)
+ strcat(line, pszStationName);// %s=stationname
+ else
+ { char result[256];
+ SearchDICOMObject(DDO, "0008,1010", result);
+ strcat(line, result);
+ }
+ break;
+ case 'o': if (pszSop)
+ strcat(line, pszSop); // %o=object instance
+ else
+ { char result[256];
+ SearchDICOMObject(DDO, "0008,0018", result);
+ strcat(line, result);
+ }
+ break;
+ case 'i': //if (patid)
+ // strcat(line, patid); // %i=patient ID
+ //else
+ { char result[256];
+ SearchDICOMObject(DDO, "0010,0020", result);
+ strcat(line, result);
+ }
+ break;
+ case 'u': Calling[0]=0;
+ if (calling) strcpy(Calling, calling);
+ while (strlen(Calling)>0 && Calling[strlen(Calling)-1]==' ') Calling[strlen(Calling)-1] = 0;
+ strcat(line, Calling); // %u=SCU
+ break;
+ case 'c': Called[0]=0;
+ if (called) strcpy(Called, called);
+ while (strlen(Called)>0 && Called[strlen(Called)-1]==' ') Called[strlen(Called)-1] = 0;
+ strcat(line, Called); // %c=calledAE = scp
+ break;
+ case 'd': time_t TimeOfDay; // %d=date and time
+ char TimeString[128], buf[64];
+ UNUSED_ARGUMENT(buf);//Stop gcc4.2 warning bcb
+ TimeOfDay = time(NULL);
+ strcpy(TimeString, ctime_r(&TimeOfDay, buf));
+ TimeString[strlen(TimeString)-1] = '\0';
+ strcat(line, TimeString);
+ break;
+ case 'n': strcat(line, "\n"); // %n=newline
+ break;
+ case 't': strcat(line, "\t"); // %t=tab
+ break;
+ case '%': strcat(line, "%"); // %%=%
+ break;
+ case '^': strcat(line, "^"); // %^=^
+ break;
+ case '~': strcat(line, "~"); // %~=~
+ break;
+ case '[': strcat(line, "["); // %[=[
+ break;
+ case 'x': // %x, %y, %z are general purpose variables
+ case 'y':
+ case 'z':
+ pVR = PDU->VariableVRs[tolower(szExecName[i+1])-'x'];
+ if (!pVR) pVR = new VR;
+ PDU->VariableVRs[tolower(szExecName[i+1])-'x'] = pVR;
+ strncpy(vr1, (char*)pVR->Data, pVR->Length);
+ vr1[pVR->Length] = 0;
+ len1 = pVR->Length - 1;
+ while(len1>0)
+ { if (vr1[len1] == ' ')
+ vr1[len1] = 0;
+ else
+ break;
+ len1--;
+ }
+ strcat(line, vr1);
+ break;
+ case 'v': // %Vxxxx,yyyy=any vr (group and element must have 4 digits)
+ char result[256]; // %V*xxxx,yyyy=any vr in any sequence
+ i += SearchDICOMObject(DDO, szExecName+i+2, result);
+ strcat(line, result);
+ break;
+
+ case 'a': { // %A as %V but then writes CRC32
+ char result2[256];
+ i += SearchDICOMObject(DDO, szExecName+i+2, result2);
+ unsigned int crc = ComputeCRC(result2, strlen(result2));
+ sprintf(result2, "%u", crc);
+ strcat(line, result2);
+ break;
+ }
+
+ case 'e': { // %Exxxx,yyyy= changed UID for any UID
+ char result2[256], result3[256];
+ i += SearchDICOMObject(DDO, szExecName+i+2, result2);
+ ChangeUID(result2, "percente", result3);
+ strcat(line, result3);
+ break;
+ }
+
+ case 'r': { // %Rxxxx,yyyy= old UID for any changed UID
+ char result2[256], result3[256];
+ i += SearchDICOMObject(DDO, szExecName+i+2, result2);
+ ChangeUIDBack(result2, result3);
+ strcat(line, result3);
+ break;
+ }
+
+ case 'q': level1 = szExecName[i+2]; // %QXxxxx,yyyy=from db (group and element must have 4 digits)
+ g = htoin(szExecName+i+3, 4);
+ e = htoin(szExecName+i+8, 4);
+
+ switch(level1)
+ { case 'p':
+ case 'P': // %QPxxxx,yyyy=query from patient db on patid
+ SetStringVR(&pVR, 0x0008, 0x0052, "PATIENT");
+ DDO2.Push(pVR);
+ pVR = DDO->GetVR(0x0010, 0x0020);
+ if (pVR && pVR->Length)
+ { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE);
+ memcpy(newVR->Data, pVR->Data, pVR->Length);
+ DDO2.Push(newVR);
+ SetStringVR(&pVR, g, e, "");
+ DDO2.Push(pVR);
+ QueryOnPatient (&DDO2, &ADDO);
+ }
+ break;
+ case 's':
+ case 'S': // %QSxxxx,yyyy=from study db on patid and study uid
+ SetStringVR(&pVR, 0x0008, 0x0052, "STUDY");
+ DDO2.Push(pVR);
+ pVR = DDO->GetVR(0x0010, 0x0020);
+ if (pVR && pVR->Length)
+ { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE);
+ memcpy(newVR->Data, pVR->Data, pVR->Length);
+ DDO2.Push(newVR);
+ pVR = DDO->GetVR(0x0020, 0x000d);
+ if (pVR && pVR->Length)
+ { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE);
+ memcpy(newVR->Data, pVR->Data, pVR->Length);
+ DDO2.Push(newVR);
+ SetStringVR(&pVR, g, e, "");
+ DDO2.Push(pVR);
+ QueryOnStudy (&DDO2, &ADDO);
+ }
+ }
+ break;
+ case 'e':
+ case 'E': // %QExxxx,yyyy=from series db on patid, study and series uid
+ SetStringVR(&pVR, 0x0008, 0x0052, "SERIES");
+ DDO2.Push(pVR);
+ pVR = DDO->GetVR(0x0010, 0x0020);
+ if (pVR && pVR->Length)
+ { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE);
+ memcpy(newVR->Data, pVR->Data, pVR->Length);
+ DDO2.Push(newVR);
+ pVR = DDO->GetVR(0x0020, 0x000d);
+ if (pVR && pVR->Length)
+ { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE);
+ memcpy(newVR->Data, pVR->Data, pVR->Length);
+ DDO2.Push(newVR);
+ pVR = DDO->GetVR(0x0020, 0x000e);
+ if (pVR && pVR->Length)
+ { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE);
+ memcpy(newVR->Data, pVR->Data, pVR->Length);
+ DDO2.Push(newVR);
+ SetStringVR(&pVR, g, e, "");
+ DDO2.Push(pVR);
+ QueryOnSeries (&DDO2, &ADDO);
+ }
+ }
+ }
+ break;
+ case 'w':
+ case 'W': // %QWxxxx,yyyy=from worklist db on accession number
+ SetStringVR(&pVR, 0x0008, 0x0052, "MODALITYWORKLIST");
+ DDO2.Push(pVR);
+ pVR = DDO->GetVR(0x0008, 0x0050);
+ if (pVR && pVR->Length)
+ { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE);
+ memcpy(newVR->Data, pVR->Data, pVR->Length);
+ DDO2.Push(newVR);
+ SetStringVR(&pVR, g, e, "");
+ DDO2.Push(pVR);
+ QueryOnModalityWorkList (&DDO2, &ADDO);
+ }
+ break;
+
+ default:
+ // %QXxxxx,yyyy=from aliasfileqX.txt (tab sep) on xxxx,yyyy
+ char result2[512];
+ FILE *f;
+ char cmd[1024];
+ char *q = line + strlen(line);
+
+ i += SearchDICOMObject(DDO, szExecName+i+3, result2) - 9; // fix for +10 later
+ strcpy(q, result2); // default return original data
+
+ sprintf(cmd, "aliasfileq%c.txt", level1);
+ f = fopen(cmd, "rt");
+ if (f)
+ { while(fgets(cmd, sizeof(cmd), f) != NULL)
+ { if (cmd[strlen(cmd)-1]=='\n') cmd[strlen(cmd)-1]=0;
+ p1 = strchr(cmd, '\t');
+ if (p1)
+ { *p1=0;
+ if (stricmp(result2, cmd)==0)
+ { strcpy(q, p1+1);
+ //i += strlen(p1+1) - strlen(result2); // adjust lenght
+ break;
+ }
+ }
+ }
+ fclose(f);
+ }
+ break;
+ }
+
+ if (ADDO.GetSize()>0) pVR = ADDO.Get(0)->GetVR(g, e);
+ else pVR = NULL;
+
+ if (pVR)
+ { strncpy(vr1, (char*)pVR->Data, pVR->Length);
+ vr1[pVR->Length] = 0;
+ len1 = pVR->Length - 1;
+ while(len1>0)
+ { if (vr1[len1] == ' ')
+ vr1[len1] = 0;
+ else
+ break;
+ len1--;
+ }
+ strcat(line, vr1);
+ }
+
+ for (unsigned int j=0; j<ADDO.GetSize(); j++)
+ { while((pVR=ADDO.Get(j)->Pop()))
+ delete pVR;
+ delete ADDO.Get(j);
+ }
+
+ i+=10;
+ break;
+ }
+ i += 2;
+
+ // get substring of variable [start,end] or [,fromend]
+ if (szExecName[i]=='[')
+ { int a=0, b=-1;
+ if (szExecName[i+1]==',')
+ sscanf(szExecName+i, "[,%d]", &b), a=-1;
+ else
+ sscanf(szExecName+i, "[%d,%d]", &a, &b);
+ for (;i<L;i++) if (szExecName[i-1]==']') break;
+ if (a>(signed int)strlen(ps)) a=strlen(ps);
+ if (a<0) { a = strlen(ps)-b; b = strlen(ps); }
+ if (a<0) a = 0;
+ if (b>(signed int)strlen(ps)) b=strlen(ps);
+ if (b>=a) {memmove(ps, ps+a, b-a+1); ps[b-a+1]=0;}
+ }
+
+ // convert to uppercase
+ if (szExecName[i]=='^')
+ { i++;
+ strupr(ps);
+ }
+ // convert to lowercase
+ else if (szExecName[i]=='~')
+ { i++;
+ strlwr(ps);
+ }
+ }
+ else
+ { l = strlen(line);
+ line[l] = szExecName[i++];
+ line[l+1] = 0;
+ }
+ }
+
+ if (skipping) // {} block being skipped
+ { SystemDebug.printf("%sconverter%d.%d skipped\n", ininame, N, part);
+ }
+
+ else if (rc==4) // ifxxxx statement causes a skip
+ { rc = 0;
+ SystemDebug.printf("%sconverter%d.%d not executed because of previous statement\n", ininame, N, part);
+ }
+
+ /* IMPORT converter: direct forward of received object */
+
+ else if (memicmp(line, "forward to", 10)==0 ||
+ memicmp(line, "forward compressed", 18)==0
+ )
+ { char host[512], port[64], compress[64], dummy[64], Level[64], Temp[66];
+ char *p, *q, *c;
+ RunTimeClassStorage RTCStorage;
+ UID AppUID ("1.2.840.10008.3.1.1.1");
+ UID iUID, uid;
+ VR *vr;
+ int offset = 11, level, channel;
+ DICOMDataObject *pDDO;
+ BOOL StripGroup2;
+ BYTE org[512], dest[512];
+ char script[512];
+ ExtendedPDU_Service *PDU;
+
+ if (N<0 || N>=MAXExportConverters) N = MAXExportConverters-1; // typically from lua
+ PDU = &import_forward_PDU[N*MAXExportConverters];
+ char *ForwardLastUID = ForwardUIDS + 66 * MAXExportConverters * N;
+ pDDO = MakeCopy(DDO);
+
+ // preprocess the forwarder string
+ if (memicmp(line, "forward compressed as ", 22)==0) offset = 28;
+ // xx to where xx = 'is', 'un', 'n0'..'n4', or 'jl', 'jk', 'j0'..'j6'
+ // xxNN same as above but NN is lossy quality
+
+ /// offer transfer syntax (compression) from forward string
+ compress[0]=0;
+ if (offset==28)
+ { compress[0] = line[22];
+ compress[1] = line[23];
+ compress[2] = 0;
+ if (line[24] != ' ')
+ { compress[2] = line[24];
+ compress[3] = line[25];
+ compress[4] = 0;
+ offset = 30;
+ }
+ }
+
+ // get the script clause (to process), must be last
+ script[0] = 0;
+ p = strstr(line + offset, " script ");
+ if (p)
+ { strcpy((char *)script, p+8);
+ p[8] = 0;
+ }
+
+ // get the org clause (originator)
+ strcpy((char *)org, (char *)MYACRNEMA);
+ p = strstr(line + offset, " org ");
+ if (p)
+ { strcpy((char *)org, p+5);
+ q = strchr((char *)org, ' '); if (q) *q=0;
+ }
+
+ // get the dest clause (called AE)
+ dest[0] = 0;
+ p = strstr(line + offset, " dest ");
+ if (p)
+ { strcpy((char *)dest, p+6);
+ q = strchr((char *)dest, ' '); if (q) *q=0;
+ }
+
+ // get the channel clause (to keep multiple associations open)
+ channel = part;
+ p = strstr(line + offset, " channel ");
+ if (p)
+ { if (p[9]=='*') channel = threadnum % MAXExportConverters;
+ else channel = atoi(p+9);
+ if (channel<0 || channel>=MAXExportConverters) channel = 0;
+ }
+
+ // get the "to AE" or "to host:port" clause
+ q = strchr(line+offset, ' '); if (q) *q=0;
+ c=compress;
+ if (compress[0]) c=dummy;
+ if(!GetACRNema(line+offset, (char *)host, (char *)port, (char *)c))
+ { strcpy(host, line+offset);
+ p = strchr(host, ':');
+ if (p)
+ { *p=0;
+ strcpy(port, p+1);
+ }
+ else
+ strcpy(port, "5678");
+ if (offset!=28) strcpy(compress, "UN");
+ }
+
+ OperatorConsole.printf("%sConverter%d.%d: forwarded object to %s\n", ininame, N, channel, line+offset);
+
+ // get UID at selected ForwardAssociationLevel into szTemp
+ vr = NULL;
+ level = 0;
+ MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile);
+ MyGetPrivateProfileString(szRootSC, "ForwardAssociationLevel", "STUDY", Level, 64, ConfigFile);
+ if (strncmp(Level, "PATIENT", 7)==0) level=1;
+ else if (strncmp(Level, "STUDY", 5)==0) level=2;
+ else if (strncmp(Level, "SERIES", 6)==0) level=3;
+ else if (strncmp(Level, "IMAGE", 5)==0) level=4;
+ else if (strncmp(Level, "SOPCLASS",8)==0) level=5, PDU[channel].ClearAbstractSyntaxs();
+ else if (strncmp(Level, "GLOBAL", 6)==0) level=6;
+ szTemp[0] = 0;
+ if (level==1) vr = pDDO->GetVR(0x0010, 0x0020);
+ if (level==2) vr = pDDO->GetVR(0x0020, 0x000d);
+ if (level==3) vr = pDDO->GetVR(0x0020, 0x000e);
+ if (level==4) vr = pDDO->GetVR(0x0008, 0x0018);
+ if (level==5) vr = pDDO->GetVR(0x0008, 0x0016);
+ if (vr) memcpy(szTemp, vr->Data, vr->Length);
+ if (vr) szTemp[vr->Length]=0;
+
+ // get sopclass (to check whether it is accepted at the current connection)
+ vr = pDDO -> GetVR(0x0008, 0x0016);
+ if (!vr)
+ { OperatorConsole.printf("*** %sConverter%d.%d: Forward failed because SopClass is missing\n", ininame, N, channel);
+ }
+
+ if (import_c_init[N][channel]==FALSE)
+ { InitializeCriticalSection(import_critical[N]+channel);
+ import_forward_PDU_time[N][channel] = time(NULL);
+ import_forward_active[N][channel] = FALSE;
+ import_c_init[N][channel]=TRUE;
+ }
+ import_forward_active[N][channel] = TRUE;
+ EnterCriticalSection(import_critical[N]+channel);
+ import_forward_PDU_time[N][channel] = time(NULL);
+
+ // does the existing link accept images of this type - if not then hang up to force a reconnect
+ // also hang up when UID at ForwardAssociationLevel changes to start a new association
+ if (PDU[channel].Link.Connected)
+ { SetUID ( iUID, vr );
+ if (!PDU[channel].IsAbstractSyntaxAccepted(iUID) || strcmp(ForwardLastUID+channel*66, szTemp)!=0 )
+ { //OperatorConsole.printf("!!! ExportConverter%d.%d: attempt to reconnect %s \n", N, channel, szTemp);
+ MyGetPrivateProfileString(szRootSC, "ForwardAssociationRelease", "1", Temp, 64, ConfigFile);
+ if (atoi(Temp)) PDU[channel].Close();
+ else PDU[channel].Link.Close();
+ }
+ }
+
+ // for new check of UID at ForwardAssociationLevel
+ strcpy(ForwardLastUID+channel*66, szTemp);
+
+ // (re)connect
+ if (!PDU[channel].Link.Connected)
+ { PDU[channel].AttachRTC(&VRType);
+ PDU[channel].SetRequestedCompressionType(compress);
+
+ PDU[channel].SetApplicationContext ( AppUID );
+ PDU[channel].SetLocalAddress ( org );
+ if (dest[0])
+ PDU[channel].SetRemoteAddress ( (unsigned char *)(dest) );
+ else
+ PDU[channel].SetRemoteAddress ( (unsigned char *)(line+offset) );
+ PDU[channel].SetTimeOut(TCPIPTimeOut);
+
+ vr = pDDO -> GetVR(0x0008, 0x0016);
+ SetUID ( iUID, vr );
+ PDU[channel].AddAbstractSyntax ( iUID ); // adds type of this image to presentation contexts
+
+ uid.Set("1.2.840.10008.1.1"); // This one should always accept: verification
+ PDU[channel].AddAbstractSyntax(uid); // assures connect will not return FALSE because image is not accepted
+
+ if (!PDU[channel].Connect((unsigned char *)&host, (unsigned char *)&port))
+ { OperatorConsole.printf("*** %sConverter%d.%d: Forward failed to connect to host %s\n", ininame, N, channel, line+offset);
+ }
+ else
+ { vr = pDDO -> GetVR(0x0008, 0x0016);
+ SetUID ( iUID, vr );
+ if (!PDU[channel].IsAbstractSyntaxAccepted(iUID))
+ { OperatorConsole.printf("*** %sConverter%d.%d: DICOM server %s does not accept type of forwarded image\n", ininame, N, channel, line+offset);
+ PDU[channel].Close();
+ }
+ }
+ }
+
+ if (PDU[channel].Link.Connected)
+ { // process data
+ if (script[0])
+ CallImportConverterN(pDDO, -1, NULL, NULL, NULL, NULL, PDU, NULL, script);
+ import_forward_PDU_time[N][channel] = time(NULL);
+
+ // recompress data to be forwarded here according to accepted compression mode; strip group 2 unless "as" or "is"
+ p = PDU[channel].GetAcceptedCompressionType(iUID);
+ StripGroup2 = memicmp(p, "as", 2)!=0 && memicmp(p, "is", 2)!=0;
+ recompress(&pDDO, p, "", StripGroup2, PDU);
+ import_forward_PDU_time[N][channel] = time(NULL);
+
+ RTCStorage.SetUID(iUID);
+
+ if (!RTCStorage.Write(PDU+channel, pDDO))
+ { OperatorConsole.printf("*** %sConverter%d.%d: Forward failed to send DICOM image to %s\n", ininame, N, channel, line+offset);
+ PDU[channel].Close();
+ }
+ else
+ { ImagesForwarded++;
+
+ if (level==4)
+ { MyGetPrivateProfileString(szRootSC, "ForwardAssociationRelease", "1", Temp, 64, ConfigFile);
+ if (atoi(Temp)) PDU[channel].Close();
+ else PDU[channel].Link.Close();
+ }
+ }
+ }
+ import_forward_PDU_time[N][channel] = time(NULL);
+ import_forward_active[N][channel] = FALSE;
+ LeaveCriticalSection(import_critical[N]+channel);
+ Startimport_forward_PDU_close_thread();
+
+ delete pDDO; // write was destructive
+ pDDO = NULL;
+ }
+
+ /* converter: write "string" to file - uses text file, use %n for newline */
+
+ else if (memicmp(line, "write \"", 7)==0)
+ { char string[256];
+ char *file;
+ FILE *f;
+
+ strcpy(string, line+7);
+ p1 = strstr(string, "\" to ");
+ if (!p1) p1 = strstr(string, "\" TO ");
+ if (p1)
+ { *p1=0;
+
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+
+ file = p1+5;
+ f = fopen(file, "wt");
+ if (f)
+ { fputs(string, f);
+ fclose(f);
+ }
+ else
+ OperatorConsole.printf("*** %sconverter%d.%d: Failed to write to file %s\n", ininame, N, part, file);
+ }
+ }
+
+ /* converter: append "string" to file - uses text file, use %n for newline */
+
+ else if (memicmp(line, "append \"", 8)==0)
+ { char string[256];
+ char *file;
+ FILE *f;
+
+ strcpy(string, line+8);
+ p1 = strstr(string, "\" to ");
+ if (!p1) p1 = strstr(string, "\" TO ");
+ if (p1)
+ { *p1=0;
+
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+
+ file = p1+5;
+ f = fopen(file, "at");
+ if (f)
+ { fputs(string, f);
+ fclose(f);
+ }
+ else
+ OperatorConsole.printf("*** Importconverter%d.%d: Failed to append to file %s\n", N, part, file);
+ }
+ }
+
+ // converter: set xxxx,yyyy to "items like %Vxxxx,yyyy or %QP0010,0030"
+ // converter: set PatientID to "items like %VPatientID or %QP0010,0030"
+ // converter: set xxxx,yyyy if "items like %Vxxxx,yyyy or %QP0010,0030"
+ // converter: set xxxx,yyyy/xxxx,yyyy to "items like %Vxxxx,yyyy or %QP0010,0030"
+ // converter: set xxxx,yyyy/xxxx,yyyy if "items like %Vxxxx,yyyy or %QP0010,0030"
+ // converter: set xxxx,yyyy.1/xxxx,yyyy to "items like %Vxxxx,yyyy or %QP0010,0030"
+ // converter: set xxxx,yyyy.1/xxxx,yyyy if "items like %Vxxxx,yyyy or %QP0010,0030"
+ // converter: set xxxx,yyyy.*/xxxx,yyyy to "items like %Vxxxx,yyyy or %QP0010,0030"
+ // converter: set xxxx,yyyy.*/xxxx,yyyy if "items like %Vxxxx,yyyy or %QP0010,0030"
+ // converter: set InstitutionCodeSequence.0/InstitutionName to "test"
+ // converter: set x to "items like %Vxxxx,yyyy or %QP0010,0030"
+ // converter: set x if "items like %Vxxxx,yyyy or %QP0010,0030"
+ // converter: set x format "%%08x" to "items like %Vxxxx,yyyy or %QP0010,0030"
+ // converter: set x format "%%08x" if "items like %Vxxxx,yyyy or %QP0010,0030"
+
+ else if (memicmp(line, "set ", 4)==0)
+ { char string[1024], format[1024];
+ int offset=0;
+ int g2=0, e2=0;
+ unsigned int index=0;
+ char ftype;
+
+ if (strchr("xyzXYZ", line[4]) && line[5]==' ')
+ { g=e=0;
+ offset = 5;
+ }
+ else if (isxdig(line[4]) && line[8]==',')
+ { g = htoin(line+4, 4);
+ e = htoin(line+9, 4);
+ offset = 13;
+ }
+ else if (isalpha(line[4]))
+ { char d[256];
+ int j;
+ RTCElement Entry;
+ strcpy(d, line+4);
+ j=0; while (isalpha(d[j])) j++;
+ d[j]=0;
+ Entry.Description = d;
+ if (VRType.GetGroupElement(&Entry))
+ { g = Entry.Group;
+ e = Entry.Element;
+ offset = j+4;
+ }
+ }
+
+ if (line[offset]=='.')
+ { if (line[offset+1]=='*')
+ { index = 9999;
+ offset += 2;
+ }
+ else
+ { offset++;
+ index = atoi(line+offset);
+ while (isdigit(line[offset])) offset++;
+ }
+ }
+
+ if (line[offset]=='/' && isxdig(line[offset+1]) && line[offset+5]==',')
+ { g2 = htoin(line+offset+1, 4);
+ e2 = htoin(line+offset+6, 4);
+ offset += 10;
+ }
+ else if (line[offset]=='/' && isalpha(line[offset+1]))
+ { char d[256];
+ int j;
+ RTCElement Entry;
+ strcpy(d, line+offset+1);
+ j=0; while (isalpha(d[j])) j++;
+ d[j]=0;
+ Entry.Description = d;
+ if (VRType.GetGroupElement(&Entry))
+ { g2 = Entry.Group;
+ e2 = Entry.Element;
+ offset += j+1;
+ }
+ }
+
+ ftype = 's';
+ if (memicmp(line+offset, " format \"", 9)==0)
+ { offset += 9;
+ strcpy(format, line+offset);
+ p1 = strchr(format, '"');
+ if (p1)
+ { *p1=0;
+ offset += p1-format+1;
+ p1 = strchr(format, '%');
+ if (p1)
+ { while (*p1)
+ { if (*p1=='s' || *p1=='f' || *p1=='x' || *p1=='d' || *p1=='g')
+ { ftype = *p1;
+ break;
+ }
+ else
+ p1++;
+ }
+ }
+ }
+ }
+ else
+ { *format = 0;
+ }
+
+ if (memicmp(line+offset, " to \"", 5)==0 ||
+ memicmp(line+offset, " if \"", 5)==0)
+ { strcpy(string, line+offset+5);
+ p1 = strrchr(string, '"');
+ if (p1)
+ { *p1=0;
+ if (*format)
+ { char dum[1024];
+ strcpy(dum, string);
+ switch (ftype)
+ { case 'd': sprintf(string, format, atoi(dum)); break;
+ case 'x': sprintf(string, format, atoi(dum)); break;
+ case 'f': sprintf(string, format, atof(dum)); break;
+ case 'g': sprintf(string, format, atof(dum)); break;
+ default: sprintf(string, format, dum); break;
+ }
+ }
+
+ int len = strlen(string);
+ VR *vr, *vrs;
+ Array < DICOMDataObject * > *ADDO1 = NULL;
+
+ if (VRType.RunTimeClass(g, e, NULL)=='US')
+ { len = 2;
+ *(unsigned short *)string = atoi(string);
+ }
+ else if (VRType.RunTimeClass(g, e, NULL)=='UL')
+ { len = 4;
+ *(unsigned int *)string = atoi(string);
+ }
+
+ if (len&1)
+ { len++;
+ if (VRType.RunTimeClass(g, e, NULL)!='UI' && VRType.RunTimeClass(g2, e2, NULL)!='UI')
+ strcat(string, " ");
+ }
+
+ if (memicmp(line+offset, " to \"", 4)==0 || len>0) // "set xxxx,xxxx if" does not set when len==0
+ { if (g==0 && e==0) // setting variable
+ { vr = PDU->VariableVRs[tolower(line[4])-'x'];
+ if (!vr) vr = new VR;
+ PDU->VariableVRs[tolower(line[4])-'x'] = vr;
+ }
+ else
+ { vr = DDO->GetVR(g, e);
+
+ if ((g2||e2) && vr && vr->SQObjectArray) // set in existing sequence
+ { ADDO1 = (Array<DICOMDataObject*>*) vr->SQObjectArray;
+ if (index>=ADDO1->GetSize()) // exceeding length of sequence ?
+ { DICOMDataObject *D = new DICOMDataObject; // new item
+ vr = new VR(g2, e2, 0, (void *)NULL, FALSE); // new VR
+ D->Push(vr);
+ ADDO1->Add(D);
+ index = ADDO1->GetSize()-1; // go set this one
+ }
+ else
+ vr = ADDO1->Get(index)->GetVR(g2, e2); // vr maybe in existing item
+ }
+ }
+
+ if(!vr) // vr does not exist
+ { if (g2||e2)
+ { vr = new VR(g2, e2, len, (BOOL)TRUE); // create it in sequence
+ if (ADDO1)
+ ADDO1->Get(index)->Push(vr); // in existing sequence
+ else // in new sequence
+ { Array < DICOMDataObject * > *SQE = new Array < DICOMDataObject * >;
+ DICOMDataObject *D = new DICOMDataObject;
+
+ vrs = new VR(g, e, 0, (void *)NULL, FALSE);
+ vrs->SQObjectArray = (void*) SQE;
+ D->Push(vr);
+ SQE->Add(D);
+ DDO->Push(vrs);
+ }
+ }
+ else
+ { if (VRType.RunTimeClass(g, e, NULL)=='SQ' && !DDO->GetVR(g, e)) // create new sequence
+ { Array < DICOMDataObject * > *SQE = new Array < DICOMDataObject * >;
+ //DICOMDataObject *D = new DICOMDataObject;
+
+ vrs = new VR(g, e, 0, (void *)NULL, FALSE);
+ vrs->SQObjectArray = (void*) SQE;
+ //SQE->Add(D);
+ DDO->Push(vrs);
+ SystemDebug.printf("%sconverter%d.%d created sequence: %04x,%04x\n", ininame, N, part, g, e);
+ vr = NULL;
+ }
+ else
+ { vr = new VR(g, e, len, (BOOL)TRUE);
+ DDO->Push(vr);
+ }
+ }
+ }
+ else
+ vr->ReAlloc(len);
+
+ if (vr)
+ { memcpy(vr->Data, string, len);
+ SystemDebug.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ }
+ }
+ else
+ SystemDebug.printf("%sconverter%d.%d executes void: %s\n", ininame, N, part, line);
+ }
+ }
+ else if (memicmp(line+offset, " to nil", 7)==0)
+ { if ((g||e) && !(g2||e2))
+ { VR *vr = DDO->GetVR(g, e);
+ if (vr)
+ { DDO->DeleteVR(vr);
+ SystemDebug.printf("%sconverter%d.%d deletes: %04x,%04x\n", ininame, N, part, g, e);
+ }
+ }
+ }
+ }
+
+ /* converter: setifempty xxxx,yyyy to "items like %Vxxxx,yyyy or %QP0010,0030" */
+ /* converter: setifempty xxxx,yyyy if "items like %Vxxxx,yyyy or %QP0010,0030" */
+ /* converter: setifempty x to "items like %Vxxxx,yyyy or %QP0010,0030" */
+ /* converter: setifempty y if "items like %Vxxxx,yyyy or %QP0010,0030" */
+
+ else if (memicmp(line, "setifempty ", 11)==0)
+ { char string[1024];
+ int offset=20;
+
+ if (strchr("xyzXYZ", line[11]))
+ { g=e=0;
+ offset = 12;
+ }
+ else
+ { g = htoin(line+11, 4);
+ e = htoin(line+16, 4);
+ }
+
+ if (memicmp(line+offset, " to \"", 4)==0 ||
+ memicmp(line+offset, " if \"", 4)==0)
+ { strcpy(string, line+offset+5);
+ p1 = strrchr(string, '"');
+ if (p1)
+ { VR *vr;
+ *p1=0;
+ int len = strlen(string);
+
+ if (len&1)
+ { len++;
+ strcat(string, " ");
+ }
+
+ if (memicmp(line+offset, " if \"", 4)==0 || len>0) // if does not set when len==0
+ { if (g==0 && e==0)
+ { vr = PDU->VariableVRs[tolower(line[11])-'x'];
+ if (!vr) vr = new VR;
+ PDU->VariableVRs[tolower(line[11])-'x'] = vr;
+ }
+ else
+ vr = DDO->GetVR(g, e);
+
+ if(!vr)
+ { vr = new VR(g, e, len, (BOOL)TRUE);
+ memcpy(vr->Data, string, len);
+ DDO->Push(vr);
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ }
+ else if (vr->Length==0)
+ { vr->ReAlloc(len);
+ memcpy(vr->Data, string, len);
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ }
+ else
+ SystemDebug.printf("%sconverter%d.%d executes void: %s\n", ininame, N, part, line);
+ }
+ else
+ SystemDebug.printf("%sconverter%d.%d executes void: %s\n", ininame, N, part, line);
+ }
+ }
+ }
+
+ /* converter: delete xxxx,yyyy */
+
+ else if (memicmp(line, "delete ", 7)==0)
+ { g = htoin(line+7, 4);
+ e = htoin(line+12, 4);
+
+ pVR = DDO->GetVR(g, e);
+ if (pVR)
+ { DDO->DeleteVR(pVR);
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ }
+ else
+ SystemDebug.printf("%sconverter%d.%d executes void: %s\n", ininame, N, part, line);
+ }
+
+ /* converter: newuids except g,e|uid and newuids */
+
+ else if (memicmp(line, "newuids except ", 15)==0)
+ { char tmp[1024];
+ strcpy(tmp, line+15);
+ strcat(tmp, "|");
+ NewUIDsInDICOMObject(DDO, tmp);
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ }
+
+ else if (memicmp(line, "newuids", 7)==0)
+ { NewUIDsInDICOMObject(DDO, "");
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ }
+
+ /* converter: olduids except g,e|uid and newuids */
+
+ else if (memicmp(line, "olduids except ", 15)==0)
+ { char tmp[1024];
+ strcpy(tmp, line+15);
+ strcat(tmp, "|");
+ OldUIDsInDICOMObject(DDO, tmp);
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ }
+
+ else if (memicmp(line, "olduids", 7)==0)
+ { OldUIDsInDICOMObject(DDO, "");
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ }
+
+ /* converters: fixkodak (remove leading 0 in 8 digit PATID), unfixkodak (add leading 0 in 8 digit PATID) */
+
+ else if (memicmp(line, "fixkodak", 8)==0)
+ { KodakFixer(DDO, FALSE);
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ }
+
+ else if (memicmp(line, "unfixkodak", 10)==0)
+ { KodakFixer(DDO, TRUE);
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ }
+
+ /* import converter: copy file to file; copy file to directory */
+
+ else if (memicmp(line, "copy ", 5)==0)
+ { char string[1024];
+ char *file;
+ struct stat statbuf;
+ char *p;
+
+ strcpy(string, line+5);
+ p = strstr(string, " to ");
+ if (!p) p = strstr(string, " TO ");
+ if (p)
+ { *p=0;
+
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+
+ file = p+4;
+
+ /* if the destination a directory then append the source filename to it */
+
+ stat(file, &statbuf);
+ if (statbuf.st_mode & S_IFDIR)
+ { p = strrchr(pszFileName, PATHSEPCHAR);
+ if (p)
+ { if (file[strlen(file)-1]==PATHSEPCHAR)
+ file[strlen(file)-1]=0;
+ strcat(file, p);
+ }
+ }
+
+ if (!DFileCopy2(string, file, 0))
+ OperatorConsole.printf("*** Exportconverter%d.%d: Failed to copy %s to %s\n", N, part, string, file);
+ else
+ ImagesCopied++;
+ }
+ }
+
+ /* converter: save to filename (filename can be generated using all % tricks) */
+
+ else if (memicmp(line, "save to ", 8)==0)
+ { char *file = line+8;
+
+ OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+
+ DICOMDataObject *pDDO = MakeCopy(DDO);
+ SaveDICOMDataObject(file, pDDO);
+ delete pDDO;
+ }
+
+ /* converter: save frame N to filename (filename can be generated using all % tricks) */
+
+ else if (memicmp(line, "save frame ", 11)==0)
+ { char *p2 = strstr(line, " to ");
+ char *file = p2 + 4;
+ int frame = atoi(line+11);
+
+ if (p2)
+ { OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+
+ DICOMDataObject *pDDO = MakeCopy(DDO);
+ ExtractFrame(pDDO, frame);
+ SaveDICOMDataObject(file, pDDO);
+ delete pDDO;
+ }
+ }
+
+ /* converter: save bmp [frame N] [size N] filename (filename can be generated using all % tricks) */
+
+ else if (memicmp(line, "save bmp ", 9)==0 ||
+ memicmp(line, "save gif ", 9)==0 ||
+ memicmp(line, "save jpg ", 9)==0)
+ { int level=0, window=0, frame=0, size=0;
+ char *file=NULL, *p2;
+ p2 = strstr(line, " to ");
+ if (p2) file = p2 + 4;
+ p2 = strstr(line, " as ");
+ if (p2) file = p2 + 4;
+ p2 = strstr(line, " level ");
+ if (p2) level = atoi(p2+7);
+ p2 = strstr(line, " window ");
+ if (p2) window = atoi(p2+8);
+ p2 = strstr(line, " frame ");
+ if (p2) frame = atoi(p2+7);
+ p2 = strstr(line, " size ");
+ if (p2) size = atoi(p2+6);
+ if (size<10) size = 4096;
+
+ if (file)
+ { OperatorConsole.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+
+ if (memicmp(line + 5, "bmp ", 4)==0) ToBMP(DDO, file, size, 0, level, window, frame);
+ else if (memicmp(line + 5, "gif ", 4)==0) ToGif(DDO, file, size, 0, level, window, frame);
+ else ToJPG(DDO, file, size, 0, level, window, frame, 95);
+ }
+ }
+
+ /* converter: process with (command line can be generated using all % tricks, tempfile appended) */
+
+ else if (memicmp(line, "process with ", 13)==0)
+ { char cline[512];
+ char tempfile[512];
+ DICOMDataObject *DO2;
+
+ PDU_Service PDU;
+ PDU.AttachRTC(&VRType);
+
+ NewTempFile(tempfile, ".dcm");
+ strcpy(cline, line+13);
+ if (cline[strlen(cline)-1]!=' ') strcat(cline, " ");
+ strcat(cline, tempfile);
+
+ OperatorConsole.printf("%sconverter%d.%d executes: process with %s\n", ininame, N, part, cline);
+
+ SaveDICOMDataObject(tempfile, DDO);
+ DDO->Reset();
+
+ system(cline);
+
+ DO2 = PDU.LoadDICOMDataObject(tempfile);
+ while (( pVR = DO2->Pop() ))
+ { DDO->Push(pVR);
+ }
+ delete DO2;
+ }
+
+ /* converter: tomono */
+ else if (memicmp(line, "tomono", 6)==0)
+ { DcmConvertPixelData(DDO, TRUE, FALSE, 0, 0, 0, 0, 0.0, 0.0, 0.0);
+ SystemDebug.printf("%sconverter%d.%d: %s\n", ininame, N, part, line);
+ }
+
+ /* converter: crop */
+ else if (memicmp(line, "crop ", 5)==0)
+ { int startx=0, endx=9999, starty=0, endy=9999;
+ sscanf(line+5, "%d,%d,%d,%d", &startx, &starty, &endx, &endy);
+ DcmConvertPixelData(DDO, FALSE, TRUE, startx, endx, starty, endy, 0.0, 0.0, 0.0);
+ SystemDebug.printf("%sconverter%d.%d: %s\n", ininame, N, part, line);
+ }
+
+ /* converter: system (command line can be generated using all % tricks) */
+
+ else if (memicmp(line, "system ", 7)==0)
+ { char cline[512];
+ strcpy(cline, line+7);
+ // BackgroundExec(cline, "");
+ system(cline);
+ SystemDebug.printf("%sconverter%d.%d: %s\n", ininame, N, part, line);
+ }
+
+ /* converter: mkdir (command line can be generated using all % tricks) */
+
+ else if (memicmp(line, "mkdir ", 6)==0)
+ { char cline[512], s[512];
+ strcpy(cline, line+6);
+ for (int sIndex = 0; sIndex<=strlen(cline); sIndex++)
+ if (cline[sIndex]==PATHSEPCHAR)
+ { strcpy(s, cline);
+ s[sIndex]='\0';
+ mkdir(s);
+ }
+ mkdir(cline); // 20120829
+ SystemDebug.printf("%sconverter%d.%d: %s\n", ininame, N, part, line);
+ }
+
+ /* converter: rm (command line can be generated using all % tricks) */
+
+ else if (memicmp(line, "rm ", 3)==0)
+ { char cline[512];
+ strcpy(cline, line+3);
+ unlink(cline);
+ SystemDebug.printf("%sconverter%d.%d: %s\n", ininame, N, part, line);
+ }
+
+ /* converter: destroy (will prevent the image from being stored in the database) */
+
+ else if (memicmp(line, "destroy", 7)==0 && calling && called)
+ { OperatorConsole.printf("%sconverter%d.%d: destroyed received image\n", ininame, N, part);
+ rc = 2;
+ }
+
+ else if (memicmp(line, "reject", 6)==0 && calling && called)
+ { OperatorConsole.printf("%sconverter%d.%d: rejected received image\n", ininame, N, part);
+ rc = 6;
+ }
+
+ else if (memicmp(line, "retry", 6)==0 && (N==2100 || N==2200))
+ { OperatorConsole.printf("%sconverter%d.%d: retry storing rejected image\n", ininame, N, part);
+ rc = 7;
+ }
+
+ else if (memicmp(line, "defer", 5)==0)
+ { OperatorConsole.printf("%sconverter%d.%d: defer for exportconverter\n", ininame, N, part);
+ rc = 8;
+ }
+
+ /* converter: storage (sets preferred device for storing image, e.g, STORAGE MAG1) */
+ /* disabled for general scripting */
+
+ else if (memicmp(line, "storage ", 8)==0 && called && calling)
+ { if (Storage) OperatorConsole.printf("%sconverter%d.%d: sets preferred storage to %s\n", ininame, N, part, line+8);
+ if (Storage) strcpy(Storage, line+8);
+ }
+
+ else if (memicmp(line, "testmode ", 9)==0)
+ { OperatorConsole.printf("%sconverter%d.%d: sets testmode to %s\n", ininame, N, part, line+9);
+ strcpy(TestMode, line+9);
+ }
+
+ /* converter: virtualservermask (only useful to insert into queries, moves) */
+
+ else if (memicmp(line, "virtualservermask ", 18)==0 && called && calling)
+ { OperatorConsole.printf("%sconverter%d.%d: sets virtual server mask to %d\n", ininame, N, part, atoi(line+18));
+ DDO->ChangeVR(0x9999, 0x0802, (UINT16) atoi(line+18), 0);
+ }
+
+ /* converter: virtualserver (only useful to insert into queries, moves) */
+
+ else if (memicmp(line, "virtualserver ", 14)==0 && called && calling)
+ { OperatorConsole.printf("%sconverter%d.%d: enables virtual server %d\n", ininame, N, part, atoi(line+14));
+ DDO->ChangeVR(0x9999, 0x0802, (UINT16)(DDO->GetUINT16(0x9999, 0x0802) | (1 << atoi(line+14))), 0);
+ }
+
+ /* converter: compression (sets preferred compression for storing image, e.g, COMPRESSION un) */
+
+ else if (memicmp(line, "compression ", 12)==0)
+ { OperatorConsole.printf("%sconverter%d.%d: compression to %s\n", ininame, N, part, line+12);
+
+ DICOMDataObject *DO2 = MakeCopy(DDO);
+ recompress(&DO2, line+12, "", line[12]=='n' || line[12]=='N', PDU);
+ DDO->Reset();
+ while (( pVR = DO2->Pop() ))
+ { DDO->Push(pVR);
+ }
+ delete DO2;
+ }
+
+ /* converter: prefetch */
+
+ else if (memicmp(line, "prefetch", 8)==0)
+ { char pat[256];
+ SearchDICOMObject(DDO, "0010,0020", pat);
+ if (prefetch_queue("prefetch", pat, "", "", "", "", "", "", "", "", "", 0, ""))
+ OperatorConsole.printf("%sconverter%d.%d: queued prefetch %s\n", ininame, N, part, pat);
+ }
+
+ /* converter: preretrieve */
+
+ else if (memicmp(line, "preretrieve ", 12)==0)
+ { char pat[256];
+ SearchDICOMObject(DDO, "0010,0020", pat);
+ if (prefetch_queue("preretrieve", pat, line+12, "", "", "", "", "", "", "", "", 0, ""))
+ OperatorConsole.printf("%sconverter%d.%d: queued preretrieve of patient %s from %s\n", ininame, N, part, pat, line+12);
+ }
+
+ else if (memicmp(line, "forward patient ", 16)==0 ||
+ memicmp(line, "forward study ", 14)==0 ||
+ memicmp(line, "forward series ", 15)==0 ||
+ memicmp(line, "forward image ", 14)==0 ||
+ memicmp(line, "get patient ", 12)==0 ||
+ memicmp(line, "get study ", 10)==0 ||
+ memicmp(line, "get series ", 11)==0 ||
+ memicmp(line, "get image ", 10)==0 ||
+ memicmp(line, "delete patient ", 15)==0 ||
+ memicmp(line, "delete study ", 13)==0 ||
+ memicmp(line, "delete series ", 14)==0 ||
+ memicmp(line, "delete image ", 13)==0 ||
+ memicmp(line, "delete patient", 15)==0 ||
+ memicmp(line, "delete study", 12)==0 ||
+ memicmp(line, "delete series", 13)==0 ||
+ memicmp(line, "delete image", 12)==0 ||
+ memicmp(line, "process patient ", 16)==0 ||
+ memicmp(line, "process study ", 14)==0 ||
+ memicmp(line, "process series ", 15)==0 ||
+ memicmp(line, "process image ", 14)==0 ||
+ memicmp(line, "merge study ", 12)==0 ||
+ memicmp(line, "submit patient ", 15)==0 ||
+ memicmp(line, "submit study ", 13)==0 ||
+ memicmp(line, "submit series ", 14)==0 ||
+ memicmp(line, "submit image ", 13)==0 ||
+ memicmp(line, "submit2 patient ", 16)==0 ||
+ memicmp(line, "submit2 study ", 14)==0 ||
+ memicmp(line, "submit2 series ", 15)==0 ||
+ memicmp(line, "submit2 image ", 14)==0)
+ { char *p = strchr(line, ' ')+1; const char *compress="", *dest="", *date="", *modality="", *sop="", *imagetype="", *seriesdesc="", *script="";
+ char studyuid[65], seriesuid[65], vr[200], dat[200];
+ VR *pVR1;
+ int len, delay=0;
+
+ studyuid[0]=0;
+ seriesuid[0]=0;
+
+ const char *level=p;
+ p = strchr(p, ' ');
+ while(p)
+ { *p=0;
+ p++;
+
+ if (memicmp(p, "compressed as ", 14)==0)
+ { compress = p+14;
+ p = strchr(p+14, ' ');
+ }
+ else if (memicmp(p, "to ", 3)==0)
+ { dest = p+3;
+ p = strchr(p+3, ' ');
+ }
+ else if (memicmp(p, "after ", 6)==0)
+ { delay = atoi(p+6);
+ p = strchr(p+6, ' ');
+ }
+ else if (memicmp(p, "by ", 3)==0)
+ { dest = p+3;
+ p = NULL; // strchr(p+3, ' ');
+ }
+ else if (memicmp(p, "from ", 5)==0)
+ { dest = p+5;
+ p = strchr(p+5, ' ');
+ }
+ else if (memicmp(p, "date ", 5)==0) // all series date yyyymmdd or yyyymmdd-yyyymmdd
+ { date = p+5;
+ p = strchr(p+5, ' ');
+ level = "selection"; // causes that no study or series UID are passed to query
+ }
+ else if (memicmp(p, "now ", 4)==0) // now -365+365: within one year from now (+/- compulsory)
+ { struct tm tmbuf1, tmbuf2; // also works on all series within date range
+ char *q;
+ int from=0, to=0;
+ from=atoi(p+4);
+ q = strchr(p+5, '+'); if (!q) q = strchr(p+5, '-'); if (q) to=atoi(q);
+
+ time_t t1 = time(NULL)+24*3600*from;
+ time_t t2 = time(NULL)+24*3600*to;
+ localtime_r(&t1, &tmbuf1);
+ localtime_r(&t2, &tmbuf2);
+
+ sprintf(dat, "%04d%02d%02d-%04d%02d%02d", tmbuf1.tm_year+1900, tmbuf1.tm_mon, tmbuf1.tm_mday, tmbuf2.tm_year+1900, tmbuf2.tm_mon, tmbuf2.tm_mday);
+ date = dat;
+
+ p = strchr(p+4, ' ');
+ level = "selection"; // causes that no study or series UID passed to query
+ }
+ else if (memicmp(p, "age ", 4)==0) // age -365+365: within one year from series date (+/- compulsory)
+ { struct tm tmbuf1, tmbuf2; // also works on all series withon date range
+ char *q;
+ int from=0, to=0;
+ from=atoi(p+4);
+ q = strchr(p+5, '+'); if (!q) q = strchr(p+5, '-'); if (q) to=atoi(q);
+
+ SearchDICOMObject(DDO, "0008,0020", dat);
+ memset(&tmbuf1, 0, sizeof(tmbuf1));
+ sscanf(dat, "%04d%02d%02d", &tmbuf1.tm_year, &tmbuf1.tm_mon, &tmbuf1.tm_mday);
+ tmbuf1.tm_year -= 1900;
+
+ time_t t = mktime(&tmbuf1);
+ time_t t1 = t+24*3600*from;
+ time_t t2 = t+24*3600*to;
+ localtime_r(&t1, &tmbuf1);
+ localtime_r(&t2, &tmbuf2);
+
+ sprintf(dat, "%04d%02d%02d-%04d%02d%02d", tmbuf1.tm_year+1900, tmbuf1.tm_mon, tmbuf1.tm_mday, tmbuf2.tm_year+1900, tmbuf2.tm_mon, tmbuf2.tm_mday);
+ date = dat;
+
+ p = strchr(p+4, ' ');
+ level = "selection"; // causes that no study or series UID passed to query
+ }
+ else if (memicmp(p, "modality ", 9)==0)
+ { modality = p+9;
+ p = strchr(p+9, ' ');
+ level = "selection"; // causes that no study or series UID is passed to query
+ }
+ else if (memicmp(p, "sop ", 4)==0)
+ { sop = p+4;
+ p = strchr(p+4, ' ');
+ level = "selection"; // causes that no study or series UID is passed to query except the given SOP
+ }
+ else if (memicmp(p, "imagetype ", 10)==0)
+ { imagetype = p+10;
+ p = strchr(p+10, ' ');
+ level = "study"; // causes that no series UID is passed to query
+ }
+ else if (memicmp(p, "target ", 7)==0) // for DcmSubmit only
+ { imagetype = p+7;
+ p = strchr(p+7, ' ');
+ }
+ else if (memicmp(p, "seriesdesc ", 11)==0)
+ { seriesdesc = p+11;
+ p = strchr(p+11, ' ');
+ level = "study"; // causes that no series UID is passed to query
+ }
+ else if (memicmp(p, "password ", 9)==0) // for DcmSubmit only
+ { seriesdesc = p+9;
+ p = strchr(p+9, ' ');
+ }
+ else if (memicmp(p, "script \"", 8)==0)
+ { if (p[strlen(p)-1]=='"') p[strlen(p)-1]=0;
+ script = p+8; // must be last parameter
+ p = NULL;
+ break;
+ }
+ else if (memicmp(p, "script ", 7)==0) // script without ""
+ { script = p+7; // must be last parameter
+ p = NULL;
+ break;
+ }
+ else if (memicmp(p, "series ", 7)==0)
+ { char *a=p+7;
+ p = strchr(p+7, ' ');
+ *p=0;
+ strcpy(seriesuid, a);
+ level = "selection"; // causes that no study UID is passed and give series
+ }
+ else if (memicmp(p, "study ", 6)==0)
+ { char *a=p+6;
+ p = strchr(p+6, ' ');
+ *p=0;
+ strcpy(studyuid, a);
+ level = "selection"; // causes that no series UID is passed and give study
+ }
+ }
+
+ pVR1 = DDO->GetVR(0x0020, 0x000d);
+ if (pVR1 && (memicmp(level, "stu", 3)==0 || memicmp(level, "ser", 3)==0) || memicmp(level, "ima", 3)==0)
+ { strncpy(vr, (char*)pVR1->Data, pVR1->Length);
+ vr[pVR1->Length] = 0;
+ len = pVR1->Length - 1;
+ while(len>0)
+ { if (vr[len] == ' ')
+ vr[len] = 0;
+ else
+ break;
+ len--;
+ }
+ strcpy(studyuid, vr);
+ }
+
+ pVR1 = DDO->GetVR(0x0020, 0x000e);
+ if (pVR1 && (memicmp(level, "ser", 3)==0 || memicmp(level, "ima", 3)==0))
+ { strncpy(vr, (char*)pVR1->Data, pVR1->Length);
+ vr[pVR1->Length] = 0;
+ len = pVR1->Length - 1;
+ while(len>0)
+ { if (vr[len] == ' ')
+ vr[len] = 0;
+ else
+ break;
+ len--;
+ }
+ strcpy(seriesuid, vr);
+ }
+
+ pVR1 = DDO->GetVR(0x0008, 0x0018);
+ if (pVR1 && memicmp(level, "ima", 3)==0)
+ { strncpy(vr, (char*)pVR1->Data, pVR1->Length);
+ vr[pVR1->Length] = 0;
+ len = pVR1->Length - 1;
+ while(len>0)
+ { if (vr[len] == ' ')
+ vr[len] = 0;
+ else
+ break;
+ len--;
+ }
+ sop = vr;
+ }
+
+ line[11]=0;
+ if (sop) level = "single object";
+ char pat[256];
+ SearchDICOMObject(DDO, "0010,0020", pat);
+ if (prefetch_queue(line, pat, dest, studyuid, seriesuid, compress, modality, date, sop, imagetype, seriesdesc, delay, script))
+ OperatorConsole.printf("%sconverter%d.%d: queued %s - (%s %s %s of %s) to %s\n", ininame, N, part, line, level, modality, date, pat, dest);
+ }
+
+ /* converter: stop and silentstop (will prevent further converters from running for this image) */
+
+ else if (memicmp(line, "stop", 4)==0)
+ { SystemDebug.printf("%sconverter%d.%d: stop\n", ininame, N, part);
+ rc = 3;
+ }
+
+ else if (memicmp(line, "silentstop", 10)==0)
+ { rc = 3;
+ }
+
+ else if (memicmp(line, "return", 6)==0)
+ { SystemDebug.printf("%sconverter%d.%d: return\n", ininame, N, part);
+ rc = 5;
+ }
+
+ else if (memicmp(line, "call ", 5)==0)
+ { FILE *f;
+ int ret;
+ char cmd[1024];
+
+ cmd[0]=0;
+ MyGetPrivateProfileString ( "scripts", line+5, cmd, cmd, 1024, ConfigFile);
+ if (*cmd)
+ ret = CallImportConverterN(DDO, -1, NULL, NULL, NULL, NULL, PDU, Storage, cmd);
+ else
+ { f = fopen(line+5, "rt");
+ if (f)
+ { SystemDebug.printf("%sconverter%d.%d: %s\n", ininame, N, part, line);
+ while(fgets(cmd, sizeof(cmd), f) != NULL)
+ { if (cmd[strlen(cmd)-1]=='\n') cmd[strlen(cmd)-1]=0;
+ if (cmd[0]!='#' && cmd[0]!=';')
+ { // ret = CallImportConverterN(DDO, -1, NULL, NULL, NULL, NULL, NULL, NULL, Storage, cmd, vars);
+ ret = CallImportConverterN(DDO, -1, NULL, NULL, NULL, NULL, PDU, Storage, cmd);
+ if (ret==5 || ret==2 || ret==6) break; // return or destroy or reject
+ }
+ }
+ fclose(f);
+ }
+ else
+ OperatorConsole.printf("*** %sconverter%d.%d script not found: %s\n", ininame, N, part, line+5);
+ }
+ rc = ret;
+ }
+
+ /* converter: script, evaluate string as script */
+
+ else if (memicmp(line, "script \"", 8)==0)
+ { char cmd[1024];
+ strcpy(cmd, line+8);
+ cmd[strlen(cmd)-1]=0;
+ rc = CallImportConverterN(DDO, -1, NULL, NULL, NULL, NULL, PDU, Storage, cmd);
+ }
+
+ /* converter: lua, evaluate string as lua program */
+
+ else if (memicmp(line, "lua \"", 5)==0)
+ { char cmd[1024];
+ // note; threadnum and dco not implemented
+ struct scriptdata sd = {PDU, NULL, DDO, N, pszModality, pszStationName, pszSop, patid, Storage, 0, 0};
+ strcpy(cmd, line+5);
+ cmd[strlen(cmd)-1]=0;
+ do_lua(&(PDU->L), cmd, &sd);
+ rc = sd.rc;
+ }
+
+ /* converter: if "string" (only execute next converter if string not empty) */
+
+ else if (memicmp(line, "ifnotempty \"", 12)==0)
+ { char string[1024];
+ char *p;
+
+ strcpy(string, line+12);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ SystemDebug.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+
+ int len = strlen(string);
+ if (len==0) rc = 4;
+ }
+ }
+
+ /* converter: ifempty "string" (only execute next converter if string empty) */
+
+ else if (memicmp(line, "ifempty \"", 9)==0)
+ { char string[1024];
+ char *p;
+
+ strcpy(string, line+9);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ SystemDebug.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+
+ int len = strlen(string);
+ if (len!=0) rc = 4;
+ }
+ }
+
+ /* converter: ifequal "string1","string2" (only execute next converter if string1 equals string2) */
+
+ else if (memicmp(line, "ifequal \"", 9)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+9);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ int cmp = strcmp(string, string2);
+ if (cmp!=0) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifnotequal "string1","string2" (only execute next converter if string1 not equals string2) */
+
+ else if (memicmp(line, "ifnotequal \"", 12)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+12);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ int cmp = strcmp(string, string2);
+ if (cmp==0) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifmatch "string1","string2" (only execute next converter if string1 matches string2 - case insensitive) */
+
+ else if (memicmp(line, "ifmatch \"", 9)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+9);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ if (!match(string, string2)) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifnotmatch "string1","string2" (only execute next converter if string1 not matches string2 - case insensitive) */
+
+ else if (memicmp(line, "ifnotmatch \"", 12)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+12);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ if (match(string, string2)) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifnumequal "string1","string2" (only execute next converter if string1 num equals string2 - integer) */
+
+ else if (memicmp(line, "ifnumequal \"", 12)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+12);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ if (atoi(string)!=atoi(string2)) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifnumnotequal "string1","string2" (only execute next converter if string1 num not equals string2 - integer) */
+
+ else if (memicmp(line, "ifnumnotequal \"", 15)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+15);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ if (atoi(string)==atoi(string2)) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifnumgreater "string1","string2" (only execute next converter if string1 num greater than string2 num - integer) */
+
+ else if (memicmp(line, "ifnumgreater \"", 14)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+14);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ if (atoi(string)<=atoi(string2)) rc = 4;
+ }
+ }
+ }
+
+ /* converter: ifnumless "string1","string2" (only execute next converter if string1 num less than string2 num - integer) */
+
+ else if (memicmp(line, "ifnumless \"", 11)==0)
+ { char string[1024];
+ char *p, *string2;
+
+ strcpy(string, line+11);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ SystemDebug.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ if (atoi(string)>=atoi(string2)) rc = 4;
+ }
+ }
+ }
+
+ /* converter: between "string1","string2" (execute next converter on time in hours: between "9", "17"; defer) */
+
+ else if (memicmp(line, "between \"", 9)==0)
+ { char string[1024];
+ char *p, *string2;
+ int h1, h2, h;
+ struct tm tmbuf;
+ time_t t = time(NULL);
+
+ localtime_r(&t, &tmbuf);
+ h = tmbuf.tm_hour;
+
+ strcpy(string, line+9);
+ h1 = atoi(string);
+ p = strrchr(string, '"');
+ if (p)
+ { *p=0;
+
+ p = strstr(string, "\",\"");
+ if (!p) p = strstr(string, "\", \"");
+ if (p)
+ { string2 = strchr(p+1, '"')+1;
+ *p=0;
+ h2 = atoi(string2);
+ SystemDebug.printf("%sconverter%d.%d executes: %s\n", ininame, N, part, line);
+ if (h2>=h1 && (h <h1 || h>=h2)) rc = 4; // between "9", "17": skip if h<9 or h>=17
+ if (h2< h1 && (h <h1 && h>=h2)) rc = 4; // between "17", "9": skip if h<=17 and h>=9
+ }
+ }
+ }
+
+ /* converter: nop (no operation) */
+
+ else if (memicmp(line, "nop", 3)==0)
+ { OperatorConsole.printf("%sconverter%d.%d: %s\n", ininame, N, part, line);
+ }
+
+ /* unrecognized command: assume call line or file */
+
+ else if (*line)
+ { FILE *f;
+ int ret;
+ char cmd[1024];
+
+ cmd[0]=0;
+ MyGetPrivateProfileString ( "scripts", line, cmd, cmd, 1024, ConfigFile);
+ if (*cmd)
+ ret = CallImportConverterN(DDO, -1, NULL, NULL, NULL, NULL, PDU, Storage, cmd);
+ else
+ { char *b = strchr(line,'(');
+ if (b) *b=0;
+ f = fopen(line, "rt");
+ if (f)
+ { if (strstr(line, ".lua")) // direct call of lua file
+ { int i, n;
+ fclose(f);
+
+ char script[512];
+ strcpy(script, "dofile('");
+ for (i=0, n=8; i<strlen(line); i++)
+ { if (line[i]=='\\')
+ { script[n++] = '\\';
+ script[n++] = '\\';
+ }
+ else
+ { script[n++] = line[i];
+ }
+ }
+ script[n++] = 0;
+ strcat(script, "')");
+
+ // accept file.lua(%i:%p) or e.g., file.lua("%i:%p"), substituted string goes unparsed to command_line
+
+ if (b)
+ { b++;
+ if (b[0]=='"')
+ { b++;
+ if (b[strlen(b)-2]=='"')
+ b[strlen(b)-2] = 0;
+ }
+ else if (b[strlen(b)-1]==')')
+ b[strlen(b)-1] = 0;
+
+ lua_setvar(PDU, "command_line", b);
+ lua_setvar(PDU, "version", DGATE_VERSION);
+ }
+
+ // note; threadnum and dco not implemented
+ struct scriptdata sd = {PDU, NULL, DDO, N, pszModality, pszStationName, pszSop, patid, Storage, 0, 0};
+ SystemDebug.printf("Importconverter%d.%d: %s\n", N, part, script);
+ do_lua(&(PDU->L), script, &sd);
+ rc = sd.rc;
+ }
+ else
+ { SystemDebug.printf("%sconverter%d.%d: %s\n", ininame, N, part, line);
+ while(fgets(cmd, sizeof(cmd), f) != NULL)
+ { if (cmd[strlen(cmd)-1]=='\n') cmd[strlen(cmd)-1]=0;
+ if (cmd[0]!='#' && cmd[0]!=';' && cmd[0]!=0)
+ { ret = CallImportConverterN(DDO, -1, NULL, NULL, NULL, NULL, PDU, Storage, cmd);
+ if (ret==5 || ret==2 || ret==6) break; // return or destroy or reject
+ }
+ }
+ fclose(f);
+ }
+ }
+ else
+ OperatorConsole.printf("*** %sconverter%d.%d error: %s\n", ininame, N, part, line);
+ }
+ rc = ret;
+ }
+
+ // process next command
+ if (szNext[0]==0) break;
+ strcpy(szExecName, szNext);
+ part++;
+
+ if (rc==3 || rc==2 || rc==5 || rc==6) break;
+ // stop destroy return reject
+ }
+
+ return rc;
+}
+
+int CallImportConverters(DICOMDataObject *DDO, char *pszModality, char *pszStationName, char *pszSop, char *patid, ExtendedPDU_Service *PDU, char *Storage)
+{ char szRootSC[64];
+// char szEntry[32];
+ char szTemp[32];
+ int i, iNbConverters;
+ int rc;
+
+ if (!MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig,
+ szRootSC, 64, ConfigFile)) return FALSE;
+ if (!MyGetPrivateProfileString(szRootSC, "ImportConverters", "99",
+ szTemp, 128, ConfigFile)) return FALSE;
+ iNbConverters = atoi(szTemp);
+
+ /* Loop over all converters */
+ rc = 0;
+ for(i=0; i<iNbConverters; i++)
+ { rc = CallImportConverterN(DDO, i, pszModality, pszStationName, pszSop, patid, PDU, Storage, NULL);
+
+ if (rc==2) break;
+ // destroy
+
+ if (rc==6) break;
+ // reject
+ }
+
+ // the status of the last one is returned: FALSE means destroy command (status 2) was executed
+ //return !(rc==2);
+
+ return rc;
+}
+
+//////////////////////////////////////////////////////////////////////////////////
+/* This code is a simple thread safe queue with its own processing thread */
+//////////////////////////////////////////////////////////////////////////////////
+
+struct conquest_queue
+{ int top;
+ int bottom;
+ int num;
+ int entrysize;
+ char *data;
+#ifdef WIN32
+ HANDLE threadhandle;
+#else
+ pthread_t threadhandle;
+#endif
+ CRITICAL_SECTION critical;
+ int delay;
+ BOOL (*process) (char *, ExtendedPDU_Service *PDU, char *);
+ BOOL (*mayprocess)(char *, ExtendedPDU_Service *PDU, char *);
+ int fails; // counts failures
+ time_t lastfailtime; // set on failure, cleared on success
+ int maxfails; // if set and exceeded stop retrying
+ char failfile[512]; // file to store failed entries in
+
+ ExtendedPDU_Service *PDU; // to allow keeping association open
+ time_t opentime; // set on success
+ int pdu_refreshdelay; // clear accepted syntaxes after .. s (use long time)
+ int pdu_closedelay; // close unused pdu after .. s (use short time)
+ int pdu_release; // if set, release pdu else just drop link
+ char *ForwardLastUID; // remember last uid of link (hang up?)
+} q1;
+
+static BOOL WINAPI processthread(struct conquest_queue *q)
+{ char *data = (char *)malloc(q->entrysize);
+
+ while (1)
+ { while (1)
+ { EnterCriticalSection(&q->critical);
+
+ if (q->top!=q->bottom)
+ { memcpy(data, q->data + q->bottom * q->entrysize, q->entrysize);
+
+ // it is possible to delay processing of queue through this function
+
+ if (q->mayprocess)
+ { if (!q->mayprocess(data, q->PDU, q->ForwardLastUID))
+ { LeaveCriticalSection(&q->critical);
+ Sleep(q->delay);
+ continue;
+ }
+ }
+
+ q->bottom = (q->bottom+1)%q->num;
+ LeaveCriticalSection(&q->critical);
+
+ // only try to process if last failure was more than FailHoldOff seconds ago
+
+ if (time(NULL)-q->lastfailtime > FailHoldOff)
+ { if (q->process(data, q->PDU, q->ForwardLastUID))
+ { q->lastfailtime = time(NULL); // failed
+ q->fails++;
+
+ // store failures
+ if (q->failfile[0])
+ { FILE *f = fopen(q->failfile, "ab");
+ if (f)
+ { fwrite(data, q->entrysize, 1, f);
+ fclose(f);
+ OperatorConsole.printf("*** Queue: holding processing of file %s\n", data);
+ }
+ }
+ }
+ else
+ { q->lastfailtime= 0; // remember that last process was a success
+ q->opentime = time(NULL); // PDU must be open by now
+ q->fails = 0;
+ }
+ }
+ else
+ { // store failures (actually these were not even tried)
+ if (q->failfile[0])
+ { FILE *f = fopen(q->failfile, "ab");
+ if (f)
+ { fwrite(data, q->entrysize, 1, f);
+ fclose(f);
+ OperatorConsole.printf("*** Queue: holding processing of file %s\n", data);
+ }
+ }
+ }
+
+ break; // this break avoids delays when the queue is not empty
+ }
+
+ LeaveCriticalSection(&q->critical);
+
+ Sleep(q->delay);
+
+ // Retry logic: RetryDelay s after last failure retry to process the data
+ // This condition would also be at startup: therefore wait until DB completely indexed
+
+ if (time(NULL)-q->lastfailtime>RetryDelay && q->failfile[0] && NumIndexing==0)
+ { int rec=0, done=0, count=0;
+ FILE *f = fopen(q->failfile, "r+b");
+
+ if (f)
+ { while(1)
+ { fseek(f, rec * q->entrysize, SEEK_SET);
+
+ if (fread(data, 1, q->entrysize, f)!=(unsigned int)q->entrysize) // if eof -> done
+ { done=1;
+ break;
+ }
+
+ if (data[0]) // filled entry ?
+ { OperatorConsole.printf("Queue: retrying processing of file %s\n", data);
+
+ if (q->process(data, q->PDU, q->ForwardLastUID))
+ { q->lastfailtime = time(NULL); // failed again
+ q->fails++;
+
+ if (q->maxfails && (q->fails>q->maxfails))
+ { OperatorConsole.printf("*** Queue: %d retries exceeds set maximum of %d - giving up\n", q->fails, q->maxfails);
+ q->lastfailtime = 0;
+ q->fails = 0;
+ done = 1;
+ }
+ break; // retry later
+ }
+ else
+ { q->lastfailtime = 0;
+ q->opentime = time(NULL); // PDU must be open by now
+ q->fails = 0;
+
+ data[0]=0; // mark data as processed
+ fseek(f, rec * q->entrysize, SEEK_SET);
+ fwrite(data, 1, 1, f);
+
+ count++; // every 10 files make time to process..
+ if(count>10) break; // ..queue entries that are freshly created
+ }
+ }
+ rec++; // next entry in file
+ }
+
+ fclose(f);
+ if (done) unlink(q->failfile); // delete file when not needed anymore
+ }
+ }
+
+ for(int i=0; i<MAXExportConverters; i++)
+ { if (q->PDU && (time(NULL)-q->opentime > q->pdu_closedelay)) // close unused association after 5 seconds
+ { if (q->PDU[i].Link.Connected)
+ //q->PDU[i].Close(); just hangup without AReleaseRQ: otherwise server sometimes fails to reconnect
+
+ if (q->pdu_release) q->PDU[i].Close();
+ else q->PDU[i].Link.Close();
+ }
+
+ if (q->PDU && (time(NULL)-q->opentime > q->pdu_refreshdelay)) // clean collected sopclasses after one hour of inactivity
+ { if (!q->PDU[i].Link.Connected)
+ q->PDU[i].ClearAbstractSyntaxs();
+ q->opentime = time(NULL);
+ }
+ }
+ }
+ }
+
+ free(data);
+ return TRUE;
+}
+
+struct conquest_queue *new_queue(int num, int size, int delay, BOOL (*process)(char *, ExtendedPDU_Service *PDU, char *), ExtendedPDU_Service *PDU, int maxfails)
+{ struct conquest_queue *result;
+#ifdef WIN32
+ unsigned long ThreadID;
+#endif
+
+ result = new conquest_queue;
+ result->top = 0;
+ result->bottom = 0;
+ result->num = num;
+ result->entrysize = size;
+ result->delay = delay;
+ result->process = process;
+ result->mayprocess = NULL;
+ result->data = (char *)malloc(num * size);
+ result->fails = 0;
+ result->maxfails = maxfails;
+ result->lastfailtime = 0;
+ result->failfile[0] = 0;
+ result->PDU = PDU;
+ result->opentime = 0;
+ result->pdu_refreshdelay = 3600;
+ result->pdu_closedelay = 5;
+ result->pdu_release = 0;
+ result->ForwardLastUID = NULL;
+
+ InitializeCriticalSection(&result->critical);
+
+ /* Note: since the queue is thread safe it is possible to start more than one thread to service it */
+
+#ifdef WIN32
+ result->threadhandle =
+ CreateThread(NULL, 0x000ff000, (LPTHREAD_START_ROUTINE) processthread, result, 0, &ThreadID);
+#else
+ pthread_create(&result->threadhandle, NULL, (void*(*)(void*))processthread, (void *)result);
+ pthread_detach(result->threadhandle);
+#endif
+
+ return result;
+}
+
+void into_queue(struct conquest_queue *q, char *in)
+{ while (1)
+ { EnterCriticalSection(&q->critical);
+
+ if ((q->top+1)%q->num != q->bottom)
+ { memcpy(q->data + q->top * q->entrysize, in, q->entrysize);
+ q->top = (q->top+1)%q->num;
+ LeaveCriticalSection(&q->critical);
+ return;
+ }
+
+ LeaveCriticalSection(&q->critical);
+
+ Sleep(q->delay);
+ }
+}
+
+// enters entry into queue if first numunique characters are not there.
+// note: will discard entry when no space in queue
+// intended for prefetching stuff: use a large queue
+
+BOOL into_queue_unique(struct conquest_queue *q, char *in, int numunique)
+{ int i;
+
+ EnterCriticalSection(&q->critical);
+
+ // no space!
+ if ((q->top+1)%q->num == q->bottom)
+ { LeaveCriticalSection(&q->critical);
+ return FALSE;
+ }
+
+ // search for identical items
+ for (i=q->bottom; i!=(q->top+1)%q->num; i = (i+1)%q->num)
+ { if (memcmp(q->data + i * q->entrysize, in, numunique)==0)
+ { LeaveCriticalSection(&q->critical);
+ return FALSE;
+ }
+ }
+
+ // enter new item
+ memcpy(q->data + q->top * q->entrysize, in, q->entrysize);
+ q->top = (q->top+1)%q->num;
+ LeaveCriticalSection(&q->critical);
+ return TRUE;
+}
+
+//////////////////////////////////////////////////////////////////////////////////
+// This code starts a thread for each defined export converter
+//////////////////////////////////////////////////////////////////////////////////
+
+static struct conquest_queue **eqN = NULL;
+static ExtendedPDU_Service ForwardPDU[MAXExportConverters][MAXExportConverters]; // max 20*20 with remaining association
+
+BOOL exportprocessN(char *data, ExtendedPDU_Service *PDU, char *t)
+{ return CallExportConverterN(data, data[1024+18+18+66], data+1024, data+1024+18, data+1024+18+18, data+1024+18+18+66+4, PDU, t, data+1024+18+18+66+4+66, data+1024+18+18+66+4+66+18);
+}
+
+void reset_queue_fails(int N)
+{ eqN[N]->fails = 0;
+}
+
+void export_queueN(struct conquest_queue **q, char *pszFileName, int N, char *pszModality, char *pszStationName, char *pszSop, char *patid, char *calling, char *called)
+{ char data[1536];
+
+ if (!*q)
+ { char szRootSC[64], szTemp[32];
+
+ *q = new_queue(QueueSize, 1536, 100, exportprocessN, N>=MAXExportConverters ? NULL : ForwardPDU[N], 0);
+ sprintf((*q)->failfile, "ExportFailures%s_%d", Port, N);
+ (*q)->ForwardLastUID = (char *) malloc(MAXExportConverters * 66);
+ memset((*q)->ForwardLastUID, 0, MAXExportConverters * 66);
+
+ MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile);
+
+ MyGetPrivateProfileString(szRootSC, "ForwardAssociationRefreshDelay", "3600", szTemp, 128, ConfigFile);
+ (*q)->pdu_refreshdelay = atoi(szTemp);
+
+ MyGetPrivateProfileString(szRootSC, "ForwardAssociationCloseDelay", "5", szTemp, 128, ConfigFile);
+ (*q)->pdu_closedelay = atoi(szTemp);
+
+ MyGetPrivateProfileString(szRootSC, "ForwardAssociationRelease", "1", szTemp, 128, ConfigFile);
+ (*q)->pdu_release = atoi(szTemp);
+
+ MyGetPrivateProfileString(szRootSC, "MaximumExportRetries", "0", szTemp, 128, ConfigFile);
+ (*q)->maxfails = atoi(szTemp);
+ }
+
+ if (pszFileName==NULL) return;
+
+ memset(data, 0, 1536);
+
+ strcpy(data, pszFileName);
+ strcpy(data+1024, pszModality);
+ strcpy(data+1024+18, pszStationName);
+ strcpy(data+1024+18+18, pszSop);
+ data[1024+18+18+66] = N;
+ strcpy(data+1024+18+18+66+4, patid);
+
+ if(calling) strcpy(data+1024+18+18+66+4+66, calling);
+ if(called) strcpy(data+1024+18+18+66+4+66+18, called);
+
+ into_queue(*q, data);
+}
+
+// This routine queues all export converter requests. Use instead of CallExportConverters
+
+void QueueExportConverters(char *pszFileName, char *pszModality, char *pszStationName, char *pszSop, char *patid, char *calling, char *called)
+{ char szRootSC[64];
+// char szEntry[32];
+ char szTemp[32];
+ int i, iNbConverters;
+
+ if (!MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig,
+ szRootSC, 64, ConfigFile)) return;
+ if (!MyGetPrivateProfileString(szRootSC, "ExportConverters", "0",
+ szTemp, 128, ConfigFile)) return;
+ iNbConverters = atoi(szTemp);
+ if (!iNbConverters) return;
+ if (iNbConverters>MAXExportConverters) iNbConverters=MAXExportConverters;
+
+ if (!eqN)
+ { eqN = (struct conquest_queue **)malloc(iNbConverters * sizeof(struct conquest_queue *));
+ memset(eqN, 0, iNbConverters * sizeof(struct conquest_queue *));
+ };
+
+ /* Loop over all converters */
+ for(i=0; i<iNbConverters; i++)
+ { export_queueN(&eqN[i], pszFileName, i, pszModality, pszStationName, pszSop, patid, calling, called);
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////////////
+// This code is a queue for filecopy requests; it is used to speed mirror copying
+//////////////////////////////////////////////////////////////////////////////////
+
+// return TRUE if it worthwile to retry (copy failed)
+
+BOOL copyprocess(char *data, ExtendedPDU_Service *PDU, char *dum)
+{ if (DFileCopy2(data, data+1024, 0))
+ { OperatorConsole.printf("Mirror copy: %s\n", data+1024);
+ return FALSE;
+ }
+ else
+ { OperatorConsole.printf("***Writing mirror copy failed: %s\n", data+1024);
+ return TRUE;
+ }
+ UNUSED_ARGUMENT(PDU);
+ UNUSED_ARGUMENT(dum);
+}
+
+void mirrorcopy_queue(char *pszFileName, char *pszDestination)
+{ char data[2048];
+ static struct conquest_queue *q = NULL;
+
+ if (!q)
+ { q = new_queue(QueueSize, 2048, 100, copyprocess, NULL, 0);
+ sprintf(q->failfile, "CopyFailures%s", Port);
+ }
+ if (pszFileName==NULL) return;
+
+ strcpy(data, pszFileName);
+ strcpy(data+1024, pszDestination);
+
+ into_queue(q, data);
+}
+
+//////////////////////////////////////////////////////////////////////////////////
+// This code is a queue for prefetch and preforward requests
+//////////////////////////////////////////////////////////////////////////////////
+
+/////////////////////////////////////////////////////////////////////
+// read all files of a patient (to populate cache) use windows call for windows version
+BOOL TestFile(char *FullFilename, char *status);
+
+static int DFileRead(char *source, unsigned int MaxRead)
+{
+ BOOL err_status = TRUE; /* Error status */
+ char *copybuffer; /* The copy buffer */
+ unsigned bufsize; /* Size of copy buffer */
+ unsigned long bytes, totbytes; /* Actual transferred bytes */
+#ifdef WIN32
+ HANDLE handle = CreateFile(source, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
+ if( handle == NULL) return FALSE;
+#else
+ /* Open input file for read-only. parser error if operation fails. */
+ int inhandle = sopen( source, O_RDONLY | O_BINARY, SH_DENYNO, S_IREAD);
+ if( inhandle == -1) return FALSE;
+#endif
+
+ /* get a large buffer */
+ bufsize = 0x4000;
+ copybuffer = (char *)malloc(bufsize);
+ if (copybuffer == NULL)
+ {
+#ifdef WIN32
+ CloseHandle(handle);
+#else
+ close(inhandle);
+#endif
+
+ return -1;
+ }
+
+ totbytes=0;
+
+ while( /*!eof(inhandle) && */err_status)
+ {
+#ifdef WIN32
+ ReadFile(handle, copybuffer, bufsize, &bytes, NULL);
+#else
+ bytes= (unsigned)read( inhandle, copybuffer, bufsize);
+#endif
+
+//#ifndef WIN32
+ if (bytes == 0)
+ break;
+//#endif
+
+ if (bytes == (unsigned) -1)
+ {
+ err_status= FALSE;
+ break;
+ }
+
+ totbytes += (bytes+512)>>10;
+ if (MaxRead && totbytes>(MaxRead>>10)) break;
+ }
+
+ free(copybuffer);
+#ifdef WIN32
+ CloseHandle(handle);
+#else
+ close(inhandle);
+#endif
+ return totbytes;
+}
+
+char LastPrefetch[65] = "";
+
+BOOL
+PrefetchPatientData (char *PatientID, unsigned int MaxRead)
+ {
+ Database aDB;
+ char Tables[512], DeviceName[512], ObjectFile[1024], FileNameFrom[1024];
+ char QueryString[512], PatientIDValue[512], PhysicalFrom[1024];
+ SQLLEN SQLResultLength;
+ BOOL Status=TRUE;
+ char error[256];
+
+ if (strcmp(PatientID, LastPrefetch)==0) return TRUE;
+
+ OperatorConsole.printf("Prefetching patient %s\n", PatientID);
+
+ sprintf(Tables, "%s", ImageTableName);
+
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return FALSE;
+ }
+
+ // MakeSafeString(PatientID, PatientIDValue);
+ strcpy(PatientIDValue, PatientID);
+ DICOM2SQLValue(PatientIDValue); // allow exact match only
+ sprintf(QueryString, "DICOMImages.ImagePat = %s", PatientIDValue);
+
+ if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ {
+ OperatorConsole.printf("***Unable to query for image records for prefetch\n");
+ aDB.Close();
+ return FALSE;
+ }
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+
+ while (aDB.NextRecord())
+ {
+ if (!FindPhysicalDevice(DeviceName, PhysicalFrom, ObjectFile)) continue;
+ strcpy(FileNameFrom, PhysicalFrom);
+ strcat(FileNameFrom, ObjectFile);
+
+ SystemDebug.printf("Prefetching file: %s\n", FileNameFrom);
+
+ if (MaxRead<0)
+ {
+ if (!TestFile(FileNameFrom, error))
+ {
+ OperatorConsole.printf("***Prefetch read failed for file: %s (%s)\n", FileNameFrom, error);
+ Status = FALSE;
+ }
+ }
+ else
+ {
+ if (DFileRead(FileNameFrom, MaxRead)<0)
+ {
+ OperatorConsole.printf("***Prefetch read failed for file: %s\n", FileNameFrom);
+ Status = FALSE;
+ }
+ }
+ }
+
+ aDB.Close();
+ strcpy(LastPrefetch, PatientID);
+
+ return Status;
+ }
+
+// move data from this to other server: returns TRUE is meaningful to retry
+// returns 0 for success; 1 for error; 2 for retryable error
+static int DcmMove(const char *patid, char* pszSourceAE, char* pszDestinationAE, const char *studyuid, const char *seriesuid, const char *compress, const char *modality, const char *date,
+ const char *sop, const char *imagetype, const char *seriesdesc, int id, char *script)
+{ PDU_Service PDU;
+ DICOMCommandObject DCO;
+ DICOMCommandObject DCOR;
+ DICOMDataObject DDO;
+ DICOMDataObject DDOR;
+ UID uid;
+ VR *vr;
+ LE_UINT16 command, datasettype, messageid, priority;
+ BYTE SOP[64];
+ BYTE AppTitle[64], host[64], port[64], compr[64];
+ int rc = 0;
+
+ if (strcmp(pszSourceAE, "(local)")==0)
+ pszSourceAE = (char *)MYACRNEMA;
+
+ PDU.AttachRTC(&VRType);
+
+ PDU.ClearAbstractSyntaxs();
+ PDU.SetLocalAddress((unsigned char*)MYACRNEMA);
+ PDU.SetRemoteAddress((unsigned char*)pszSourceAE);
+
+ uid.Set("1.2.840.10008.3.1.1.1"); // Application context (DICOM App)
+ PDU.SetApplicationContext(uid);
+ uid.Set("1.2.840.10008.5.1.4.1.2.1.2"); // patientrootmove
+ PDU.AddAbstractSyntax(uid);
+ uid.Set("1.2.840.10008.5.1.4.1.2.2.2"); // studyrootmove
+ PDU.AddAbstractSyntax(uid);
+
+ if (strcmp(pszSourceAE, (char *)MYACRNEMA)==0)
+ {
+ if(!PDU.Connect((BYTE *)"127.0.0.1", Port))
+ {
+ OperatorConsole.printf("***forward xxxx to: local server not working\n");
+ return 1; // self not working: no retry
+ }
+ messageid = id;
+ }
+ else
+ {
+ if(!GetACRNema(pszSourceAE, (char *)host, (char *)port, (char *)compr))
+ {
+ OperatorConsole.printf("***preretrieve: AE not found: %s\n", pszSourceAE);
+ return 1; // wrong address no retry
+ }
+ if(!PDU.Connect(host, port))
+ {
+ OperatorConsole.printf("***preretrieve: could not connect to AE: %s\n", pszSourceAE);
+ return 2; // remote not working: retry
+ }
+ messageid = id; // special to indicate move to itself - no import/exportconverters
+ }
+
+ if (*studyuid || *seriesuid || *sop || *modality || *date || *imagetype || *seriesdesc)
+ sprintf((char*) SOP, "1.2.840.10008.5.1.4.1.2.2.2"); // study-root move
+ else
+ sprintf((char*) SOP, "1.2.840.10008.5.1.4.1.2.1.2"); // patient-root move
+
+ vr = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE);
+ DCO.Push(vr);
+ command = 0x0021;
+ vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE);
+ DCO.Push(vr);
+ priority = 0;
+ vr = new VR (0x0000, 0x0700, 0x0002, &priority, FALSE);
+ DCO.Push(vr);
+ datasettype = 0x0102;
+ vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE);
+ DCO.Push(vr);
+
+ vr = new VR (0x0000, 0x0110, 0x0002, &messageid, FALSE);
+ DCO.Push(vr);
+
+ memset((char*)AppTitle, ' ', 20);
+ memcpy((void*)AppTitle, pszDestinationAE, strlen(pszDestinationAE));
+ vr = new VR(0x0000, 0x0600, 16, (void*)&AppTitle[0], FALSE);
+ DCO.Push(vr);
+
+ if (*sop) SetStringVR(&vr, 0x0008, 0x0052, "IMAGE");
+ else if (*imagetype) SetStringVR(&vr, 0x0008, 0x0052, "IMAGE");
+ else if (*modality) SetStringVR(&vr, 0x0008, 0x0052, "SERIES");
+ else if (*date) SetStringVR(&vr, 0x0008, 0x0052, "SERIES");
+ else if (*seriesuid) SetStringVR(&vr, 0x0008, 0x0052, "SERIES");
+ else if (*seriesdesc)SetStringVR(&vr, 0x0008, 0x0052, "SERIES");
+ else if (*studyuid) SetStringVR(&vr, 0x0008, 0x0052, "STUDY");
+ else SetStringVR(&vr, 0x0008, 0x0052, "PATIENT");
+ DDO.Push(vr);
+
+ if (*patid)
+ {
+ SetStringVR(&vr, 0x0010, 0x0020, patid);
+ DDO.Push(vr);
+ }
+ if (*studyuid && id!=7777)
+ {
+ SetStringVR(&vr, 0x0020, 0x000d, studyuid);
+ DDO.Push(vr);
+ }
+ if (*studyuid && id==7777) // lazy move by accession number
+ {
+ SetStringVR(&vr, 0x0008, 0x0050, studyuid);
+ DDO.Push(vr);
+ }
+ if (*seriesuid)
+ {
+ SetStringVR(&vr, 0x0020, 0x000e, seriesuid);
+ DDO.Push(vr);
+ }
+ if (*sop)
+ {
+ SetStringVR(&vr, 0x0008, 0x0018, sop);
+ DDO.Push(vr);
+ }
+ if (*modality)
+ {
+ SetStringVR(&vr, 0x0008, 0x0060, modality);
+ DDO.Push(vr);
+ }
+ if (*date)
+ {
+ SetStringVR(&vr, 0x0008, 0x0020, date);
+ DDO.Push(vr);
+ }
+ if (*imagetype)
+ {
+ vr = new VR(0x0008, 0x0008, strlen(imagetype), (void*)imagetype, FALSE );
+ DDO.Push(vr);
+ }
+ if (*seriesdesc)
+ {
+ vr = new VR(0x0008, 0x103e, strlen(seriesdesc), (void*)seriesdesc, FALSE );
+ DDO.Push(vr);
+ }
+ if (*compress)
+ {
+ SetStringVR(&vr, 0x9999, 0x0700, compress);
+ DCO.Push(vr);
+ }
+ if (*script)
+ {
+ SetStringVR(&vr, 0x9999, 0x0900, script);
+ DCO.Push(vr);
+ }
+
+ uid.Set(SOP);
+ PDU.Write(&DCO, uid);
+ PDU.Write(&DDO, uid);
+
+ while(TRUE)
+ {
+ if(!PDU.Read(&DCOR))
+ {
+ OperatorConsole.printf("***preretrieve/forward xxx to: association lost\n");
+ return 2; // associate lost: may retry
+ }
+
+ if(DCOR.GetUINT16(0x0000, 0x0100)!=0x8021)
+ {
+ OperatorConsole.printf("***preretrieve/forward xxx to: invalid C-move response\n");
+ rc = 1;
+ goto EXIT; // not a C-MOVE-RSP ? error no retry
+ }
+
+ if(DCOR.GetUINT16(0x0000, 0x0800)!=0x0101)
+ {
+ PDU.Read(&DDOR);// ignore the data set
+ DDOR.Reset();
+ }
+
+ if(DCOR.GetUINT16(0x0000, 0x0900)==0x0000)
+ {
+ rc = 0;
+ goto EXIT; // completed OK, no retry
+ }
+ else if (DCOR.GetUINT16(0x0000, 0x0900)==0xff00)
+ { // continuing no problem
+ DCOR.Reset();
+ continue;
+ }
+ else
+ {
+ OperatorConsole.printf("***preretrieve/forward xxx to: remote DICOM error\n");
+ NonDestructiveDumpDICOMObject(&DCOR);
+ rc = 1; // remote DICOM error: NO retry FOR NOW
+ goto EXIT;
+ }
+ DCOR.Reset();
+ }
+EXIT:
+ PDU.Close();
+ return rc;
+}
+
+// move data from this to other server controlled by DICOMDataObject
+
+static BOOL DcmMove2(char* pszSourceAE, const char* pszDestinationAE, BOOL patroot, int id, DICOMDataObject *DDO, const char *callback)
+{ ExtendedPDU_Service PDU;
+ DICOMCommandObject DCO;
+ DICOMCommandObject DCOR;
+ DICOMDataObject DDOR;
+ UID uid;
+ VR *vr;
+ LE_UINT16 command, datasettype, messageid, priority;
+ BYTE SOP[64], AppTitle[64], host[64], port[64], compr[64];
+ BOOL rc = FALSE;
+
+ if (strcmp(pszSourceAE, "(local)")==0)
+ pszSourceAE = (char *)MYACRNEMA;
+
+ PDU.AttachRTC(&VRType);
+
+ PDU.ClearAbstractSyntaxs();
+ PDU.SetLocalAddress((unsigned char*)MYACRNEMA);
+ PDU.SetRemoteAddress((unsigned char*)pszSourceAE);
+
+ uid.Set("1.2.840.10008.3.1.1.1"); // Application context (DICOM App)
+ PDU.SetApplicationContext(uid);
+ uid.Set("1.2.840.10008.5.1.4.1.2.1.2"); // patientrootmove
+ PDU.AddAbstractSyntax(uid);
+ uid.Set("1.2.840.10008.5.1.4.1.2.2.2"); // studyrootmove
+ PDU.AddAbstractSyntax(uid);
+
+ if (strcmp(pszSourceAE, (char *)MYACRNEMA)==0)
+ {
+ if(!PDU.Connect((BYTE *)"127.0.0.1", Port))
+ {
+ OperatorConsole.printf("***dicommove: local server not working\n");
+ sprintf(StatusString, "***dicommove: local server not working");
+ return FALSE; // self not working: no retry
+ }
+ messageid = id;
+ }
+ else
+ {
+ if(!GetACRNema(pszSourceAE, (char *)host, (char *)port, (char *)compr))
+ {
+ OperatorConsole.printf("***dicommove: AE not found: %s\n", pszSourceAE);
+ sprintf(StatusString, "***dicommove: AE not found: %s", pszSourceAE);
+ return FALSE; // wrong address no retry
+ }
+ if(!PDU.Connect(host, port))
+ {
+ OperatorConsole.printf("***dicommove: could not connect to AE: %s\n", pszSourceAE);
+ sprintf(StatusString, "***dicommove: could not connect to AE: %s", pszSourceAE);
+ return TRUE; // remote not working: retry
+ }
+ messageid = id; // special to indicate move to itself - no import/exportconverters
+ }
+
+ if (patroot)
+ sprintf((char*) SOP, "1.2.840.10008.5.1.4.1.2.1.2"); // patient-root move
+ else
+ sprintf((char*) SOP, "1.2.840.10008.5.1.4.1.2.2.2"); // study-root move
+
+ vr = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE);
+ DCO.Push(vr);
+ command = 0x0021;
+ vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE);
+ DCO.Push(vr);
+ priority = 0;
+ vr = new VR (0x0000, 0x0700, 0x0002, &priority, FALSE);
+ DCO.Push(vr);
+ datasettype = 0x0102;
+ vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE);
+ DCO.Push(vr);
+
+ vr = new VR (0x0000, 0x0110, 0x0002, &messageid, FALSE);
+ DCO.Push(vr);
+
+ memset((char*)AppTitle, ' ', 20);
+ memcpy((void*)AppTitle, pszDestinationAE, strlen(pszDestinationAE));
+ vr = new VR(0x0000, 0x0600, 16, (void*)&AppTitle[0], FALSE);
+ DCO.Push(vr);
+
+ uid.Set(SOP);
+ PDU.Write(&DCO, uid);
+ PDU.Write(DDO, uid);
+
+ while(TRUE)
+ {
+ if(!PDU.Read(&DCOR))
+ {
+ OperatorConsole.printf("***dicommove: association lost\n");
+ sprintf(StatusString, "***dicommove: association lost");
+ return TRUE; // associate lost: may retry
+ }
+
+ if(DCOR.GetUINT16(0x0000, 0x0100)!=0x8021)
+ {
+ OperatorConsole.printf("***dicommove: invalid C-move response\n");
+ sprintf(StatusString, "***dicommove: invalid C-move response");
+ rc = FALSE;
+ goto EXIT; // not a C-MOVE-RSP ? no retry
+ }
+
+ if(DCOR.GetUINT16(0x0000, 0x0800)!=0x0101)
+ {
+ PDU.Read(&DDOR);// ignore the data set
+ DDOR.Reset();
+ }
+
+ if(DCOR.GetUINT16(0x0000, 0x0900)==0x0000)
+ {
+ rc = FALSE;
+ *StatusString=0;
+ goto EXIT; // completed OK, no retry
+ }
+ else if (DCOR.GetUINT16(0x0000, 0x0900)==0xff00)
+ { // continuing no problem
+ int iNbSent = DCOR.GetUINT16(0x0000, 0x1021);
+ int iNbToGo = DCOR.GetUINT16(0x0000, 0x1020);
+ sprintf(StatusString, "dicommove: %d of %d images transferred", iNbSent, iNbSent+iNbToGo);
+
+ if (callback && *callback)
+ {
+ struct scriptdata sd = {&PDU, &DCOR, NULL, -1, NULL, NULL, NULL, NULL, NULL, 0, 0};
+ do_lua(&(PDU.L), (char *)callback, &sd);
+ if (sd.DDO) delete sd.DDO;
+ }
+
+ DCOR.Reset();
+ continue;
+ }
+ else
+ {
+ OperatorConsole.printf("***dicommove: remote DICOM error\n");
+ sprintf(StatusString, "***dicommove: remote DICOM error");
+ NonDestructiveDumpDICOMObject(&DCOR);
+ rc = FALSE; // remote DICOM error: NO retry FOR NOW
+ goto EXIT;
+ }
+ DCOR.Reset();
+ }
+EXIT:
+ PDU.Close();
+ return rc;
+}
+
+// delete patient data from this server: always returns FALSE
+
+static BOOL DcmDelete(char *patid, char *studyuid, char *seriesuid, char *modality, char *date, char *sop, char *imagetype)
+{ DICOMDataObject DDO;
+ VR *vr;
+
+ if (*patid)
+ {
+ SetStringVR(&vr, 0x0010, 0x0020, patid);
+ DDO.Push(vr);
+ }
+ if (*studyuid)
+ {
+// vr = new VR(0x0020, 0x000d, (strlen(studyuid)+1)&0xfe, (void*)studyuid, FALSE );
+ SetStringVR(&vr, 0x0020, 0x000d, studyuid);
+ DDO.Push(vr);
+ }
+ if (*seriesuid)
+ {
+// vr = new VR(0x0020, 0x000e, (strlen(seriesuid)+1)&0xfe, (void*)seriesuid, FALSE );
+ SetStringVR(&vr, 0x0020, 0x000e, seriesuid);
+ DDO.Push(vr);
+ }
+ if (*sop)
+ {
+// vr = new VR(0x0008, 0x0018, (strlen(sop)+1)&0xfe, (void*)sop, FALSE );
+ SetStringVR(&vr, 0x0008, 0x0018, sop);
+ DDO.Push(vr);
+ }
+ if (*modality)
+ {
+ SetStringVR(&vr, 0x0008, 0x0060, modality);
+ DDO.Push(vr);
+ }
+ if (*date)
+ {
+ SetStringVR(&vr, 0x0008, 0x0020, date);
+ DDO.Push(vr);
+ }
+ if (*imagetype)
+ {
+ vr = new VR(0x0008, 0x0008, strlen(imagetype), (void*)imagetype, FALSE );
+ DDO.Push(vr);
+ }
+
+ RemoveFromPACS(&DDO, FALSE);
+ return FALSE;
+}
+
+int DcmMergeStudy(const char *server, char *pat, char *study, char *modality, char *seriesdesc, char *script, ExtendedPDU_Service *PDU);
+int DcmSubmitData(char *pat, char *study, char *series, char *sop, char *script,
+ char *modesubmit, char *hostsubmit, int portsubmit, char *ident);
+
+// runs in the thread
+BOOL prefetchprocess(char *data, ExtendedPDU_Service *PDU, char *dum)
+{ if (memicmp(data+65, "prefetch", 8)==0) PrefetchPatientData(data, 0);
+ if (memicmp(data+65, "forward ", 8)==0) return DcmMove (data, (char *)MYACRNEMA, data+82, data+100, data+165, data+230, data+256, data+276, data+300, data+366, data+500, 5, data+570)==2;
+ if (memicmp(data+65, "preretrieve", 11)==0) return DcmMove (data, data+82, (char *)MYACRNEMA, data+100, data+165, data+230, data+256, data+276, data+300, data+366, data+500, 0xfbad, data+570)==2;
+ if (memicmp(data+65, "get ", 4)==0) return DcmMove (data, data+82, (char *)MYACRNEMA, data+100, data+165, data+230, data+256, data+276, data+300, data+366, data+500, 0xfbad, data+570)==2;
+ if (memicmp(data+65, "delete ", 7)==0) DcmDelete(data, data+100, data+165, data+256, data+276, data+300, data+366);
+ if (memicmp(data+65, "merge ", 6)==0) DcmMergeStudy ("local", data, data+100, data+256, data+500, data+570, PDU);
+ if (memicmp(data+65, "submit ", 7)==0) DcmSubmitData (data, data+100, data+165, data+300, data+570, "sftp", data+366, 22, data+500);
+ if (memicmp(data+65, "submit2 ", 8)==0) DcmSubmitData (data, data+100, data+165, data+300, data+570, "other", data+366, 22, data+500);
+ if (memicmp(data+65, "process ", 8)==0)
+ { char *p = strchr(data+230, ' ');
+ if (p && memicmp(p-4, ".lua", 4)==0)
+ { struct scriptdata sd1 = {PDU, NULL, NULL, -1, NULL, NULL, NULL, NULL, NULL, 0, 0};
+ char script[512]; int i, n;
+ strcpy(script, "dofile('");
+ *p=0;
+ for (i=0, n=8; i<strlen(data+230); i++)
+ { if (data[i+230]=='\\')
+ { script[n++] = '\\';
+ script[n++] = '\\';
+ }
+ else
+ { script[n++] = data[i+230];
+ }
+ }
+ script[n++] = 0;
+ strcat(script, "')");
+ //OperatorConsole.On();
+
+ lua_setvar(PDU, "command_line", p+1);
+ lua_setvar(PDU, "version", DGATE_VERSION);
+ do_lua(&(PDU->L), script, &sd1);
+ }
+ else
+#ifdef WIN32
+ WinExec(data+230, SW_MINIMIZE);
+#else
+ system(data+230);
+#endif
+ }
+
+ return FALSE;
+ UNUSED_ARGUMENT(dum);
+}
+
+// blocks the thread so as not to prefetch too often
+BOOL mayprefetchprocess(char *data, ExtendedPDU_Service *PDU, char *dum)
+{ if ((*(unsigned int*)(data+996)) + (*(unsigned int*)(data+992)) > (unsigned int)time(NULL)) return FALSE; // hold until e.g. 10 minutes past
+ return TRUE;
+ UNUSED_ARGUMENT(PDU);
+ UNUSED_ARGUMENT(dum);
+}
+
+ExtendedPDU_Service prefetchPDU; // for prefetch script context
+
+// enter prefetch or preforward request into queue
+BOOL prefetch_queue(const char *operation, char *patientid, const char *server, const char *studyuid,
+ const char *seriesuid, const char *compress, const char *modality, const char *date,
+ const char *sop, const char *imagetype, const char *seriesdesc, int delay, const char *script)
+{ char data[1000];
+ static struct conquest_queue *q = NULL;
+
+ if (delay==0) delay = ForwardCollectDelay;
+
+ if (!q)
+ { char szRootSC[64], szTemp[32];
+
+ prefetchPDU.SetLocalAddress ( (BYTE *)"prefetch" );
+ prefetchPDU.SetRemoteAddress ( (BYTE *)"prefetch" );
+ prefetchPDU.ThreadNum = 0;
+
+ q = new_queue(QueueSize, 1000, 100, prefetchprocess, &prefetchPDU, 0);
+ q->mayprocess = mayprefetchprocess;
+ sprintf(q->failfile, "DelayedFetchForwardFailures%s", Port);
+
+ MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile);
+ MyGetPrivateProfileString(szRootSC, "MaximumDelayedFetchForwardRetries", "0", szTemp, 128, ConfigFile);
+ q->maxfails = atoi(szTemp);
+ }
+
+ memset(data, 0, 1000);
+ strncpy(data, patientid, 64);
+ strncpy(data+65, operation, 16);
+ *(unsigned int*)(data+996) = time(NULL);
+ *(unsigned int*)(data+992) = delay;
+
+ if (memicmp(data+65, "process ", 8)==0)
+ { strncpy(data+100, studyuid, 64);
+ strncpy(data+165, seriesuid, 64);
+ strncpy(data+230, server, 360);
+ return into_queue_unique(q, data, 230);
+ }
+ else
+ { strncpy(data+82, server, 17);
+ strncpy(data+100, studyuid, 64);
+ strncpy(data+165, seriesuid, 64);
+ strncpy(data+230, compress, 25);
+ strncpy(data+256, modality, 19);
+ strncpy(data+276, date, 23);
+ strncpy(data+300, sop, 64);
+ strncpy(data+366, imagetype, 128);
+ strncpy(data+500, seriesdesc,64);
+ if (script) strncpy(data+570, script, 400);
+ return into_queue_unique(q, data, 992);
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////////////
+// This queue is intended to prefetch (in disk cache) patient data
+// likely to be requested soon in the time that the server is inactive
+// Enter P+patientID or S+studyUID to be read using into_queue or enter
+// empty item to abort current prefetch
+//////////////////////////////////////////////////////////////////////////////////
+
+static BOOL WINAPI prefetcherthread(struct conquest_queue *q)
+{ char data[66], curitem[65];
+ Database aDB;
+ char DeviceName[512], ObjectFile[1024], FileNameFrom[1024];
+ char QueryString[512], QueryValue[512], PhysicalFrom[1024];
+ SQLLEN SQLResultLength;
+// BOOL Status=TRUE;
+ BOOL qact = FALSE;
+ int count, kb;
+ time_t TimeOfDay;
+
+#ifdef __GNUC__ //Warnings
+ count = 0;
+ kb = 0;
+ TimeOfDay = 0;
+#endif
+ curitem[0]=0;
+
+ while (1)
+ { while (1)
+ { EnterCriticalSection(&q->critical);
+
+ if (q->top!=q->bottom)
+ { memcpy(data, q->data + q->bottom * q->entrysize, q->entrysize);
+ q->bottom = (q->bottom+1)%q->num;
+ LeaveCriticalSection(&q->critical);
+
+ if (data[0]==0 && qact) // abort current prefetch
+ { int skipped = 0;
+ while (aDB.NextRecord()) skipped++;
+ OperatorConsole.printf("Aborted prefetch after reading %d images (%d MB) in %d s, %d images skipped\n", count, (kb+512)>>10, (int)time(NULL) - TimeOfDay, skipped);
+ qact = FALSE;
+ curitem[0]=0;
+ aDB.Close();
+ break;
+ };
+
+ if (data[0]==0) break; // ignore abort when not active
+ if (strcmp(curitem, data+1)==0) break; // already prefetched
+
+ if (!qact)
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ { OperatorConsole.printf("***Unable to open database for prefetch\n");
+ break;
+ };
+
+ //MakeSafeString(data+1, QueryValue);
+ strcpy(QueryValue, data+1);
+ DICOM2SQLValue(QueryValue); // allow exact match only
+
+ TimeOfDay = time(NULL);
+ kb = 0;
+ count = 0;
+
+ if (data[0]=='P')
+ { OperatorConsole.printf("Prefetching patient %s\n", data+1);
+ sprintf(QueryString, "DICOMImages.ImagePat = %s", QueryValue);
+ if (!aDB.Query("DICOMImages", "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ { OperatorConsole.printf("***Unable to query for image records for prefetch\n");
+ break;
+ };
+ }
+ else
+ { OperatorConsole.printf("Prefetching study %s\n", data+1);
+ sprintf(QueryString, "DICOMSeries.StudyInsta = %s and DICOMSeries.SeriesInst = DICOMImages.SeriesInst", QueryValue);
+ if (!aDB.Query("DICOMSeries, DICOMImages", "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL))
+ { OperatorConsole.printf("***Unable to query on study for image records for prefetch\n");
+ break;
+ };
+ };
+
+ aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength);
+ aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength);
+ qact = TRUE;
+ strcpy(curitem, data+1);
+
+ // do not break: delay a bit
+ }
+ else if (qact)
+ { LeaveCriticalSection(&q->critical);
+
+ if (aDB.NextRecord())
+ { if (!FindPhysicalDevice(DeviceName, PhysicalFrom, ObjectFile)) break;
+ strcpy(FileNameFrom, PhysicalFrom);
+ strcat(FileNameFrom, ObjectFile);
+
+ SystemDebug.printf("Prefetching file: %s\n", FileNameFrom);
+ kb += DFileRead(FileNameFrom, 0);
+ count++;
+ break;
+ }
+ else
+ { qact = FALSE;
+ aDB.Close();
+ OperatorConsole.printf("Prefetch done: read %d images (%d MB) in %d s\n", count, (kb+512)>>10, (int)time(NULL) - TimeOfDay);
+ }
+ }
+ else
+ LeaveCriticalSection(&q->critical);
+
+ Sleep(q->delay);
+ }
+ }
+
+ DeleteCriticalSection(&q->critical);
+
+ return TRUE;
+}
+
+struct conquest_queue *prefetcherqueue;
+ExtendedPDU_Service prefetcherPDU; // for prefetcher script context
+
+struct conquest_queue *new_prefetcherqueue(void)
+{ struct conquest_queue *result;
+#ifdef WIN32
+ unsigned long ThreadID;
+#endif
+ int num=1000, size = 66;
+
+ prefetcherPDU.SetLocalAddress ( (BYTE *)"prefetcher" );
+ prefetcherPDU.SetRemoteAddress ( (BYTE *)"prefetcher" );
+ prefetcherPDU.ThreadNum = 0;
+
+ result = new conquest_queue;
+ result->top = 0;
+ result->bottom = 0;
+ result->num = num;
+ result->entrysize = size;
+ result->delay = 10;
+ result->process = NULL;
+ result->mayprocess = NULL;
+ result->data = (char *)malloc(num * size);
+ result->fails = 0;
+ result->lastfailtime = 0;
+ result->failfile[0] = 0;
+ result->PDU = &prefetcherPDU;
+ result->opentime = 0;
+ result->pdu_refreshdelay = 3600;
+ result->pdu_closedelay = 5;
+ result->pdu_release = 0;
+ result->ForwardLastUID = NULL;
+
+ InitializeCriticalSection(&result->critical);
+
+#ifdef WIN32
+ result->threadhandle =
+ CreateThread(NULL, 0x000ff000, (LPTHREAD_START_ROUTINE) prefetcherthread, result, 0, &ThreadID);
+#else
+ pthread_create(&result->threadhandle, NULL, (void*(*)(void*))prefetcherthread, (void *)result);
+ pthread_detach(result->threadhandle);
+#endif
+
+ return result;
+}
+
+// Control prefetcher from queries or moves
+
+static int prefetchermode=0;
+
+BOOL prefetcher(struct DICOMDataObject *DDO, BOOL move)
+{ VR *pVR = NULL;
+ char id[66];
+ int len;
+
+ if (!prefetchermode) return FALSE;
+
+ if (!prefetcherqueue)
+ prefetcherqueue = new_prefetcherqueue();
+
+ if (!DDO) return FALSE;
+
+ memset(id, 0, 66);
+
+ if (move)
+ { pVR = DDO->GetVR(0x0008, 0x0018);
+ if (pVR && pVR->Length) return FALSE; // do not abort on single sop move
+
+ into_queue(prefetcherqueue, id); // abort on all other moves
+ return FALSE;
+ }
+
+ pVR = DDO->GetVR(0x0010, 0x0020); // get patientid
+ if (!pVR)
+ id[0] = 0;
+ else
+ { id[0] = 'P';
+ strncpy(id+1, (char*)pVR->Data, pVR->Length);
+ id[pVR->Length+1] = 0;
+ len = pVR->Length - 1;
+ while(len>0)
+ { if (id[len+1] == ' ')
+ id[len+1] = 0;
+ else
+ break;
+ len--;
+ }
+ }
+
+ // no patient id or wildcard provided: try study
+ if (id[0]==0 || id[1]==0 || strchr(id, '*')!=NULL)
+ { pVR = DDO->GetVR(0x0020, 0x000d);
+ if (!(pVR && pVR->Length)) return FALSE; // no study: do not affect prefetch
+
+ id[0]='S'; // prefetch on study (for e.g. kpacs)
+ strncpy(id+1, (char*)pVR->Data, pVR->Length);
+ id[pVR->Length+1] = 0;
+ }
+
+ // any other query will start prefetch of patient or study
+ into_queue(prefetcherqueue, id);
+ return TRUE;
+}
+
+//////////////////////////////////////////////////////////////////////////////////
+// This code is for worklist processing
+//////////////////////////////////////////////////////////////////////////////////
+
+// will replace all items in object with worklist fields (if filled) for AccessionNumber
+// returns TRUE if replacement was succesfull: AccessionNumber was found or no entries to replace
+// Note: since PatientId and StudyInstanceUID may be changed by this operation, this operation
+// cannot be done after the original images were entered into the server. I will need to consider
+// generating new SOP and Series UID's in this case
+
+BOOL ApplyWorklist(DICOMDataObject *DDOPtr, Database *DB)
+ {
+ DBENTRY *DBE;
+ int Index, I;
+ char Fields[1024];
+ char QueryString[256];
+ VR *vr;
+ char *Data[100];
+ SQLLEN SQLResultLength[100];
+
+ if (!WorkListDB[0].Element) // no worklist DB
+ return FALSE;
+
+ DBE = WorkListDB;
+ Fields[0]=0;
+
+ vr = DDOPtr->GetVR(DBE[0].Group, DBE[0].Element); // query string for AccessionNumber
+ if (vr)
+ {
+ strcpy(QueryString, DBE[0].SQLColumn);
+// strcat(QueryString, DBE[0].SQLColumn);
+ strcat(QueryString, " = '");
+ QueryString[strlen(QueryString) + vr->Length]=0;
+ memcpy(QueryString+strlen(QueryString), vr->Data, vr->Length);
+ if (QueryString[strlen(QueryString)-1]==' ') QueryString[strlen(QueryString)-1]=0;
+ strcat(QueryString, "'");
+
+// strcat(QueryString, " and PatientID = '"); // patient ID cannnot be used: may be the same in image as in worklist !
+// vr = DDOPtr->GetVR(0x0010, 0x0020);
+// memcpy(QueryString+strlen(QueryString), vr->Data, vr->Length);
+// if (QueryString[strlen(QueryString)-1]==' ') QueryString[strlen(QueryString)-1]=0;
+// strcat(QueryString, "'");
+ }
+ else
+ return FALSE;
+
+ if (vr->Length==0)
+ return FALSE; // accessionnumber not filled in
+
+ Index = 1; // do not read AccessionNumber from db
+ I = 0;
+ while ( TRUE )
+ {
+ if(!DBE[Index].Element) break; // end of fields
+ vr = DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element);
+ if (vr && DBE[Index].DICOMType!=DT_STARTSEQUENCE && DBE[Index].DICOMType!=DT_ENDSEQUENCE)
+ { // field is real and present in image
+ strcat(Fields, DBE[Index].SQLColumn);
+ strcat(Fields, ",");
+ ++I;
+ }
+ ++Index;
+ }
+ Fields[strlen(Fields)-1]=0; // remove trailing ,
+
+ if (I==0) return TRUE; // nothing to do
+
+ // no db access
+ if (!DB->Query(WorkListTableName, Fields, QueryString, NULL))
+ return FALSE;
+
+ Index = 1; // do not read AccessionNumber from db
+ I = 0;
+ while ( TRUE )
+ {
+ if(!DBE[Index].Element) break; // end of fields
+ vr = DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element);
+ if (vr && DBE[Index].DICOMType!=DT_STARTSEQUENCE && DBE[Index].DICOMType!=DT_ENDSEQUENCE)
+ { // field is real and present in image
+ Data[I] = (char *)malloc(256); // data area for db read
+ DB->BindField (I+1, SQL_C_CHAR, Data[I], 255, SQLResultLength+I);
+ Data[I][0]=0;
+ ++I;
+ }
+ ++Index;
+ }
+
+ if (!DB->NextRecord()) // no record found ?
+ return FALSE;
+
+ Index = 1; // do not read AccessionNumber from db
+ I = 0;
+ while ( TRUE )
+ {
+ if(!DBE[Index].Element) break;
+ vr = DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element);
+ if (vr && DBE[Index].DICOMType!=DT_STARTSEQUENCE && DBE[Index].DICOMType!=DT_ENDSEQUENCE)
+ { // field is real and present in image
+
+#if 0 // mvh 20051208
+ SQLResultLength[I] = strlen(Data[I]);
+#endif
+
+ if (SQLResultLength[I]) // only replace if db field contains data
+ {
+ if (SQLResultLength[I] & 1) // make length even
+ {
+ if (DBE[Index].DICOMType==DT_UI)
+ Data[I][SQLResultLength[I]++] = 0; // uid
+ else
+ Data[I][SQLResultLength[I]++] = ' '; // text
+ }
+ Data[I][SQLResultLength[I]] = 0;
+
+ vr->ReAlloc(SQLResultLength[I]);
+ memcpy(vr->Data, (void*)Data[I], SQLResultLength[I]);
+ }
+
+ free(Data[I]);
+ ++I;
+ }
+ ++Index;
+ }
+
+ return TRUE; // success
+ }
+
+
+// Save a dicom composite data object to disk and update database; returns filename
+// Warning: Filename must point to an array of 1024 characters that is filled
+
+BOOL NewDeleteSopFromDB(char *pat, char *study, char *series, char *sop, Database &aDB);
+
+int
+SaveToDisk(Database &DB, DICOMDataObject *DDOPtr, char *Filename, BOOL NoKill, ExtendedPDU_Service *PDU, int Syntax, BOOL nopreget)
+ {
+// FILE *fp;
+ DICOMDataObject DDO;
+ //PDU_Service PDU;
+ Debug AutoRoute;
+ char s[1024];
+ char rRoot[1024], rFilename[1024], MirrorFilename[1024];
+ char Device[256], MirrorDevice[256], Device2[256];
+// char SOPInstanceUID[256];
+ int len, UseChapter10, devlen, has_dcm_extension=0;
+ unsigned int sIndex;
+ VR* pVR;
+ char szModality[66];
+ char szStationName[66];
+ char szSop[66], szSeries[66], szStudy[66];
+ char patid[66];
+ BOOL bForcedImplicit = FALSE;
+ char *p;
+ char Storage[64];
+ BOOL rewrite=FALSE;
+
+ char *calling = (char *)((AAssociateAC *)PDU)->CallingApTitle;
+ char *called = (char *)((AAssociateAC *)PDU)->CalledApTitle;
+
+ //PDU.AttachRTC(&VRType);
+
+ if (WorkListMode==1) // optionally update information from worklist db
+ ApplyWorklist(DDOPtr, &DB);
+ else if (WorkListMode==2) // compulsory update information from worklist db
+ {
+ if (!ApplyWorklist(DDOPtr, &DB))
+ {
+ OperatorConsole.printf("***[WorkListMode 2] Worklist entry (AccessionNumber) not found; object not saved\n");
+ //return FALSE;
+
+ int rc = CallImportConverterN(DDOPtr, 2200, NULL, NULL, NULL, NULL, PDU, NULL, NULL);
+ if (rc==7) // retry command
+ {
+ if (!ApplyWorklist(DDOPtr, &DB))
+ {
+ OperatorConsole.printf("***[WorkListMode 2] Worklist entry (AccessionNumber) not found on retry; object not saved\n");
+ return FALSE;
+ }
+ }
+ else
+ {
+ delete DDOPtr;
+ return FALSE;
+ }
+ }
+ }
+
+ FixImage(DDOPtr); // Make sure the required DICOM UID's are there + fix patient ID if enabled
+
+ /* PDU.SaveDICOMDataObject destroys the contents of DDOPtr. We need to know
+ the modality in order to decide whether ExportConverters or ImportConverters
+ should be called. Also, importconverters may modify dicom tags.
+ Get the original data here...
+ */
+ SearchDICOMObject(DDOPtr, "0008,0060", szModality);
+ SearchDICOMObject(DDOPtr, "0008,1010", szStationName);
+ SearchDICOMObject(DDOPtr, "0008,0018", szSop);
+ SearchDICOMObject(DDOPtr, "0020,000e", szSeries);
+ SearchDICOMObject(DDOPtr, "0020,000d", szStudy);
+ SearchDICOMObject(DDOPtr, "0010,0020", patid);
+
+ Storage[0]=0;
+ if (!nopreget)
+ {
+ int rc = CallImportConverters(DDOPtr, szModality, szStationName, szSop, patid, PDU, Storage);
+ if (rc==2)
+ {
+ // the import converter destroyed the image: silently cancel store
+ Filename[0]=0;
+ delete DDOPtr;
+ return TRUE;
+ }
+ else if (rc==6)
+ {
+ // the import converter reject the image: cancel store and complain
+ Filename[0]=0;
+ delete DDOPtr;
+ return FALSE;
+ }
+
+ // These might have changed ... reload
+ SearchDICOMObject(DDOPtr, "0008,0060", szModality);
+ SearchDICOMObject(DDOPtr, "0008,1010", szStationName);
+ SearchDICOMObject(DDOPtr, "0008,0018", szSop);
+ SearchDICOMObject(DDOPtr, "0020,000e", szSeries);
+ SearchDICOMObject(DDOPtr, "0020,000d", szStudy);
+ SearchDICOMObject(DDOPtr, "0010,0020", patid);
+ }
+
+ // make a filename for the new object; note: rRoot (patient directory part of rFilename) is not used any longer
+ *rRoot=1;
+ if (!GenerateFileName(DDOPtr, Device, rRoot, rFilename, NoKill, Syntax, (char *)called, (char *)calling, &DB))
+ {
+ //OperatorConsole.printf("***Failed to create filename for DICOM object (is it a slice ?)\n");
+#ifdef FAILSAFE_STORAGE
+ strcpy(rFilename, "failsafe_storage\\");
+ GenUID(rFilename + strlen(rFilename));
+ strcat(rFilename, ".v2");
+ OperatorConsole.printf("***There was a DB problem, failsafe storage created following filename: %s\n", rFilename);
+#else
+ return FALSE; //!!!!!!!!! added mvh+ljz 19980409
+#endif
+ }
+ if (memcmp(rFilename, "lua:", 4)==0) lua_getstring(PDU, NULL, DDOPtr, rFilename+4, rFilename);
+
+ // newly written image (not rewritten image): use selection preferred storage if enough space
+ if (*rRoot)
+ {
+ if (Storage[0])
+ {
+ int PreferredDevice = atoi(Storage+3);
+ if(CheckFreeStoreOnMAGDevice(PreferredDevice) > 30)
+ sprintf(Device, "MAG%d", PreferredDevice);
+ }
+ }
+ else
+ rewrite=TRUE;
+
+ // If MAG is full, may write to MIRROR, but database will say MAG
+ if (memicmp(Device, "MIRROR", 6)==0)
+ sprintf(Device2, "MAG%d", atoi(Device+6));
+ else
+ strcpy(Device2, Device); // fix 20040606 (was sprintf(Device2, "MAG%d", atoi(Device+3));)
+
+ // do not rewrite image not on MAG but it is not an error (warning is generated earlier)
+ if (memicmp(Device2, "MAG", 3)!=0)
+ {
+ Filename[0]=0;
+ delete DDOPtr; // 20040402
+ return TRUE;
+ }
+
+ // When written replace virtual MAG device, i.e. MAG0.1 (for VirtualServerFor1) with real one: MAG0
+ p = strchr(Device2, '.');
+ if (p && p[1]>='0' && p[1]<='9')
+ { *p = 0;
+ rewrite=FALSE;
+ }
+
+ // try to enter object into database (object is not saved when this fails)
+ if(!SaveToDataBase(DB, DDOPtr, rFilename, Device2, *rRoot))
+ {
+ OperatorConsole.printf("***Error saving to SQL: %s\n", rFilename);
+#ifndef FAILSAFE_STORAGE
+ int rc = CallImportConverterN(DDOPtr, 2100, NULL, NULL, NULL, NULL, PDU, NULL, NULL);
+ if (rc==7) // retry command
+ {
+ if(!SaveToDataBase(DB, DDOPtr, rFilename, Device2, *rRoot))
+ {
+ OperatorConsole.printf("***Error saving to SQL on retry: %s\n", rFilename);
+ }
+ }
+ else
+ {
+ delete DDOPtr; // 20090616
+ return FALSE;
+ }
+#endif
+ }
+
+ // Make the patient directory (and any required subdirectories), that might not be there
+ GetPhysicalDevice(Device, Filename);
+ devlen = strlen(Filename);
+ strcat(Filename, rFilename);
+
+ for (sIndex = devlen; sIndex<=strlen(Filename); sIndex++)
+ if (Filename[sIndex]==PATHSEPCHAR)
+ {
+ strcpy(s, Filename);
+ s[sIndex]='\0';
+ mkdir(s);
+ }
+
+ // Find a mirror device if it exists (will not do this if MIRROR is being written because MAG if full)
+ if (memicmp(Device, "MAG", 3)==0)
+ {
+ sprintf(MirrorDevice, "MIRROR%d", atoi(Device+3));
+ if (!GetPhysicalDevice(MirrorDevice, MirrorFilename))
+ MirrorDevice[0]=0;
+ }
+ else
+ MirrorDevice[0]=0;
+
+ // Make the mirror patient directory (and any required subdirectories), that might not be there
+ if (MirrorDevice[0])
+ {
+ devlen = strlen(MirrorFilename);
+ strcat(MirrorFilename, rFilename);
+
+ for (sIndex = devlen; sIndex<strlen(MirrorFilename); sIndex++)
+ if (MirrorFilename[sIndex]==PATHSEPCHAR)
+ {
+ strcpy(s, MirrorFilename);
+ s[sIndex]='\0';
+ mkdir(s);
+ }
+ }
+
+ // check the filename to determine format; this avoids format change on rewrite
+ len = strlen(rFilename);
+ if (len>4)
+ has_dcm_extension = (stricmp(rFilename+len-3, ".v2")!=0);
+
+ if (*TestMode) strcat(rFilename, TestMode);
+
+ /* Type of save depends on file name extension is .dcm (UseChapter10)
+ and on the transfer syntax (not ImplicitLittleEndian, not
+ ExplicitLittleEndian and not ExplicitBigEndian)
+ */
+ pVR = DDOPtr->GetVR(0x0002, 0x0010); // TransferSyntaxUID
+ if (pVR && pVR->Data)
+ {
+ strncpy(s, (char*)pVR->Data, pVR->Length);
+ s[pVR->Length] = 0;
+ if ((strcmp(s, "1.2.840.10008.1.2") != 0) &&
+ (strcmp(s, "1.2.840.10008.1.2.1") != 0) &&
+ (strcmp(s, "1.2.840.10008.1.2.2") != 0))
+ {
+ if (!has_dcm_extension)
+ {
+ OperatorConsole.printf("SaveToDisk: cannot rewrite jpeg/rle image in v2 format: %s\n", Filename);
+ Filename[0]=0;
+ delete DDOPtr;
+ return TRUE;
+ }
+ UseChapter10 = has_dcm_extension || NoDicomCheck;
+ }
+ else
+ {
+ UseChapter10 = has_dcm_extension || NoDicomCheck;
+ //bForcedImplicit = TRUE; // 20040406
+ }
+ }
+ else
+ UseChapter10 = has_dcm_extension || NoDicomCheck;
+
+ // is it nki compressed and attempt to store as .dcm --> decompress ?
+ if (DDOPtr->GetVR(0x7fdf, 0x0010)!=NULL && DDOPtr->GetVR(0x7fe0, 0x0010)==NULL && has_dcm_extension)
+ {
+ OperatorConsole.printf("SaveToDisk: *** warning: cannot write NKI compressed in dcm format, decompressing: %s\n", Filename);
+ DecompressNKI(DDOPtr);
+ }
+
+ int t = time(NULL);
+ if (!UseChapter10)
+ PDU->SaveDICOMDataObject(Filename, ACRNEMA_VR_DUMP, DDOPtr);
+ else if (bForcedImplicit)
+ PDU->SaveDICOMDataObject(Filename, DICOM_CHAPTER_10_IMPLICIT, DDOPtr);
+ else
+ // OR (tested OK) chapter 10 format (does not compress) code in filepdu.cxx (dicom.lib)
+ PDU->SaveDICOMDataObject(Filename, DICOM_CHAPTER_10_EXPLICIT, DDOPtr);
+ SaveTime += time(NULL)-t;
+
+ // 20080817: check file was actually written, if not report error and delete database entry
+ if (DFileSize(Filename)==0)
+ {
+ OperatorConsole.printf("***Error writing file: %s\n", Filename);
+ NewDeleteSopFromDB(patid, szStudy, szSeries, szSop, DB);
+ return FALSE;
+ }
+
+ if (MirrorDevice[0])
+ {
+#if DONTQUEUEMIRRORCOPY
+ if (DFileCopy2(Filename, MirrorFilename, 0))
+ OperatorConsole.printf("Mirror copy: %s\n", MirrorFilename);
+ else
+ OperatorConsole.printf("***Writing mirror copy failed: %s\n", MirrorFilename);
+#else
+ mirrorcopy_queue(Filename, MirrorFilename);
+#endif
+ }
+
+ // notify the autorouter that a dicom object has landed
+ if ( Edition != E_PERSONAL )
+ {
+ if(szSop[0]!='\0')
+ AutoRoute.printf("%s", szSop);
+ }
+
+ // notify additional executables that a dicom object has landed; note: szModality, szStationName, szSop, and patid
+ // filters work on the original dicom tags; not on those thay were changed by import converters; while %V etc are changed
+
+ if (!nopreget)
+#if DONTQUEUEEXPORTCONVERTERS
+ CallExportConverters(Filename, szModality, szStationName, szSop, patid, (char *)calling, (char *)called, NULL, NULL);
+#else
+ QueueExportConverters(Filename, szModality, szStationName, szSop, patid, (char *)calling, (char *)called);
+#endif
+
+ delete DDOPtr;
+
+ return ( rewrite?2:TRUE );
+ }
+
+static BOOL WINAPI monitorthread(char *folder)
+{ ExtendedPDU_Service PDU; // for script context of monitoring thread
+ PDU.SetLocalAddress ( (BYTE *)"monitor" );
+ PDU.SetRemoteAddress ( (BYTE *)"monitor" );
+ while (TRUE)
+ { LoadAndDeleteDir(folder, NULL, &PDU);
+ Sleep(1000);
+ }
+ return TRUE;
+}
+
+static char monitorfolder[1024], monitorfolder2[1024];
+
+void StartMonitorThread(char *global_folder)
+{
+#ifdef WIN32
+ unsigned long ThreadID;
+ CreateThread(NULL, 0x000ff000, (LPTHREAD_START_ROUTINE) monitorthread, global_folder, 0, &ThreadID);
+#else
+ pthread_t ThreadID;
+ pthread_create(&ThreadID, NULL, (void*(*)(void*))monitorthread, (void *)global_folder);
+ pthread_detach(ThreadID);
+#endif
+}
+
+static BOOL ZipTriggered=FALSE;
+static BOOL CleanTriggered=FALSE;
+static BOOL GoZipThread=FALSE;
+static BOOL ScriptTriggered=FALSE;
+
+BOOL PanicKillOff(unsigned int MAGThreshHold);
+
+static BOOL WINAPI zipthread(void)
+{ OperatorConsole.printf("Started zip and cleanup thread\n");
+
+ while (GoZipThread)
+ { Sleep(1000);
+
+ char timehhmmss[16], szRootSC[64], logfolder[512], ziptime[64], NightlyCleanThreshhold[64];
+ struct tm tmbuf;
+ time_t t = time(NULL);
+ localtime_r(&t, &tmbuf);
+ sprintf(timehhmmss, "%02d:%02d:%02d", tmbuf.tm_hour, tmbuf.tm_min, tmbuf.tm_sec);
+
+ *ziptime=0;
+ *NightlyCleanThreshhold=0;
+
+ if (MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile))
+ { MyGetPrivateProfileString(szRootSC, "ziptime", "", ziptime, 64, ConfigFile);
+ MyGetPrivateProfileString(szRootSC, "NightlyCleanThreshhold", "0", NightlyCleanThreshhold, 64, ConfigFile);
+ }
+
+ if (memicmp(timehhmmss, ziptime, strlen(ziptime))==0 && strlen(ziptime))
+ { if (!ZipTriggered)
+ { // does the log folder exists
+ strcpy(logfolder, BaseDir); strcat(logfolder, "logs");
+ if (!dgate_IsDirectory(logfolder))continue;
+
+ // create zip file name for today or yesterday
+ if (atoi(ziptime)<8) t = time(NULL) - 24*3600;
+ else t = time(NULL);
+ localtime_r(&t, &tmbuf);
+ sprintf(logfolder + strlen(logfolder), "%clogs_%04d%02d%02d.zip", PATHSEPCHAR, tmbuf.tm_year+1900, tmbuf.tm_mon+1, tmbuf.tm_mday);
+
+ // do not overwrite current zip
+ if (!DFileExists(logfolder))
+ { char b[512];
+
+ // something to zip
+ strcpy(b, BaseDir);
+ strcat(b, "serverstatus.log");
+ if (!DFileExists(b)) continue;
+
+ // zip the relevant files
+ ZipTriggered = TRUE;
+#ifdef WIN32
+ sprintf(b, "-y -tzip a \"%s\" \"%s*.log\" \"%s*.ini\" \"%s*.sql\" \"%s*.map\" \"%s*.lst\"", logfolder, BaseDir, BaseDir, BaseDir, BaseDir, BaseDir);
+ BackgroundExec("7za.exe", b);
+#else
+ sprintf(b, "7za -y -tzip a \"%s\" \"%s*.log\" \"%s*.ini\" \"%s*.sql\" \"%s*.map\" \"%s*.lst\"", logfolder, BaseDir, BaseDir, BaseDir, BaseDir, BaseDir);
+ system(b);
+#endif
+ // delete the usual log file stuff that was just zipped
+ strcpy(b, BaseDir); strcat(b, "serverstatus.log"); unlink(b);
+ strcpy(b, BaseDir); strcat(b, "PacsTrouble.log"); unlink(b);
+ strcpy(b, BaseDir); strcat(b, "PacsUser.log"); unlink(b);
+ strcpy(b, BaseDir); strcat(b, "maintenance.log"); unlink(b);
+ strcpy(b, BaseDir); strcat(b, "installation.log"); unlink(b);
+ strcpy(b, BaseDir); strcat(b, "conquestdicomserver.log"); unlink(b);
+
+ OperatorConsole.printf("Dgate zipped todays log files as: %s\n", logfolder);
+ }
+ }
+ }
+ else
+ ZipTriggered = FALSE;
+
+ if (memicmp(timehhmmss, "01:00", strlen("01:00"))==0 && atoi(NightlyCleanThreshhold))
+ { if (!CleanTriggered)
+ { CleanTriggered = TRUE;
+ if (LargestFreeMAG()<(unsigned int)atoi(NightlyCleanThreshhold))
+ { OperatorConsole.printf("Dgate is performing disk cleanup\n");
+ PanicKillOff((unsigned int)atoi(NightlyCleanThreshhold));
+ }
+ }
+ }
+ else
+ CleanTriggered = FALSE;
+
+ if (memicmp(timehhmmss, "03:00", strlen("03:00"))==0)
+ { if (!ScriptTriggered)
+ { ScriptTriggered = TRUE;
+ char cmd[1024];
+ MyGetPrivateProfileString("lua", "nightly", "", cmd, 1024, ConfigFile);
+ globalPDU.SetLocalAddress ( (BYTE *)"global" );
+ globalPDU.SetRemoteAddress ( (BYTE *)"nightly" );
+ globalPDU.ThreadNum = 0;
+ struct scriptdata sd = {&globalPDU, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, 0, 0};
+ do_lua(&(globalPDU.L), cmd, &sd);
+ if (sd.DDO) delete sd.DDO;
+ }
+ }
+ else
+ ScriptTriggered = FALSE;
+
+ if (!ScriptTriggered)
+ { ScriptTriggered = TRUE;
+ char cmd[1024];
+ MyGetPrivateProfileString("lua", "background", "", cmd, 1024, ConfigFile);
+ globalPDU.SetLocalAddress ( (BYTE *)"global" );
+ globalPDU.SetRemoteAddress ( (BYTE *)"background" );
+ globalPDU.ThreadNum = 0;
+ struct scriptdata sd = {&globalPDU, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, 0, 0};
+ do_lua(&(globalPDU.L), cmd, &sd);
+ if (sd.DDO) delete sd.DDO;
+ ScriptTriggered = FALSE;
+ }
+ }
+ OperatorConsole.printf("Stopped zip and cleanup thread\n");
+ return TRUE;
+}
+
+void StartZipThread(void)
+{ if (GoZipThread) return;
+
+ GoZipThread = TRUE;
+#ifdef WIN32
+ unsigned long ThreadID;
+ CreateThread(NULL, 0x000ff000, (LPTHREAD_START_ROUTINE) zipthread, NULL, 0, &ThreadID);
+#else
+ pthread_t ThreadID;
+ pthread_create(&ThreadID, NULL, (void*(*)(void*))zipthread, (void *)NULL);
+ pthread_detach(ThreadID);
+#endif
+}
+
+void StopZipThread(void)
+{ GoZipThread = FALSE;
+ Sleep(2000);
+}
+
+// some help for the simple user
+BOOL
+PrintOptions ()
+ {
+ fprintf(stderr, "\n");
+ fprintf(stderr, "DGATE: UCDMC/NKI DICOM server thread and PACS utility application %s\n", DGATE_VERSION);
+ fprintf(stderr, "\n");
+ fprintf(stderr, "Usage:\n");
+ fprintf(stderr, "(1) DGATE <-!#|-v|-u#|-^#> Report as in dicom.ini|stdout|UDP|File(#=port)\n");
+ fprintf(stderr, " [-p#|-qIP|-b] Set port|Set target IP|run debug 1-thread mode\n");
+ fprintf(stderr, " [-wDIR] Set the working directory for dgate(ini,dic,...)\n");
+ fprintf(stderr, " [-i|-r|-arDEVICE] Init|Init/regenerate DB|Regen single device\n");
+ fprintf(stderr, " [-d|-m|-k] List (-d) devices (-m) AE map (-k) DICOM.SQL\n");
+ fprintf(stderr, " [-t|-o] Test console|Test database\n");
+ fprintf(stderr, " [-sOpt|-esap d u p] Create ODBC source (WIN32), database with SApw\n");
+ fprintf(stderr, " [-nd|-nc#|-jd|-jc#] NKI de-/compress#|JPEG de-/compress# FILE\n");
+ fprintf(stderr, " [-j*##|-j-##FILE] Recompress FILE to ##\n");
+ fprintf(stderr, " [-as#,N|-amFROM,TO] Select#KB to archive of MAGN|move device data\n");
+ fprintf(stderr, " [-au|-aeFROM,TO] Undo select for archiving|rename device\n");
+ fprintf(stderr, " [-av|-atDEVICE] Verify mirror disk|Test read files for DEVICE\n");
+ fprintf(stderr, " [-abJUKEBOX1.2,N] Make cacheset to burn JUKEBOX1,CD2 from MAGN\n");
+ fprintf(stderr, " [-acJUKEBOX1.2] Verify JUKEBOX1,CD2 against cacheset\n");
+ fprintf(stderr, " [-adJUKEBOX1.2] Verify and delete cacheset for JUKEBOX1, CD2\n");
+ fprintf(stderr, " [-f<p|t|s|i>ID] Delete DB for Patient, sTudy, Series, Image\n");
+ fprintf(stderr, " [-f<e|d|z>file] Enter/Delete DB of file, Zap server file\n");
+ fprintf(stderr, " [-faFILE<,ID>] Add file to server<optionally change PATID>\n");
+ fprintf(stderr, " [-zID] Delete (zap) patient\n");
+ fprintf(stderr, " [-frDEVICE,DIR] Regen single directory DIR on DEVICE\n");
+ fprintf(stderr, " [-f<c|k>PATID,file] Change/Kopy PATID of file (irreversible/once)\n");
+ fprintf(stderr, " [-f?file|-fu|-c#] get UID of file|Make new UID|UID helper(0..99)\n");
+ fprintf(stderr, " [-ff#] Delete old patients until #MB free\n");
+ fprintf(stderr, " [-gSERVER,DATE] grab images from SERVER of date not on here\n");
+ fprintf(stderr, " Otherwise: run as threaded server, port=1111\n");
+ fprintf(stderr, "\n");
+ fprintf(stderr, "(2) DGATE FileMapping Run server child; shared memory has socket#\n");
+ fprintf(stderr, "\n");
+ fprintf(stderr, "(3) DGATE <-pPORT> <-qIP> --command:arguments\n");
+ fprintf(stderr, " Send command to (this or other) running server\n");
+ fprintf(stderr, " (works directly - use with care)\n");
+ fprintf(stderr, "Delete options:\n");
+ fprintf(stderr, " --deleteimagefile:file Delete given image file from server\n" );
+ fprintf(stderr, " --deletepatient:patid Delete given patient from server\n" );
+ fprintf(stderr, " --deletestudy:patid:studyuid Delete given study from server\n" );
+ fprintf(stderr, " --deletestudies:date(range) Delete studies from server on date\n" );
+ fprintf(stderr, " --deleteseries:patid:seriesuid Delete given series from server\n" );
+ fprintf(stderr, " --deleteimagefromdb:file Delete given file from db only\n" );
+ fprintf(stderr, " --deletesopfromdb:pat,study,series,sop Delete specified image from db only\n" );
+ fprintf(stderr, "\n");
+ fprintf(stderr, "DICOM move options:\n");
+ fprintf(stderr, " --movepatient:source,dest,patid Move patient, source e.g. (local)\n" );
+ fprintf(stderr, " --movestudy:source,dest,patid:studyuid Move study, patid: optional\n" );
+ fprintf(stderr, " --moveaccession:source,dest,patid:acc Move by Accession#, patid: optional\n" );
+ fprintf(stderr, " --movestudies:source,dest,date(range) Move studies on date\n" );
+ fprintf(stderr, " --moveseries:src,dst,patid:seruid,stuid Move series patid: optional\n" );
+ fprintf(stderr, "\n");
+ fprintf(stderr, "Modification of dicom objects:\n");
+ fprintf(stderr, " --modifypatid:patid,file Change patid of given file\n" );
+ fprintf(stderr, " --anonymize:patid,file Anonymize given file\n" );
+ fprintf(stderr, " --modifystudy:p,s,script Change items in patient or study\n" );
+ fprintf(stderr, " --modifyseries:p,s,script Change items in series\n" );
+ fprintf(stderr, " --modifyimage:file,script Change items in file\n" );
+ fprintf(stderr, " --mergestudy:uid,uid,.. Start merging studies with given studyuids\n" );
+ fprintf(stderr, " --mergestudyfile:file Use to process all files to merge\n" );
+ fprintf(stderr, " --mergeseries:uid,uid,.. Start merging series with given seriesuids\n" );
+ fprintf(stderr, " --mergeseriesfile:file Use to process all files to merge\n" );
+ fprintf(stderr, " --attachanytopatient:any,sample Modify uids to attach any object to\n" );
+ fprintf(stderr, " --attachanytostudy:any,sample patient|study|series in sample file\n" );
+ fprintf(stderr, " --attachanytoseries:any,sample Do not attach same at different levels\n" );
+ fprintf(stderr, " --attachrtplantortstruct:plan,struc Attach rtplan to rtstruct\n" );
+ fprintf(stderr, "\n");
+ fprintf(stderr, "Maintenance options:\n");
+ fprintf(stderr, " --initializetables: Clear and create database\n" );
+ fprintf(stderr, " --initializetables:1 Clear and create database without indices\n" );
+ fprintf(stderr, " --initializetables:2 Clear and create worklist database\n" );
+ fprintf(stderr, " --regen: Re-generate entire database\n" );
+ fprintf(stderr, " --regendevice:device Re-generate database for single device\n" );
+ fprintf(stderr, " --regendir:device,dir Re-generate database for single directory\n" );
+ fprintf(stderr, " --regenfile:file Re-enter given file in database\n" );
+ fprintf(stderr, " --makespace:# Delete old patients to make #MB space\n" );
+ fprintf(stderr, " --quit: Stop the server\n" );
+ fprintf(stderr, " --safequit: Stop the server when not active\n" );
+ fprintf(stderr, "\n");
+ fprintf(stderr, "Logging options:\n");
+ fprintf(stderr, " --debuglog_on:file/port Start debug logging\n" );
+ fprintf(stderr, " --log_on:file/port/pipe Start normal logging\n" );
+ fprintf(stderr, " --debuglevel:# Set debug logging level\n" );
+ fprintf(stderr, " --display_status:file Display server status\n" );
+ fprintf(stderr, " --status_string:file Display status string of submit operation\n" );
+ fprintf(stderr, " --checklargestmalloc: Estimates DICOM object size limit\n" );
+ fprintf(stderr, " --get_freestore:dev,fmt Report free #Mb on device\n" );
+ fprintf(stderr, " --testmode:# Append # to dicom filenames\n" );
+ fprintf(stderr, " --echo:AE,file Echo server; show response\n" );
+ fprintf(stderr, "\n");
+ fprintf(stderr, "Configuration options:\n");
+ fprintf(stderr, " --get_param:name,fmt Read any parameter from DICOM.INI\n" );
+ fprintf(stderr, " --get_ini_param:name,fmt Read any parameter from DICOM.INI\n" );
+ fprintf(stderr, " --get_ini_num:index,fmt List any entry from DICOM.INI\n" );
+ fprintf(stderr, " --get_ini:fmt List all entries from DICOM.INI\n" );
+ fprintf(stderr, " --put_param:name,value Write any parameter to DICOM.INI\n" );
+ fprintf(stderr, " --delete_param:name Delete any parameter from DICOM.INI\n" );
+ fprintf(stderr, " --read_ini: Re-read all parameters from DICOM.INI\n" );
+ fprintf(stderr, " --get_amap:index,fmt List any entry from ACRNEMA.MAP\n" );
+ fprintf(stderr, " --get_amaps:fmt List all entries from ACRNEMA.MAP\n" );
+ fprintf(stderr, " --put_amap:i,AE,ip,p#,cmp Write entry in memory for ACRNEMA.MAP\n" );
+ fprintf(stderr, " --delete_amap:index Delete entry in memory for ACRNEMA.MAP\n" );
+ fprintf(stderr, " --write_amap: Write ACRNEMA.MAP from memory to disk\n" );
+ fprintf(stderr, " --read_amap: Re-read ACRNEMA.MAP from disk to memory\n" );
+ fprintf(stderr, " --get_sop:index,fmt List any accepted service class UID\n" );
+ fprintf(stderr, " --put_sop:index,UID,name Write/add accepted service class UID\n" );
+ fprintf(stderr, " --delete_sop:index Delete accepted service class UID\n" );
+ fprintf(stderr, " --get_transfer:index,fmt List any accepted transfer syntax\n" );
+ fprintf(stderr, " --put_transfer:in,UID,nam Write/add accepted transfer syntax\n" );
+ fprintf(stderr, " --delete_transfer:index Delete accepted transfer syntax\n" );
+ fprintf(stderr, " --get_application:idx,fmt List any accepted application UID\n" );
+ fprintf(stderr, " --put_application:i,U,n Write/add accepted application UID\n" );
+ fprintf(stderr, " --delete_application:inde Delete accepted application UID\n" );
+ fprintf(stderr, " --get_localae:index,fmt List any accepted local AE title\n" );
+ fprintf(stderr, " --put_localae:in,AE,name Write/add accepted local AE title\n" );
+ fprintf(stderr, " --delete_localae:index Delete accepted local AE title\n" );
+ fprintf(stderr, " --get_remoteae:index,fmt List any accepted remote AE title\n" );
+ fprintf(stderr, " --put_remoteae:in,AE,name Write/add accepted remote AE title\n" );
+ fprintf(stderr, " --delete_remoteae:index Delete accepted remote AE title\n" );
+ fprintf(stderr, " --get_dic:index,fmt List any dicom dictionary item\n" );
+ fprintf(stderr, " --get_sqldef:level,in,fmt List any database field definition\n" );
+ fprintf(stderr, "\n");
+ fprintf(stderr, "Communication options:\n");
+ fprintf(stderr, " --addimagefile:file,patid Copy file into server, optionally new patid\n" );
+ fprintf(stderr, " --addlocalfile:file,patid Copy local file into server, opt. new patid\n" );
+ fprintf(stderr, " --loadanddeletedir:dir,patid Load folder and delete its contents\n" );
+ fprintf(stderr, " --loadhl7:file Load HL7 data into worklist\n" );
+ fprintf(stderr, " --dump_header:filein,fileout Create header dump of file\n" );
+ fprintf(stderr, " --forward:file,mode,server Send file with compr. mode to server\n");
+ fprintf(stderr, " --grabimagesfromserver:AE,date Update this server from other\n" );
+ fprintf(stderr, " --prefetch:patientid Prefetch all images for improved speed\n" );
+ fprintf(stderr, " --browsepatient:searchstring Select patient in windows GUI\n" );
+ fprintf(stderr, " --submit:p,s,s,s,target,pw,scr Immediate sftp submit of data\n" );
+ fprintf(stderr, " --submit2:p,s,s,s,target,c,scr Immediate submit with command line c\n" );
+ fprintf(stderr, " --export:p,st,ser,sop,file,scr Immediate process and zip/7z data\n" );
+ fprintf(stderr, " --scheduletransfer:options Background sftp transfer as above\n" );
+ fprintf(stderr, "\n");
+ fprintf(stderr, "Test options:\n");
+ fprintf(stderr, " --genuid: Generate an UID\n" );
+ fprintf(stderr, " --changeuid:UID Give new UID as generated now or before\n" );
+ fprintf(stderr, " --changeuidback:UID Give old UID from one generated above\n" );
+ fprintf(stderr, " --checksum:string Give checksum of string\n" );
+ fprintf(stderr, " --testcompress:file Enter file in server with many compressions\n" );
+ fprintf(stderr, " --clonedb:AE Clone db from server for testing\n" );
+ fprintf(stderr, "\n");
+ fprintf(stderr, "Conversion options:\n");
+ fprintf(stderr, " --convert_to_gif:file,size,out,l/w/f Downsize and convert to mono GIF\n");
+ fprintf(stderr, " --convert_to_bmp:file,size,out,l/w/f Downsize and convert to color BMP\n");
+ fprintf(stderr, " --convert_to_jpg:file,size,out,l/w/f Downsize and convert to color JPG\n");
+ fprintf(stderr, " --convert_to_dicom:file,size,comp,f Downsize/compress/frame DICOM\n");
+ fprintf(stderr, " --extract_frames:file,out,first,last Select frames of DICOM file\n");
+ fprintf(stderr, " --count_frames:file report # frames in DICOM file\n");
+ fprintf(stderr, " --uncompress:file,out Uncompress DICOM\n");
+ fprintf(stderr, " --wadorequest:parameters Internal WADO server\n");
+ fprintf(stderr, "\n");
+ fprintf(stderr, "Database options:\n");
+ fprintf(stderr, " --query:table|fields|where|fmt|file Arbitrary query output to file\n" );
+ fprintf(stderr, " --query2:tab|fld|whe|fmt|max|file Same but limit output rows to max\n" );
+ fprintf(stderr, " --patientfinder:srv|str|fmt|file List patients on server\n" );
+ fprintf(stderr, " --studyfinder:srv|str|fmt|file List studies on server\n" );
+ fprintf(stderr, " --seriesfinder:srv|str|fmt|file List series on server\n" );
+ fprintf(stderr, " --imagefinder:srv|str|fmt|file List images on server\n" );
+ fprintf(stderr, " --serieslister:srv|pat|stu|fmt|file List series in a study\n" );
+ fprintf(stderr, " --imagelister:srv|pat|ser|fmt|file List (local) files in a series\n" );
+ fprintf(stderr, " --extract:PatientID = 'id' Extract all dbase tables to X..\n" );
+ fprintf(stderr, " --extract: Extract patient dbase table to XA..\n" );
+ fprintf(stderr, " --addrecord:table|flds|values Append record, values must be in ''\n" );
+ fprintf(stderr, " --deleterecord:table,where Delete record from table\n" );
+ fprintf(stderr, "For DbaseIII without ODBC:\n");
+ fprintf(stderr, " --packdbf: Pack database, recreate memory index\n" );
+ fprintf(stderr, " --indexdbf: Re-create memory index\n" );
+ fprintf(stderr, "\n");
+ fprintf(stderr, "Archival options:\n");
+ fprintf(stderr, " --renamedevice:from,to Rename device in database\n" );
+ fprintf(stderr, " --verifymirrordisk:device Verify mirror disk for selected device\n" );
+ fprintf(stderr, " --testimages:device Test read all images on device\n" );
+ fprintf(stderr, " --movedatatodevice:to,from Move patients from one device to another\n" );
+ fprintf(stderr, " --moveseriestodevice:to,from Move series from one device to another\n" );
+ fprintf(stderr, " --selectlruforarchival:kb,device Step 1 for archival: to device.Archival\n" );
+ fprintf(stderr, " --selectseriestomove:device,age,kb Step 1 for archival: to device.Archival\n" );
+ fprintf(stderr, " --preparebunchforburning:to,from Step 2 for archival: moves to cache\n" );
+ fprintf(stderr, " --deletebunchafterburning:deviceto Step 3 for archival: deletes from cache\n" );
+ fprintf(stderr, " --comparebunchafterburning:deviceto Part step 3 - compare jukebox to cache\n" );
+ fprintf(stderr, " --restoremagflags: Undo archival sofar\n" );
+ fprintf(stderr, "\n");
+ fprintf(stderr, "Scripting options:\n");
+ fprintf(stderr, " --lua:chunk Run lua chunk in server, wait to finish\n" );
+ fprintf(stderr, " --luastart:chunk Run lua chunk in server, retn immediate\n" );
+ fprintf(stderr, " --dolua:chunk Run lua chunk in this dgate instance\n" );
+ fprintf(stderr, " --dolua:filename Run lua file in this dgate instance\n" );
+ return ( TRUE );
+ }
+
+// external references
+BOOL SelectLRUForArchival(char *Device, int KB, ExtendedPDU_Service *PDU);
+BOOL SelectSeriesForArchival(char *Device, int age, int kb);
+BOOL PrepareBunchForBurning(char *DeviceFrom, char *DeviceTo);
+BOOL MoveDataToDevice(char *DeviceFrom, char *DeviceTo);
+BOOL MoveSeriesToDevice(char *DeviceFrom, char *DeviceTo);
+BOOL RestoreMAGFlags();
+BOOL CompareBunchAfterBurning(char *DeviceTo);
+BOOL DeleteBunchAfterBurning(char *DeviceTo);
+BOOL VerifyMirrorDisk(char *DeviceFrom);
+BOOL RenameDevice(char *DeviceFrom, char *DeviceTo);
+BOOL TestImages(char *DeviceFrom);
+
+// forward references
+BOOL GrabImagesFromServer(BYTE *calledae, const char *studydate, char *destination);
+
+#if defined(__BORLANDC__) || defined(__WATCOMC__)
+typedef BOOL (__stdcall *_SQLConfigDataSource)(HWND hwndParent,
+ WORD fRequest,
+ LPCSTR lpszDriver,
+ LPCSTR lpszAttributes);
+_SQLConfigDataSource __SQLConfigDataSource;
+#define SQLConfigDataSource __SQLConfigDataSource
+#define ODBC_ADD_DSN 1 // Add data source
+#endif
+
+static char ServerCommandAddress[64] = "127.0.0.1";
+
+// Main routine for parsing the command line; return FALSE when not running
+// as server or a socket # when running as server thread
+int
+ParseArgs (int argc, char *argv[], ExtendedPDU_Service *PDU)
+ {
+ UINT Valid;
+ int valid_argc, mode1=0;
+ int Socketfd = 0;
+ BOOL bUIDPostfixSet = FALSE;
+
+ Valid = 2;
+
+ ConfigMicroPACS();
+
+ UserLog.On(UserLogFile);
+ UserLog.AddTimeStamps(TRUE);
+ TroubleLog.On(TroubleLogFile);
+ TroubleLog.AddTimeStamps(TRUE);
+
+ valid_argc = 1;
+
+ while ( valid_argc < argc )
+ {
+#ifndef UNIX // Win32...
+ if ((argv[valid_argc][0]=='-')||(argv[valid_argc][0]=='/'))
+#else // UNIX..
+ if(argv[valid_argc][0]=='-')
+#endif
+ {
+ switch ( argv[valid_argc][1] )
+ {
+ case 'h': // wait e.g., to allow attaching debugger
+ case 'H':
+#ifdef WIN32
+ getch();
+#endif WIN32
+ break; //Done already.
+
+ case 'w': // set workdir for ini, map, dic
+ case 'W':
+ break; //Done already.
+
+ case 'v': // verbose mode
+ case 'V':
+ SystemDebug.On();
+ OperatorConsole.On();
+ break;
+
+ case 'b': // debug mode
+ case 'B':
+ SystemDebug.On();
+ OperatorConsole.On();
+ DebugLevel = 4;
+ NoThread=TRUE;
+ break;
+
+ case 'c': // set UID counter
+ case 'C':
+ UIDPostfix = atoi(argv[valid_argc]+2);
+ bUIDPostfixSet = TRUE;
+ break;
+
+ case 'u':
+ case 'U': // be verbose to specified pipe/udp
+ if(argv[valid_argc][2] == PATHSEPCHAR)
+ {
+ OperatorConsole.OnMsgPipe(argv[valid_argc]+2);
+ SystemDebug.OnMsgPipe(argv[valid_argc]+2);
+ }
+ else
+ {
+ OperatorConsole.OnUDP(OCPipeName, argv[valid_argc]+2);
+ SystemDebug.OnUDP(OCPipeName, argv[valid_argc]+2);
+ }
+ break;
+
+
+ case '!': // be verbose to pipe/udp specified in DICOM.INI (no debug)
+ if(OCPipeName[0] == PATHSEPCHAR)
+ {
+ OperatorConsole.OnMsgPipe(OCPipeName);
+ }
+ else
+ {
+ if (argv[valid_argc][2]>='0' && argv[valid_argc][2]<='9')
+ {
+ OperatorConsole.OnUDP(OCPipeName, argv[valid_argc]+2);
+#if 0
+ SystemDebug.OnUDP(OCPipeName, argv[valid_argc]+2);
+#endif
+ }
+ else
+ OperatorConsole.OnUDP(OCPipeName, "1111");
+ }
+ break;
+
+ case '^': // be verbose to passed file with timestamps (no debug)
+ OperatorConsole.On(argv[valid_argc]+2);
+ OperatorConsole.AddTimeStamps(1);
+ StartZipThread();
+ break;
+
+ case '#': // be verbose to passed file with timestamps (with debug)
+ OperatorConsole.On(argv[valid_argc]+2);
+ OperatorConsole.AddTimeStamps(1);
+ SystemDebug.On(argv[valid_argc]+2);
+ SystemDebug.AddTimeStamps(1);
+ StartZipThread();
+ break;
+
+ case 'p': // override dicom.ini port#
+ case 'P':
+ strcpy((char*)Port, argv[valid_argc]+2);
+ ++Valid;
+ break;
+ // fall through was not intended !
+
+ case 'q': // override dicom.ini ServerCommandAddress (for dgate -- options)
+ case 'Q':
+ strcpy((char*)ServerCommandAddress, argv[valid_argc]+2);
+ ++Valid;
+ break;
+ // fall through was not intended !
+
+ case 'r': // init and regenerate database
+ case 'R':
+ RunServer = FALSE;
+ NeedPack = 2;
+ SystemDebug.printf("Regen Database\n");
+
+ if(!LoadKFactorFile((char*)KFACTORFILE))
+ {
+ OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE);
+ exit(1);
+ }
+
+ OperatorConsole.printf("Step 1: Re-intialize SQL Tables\n");
+
+ mode1 = atoi(argv[valid_argc]+2);
+ InitializeTables (mode1);
+
+ OperatorConsole.printf("Step 2: Load / Add DICOM Object files\n");
+
+ Regen();
+
+ OperatorConsole.printf("Regeneration Complete\n");
+
+ return ( FALSE );
+
+ case 'd': // List magnetic device status
+ case 'D':
+ RunServer = FALSE;
+ NeedPack = FALSE;
+
+ SystemDebug.Off();
+ PrintFreeSpace();
+ return ( FALSE );
+
+ case 'm': // list map of outgoing AE's
+ case 'M':
+ RunServer = FALSE;
+ NeedPack = FALSE;
+
+ if(!InitACRNemaAddressArray())
+ {
+ OperatorConsole.printf("***Error loading acr-nema map file:%s\n",ACRNEMAMAP);
+ exit(1);
+ }
+
+ PrintAMap();
+ return ( FALSE );
+
+
+ case 'k': // list K factor file (DICOM.SQL)
+ case 'K':
+ RunServer = FALSE;
+ NeedPack = FALSE;
+
+ if(!LoadKFactorFile((char*)KFACTORFILE))
+ {
+ OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE);
+ exit (1);
+ }
+
+ PrintKFactorFile();
+ return ( FALSE );
+
+
+ case 't': // test (TCP/IP) console connnection
+ case 'T':
+ {
+ char lt[] = "This is a very long text output for testing -- ";
+ RunServer = FALSE;
+ NeedPack = FALSE;
+ OperatorConsole.printf("This output is generated by the dicom server application\n");
+ OperatorConsole.printf("If you can read this, the console communication is OK\n");
+ SystemDebug.printf("This is systemdebug output; can you read this ?\n");
+ SystemDebug.printf("%s%s%s%s%s%s\n", lt, lt, lt, lt, lt, lt);
+ OperatorConsole.printf(" ---------- Succesful end of test -----------\n");
+ return ( FALSE );
+ }
+
+ case 'o': // test ODBC database connnection
+ case 'O':
+ {
+ Database aDB;
+ int i;
+ RunServer = FALSE;
+ NeedPack = FALSE;
+ for (i=1; i<=10; i++)
+ {
+ OperatorConsole.printf("Attempting to open database; test #%d of 10\n", i);
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ exit (1);
+ }
+
+ OperatorConsole.printf("Creating test table\n");
+ aDB.CreateTable ( "xtesttable", "Name varchar(254), AccessTime int" );
+
+ OperatorConsole.printf("Adding a record\n");
+ aDB.AddRecord("xtesttable", "Name", "'Testvalue'");
+
+ OperatorConsole.printf("Dropping test table\n");
+ aDB.DeleteTable ( "xtesttable" );
+
+ OperatorConsole.printf("Closing database\n");
+ aDB.Close();
+ }
+
+ OperatorConsole.printf(" ---------- Succesful end of test -----------\n");
+ return ( FALSE );
+ }
+
+ case 'a': // Archival code
+ case 'A': // Archival code
+ {
+ RunServer = FALSE;
+ NeedPack = 5;
+ OperatorConsole.printf(" ---------- Start archival operation -----------\n");
+
+ if(!LoadKFactorFile((char*)KFACTORFILE))
+ {
+ OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE);
+ exit(1);
+ }
+
+ // Select a number of KB to archive from device MAGn (default MAG0)
+ if (argv[valid_argc][2] == 's' || argv[valid_argc][2] == 'S')
+ {
+ char MAG[256];
+ char *p;
+ p = strchr(argv[valid_argc]+3,',');
+ if (p)
+ sprintf(MAG, "MAG%d", atoi(p+1));
+ else
+ strcpy(MAG, "MAG?");
+ if (!SelectLRUForArchival(MAG, atoi(argv[valid_argc]+3), PDU))
+ exit(1);
+ }
+
+ // Create cache set for burning for JUKEBOXn.n from MAGn (default MAG0)
+ else if (argv[valid_argc][2] == 'b' || argv[valid_argc][2] == 'B')
+ {
+ char MAG[256], Device[256];
+ char *p;
+ strcpy(Device, argv[valid_argc]+3);
+ p = strchr(Device,',');
+ if (p)
+ {
+ sprintf(MAG, "MAG%d", atoi(p+1));
+ *p = 0;
+ }
+ else
+ strcpy(MAG, "MAG?");
+ if (!PrepareBunchForBurning(MAG, Device))
+ exit(1);
+ }
+
+ // Move (all) data from device1 to device2
+ else if (argv[valid_argc][2] == 'm' || argv[valid_argc][2] == 'M')
+ {
+ char Device1[256];
+ char *p;
+ strcpy(Device1, argv[valid_argc]+3);
+ p = strchr(Device1,',');
+ if (p)
+ {
+ *p = 0;
+ if (!MoveDataToDevice(Device1, p+1)) exit(1);
+ }
+ else
+ exit(1);
+ }
+
+ // Undo any archiving that was not completed
+ else if (argv[valid_argc][2] == 'u' || argv[valid_argc][2] == 'U')
+ {
+ if (!RestoreMAGFlags())
+ exit(1);
+ }
+
+ // Verify CD in jukebox against its cache set
+ else if (argv[valid_argc][2] == 'c' || argv[valid_argc][2] == 'C')
+ {
+ if (!CompareBunchAfterBurning(argv[valid_argc]+3))
+ exit(1);
+ }
+
+ // Verify MAG device against its mirror device
+ else if (argv[valid_argc][2] == 'v' || argv[valid_argc][2] == 'V')
+ {
+ if (!VerifyMirrorDisk(argv[valid_argc]+3))
+ exit(1);
+ }
+
+ // Test read slices on device
+ else if (argv[valid_argc][2] == 't' || argv[valid_argc][2] == 'T')
+ {
+ if (!TestImages(argv[valid_argc]+3))
+ exit(1);
+ }
+
+ // Delete cache set for burned CD
+ else if (argv[valid_argc][2] == 'd' || argv[valid_argc][2] == 'D')
+ {
+ if (!DeleteBunchAfterBurning(argv[valid_argc]+3))
+ exit(1);
+ }
+
+ // Regen a single device (for database maintenance)
+ else if (argv[valid_argc][2] == 'r' || argv[valid_argc][2] == 'R')
+ {
+ if(!LoadKFactorFile((char*)KFACTORFILE))
+ {
+ OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE);
+ exit(1);
+ }
+ OperatorConsole.printf("Regen single device: %s\n", argv[valid_argc]+3);
+ if (!Regen(argv[valid_argc]+3, FALSE)) exit(1);
+ OperatorConsole.printf("Regeneration Complete\n");
+ }
+
+ // rEname device name
+ else if (argv[valid_argc][2] == 'e' || argv[valid_argc][2] == 'E')
+ {
+ char DeviceFrom[256];
+ char *p;
+ strcpy(DeviceFrom, argv[valid_argc]+3);
+ p = strchr(DeviceFrom,',');
+ if (p)
+ {
+ *p = 0;
+ if (!RenameDevice(DeviceFrom, p+1)) exit(1);
+ }
+ else
+ {
+ OperatorConsole.printf("option requires two device names\n");
+ exit(1);
+ }
+ }
+
+ else
+ {
+ OperatorConsole.printf("Unknown archiving option\n");
+ exit(1);
+ }
+
+ OperatorConsole.printf(" ---------- End of archival operation -----------\n");
+ return ( FALSE );
+ }
+
+
+#ifdef WIN32
+ case 's':
+ case 'S': // Create ODBC data source
+ {
+ char Options[1512], Driver[512];
+ int i, len;
+#if defined(__BORLANDC__) || defined(__WATCOMC__)
+ HINSTANCE hODBCInst = LoadLibrary("odbccp32.dll");
+ __SQLConfigDataSource= (_SQLConfigDataSource)GetProcAddress(hODBCInst, "SQLConfigDataSource");
+#endif
+ strcpy(Driver, "Microsoft dBase Driver (*.dbf)");
+
+ strcpy(Options,
+ "DSN=ConQuestPacs;"
+ "Description=ConQuest DICOM server data source;"
+ "Fil=dBase III;"
+ "DriverID=21;"
+ "Deleted=1;"
+ "DefaultDir=C:\\quirt");
+
+ for (i=2; i<strlen(argv[valid_argc]); i++)
+ {
+ if (argv[valid_argc][i] == ';')
+ {
+ memcpy(Driver, argv[valid_argc]+2, i-2);
+ Driver[i-2]=0;
+ strcpy(Options, argv[valid_argc]+i+1);
+ Options[strlen(Options)+1] = 0;
+ break;
+ }
+ }
+
+ OperatorConsole.printf("Creating data source\n");
+ OperatorConsole.printf("Driver = %s\n", Driver);
+ OperatorConsole.printf("Options = %s\n", Options);
+
+ len = strlen(Options);
+ for (i=0; i<len; i++)
+ if (Options[i] == ';') Options[i] = 0;
+
+ RunServer = FALSE;
+ NeedPack = FALSE;
+ if ( !SQLConfigDataSource(NULL, ODBC_ADD_SYS_DSN, Driver, Options) )
+ // if ( !SQLConfigDataSource(NULL, ODBC_ADD_DSN, Driver, Options) )
+ { char szMsg[256] = "(No details)";
+ char szTmp[280];
+ DWORD dwErrorCode;
+ OperatorConsole.printf("***Datasource configuration FAILED\n");
+#if !defined(__BORLANDC__) && !defined(__WATCOMC__) && 0
+ SQLInstallerError(1, &dwErrorCode, szMsg, sizeof(szMsg) - 1, NULL);
+ sprintf(szTmp, "***%s (ec=%d)\n", szMsg, dwErrorCode);
+ OperatorConsole.printf(szTmp);
+#endif
+ exit(1);
+ }
+ else
+ OperatorConsole.printf("Datasource configuration succesful\n");
+ OperatorConsole.printf(" ----------------------------------\n");
+ return ( FALSE );
+ }
+#endif
+
+
+ case 'e': // create database (-eSAPW DB USER PW)
+ case 'E':
+ {
+ Database DB;
+ DebugLevel=4;
+ if (DB.db_type==DT_POSTGRES)
+ {
+ if (DB.Open ( "postgres", "postgres", argv[valid_argc]+2, DataHost))
+ if (DB.CreateDatabase(argv[valid_argc+1], argv[valid_argc+2], argv[valid_argc+3]))
+ OperatorConsole.printf("succesfully created database and login\n");
+ }
+ else if (strcmp(argv[valid_argc+2], "root")==0 || strcmp(argv[valid_argc+2], "sa")==0)
+ {
+ if (DB.Open ( DataSource, argv[valid_argc+2], argv[valid_argc]+2, DataHost))
+ if (DB.CreateDatabase(argv[valid_argc+1], argv[valid_argc+2], argv[valid_argc]+3))
+ OperatorConsole.printf("succesfully created database\n");
+ }
+ else
+ {
+ if (DB.Open ( DataSource, "sa", argv[valid_argc]+2, DataHost))
+ if (DB.CreateDatabase(argv[valid_argc+1], argv[valid_argc+2], argv[valid_argc+3]))
+ OperatorConsole.printf("succesfully created database and login\n");
+ }
+ OperatorConsole.printf(" ----------------------------------\n");
+ exit(0);
+ }
+
+ case 'i': // initialize database
+ case 'I':
+ RunServer = FALSE;
+ NeedPack = FALSE;
+
+ OperatorConsole.printf("Initializing Tables\n");
+
+ if(!LoadKFactorFile((char*)KFACTORFILE))
+ {
+ OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE);
+ exit(1);
+ }
+
+ mode1 = atoi(argv[valid_argc]+2);
+ InitializeTables (mode1);
+
+ return ( FALSE );
+
+ case 'z': // delete (zap) patient
+ case 'Z':
+ RunServer = FALSE;
+ NeedPack = 5;
+
+ if(!LoadKFactorFile((char*)KFACTORFILE))
+ {
+ OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE);
+ exit (1);
+ }
+
+ if (!DeletePatient(argv[valid_argc]+2, FALSE))
+ exit(1);
+
+ return ( FALSE );
+
+ case 'g': // grab data from server
+ case 'G':
+ {
+ char *p;
+
+ RunServer = FALSE;
+ NeedPack = 5;
+
+ if(!InitACRNemaAddressArray())
+ {
+ OperatorConsole.printf("***Error loading acr-nema map file:%s\n",ACRNEMAMAP);
+ exit(1);
+ }
+
+ if(!LoadKFactorFile((char*)KFACTORFILE))
+ {
+ OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE);
+ exit (1);
+ }
+
+ p = strchr(argv[valid_argc]+2,',');
+ if (p)
+ {
+ *p=0;
+ if (!GrabImagesFromServer((unsigned char *)argv[valid_argc]+2, p+1, (char *)MYACRNEMA))
+ exit(1);
+ }
+ else
+ {
+ if (!GrabImagesFromServer((unsigned char *)argv[valid_argc]+2, "*", (char *)MYACRNEMA))
+ exit(1);
+ }
+
+ return ( FALSE );
+ }
+
+ case 'f': // Database fix options
+ case 'F':
+ RunServer = FALSE;
+ NeedPack = 5;
+
+ if(!LoadKFactorFile((char*)KFACTORFILE))
+ {
+ OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE);
+ exit (1);
+ }
+
+
+ if (argv[valid_argc][2] == 'p' || argv[valid_argc][2] == 'P')
+ {
+ if (!DeletePatient(argv[valid_argc]+3, TRUE))
+ exit(1);
+ }
+
+ if (argv[valid_argc][2] == 'f' || argv[valid_argc][2] == 'F')
+ {
+ if (LargestFreeMAG()>(unsigned int)atoi(argv[valid_argc]+3)) exit(0);
+
+ if (!PanicKillOff((unsigned int)atoi(argv[valid_argc]+3)))
+ exit(1);
+ }
+
+ else if (argv[valid_argc][2] == 't' || argv[valid_argc][2] == 'T')
+ {
+ if (!DeleteStudy(argv[valid_argc]+3, TRUE))
+ exit(1);
+ }
+
+ else if (argv[valid_argc][2] == 's' || argv[valid_argc][2] == 'S')
+ {
+ if (!DeleteSeries(argv[valid_argc]+3, TRUE))
+ exit(1);
+ }
+
+ else if (argv[valid_argc][2] == 'i' || argv[valid_argc][2] == 'I')
+ {
+ if (!DeleteImage(argv[valid_argc]+3, TRUE))
+ exit(1);
+ }
+
+ else if (argv[valid_argc][2] == 'r' || argv[valid_argc][2] == 'R')
+ {
+ char par[256];
+ char *p;
+ strcpy(par, argv[valid_argc]+3);
+ p = strchr(par,',');
+ if (p)
+ {
+ *p=0;
+ if (!Regen(par, FALSE, p+1))
+ exit(1);
+ }
+ else
+ if (!Regen("MAG0", FALSE, par))
+ exit(1);
+ }
+
+ else if (argv[valid_argc][2] == 'e' || argv[valid_argc][2] == 'E')
+ {
+ if (!RegenFile(argv[valid_argc]+3))
+ exit(1);
+ }
+
+ else if (argv[valid_argc][2] == 'd' || argv[valid_argc][2] == 'D')
+ {
+ if (!DeleteImageFile(argv[valid_argc]+3, TRUE))
+ exit(1);
+ }
+
+ else if (argv[valid_argc][2] == 'z' || argv[valid_argc][2] == 'Z')
+ {
+ if (!DeleteImageFile(argv[valid_argc]+3, FALSE))
+ exit(1);
+ }
+
+ else if (argv[valid_argc][2] == 'a' || argv[valid_argc][2] == 'A')
+ {
+ char par[1024];
+ char *p;
+
+ strcpy(par, argv[valid_argc]+3);
+ p = strchr(par,',');
+ if (bUIDPostfixSet)
+ gl_iFileCounter = UIDPostfix;
+ else
+ gl_iFileCounter = ComputeCRC(par, strlen(par));
+ if (p)
+ {
+ *p=0;
+ if (!AddImageFile(par, p+1, PDU))
+ exit(1);
+ }
+ else
+ {
+ if (!AddImageFile(par, NULL, PDU))
+ exit(1);
+ }
+ }
+
+ else if (argv[valid_argc][2] == '?')
+ {
+ char UID[256];
+ if (!GetImageFileUID(argv[valid_argc]+3, UID))
+ exit(1);
+ printf("%s\n", UID);
+ }
+
+ else if (argv[valid_argc][2] == 'u' || argv[valid_argc][2] == 'U')
+ {
+ char UID[256];
+ if (!GenUID(UID))
+ exit(1);
+ printf("%s\n", UID);
+ }
+
+ else if (argv[valid_argc][2] == 'c' || argv[valid_argc][2] == 'C')
+ {
+ char par[256];
+ char *p;
+ strcpy(par, argv[valid_argc]+3);
+ p = strchr(par,',');
+ if (p)
+ {
+ *p=0;
+ if (!ModifyPATIDofImageFile(p+1, par, TRUE, NULL, PDU))
+ exit(1);
+ }
+ }
+ else if (argv[valid_argc][2] == 'k' || argv[valid_argc][2] == 'K')
+ {
+ char par[256];
+ char *p;
+ strcpy(par, argv[valid_argc]+3);
+ p = strchr(par,',');
+ if (p)
+ {
+ *p=0;
+ if (!ModifyPATIDofImageFile(p+1, par, FALSE, NULL, PDU))
+ exit(1);
+ }
+ }
+ return ( FALSE );
+
+
+
+ case 'n': // NKI compression options
+ case 'N':
+ RunServer = FALSE;
+ NeedPack = FALSE;
+
+ if (argv[valid_argc][2] == 'd' || argv[valid_argc][2] == 'D')
+ {
+ //int dum;
+ //if (!DecompressImageFile(argv[valid_argc]+3, &dum))
+ char dum[3]="un";
+ if (!recompressFile(argv[valid_argc]+3, dum, PDU))
+ exit(1);
+ }
+
+ if (argv[valid_argc][2] == 'c' || argv[valid_argc][2] == 'C')
+ {
+ //int dum;
+ //if (!CompressNKIImageFile(argv[valid_argc]+4, argv[valid_argc][3]-'0', &dum))
+ if (!recompressFile(argv[valid_argc]+4, argv[valid_argc]+2, PDU))
+ exit(1);
+ }
+
+ return ( FALSE );
+
+ case 'j': // JPEG compression options
+ case 'J':
+ RunServer = FALSE;
+ NeedPack = FALSE;
+
+ if (argv[valid_argc][2] == 'd' || argv[valid_argc][2] == 'D')
+ {
+ //int dum;
+ //if (!DecompressImageFile(argv[valid_argc]+3, &dum))
+ char dum[3]="un";
+ if (!recompressFile(argv[valid_argc]+3, dum, PDU))
+ exit(1);
+ }
+
+ if (argv[valid_argc][2] == 'c' || argv[valid_argc][2] == 'C')
+ {
+ //int dum;
+ //if (!CompressJPEGImageFile(argv[valid_argc]+4, argv[valid_argc][3], &dum))
+ if (!recompressFile(argv[valid_argc]+4, argv[valid_argc]+2, PDU))
+ exit(1);
+ }
+
+ if (argv[valid_argc][2] == '*') // test recompressFile
+ {
+ char mode[4];
+ mode[0] = argv[valid_argc][3];
+ mode[1] = argv[valid_argc][4];
+ mode[2] = 0;
+ if (!recompressFile(argv[valid_argc]+5, mode, PDU))
+ exit(1);
+ }
+
+ if (argv[valid_argc][2] == '-') // test recompress
+ {
+ PDU_Service PDU2;
+// VR *pVR;
+
+ PDU2.AttachRTC(&VRType);
+
+ DICOMDataObject *pDDO;
+ pDDO = PDU2.LoadDICOMDataObject(argv[valid_argc]+5);
+ char mode[4];
+ mode[0] = argv[valid_argc][3];
+ mode[1] = argv[valid_argc][4];
+ mode[2] = 0;
+ if (!recompress(&pDDO, mode, "", mode[0]=='n' || mode[0]=='N', PDU))
+ exit(1);
+
+ PDU2.SaveDICOMDataObject(argv[valid_argc]+5, ACRNEMA_VR_DUMP, pDDO);
+ delete pDDO;
+ }
+
+ return ( FALSE );
+
+
+ case '-': // Server command
+ if (memcmp(argv[valid_argc]+2, "addlocalfile:", 13)==0)
+ {
+ char *p1 = strchr(argv[valid_argc]+2, ',');
+ if (p1) *p1=0;
+ char com[512];
+ if (p1) sprintf(com, "addimagefile:%s,%s", argv[valid_argc]+15, p1+1);
+ else sprintf(com, "addimagefile:%s", argv[valid_argc]+15);
+ printf("%s", com);
+ printf("%s", argv[valid_argc]+15);
+ SendServerCommand("Server command sent using DGATE -- option", com, 0, argv[valid_argc]+15, FALSE, TRUE);
+ exit(1);
+ }
+ if (memcmp(argv[valid_argc]+2, "dolua:", 6)==0)
+ {
+ struct stat st;
+ OperatorConsole.On();
+ //SystemDebug.On();
+ LoadKFactorFile((char*)KFACTORFILE);
+ InitACRNemaAddressArray();
+ struct scriptdata sd = {&globalPDU, NULL, NULL, -1, NULL, NULL, NULL, NULL, NULL, 0, NULL};
+ globalPDU.SetLocalAddress ( (BYTE *)"global" );
+ globalPDU.SetRemoteAddress ( (BYTE *)"dolua" );
+ globalPDU.ThreadNum = 0;
+ lua_createtable (globalPDU.L, 0, 0);
+ for (int i=0; i<argc; i++)
+ {
+ lua_pushinteger(globalPDU.L, i+1);
+ lua_pushstring (globalPDU.L, argv[i]);
+ lua_settable (globalPDU.L, -3);
+ }
+ lua_setglobal (globalPDU.L, "arg");
+ char file[1024], cmd[1024];
+ strcpy(file, argv[valid_argc]+8);
+ if(stat(file, &st) != 0)
+ {
+ memmove(file+4, file, strlen(file)+1);
+ strcpy(file, "lua");
+ file[3] = PATHSEPCHAR;
+ }
+ if(stat(file, &st) == 0)
+ sprintf(cmd, "dofile([[%s]])", file);
+ else
+ strcpy(cmd, argv[valid_argc]+8);
+ do_lua(&(globalPDU.L), cmd, &sd);
+ if (sd.DDO) delete sd.DDO;
+ exit(1);
+ }
+
+ SendServerCommand("Server command sent using DGATE -- option", argv[valid_argc]+2, 0, NULL, FALSE);
+ exit(1);
+
+ default: // provide some help
+ RunServer = FALSE;
+ NeedPack = FALSE;
+ PrintOptions();
+ return (FALSE);
+ }
+ }
+ else
+ {
+// FILE *logFile;
+
+// This is a simple way to get a socket#; but why make it simple if it can be done complex ?
+// Socketfd = (void*)atoi(argv[valid_argc]);
+
+
+// Open some channel (UDP/pipe) for statistics when running as server child (from .ini file)
+ if(OCPipeName[0] == PATHSEPCHAR)
+ {
+ OperatorConsole.OnMsgPipe(OCPipeName);
+ }
+ else
+ {
+ OperatorConsole.OnUDP(OCPipeName, "1111");
+ }
+
+// WIN32: get the socket# through shared memory
+#ifndef UNIX
+ HANDLE hMap;
+ IPCBlock *IPCBlockPtrInstance;
+ hMap = OpenFileMapping(FILE_MAP_ALL_ACCESS,
+ FALSE,
+ argv[valid_argc]);
+ if(!hMap)
+ {
+ OperatorConsole.printf("***Child: Unable to OpenFileMapping : %d (%s)\n",
+ GetLastError(), argv[valid_argc]);
+ exit(0);
+ }
+
+ IPCBlockPtrInstance = (IPCBlock*)MapViewOfFile(hMap,
+ FILE_MAP_ALL_ACCESS, 0,0, sizeof(IPCBlock));
+ if(!IPCBlockPtrInstance)
+ {
+ OperatorConsole.printf("***Child: Unable to MapViewOfFile : %d\n",
+ GetLastError());
+ }
+ Socketfd = IPCBlockPtrInstance->Socketfd;
+ UnmapViewOfFile(IPCBlockPtrInstance);
+ CloseHandle(hMap);
+
+// UNIX: get the socket# from a small file or pipe
+#else
+#if 0
+ IPCBlock aIPCBlock;
+ ifstream aStream(argv[valid_argc], ios::in | ios::nocreate);
+ if(aStream.good())
+ {
+ aStream.read((unsigned char *)&aIPCBlock, sizeof(aIPCBlock));
+ }
+ if(!aStream.good() || aStream.gcount() != sizeof(aIPCBlock) ||
+ aIPCBlock.Magic != IPCBlockMagic)
+ {
+ // magic # assures safety --
+ // we don't try unlink("/"), for example
+ OperatorConsole.printf("***Child: Unable to read file %s\n",
+ argv[valid_argc]);
+ }
+ else
+ {
+ unlink(argv[valid_argc]);
+ }
+ Socketfd = aIPCBlock.Socketfd;
+#endif
+#endif
+ }
+
+ ++valid_argc;
+ }
+
+ /* check access for logging and saving images */
+
+ if (1)
+ {
+ FILE *f;
+ char Filename[1024];
+ int i;
+
+ f = fopen(TroubleLogFile, "at");
+ if (f) fclose(f);
+ if (!f) OperatorConsole.printf("*** Not enough rights to write to logfiles\n");
+
+ memset(Filename, 0, 1024);
+ GetPhysicalDevice("MAG0", Filename);
+ strcat(Filename, "printer_files");
+ mkdir(Filename);
+ i = strlen(Filename);
+ Filename[i] = PATHSEPCHAR;
+ Filename[i+1] = 0;
+ strcat(Filename, "accesstest.log");
+ f = fopen(Filename, "at");
+ if (f) fclose(f);
+ if (!f) OperatorConsole.printf("*** Not enough rights to write in MAG0\n");
+
+ memset(Filename, 0, 1024);
+ GetPhysicalDevice("MAG0", Filename);
+ strcat(Filename, "incoming");
+ if (dgate_IsDirectory(Filename))
+ {
+ strcat(Filename, "\\");
+ Filename[strlen(Filename)-1] = PATHSEPCHAR;
+ OperatorConsole.printf("Monitoring for files in: %s\n", Filename);
+ strcpy(monitorfolder, Filename);
+ StartMonitorThread(monitorfolder);
+ }
+ }
+
+// prepare to run as a child server thread
+ if(!LoadKFactorFile((char*)KFACTORFILE))
+ {
+ OperatorConsole.printf("***Error loading kfactor file:%s\n", KFACTORFILE);
+ return ( FALSE );
+ }
+
+ if(!InitACRNemaAddressArray())
+ {
+ OperatorConsole.printf("***Error loading acr-nema map file:%s\n",ACRNEMAMAP);
+ return ( FALSE );
+ }
+
+ if(!atoi((char*)Port))
+ return ( Socketfd );
+ if(Valid > 1) // always TRUE !!!!!
+ return ( Socketfd );
+
+ return ( Socketfd );
+ }
+
+/*
+BOOL
+SetString(VR *vr, char *s, int Max)
+ {
+ memset((void*)s, 0, Max);
+ if(vr)
+ if(vr->Data)
+ {
+ memcpy((void*)s, vr->Data, vr->Length%Max);
+ return ( TRUE );
+ }
+ return ( FALSE );
+ }
+*/
+
+class DriverApp
+ {
+ public:
+ virtual BOOL ServerChild ( int ) = 0;
+ public:
+ BOOL ServerChildThread ( int );
+ BOOL Server ( BYTE * );
+ int ChildSocketfd;
+ volatile int Lock;
+ unsigned int ConnectedIP;
+#ifndef __GNUC__
+ DriverApp () { Lock = 0; };
+#else //The GCC way
+ DriverApp ():ChildSocketfd(0), Lock(0) {};
+ virtual ~DriverApp() {};
+#endif
+ };
+
+// Query / Retrieve Engine
+
+class MyPatientRootQuery :
+ public PatientRootQuery
+ {
+ public:
+ BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL QueryResultScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *);
+ BOOL CallBack (DICOMCommandObject *, DICOMDataObject *);
+ int RecordsFound;
+#ifdef __GNUC__
+ MyPatientRootQuery():RecordsFound(0) {};
+#endif
+ };
+
+class MyStudyRootQuery :
+ public StudyRootQuery
+ {
+ public:
+ BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL QueryResultScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *);
+ BOOL CallBack (DICOMCommandObject *, DICOMDataObject *);
+ int RecordsFound;
+#ifdef __GNUC__
+ MyStudyRootQuery():RecordsFound(0) {};
+#endif
+ };
+
+class MyPatientStudyOnlyQuery :
+ public PatientStudyOnlyQuery
+ {
+ public:
+ BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL QueryResultScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *);
+ BOOL CallBack (DICOMCommandObject *, DICOMDataObject *);
+ int RecordsFound;
+#ifdef __GNUC__
+ MyPatientStudyOnlyQuery():RecordsFound(0) {};
+#endif
+ };
+
+
+class MyModalityWorkListQuery :
+ public ModalityWorkListQuery
+ {
+ public:
+ BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL QueryResultScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *);
+ BOOL CallBack (DICOMCommandObject *, DICOMDataObject *);
+ int RecordsFound;
+#ifdef __GNUC__
+ MyModalityWorkListQuery():RecordsFound(0) {};
+#endif
+ };
+
+
+class MyPatientRootRetrieve :
+ public PatientRootRetrieve
+ {
+ RunTimeClassStorage RTCStorage;
+
+ public:
+ BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *);
+ BOOL CallBack (DICOMCommandObject *, DICOMDataObject *);
+ BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **,
+ StandardStorage **);
+ BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE * );
+#ifdef __GNUC__
+ MyPatientRootRetrieve():RTCStorage() {};
+#endif
+ };
+
+class MyPatientRootRetrieveNKI :
+ public PatientRootRetrieveNKI
+ {
+ RunTimeClassStorage RTCStorage;
+
+ public:
+ BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL QueryResultScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *);
+ BOOL CallBack (DICOMCommandObject *, DICOMDataObject *);
+ BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **,
+ StandardStorage **,
+ DICOMCommandObject *,
+ Array < DICOMDataObject *> *,
+ void *);
+ BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE *, BYTE * );
+#ifdef __GNUC__
+ MyPatientRootRetrieveNKI():RTCStorage() {};
+#endif
+ };
+
+class MyPatientRootRetrieveGeneric :
+ public PatientRootRetrieveGeneric
+ {
+ RunTimeClassStorage RTCStorage;
+
+ public:
+ BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *);
+ BOOL CallBack (DICOMCommandObject *, DICOMDataObject *);
+ BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **,
+ StandardStorage **,
+ DICOMCommandObject *,
+ Array < DICOMDataObject *> *,
+ void *);
+ BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE *, BYTE * );
+#ifdef __GNUC__
+ MyPatientRootRetrieveGeneric():RTCStorage() {};
+#endif
+ };
+
+class MyStudyRootRetrieve :
+ public StudyRootRetrieve
+ {
+ RunTimeClassStorage RTCStorage;
+
+ public:
+ BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *);
+ BOOL CallBack (DICOMCommandObject *, DICOMDataObject *);
+ BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **,
+ StandardStorage **);
+ BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE * );
+#ifdef __GNUC__
+ MyStudyRootRetrieve():RTCStorage() {};
+#endif
+ };
+
+class MyStudyRootRetrieveNKI :
+ public StudyRootRetrieveNKI
+ {
+ RunTimeClassStorage RTCStorage;
+
+ public:
+ BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *);
+ BOOL CallBack (DICOMCommandObject *, DICOMDataObject *);
+ BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **,
+ StandardStorage **,
+ DICOMCommandObject *,
+ Array < DICOMDataObject *> *,
+ void *);
+ BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE *, BYTE * );
+#ifdef __GNUC__
+ MyStudyRootRetrieveNKI():RTCStorage() {};
+#endif
+ };
+
+class MyStudyRootRetrieveGeneric :
+ public StudyRootRetrieveGeneric
+ {
+ RunTimeClassStorage RTCStorage;
+
+ public:
+ BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *);
+ BOOL CallBack (DICOMCommandObject *, DICOMDataObject *);
+ BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **,
+ StandardStorage **,
+ DICOMCommandObject *,
+ Array < DICOMDataObject *> *,
+ void *);
+ BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE *, BYTE * );
+#ifdef __GNUC__
+ MyStudyRootRetrieveGeneric():RTCStorage() {};
+#endif
+ };
+
+class MyPatientStudyOnlyRetrieve :
+ public PatientStudyOnlyRetrieve
+ {
+ RunTimeClassStorage RTCStorage;
+
+ public:
+ BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *);
+ BOOL CallBack (DICOMCommandObject *, DICOMDataObject *);
+ BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **,
+ StandardStorage **);
+ BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE * );
+#ifdef __GNUC__
+ MyPatientStudyOnlyRetrieve():RTCStorage() {};
+#endif
+ };
+
+class MyPatientStudyOnlyRetrieveNKI :
+ public PatientStudyOnlyRetrieveNKI
+ {
+ RunTimeClassStorage RTCStorage;
+
+ public:
+ BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *);
+ BOOL CallBack (DICOMCommandObject *, DICOMDataObject *);
+ BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **,
+ StandardStorage **,
+ DICOMCommandObject *,
+ Array < DICOMDataObject *> *,
+ void *);
+ BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE *, BYTE * );
+#ifdef __GNUC__
+ MyPatientStudyOnlyRetrieveNKI():RTCStorage() {};
+#endif
+ };
+
+class MyPatientStudyOnlyRetrieveGeneric :
+ public PatientStudyOnlyRetrieveGeneric
+ {
+ RunTimeClassStorage RTCStorage;
+
+ public:
+ BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO);
+ BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *);
+ BOOL CallBack (DICOMCommandObject *, DICOMDataObject *);
+ BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **,
+ StandardStorage **,
+ DICOMCommandObject *,
+ Array < DICOMDataObject *> *,
+ void *);
+ BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE *, BYTE * );
+#ifdef __GNUC__
+ MyPatientStudyOnlyRetrieveGeneric():RTCStorage() {};
+#endif
+ };
+
+// This class handles storage; used to allow error messages to be sent back to the caller
+
+class MyUnknownStorage : public UnknownStorage
+ {
+ public:
+ Database *DB; // must be set by caller (needs one per thread)
+ BOOL nopreget; // must be set by caller (derived from messageid)
+
+ // called for each incoming DDO
+ UINT16 CheckObject(DICOMDataObject *DDO, PDU_Service *PDU)
+ {
+ char Filename[1024];
+ char Called[20], Calling[20];
+ char *Compression;
+ int rc;
+
+ if (!DB) return 0; // no db set: processing done by caller (failsafe_storage)
+
+#ifdef DEBUG_MODE
+ //OperatorConsole.printf("C-Store (RTC class)\n");
+#endif
+ ImagesReceived++;
+
+ // If the called AE looks like SERVER~j2, then the last 2 characters override IncomingCompression
+ strcpy(Called, (char *)(((AAssociateAC *)PDU)->CalledApTitle));
+ while (Called[strlen(Called)-1]==' ') Called[strlen(Called)-1] = 0;
+
+ strcpy(Calling, (char *)(((AAssociateAC *)PDU)->CallingApTitle));
+ while (Calling[strlen(Calling)-1]==' ') Calling[strlen(Calling)-1] = 0;
+
+ Compression = strchr(Called, '~');
+ if (!Compression) Compression = IncomingCompression; else Compression++;
+
+ // Recompress (e.g., leave as is or decompress) incoming files
+ recompress(&DDO, Compression, "", Compression[0]=='n' || Compression[0]=='N', (ExtendedPDU_Service *)PDU);
+
+ // Virtual compression: save in database, not on disk
+ if (Compression[0]=='v' || Compression[0]=='V')
+ {
+ char rRoot[1024], rFilename[1024];
+ char Device[256];
+
+ FixImage(DDO); // Make sure the required DICOM UID's are there + fix patient ID if enabled
+
+ *rRoot=1;
+ if (!GenerateFileName(DDO, Device, rRoot, rFilename, TRUE, 0, Called, Calling, DB))
+ {
+ OperatorConsole.printf("**** Virtual storage filename problem - %s\n", rFilename);
+ }
+ if (memcmp(rFilename, "lua:", 4)==0) lua_getstring((ExtendedPDU_Service *)PDU, NULL, DDO, rFilename+4, rFilename);
+ if(!SaveToDataBase(*DB, DDO, rFilename, Device, *rRoot))
+ {
+ OperatorConsole.printf("**** Virtual storage db problem - %s\n", rFilename);
+ }
+
+ OperatorConsole.printf("Virtual file: %s\n", rFilename);
+ delete DDO;
+
+ ImagesSaved++;
+ return 0;
+ }
+
+ // NOTE: NOT THREAD SAFE - IF ONE THREAD HANDLES READS AND WRITES THIS OPERATION CAN FAIL DUE TO DB SHARING:
+
+ rc = SaveToDisk(*DB, DDO, Filename, FALSE, (ExtendedPDU_Service *)PDU, 0, nopreget);
+ //delete DDO;
+ //rc = TRUE;
+ //strcpy(Filename, "");
+
+ if(!rc)
+ {
+ //delete DDO;
+ return StorageFailedErrorCode; // Processing failed
+ }
+
+ else
+ {
+ if(strlen(Filename))
+ {
+ if (rc==2) OperatorConsole.printf("Rewritten file: %s\n", Filename);
+ else OperatorConsole.printf("Written file: %s\n", Filename);
+ }
+ ImagesSaved++;
+ return 0;
+ }
+ }
+#ifdef __GNUC__
+ MyUnknownStorage():DB(),nopreget(FALSE) {};
+ private:// This will prevent it from being copied (it has a pointer)
+ MyUnknownStorage(const MyUnknownStorage&);
+ const MyUnknownStorage & operator = (const MyUnknownStorage&);
+#endif
+ };
+
+class StorageApp :
+ public DriverApp
+ {
+ // MyUnknownStorage SOPUnknownStorage;
+ //Verification SOPVerification;
+ //MyPatientRootQuery SOPPatientRootQuery;
+ //MyPatientRootRetrieve SOPPatientRootRetrieve;
+ //MyPatientRootRetrieveNKI SOPPatientRootRetrieveNKI;
+ //MyPatientRootRetrieveGeneric SOPPatientRootRetrieveGeneric;
+
+ //MyStudyRootQuery SOPStudyRootQuery;
+ //MyStudyRootRetrieve SOPStudyRootRetrieve;
+ //MyStudyRootRetrieveNKI SOPStudyRootRetrieveNKI;
+ //MyStudyRootRetrieveGeneric SOPStudyRootRetrieveGeneric;
+
+ //MyPatientStudyOnlyQuery SOPPatientStudyOnlyQuery;
+ //MyPatientStudyOnlyRetrieve SOPPatientStudyOnlyRetrieve;
+ //MyPatientStudyOnlyRetrieveNKI SOPPatientStudyOnlyRetrieveNKI;
+ //MyPatientStudyOnlyRetrieveGeneric SOPPatientStudyOnlyRetrieveGeneric;
+
+ //MyModalityWorkListQuery SOPModalityWorkListQuery;
+ public:
+ BOOL ServerChild ( int );
+ void FailSafeStorage(CheckedPDU_Service *PDU);
+ BOOL PrinterSupport( CheckedPDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *PrintData[]);
+ BOOL StorageCommitmentSupport( CheckedPDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject **CommitData);
+ };
+
+// from dbsql.cpp
+BOOL
+UpdateOrAddToTable(
+ Database &DB,
+ DBENTRY *DCMGateDB,
+ char *TableName,
+ DICOMDataObject *DDOPtr,
+ const char *ObjectFile,
+ const char *DeviceName,
+ char *Patid,
+ char *Modality,
+ BOOL *Added,
+ BOOL JustAdd,
+ BOOL CheckDuplicates);
+
+void KodakFixer(DICOMDataObject *DDOPtr, BOOL tokodak)
+{ VR *vr = DDOPtr->GetVR(0x0010, 0x0020);
+ char patid[11];
+
+ if (!vr) return;
+ if (!vr->Data) return;
+ if (!vr->Length) return;
+ if (vr->Length>8) return;
+
+ memset(patid, 0, 10);
+ memcpy(patid, (char *)(vr->Data), vr->Length);
+ patid[vr->Length]=0;
+ if (patid[vr->Length-1]==' ') patid[vr->Length-1] = 0;
+
+ if (!tokodak && strlen(patid)==8 && patid[0] == '0' && atoi(patid)>1000000 )
+ {
+ vr->ReAlloc(8);
+ patid[8] = ' ';
+ memcpy(vr->Data, patid + 1, 8);
+
+ SystemDebug.printf("Fixed patient ID from kodak, now %s\n", patid+1);
+ }
+
+ if (tokodak && strlen(patid)==7 && patid[0] != '0' && atoi(patid)>1000000 )
+ {
+ vr->ReAlloc(8);
+ ((char *)(vr->Data))[0]='0';
+ memcpy(((char *)(vr->Data))+1, patid, 7);
+
+ //sprintf((char *)(vr->Data), "0%s", patid);
+
+ SystemDebug.printf("Fixed patient ID to kodak, now 0%s\n", patid);
+ }
+ }
+
+
+// compute some sort of CRC as hash key for query
+UINT32 crc_ddo(DICOMObject *DO)
+{ DICOMObject DO2;
+ VR *vr;
+ unsigned int crc=0;
+
+ while((vr=DO->Pop()))
+ { crc += ComputeCRC((char *)vr->Data, vr->Length);
+ crc += 4523 * vr->Group;
+ crc += 1023 * vr->Element;
+ DO2.Push(vr);
+ }
+ DO->Reset();
+ while((vr=DO2.Pop()))
+ { DO->Push(vr);
+ }
+ return crc;
+}
+
+// compare two dicom objects
+BOOL compare_ddo(DICOMObject *DO1, DICOMObject *DO2)
+{ DICOMObject DO10, DO20;
+ VR *vr1, *vr2;
+ BOOL result=TRUE;
+
+ while((vr1=DO1->Pop()))
+ { vr2=DO2->Pop();
+ if (vr2)
+ { if (vr1->Length != vr2->Length || vr1->Group != vr2->Group || vr1->Element != vr2->Element) result = FALSE;
+ else
+ { if (vr1->Length)
+ if (memcmp(vr1->Data, vr2->Data, vr1->Length)!=0) result = FALSE;
+ }
+ DO20.Push(vr2);
+ }
+ DO10.Push(vr1);
+ }
+ while((vr2=DO2->Pop()))
+ { DO20.Push(vr2);
+ result = FALSE;
+ }
+
+ DO1->Reset();
+ while((vr1=DO10.Pop()))
+ { DO1->Push(vr1);
+ }
+ DO2->Reset();
+ while((vr1=DO20.Pop()))
+ { DO2->Push(vr1);
+ }
+ return result;
+}
+
+// strip meta information group 2 from a dicom object
+static void dgateStrip2(DICOMDataObject *pDDO)
+{ DICOMObject DO2;
+ VR *vr;
+
+ while((vr=pDDO->Pop()))
+ { if (vr->Group==2) delete vr;
+ else DO2.Push(vr);
+ }
+
+ pDDO->Reset();
+ while((vr=DO2.Pop())) pDDO->Push(vr);
+}
+
+// cached virtual query: use in place of 3 calls to VirtualQuery(DDOPtr, Level, i, ADDO)
+// use e.g., VirtualServerFor0 = AE,CACHESERIES or AE,CACHESTUDIES
+int VirtualQueryCached(DICOMDataObject *DDO, const char *Level, int N, Array < DICOMDataObject *> *pADDO)
+{ BOOL cache = FALSE, cacheseries = TRUE, nonvirtual=FALSE;
+ int rc;
+
+ // if ImageType in query change cache name
+ char ImageType[128];
+ ImageType[0]=0;
+ VR *vr = DDO->GetVR(0x0008, 0x0008);
+ if (vr && vr->Length)
+ { strncpy(ImageType, (char*)vr->Data, vr->Length);
+ ImageType[vr->Length] = 0;
+ if (ImageType[vr->Length-1]==' ') ImageType[vr->Length-1]=0;
+ }
+
+ if (*VirtualServerFor[N]==0) return 0;
+ if (strstr(VirtualServerFor[N], ",CACHE")) cache = TRUE;
+ if (strstr(VirtualServerFor[N], ",CACHESTUDIES")) cacheseries = FALSE;
+ if (strstr(VirtualServerFor[N], ",NONVIRTUAL")) nonvirtual = TRUE;
+
+ if (!cache)
+ { int save = DDO->GetUINT16(0x9999, 0x0802);
+ if (nonvirtual) DDO->ChangeVR(0x9999, 0x0802, (UINT16) 0x8000, 0);
+ rc = VirtualQuery(DDO, Level, N, pADDO);
+ if (nonvirtual) DDO->ChangeVR(0x9999, 0x0802, (UINT16) save, 0);
+ return rc;
+ }
+
+ VR *vpat = DDO->GetVR(0x0010, 0x0020);
+ VR *vstu = DDO->GetVR(0x0020, 0x000d);
+ VR *vser = DDO->GetVR(0x0020, 0x000e);
+ VR *vsop = DDO->GetVR(0x0008, 0x0018);
+
+ int lpat=0, lstu=0, lser=0, lsop=0;
+ if (vpat) lpat = vpat->Length;
+ if (vstu) lstu = vstu->Length;
+ if (vser) lser = vser->Length;
+ if (vsop) lsop = vsop->Length;
+
+ // do not cache wildcard patient ID searches
+ if (lpat) if (memchr(vpat->Data, '*', vpat->Length)) lpat=0;
+
+ // only cache IMAGE queries at {series,} study and patient level (pat or study {or series} fully specified)
+ if (memcmp(Level, "IMAGE", 5)==0 && lsop==0 && (lpat!=0 || lstu!=0 || (lser!=0 && cacheseries)))
+ { // VR *vr;
+ Array < DICOMDataObject *> Series;
+ char today[70];
+ struct tm tmbuf1;
+
+ time_t now = time(NULL);
+ localtime_r(&now, &tmbuf1);
+ sprintf(today, "%04d%02d%02d", tmbuf1.tm_year+1900, tmbuf1.tm_mon, tmbuf1.tm_mday);
+
+ // Edit query down to series/study level to ask for #images per series/study
+ DICOMDataObject *DDO2 = MakeCopy(DDO);
+ dgateStrip2(DDO2);
+ DDO2->ChangeVR(0x0008, 0x0020+(int)cacheseries, "", 'DA', TRUE); // series/study date
+ if (cacheseries) DDO2->ChangeVR(0x0008, 0x0052, "SERIES", 'CS', TRUE); // level
+ else DDO2->ChangeVR(0x0008, 0x0052, "STUDY" , 'CS', TRUE); // level
+ if (lstu==0) DDO2->ChangeVR(0x0020, 0x000d, "", 'UI', FALSE); // studyuid
+ if (lser==0 && cacheseries) DDO2->ChangeVR(0x0020, 0x000e, "", 'UI', FALSE); // seriesuid
+ DDO2->ChangeVR(0x0020, 0x1208+(int)cacheseries, "", 'IS', TRUE); // numberofseries/studyrelatedinstances
+ if (nonvirtual) DDO2->ChangeVR(0x9999, 0x0802, (UINT16) 0x8000, 0);
+
+ if (cacheseries) VirtualQuery(DDO2, "SERIES", N, &Series);
+ else VirtualQuery(DDO2, "STUDY", N, &Series);
+ delete DDO2;
+
+ // perform sub-query per series/study and combine results
+ for (unsigned int i=0; i<Series.GetSize(); i++)
+ { char studuid[70], seruid[70], num[70], pat[70], date[70];
+
+ SearchDICOMObject(Series[i], "0010,0020", pat);
+ if (*pat==0) strcpy(pat, "unknown");
+ SearchDICOMObject(Series[i], "0020,000d", studuid);
+ SearchDICOMObject(Series[i], "0020,000e", seruid);
+
+ if (cacheseries) SearchDICOMObject(Series[i], "0020,1209", num);
+ else SearchDICOMObject(Series[i], "0020,1208", num);
+ if (cacheseries) SearchDICOMObject(Series[i], "0008,0021", date);
+ else SearchDICOMObject(Series[i], "0008,0020", date);
+ if (*date==0) strcpy(date, "00000000");
+
+ DDO2 = MakeCopy(DDO);
+ dgateStrip2(DDO2);
+ DDO2->ChangeVR(0x0020, 0x000d, studuid, 'UI', FALSE);
+ if (cacheseries) DDO2->ChangeVR(0x0020, 0x000e, seruid, 'UI', FALSE);
+ if (nonvirtual) DDO2->ChangeVR(0x9999, 0x0802, (UINT16) 0x8000, 0);
+
+ // still do small queries and those related to today
+ if (atoi(num)<1 || strcmp(today, date)==0)
+ { if (atoi(num)<1) SystemDebug.printf("VirtualQueryCached: %s does not provide computed fields - cannot cache\n,", VirtualServerFor[N]);
+ VirtualQuery(DDO2, Level, N, pADDO);
+ }
+ else
+ { char Filename[1024], s[1024], *p;
+ VR *vr1;
+ BOOL hit;
+ int devlen;
+
+ // key for hash based searching of query (collisions will force re-query)
+ UINT32 crc = atoi(num) * (crc_ddo(DDO2) + 41 + 6*(int)cacheseries) +
+ ComputeCRC(VirtualServerFor[N], strlen(VirtualServerFor[N]));
+ // new query type needs other cache entry
+ if (ImageType[0]) crc += 273;
+
+ // filename of stored query
+ memset(Filename, 0, 1024);
+ GetPhysicalDevice("MAG0", Filename);
+ devlen = strlen(Filename);
+ strcat(Filename, "printer_files\\");
+ p = Filename + strlen(Filename);
+ sprintf(p, "querycache\\%4.4s\\%4.4s\\%08x.query.dcm", date, date+4, crc);
+
+ // was the same query stored previously ?
+ hit = FALSE;
+ if (DFileExists(Filename))
+ { DICOMDataObject *DO2 = LoadForGUI(Filename);
+ if (DO2)
+ { dgateStrip2(DO2);
+ if (compare_ddo(DDO2, DO2))
+ hit = TRUE;
+ }
+ }
+
+ // if so, load the result from disk
+ if (hit)
+ { sprintf(p, "querycache\\%4.4s\\%4.4s\\%08x.result.dcm", date, date+4, crc);
+ DICOMDataObject *DO = LoadForGUI(Filename);
+ if (DO)
+ { vr1 = DO->GetVR(0x9999, 0x1000);
+ Array < DICOMDataObject * > *ADDOread =
+ (Array<DICOMDataObject*>*) vr1->SQObjectArray;
+ if (ADDOread)
+ { for (unsigned int j=0; j<ADDOread->GetSize(); j++)
+ pADDO->Add(ADDOread->Get(j));
+ SystemDebug.printf("VirtualQueryCached: read %d cache records for %s:%s/%s from %s\n",
+ ADDOread->GetSize(), pat, studuid, seruid, Filename);
+ }
+ else
+ hit = FALSE;
+ }
+ else
+ hit = FALSE;
+ }
+
+ // if not, perform the query and store the query and its result on disk
+ if (!hit)
+ { int N1 = pADDO->GetSize();
+ VirtualQuery(DDO2, Level, N, pADDO);
+ int M1 = pADDO->GetSize();
+ sprintf(p, "querycache\\%4.4s\\%4.4s\\%08x.query.dcm", date, date+4, crc);
+ for (unsigned int sIndex = devlen; sIndex<=strlen(Filename); sIndex++)
+ if (Filename[sIndex]==PATHSEPCHAR)
+ { strcpy(s, Filename);
+ s[sIndex]='\0';
+ mkdir(s);
+ }
+ SaveDICOMDataObject(Filename, DDO2); // destroys DDO2!
+
+ // transfer ADDO N1..M1 into sequence to be stored
+ vr1 = new VR(0x9999, 0x1000, 0, (void *)NULL, FALSE);
+ Array < DICOMDataObject * > *SQE = new Array < DICOMDataObject * >;
+ for (int j=N1; j<M1; j++)
+ { DICOMDataObject *dd = MakeCopy(pADDO->Get(j));
+ SQE->Add(dd);
+ }
+ vr1->SQObjectArray = (void*) SQE;
+
+ DICOMDataObject *D = new DICOMDataObject;
+ D->Push(vr1);
+ sprintf(p, "querycache\\%4.4s\\%4.4s\\%08x.result.dcm", date, date+4, crc);
+ SaveDICOMDataObject(Filename, D);
+ SystemDebug.printf("VirtualQueryCached: stored %d cache records for %s:%s/%s in %s\n",
+ M1-N1, pat, studuid, seruid, Filename);
+ }
+ }
+ delete DDO2;
+ delete Series[i];
+ }
+ return TRUE;
+ }
+ else
+ { int save = DDO->GetUINT16(0x9999, 0x0802);
+ if (nonvirtual) DDO->ChangeVR(0x9999, 0x0802, (UINT16) 0x8000, 0);
+ rc = VirtualQuery(DDO, Level, N, pADDO);
+ if (nonvirtual) DDO->ChangeVR(0x9999, 0x0802, (UINT16) save, 0);
+ return rc;
+ }
+}
+
+int VirtualQuery(DICOMDataObject *DDO, const char *Level, int N, Array < DICOMDataObject *> *pADDO, char *ae)
+ {
+ char AE[48];
+ strcpy(AE, VirtualServerFor[N]);
+ if (ae) strcpy(AE, ae);
+ if (*AE==0) return FALSE;
+
+ char *param = strchr(AE, ',');
+ if (param) *param++ = 0;
+
+ unsigned char ip[64], port[64], compress[64], SOP[66];
+ VR *vr;
+ UID uid;
+ DICOMCommandObject DCO, DCOR;
+ DICOMDataObject DDOR;
+ LE_UINT16 command, datasettype, messageid, priority;
+ DICOMDataObject *DDOPtr, *DDOPtr2;
+ DBENTRY *DBE;
+ int Index, level, count=0;
+
+ level=0;
+ if (strncmp(Level, "PATIENT", 7)==0) level=1;
+ else if (strncmp(Level, "STUDY", 5)==0) level=2;
+ else if (strncmp(Level, "SERIES", 6)==0) level=3;
+ else if (strncmp(Level, "IMAGE", 5)==0) level=4;
+ else if (strncmp(Level, "WORKLIST",8)==0) level=5;
+
+ ExtendedPDU_Service PDU;
+ PDU.AttachRTC(&VRType);
+
+ if(!GetACRNema(AE, (char *)ip, (char *)port, (char *)compress))
+ return 0;
+
+ // 20070103
+ if (param)
+ if (strstr(param, "FIXKODAK") || strstr(param, "fixkodak")) // disallow wildcard date queries
+ {
+ BOOL flag;
+ vr = DDO->GetVR(0x0010, 0x0030); // birthdate
+ flag = (vr && vr->Length>0 && *(char *)vr->Data == '*');
+ vr = DDO->GetVR(0x0008, 0x0020); // study date
+ flag = flag || (vr && vr->Length>0 && *(char *)vr->Data == '*');
+ vr = DDO->GetVR(0x0008, 0x0021); // series date
+ flag = flag || (vr && vr->Length>0 && *(char *)vr->Data == '*');
+ vr = DDO->GetVR(0x0008, 0x0022); // acq date
+ flag = flag || (vr && vr->Length>0 && *(char *)vr->Data == '*');
+ vr = DDO->GetVR(0x0008, 0x0023); // img date
+ flag = flag || (vr && vr->Length>0 && *(char *)vr->Data == '*');
+
+ if (!FixKodak)
+ {
+ OperatorConsole.printf("*** Virtual query - FIXKODAK is set for server %s but FixKodak is not set in dicom.ini\n", AE);
+ }
+
+ if (flag)
+ {
+ OperatorConsole.printf("Virtual query - blocked wildcard date query to %s\n", AE);
+ return 0;
+ }
+ }
+
+
+ // Start setting up connection for C-FIND
+ PDU.ClearAbstractSyntaxs();
+ PDU.SetLocalAddress(MYACRNEMA);
+ PDU.SetRemoteAddress((unsigned char *)AE);
+
+ uid.Set("1.2.840.10008.3.1.1.1"); // Application context (DICOM App)
+ PDU.SetApplicationContext(uid);
+
+ if (level==1) uid.Set("1.2.840.10008.5.1.4.1.2.1.1"); // PatientRootQuery
+ else if (level==5) uid.Set("1.2.840.10008.5.1.4.31"); // WorkListQuery
+ else uid.Set("1.2.840.10008.5.1.4.1.2.2.1"); // StudyRootQuery
+ PDU.AddAbstractSyntax(uid);
+
+ PDU.SetTimeOut(TCPIPTimeOut);
+
+ // Make the association for the FIND on port/ip
+ if(!PDU.Connect(ip, port))
+ {
+ OperatorConsole.printf("*** Virtual query - failed to connect for C-FIND to %s\n", AE);
+ return ( 0 );
+ }
+
+
+ // Start a Patient/StudyRootQuery
+
+ if (level==1) strcpy((char*) SOP, "1.2.840.10008.5.1.4.1.2.1.1"); // PatientRootQuery
+ else if (level==5) strcpy((char*) SOP, "1.2.840.10008.5.1.4.31"); // WorklistQuery
+ else strcpy((char*) SOP, "1.2.840.10008.5.1.4.1.2.2.1"); // StudyRootQuery
+ vr = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE);
+ DCO.Push(vr);
+ command = 0x0020;
+ vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE);
+ DCO.Push(vr);
+ priority = 0; // MEDIUM
+ vr = new VR (0x0000, 0x0700, 0x0002, &priority, FALSE);
+ DCO.Push(vr);
+ datasettype = 0x0102;
+ vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE);
+ DCO.Push(vr);
+ messageid = 0x0003;
+ vr = new VR (0x0000, 0x0110, 0x0002, &messageid, FALSE);
+ DCO.Push(vr);
+
+ DDOPtr = MakeCopy(DDO);
+ DDOPtr2 = MakeCopy(DDO);
+
+ // Use passed data object and Level for query
+
+ DDOPtr->ChangeVR(0x0008, 0x0052, Level, 'CS', TRUE);
+
+ vr = DDOPtr->GetVR(0x0002, 0x0010); // delete transfer syntax
+ if (vr) DDOPtr->DeleteVR(vr);
+
+ // Here fixkodak fiximage should operate adding 0 to e.g., 9901234 patient ID
+ if (param)
+ if (strstr(param, "FIXKODAK") || strstr(param, "fixkodak"))
+ KodakFixer(DDOPtr, TRUE);
+ CallImportConverterN(DDOPtr, 2300, NULL, NULL, NULL, NULL, &PDU, NULL, NULL);
+
+ MyPatientRootQuery mq;
+ MyStudyRootQuery sq;
+ MyModalityWorkListQuery wq;
+ unsigned int s=pADDO->GetSize();
+
+ // ImageType in query needed for IMAGETYPEFIX below
+ char ImageType[128];
+ ImageType[0]=0;
+ vr = DDOPtr->GetVR(0x0008, 0x0008);
+ if (vr && vr->Length)
+ {
+ strncpy(ImageType, (char*)vr->Data, vr->Length);
+ ImageType[vr->Length] = 0;
+ if (ImageType[vr->Length-1]==' ') ImageType[vr->Length-1]=0;
+ }
+
+ // EchoNumbers in query needed for IMAGETYPEFIX below
+ char EchoNumbers[128];
+ EchoNumbers[0]=0;
+ vr = DDOPtr->GetVR(0x0018, 0x0068);
+ if (vr && vr->Length)
+ {
+ strncpy(EchoNumbers, (char*)vr->Data, vr->Length);
+ EchoNumbers[vr->Length] = 0;
+ if (EchoNumbers[vr->Length-1]==' ') EchoNumbers[vr->Length-1]=0;
+ }
+
+ // forward query
+ if (level==1) mq.Write(&PDU, DDOPtr, pADDO);
+ else if (level==5) wq.Write(&PDU, DDOPtr, pADDO);
+ else sq.Write(&PDU, DDOPtr, pADDO);
+
+ PDU.Close();
+
+ // anything recieved ?
+ if (pADDO->GetSize() != s)
+ {
+ DBENTRY *dum;
+ int el[1000], gr[1000], count1, j, count2;
+ unsigned int i;
+ BOOL us[1000];
+ DICOMDataObject DO2;
+
+ if (DebugLevel>=3)
+ {
+ SystemDebug.printf("Virtual query: first response from %s (total %d records)\n", AE, pADDO->GetSize() - s);
+ NonDestructiveDumpDICOMObject(pADDO->Get(s));
+
+ //for(int i=s; i<pADDO->GetSize(); i++)
+ // NonDestructiveDumpDICOMObject(pADDO->Get(s));
+ }
+
+ // build list of valid response vr's: those in query AND in our database at correct level
+ // Our database model is used because the virtual server mimics ours with data from elsewhere
+
+ count1=0;
+ while ((vr = DDOPtr2->Pop()))
+ {
+ if (level==0)
+ {
+ if (VerifyIsInDBE(vr, WorkListDB, dum))
+ {
+ us[count1 ] = FALSE;
+ el[count1 ] = vr->Element;
+ gr[count1++] = vr->Group;
+ delete vr;
+ continue;
+ }
+ }
+ if (level>=1)
+ {
+ if (VerifyIsInDBE(vr, PatientDB, dum) || (vr->Group==0x0020 && vr->Element==0x1200) || (vr->Group==0x0020 && vr->Element==0x1202) || (vr->Group==0x0020 && vr->Element==0x1204))
+ {
+ us[count1 ] = FALSE;
+ el[count1 ] = vr->Element;
+ gr[count1++] = vr->Group;
+ delete vr;
+ continue;
+ }
+ }
+ if (level>=2)
+ {
+ if (VerifyIsInDBE(vr, StudyDB, dum) || (vr->Group==0x0020 && vr->Element==0x1208) || (vr->Group==0x0020 && vr->Element==0x1206))
+ {
+ us[count1 ] = FALSE;
+ el[count1 ] = vr->Element;
+ gr[count1++] = vr->Group;
+ delete vr;
+ continue;
+ }
+ }
+ if (level>=3)
+ {
+ if (VerifyIsInDBE(vr, SeriesDB, dum) || (vr->Group==0x0020 && vr->Element==0x1209))
+ {
+ us[count1 ] = FALSE;
+ el[count1 ] = vr->Element;
+ gr[count1++] = vr->Group;
+ delete vr;
+ continue;
+ }
+ }
+ if (level>=4)
+ {
+ if (VerifyIsInDBE(vr, ImageDB, dum))
+ {
+ us[count1 ] = FALSE;
+ el[count1 ] = vr->Element;
+ gr[count1++] = vr->Group;
+ delete vr;
+ continue;
+ }
+ }
+ if (level>=5)
+ {
+ if (VerifyIsInDBE(vr, WorkListDB, dum))
+ {
+ us[count1 ] = FALSE;
+ el[count1 ] = vr->Element;
+ gr[count1++] = vr->Group;
+ delete vr;
+ continue;
+ }
+ }
+ delete vr;
+ }
+
+ count2=0; // counts valid fields during first record
+
+ SystemDebug.printf("Virtualquery: processing response from server: %s\n", AE);
+ for (i=s; i<pADDO->GetSize(); i++)
+ {
+ if (i==s+1 && count2==count1) // after one record: all fields were valid
+ break;
+
+ if (i==s+1 && count2!=count1)
+ SystemDebug.printf("Virtualquery: cleaning response from server: %s %d %d\n", AE, count2, count1);
+
+ while((vr=pADDO->Get(i)->Pop()))
+ {
+ for (j=0; j<count1; j++)
+ {
+ if (0x0052==vr->Element && 0x0008==vr->Group)
+ {
+ delete vr;
+ break; // auto generated - no need to copy
+ }
+
+ if (0x0000==vr->Element)
+ {
+ delete vr;
+ break; // auto generated - no need to copy
+ }
+
+ if (el[j]==vr->Element && gr[j]==vr->Group)
+ { // copy valid fields
+ DO2.Push(vr);
+ us[j] = TRUE;
+ count2++;
+ break;
+ }
+
+ if (j==count1-1)
+ {
+ count2=-10000; // superfluous fields: cleanup always required
+ delete vr;
+ }
+ }
+ }
+
+ for (j=0; j<count1; j++) // insert empties for missing fields
+ {
+ if (!us[j])
+ {
+ vr = new VR(gr[j], el[j], 0, FALSE);
+ DO2.Push(vr);
+ }
+ else
+ us[j]=FALSE;
+ }
+
+ pADDO->Get(i)->Reset();
+ while((vr=DO2.Pop()))
+ pADDO->Get(i)->Push(vr);
+
+ DO2.Reset();
+ }
+
+ // Here fixkodak operates stripping 0 to e.g., 09901234 patient ID
+ if (param)
+ if (strstr(param, "FIXKODAK") || strstr(param, "fixkodak"))
+ for (i=s; i<pADDO->GetSize(); i++)
+ KodakFixer(pADDO->Get(i), FALSE);
+ for (i=s; i<pADDO->GetSize(); i++)
+ CallImportConverterN(pADDO->Get(i), 2400, NULL, NULL, NULL, NULL, &PDU, NULL, NULL);
+
+ // Here IMAGETYPEFIX filters results that do not match the queried ImageType
+ if (ImageType[0] && param && strstr(param, "IMAGETYPEFIX"))
+ {
+ int count=0;
+ for (i=pADDO->GetSize()-1; i!=((unsigned int)-1); i--)
+ {
+ BOOL pass=TRUE;
+ vr = pADDO->Get(i)->GetVR(0x0008, 0x0008);
+ if (vr && vr->Length)
+ {
+ char it[256];
+ char *p=it+1;
+ strcpy(it, "\\");
+ strncpy(p, (char*) vr->Data, vr->Length);
+ p[vr->Length]=0;
+ if (p[vr->Length-1]==' ') p[vr->Length-1]=0;
+ strcat(it, "\\");
+ char *q = strstr(it, ImageType);
+ if (!q)
+ pass = FALSE;
+ else if (q[-1]!='\\' || q[strlen(ImageType)]!='\\')
+ pass = FALSE;
+ }
+ vr = pADDO->Get(i)->GetVR(0x0018, 0x0068);
+ if (vr && vr->Length)
+ {
+ char en[256];
+ char *p=en+1;
+ strcpy(en, "\\");
+ strncpy(p, (char*) vr->Data, vr->Length);
+ p[vr->Length]=0;
+ if (p[vr->Length-1]==' ') p[vr->Length-1]=0;
+ strcat(en, "\\");
+ char *q = strstr(en, EchoNumbers);
+ if (!q)
+ pass = FALSE;
+ else if (q[-1]!='\\' || q[strlen(EchoNumbers)]!='\\')
+ pass = FALSE;
+ }
+ if (!pass)
+ {
+ while((vr = pADDO->Get(i)->Pop()))
+ delete vr;
+ delete pADDO->Get(i);
+ pADDO->RemoveAt (i);
+ count++;
+ }
+ }
+ if (count)
+ OperatorConsole.printf("IMAGETYPEFIX removed %d incorrect query results\n", count);
+ }
+ }
+ else
+ while ((vr = DDOPtr2->Pop()))
+ delete vr;
+
+ delete DDOPtr2;
+ delete DDOPtr;
+
+ return pADDO->GetSize() - s;
+ }
+
+int VirtualQueryToDB(DICOMDataObject *DDO, int N, char *ae=NULL)
+ {
+ char AE[48];
+ strcpy(AE, VirtualServerFor[N]);
+ if (ae) strcpy(AE, ae);
+ if (*AE==0) return FALSE;
+
+ char *param = strchr(AE, ',');
+ if (param) *param++ = 0;
+
+ char rRoot[1024], rFilename[1024], ID[66];
+ VR *vr;
+ BOOL quit;
+ Database DB;
+ char Device[256];
+ DICOMDataObject *DDOPtr;
+ DBENTRY *DBE;
+ int Index, count=0;
+
+ ExtendedPDU_Service PDU;
+ PDU.AttachRTC(&VRType);
+
+ // 20070103
+ if (param)
+ if (strstr(param, "FIXKODAK") || strstr(param, "fixkodak")) // disallow wildcard date queries
+ {
+ BOOL flag;
+ vr = DDO->GetVR(0x0010, 0x0030); // birthdate
+ flag = (vr && vr->Length>0 && *(char *)vr->Data == '*');
+ vr = DDO->GetVR(0x0008, 0x0020); // study date
+ flag = flag || (vr && vr->Length>0 && *(char *)vr->Data == '*');
+ vr = DDO->GetVR(0x0008, 0x0021); // series date
+ flag = flag || (vr && vr->Length>0 && *(char *)vr->Data == '*');
+ vr = DDO->GetVR(0x0008, 0x0022); // acq date
+ flag = flag || (vr && vr->Length>0 && *(char *)vr->Data == '*');
+ vr = DDO->GetVR(0x0008, 0x0023); // img date
+ flag = flag || (vr && vr->Length>0 && *(char *)vr->Data == '*');
+
+ if (!FixKodak)
+ {
+ OperatorConsole.printf("*** Virtual query to db - FIXKODAK is set for server %s but FixKodak is not set in dicom.ini\n", AE);
+ }
+
+ if (flag)
+ {
+ OperatorConsole.printf("Virtual query to db - blocked wildcard date query to %s\n", AE);
+ return 0;
+ }
+ }
+
+ DDOPtr = MakeCopy(DDO);
+
+ // Use passed data object and Level for query
+
+ DDOPtr->ChangeVR(0x0008, 0x0052, "IMAGE", 'CS', TRUE);
+
+ vr = DDOPtr->GetVR(0x0002, 0x0010); // delete transfer syntax
+ if (vr) DDOPtr->DeleteVR(vr);
+
+ // Here fixkodak fiximage should operate adding 0 to e.g., 9901234 patient ID
+ if (param)
+ if (strstr(param, "FIXKODAK") || strstr(param, "fixkodak"))
+ KodakFixer(DDOPtr, TRUE);
+ CallImportConverterN(DDOPtr, 2300, NULL, NULL, NULL, NULL, &PDU, NULL, NULL);
+
+ Index = 0; DBE = StudyDB;
+ while ( TRUE ) // study, series and image query
+ {
+ if(!DBE[Index].Element) break;
+ if (DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element)) {++Index; continue; }
+ SetStringVR(&vr, DBE[Index].Group, DBE[Index].Element, "");
+ DDOPtr->Push(vr);
+ ++Index;
+ }
+ Index = 0; DBE = SeriesDB;
+ while ( TRUE ) // series and image query
+ {
+ if(!DBE[Index].Element) break;
+ if (DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element)) {++Index; continue; }
+ SetStringVR(&vr, DBE[Index].Group, DBE[Index].Element, "");
+ DDOPtr->Push(vr);
+ ++Index;
+ }
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ))
+ {
+ OperatorConsole.printf("**** Virtualquery: failed to connect to database: %s\n", AE);
+ return 0;
+ }
+
+ char ImageType[128];
+ ImageType[0]=0;
+
+ Index = 0; DBE = ImageDB;
+ vr = DDOPtr->GetVR(0x0008, 0x0008);
+ if (vr && vr->Length)
+ {
+ strncpy(ImageType, (char*)vr->Data, vr->Length);
+ ImageType[vr->Length] = 0;
+ if (ImageType[vr->Length-1]==' ') ImageType[vr->Length-1]=0;
+
+ // mvh 20120914: a move with an imagetype of e.g. original\phasemap
+ // will match original OR phase; this is typically not intended
+ // for now extract third item and assume it is intended
+ // to be differentiating, note that against conquest this
+ // only works if DT_MSTR is defined in dicom.sql for ImageType
+ // Enable this option by adding virtualserver parameter IMAGETYPEFIX3
+
+ if (param && strstr(param, "IMAGETYPEFIX3"))
+ {
+ char tmp[128];
+ strcpy(tmp, ImageType);
+ char *p = strchr(tmp, '\\'); // p = \primary
+ if (p) p = strchr(p+1, '\\'); // p = \phasemap
+ if (p)
+ {
+ char *q = strchr(p+1, '\\'); // end of 3rd section
+ if (q) *q=0;
+ SetStringVR(&vr, 0x0008, 0x0008, p+1);
+ strcpy(ImageType, p+1);
+ }
+ }
+ }
+
+ while ( TRUE )
+ {
+ if(!DBE[Index].Element) break;
+
+ if (DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element)) {++Index; continue; }
+ SetStringVR(&vr, DBE[Index].Group, DBE[Index].Element, "");
+ DDOPtr->Push(vr);
+ ++Index;
+ }
+
+ // Here fixkodak fiximage should operate adding 0 to e.g., 9901234 patient ID
+ if (param)
+ if (strstr(param, "FIXKODAK") || strstr(param, "fixkodak"))
+ KodakFixer(DDOPtr, TRUE);
+ CallImportConverterN(DDOPtr, 2300, NULL, NULL, NULL, NULL, &PDU, NULL, NULL);
+
+ // Do the Query
+
+ Array < DICOMDataObject *> BDDO;
+ DICOMDataObject *DDOR2;
+ VirtualQueryCached(DDOPtr, "IMAGE", N, &BDDO);
+
+ for (int i=0; i<BDDO.GetSize(); i++)
+ {
+ DDOR2 = BDDO.Get(i);
+
+ // full db add
+ FixImage(DDOR2); // Make sure the required DICOM UID's are there + fix patient ID if enabled
+
+ *rRoot=1;
+ *rFilename=0;
+ if (!GenerateFileName(DDOR2, Device, rRoot, rFilename, TRUE, 0, (char *)MYACRNEMA, (char *)AE, &DB))
+ OperatorConsole.printf("**** Virtual query (%s) filename problem - %s\n", AE, rFilename);
+ if (memcmp(rFilename, "lua:", 4)==0) lua_getstring(&PDU, NULL, DDOR2, rFilename+4, rFilename);
+ if (*rRoot) // keeps set if image is not on server
+ {
+ if (strchr(Device, '.')==NULL)
+ sprintf(Device+strlen(Device), ".%d", N); // set virtual device # (keep lowest)
+ if(!SaveToDataBase(DB, DDOR2, rFilename, Device, TRUE))
+ OperatorConsole.printf("**** Virtual query db problem - %s\n", rFilename);
+ else
+ {
+ SystemDebug.printf("Virtual query (%s) added - %s\n", AE, rFilename);
+ count++;
+ }
+ }
+ while((vr = DDOR2->Pop()))
+ delete vr;
+ }
+
+ while ((vr = DDOPtr->Pop()))
+ delete vr;
+ delete DDOPtr;
+ return count;
+ }
+
+// sort functions used by RemoveQueryDuplicates
+
+static int SortPatient(const void* pElem1, const void* pElem2)
+ {
+ VR *vr1, *vr2;
+ DICOMDataObject *ddo1= *(DICOMDataObject **) pElem1;
+ DICOMDataObject *ddo2= *(DICOMDataObject **) pElem2;
+
+ vr1 = ddo1->GetVR(0x0010, 0x0020);
+ vr2 = ddo2->GetVR(0x0010, 0x0020);
+
+ if (vr1==NULL || vr2==NULL)
+ return 0;
+ if (vr1->Length < vr2->Length)
+ return -1;
+ if (vr1->Length > vr2->Length)
+ return 1;
+ if (vr1->Length==0)
+ return 0;
+ return memicmp((char *)vr1->Data, (char *)vr2->Data, vr1->Length);
+ }
+
+static int SortStudy(const void* pElem1, const void* pElem2)
+ {
+ VR *vr1, *vr2;
+ DICOMDataObject *ddo1= *(DICOMDataObject **) pElem1;
+ DICOMDataObject *ddo2= *(DICOMDataObject **) pElem2;
+
+ vr1 = ddo1->GetVR(0x0020, 0x000d);
+ vr2 = ddo2->GetVR(0x0020, 0x000d);
+
+ if (vr1==NULL || vr2==NULL)
+ return 0;
+ if (vr1->Length < vr2->Length)
+ return -1;
+ if (vr1->Length > vr2->Length)
+ return 1;
+ if (vr1->Length==0)
+ return 0;
+ return memicmp((char *)vr1->Data, (char *)vr2->Data, vr1->Length);
+ }
+
+static int SortSeries(const void* pElem1, const void* pElem2)
+ {
+ VR *vr1, *vr2;
+ DICOMDataObject *ddo1= *(DICOMDataObject **) pElem1;
+ DICOMDataObject *ddo2= *(DICOMDataObject **) pElem2;
+
+ vr1 = ddo1->GetVR(0x0020, 0x000e);
+ vr2 = ddo2->GetVR(0x0020, 0x000e);
+
+ if (vr1==NULL || vr2==NULL)
+ return 0;
+ if (vr1->Length < vr2->Length)
+ return -1;
+ if (vr1->Length > vr2->Length)
+ return 1;
+ if (vr1->Length==0)
+ return 0;
+ return memicmp((char *)vr1->Data, (char *)vr2->Data, vr1->Length);
+ }
+
+static int SortImages(const void* pElem1, const void* pElem2)
+ {
+ VR *vr1, *vr2;
+ DICOMDataObject *ddo1= *(DICOMDataObject **) pElem1;
+ DICOMDataObject *ddo2= *(DICOMDataObject **) pElem2;
+
+ vr1 = ddo1->GetVR(0x0008, 0x0018);
+ vr2 = ddo2->GetVR(0x0008, 0x0018);
+
+ if (vr1==NULL || vr2==NULL)
+ return 0;
+ if (vr1->Length < vr2->Length)
+ return -1;
+ if (vr1->Length > vr2->Length)
+ return 1;
+ if (vr1->Length==0)
+ return 0;
+ return memicmp((char *)vr1->Data, (char *)vr2->Data, vr1->Length);
+ }
+
+static int SortAccession(const void* pElem1, const void* pElem2)
+ {
+ VR *vr1, *vr2;
+ DICOMDataObject *ddo1= *(DICOMDataObject **) pElem1;
+ DICOMDataObject *ddo2= *(DICOMDataObject **) pElem2;
+
+ vr1 = ddo1->GetVR(0x0008, 0x0050);
+ vr2 = ddo2->GetVR(0x0008, 0x0050);
+
+ if (vr1==NULL || vr2==NULL)
+ return 0;
+ if (vr1->Length < vr2->Length)
+ return -1;
+ if (vr1->Length > vr2->Length)
+ return 1;
+ if (vr1->Length==0)
+ return 0;
+ return memicmp((char *)vr1->Data, (char *)vr2->Data, vr1->Length);
+ }
+
+static int SortImageNumber(const void* pElem1, const void* pElem2)
+ {
+ VR *vr1, *vr2;
+ DICOMDataObject *ddo1= *(DICOMDataObject **) pElem1;
+ DICOMDataObject *ddo2= *(DICOMDataObject **) pElem2;
+ char t1[68], t2[68];
+
+ vr1 = ddo1->GetVR(0x0020, 0x0013);
+ vr2 = ddo2->GetVR(0x0020, 0x0013);
+
+ if (vr1==NULL || vr2==NULL)
+ return 0;
+
+ if (vr1->Length) strncpy(t1, (char *)vr1->Data, vr1->Length); t1[vr1->Length]=0;
+ if (vr2->Length) strncpy(t2, (char *)vr2->Data, vr2->Length); t2[vr2->Length]=0;
+
+ if (atoi(t1) < atoi(t2))
+ return -1;
+ else if (atoi(t1) > atoi(t2))
+ return 1;
+ else
+ return 0;
+ }
+
+// Remove duplicate entries from a query response - on selected Level
+
+void RemoveQueryDuplicates(const char *Level, Array < DICOMDataObject * > *ADDO)
+ {
+ DICOMDataObject **addo = (DICOMDataObject **)malloc(ADDO->GetSize() * sizeof(DICOMDataObject *));
+ int g, e;
+ unsigned int i, j;
+ VR *vr1, *vr2;
+
+ for (i=0; i<ADDO->GetSize(); i++) addo[i] = ADDO->Get(i);
+
+ // sort on primary key
+ if (strncmp(Level, "PATIENT", 7)==0) qsort(addo, ADDO->GetSize(), sizeof(DICOMDataObject *), SortPatient), g=0x0010, e=0x0020;
+ else if (strncmp(Level, "STUDY", 5)==0) qsort(addo, ADDO->GetSize(), sizeof(DICOMDataObject *), SortStudy), g=0x0020, e=0x000d;
+ else if (strncmp(Level, "SERIES", 6)==0) qsort(addo, ADDO->GetSize(), sizeof(DICOMDataObject *), SortSeries), g=0x0020, e=0x000e;
+ else if (strncmp(Level, "IMAGE", 5)==0) qsort(addo, ADDO->GetSize(), sizeof(DICOMDataObject *), SortImages), g=0x0008, e=0x0018;
+ else if (strncmp(Level, "WORKLIST",8)==0) qsort(addo, ADDO->GetSize(), sizeof(DICOMDataObject *), SortAccession),g=0x0008, e=0x0050;
+ else
+ {
+ free(addo);
+ return;
+ }
+
+ j = ADDO->GetSize();
+ while(ADDO->GetSize()) ADDO->RemoveAt(0);
+
+ // remove duplicates of primary key
+ for (i=0; i<j; i++)
+ {
+ if (i>0)
+ {
+ vr1 = addo[i-1]->GetVR(g, e);
+ vr2 = addo[i ]->GetVR(g, e);
+ if (vr1 && vr2 && vr1->Length==vr2->Length)
+ if (memicmp((char *)vr1->Data, (char *)vr2->Data, vr1->Length)==0)
+ {
+ // This is a double: here it should be checked if there are any
+ // computed fields 0020,12xx, if so these should be ADDED
+ ADDO->Get(ADDO->GetSize()-1) = addo[i];
+ delete addo[i-1];
+ continue;
+ }
+ }
+ ADDO->Add(addo[i]);
+ }
+ SystemDebug.printf("Virtualquery: removed %d duplicates out of %d entries\n", j-ADDO->GetSize(), j);
+ free(addo);
+ }
+
+// Patient, study or series finder (server functional); search string starts with = means exact
+
+BOOL PatientStudyFinder(char *server, char *str, char *fmt, FILE *f, const char *level)
+ {
+ DICOMDataObject DDO;
+ VR *vr;
+ char tmp[256], tmp2[256];
+ char outp[7][256];
+// BOOL local=stricmp(server, (char *)MYACRNEMA)==0;
+ Array < DICOMDataObject * > ADDO;
+ unsigned int i, j;
+ tmp2[0]=0; tmp[0]=0;
+
+ // search ID
+ SetStringVR(&vr, 0x0008, 0x0052, level);
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0010, 0x0010, "");
+ DDO.Push(vr);
+
+ if (str[0] == '=')
+ {
+ if (level[0]=='I') sprintf(tmp2, "%s", str+1);
+ else sprintf(tmp, "%s", str+1);
+ }
+ else
+ sprintf(tmp, "*%s*", str);
+ SetStringVR(&vr, 0x0010, 0x0020, tmp);
+ DDO.Push(vr);
+
+ if (level[0]=='S' || level[0]=='I')
+ {
+ SetStringVR(&vr, 0x0020, 0x000d, "");
+ DDO.Push(vr);
+ if (level[1]=='E')
+ {
+ SetStringVR(&vr, 0x0008, 0x0020, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0008, 0x0031, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0020, 0x000e, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0008, 0x0060, "");
+ DDO.Push(vr);
+ }
+ else if (level[1]=='T')
+ {
+ SetStringVR(&vr, 0x0008, 0x0020, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0008, 0x0061, "");
+ DDO.Push(vr);
+ }
+ else if (level[1]=='M')
+ {
+ SetStringVR(&vr, 0x0020, 0x000e, tmp2);
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0008, 0x0018, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0020, 0x0013, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0020, 0x1041, "");
+ DDO.Push(vr);
+ }
+ }
+
+ if (strcmp(server, "local")==0)
+ {
+ if (level[0]=='P') QueryOnPatient (&DDO, &ADDO);
+ if (level[0]=='S' && level[1]=='T') QueryOnStudy (&DDO, &ADDO);
+ if (level[0]=='S' && level[1]=='E') QueryOnSeries (&DDO, &ADDO);
+ if (level[0]=='I' && level[1]=='M') QueryOnImage (&DDO, &ADDO);
+ }
+ else
+ VirtualQuery(&DDO, level, 0, &ADDO, server);
+
+ DDO.Reset();
+
+ // search name
+ if (level[0]!='I')
+ {
+ SetStringVR(&vr, 0x0008, 0x0052, level);
+ DDO.Push(vr);
+ if (str[0] == '=')
+ sprintf(tmp, "%s", str+1);
+ else
+ sprintf(tmp, "*%s*", str);
+ SetStringVR(&vr, 0x0010, 0x0010, tmp);
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0010, 0x0020, "");
+ DDO.Push(vr);
+ if (level[0]=='S')
+ {
+ SetStringVR(&vr, 0x0008, 0x0020, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0020, 0x000d, "");
+ DDO.Push(vr);
+ if (level[1]=='E')
+ {
+ SetStringVR(&vr, 0x0008, 0x0031, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0020, 0x000e, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0008, 0x0060, "");
+ DDO.Push(vr);
+ }
+ else
+ {
+ SetStringVR(&vr, 0x0008, 0x0061, "");
+ DDO.Push(vr);
+ }
+ }
+ if (strcmp(server, "local")==0)
+ {
+ if (level[0]=='P') QueryOnPatient (&DDO, &ADDO);
+ if (level[0]=='S' && level[1]=='T') QueryOnStudy (&DDO, &ADDO);
+ if (level[0]=='S' && level[1]=='E') QueryOnSeries (&DDO, &ADDO);
+ }
+ else
+ VirtualQuery(&DDO, level, 0, &ADDO, server);
+
+ DDO.Reset();
+ }
+
+ // search study date (=passed as is), only yyyy, yyyymm, yyyymmdd or data range queries
+ if (level[0]=='S' && str[0]!='=')
+ {
+ SetStringVR(&vr, 0x0008, 0x0052, level);
+ DDO.Push(vr);
+ if (str[0] == '=')
+ sprintf(tmp, "%s", str+1);
+ else
+ {
+ if (strlen(str)==4 && atoi(str)>1900 && atoi(str)<2200)
+ sprintf(tmp, "%s0101-%s1231", str, str);
+ else if (strlen(str)==6 && atoi(str)>190000 && atoi(str)<220000)
+ sprintf(tmp, "%s01-%s31", str, str);
+ else if (strlen(str)==8 && atoi(str)>19000000 && atoi(str)<22000000)
+ sprintf(tmp, "%s", str);
+ else if (strlen(str)==9 && atoi(str)>19000000 && atoi(str)<22000000 && str[8]=='-')
+ sprintf(tmp, "%s", str);
+ else if (strlen(str)==9 && atoi(str+1)>19000000 && atoi(str+1)<22000000 && str[0]=='-')
+ sprintf(tmp, "%s", str);
+ else if (strlen(str)==17 && atoi(str)>19000000 && atoi(str)<22000000 && str[8]=='-' && atoi(str+9)>19000000 && atoi(str+9)<22000000)
+ sprintf(tmp, "%s", str);
+ else
+ sprintf(tmp, "invalid");
+ }
+
+
+ SetStringVR(&vr, 0x0008, 0x0020, tmp);
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0010, 0x0010, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0010, 0x0020, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0020, 0x000d, "");
+ DDO.Push(vr);
+ if (level[1]=='E')
+ {
+ SetStringVR(&vr, 0x0008, 0x0031, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0020, 0x000e, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0008, 0x0060, "");
+ DDO.Push(vr);
+ }
+ else
+ {
+ SetStringVR(&vr, 0x0008, 0x0061, "");
+ DDO.Push(vr);
+ }
+
+
+ if (strcmp(tmp, "invalid")!=0)
+ {
+ if (strcmp(server, "local")==0)
+ {
+ if (level[1]=='T') QueryOnStudy (&DDO, &ADDO);
+ if (level[1]=='E') QueryOnSeries (&DDO, &ADDO);
+ }
+ else
+ VirtualQuery(&DDO, level, 0, &ADDO, server);
+ }
+
+ DDO.Reset();
+ }
+
+ // search study UID (as is) for series level (exact only)
+ if (level[0]=='S' && level[1]=='E' && str[0] == '=' && strlen(str)>8)
+ {
+ SetStringVR(&vr, 0x0008, 0x0052, level);
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0008, 0x0020, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0010, 0x0010, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0010, 0x0020, "");
+ DDO.Push(vr);
+ if (str[0] == '=')
+ sprintf(tmp, "%s", str+1);
+ else
+ sprintf(tmp, "%s", str);
+ SetStringVR(&vr, 0x0020, 0x000d, tmp);
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0008, 0x0031, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0020, 0x000e, "");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0008, 0x0060, "");
+ DDO.Push(vr);
+
+
+ if (strcmp(server, "local")==0)
+ {
+ QueryOnSeries (&DDO, &ADDO);
+ }
+ else
+ VirtualQuery(&DDO, level, 0, &ADDO, server);
+
+ DDO.Reset();
+ }
+
+ RemoveQueryDuplicates(level, &ADDO);
+
+ for (i=0; i<ADDO.GetSize(); i++)
+ {
+ j = 0;
+ while((vr=ADDO.Get(i)->Pop()))
+ {
+ if (0x0052==vr->Element && 0x0008==vr->Group)
+ {
+ delete vr;
+ continue;
+ }
+
+ if (0x0000==vr->Element)
+ {
+ delete vr;
+ continue;
+ }
+
+ if (j<7)
+ {
+ memcpy(outp[j], vr->Data, vr->Length);
+ if (vr->Length && outp[j][vr->Length-1]==' ') outp[j++][vr->Length-1]=0;
+ else outp[j++][vr->Length]=0;
+ }
+ delete vr;
+ }
+
+ if (level[0]=='P')
+ fprintf(f, fmt, outp[0], outp[1],
+ outp[0], outp[1],
+ outp[0], outp[1],
+ outp[0], outp[1],
+ outp[0], outp[1],
+ outp[0], outp[1],
+ outp[0], outp[1],
+ outp[0], outp[1]);
+ else if (level[1]=='T')
+ fprintf(f, fmt, outp[0], outp[1], outp[2], outp[3], outp[4],
+ outp[0], outp[1], outp[2], outp[3], outp[4],
+ outp[0], outp[1], outp[2], outp[3], outp[4],
+ outp[0], outp[1], outp[2], outp[3], outp[4],
+ outp[0], outp[1], outp[2], outp[3], outp[4],
+ outp[0], outp[1], outp[2], outp[3], outp[4],
+ outp[0], outp[1], outp[2], outp[3], outp[4]);
+ else if (level[1]=='E' || level[1]=='M')
+ fprintf(f, fmt, outp[0], outp[1], outp[2], outp[3], outp[4], outp[5], outp[6],
+ outp[0], outp[1], outp[2], outp[3], outp[4], outp[5], outp[6],
+ outp[0], outp[1], outp[2], outp[3], outp[4], outp[5], outp[6],
+ outp[0], outp[1], outp[2], outp[3], outp[4], outp[5], outp[6],
+ outp[0], outp[1], outp[2], outp[3], outp[4], outp[5], outp[6],
+ outp[0], outp[1], outp[2], outp[3], outp[4], outp[5], outp[6],
+ outp[0], outp[1], outp[2], outp[3], outp[4], outp[5], outp[6]);
+ delete ADDO.Get(i);
+ }
+
+ return TRUE;
+ }
+
+// Image lister: get filenames, url's or pat:uid identifier of all objects in one series
+BOOL ImageFileLister(const char *server, char *pat, char *study, char *series, char *sop, char *fmt, FILE *f)
+ {
+ DICOMDataObject DDO;
+ VR *vr;
+ char Device[256], Filename[512], FullFilename[512], Sop[66];
+// BOOL local=stricmp(server, (char *)MYACRNEMA)==0;
+ Array < DICOMDataObject * > ADDO;
+ unsigned int i, j;
+ DICOMDataObject **addo;
+
+ // search ID
+ SetStringVR(&vr, 0x0008, 0x0052, "IMAGE");
+ DDO.Push(vr);
+ if (pat)
+ {
+ SetStringVR(&vr, 0x0010, 0x0020, pat);
+ DDO.Push(vr);
+ }
+ if (study)
+ {
+ SetStringVR(&vr, 0x0020, 0x000d, study);
+ DDO.Push(vr);
+ }
+ if (series)
+ {
+ SetStringVR(&vr, 0x0020, 0x000e, series);
+ DDO.Push(vr);
+ }
+ if (sop)
+ {
+ SetStringVR(&vr, 0x0008, 0x0018, sop);
+ DDO.Push(vr);
+ }
+ SetStringVR(&vr, 0x9999, 0x0800, ""); // filename
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x9999, 0x0801, ""); // device
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0020, 0x0013, ""); // slice number
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0008, 0x0018, ""); // uid
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0028, 0x0008, ""); // #frames
+ DDO.Push(vr);
+
+ if (strcmp(server, "local")==0)
+ {
+ QueryOnImage (&DDO, &ADDO);
+ }
+ else
+ VirtualQuery(&DDO, "IMAGE", 0, &ADDO, (char *)server);
+
+ // sort on image number
+ addo = (DICOMDataObject **)malloc(ADDO.GetSize() * sizeof(DICOMDataObject *));
+ for (i=0; i<ADDO.GetSize(); i++) addo[i] = ADDO.Get(i);
+ qsort(addo, ADDO.GetSize(), sizeof(DICOMDataObject *), SortImageNumber);
+ j = ADDO.GetSize(); while(ADDO.GetSize()) ADDO.RemoveAt(0);
+ for (i=0; i<j; i++) ADDO.Add(addo[i]);
+ free(addo);
+
+ if (fmt[0]=='?')
+ {
+ fprintf(f, fmt+1, ADDO.GetSize());
+
+ for (i=0; i<ADDO.GetSize(); i++)
+ { while((vr=ADDO.Get(i)->Pop()))
+ delete vr;
+ delete ADDO.Get(i);
+ }
+ return true;
+ }
+
+ // locate files
+ for (i=0; i<ADDO.GetSize(); i++)
+ {
+ char is[20], is1[20], frames[256];
+ int nframes;
+ sprintf(is, "%d", i);
+ sprintf(is1, "%d", i+1);
+
+ Filename[0] = 0; Device[0] = 0;
+
+ vr = ADDO.Get(i)->GetVR(0x9999, 0x0800);
+ if (vr)
+ {
+ memcpy(Filename, vr->Data, vr->Length);
+ if (vr->Length && Filename[vr->Length-1]==' ') Filename[vr->Length-1] = 0;
+ else Filename[vr->Length] = 0;
+ }
+ vr = ADDO.Get(i)->GetVR(0x9999, 0x0801);
+ if (vr)
+ {
+ memcpy(Device, vr->Data, vr->Length);
+ if (vr->Length && Device[vr->Length-1]==' ') Device[vr->Length-1] = 0;
+ else Device[vr->Length] = 0;
+ }
+ vr = ADDO.Get(i)->GetVR(0x0008, 0x0018);
+ if (vr)
+ {
+ memcpy(Sop, vr->Data, vr->Length);
+ if (vr->Length && Sop[vr->Length-1]==' ') Sop[vr->Length-1] = 0;
+ else Sop[vr->Length] = 0;
+ }
+
+ SearchDICOMObject(ADDO.Get(i), "0028,0008", frames);
+ nframes = atoi(frames);
+
+ if (FindPhysicalDevice(Device, FullFilename, Filename))
+ {
+ if (i==ADDO.GetSize()-1 && fmt[strlen(fmt)-1]=='*') fmt[strlen(fmt)-1]=0;
+ strcat(FullFilename, Filename);
+ if (fmt[0]=='#')
+ fprintf(f, fmt+1, Device, Filename, is, is1, Device, Filename, is, is1, Device, Filename, is, is1 );
+ else if (fmt[0]=='@')
+ {
+ for (j=0; j<strlen(Filename); j++) if (Filename[j]=='\\') Filename[j]='/';
+ fprintf(f, fmt+1, Device, Filename, is, is1, Device, Filename, is, is1, Device, Filename, is, is1 );
+ }
+ else if (fmt[0]==':')
+ {
+ char out[100]; int outlen=0;
+ for (j=0; j<strlen(pat); j++)
+ {
+ if (pat[j]==' ') { out[outlen++] = '%'; out[outlen++] = '2'; out[outlen++] = '0'; }
+ else out[outlen++] = pat[j];
+ }
+ out[outlen++]=0;
+ fprintf(f, fmt+1, out, Sop, is, is1, out, Sop, is, is1, out, Sop, is, is1);
+ }
+ else if (fmt[0]=='$')
+ fprintf(f, fmt+1, nframes);
+ else
+ fprintf(f, fmt, FullFilename, is, is1, FullFilename, is, is1, FullFilename, is, is1);
+ }
+
+ while((vr=ADDO.Get(i)->Pop()))
+ delete vr;
+ delete ADDO.Get(i);
+ }
+
+ return TRUE;
+ }
+
+// Series lister: get all series of one (or all) study
+BOOL SeriesUIDLister(char *server, char *pat, char *study, char *fmt, FILE *f)
+ {
+ DICOMDataObject DDO;
+ VR *vr;
+ char UID[256];
+// BOOL local=stricmp(server, (char *)MYACRNEMA)==0;
+ Array < DICOMDataObject * > ADDO;
+ unsigned int i;
+
+ // search ID
+ SetStringVR(&vr, 0x0008, 0x0052, "SERIES");
+ DDO.Push(vr);
+ if (pat)
+ {
+ SetStringVR(&vr, 0x0010, 0x0020, pat);
+ DDO.Push(vr);
+ }
+ if (study)
+ {
+ SetStringVR(&vr, 0x0020, 0x000d, study);
+ DDO.Push(vr);
+ }
+ SetStringVR(&vr, 0x0020, 0x000e, "");
+ DDO.Push(vr);
+
+ if (strcmp(server, "local")==0)
+ {
+ QueryOnSeries (&DDO, &ADDO);
+ }
+ else
+ VirtualQuery(&DDO, "SERIES", 0, &ADDO, server);
+
+ if (fmt[0]=='?')
+ {
+ fprintf(f, fmt+1, ADDO.GetSize());
+
+ for (i=0; i<ADDO.GetSize(); i++)
+ { while((vr=ADDO.Get(i)->Pop()))
+ delete vr;
+ delete ADDO.Get(i);
+ }
+
+ return TRUE;
+ }
+
+ for (i=0; i<ADDO.GetSize(); i++)
+ {
+ UID[0] = 0;
+
+ vr = ADDO.Get(i)->GetVR(0x0020, 0x000e);
+ if (vr)
+ {
+ memcpy(UID, vr->Data, vr->Length);
+ if (vr->Length && UID[vr->Length-1]==' ') UID[vr->Length-1] = 0;
+ else UID[vr->Length] = 0;
+
+ fprintf(f, fmt, UID, i, UID, i, UID, i);
+ }
+
+ while((vr=ADDO.Get(i)->Pop()))
+ delete vr;
+ delete ADDO.Get(i);
+ }
+
+ return TRUE;
+ }
+
+BOOL DeleteUIDChanges(char *Reason);
+
+// Series merge: merge all series of one study of a given modality
+int DcmMergeStudy(const char *server, char *pat, char *study, char *modality, char *seriesdesc, char *script, ExtendedPDU_Service *PDU)
+ {
+ DICOMDataObject DDO;
+ VR *vr;
+ char UID[256];
+// BOOL local=stricmp(server, (char *)MYACRNEMA)==0;
+ Array < DICOMDataObject * > ADDO;
+ unsigned int i;
+ char *uids[1000];
+ char tempfile[512], mergeid[32];
+ FILE *f;
+
+ NewTempFile(tempfile, ".txt");
+
+#ifdef WIN32
+ sprintf(mergeid, "mergst.%u.%d.%u", (unsigned int)time(NULL), GetTickCount()%1000, (UIDPostfix++)%100);
+#else
+ sprintf(mergeid, "mergst.%u.%u", (unsigned int)time(NULL), (UIDPostfix++)%10000);
+#endif
+
+
+ // search ID
+ SetStringVR(&vr, 0x0008, 0x0052, "SERIES");
+ DDO.Push(vr);
+ if (*pat)
+ {
+ SetStringVR(&vr, 0x0010, 0x0020, pat);
+ DDO.Push(vr);
+ }
+ if (*study)
+ {
+ SetStringVR(&vr, 0x0020, 0x000d, study);
+ DDO.Push(vr);
+ }
+ if (*modality)
+ {
+ SetStringVR(&vr, 0x0008, 0x0060, modality);
+ DDO.Push(vr);
+ }
+ if (*seriesdesc)
+ {
+ SetStringVR(&vr, 0x0008, 0x103e, seriesdesc);
+ DDO.Push(vr);
+ }
+ SetStringVR(&vr, 0x0020, 0x000e, "");
+ DDO.Push(vr);
+
+ if (strcmp(server, "local")==0)
+ {
+ QueryOnSeries (&DDO, &ADDO);
+ }
+ else
+ VirtualQuery(&DDO, "SERIES", 0, &ADDO, (char *)server);
+
+ for (i=0; i<ADDO.GetSize(); i++)
+ {
+ UID[0] = 0;
+
+ vr = ADDO.Get(i)->GetVR(0x0020, 0x000e);
+ if (vr)
+ {
+ memcpy(UID, vr->Data, vr->Length);
+ if (vr->Length && UID[vr->Length-1]==' ') UID[vr->Length-1] = 0;
+ else UID[vr->Length] = 0;
+
+ uids[i] = strdup(UID);
+ }
+
+ while((vr=ADDO.Get(i)->Pop()))
+ delete vr;
+ delete ADDO.Get(i);
+ }
+
+ char temp[512];
+ MergeUIDs(uids, ADDO.GetSize(), mergeid, temp);
+
+ for (i=0; i<ADDO.GetSize(); i++)
+ {
+ f = fopen(tempfile, "wt");
+ char formt[]="%s\n";
+ ImageFileLister(server, pat, NULL, uids[i], NULL, formt, f);
+ fclose(f);
+
+ f = fopen(tempfile, "rt");
+ while(fgets(temp, sizeof(temp), f) != NULL)
+ { if (temp[strlen(temp)-1]=='\n') temp[strlen(temp)-1]=0;
+ MergeUIDofImageFile(temp, TRUE, "SeriesUID", script, mergeid, PDU);
+ }
+ fclose(f);
+ unlink(tempfile);
+
+ free(uids[i]);
+ }
+
+ DeleteUIDChanges(mergeid);
+
+ return TRUE;
+ }
+
+// Submit: zip and sftp mode: use 7za to zip and (sftp mode) pscp to transfer data to central server
+// optionally data may be processed by passed script
+
+int DcmSubmitData(char *pat, char *study, char *series, char *sop, char *script,
+ char *modesubmit, char *hostsubmit, int portsubmit, char *ident)
+ {
+ char tempfile[512], tempfile2[512], archfile[512], temp[512], ziptype[512];
+ FILE *f, *g;
+ int rc = FALSE;
+ char *p;
+ ExtendedPDU_Service PDU; // script context of submit process
+ PDU.SetLocalAddress ( (BYTE *)"submit" );
+ PDU.SetRemoteAddress ( (BYTE *)"submit" );
+
+ UNUSED_ARGUMENT(portsubmit);
+
+ NewTempFile(tempfile, ".txt");
+ NewTempFile(tempfile2, ".txt");
+
+ f = fopen(tempfile, "wt");
+ char formt[]="%s\n";
+ ImageFileLister("local", pat, study, series, sop, formt, f);
+ fclose(f);
+
+ sprintf(StatusString, "Starting submission");
+
+ if (script)
+ { int total=0, count=0;
+ f = fopen(tempfile, "rt");
+ while(fgets(temp, sizeof(temp), f) != NULL) total++;
+ fclose(f);
+
+ f = fopen(tempfile, "rt");
+ g = fopen(tempfile2, "wt");
+ while(fgets(temp, sizeof(temp), f) != NULL)
+ { if (temp[strlen(temp)-1]=='\n') temp[strlen(temp)-1]=0;
+
+ sprintf(StatusString, "Processing image %d of %d", count+1, total);
+
+ DICOMDataObject *pDDO;
+ pDDO = LoadForGUI(temp);
+ if (pDDO)
+ { rc = CallImportConverterN(pDDO, -1, NULL, NULL, NULL, NULL, &PDU, NULL, script);
+ if (rc!=2 && rc!=6)
+ { NewTempFile(temp, ".dcm");
+ SaveDICOMDataObject(temp, pDDO);
+ fprintf(g, "%s\n", temp);
+ }
+ delete pDDO;
+ }
+ else
+ {
+ sprintf(StatusString, "*** Failed to read DICOM image to process before submit\n");
+ OperatorConsole.printf("*** Failed to read DICOM image to process before submit\n");
+ }
+ }
+ fclose(f);
+ fclose(g);
+ unlink(tempfile);
+ strcpy(tempfile, tempfile2);
+ }
+
+ strcpy(ziptype, "zip");
+ if (stricmp(modesubmit, "zip")==0)
+ { strcpy(archfile, hostsubmit);
+ p = strrchr(archfile, '.');
+ if (p) strcpy(ziptype, p+1);
+ if (stricmp(ziptype, "7z" )==0) strcpy(ziptype, "7z");
+ if (stricmp(ziptype, "zip" )==0) strcpy(ziptype, "zip");
+ if (stricmp(ziptype, "tar" )==0) strcpy(ziptype, "tar");
+ unlink(archfile);
+ }
+ else
+ NewTempFile(archfile, ".zip");
+
+ sprintf(StatusString, "Zipping processed images");
+#ifdef WIN32
+ sprintf(temp, "-y a \"%s\" -t%s @%s", archfile, ziptype, tempfile);
+ BackgroundExec("7za.exe", temp);
+ // Note: does not check result of 7za
+#else
+ sprintf(temp, "7za -y a \"%s\" -t%s @%s", archfile, ziptype, tempfile);
+ if (system(temp)!=0)
+ { OperatorConsole.printf("*** Failed zipping archive to submit/export\n");
+ }
+#endif
+
+ if (script)
+ { sprintf(StatusString, "Deleting processed images");
+ f = fopen(tempfile, "rt");
+ while(fgets(temp, sizeof(temp), f) != NULL)
+ { if (temp[strlen(temp)-1]=='\n') temp[strlen(temp)-1]=0;
+ unlink(temp);
+ }
+ fclose(f);
+ }
+ unlink(tempfile);
+
+ if (stricmp(modesubmit, "sftp")==0)
+ { sprintf(StatusString, "Starting upload");
+ sprintf(temp, "pscp -pw %s -batch %s %s", ident, archfile, hostsubmit);
+ if (system(temp)!=0)
+ { OperatorConsole.printf("*** Failed uploading archive to submit\n");
+ sprintf(StatusString, "*** Failed uploading archive to submit");
+ rc = TRUE; // may be retried (scheduletransfer)
+ }
+ else
+ { *StatusString=0;
+ unlink(archfile);
+ }
+ }
+
+ if (stricmp(modesubmit, "other")==0)
+ { sprintf(StatusString, "Starting upload");
+ sprintf(temp, ident, archfile, hostsubmit);
+ if (system(temp)!=0)
+ { OperatorConsole.printf("*** Failed uploading archive to submit\n");
+ sprintf(StatusString, "*** Failed uploading archive to submit");
+ rc = TRUE; // may be retried (scheduletransfer)
+ }
+ else
+ { *StatusString=0;
+ unlink(archfile);
+ }
+ }
+
+ return rc;
+ }
+
+BOOL MyPatientRootQuery :: QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ UNUSED_ARGUMENT(DCO);
+ return CallImportConverterN(DDO, 1000, NULL, NULL, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+// this callback is called very often, therefore save much time by this:
+// if ImportConverter 1500 does not exists check once a second it appears
+static time_t t_1500=0;
+BOOL MyPatientRootQuery :: QueryResultScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ int rc=0;
+ UNUSED_ARGUMENT(DCO);
+ if (!t_1500)
+ {
+ rc = CallImportConverterN(DDO, 1500, NULL, NULL, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL);
+ if (rc==0) t_1500 = time(NULL);
+ }
+ else
+ {
+ if (t_1500 != time(NULL)) t_1500=0;
+ }
+ return rc!=2;
+ }
+
+// Implementation: Query
+BOOL MyPatientRootQuery :: SearchOn (
+ DICOMDataObject *DDOPtr,
+ Array < DICOMDataObject * > *ADDO)
+ {
+ char Level [ 10 ];
+ int sources=0, count1, count2;
+ BOOL st;
+ UINT16 mask;
+
+ SetString(DDOPtr->GetVR(0x0008, 0x0052), Level, 10);
+ strcpy(QueryRetrieveLevel, Level);
+ OperatorConsole.printf("(PatientRootQuery) search level: %s\n", Level);
+ if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr);
+
+ mask = DDOPtr->GetUINT16(0x9999, 0x0802);
+ if (!mask) mask = 0xffff;
+
+ for (int i=0; i<10; i++)
+ if (mask & (1<<i))
+ sources += VirtualQueryCached(DDOPtr, Level, i, ADDO)!=0;
+ count1 = ADDO->GetSize();
+
+ prefetcher(DDOPtr, FALSE);
+
+ if(!strncmp(Level, "PATIENT", 7))
+ st = ( QueryOnPatient (DDOPtr, ADDO));
+ else if(!strncmp(Level, "STUDY", 5))
+ st = ( QueryOnStudy (DDOPtr, ADDO));
+ else if(!strncmp(Level, "SERIES", 6))
+ st = ( QueryOnSeries (DDOPtr, ADDO));
+ else if(!strncmp(Level, "IMAGE", 5))
+ st = ( QueryOnImage (DDOPtr, ADDO));
+ else
+ st = FALSE;
+
+ count2 = ADDO->GetSize()-count1;
+ sources += count2!=0;
+
+ if (sources>1) // more than one source; data can be duplicated
+ RemoveQueryDuplicates(Level, ADDO);
+
+ RecordsFound = ADDO->GetSize();
+
+ return st;
+ }
+
+BOOL MyStudyRootQuery :: QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ UNUSED_ARGUMENT(DCO);
+ return CallImportConverterN(DDO, 1000, NULL, NULL, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+BOOL MyStudyRootQuery :: QueryResultScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ int rc=0;
+ UNUSED_ARGUMENT(DCO);
+ if (!t_1500)
+ {
+ rc = CallImportConverterN(DDO, 1500, NULL, NULL, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL);
+ if (rc==0) t_1500 = time(NULL);
+ }
+ else
+ {
+ if (t_1500 != time(NULL)) t_1500=0;
+ }
+ return rc!=2;
+ }
+
+BOOL MyStudyRootQuery :: SearchOn (
+ DICOMDataObject *DDOPtr,
+ Array < DICOMDataObject * > *ADDO)
+ {
+ char Level [ 10 ];
+ int sources=0, count1, count2;
+ BOOL st;
+ UINT16 mask;
+
+ SetString(DDOPtr->GetVR(0x0008, 0x0052), Level, 10);
+ strcpy(QueryRetrieveLevel, Level);
+ OperatorConsole.printf("(StudyRootQuery) search level: %s\n", Level);
+ if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr);
+
+ mask = DDOPtr->GetUINT16(0x9999, 0x0802);
+ if (!mask) mask = 0xffff;
+
+ for (int i=0; i<10; i++)
+ if (mask & (1<<i))
+ sources += VirtualQueryCached(DDOPtr, Level, i, ADDO)!=0;
+ count1 = ADDO->GetSize();
+
+ prefetcher(DDOPtr, FALSE);
+
+ if(!strncmp(Level, "STUDY", 5))
+ st = ( QueryOnStudy (DDOPtr, ADDO));
+ else if(!strncmp(Level, "SERIES", 6))
+ st = ( QueryOnSeries (DDOPtr, ADDO));
+ else if(!strncmp(Level, "IMAGE", 5))
+ st = ( QueryOnImage (DDOPtr, ADDO));
+ else
+ st = FALSE;
+
+ count2 = ADDO->GetSize()-count1;
+ sources += count2!=0;
+ if (sources>1)
+ RemoveQueryDuplicates(Level, ADDO);
+
+ if (DebugLevel>=3 && ADDO->GetSize()!=0)
+ {
+ SystemDebug.printf("First record of cleaned response:\n");
+ NonDestructiveDumpDICOMObject(ADDO->Get(0));
+ }
+
+ RecordsFound = ADDO->GetSize();
+ return st;
+ }
+
+BOOL MyPatientStudyOnlyQuery :: QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ UNUSED_ARGUMENT(DCO);
+ return CallImportConverterN(DDO, 1000, NULL, NULL, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+BOOL MyPatientStudyOnlyQuery :: QueryResultScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ int rc=0;
+ UNUSED_ARGUMENT(DCO);
+ if (!t_1500)
+ {
+ rc = CallImportConverterN(DDO, 1500, NULL, NULL, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL);
+ if (rc==0) t_1500 = time(NULL);
+ }
+ else
+ {
+ if (t_1500 != time(NULL)) t_1500=0;
+ }
+ return rc!=2;
+ }
+
+BOOL MyPatientStudyOnlyQuery :: SearchOn (
+ DICOMDataObject *DDOPtr,
+ Array < DICOMDataObject * > *ADDO)
+ {
+ char Level [ 10 ];
+ int sources=0, count1, count2;
+ BOOL st;
+ UINT16 mask;
+
+ SetString(DDOPtr->GetVR(0x0008, 0x0052), Level, 10);
+ strcpy(QueryRetrieveLevel, Level);
+ OperatorConsole.printf("(PatientStudyOnlyQuery) search level: %s\n", Level);
+ if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr);
+
+ mask = DDOPtr->GetUINT16(0x9999, 0x0802);
+ if (!mask) mask = 0xffff;
+
+ for (int i=0; i<10; i++)
+ if (mask & (1<<i))
+ sources += VirtualQueryCached(DDOPtr, Level, i, ADDO)!=0;
+ count1 = ADDO->GetSize();
+
+ prefetcher(DDOPtr, FALSE);
+
+ if(!strncmp(Level, "PATIENT", 7))
+ st = ( QueryOnPatient (DDOPtr, ADDO));
+ else if(!strncmp(Level, "STUDY", 5))
+ st = ( QueryOnStudy (DDOPtr, ADDO));
+ else
+ st = FALSE;
+
+ count2 = ADDO->GetSize()-count1;
+ sources += count2!=0;
+ if (sources>1)
+ RemoveQueryDuplicates(Level, ADDO);
+
+ if (DebugLevel>=3 && ADDO->GetSize()!=0)
+ {
+ SystemDebug.printf("First record of cleaned response:\n");
+ NonDestructiveDumpDICOMObject(ADDO->Get(0));
+ }
+
+ RecordsFound = ADDO->GetSize();
+ return st;
+ }
+
+BOOL MyModalityWorkListQuery :: QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ UNUSED_ARGUMENT(DCO);
+ return CallImportConverterN(DDO, 1100, NULL, NULL, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+BOOL MyModalityWorkListQuery :: QueryResultScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ UNUSED_ARGUMENT(DCO);
+ return CallImportConverterN(DDO, 1600, NULL, NULL, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+BOOL MyModalityWorkListQuery :: SearchOn (
+ DICOMDataObject *DDOPtr,
+ Array < DICOMDataObject * > *ADDO)
+ {
+ char Level [ 10 ];
+ int sources=0, count1, count2;
+ BOOL st;
+ UINT16 mask;
+
+ SetString(DDOPtr->GetVR(0x0008, 0x0052), Level, 10);
+ strcpy(QueryRetrieveLevel, Level);
+
+ mask = DDOPtr->GetUINT16(0x9999, 0x0802);
+ if (!mask) mask = 0xffff;
+
+ OperatorConsole.printf("(ModalityWorkListQuery) search level: %s\n", Level);
+ if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr);
+
+// for (int i=0; i<10; i++)
+// if (mask & (1<<i))
+// sources += VirtualQuery(DDOPtr, Level, i, ADDO)!=0;
+ count1 = ADDO->GetSize();
+
+// prefetcher(DDOPtr, FALSE);
+
+ st = ( QueryOnModalityWorkList (DDOPtr, ADDO));
+
+ count2 = ADDO->GetSize()-count1;
+ sources += count2!=0;
+ if (sources>1)
+ RemoveQueryDuplicates(Level, ADDO);
+
+ if (DebugLevel>=3 && ADDO->GetSize()!=0)
+ {
+ SystemDebug.printf("First record of cleaned response:\n");
+ NonDestructiveDumpDICOMObject(ADDO->Get(0));
+ }
+
+ RecordsFound = ADDO->GetSize();
+ return st;
+ }
+
+BOOL MyPatientRootQuery :: CallBack (
+ DICOMCommandObject *DCOPtr,
+ DICOMDataObject *DDOPtr)
+ {
+ UNUSED_ARGUMENT(DCOPtr);
+ UNUSED_ARGUMENT(DDOPtr);
+ return ( TRUE );
+ }
+
+BOOL MyStudyRootQuery :: CallBack (
+ DICOMCommandObject *DCOPtr,
+ DICOMDataObject *DDOPtr)
+ {
+ UNUSED_ARGUMENT(DCOPtr);
+ UNUSED_ARGUMENT(DDOPtr);
+ return ( TRUE );
+ }
+
+BOOL MyPatientStudyOnlyQuery :: CallBack (
+ DICOMCommandObject *DCOPtr,
+ DICOMDataObject *DDOPtr)
+ {
+ UNUSED_ARGUMENT(DCOPtr);
+ UNUSED_ARGUMENT(DDOPtr);
+ return ( TRUE );
+ }
+
+BOOL MyModalityWorkListQuery :: CallBack (
+ DICOMCommandObject *DCOPtr,
+ DICOMDataObject *DDOPtr)
+ {
+ UNUSED_ARGUMENT(DCOPtr);
+ UNUSED_ARGUMENT(DDOPtr);
+ return ( TRUE );
+ }
+
+
+BOOL MyPatientRootRetrieve :: QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ char dest[20];
+ memset(dest, 0, 20);
+ VR *vr = DCO->GetVR(0x0000, 0x0600);
+ if (vr) memcpy(dest, (char *)(vr->Data), vr->Length);
+ while (strlen(dest)>0 && dest[strlen(dest)-1]==' ') dest[strlen(dest)-1] = 0;
+
+ return CallImportConverterN(DDO, 1200, NULL, dest, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+BOOL MyPatientRootRetrieve :: SearchOn (
+ DICOMDataObject *DDOPtr,
+ Array < DICOMDataObject * > *ADDO)
+ {
+ VR *vr;
+ UINT16 mask;
+
+ prefetcher(DDOPtr, TRUE);
+
+ SystemDebug.printf("MyPatientRootRetrieve :: SearchOn\n");
+ if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr);
+
+ mask = DDOPtr->GetUINT16(0x9999, 0x0802);
+ if (!mask) mask = 0xffff;
+
+ for (int i=0; i<10; i++)
+ if (mask & (1<<i))
+ VirtualQueryToDB(DDOPtr, i);
+
+ if(!DDOPtr->GetVR(0x0008, 0x0018))
+ {
+ vr = new VR ( 0x0008, 0x0018, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0008, 0x0016))
+ {
+ vr = new VR ( 0x0008, 0x0016, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000d))
+ {
+ vr = new VR ( 0x0020, 0x000d, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000e))
+ {
+ vr = new VR ( 0x0020, 0x000e, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0800))
+ {
+ vr = new VR ( 0x9999, 0x0800, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0801))
+ {
+ vr = new VR ( 0x9999, 0x0801, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ QueryOnImage(DDOPtr, ADDO);
+ if(!ADDO->GetSize())
+ return(FALSE);
+ OperatorConsole.printf("Number of images to send: %d\n", ADDO->GetSize());
+ return(TRUE);
+ }
+
+BOOL MyPatientRootRetrieveNKI :: QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ char dest[20];
+ memset(dest, 0, 20);
+ VR *vr = DCO->GetVR(0x0000, 0x0600);
+ if (vr) memcpy(dest, (char *)(vr->Data), vr->Length);
+ while (strlen(dest)>0 && dest[strlen(dest)-1]==' ') dest[strlen(dest)-1] = 0;
+
+ return CallImportConverterN(DDO, 1200, NULL, dest, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+BOOL MyPatientRootRetrieveNKI :: SearchOn (
+ DICOMDataObject *DDOPtr,
+ Array < DICOMDataObject * > *ADDO)
+ {
+ VR *vr;
+ UINT16 mask;
+
+ prefetcher(DDOPtr, TRUE);
+
+ SystemDebug.printf("MyPatientRootRetrieveNKI :: SearchOn\n");
+ if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr);
+
+ mask = DDOPtr->GetUINT16(0x9999, 0x0802);
+ if (!mask) mask = 0xffff;
+
+ for (int i=0; i<10; i++)
+ if (mask & (1<<i))
+ VirtualQueryToDB(DDOPtr, i);
+
+ if(!DDOPtr->GetVR(0x0008, 0x0018))
+ {
+ vr = new VR ( 0x0008, 0x0018, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0008, 0x0016))
+ {
+ vr = new VR ( 0x0008, 0x0016, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000d))
+ {
+ vr = new VR ( 0x0020, 0x000d, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000e))
+ {
+ vr = new VR ( 0x0020, 0x000e, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0800))
+ {
+ vr = new VR ( 0x9999, 0x0800, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0801))
+ {
+ vr = new VR ( 0x9999, 0x0801, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ QueryOnImage(DDOPtr, ADDO);
+ if(!ADDO->GetSize())
+ return(FALSE);
+ OperatorConsole.printf("Number of images to send: %d\n", ADDO->GetSize());
+ return(TRUE);
+ }
+
+BOOL MyPatientRootRetrieveGeneric :: QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ char dest[20];
+ memset(dest, 0, 20);
+ VR *vr = DCO->GetVR(0x0000, 0x0600);
+ if (vr) memcpy(dest, (char *)(vr->Data), vr->Length);
+ while (strlen(dest)>0 && dest[strlen(dest)-1]==' ') dest[strlen(dest)-1] = 0;
+
+ return CallImportConverterN(DDO, 1200, NULL, dest, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+BOOL MyPatientRootRetrieveGeneric :: SearchOn (
+ DICOMDataObject *DDOPtr,
+ Array < DICOMDataObject * > *ADDO)
+ {
+ VR *vr;
+ UINT16 mask;
+
+ prefetcher(DDOPtr, TRUE);
+
+ SystemDebug.printf("MyPatientRootRetrieveGeneric :: SearchOn\n");
+ if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr);
+
+ mask = DDOPtr->GetUINT16(0x9999, 0x0802);
+ if (!mask) mask = 0xffff;
+
+ for (int i=0; i<10; i++)
+ if (mask & (1<<i))
+ VirtualQueryToDB(DDOPtr, i);
+
+ if(!DDOPtr->GetVR(0x0008, 0x0018))
+ {
+ vr = new VR ( 0x0008, 0x0018, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0008, 0x0016))
+ {
+ vr = new VR ( 0x0008, 0x0016, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000d))
+ {
+ vr = new VR ( 0x0020, 0x000d, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000e))
+ {
+ vr = new VR ( 0x0020, 0x000e, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0800))
+ {
+ vr = new VR ( 0x9999, 0x0800, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0801))
+ {
+ vr = new VR ( 0x9999, 0x0801, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ QueryOnImage(DDOPtr, ADDO);
+ if(!ADDO->GetSize())
+ return(FALSE);
+ OperatorConsole.printf("Number of images to send: %d\n", ADDO->GetSize());
+ return(TRUE);
+ }
+
+BOOL MyStudyRootRetrieve :: QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ char dest[20];
+ memset(dest, 0, 20);
+ VR *vr = DCO->GetVR(0x0000, 0x0600);
+ if (vr) memcpy(dest, (char *)(vr->Data), vr->Length);
+ while (strlen(dest)>0 && dest[strlen(dest)-1]==' ') dest[strlen(dest)-1] = 0;
+
+ return CallImportConverterN(DDO, 1200, NULL, dest, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+BOOL MyStudyRootRetrieve :: SearchOn (
+ DICOMDataObject *DDOPtr,
+ Array < DICOMDataObject * > *ADDO)
+ {
+ VR *vr;
+ UINT16 mask;
+
+ prefetcher(DDOPtr, TRUE);
+
+ SystemDebug.printf("MyStudyRootRetrieve :: SearchOn\n");
+ if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr);
+
+ mask = DDOPtr->GetUINT16(0x9999, 0x0802);
+ if (!mask) mask = 0xffff;
+
+ for (int i=0; i<10; i++)
+ if (mask & (1<<i))
+ VirtualQueryToDB(DDOPtr, i);
+
+ if(!DDOPtr->GetVR(0x0008, 0x0018))
+ {
+ vr = new VR ( 0x0008, 0x0018, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0008, 0x0016))
+ {
+ vr = new VR ( 0x0008, 0x0016, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000d))
+ {
+ vr = new VR ( 0x0020, 0x000d, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000e))
+ {
+ vr = new VR ( 0x0020, 0x000e, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0800))
+ {
+ vr = new VR ( 0x9999, 0x0800, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0801))
+ {
+ vr = new VR ( 0x9999, 0x0801, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ QueryOnImage(DDOPtr, ADDO);
+ if(!ADDO->GetSize())
+ return(FALSE);
+ OperatorConsole.printf("Number of Images to send: %d\n", ADDO->GetSize());
+ return(TRUE);
+ }
+
+BOOL MyStudyRootRetrieveNKI :: QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ char dest[20];
+ memset(dest, 0, 20);
+ VR *vr = DCO->GetVR(0x0000, 0x0600);
+ if (vr) memcpy(dest, (char *)(vr->Data), vr->Length);
+ while (strlen(dest)>0 && dest[strlen(dest)-1]==' ') dest[strlen(dest)-1] = 0;
+
+ return CallImportConverterN(DDO, 1200, NULL, dest, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+BOOL MyStudyRootRetrieveNKI :: SearchOn (
+ DICOMDataObject *DDOPtr,
+ Array < DICOMDataObject * > *ADDO)
+ {
+ VR *vr;
+ UINT16 mask;
+
+ prefetcher(DDOPtr, TRUE);
+
+ SystemDebug.printf("MyStudyRootRetrieveNKI :: SearchOn\n");
+ if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr);
+
+ mask = DDOPtr->GetUINT16(0x9999, 0x0802);
+ if (!mask) mask = 0xffff;
+
+ for (int i=0; i<10; i++)
+ if (mask & (1<<i))
+ VirtualQueryToDB(DDOPtr, i);
+
+ if(!DDOPtr->GetVR(0x0008, 0x0018))
+ {
+ vr = new VR ( 0x0008, 0x0018, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0008, 0x0016))
+ {
+ vr = new VR ( 0x0008, 0x0016, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000d))
+ {
+ vr = new VR ( 0x0020, 0x000d, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000e))
+ {
+ vr = new VR ( 0x0020, 0x000e, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0800))
+ {
+ vr = new VR ( 0x9999, 0x0800, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0801))
+ {
+ vr = new VR ( 0x9999, 0x0801, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ QueryOnImage(DDOPtr, ADDO);
+ if(!ADDO->GetSize())
+ return(FALSE);
+ OperatorConsole.printf("Number of Images to send: %d\n", ADDO->GetSize());
+ return(TRUE);
+ }
+
+BOOL MyStudyRootRetrieveGeneric :: QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ char dest[20];
+ memset(dest, 0, 20);
+ VR *vr = DCO->GetVR(0x0000, 0x0600);
+ if (vr) memcpy(dest, (char *)(vr->Data), vr->Length);
+ while (strlen(dest)>0 && dest[strlen(dest)-1]==' ') dest[strlen(dest)-1] = 0;
+
+ return CallImportConverterN(DDO, 1200, NULL, dest, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+BOOL MyStudyRootRetrieveGeneric :: SearchOn (
+ DICOMDataObject *DDOPtr,
+ Array < DICOMDataObject * > *ADDO)
+ {
+ VR *vr;
+ UINT16 mask;
+
+ prefetcher(DDOPtr, TRUE);
+
+ SystemDebug.printf("MyStudyRootRetrieveGeneric :: SearchOn\n");
+ if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr);
+
+ mask = DDOPtr->GetUINT16(0x9999, 0x0802);
+ if (!mask) mask = 0xffff;
+
+ for (int i=0; i<10; i++)
+ if (mask & (1<<i))
+ VirtualQueryToDB(DDOPtr, i);
+
+ if(!DDOPtr->GetVR(0x0008, 0x0018))
+ {
+ vr = new VR ( 0x0008, 0x0018, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0008, 0x0016))
+ {
+ vr = new VR ( 0x0008, 0x0016, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000d))
+ {
+ vr = new VR ( 0x0020, 0x000d, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000e))
+ {
+ vr = new VR ( 0x0020, 0x000e, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0800))
+ {
+ vr = new VR ( 0x9999, 0x0800, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0801))
+ {
+ vr = new VR ( 0x9999, 0x0801, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ QueryOnImage(DDOPtr, ADDO);
+ if(!ADDO->GetSize())
+ return(FALSE);
+ OperatorConsole.printf("Number of Images to send: %d\n", ADDO->GetSize());
+ return(TRUE);
+ }
+
+BOOL MyPatientStudyOnlyRetrieve :: QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ char dest[20];
+ memset(dest, 0, 20);
+ VR *vr = DCO->GetVR(0x0000, 0x0600);
+ if (vr) memcpy(dest, (char *)(vr->Data), vr->Length);
+ while (strlen(dest)>0 && dest[strlen(dest)-1]==' ') dest[strlen(dest)-1] = 0;
+
+ return CallImportConverterN(DDO, 1200, NULL, dest, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+BOOL MyPatientStudyOnlyRetrieve :: SearchOn (
+ DICOMDataObject *DDOPtr,
+ Array < DICOMDataObject * > *ADDO)
+ {
+ VR *vr;
+ UINT16 mask;
+
+ prefetcher(DDOPtr, TRUE);
+
+ SystemDebug.printf("MyPatientStudyOnlyRetrieve :: SearchOn\n");
+ if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr);
+
+ mask = DDOPtr->GetUINT16(0x9999, 0x0802);
+ if (!mask) mask = 0xffff;
+
+ for (int i=0; i<10; i++)
+ if (mask & (1<<i))
+ VirtualQueryToDB(DDOPtr, i);
+
+ if(!DDOPtr->GetVR(0x0008, 0x0018))
+ {
+ vr = new VR ( 0x0008, 0x0018, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0008, 0x0016))
+ {
+ vr = new VR ( 0x0008, 0x0016, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000d))
+ {
+ vr = new VR ( 0x0020, 0x000d, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000e))
+ {
+ vr = new VR ( 0x0020, 0x000e, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0800))
+ {
+ vr = new VR ( 0x9999, 0x0800, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0801))
+ {
+ vr = new VR ( 0x9999, 0x0801, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ QueryOnImage(DDOPtr, ADDO);
+ if(!ADDO->GetSize())
+ return(FALSE);
+ OperatorConsole.printf("Number of Images to send: %d\n", ADDO->GetSize());
+ return(TRUE);
+ }
+
+BOOL MyPatientStudyOnlyRetrieveNKI :: QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ char dest[20];
+ memset(dest, 0, 20);
+ VR *vr = DCO->GetVR(0x0000, 0x0600);
+ if (vr) memcpy(dest, (char *)(vr->Data), vr->Length);
+ while (strlen(dest)>0 && dest[strlen(dest)-1]==' ') dest[strlen(dest)-1] = 0;
+
+ return CallImportConverterN(DDO, 1200, NULL, dest, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+BOOL MyPatientStudyOnlyRetrieveNKI :: SearchOn (
+ DICOMDataObject *DDOPtr,
+ Array < DICOMDataObject * > *ADDO)
+ {
+ VR *vr;
+ UINT16 mask;
+
+ prefetcher(DDOPtr, TRUE);
+
+ SystemDebug.printf("MyPatientStudyOnlyRetrieveNKI :: SearchOn\n");
+ if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr);
+
+ mask = DDOPtr->GetUINT16(0x9999, 0x0802);
+ if (!mask) mask = 0xffff;
+
+ for (int i=0; i<10; i++)
+ if (mask & (1<<i))
+ VirtualQueryToDB(DDOPtr, i);
+
+ if(!DDOPtr->GetVR(0x0008, 0x0018))
+ {
+ vr = new VR ( 0x0008, 0x0018, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0008, 0x0016))
+ {
+ vr = new VR ( 0x0008, 0x0016, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000d))
+ {
+ vr = new VR ( 0x0020, 0x000d, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000e))
+ {
+ vr = new VR ( 0x0020, 0x000e, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0800))
+ {
+ vr = new VR ( 0x9999, 0x0800, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0801))
+ {
+ vr = new VR ( 0x9999, 0x0801, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ QueryOnImage(DDOPtr, ADDO);
+ if(!ADDO->GetSize())
+ return(FALSE);
+ OperatorConsole.printf("Number of Images to send: %d\n", ADDO->GetSize());
+ return(TRUE);
+ }
+
+BOOL MyPatientStudyOnlyRetrieveGeneric :: QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO)
+ {
+ char dest[20];
+ memset(dest, 0, 20);
+ VR *vr = DCO->GetVR(0x0000, 0x0600);
+ if (vr) memcpy(dest, (char *)(vr->Data), vr->Length);
+ while (strlen(dest)>0 && dest[strlen(dest)-1]==' ') dest[strlen(dest)-1] = 0;
+
+ return CallImportConverterN(DDO, 1200, NULL, dest, NULL, NULL, (ExtendedPDU_Service *)PDU, NULL, NULL)!=2;
+ }
+
+BOOL MyPatientStudyOnlyRetrieveGeneric :: SearchOn (
+ DICOMDataObject *DDOPtr,
+ Array < DICOMDataObject * > *ADDO)
+ {
+ VR *vr;
+ UINT16 mask;
+
+ prefetcher(DDOPtr, TRUE);
+
+ SystemDebug.printf("MyPatientStudyOnlyRetrieveGeneric :: SearchOn\n");
+ if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr);
+
+ mask = DDOPtr->GetUINT16(0x9999, 0x0802);
+ if (!mask) mask = 0xffff;
+
+ for (int i=0; i<10; i++)
+ if (mask & (1<<i))
+ VirtualQueryToDB(DDOPtr, i);
+
+ if(!DDOPtr->GetVR(0x0008, 0x0018))
+ {
+ vr = new VR ( 0x0008, 0x0018, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0008, 0x0016))
+ {
+ vr = new VR ( 0x0008, 0x0016, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000d))
+ {
+ vr = new VR ( 0x0020, 0x000d, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x0020, 0x000e))
+ {
+ vr = new VR ( 0x0020, 0x000e, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0800))
+ {
+ vr = new VR ( 0x9999, 0x0800, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ if(!DDOPtr->GetVR(0x9999, 0x0801))
+ {
+ vr = new VR ( 0x9999, 0x0801, 0, FALSE );
+ DDOPtr->Push(vr);
+ }
+ QueryOnImage(DDOPtr, ADDO);
+ if(!ADDO->GetSize())
+ return(FALSE);
+ OperatorConsole.printf("Number of Images to send: %d\n", ADDO->GetSize());
+ return(TRUE);
+ }
+
+BOOL MyPatientRootRetrieve :: CallBack (
+ DICOMCommandObject *DCOPtr,
+ DICOMDataObject *DDOPtr)
+ {
+ UNUSED_ARGUMENT(DCOPtr);
+ UNUSED_ARGUMENT(DDOPtr);
+ return ( TRUE );
+ }
+
+BOOL MyPatientRootRetrieveNKI :: CallBack (
+ DICOMCommandObject *DCOPtr,
+ DICOMDataObject *DDOPtr)
+ {
+ UNUSED_ARGUMENT(DCOPtr);
+ UNUSED_ARGUMENT(DDOPtr);
+ return ( TRUE );
+ }
+
+BOOL MyPatientRootRetrieveGeneric :: CallBack (
+ DICOMCommandObject *DCOPtr,
+ DICOMDataObject *DDOPtr)
+ {
+ UNUSED_ARGUMENT(DCOPtr);
+ UNUSED_ARGUMENT(DDOPtr);
+ return ( TRUE );
+ }
+
+BOOL MyStudyRootRetrieve :: CallBack (
+ DICOMCommandObject *DCOPtr,
+ DICOMDataObject *DDOPtr)
+ {
+ UNUSED_ARGUMENT(DCOPtr);
+ UNUSED_ARGUMENT(DDOPtr);
+ return ( TRUE );
+ }
+
+BOOL MyStudyRootRetrieveNKI :: CallBack (
+ DICOMCommandObject *DCOPtr,
+ DICOMDataObject *DDOPtr)
+ {
+ UNUSED_ARGUMENT(DCOPtr);
+ UNUSED_ARGUMENT(DDOPtr);
+ return ( TRUE );
+ }
+
+BOOL MyStudyRootRetrieveGeneric :: CallBack (
+ DICOMCommandObject *DCOPtr,
+ DICOMDataObject *DDOPtr)
+ {
+ UNUSED_ARGUMENT(DCOPtr);
+ UNUSED_ARGUMENT(DDOPtr);
+ return ( TRUE );
+ }
+
+BOOL MyPatientStudyOnlyRetrieve :: CallBack (
+ DICOMCommandObject *DCOPtr,
+ DICOMDataObject *DDOPtr)
+ {
+ UNUSED_ARGUMENT(DCOPtr);
+ UNUSED_ARGUMENT(DDOPtr);
+ return ( TRUE );
+ }
+
+BOOL MyPatientStudyOnlyRetrieveNKI :: CallBack (
+ DICOMCommandObject *DCOPtr,
+ DICOMDataObject *DDOPtr)
+ {
+ UNUSED_ARGUMENT(DCOPtr);
+ UNUSED_ARGUMENT(DDOPtr);
+ return ( TRUE );
+ }
+
+BOOL MyPatientStudyOnlyRetrieveGeneric :: CallBack (
+ DICOMCommandObject *DCOPtr,
+ DICOMDataObject *DDOPtr)
+ {
+ UNUSED_ARGUMENT(DCOPtr);
+ UNUSED_ARGUMENT(DDOPtr);
+ return ( TRUE );
+ }
+
+/* Read ahead implementation */
+
+#define STATUS_EMPTY 0
+#define STATUS_FAILED 1
+#define STATUS_READ 2
+#define STATUS_RETRIEVED 3
+#define STATUS_BUSY 4
+
+struct ReadAheadThreadData
+ {
+ char *SOPs;
+ char *Studies;
+ char *Series;
+ char *ObjectFiles;
+ char *Devices;
+ int *volatile Status;
+ char *pats;
+ int NumToRead;
+ DICOMDataObject **DDOOutPtr;
+ Database *DB;
+ int iVrSizeLimit;
+#ifdef WIN32
+ HANDLE Handle;
+#else
+ pthread_t Handle;
+#endif
+ DICOMCommandObject *pDCO;
+ char *Filenames;
+ volatile BOOL Busy;
+ volatile BOOL ForceEnd;
+ volatile BOOL TimeOut;
+ char *FullFilenames;
+ int filesmissing;
+ int numreadahead;
+ int overlap;
+ volatile BOOL reverse;
+ };
+
+#ifdef WIN32
+#define NULLHANDLE NULL
+#else
+#define NULLHANDLE 0
+#endif
+
+// to process any recieved data during virtual server operation
+// call once in a while during virtual reception of data
+
+static int ProcessRATData(struct ReadAheadThreadData *ratd, int maxfiles)
+ {
+ char FullFilename[1024];
+ ExtendedPDU_Service PDU;
+ int len, UseChapter10=0, i, k;
+ DICOMDataObject *DDOOut;
+
+ // count files in memory and limit to 2 * OverlapVirtualGet
+ k = 0;
+ for (i=0; i<ratd->NumToRead; i++)
+ if (ratd->Status[i]==STATUS_READ) ++k;
+ if (k>=maxfiles) return 0;
+
+ PDU.AttachRTC(&VRType);
+
+ // find images ready to read from start of list
+ for (i=0; i<ratd->NumToRead; i++)
+ {
+ if (ratd->Status[i]!=STATUS_EMPTY) continue; // already processed
+
+ ratd->Status[i]=STATUS_BUSY;
+ if (*(ratd->FullFilenames+i*1024)==0) // retry; may have been collected by virtual server
+ {
+ GetPhysicalDevice(ratd->Devices + i * 32, FullFilename);
+ strcat(FullFilename, ratd->ObjectFiles + i * 256);
+ if (!DFileExists(FullFilename))
+ { ratd->Status[i]=STATUS_EMPTY; // stop at hole
+ break;
+ }
+ }
+ else
+ strcpy(FullFilename, ratd->FullFilenames + i*1024);
+
+ len = strlen(FullFilename);
+ if (len>4)
+ UseChapter10 = (stricmp(FullFilename+len-4, ".v2")!=0) || NoDicomCheck;
+
+ if (ratd->ForceEnd)
+ {
+ ratd->Status[i]=STATUS_EMPTY;
+ return k;
+ }
+
+ if (*TestMode) strcat(FullFilename, TestMode);
+
+ int t = (int)time(NULL);
+ if (!UseChapter10)
+ DDOOut = LoadImplicitLittleEndianFile(FullFilename, ratd->iVrSizeLimit);
+ else
+ DDOOut = PDU.LoadDICOMDataObject(FullFilename);
+ LoadTime += (int)time(NULL)-t;
+
+ if (!DDOOut)
+ {
+ ratd->Status[i]=STATUS_EMPTY;
+ break;
+ }
+
+ if (ratd->ForceEnd)
+ {
+ delete DDOOut;
+ ratd->Status[i]=STATUS_EMPTY;
+ return k;
+ }
+
+ t = (int)time(NULL);
+ ProcessDDO(&DDOOut, ratd->pDCO, &PDU);
+ ProcessTime += (int)time(NULL)-t;
+
+ strcpy(ratd->Filenames + i*1024, FullFilename);
+ ratd->DDOOutPtr[i] = DDOOut;
+ ratd->Status[i] = STATUS_READ;
+ SystemDebug.printf("ProcessRATData: overlap read > %04d\n", i);
+
+ if (++k >= maxfiles) break;
+ }
+
+ // find images ready to read from end of list (sometimes PACS deliver in reversed order)
+ for (i=ratd->NumToRead-1; i>=0; i--)
+ {
+ if (ratd->Status[i]!=STATUS_EMPTY) continue;
+
+ ratd->Status[i]=STATUS_BUSY;
+ if (*(ratd->FullFilenames+i*1024)==0)
+ {
+ GetPhysicalDevice(ratd->Devices + i * 32, FullFilename);
+ strcat(FullFilename, ratd->ObjectFiles + i * 256);
+ if (!DFileExists(FullFilename))
+ { ratd->Status[i]=STATUS_EMPTY;
+ break;
+ }
+ }
+ else
+ strcpy(FullFilename, ratd->FullFilenames + i*1024);
+
+ len = strlen(FullFilename);
+ if (len>4)
+ UseChapter10 = (stricmp(FullFilename+len-4, ".v2")!=0) || NoDicomCheck;
+
+ if (ratd->ForceEnd)
+ {
+ ratd->Status[i]=STATUS_EMPTY;
+ return k;
+ }
+
+ if (*TestMode) strcat(FullFilename, TestMode);
+
+ int t = (int)time(NULL);
+ if (!UseChapter10)
+ DDOOut = LoadImplicitLittleEndianFile(FullFilename, ratd->iVrSizeLimit);
+ else
+ DDOOut = PDU.LoadDICOMDataObject(FullFilename);
+ LoadTime += (int)time(NULL)-t;
+
+ if (!DDOOut)
+ {
+ ratd->Status[i]=STATUS_EMPTY;
+ break;
+ }
+
+ if (ratd->ForceEnd)
+ {
+ delete DDOOut;
+ ratd->Status[i]=STATUS_EMPTY;
+ return k;
+ }
+
+ t = (int)time(NULL);
+ ProcessDDO(&DDOOut, ratd->pDCO, &PDU);
+ ProcessTime += (int)time(NULL)-t;
+
+ strcpy(ratd->Filenames + i*1024, FullFilename);
+ ratd->DDOOutPtr[i] = DDOOut;
+ ratd->Status[i] = STATUS_READ;
+ SystemDebug.printf("ProcessRATData: overlap read > %04d\n", i);
+
+ if (++k >= maxfiles) break;
+ }
+
+ return k;
+ }
+
+// same as VirtualServer but splits virtual query in one request per series
+BOOL VirtualServer2(struct ReadAheadThreadData *ratd, int N)
+ {
+ char AE[48];
+ strcpy(AE, VirtualServerFor[N]);
+ BOOL PerSeries = VirtualServerPerSeries[N];
+ if (*AE==0) return FALSE;
+
+ char *param = strchr(AE, ',');
+ if (param) *param++ = 0;
+
+ unsigned char ip[64], port[64], compress[64];
+ VR *vr;
+ char SOP[66];
+ DICOMCommandObject DCO, DCOR2;
+ DICOMDataObject DDO, DDOR2;
+ LE_UINT16 command, datasettype, messageid=3, priority;
+ UID uid;
+ int quit, i, j, ims=0;
+ unsigned int k;
+ ExtendedPDU_Service PDU2;
+ char *sops, *p;
+ int *seriesnum;
+ char pats[66], series[66], studies[66], szTemp[64], szRootSC[64];
+
+ MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile);
+ MyGetPrivateProfileString(szRootSC, "OverlapVirtualGet", "0", szTemp, 64, ConfigFile);
+ ratd->overlap = atoi(szTemp);
+
+ OperatorConsole.printf("Virtual server - collecting %d missing objects from %s\n", ratd->filesmissing, AE);
+
+ PDU2.AttachRTC(&VRType);
+ if(!GetACRNema(AE, (char *)ip, (char *)port, (char *)compress))
+ return FALSE;
+
+ PDU2.ClearAbstractSyntaxs();
+ PDU2.SetLocalAddress(MYACRNEMA);
+ PDU2.SetRemoteAddress((unsigned char *)AE);
+
+ uid.Set("1.2.840.10008.3.1.1.1"); // Application context (DICOM App)
+ PDU2.SetApplicationContext(uid);
+
+ uid.Set("1.2.840.10008.5.1.4.1.2.2.2"); // StudyRootRetrieve (C-Move SOP)
+ PDU2.AddAbstractSyntax(uid);
+
+ PDU2.SetTimeOut(TCPIPTimeOut);
+
+ // Make association for MOVE on port/ip
+ if(!PDU2.Connect(ip, port))
+ {
+ PDU2.Close();
+ OperatorConsole.printf("*** Virtual server - failed to connect %s (%s %s) for C-MOVE\n", AE, ip, port);
+ return(FALSE);
+ }
+
+ // collect move requests together if possible (same series)
+ sops = (char *)malloc(66*ratd->NumToRead); sops[0]=0;
+ seriesnum = (int *)malloc(sizeof(int)*(ratd->NumToRead+1)); memset(seriesnum, 0, sizeof(int)*(ratd->NumToRead+1));
+
+ pats[0]=series[0]=studies[0] = 0;
+ j = 1;
+
+ if (ratd->NumToRead)
+ {
+ strcpy(pats , ratd->pats +0*66);
+ strcpy(studies, ratd->Studies+0*66);
+ strcpy(series , ratd->Series +0*66);
+ }
+
+ for (i=0; i<ratd->NumToRead; i++)
+ {
+ if (*(ratd->FullFilenames+i*1024)) continue; // present (keeps seriesnum to 0)
+
+ p = strchr(ratd->Devices+i*32, '.');
+ if (p && atoi(p+1)!=N) continue; // not on this server (keeps seriesnum to 0)
+
+ if (strcmp(pats, ratd->pats +i*66) || // next series to collect ?
+ strcmp(studies, ratd->Studies+i*66) ||
+ strcmp(series, ratd->Series +i*66))
+ {
+ strcpy(pats , ratd->pats +i*66);
+ strcpy(studies, ratd->Studies+i*66);
+ strcpy(series , ratd->Series +i*66);
+ j++;
+ }
+
+ seriesnum[i] = j; // this loop sets it to e.g., 111101220222333330
+ // or 00000000000000000000000010000000000000000
+ }
+
+ // perform one or more c-move requests (sops = all sops for this move; j = series#, k = number of images collected)
+ sops[0]=0; j=1; k=0;
+ for (i=0; i<=ratd->NumToRead; i++)
+ {
+ // image does not need to be to be retrieved (do not continue for the last cycle; always needs to retrieve)
+ if (i<ratd->NumToRead && seriesnum[i]==0)
+ continue;
+
+ // image i is from a new series, send series belonging to image i-1
+ else if ( (j!=seriesnum[i] && k>0)
+ || (k>=64) // limit to 64 images per move
+ )
+ {
+ DCO.Reset();
+ DDO.Reset();
+
+ // move missing file to this server
+ strcpy((char*) SOP, "1.2.840.10008.5.1.4.1.2.2.2"); // StudyRootMove (C-Move SOP)
+ vr = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE);
+ DCO.Push(vr);
+ command = 0x0021;
+ vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE);
+ DCO.Push(vr);
+ priority = 0; // MEDIUM
+ vr = new VR (0x0000, 0x0700, 0x0002, &priority, FALSE);
+ DCO.Push(vr);
+ datasettype = 0x0102;
+ vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE);
+ DCO.Push(vr);
+ messageid++;
+ vr = new VR (0x0000, 0x0110, 0x0002, &messageid, FALSE);
+ DCO.Push(vr);
+ vr = new VR(0x0000, 0x0600, 16, (void*)MYACRNEMA, FALSE);
+ DCO.Push(vr);
+
+ // Data object. Query level is image or series; ask for patient ID and SopInstanceUID
+ // use IMAGE level only if PerSeries=0 or #images < PerSeries (e.g., allow max 1000 sops to be sent as IMAGE move)
+ if (PerSeries && k>PerSeries) SetStringVR(&vr, 0x0008, 0x0052, "SERIES");
+ else SetStringVR(&vr, 0x0008, 0x0052, "IMAGE");
+ DDO.Push(vr);
+
+ // send images collected in sops (or one series) with patient etc from previous image
+ // send sops only if PerSeries=0 or #images < PerSeries (e.g., allow max 1000 sops to be sent)
+ // 20131103: made it <= instead of > such that check few lines above is exact inverse
+ if (!PerSeries || k<=PerSeries)
+ {
+ // for safety: it could be that we need to collect 0 images
+ if (strlen(sops)>0) sops[strlen(sops)-1]=0;
+ SetStringVR(&vr, 0x0008, 0x0018, sops);
+ DDO.Push(vr);
+ }
+ SetStringVR(&vr, 0x0010, 0x0020, ratd->pats+(i-1)*66);
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0020, 0x000d, ratd->Studies+(i-1)*66);
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0020, 0x000e, ratd->Series+(i-1)*66);
+ DDO.Push(vr);
+
+ // Here fixkodak fiximage should operate adding 0 to e.g., 9901234 patient ID
+ if (param)
+ if (strstr(param, "FIXKODAK") || strstr(param, "fixkodak"))
+ KodakFixer(&DDO, TRUE);
+ CallImportConverterN(&DDO, 2300, NULL, NULL, NULL, NULL, &PDU2, NULL, NULL);
+
+ // Write command object and data object
+ PDU2.Write(&DCO, uid);
+
+ if (DebugLevel>3)
+ {
+ SystemDebug.printf("Move request sent to virtual server %s (VirtualServerPerSeries = %d):\n", AE, PerSeries);
+ NonDestructiveDumpDICOMObject(&DDO);
+ }
+
+ PDU2.Write(&DDO, uid);
+
+ // Get response and count collected images
+ quit = 0;
+ while(!quit)
+ {
+ if(!PDU2.Read(&DCOR2))
+ {
+ OperatorConsole.printf("*** Virtual server - C-MOVE association lost to %s\n", AE);
+ quit=2; // error (flag not yet used)
+ }
+ if(DCOR2.GetUINT16(0x0000, 0x0100)!=0x8021)
+ {
+ OperatorConsole.printf("*** Virtual server - C-MOVE got a wrong response from %s\n", AE);
+ quit=3; // error (flag not yet used)
+ }
+ // ignore the data set
+ if(DCOR2.GetUINT16(0x0000, 0x0800)!=0x0101)
+ {
+ PDU2.Read(&DDOR2);
+ DDOR2.Reset();
+ }
+ if(DCOR2.GetUINT16(0x0000, 0x0900)==0x0000) // success ?
+ {
+ OperatorConsole.printf("Virtual server - Grabbed %d images for %s from %s\n", ims, pats, AE);
+ quit=1;
+ }
+ else if (DCOR2.GetUINT16(0x0000, 0x0900)==0xff00) // continuing no problem
+ {
+ ims++;
+ if (ratd->ForceEnd)
+ {
+ /* Send a CANCEL message... */
+ DCO.Reset();
+ command = 0x0fff; // C_CANCEL_MOVE_RQ
+ vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE);
+ DCO.Push(vr);
+ messageid = 5; // MsgID of original MOVE_RQ
+ vr = new VR (0x0000, 0x0120, 0x0002, &messageid, FALSE);
+ DCO.Push(vr);
+ datasettype = 0x0101; // No DataSet is present
+ vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE);
+ DCO.Push(vr);
+ PDU2.Write(&DCO, uid);
+ /* ... and drop the connection. */
+ goto EXIT;
+ }
+ if (ratd->overlap)
+ if ((ims%ratd->overlap)==0)
+ ProcessRATData(ratd, ratd->overlap); // parallel process some data
+ }
+ else
+ {
+ int RemoteError = DCOR2.GetUINT16(0x0000, 0x0900);
+ OperatorConsole.printf("*** Virtual server - remote C-MOVE DICOM Error code %x (%d) from %s\n", RemoteError, RemoteError, AE);
+ NonDestructiveDumpDICOMObject(&DCOR2);
+ quit=4; // error (flag not yet used)
+ }
+ DCOR2.Reset();
+ }
+
+ // start a new move for a new series
+ sops[0]=0; k=0;
+ // rare virtualserver crash 2; a if was needed but now not because I made seriesnum one longer
+ j = seriesnum[i];
+ }
+
+ // append image sop to series
+ if (i<ratd->NumToRead)
+ {
+ strcat(sops, ratd->SOPs+i*66);
+ strcat(sops, "\\");
+ k++;
+ }
+ }
+
+EXIT:
+ free(sops);
+ free(seriesnum);
+ PDU2.Close();
+
+ ratd->filesmissing -= ims; // how many are left ?
+ return (ratd->filesmissing==0); // all missing images retrieved? -> OK
+ }
+
+static BOOL WINAPI ReadAheadThread(struct ReadAheadThreadData *ratd)
+ {
+ char FullFilename[1024];
+ char Filename[1024];
+ char Device[256];
+ ExtendedPDU_Service PDU;
+ int len, UseChapter10=0, i, j, k, ir;
+ DICOMDataObject *DDOOut;
+
+ ratd->filesmissing=0;
+
+ PDU.AttachRTC(&VRType);
+
+ // Check if all files are there and generate their full filenames
+
+ ratd->FullFilenames = (char *)malloc(ratd->NumToRead * 1024);
+
+ for (i=0; i<ratd->NumToRead; i++)
+ {
+ strcpy(Filename, ratd->ObjectFiles + i * 256);
+ strcpy(Device, ratd->Devices + i * 32);
+
+ if (!FindPhysicalDevice(Device, ratd->FullFilenames+i*1024, Filename))
+ {
+ *(ratd->FullFilenames+i*1024)=0;
+ ratd->filesmissing++;
+ }
+ else
+ strcat(ratd->FullFilenames+i*1024, Filename);
+ }
+
+ // virtual server: grab images in db but not on disk from other server; send them; and optionally delete them
+
+ if (ratd->filesmissing>0 && !ratd->ForceEnd)
+ {
+ for (int i1=0; i1<10; i1++)
+ if (VirtualServer2(ratd, i1))
+ { break;
+ }
+ }
+
+ // double check that files are indeed missing; may have been miscounted by VirtualServer2 (if too few c-move callbacks)
+ if (ratd->filesmissing>0)
+ {
+ ratd->filesmissing = 0;
+ for (int i1=0; i1<ratd->NumToRead; i1++)
+ if (*(ratd->FullFilenames+i1*1024)==0)
+ {
+ strcpy(Filename, ratd->ObjectFiles + i1 * 256);
+ strcpy(Device, ratd->Devices + i1 * 32);
+ if (!FindPhysicalDevice(Device, FullFilename, Filename)) ratd->filesmissing++;
+ }
+ }
+
+ if (ratd->filesmissing>0)
+ {
+ OperatorConsole.printf("*** Failed to retrieve some files:\n");
+ for (int i1=0; i1<ratd->NumToRead; i1++)
+ if (*(ratd->FullFilenames+i1*1024)==0)
+ {
+ strcpy(Filename, ratd->ObjectFiles + i1 * 256);
+ strcpy(Device, ratd->Devices + i1 * 32);
+
+ if (!FindPhysicalDevice(Device, ratd->FullFilenames+i1*1024, Filename))
+ {
+ OperatorConsole.printf("*** missing file: %s %s\n", Device, Filename);
+ if (strlen(Device)>3 && Device[4]=='.')
+ DeleteImage(ratd->SOPs+i1*66, TRUE); // e.g. MAG0.0
+ }
+ else
+ strcat(ratd->FullFilenames+i1*1024, Filename); // was missing added 20131030
+ }
+ }
+
+ k=0;
+ for (i=0; i<ratd->NumToRead; i++)
+ {
+ if (ratd->reverse) ir = ratd->NumToRead-1-i;
+ else ir = i;
+ if (ratd->Status[ir]!=STATUS_EMPTY) continue;
+ ratd->Status[ir]=STATUS_BUSY;
+
+ if (*(ratd->FullFilenames+ir*1024)==0) // retry; may have been collected by virtual server
+ {
+ strcpy(Filename, ratd->ObjectFiles + ir * 256);
+ strcpy(Device, ratd->Devices + ir * 32);
+
+ if (!FindPhysicalDevice(Device, FullFilename, Filename))
+ {
+ OperatorConsole.printf("***Could still not find file: %s\n", Filename);
+ ratd->Status[ir]=STATUS_FAILED;
+ continue;
+ }
+/* {
+ OperatorConsole.printf("***Could not find file:%s\n", Filename);
+ free(ratd->FullFilenames);
+
+ // mvh 20060401: fix hang condition when a read ahead failed
+ ratd->Busy = FALSE;
+ ratd->TimeOut = TRUE;
+
+ return FALSE;
+ }
+*/
+ strcat(FullFilename, Filename);
+ }
+ else
+ strcpy(FullFilename, ratd->FullFilenames + ir*1024);
+
+ len = strlen(FullFilename);
+ if (len>4)
+ UseChapter10 = (stricmp(FullFilename+len-4, ".v2")!=0) || NoDicomCheck;
+
+ if (ratd->ForceEnd)
+ { ratd->Status[ir]=STATUS_FAILED;
+ goto TimeOut;
+ }
+
+ if (*TestMode) strcat(FullFilename, TestMode);
+
+ int t = (int)time(NULL);
+ if (!UseChapter10)
+ DDOOut = LoadImplicitLittleEndianFile(FullFilename, ratd->iVrSizeLimit);
+ else
+ DDOOut = PDU.LoadDICOMDataObject(FullFilename);
+ LoadTime += (int)time(NULL)-t;
+
+ if (!DDOOut)
+ // mvh 20060401: fix hang condition when a read ahead failed
+ {
+ OperatorConsole.printf("***Could not read file:%s\n", Filename);
+ ratd->Status[ir]=STATUS_FAILED;
+ continue;
+/* ratd->Busy = FALSE;
+ ratd->TimeOut = TRUE;
+ free(ratd->FullFilenames);
+ return FALSE;
+*/
+ }
+
+ if (!CacheVirtualData)
+ {
+ if (ratd->Status[ir]==STATUS_RETRIEVED) // if virtual server retrieved data
+ unlink(FullFilename); // delete data if not caching
+ }
+
+ if (ratd->ForceEnd)
+ {
+ delete DDOOut;
+ ratd->Status[ir]=STATUS_EMPTY;
+ goto TimeOut;
+ }
+
+ t = (int)time(NULL);
+ ProcessDDO(&DDOOut, ratd->pDCO, &PDU);
+ ProcessTime += (int)time(NULL)-t;
+
+ strcpy(ratd->Filenames + ir*1024, FullFilename);
+ ratd->DDOOutPtr[ir] = DDOOut;
+ ratd->Status[ir] = STATUS_READ;
+ SystemDebug.printf("ReadAheadThread: readahead > %04d\n", ir);
+
+ k = 0;
+ for (j=0; j<ratd->NumToRead; j++)
+ if (ratd->Status[j]==STATUS_READ)
+ k++;
+
+ int m=0;
+ while (k>ratd->numreadahead+ratd->overlap+2)
+ {
+ if (ratd->ForceEnd) goto TimeOut;
+ //printf(".");
+ Sleep(10);
+ k = 0;
+ for (j=0; j<ratd->NumToRead; j++)
+ if (ratd->Status[j]==STATUS_READ)
+ k++;
+ if (++m>100)
+ { SystemDebug.printf("ReadAheadThread: warning - resolving deadlock due to erratic incoming order\n");
+ break;
+ }
+ }
+
+ // Make the thread wait when it is further than numreadahead slices ahead - self timeout is disabled
+ /* j = 0;
+ while (ir>=ratd->numreadahead && ratd->DDOOutPtr[i-ratd->numreadahead] && ratd->SOPs[(ir-ratd->numreadahead)*66]!=0)
+ {
+ if (ratd->ForceEnd) goto TimeOut;
+ Sleep(1);
+ //printf(".");
+ //if (j++ > 5000) goto TimeOut;
+ } */
+ }
+
+ ratd->Busy = FALSE;
+ free(ratd->FullFilenames);
+ return TRUE;
+
+ // Happens when the client hangs up the TCP/IP connection (signalled by ForceEnd)
+TimeOut:
+ ratd->TimeOut = TRUE;
+ ratd->Busy = FALSE;
+ free(ratd->FullFilenames);
+ return TRUE;
+ }
+
+BOOL
+RetrieveOn (
+ DICOMDataObject *DDOMask,
+ DICOMDataObject **DDOOutPtr,
+ StandardStorage **SStorage,
+ RunTimeClassStorage &RTCStorage,
+ DICOMCommandObject *pDCO = NULL,
+ Array < DICOMDataObject *> *pADDO = NULL,
+ void *ExtraBytes = NULL)
+ {
+ VR *vr1;
+ char FullFilename[1024];
+ char Filename[1024];
+ char Device[256];
+ ExtendedPDU_Service PDU;
+ int len, UseChapter10=0, i, j;
+ VR* pVR;
+ unsigned int iVrSizeLimit;
+#ifdef WIN32
+ unsigned long ThreadID;
+#endif
+ struct ReadAheadThreadData *ratd;
+ DICOMDataObject *tt;
+
+ PDU.AttachRTC(&VRType);
+
+ ratd = (struct ReadAheadThreadData *)ExtraBytes;
+
+ // assume read will fail unless proven otherwise
+ *DDOOutPtr = NULL;
+
+ // This line will disable the read ahead thread
+ if (!EnableReadAheadThread || NoThread) pADDO = NULL;
+
+ // mvh 20060401: fix hang condition when a read ahead failed
+ if (ratd->TimeOut) return FALSE;
+
+ // start read ahead thread when first slice of more than (one:normal, zero:virtual server) is requested
+ if (pADDO && pADDO->Get(0)==DDOMask && pADDO->GetSize() > 0)
+ {
+ VR *vr;
+
+ iVrSizeLimit = 0xffffffff;
+ if (pDCO)
+ {
+ pVR = pDCO->GetVR(0x9999, 0x0100);
+ if (pVR)
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ iVrSizeLimit = (unsigned int)(*((unsigned int*)pVR->Data));
+#else //Big Endian like Apple power pc
+ iVrSizeLimit = SwitchEndian((unsigned int)(*((unsigned int*)pVR->Data)));
+#endif
+ }
+
+ // wait for thread to end from possible previous move on same association
+ while (ratd->Busy)
+ {
+ Sleep(10);
+ //printf(".");
+ }
+
+ // free memory of thread if not already done so
+ if (ratd->Devices)
+ {
+ if (ratd->pDCO) delete ratd->pDCO; ratd->pDCO = NULL;
+ for (i=0; i<ratd->NumToRead; i++)
+ if (ratd->DDOOutPtr[i])
+ delete ratd->DDOOutPtr[i];
+ free(ratd->DDOOutPtr); ratd->DDOOutPtr = NULL;
+ free(ratd->Filenames); ratd->Filenames = NULL;
+ free(ratd->ObjectFiles);ratd->ObjectFiles = NULL;
+ free(ratd->Devices); ratd->Devices = NULL;
+ free(ratd->Status); ratd->Status = NULL;
+ free(ratd->SOPs); ratd->SOPs = NULL;
+ free(ratd->Series); ratd->Series = NULL;
+ free(ratd->Studies); ratd->Studies = NULL;
+ free(ratd->pats); ratd->pats = NULL;
+ CloseHandle(ratd->Handle); ratd->Handle = NULLHANDLE;
+ }
+
+ // initialize thread data
+ ratd->Busy = TRUE;
+ ratd->TimeOut = FALSE;
+ if (pDCO)
+ ratd->pDCO = (DICOMCommandObject *)MakeCopy((DICOMDataObject *)pDCO);
+
+ ratd->numreadahead = EnableReadAheadThread<2 ? 5 : EnableReadAheadThread;
+ ratd->overlap = 0;
+ ratd->NumToRead = pADDO->GetSize();
+ ratd->SOPs = (char *) malloc(ratd->NumToRead * 66);
+ ratd->Series = (char *) malloc(ratd->NumToRead * 66);
+ ratd->Studies= (char *) malloc(ratd->NumToRead * 66);
+ ratd->pats = (char *) malloc(ratd->NumToRead * 66);
+ ratd->ObjectFiles = (char *) malloc(ratd->NumToRead * 256);
+ ratd->Devices = (char *) malloc(ratd->NumToRead * 32);
+ ratd->Status = (int *) malloc(ratd->NumToRead * sizeof(int));
+ memset(ratd->SOPs, 0, ratd->NumToRead * 66);
+ memset(ratd->Series, 0, ratd->NumToRead * 66);
+ memset(ratd->Studies, 0, ratd->NumToRead * 66);
+ memset(ratd->pats, 0, ratd->NumToRead * 66);
+ memset(ratd->ObjectFiles, 0, ratd->NumToRead * 256);
+ memset(ratd->Devices, 0, ratd->NumToRead * 32);
+ memset((char *)ratd->Status, 0, ratd->NumToRead * sizeof(int));
+
+ for (i=0; i<ratd->NumToRead; i++)
+ {
+ tt = pADDO->Get(i);
+ vr = tt->GetVR(0x9999, 0x0800);
+ if (vr)
+ {
+ memcpy(ratd->ObjectFiles+i*256, vr->Data, vr->Length);
+ if (vr->Length && (ratd->ObjectFiles+i*256)[vr->Length-1]==' ') (ratd->ObjectFiles+i*256)[vr->Length-1] = 0;
+ }
+
+ vr = tt->GetVR(0x9999, 0x0801);
+ if (vr)
+ {
+ memcpy(ratd->Devices+i*32, vr->Data, vr->Length);
+ if (vr->Length && (ratd->Devices+i*32)[vr->Length-1]==' ') (ratd->Devices+i*32)[vr->Length-1] = 0;
+ }
+
+ vr = tt->GetVR(0x0008, 0x0018);
+ if (vr) memcpy(ratd->SOPs+i*66, vr->Data, vr->Length);
+
+ vr = tt->GetVR(0x0020, 0x000d);
+ if (vr) memcpy(ratd->Studies+i*66, vr->Data, vr->Length);
+
+ vr = tt->GetVR(0x0020, 0x000e);
+ if (vr) memcpy(ratd->Series+i*66, vr->Data, vr->Length);
+
+ vr = tt->GetVR(0x0010, 0x0020);
+ if (vr)
+ {
+ memcpy(ratd->pats+i*66, vr->Data, vr->Length);
+ if (vr->Length && (ratd->pats+i*66)[vr->Length-1]==' ') (ratd->pats+i*66)[vr->Length-1] = 0;
+ }
+ }
+
+ ratd->iVrSizeLimit = iVrSizeLimit;
+
+ ratd->DDOOutPtr = (DICOMDataObject **) malloc(ratd->NumToRead * sizeof(DICOMDataObject *));
+ memset(ratd->DDOOutPtr, 0, ratd->NumToRead * sizeof(DICOMDataObject *));
+
+ ratd->Filenames = (char *) malloc(ratd->NumToRead * 1024);
+ memset(ratd->Filenames, 0, ratd->NumToRead * 1024);
+ ratd->reverse=FALSE;
+
+ // start the thread
+#ifdef WIN32
+ ratd->Handle = CreateThread(NULL, 0x000ff000,
+ (LPTHREAD_START_ROUTINE) ReadAheadThread,
+ ratd, 0, &ThreadID);
+#else
+ pthread_create(&ratd->Handle, NULL, (void*(*)(void*))ReadAheadThread, (void *)ratd);
+ pthread_detach(ratd->Handle);
+#endif
+ }
+
+
+ // Get an item from the read ahead thread if it is running
+ if (pADDO && ratd->Handle!=NULLHANDLE && !ratd->TimeOut)
+ {
+ j = 0;
+ while (!ratd->TimeOut)
+ {
+ for (i=0; i<ratd->NumToRead; i++)
+ {
+ if (!ratd->reverse && (ratd->Status[i]==STATUS_READ || ratd->Status[i]==STATUS_FAILED) && pADDO->Get(i)==DDOMask)
+ {
+ *DDOOutPtr = ratd->DDOOutPtr[i];
+ strcpy(Filename, ratd->Filenames + i*1024);
+ ratd->Status[i] = STATUS_RETRIEVED;
+ SystemDebug.printf("RetrieveOn: givenout < %04d\n", i);
+
+ // if it is the last item wait for the thread to end and free the memory
+ if (pADDO->Get(ratd->NumToRead-1)==DDOMask) // && i==ratd->NumToRead-1 && ratd->Status[i] == STATUS_RETRIEVED)
+ {
+ while (1)
+ {
+ ratd->ForceEnd = TRUE;
+#ifdef WIN32
+ if (WaitForSingleObject(ratd->Handle, 10) != WAIT_TIMEOUT) break;
+ if (j++ > 200*100) break;
+#else
+ while(ratd->Busy) Sleep(10);
+ if (j++ > 200*100) break;
+#endif
+ }
+ if (ratd->pDCO) delete ratd->pDCO; ratd->pDCO = NULL;
+ free(ratd->DDOOutPtr); ratd->DDOOutPtr = NULL;
+ free(ratd->Filenames); ratd->Filenames = NULL;
+ free(ratd->SOPs); ratd->SOPs = NULL;
+ free(ratd->Series); ratd->Series = NULL;
+ free(ratd->Studies); ratd->Studies = NULL;
+ free(ratd->pats); ratd->pats = NULL;
+ free(ratd->ObjectFiles); ratd->ObjectFiles = NULL;
+ free(ratd->Devices); ratd->Devices = NULL;
+ free(ratd->Status); ratd->Status = NULL;
+ CloseHandle(ratd->Handle); ratd->Handle = NULLHANDLE;
+ }
+
+ goto further;
+ }
+ if ( (ratd->Status[ratd->NumToRead-1-i]==STATUS_READ || ratd->Status[ratd->NumToRead-1-i]==STATUS_FAILED) && pADDO->Get(i)==DDOMask)
+ {
+ ratd->reverse = TRUE;
+ *DDOOutPtr = ratd->DDOOutPtr[ratd->NumToRead-1-i];
+ strcpy(Filename, ratd->Filenames + (ratd->NumToRead-1-i)*1024);
+ ratd->Status[ratd->NumToRead-1-i] = STATUS_RETRIEVED;
+ SystemDebug.printf("RetrieveOn: givenout < %04d\n", ratd->NumToRead-1-i);
+
+ // if it is the last item wait for the thread to end and free the memory
+ if (pADDO->Get(ratd->NumToRead-1)==DDOMask) // && i==ratd->NumToRead-1 && ratd->Status[i] == STATUS_RETRIEVED)
+ {
+ while (1)
+ {
+ ratd->ForceEnd = TRUE;
+#ifdef WIN32
+ if (WaitForSingleObject(ratd->Handle, 10) != WAIT_TIMEOUT) break;
+ if (j++ > 200*100) break;
+#else
+ while(ratd->Busy) Sleep(10);
+ if (j++ > 200*100) break;
+#endif
+ }
+ if (ratd->pDCO) delete ratd->pDCO; ratd->pDCO = NULL;
+ free(ratd->DDOOutPtr); ratd->DDOOutPtr = NULL;
+ free(ratd->Filenames); ratd->Filenames = NULL;
+ free(ratd->SOPs); ratd->SOPs = NULL;
+ free(ratd->Series); ratd->Series = NULL;
+ free(ratd->Studies); ratd->Studies = NULL;
+ free(ratd->pats); ratd->pats = NULL;
+ free(ratd->ObjectFiles); ratd->ObjectFiles = NULL;
+ free(ratd->Devices); ratd->Devices = NULL;
+ free(ratd->Status); ratd->Status = NULL;
+ CloseHandle(ratd->Handle); ratd->Handle = NULLHANDLE;
+ }
+
+ goto further;
+ }
+ }
+ Sleep(1); // 20021215: fixes bug reported by Aaron Cann - 100% load
+ } // end of endless while
+
+ // mvh 20060401: fix hang condition when a read ahead failed
+ if (ratd->TimeOut)
+ {
+ if (ratd->Devices)
+ {
+ if (ratd->pDCO) delete ratd->pDCO; ratd->pDCO = NULL;
+ for (i=0; i<ratd->NumToRead; i++)
+ if (ratd->DDOOutPtr[i])
+ delete ratd->DDOOutPtr[i];
+ free(ratd->DDOOutPtr); ratd->DDOOutPtr = NULL;
+ free(ratd->Filenames); ratd->Filenames = NULL;
+ free(ratd->ObjectFiles);ratd->ObjectFiles = NULL;
+ free(ratd->Devices); ratd->Devices = NULL;
+ free(ratd->Status); ratd->Status = NULL;
+ free(ratd->SOPs); ratd->SOPs = NULL;
+ free(ratd->Series); ratd->Series = NULL;
+ free(ratd->Studies); ratd->Studies = NULL;
+ free(ratd->pats); ratd->pats = NULL;
+ CloseHandle(ratd->Handle); ratd->Handle = NULLHANDLE;
+ }
+ return FALSE;
+ }
+
+
+further:
+ if(*DDOOutPtr)
+ {
+ OperatorConsole.printf("Sending file : %s\n", Filename); // note subtle difference in message!
+ RTCStorage.SetUID(DDOMask->GetVR(0x0008, 0x0016));
+ (*SStorage) = &RTCStorage;
+ ImagesSent++;
+
+ SystemDebug.printf("Image Loaded from Read Ahead Thread, returning TRUE\n");
+ return ( TRUE );
+ }
+ // apparently flow could before fall through here in case
+ // of an error condition; added return FALSE 20120908
+ return ( FALSE );
+ } // end if ratd running
+
+
+ // use normal read code used when only one slice is requested
+
+ char pat[66]; /* get the patient ID */
+ pat[0]=0;
+ vr1 = DDOMask->GetVR(0x0010, 0x0020);
+ if (vr1)
+ {
+ memcpy(pat, vr1->Data, vr1->Length);
+ pat[vr1->Length]=0;
+ if (vr1->Length && pat[vr1->Length-1]==' ') pat[vr1->Length-1] = 0;
+ }
+
+ char series[66]; /* get the series UID */
+ series[0]=0;
+ vr1 = DDOMask->GetVR(0x0020, 0x000e);
+ if (vr1)
+ {
+ memcpy(series, vr1->Data, vr1->Length);
+ series[vr1->Length]=0;
+ if (vr1->Length && series[vr1->Length-1]==' ') series[vr1->Length-1] = 0;
+ }
+
+ char study[66]; /* get the study UID */
+ study[0]=0;
+ vr1 = DDOMask->GetVR(0x0020, 0x000d);
+ if (vr1)
+ {
+ memcpy(study, vr1->Data, vr1->Length);
+ study[vr1->Length]=0;
+ if (vr1->Length && study[vr1->Length-1]==' ') study[vr1->Length-1] = 0;
+ }
+
+ vr1 = DDOMask->GetVR(0x0008, 0x0018); /* The SOPInstanceUID */
+ if(!vr1)
+ return ( FALSE ); // it aint going to happen
+
+
+ // New code uses cached database, but this connection might have hung up
+ // New code: cache a database for as long as the RTCStorage exists
+
+ // if (!RTCStorage.DB.Connected)
+ // RTCStorage.DB.Open ( DataSource, UserName, Password, DataHost );
+ // if(!GetFileName(vr1, Filename, Device, /* RTCStorage.DB, */ TRUE))
+ // return ( FALSE ); // not in database ?
+
+ // Therefore use slower old code here: re-opens a database for each slice read
+ if(!GetFileName(vr1, Filename, Device, TRUE, pat, study, series))
+ return ( FALSE ); // not in database ?
+
+ if (!FindPhysicalDevice(Device, FullFilename, Filename))
+ {
+ OperatorConsole.printf("***Could not find file:%s\n", Filename);
+ return FALSE;
+ }
+ strcat(FullFilename, Filename);
+
+ // check the filename to determine format
+
+ len = strlen(FullFilename);
+ if (len>4)
+ UseChapter10 = (stricmp(FullFilename+len-4, ".v2")!=0) || NoDicomCheck;
+
+ if (*TestMode) strcat(FullFilename, TestMode);
+
+ int t = (int)time(NULL);
+ if (!UseChapter10)
+ {
+ /* Following load-routine works only for 'implicit' (i.e. no type-codes)
+ LittleEndian files.
+ It is able to skip large VRs; only NKI DicomNodes know how to add extra
+ (private) VRs to the DCO, in order to accomplish this.
+ */
+ iVrSizeLimit = 0xffffffff;
+ if (pDCO)
+ { /* Check whether there is a iVrSizeLimitLength */
+ pVR = pDCO->GetVR(0x9999, 0x0100);
+ if (pVR)
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ iVrSizeLimit = (unsigned int)(*((unsigned int*)pVR->Data));
+#else //Big Endian like Apple power pc
+ iVrSizeLimit = SwitchEndian((unsigned int)(*((unsigned int*)pVR->Data)));
+#endif
+ }
+ (*DDOOutPtr) = LoadImplicitLittleEndianFile(FullFilename, iVrSizeLimit);
+ /* Decompression and (in the future) other processing takes place in
+ ProcessDDO (c.f. NKIqrsop.cxx)
+ */
+ }
+ else
+ // OR: code in filepdu.cxx (dicom.lib); does not decompress but supports all formats
+ { (*DDOOutPtr) = PDU.LoadDICOMDataObject(FullFilename);
+ // OR: Code in loadddo.c, this directory; includes decompression, does not support sequences
+ // (*DDOOutPtr) = LoadDICOMDataObject(FullFilename);
+
+ }
+ LoadTime += time(NULL)-t;
+
+ t= (int)time(NULL);
+ ProcessDDO(DDOOutPtr, pDCO, &PDU);
+ ProcessTime += time(NULL)-t;
+
+ if(*DDOOutPtr)
+ {
+ OperatorConsole.printf("Sending file: %s\n", FullFilename);
+ ImagesSent++;
+ }
+ else
+ {
+ OperatorConsole.printf("***Could not read file: %s\n", FullFilename);
+ return ( FALSE );
+ }
+
+ RTCStorage.SetUID(DDOMask->GetVR(0x0008, 0x00016));
+ (*SStorage) = &RTCStorage;
+
+ SystemDebug.printf("Image Loaded, returning TRUE\n");
+ return ( TRUE );
+ }
+
+BOOL MyPatientRootRetrieve :: RetrieveOn (
+ DICOMDataObject *DDOMask,
+ DICOMDataObject **DDOOutPtr,
+ StandardStorage **SStorage)
+ {
+ SystemDebug.printf("MyPatientRootRetrieve :: RetrieveOn\n");
+ return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage));
+ }
+
+BOOL MyPatientRootRetrieveNKI :: RetrieveOn (
+ DICOMDataObject *DDOMask,
+ DICOMDataObject **DDOOutPtr,
+ StandardStorage **SStorage,
+ DICOMCommandObject *pDCO,
+ Array < DICOMDataObject *> *pADDO,
+ void *ExtraBytes)
+ {
+ SystemDebug.printf("MyPatientRootRetrieveNKI :: RetrieveOn\n");
+// return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, GetDCO(), GetADDO(), ExtraBytes));
+ return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, pDCO, pADDO, ExtraBytes));
+ }
+
+BOOL MyPatientRootRetrieveGeneric :: RetrieveOn (
+ DICOMDataObject *DDOMask,
+ DICOMDataObject **DDOOutPtr,
+ StandardStorage **SStorage,
+ DICOMCommandObject *pDCO,
+ Array < DICOMDataObject *> *pADDO,
+ void *ExtraBytes)
+ {
+ SystemDebug.printf("MyPatientRootRetrieveGeneric :: RetrieveOn\n");
+// return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, NULL, GetADDO(), ExtraBytes));
+ return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, pDCO, pADDO, ExtraBytes)); // 20100227: pass DCO: used in %s for RetrieveResultConverter
+ }
+
+BOOL MyStudyRootRetrieve :: RetrieveOn (
+ DICOMDataObject *DDOMask,
+ DICOMDataObject **DDOOutPtr,
+ StandardStorage **SStorage)
+ {
+ SystemDebug.printf("MyStudyRootRetrieve :: RetrieveOn\n");
+ return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage));
+ }
+
+BOOL MyStudyRootRetrieveNKI :: RetrieveOn (
+ DICOMDataObject *DDOMask,
+ DICOMDataObject **DDOOutPtr,
+ StandardStorage **SStorage,
+ DICOMCommandObject *pDCO,
+ Array < DICOMDataObject *> *pADDO,
+ void *ExtraBytes)
+ {
+ SystemDebug.printf("MyStudyRootRetrieveNKI :: RetrieveOn\n");
+// return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, GetDCO(), GetADDO(), ExtraBytes));
+ return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, pDCO, pADDO, ExtraBytes));
+ }
+
+BOOL MyStudyRootRetrieveGeneric :: RetrieveOn (
+ DICOMDataObject *DDOMask,
+ DICOMDataObject **DDOOutPtr,
+ StandardStorage **SStorage,
+ DICOMCommandObject *pDCO,
+ Array < DICOMDataObject *> *pADDO,
+ void *ExtraBytes)
+ {
+ SystemDebug.printf("MyStudyRootRetrieveGeneric :: RetrieveOn\n");
+ return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, pDCO, pADDO, ExtraBytes)); // 20100227: pass DCO: used in %s for RetrieveResultConverter
+ }
+
+BOOL MyPatientStudyOnlyRetrieve :: RetrieveOn (
+ DICOMDataObject *DDOMask,
+ DICOMDataObject **DDOOutPtr,
+ StandardStorage **SStorage)
+ {
+ SystemDebug.printf("MyPatientStudyOnlyRetrieve :: RetrieveOn\n");
+ return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage));
+ }
+
+BOOL MyPatientStudyOnlyRetrieveNKI :: RetrieveOn (
+ DICOMDataObject *DDOMask,
+ DICOMDataObject **DDOOutPtr,
+ StandardStorage **SStorage,
+ DICOMCommandObject *pDCO,
+ Array < DICOMDataObject *> *pADDO,
+ void *ExtraBytes)
+ {
+ SystemDebug.printf("MyPatientStudyOnlyRetrieveNKI :: RetrieveOn\n");
+ return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, pDCO, pADDO, ExtraBytes));
+ }
+
+BOOL MyPatientStudyOnlyRetrieveGeneric :: RetrieveOn (
+ DICOMDataObject *DDOMask,
+ DICOMDataObject **DDOOutPtr,
+ StandardStorage **SStorage,
+ DICOMCommandObject *pDCO,
+ Array < DICOMDataObject *> *pADDO,
+ void *ExtraBytes)
+ {
+ SystemDebug.printf("MyPatientStudyOnlyRetrieveGeneric :: RetrieveOn\n");
+ return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, pDCO, pADDO, ExtraBytes)); // 20100227: pass DCO: used in %s for RetrieveResultConverter
+ }
+
+BOOL
+QualifyOn(
+ BYTE *ACRNema,
+ BYTE *MyACRNema,
+ BYTE *RemoteIP,
+ BYTE *RemotePort,
+ BYTE *Compress)
+ {
+ strcpy((char*)MyACRNema, (char*)MYACRNEMA);
+ if(!GetACRNema((char*)ACRNema, (char*)RemoteIP, (char*)RemotePort, (char*)Compress))
+ {
+ return FALSE; // use "* * 104 un" in acrnema.map to emulate this
+
+ // This is a non-standard "feature". Perhaps the ACR-Nema
+ // is reversable via DNS. You should return FALSE here
+ // if you don't want this.
+ /* strcpy((char*)RemoteIP, (char*) ACRNema);
+ strcpy((char*)RemotePort, "104");
+ SystemDebug.printf("(QualifyOn) (anonymous) IP:%s, PORT:%s\n", RemoteIP,RemotePort);
+ return ( TRUE );
+ */
+ }
+
+ /* GetACRNema is able to discern upper and lower case, so that when two different
+ stations have the same AE, we can still map them to different IP addresses...
+ However, when associating to a 'lower case AE station', it may very well be that
+ that station wants an upper case 'Called AE title'.
+ */
+
+ char szRootSC[64], Temp[64];
+ if (MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile))
+ if (MyGetPrivateProfileString(szRootSC, "SendUpperCaseAE", "0", Temp, 64, ConfigFile))
+ if (atoi(Temp)) strupr((char*)ACRNema);
+
+ SystemDebug.printf("(QualifyOn) (mapped) IP:%s, PORT:%s\n", RemoteIP,RemotePort);
+ return ( TRUE );
+ }
+
+BOOL MyPatientRootRetrieve :: QualifyOn (
+ BYTE *ACRNema,
+ BYTE *MyACRNema,
+ BYTE *RemoteIP,
+ BYTE *RemotePort)
+ {
+ BYTE dummy[64];
+ return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, dummy));
+ }
+
+BOOL MyPatientRootRetrieveNKI :: QualifyOn (
+ BYTE *ACRNema,
+ BYTE *MyACRNema,
+ BYTE *RemoteIP,
+ BYTE *RemotePort,
+ BYTE *Compress)
+ {
+ return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, Compress));
+ }
+
+BOOL MyPatientRootRetrieveGeneric :: QualifyOn (
+ BYTE *ACRNema,
+ BYTE *MyACRNema,
+ BYTE *RemoteIP,
+ BYTE *RemotePort,
+ BYTE *Compress)
+ {
+ return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, Compress));
+ }
+
+BOOL MyStudyRootRetrieve :: QualifyOn (
+ BYTE *ACRNema,
+ BYTE *MyACRNema,
+ BYTE *RemoteIP,
+ BYTE *RemotePort)
+ {
+ BYTE dummy[64];
+ return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, dummy));
+ }
+
+BOOL MyStudyRootRetrieveNKI :: QualifyOn (
+ BYTE *ACRNema,
+ BYTE *MyACRNema,
+ BYTE *RemoteIP,
+ BYTE *RemotePort,
+ BYTE *Compress)
+ {
+ return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, Compress));
+ }
+
+BOOL MyStudyRootRetrieveGeneric :: QualifyOn (
+ BYTE *ACRNema,
+ BYTE *MyACRNema,
+ BYTE *RemoteIP,
+ BYTE *RemotePort,
+ BYTE *Compress)
+ {
+ return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, Compress));
+ }
+
+BOOL MyPatientStudyOnlyRetrieve :: QualifyOn (
+ BYTE *ACRNema,
+ BYTE *MyACRNema,
+ BYTE *RemoteIP,
+ BYTE *RemotePort)
+ {
+ BYTE dummy[64];
+ return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, dummy));
+ }
+
+BOOL MyPatientStudyOnlyRetrieveNKI :: QualifyOn (
+ BYTE *ACRNema,
+ BYTE *MyACRNema,
+ BYTE *RemoteIP,
+ BYTE *RemotePort,
+ BYTE *Compress)
+ {
+ return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, Compress));
+ }
+
+BOOL MyPatientStudyOnlyRetrieveGeneric :: QualifyOn (
+ BYTE *ACRNema,
+ BYTE *MyACRNema,
+ BYTE *RemoteIP,
+ BYTE *RemotePort,
+ BYTE *Compress)
+ {
+ return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, Compress));
+ }
+
+BOOL RunTimeClassStorage :: GetUID ( UID &uid )
+ {
+ uid = MyUID;
+ return ( TRUE );
+ }
+
+BOOL RunTimeClassStorage :: SetUID ( UID &uid )
+ {
+ MyUID = uid;
+ return ( TRUE );
+ }
+
+BOOL RunTimeClassStorage :: SetUID ( VR *vr )
+ {
+ char s [ 66 ];
+
+ memset((void*)s, 0, 66);
+ if(vr)
+ {
+ memcpy((void*)s, vr->Data, vr->Length>64 ? 64 : vr->Length);
+ MyUID.Set(s);
+ return(TRUE);
+ }
+ return ( FALSE );
+ }
+
+BOOL RunTimeClassStorage :: SetUID ( DICOMDataObject *DDOPtr)
+ {
+ return(SetUID (DDOPtr->GetVR(0x0008, 0x0016)));
+ }
+
+#ifndef UNIX
+BOOL WINAPI DriverHelper ( DriverApp * );
+#else
+ThreadRoutineType DriverHelper ( ThreadRoutineArgType );
+#endif
+
+BOOL DriverApp :: Server ( BYTE *port )
+ {
+ Socket MSocket;
+#ifndef UNIX
+ DWORD ThreadID;
+ HANDLE ThreadHandle;
+#else
+ pthread_t ThreadID;
+
+ // NOTE: this Database is not used BUT, if you don't create/open the
+ // Database in the main thread, you won't be able to in child threads...
+
+ Database aDB;
+ if(!aDB.Open(DataSource, UserName, Password, DataHost))
+ {
+ OperatorConsole.printf("***Unable to open database %s as user %s on %s\n",
+ DataSource, UserName, DataHost);
+ return FALSE;
+ }
+#endif
+ MSocket.SetTimeOut(TCPIPTimeOut);
+
+ if (!MSocket.Listen ((char*) port ))
+ {
+ OperatorConsole.printf("***Failed to Listen () - bind error\n");
+ return ( FALSE ); // failed on the bind
+ }
+
+ while (MSocket.Accept() )
+ {
+
+ while ( Lock )
+ Sleep(50);
+ Lock = 1;
+
+ ConnectedIP = MSocket.sa.sin_addr.s_addr;
+ ChildSocketfd= MSocket.Socketfd;
+
+ if (NoThread)
+ DriverHelper(this);
+ else
+ {
+#ifndef UNIX
+ if(!(ThreadHandle = CreateThread(NULL, 0x0000f000, (LPTHREAD_START_ROUTINE) DriverHelper,
+ this, 0, &ThreadID)))
+#else // UNIX
+ pthread_create(&ThreadID, NULL, DriverHelper, (void *)this);
+ pthread_detach(ThreadID);
+ if (!ThreadID)
+#endif
+ {
+ OperatorConsole.printf("***Failed to create thread for child\n");
+ closesocket ( MSocket.Socketfd );
+ }
+ else
+ CloseHandle(ThreadHandle);
+ }
+
+ MSocket.Socketfd = 0;
+ MSocket.Connected = FALSE;
+
+#ifdef DO_LEAK_DETECTION
+ if (kbhit())
+ { /* Only in debug-mode */
+ Sleep(10000); // Hope that other threads are finished by now
+ /* Cleanup */
+ CloseACRNemaAddressArray();
+ free(PatientDB);
+ free(StudyDB);
+ free(SeriesDB);
+ free(ImageDB);
+ FreeDeviceTables();
+ break;
+ }
+#endif
+ }
+#ifdef DEBUG_MODE
+ OperatorConsole.printf("***Error in Accept() function call\n");
+ SystemDebug.printf("***Attemping to re-bind socket\n");
+#endif
+ return ( FALSE );
+ }
+
+BOOL DriverApp :: ServerChildThread ( int Socketfd )
+ {
+ //ExitThread ( (int) ServerChild ( Socketfd ) );
+ ServerChild( Socketfd );
+ return ( FALSE );
+ }
+
+// Technically this routine is not needed. However, Microsoft Visual C++
+// has some odd quarks to it. This work around maintains MT safe.
+
+#ifndef UNIX
+BOOL WINAPI DriverHelper (DriverApp *App)
+ {
+#else
+ThreadRoutineType DriverHelper(void *theApp)
+ {
+ DriverApp *App = (DriverApp *)theApp;
+#endif
+ int Socketfd;
+
+ // pick up data from passed-in object
+
+ Socketfd = App->ChildSocketfd;
+
+ // release lock on data
+
+ App->Lock = 0;
+
+ App->ServerChildThread ( Socketfd );
+ // we never technically get here
+ // LJ: in M$VC-debug, we actually do get here, and a crash follows (at least when
+ // ODBC is used)
+// ExitThread(0x00);
+ return ( THREAD_RETURN_FALSE );
+ }
+
+// Log some user information
+
+void LogUser(const char* pszOperation, AAssociateRQ* pARQ, DICOMCommandObject* pDCO)
+ {
+ UserLog.printf("\"%s\",\"%s\"\n", pszOperation, pARQ->CallingApTitle);
+ UNUSED_ARGUMENT(pDCO);
+// NonDestructiveDumpDICOMObject(pDCO); object does not exist anymore
+ }
+
+// Helps when looking at crash dump
+
+void WipeStack(void)
+ {
+ char Dummy[512];
+ memset(Dummy, '?', sizeof(Dummy));
+ }
+
+#ifdef __BORLANDC__
+extern "C" int _RTLENTRY _EXPFUNC _heapchk (void);
+#endif
+
+// Storage that does not require a database
+
+void StorageApp :: FailSafeStorage(CheckedPDU_Service *PDU)
+{ DICOMDataObject *DDO;
+ DICOMCommandObject DCO;
+ char Filename[1024];
+ char Physical[1024];
+ int i;
+
+ // defined here to make thread safe: multiple instances of SOPUnknownStorage.DB required
+ MyUnknownStorage SOPUnknownStorage;
+
+ DDO = new DICOMDataObject;
+
+ while(TRUE)
+ { DCO.Reset();
+ if (!PDU->Read(&DCO))
+ break;
+
+ SOPUnknownStorage.DB = NULL; // no processing
+ SOPUnknownStorage.nopreget = FALSE;
+ if(!SOPUnknownStorage.Read(PDU, &DCO, DDO)) break;
+
+ GetPhysicalDevice("MAG0", Physical);
+ sprintf(Filename, "%sfailsafe_storage", Physical);
+ mkdir(Filename);
+ i = strlen(Filename);
+ Filename[i] = PATHSEPCHAR;
+ Filename[i+1] = 0;
+ GenUID(Filename + strlen(Filename));
+ strcat(Filename, ".dcm");
+ PDU->SaveDICOMDataObject(Filename, DICOM_CHAPTER_10_IMPLICIT, DDO);
+
+ OperatorConsole.printf("***Failsafe storage saved incoming file as: %s\n", Filename);
+ }
+
+ delete DDO;
+}
+
+void TestCompress(char *filename, const char *modes, ExtendedPDU_Service *PDU)
+{ DICOMDataObject *pDDO;
+ int syntax;//, len;
+ unsigned int i;
+ //PDU_Service PDU;
+// VR *vrSOPInstanceUID;
+ Database DB;
+ char rFilename[1024];
+ char mode[3];
+ char SOP[66];
+ VR *vr;
+
+ //PDU.AttachRTC(&VRType);
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ OperatorConsole.printf("***Error Connecting to SQL\n");
+ return;
+ }
+
+ pDDO = LoadForGUI(filename);
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[TestCompress] %s -FAILED: Error on Load\n", filename);
+ return;
+ }
+
+ for(syntax=3; syntax<=4; syntax++)
+ for(i=0; i<strlen(modes); i+=2)
+ { memcpy(mode, modes+i, 2);
+ mode[2]=0;
+ Sleep(1);
+
+ pDDO = LoadForGUI(filename);
+ strcpy(rFilename, "org");
+
+ GenUID(SOP); vr = new VR(0x0008, 0x0018, (strlen(SOP)+1)&0xfe, (void*)SOP, (BOOL) FALSE );
+ pDDO->ReplaceVR(vr); delete vr;
+ vr = new VR(0x0020, 0x0013, strlen(rFilename), (void*)rFilename, (BOOL) FALSE );
+ pDDO->ReplaceVR(vr); delete vr;
+ //SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"testcompress", (unsigned char *)"testcompress", syntax);
+ SaveToDisk(DB, pDDO, rFilename, TRUE, PDU, syntax);
+ pDDO = PDU->LoadDICOMDataObject(rFilename);
+ OperatorConsole.printf("Added file: %s (filename syntax %d)\n", rFilename, syntax);
+
+ // recompress dropped file
+ recompress(&pDDO, mode, "", mode[0]=='n' || mode[0]=='N', PDU); strcpy(rFilename, mode);
+ GenUID(SOP); vr = new VR(0x0008, 0x0018, (strlen(SOP)+1)&0xfe, (void*)SOP, (BOOL) FALSE );
+ pDDO->ReplaceVR(vr); delete vr;
+ vr = new VR(0x0020, 0x0013, strlen(rFilename), (void*)rFilename, (BOOL) FALSE );
+ pDDO->ReplaceVR(vr); delete vr;
+ //SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"testcompress", (unsigned char *)"testcompress", syntax);
+ SaveToDisk(DB, pDDO, rFilename, TRUE, PDU, syntax);
+ pDDO = PDU->LoadDICOMDataObject(rFilename);
+ OperatorConsole.printf("Added file: %s (compression %s, syntax %d)\n", rFilename, mode, syntax);
+
+ // uncompress dropped file
+ recompress(&pDDO, "un", "", FALSE, PDU); strcpy(rFilename, mode); strcat(rFilename, "_un");
+ GenUID(SOP); vr = new VR(0x0008, 0x0018, (strlen(SOP)+1)&0xfe, (void*)SOP, (BOOL) FALSE );
+ pDDO->ReplaceVR(vr); delete vr;
+ vr = new VR(0x0020, 0x0013, strlen(rFilename), (void*)rFilename, (BOOL) FALSE );
+ pDDO->ReplaceVR(vr); delete vr;
+ //SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"testcompress", (unsigned char *)"testcompress", syntax);
+ SaveToDisk(DB, pDDO, rFilename, TRUE, PDU, syntax);
+ pDDO = PDU->LoadDICOMDataObject(rFilename);
+ OperatorConsole.printf("Added file: %s (compression %s_un, syntax %d)\n", rFilename, mode, syntax);
+
+ // recompress dropped file again
+ recompress(&pDDO, mode, "", mode[0]=='n' || mode[0]=='N', PDU); strcpy(rFilename, mode); strcat(rFilename, "_un_"); strcat(rFilename, mode);
+ GenUID(SOP); vr = new VR(0x0008, 0x0018, (strlen(SOP)+1)&0xfe, (void*)SOP, (BOOL) FALSE );
+ pDDO->ReplaceVR(vr); delete vr;
+ vr = new VR(0x0020, 0x0013, strlen(rFilename), (void*)rFilename, (BOOL) FALSE );
+ pDDO->ReplaceVR(vr); delete vr;
+ //SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"testcompress", (unsigned char *)"testcompress", syntax);
+ SaveToDisk(DB, pDDO, rFilename, TRUE, PDU, syntax);
+ pDDO = PDU->LoadDICOMDataObject(rFilename);
+ OperatorConsole.printf("Added file: %s (compression %s_un_%s, syntax %d)\n", rFilename, mode, mode, syntax);
+ }
+
+ delete pDDO;
+}
+
+void TestForward(char *filename, const char *mode, char *server, ExtendedPDU_Service *PDU)
+{ char host[64], port[64], compress[64];
+ char *p;
+ RunTimeClassStorage RTCStorage;
+ ExtendedPDU_Service PDU2;
+ DICOMDataObject* pDDO;
+ UID AppUID ("1.2.840.10008.3.1.1.1");
+ UID iUID;
+ VR *vr;
+ char SOP[66], temp[20];
+ BOOL StripGroup2;
+
+ PDU2.AttachRTC(&VRType);
+
+ if(!GetACRNema(server, (char *)host, (char *)port, (char *)compress))
+ { strcpy(host, server);
+ p = strchr(host, ':');
+ if (p)
+ { *p=0;
+ strcpy(port, p+1);
+ }
+ else
+ strcpy(port, "5678");
+ }
+
+ PDU2.SetRequestedCompressionType(""); // default
+
+ pDDO = LoadForGUI(filename);
+ if (!pDDO)
+ { OperatorConsole.printf("*** Test forward: failed to load DICOM object %s\n", filename);
+ return;
+ }
+
+ // offer transfer syntax from forward string
+ if (mode)
+ PDU2.SetRequestedCompressionType(mode);
+ else
+ // offer transfer syntax from acrnema.map
+ PDU2.SetRequestedCompressionType(compress);
+
+ PDU2.SetApplicationContext ( AppUID );
+ PDU2.SetLocalAddress ( MYACRNEMA );
+ PDU2.SetRemoteAddress ( (unsigned char *)server );
+
+ vr = pDDO -> GetVR(0x0008, 0x0016);
+ if (!vr)
+ { OperatorConsole.printf("*** Test forward: Forward failed because SopClass is missing in %s\n", filename);
+ delete pDDO;
+ return;
+ }
+ SetUID ( iUID, vr );
+ PDU2.AddAbstractSyntax ( iUID );
+ PDU2.SetTimeOut(TCPIPTimeOut);
+
+ if (!PDU2.Connect((unsigned char *)&host, (unsigned char *)&port))
+ { OperatorConsole.printf("*** Test forward: Forward failed to connect to host %s\n", server);
+ delete pDDO;
+ return;
+ }
+
+ if (!PDU2.IsAbstractSyntaxAccepted(iUID))
+ { OperatorConsole.printf("*** Test forward: DICOM server %s does not accept type of forwarded images\n", server);
+ PDU2.Close();
+ delete pDDO;
+ return;
+ }
+
+ OperatorConsole.printf("Test forward: requested %s, accepted %s, sending to %s = %s:%s\n", mode, PDU2.GetAcceptedCompressionType(iUID), server, host, port);
+
+ GenUID(SOP); vr = new VR(0x0008, 0x0018, (strlen(SOP)+1)&0xfe, (void*)SOP, (BOOL) FALSE );
+ pDDO->ReplaceVR(vr); delete vr;
+ sprintf(temp, "%s %s", mode, PDU2.GetAcceptedCompressionType(iUID));
+ vr = new VR(0x0020, 0x0013, strlen(temp), (void*)temp, (BOOL) FALSE );
+ pDDO->ReplaceVR(vr); delete vr;
+
+ // recompress data to be forwarded here according to accepted compression mode
+ p = PDU2.GetAcceptedCompressionType(iUID);
+ StripGroup2 = memicmp(p, "as", 2)!=0 && memicmp(p, "is", 2)!=0;
+ recompress(&pDDO, p, "", StripGroup2, PDU);
+
+ RTCStorage.SetUID(iUID);
+
+ if (!RTCStorage.Write(&PDU2, pDDO))
+ { OperatorConsole.printf("*** Test forward: Forward failed to send DICOM image to %s\n", server);
+ PDU2.Close();
+ delete pDDO;
+ return;
+ }
+
+ delete pDDO;
+ PDU2.Close();
+}
+
+void TestSyntax(char *filename, int syntax, ExtendedPDU_Service *PDU)
+{ DICOMDataObject* pDDO;
+ VR *vr;
+ char SOP[66], temp[20];
+ Database DB;
+ char rFilename[1024];
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ OperatorConsole.printf("***Error Connecting to SQL\n");
+ return;
+ }
+
+ pDDO = LoadForGUI(filename);
+ if (!pDDO)
+ { OperatorConsole.printf("*** Test syntax: failed to load DICOM object %s\n", filename);
+ return;
+ }
+
+ GenUID(SOP); vr = new VR(0x0008, 0x0018, (strlen(SOP)+1)&0xfe, (void*)SOP, (BOOL) FALSE );
+ pDDO->ReplaceVR(vr); delete vr;
+ sprintf(temp, "syntax %d", syntax);
+ vr = new VR(0x0020, 0x0013, strlen(temp), (void*)temp, (BOOL) FALSE );
+ pDDO->ReplaceVR(vr); delete vr;
+
+ //SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"testsyntax", (unsigned char *)"testsyntax", syntax);
+ SaveToDisk(DB, pDDO, rFilename, TRUE, PDU, syntax);
+}
+
+static BOOL WINAPI testsavethread(char *filename)
+{ ExtendedPDU_Service PDU; // for script context (test only)
+ PDU.SetLocalAddress ( (BYTE *)"testsavethread" );
+ PDU.SetRemoteAddress ( (BYTE *)"testsavethread" );
+ TestSyntax(filename, 0, &PDU);
+ return TRUE;
+}
+
+void TestThreadedSave(char *filename)
+{
+#ifdef WIN32
+ unsigned long ThreadID;
+ CreateThread(NULL, 0x000ff000, (LPTHREAD_START_ROUTINE) testsavethread, filename, 0, &ThreadID);
+#else
+ pthread_t ThreadID;
+ pthread_create(&ThreadID, NULL, (void*(*)(void*))testsavethread, (void *)filename);
+ pthread_detach(ThreadID);
+#endif
+}
+
+///////////////////////////// elementary printer server support //////////////////////////
+
+// basic film session: is created, deleted, set and action
+
+class CFSRQ : public NCreateRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; }
+ };
+
+class CFSRSP : public NCreateRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; }
+ };
+
+class DFSRQ : public NDeleteRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; }
+ };
+
+class DFSRSP : public NDeleteRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; }
+ };
+
+class SFSRQ : public NSetRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; }
+ };
+
+class SFSRSP : public NSetRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; }
+ };
+
+class AFSRQ : public NActionRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; }
+ };
+
+class AFSRSP : public NActionRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; }
+ };
+
+// basic film box: is created, set, action(printed) and deleted
+
+class CFBRQ : public NCreateRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; }
+ };
+
+class CFBRSP : public NCreateRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; }
+ };
+
+class DFBRQ : public NDeleteRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; }
+ };
+
+class DFBRSP : public NDeleteRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; }
+ };
+
+class AFBRQ : public NActionRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; }
+ };
+
+class AFBRSP : public NActionRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; }
+ };
+
+class SFBRQ : public NSetRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; }
+ };
+
+class SFBRSP : public NSetRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; }
+ };
+
+// Basic GrayScale ImageBox should only be set
+
+class SBGIBRQ : public NSetRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.4"); return TRUE; }
+ };
+
+class SBGIBRRSP : public NSetRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.4"); return TRUE; }
+ };
+
+// Basic Color ImageBox should only be set
+
+class SBCIBRQ : public NSetRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.4.1"); return TRUE; }
+ };
+
+class SBCIBRRSP : public NSetRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.4.1"); return TRUE; }
+ };
+
+// Printer
+
+class GPRQ : public NGetRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.16"); return TRUE; }
+ };
+
+class GPRSP : public NGetRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.16"); return TRUE; }
+ };
+
+class EPRQ : public NEventReportRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.16"); return TRUE; }
+ };
+
+class EPRSP : public NEventReportRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.16"); return TRUE; }
+ };
+
+/* OPTIONAL sop classes
+
+// Basic Annotation Box should only be set
+
+class SBABRQ : public NSetRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.15"); return TRUE; }
+ } SetBasicAnnotationBoxRequest;
+
+class SBABRRSP : public NSetRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.15"); return TRUE; }
+ } SetBasicAnnotationBoxResponse;
+
+// Print job
+
+class GPJRQ : public NGetRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.14"); return TRUE; }
+ } GetPrintJobRequest;
+
+class GPJRSP : public NGetRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.14"); return TRUE; }
+ } GetPrintJobResponse;
+
+class EPJRQ : public NEventReportRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.14"); return TRUE; }
+ } EventReportPrintJobRequest;
+
+class EPJRSP : public NEventReportRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.14"); return TRUE; }
+ } EventReportPrintJobResponse;
+
+// Presentation LUT: is created and deleted
+
+class CPLRQ : public NCreateRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.23"); return TRUE; }
+ } CreatePresentationLUTRequest;
+
+class CPLRSP : public NCreateRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.23"); return TRUE; }
+ } CreatePresentationLUTResponse;
+
+class DPLRQ : public NDeleteRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.23"); return TRUE; }
+ } DeletePresentationLUTRequest;
+
+class DPLRSP : public NDeleteRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.23"); return TRUE; }
+ } DeletePresentationLUTResponse;
+
+// Printer configuration: get only
+
+class GPCRQ : public NGetRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.16.376"); return TRUE; }
+ } GetPrinterConfigurationRequest;
+
+class GPCRSP : public NGetRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.16.376"); return TRUE; }
+ } GetPrinterConfigurationResponse;
+
+*/
+
+static int pcount=0;
+
+BOOL StorageApp :: PrinterSupport( CheckedPDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *PrintData[])
+ {
+ DICOMDataObject *DDO;
+ char uid[65], Filename[1024];
+ UID Uid;
+ VR *vr, *vrs;
+
+ UID aBasicGrayscalePrintManagementMetaSOPClass("1.2.840.10008.5.1.1.9");
+ UID aBasicColorPrintManagementMetaSOPClass("1.2.840.10008.5.1.1.18");
+
+ UID aBasicFilmSessionSOPClassUID("1.2.840.10008.5.1.1.1");
+ UID aBasicFilmBoxSOPClassUID("1.2.840.10008.5.1.1.2");
+ UID aBasicGrayscaleImageBoxSOPClassUID("1.2.840.10008.5.1.1.4");
+ UID aBasicColorImageBoxSOPClassUID("1.2.840.10008.5.1.1.4.1");
+ UID aBasicPrinterSOPClassUID("1.2.840.10008.5.1.1.16");
+ UID aAppuid("1.2.840.10008.3.1.1.1");
+ UID aPrinter("1.2.840.10008.5.1.1.17");
+ int i;
+ char szPrintSOP[65];
+ bool rc;
+
+
+CFSRQ CreateBasicFilmSessionRequest;
+CFSRSP CreateBasicFilmSessionResponse;
+DFSRQ DeleteBasicFilmSessionRequest;
+DFSRSP DeleteBasicFilmSessionResponse;
+SFSRQ SetBasicFilmSessionRequest;
+SFSRSP SetBasicFilmSessionResponse;
+AFSRQ ActionBasicFilmSessionRequest;
+AFSRSP ActionBasicFilmSessionResponse;
+CFBRQ CreateBasicFilmBoxRequest;
+CFBRSP CreateBasicFilmBoxResponse;
+DFBRQ DeleteBasicFilmBoxRequest;
+DFBRSP DeleteBasicFilmBoxResponse;
+AFBRQ ActionBasicFilmBoxRequest;
+AFBRSP ActionBasicFilmBoxResponse;
+SFBRQ SetBasicFilmBoxRequest;
+SFBRSP SetBasicFilmBoxResponse;
+SBGIBRQ SetBasicGrayScaleImageBoxRequest;
+SBGIBRRSP SetBasicGrayScaleImageBoxResponse;
+SBCIBRQ SetBasicColorImageBoxRequest;
+SBCIBRRSP SetBasicColorImageBoxResponse;
+GPRQ GetPrinterRequest;
+GPRSP GetPrinterResponse;
+EPRQ EventReportPrinterRequest;
+EPRSP EventReportPrinterResponse;
+
+ DDO = new DICOMDataObject;
+
+ vr = DCO->GetVR(0x0000, 0x0002);
+ if (!vr)
+ vr = DCO->GetVR(0x0000, 0x0003);
+
+ if (vr && vr->Length >= strlen("1.2.840.10008.5.1.1.1 "))
+ {
+ strncpy(szPrintSOP, (char*)vr->Data, vr->Length);
+ szPrintSOP[vr->Length] = 0;
+
+ if (strcmp(szPrintSOP, "1.2.840.10008.5.1.1.16") == 0)
+ {
+ if (GetPrinterRequest.Read(DCO, PDU, DDO))
+ {
+ OperatorConsole.printf("getting Printer\n");
+ if (DebugLevel>=3) NonDestructiveDumpDICOMObject(DDO);
+
+ // open up PDU for class UIDs used by printer objects
+ PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass,
+ aBasicFilmSessionSOPClassUID);
+ PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass,
+ aBasicFilmBoxSOPClassUID);
+ PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass,
+ aBasicGrayscaleImageBoxSOPClassUID);
+ PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass,
+ aBasicPrinterSOPClassUID);
+
+ PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass,
+ aBasicFilmSessionSOPClassUID);
+ PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass,
+ aBasicFilmBoxSOPClassUID);
+ PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass,
+ aBasicColorImageBoxSOPClassUID);
+ PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass,
+ aBasicPrinterSOPClassUID);
+
+ PrintData[0] = new DICOMDataObject;
+ VR *aVR;
+ aVR = new VR(0x2110, 0x0010, strlen("NORMAL"), (void *)"NORMAL", FALSE);
+ PrintData[0]->Push(aVR);
+ aVR = new VR(0x2110, 0x0020, strlen("NORMAL"), (void *)"NORMAL", FALSE);
+ PrintData[0]->Push(aVR);
+ aVR = new VR(0x2110, 0x0030, strlen("Conquest dicom printer"), (void *)"Conquest dicom printer", FALSE);
+ PrintData[0]->Push(aVR);
+
+ delete DDO;
+ if (DebugLevel>=3) NonDestructiveDumpDICOMObject(PrintData[0]);
+ rc = GetPrinterResponse.Write(PDU, DCO, &aPrinter, 0, PrintData[0]);
+ free(PrintData[0]);
+ return rc;
+ }
+
+ if (EventReportPrinterRequest.Read(DCO, PDU, DDO))
+ {
+ OperatorConsole.printf("N-event Printer\n");
+ if (DebugLevel>=3) NonDestructiveDumpDICOMObject(DDO);
+ delete DDO;
+ return EventReportPrinterResponse.Write(PDU, DCO, &aPrinter, 0, PrintData[0]);
+ }
+ }
+
+ else if (strcmp(szPrintSOP, "1.2.840.10008.5.1.1.1") == 0)
+ {
+ if (CreateBasicFilmSessionRequest.Read(DCO, PDU, DDO))
+ {
+ OperatorConsole.printf("Creating Basic Film Session\n");
+ if (DebugLevel>=3) NonDestructiveDumpDICOMObject(DDO);
+ PrintData[1] = DDO;
+
+ // open up PDU for class UIDs used by printer objects
+ PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass,
+ aBasicFilmSessionSOPClassUID);
+ PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass,
+ aBasicFilmBoxSOPClassUID);
+ PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass,
+ aBasicGrayscaleImageBoxSOPClassUID);
+ PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass,
+ aBasicPrinterSOPClassUID);
+
+ PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass,
+ aBasicFilmSessionSOPClassUID);
+ PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass,
+ aBasicFilmBoxSOPClassUID);
+ PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass,
+ aBasicColorImageBoxSOPClassUID);
+ PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass,
+ aBasicPrinterSOPClassUID);
+
+ GenUID(uid);
+ Uid.Set(uid);
+
+ CreateBasicFilmSession++;
+ BOOL r = CreateBasicFilmSessionResponse.Write(PDU, DCO, &Uid, 0, DDO);
+ delete DDO;
+ return r;
+ }
+ if (DeleteBasicFilmSessionRequest.Read(DCO, PDU))
+ {
+ OperatorConsole.printf("Deleting Basic Film Session\n");
+ //delete PrintData[1];
+ //PrintData[1] = NULL;
+ DeleteBasicFilmSession++;
+ delete DDO;
+ return DeleteBasicFilmSessionResponse.Write(PDU, DCO, &Uid, 0);
+ }
+
+ if (ActionBasicFilmSessionRequest.Read(DCO, PDU, DDO))
+ {
+ OperatorConsole.printf("Printing Basic Film Session\n");
+ if (DebugLevel>=3) NonDestructiveDumpDICOMObject(DDO);
+ ActionBasicFilmSession++;
+ delete DDO;
+ return ActionBasicFilmSessionResponse.Write(PDU, DCO, NULL, 0, 0, NULL);
+ }
+
+ if (SetBasicFilmSessionRequest.Read(DCO, PDU, DDO))
+ {
+ PrintData[1] = DDO;
+ OperatorConsole.printf("Set Basic Film Session\n");
+ if (DebugLevel>=3) NonDestructiveDumpDICOMObject(DDO);
+ SetBasicFilmSession++;
+ delete DDO;
+ return SetBasicFilmSessionResponse.Write(PDU, DCO, NULL, 0, NULL);
+ }
+ }
+
+
+ else if (strcmp(szPrintSOP, "1.2.840.10008.5.1.1.2") == 0)
+ {
+ if (CreateBasicFilmBoxRequest.Read(DCO, PDU, DDO))
+ {
+ int n=1, rows=1, cols=1;
+ char text[256];
+
+ PrintData[2] = DDO;
+ GenUID(uid);
+ Uid.Set(uid);
+
+ VR *avr = DDO->GetVR(0x2010, 0x0010);
+ if (avr)
+ {
+ char *p1, *p2;
+ memset(text, 0, 256);
+ memcpy(text, avr->Data, avr->Length);
+ p1 = strchr(text, '\\');
+ p2 = strchr(text, ',');
+ if (p1 && p2)
+ {
+ rows = atoi(p1+1);
+ cols = atoi(p2+1);
+ n = rows * cols;
+ }
+ }
+
+ text[0]=0;
+ avr = DDO->GetVR(0x2010, 0x0040);
+ if (avr)
+ {
+ memset(text, 0, 256);
+ memcpy(text, avr->Data, avr->Length);
+ }
+
+ OperatorConsole.printf("Creating Basic Film Box with %d Image boxes - %s - Film# %d\n", n, text, pcount);
+ if (DebugLevel>=3) NonDestructiveDumpDICOMObject(DDO);
+
+ Array < DICOMDataObject * > *SQE = new Array < DICOMDataObject * >;
+ vrs = new VR(0x2010, 0x0510, 0, (void *)NULL, FALSE);
+ vrs->SQObjectArray = (void*) SQE;
+
+ for (i=0; i<n; i++)
+ {
+ char *uid2 = (char *)malloc(65);
+ strcpy(uid2, uid);
+ if (uid2[50]=='.') uid2[50]=0; // make space for pcount, row/col info
+ else uid2[51]=0;
+ sprintf(uid2 + strlen(uid2), ".%d.%d.%d.%d", pcount%1000, rows, cols, i);
+ DICOMDataObject *D = new DICOMDataObject;
+ VR *aVR;
+ aVR = new VR(0x0008, 0x1150, strlen("1.2.840.10008.5.1.1.4 "), (void *)"1.2.840.10008.5.1.1.4", FALSE);
+ D->Push(aVR);
+ aVR = new VR(0x0008, 0x1155, (strlen(uid2)+1)&0xfffe, (void *)uid2, TRUE); //leak
+ D->Push(aVR);
+ SQE->Add(D);
+ }
+
+ pcount++;
+ DDO->Push(vrs);
+
+ CreateBasicFilmBox++;
+ if (DebugLevel>=3) NonDestructiveDumpDICOMObject(DDO);
+ BOOL r = CreateBasicFilmBoxResponse.Write(PDU, DCO, &Uid, 0, DDO);
+ delete DDO;
+ return r;
+ }
+
+ if (ActionBasicFilmBoxRequest.Read(DCO, PDU, DDO))
+ {
+ OperatorConsole.printf("Printing Basic Film Box\n");
+ if (DebugLevel>=3) NonDestructiveDumpDICOMObject(DDO);
+ ActionBasicFilmBox++;
+ delete DDO;
+ return ActionBasicFilmBoxResponse.Write(PDU, DCO, NULL, 0, 0, NULL);
+ }
+
+ if (SetBasicFilmBoxRequest.Read(DCO, PDU, DDO))
+ {
+ PrintData[2] = DDO;
+ OperatorConsole.printf("Set Basic Film Box\n");
+ if (DebugLevel>=3) NonDestructiveDumpDICOMObject(DDO);
+ SetBasicFilmBox++;
+ delete DDO;
+ return SetBasicFilmBoxResponse.Write(PDU, DCO, NULL, 0, NULL);
+ }
+
+ if (DeleteBasicFilmBoxRequest.Read(DCO, PDU))
+ {
+ OperatorConsole.printf("Deleting Basic Film Box\n");
+ //delete PrintData[2];
+ //PrintData[2] = NULL;
+ DeleteBasicFilmBox++;
+ delete DDO;
+ return DeleteBasicFilmBoxResponse.Write(PDU, DCO, &Uid, 0);
+ }
+ }
+
+ else if (strcmp(szPrintSOP, "1.2.840.10008.5.1.1.4") == 0)
+ {
+ if (SetBasicGrayScaleImageBoxRequest.Read(DCO, PDU, DDO))
+ {
+ if (DebugLevel>=3) NonDestructiveDumpDICOMObject(DDO);
+ vr = DCO->GetVR(0x0000, 0x1001);
+ if (vr)
+ {
+ memset(Filename, 0, 1024);
+ GetPhysicalDevice("MAG0", Filename);
+ strcat(Filename, "printer_files");
+ mkdir(Filename);
+ i = strlen(Filename);
+ Filename[i] = PATHSEPCHAR;
+ Filename[i+1] = 0;
+ memcpy(Filename + strlen(Filename), vr->Data, vr->Length);
+ strcat(Filename, ".dcm");
+ }
+
+ //OperatorConsole.printf("Setting Basic GrayScale ImageBox\n");
+
+ vr = DDO->GetVR(0x2020, 0x0110);
+ if(vr && vr->SQObjectArray)
+ {
+ Array < DICOMDataObject * > *aSQArray;
+ aSQArray = (Array < DICOMDataObject * > *) vr->SQObjectArray;
+ if ( aSQArray->GetSize() )
+ {
+ PDU->SaveDICOMDataObject(Filename, DICOM_CHAPTER_10_EXPLICIT, aSQArray->Get(0));
+ OperatorConsole.printf("Print file: %s\n", Filename);
+ }
+ }
+
+ SetBasicGrayScaleImageBox++;
+ delete DDO;
+ return SetBasicGrayScaleImageBoxResponse.Write(PDU, DCO, NULL, 0, NULL);
+ }
+ }
+
+ else if (strcmp(szPrintSOP, "1.2.840.10008.5.1.1.4.1") == 0)
+ {
+ if (SetBasicColorImageBoxRequest.Read(DCO, PDU, DDO))
+ {
+ if (DebugLevel>=3) NonDestructiveDumpDICOMObject(DDO);
+ vr = DCO->GetVR(0x0000, 0x1001);
+ if (vr)
+ {
+ memset(Filename, 0, 1024);
+ GetPhysicalDevice("MAG0", Filename);
+ strcat(Filename, "printer_files");
+ mkdir(Filename);
+ i = strlen(Filename);
+ Filename[i] = PATHSEPCHAR;
+ Filename[i+1] = 0;
+ memcpy(Filename + strlen(Filename), vr->Data, vr->Length);
+ strcat(Filename, ".dcm");
+ }
+
+ //OperatorConsole.printf("Setting Basic Color ImageBox\n");
+
+ vr = DDO->GetVR(0x2020, 0x0111);
+ if(vr && vr->SQObjectArray)
+ {
+ Array < DICOMDataObject * > *aSQArray;
+ aSQArray = (Array < DICOMDataObject * > *) vr->SQObjectArray;
+ if ( aSQArray->GetSize() )
+ {
+ PDU->SaveDICOMDataObject(Filename, DICOM_CHAPTER_10_EXPLICIT, aSQArray->Get(0));
+ OperatorConsole.printf("Print file: %s\n", Filename);
+ }
+ }
+
+ SetBasicColorImageBox++;
+ delete DDO;
+ return SetBasicColorImageBoxResponse.Write(PDU, DCO, NULL, 0, NULL);
+ }
+ }
+ }
+ delete DDO;
+ return FALSE;
+ }
+
+///////////////////////////// elementary storage commitment support as SCP //////////////////////////
+//////////// storage commitment as SCU would be needed for a safe Move/Delete operation /////////////
+
+/* first is a sample transaction
+
+SEND ASSOCIATE-RQ (
+PRESENTATION-CONTEXT-ITEMS
+("Storage Commitment Push Model SOP Class", "Implicit VR Little Endian")
+)
+
+RECEIVE ASSOCIATE-AC (
+PRESENTATION-CONTEXT-ITEMS
+("Storage Commitment Push Model SOP Class", 0, "Implicit VR Little Endian")
+)
+
+
+SEND N-ACTION-RQ "Commitment Push" (
+(0x00000003, "Storage Commitment Push Model SOP Class")
+(0x00001001, "1.2.840.10008.1.20.1.1") # Well-known Instance UID
+(0x00001008, 1) # Request Storage Commitment
+
+(0x00081195, UI, "NEW:TransactionUID") # Transaction UID
+(0x00081199, SQ,
+>(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID
+>(0x00081155, UI, "NEW:ImageInstanceUID1") # Referenced SOP Instance UID
+,
+>(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID
+>(0x00081155, UI, "NEW:ImageInstanceUID2") # Referenced SOP Instance UID
+,
+>(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID
+>(0x00081155, UI, "NEW:ImageInstanceUID3") # Referenced SOP Instance UID
+,
+>(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID
+>(0x00081155, UI, "NEW:ImageInstanceUID4") # Referenced SOP Instance UID
+) # Referenced SOP Sequence
+(0x00081111, SQ,
+>(0x00081150, UI, "1.2.840.10008.3.1.2.3.3") # Referenced SOP Class UID
+>(0x00081155, UI, "NEW:MppsUID") # Referenced SOP Instance UID
+) # Referenced Study Component Sequence
+)
+
+RECEIVE N-ACTION-RSP (
+(0x00000002, "Storage Commitment Push Model SOP Class")
+(0x00001000, "1.2.840.10008.1.20.1.1") # Well-known Instance UID
+(0x00000900, 0x0000)
+)
+
+
+SEND RELEASE-RQ
+RECEIVE RELEASE-RP
+
+
+RECEIVE ASSOCIATE-RQ (
+PRESENTATION-CONTEXT-ITEMS
+("Storage Commitment Push Model SOP Class", "Implicit VR Little Endian")
+)
+
+SEND ASSOCIATE-AC (
+PRESENTATION-CONTEXT-ITEMS
+("Storage Commitment Push Model SOP Class", 0, "Implicit VR Little Endian")
+)
+
+
+RECEIVE N-EVENT-REPORT-RQ "Commitment Push" (
+(0x00000002, "Storage Commitment Push Model SOP Class")
+(0x00001000, "1.2.840.10008.1.20.1.1") # Well-known Instance UID
+(0x00001002, 1) # Storage Commitment Request Successful
+
+(0x00081195, UI, "TransactionUID") # Transaction UID
+(0x00080054, AE, "ARCHIVE") # Retrieve AE Title
+(0x00081199, SQ,
+>(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID
+>(0x00081155, UI, "ImageInstanceUID1") # Referenced SOP Instance UID
+,
+>(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID
+>(0x00081155, UI, "ImageInstanceUID2") # Referenced SOP Instance UID
+,
+>(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID
+>(0x00081155, UI, "ImageInstanceUID3") # Referenced SOP Instance UID
+,
+>(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID
+>(0x00081155, UI, "ImageInstanceUID4") # Referenced SOP Instance UID
+) # Referenced SOP Sequence
+)
+
+SEND N-EVENT-REPORT-RSP (
+(0x00000002, "Storage Commitment Push Model SOP Class")
+(0x00001000, "1.2.840.10008.1.20.1.1") # Well-known Instance UID
+(0x00000900, 0x0000)
+)
+
+
+RECEIVE RELEASE-RQ
+SEND RELEASE-RP
+*/
+
+class ASCPRQ : public NActionRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.1.20.1"); return TRUE; }
+ };
+
+class ASCPRSP : public NActionRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.1.20.1"); return TRUE; }
+ };
+
+class ESCPRQ : public NEventReportRQ
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.1.20.1"); return TRUE; }
+ };
+
+class ESCPRSP : public NEventReportRSP
+ {
+ public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.1.20.1"); return TRUE; }
+ };
+
+BOOL StorageApp :: StorageCommitmentSupport( CheckedPDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject **CommitData)
+ {
+ VR *vr;
+ DICOMCommandObject DCOR;
+ char Sop[65], Calling[20];
+ BYTE ip[64], port[64], compress[64];
+ int nfail=0;
+ BOOL status;
+
+ UID StorageCommitmentPushModelClassUID("1.2.840.10008.1.20.1");
+ UID StorageCommitmentPushModelInstanceUID("1.2.840.10008.1.20.1.1");
+
+ ASCPRQ ActionStorageCommitmentPushRequest;
+ ASCPRSP ActionStorageCommitmentPushResponse;
+
+ ESCPRQ EventStorageCommitmentPushRequest;
+ ESCPRSP EventStorageCommitmentPushResponse;
+
+ // association was closed after action: send response on new association
+
+ if (*CommitData)
+ {
+ PDU_Service PDU2;
+ UID uid;
+
+ strcpy(Calling, (char *)(((AAssociateAC *)PDU)->CallingApTitle));
+ while (strlen(Calling) && Calling[strlen(Calling)-1]==' ') Calling[strlen(Calling)-1] = 0;
+
+ PDU2.AttachRTC(&VRType);
+ if(!GetACRNema(Calling, (char *)ip, (char *)port, (char *)compress))
+ {
+ OperatorConsole.printf("*** Storage commitment - host not found: %s\n", Calling);
+ return FALSE;
+ }
+
+ PDU2.ClearAbstractSyntaxs();
+ PDU2.SetLocalAddress(MYACRNEMA);
+ PDU2.SetRemoteAddress((unsigned char *)Calling);
+
+ uid.Set("1.2.840.10008.3.1.1.1"); // Application context (DICOM App)
+ PDU2.SetApplicationContext(uid);
+
+ uid.Set("1.2.840.10008.1.20.1");
+ PDU2.AddAbstractSyntax(uid);
+
+ PDU2.SetTimeOut(TCPIPTimeOut);
+
+ // Make new association for EVENT on port/ip
+ if(!PDU2.Connect(ip, port))
+ {
+ OperatorConsole.printf("*** Storage commitment - failed to reconnect to %s (%s %s) for N-EVENT\n", Calling, ip, port);
+ return FALSE;
+ }
+
+ status = EventStorageCommitmentPushRequest.Write(&PDU2, *CommitData, &StorageCommitmentPushModelInstanceUID, nfail==0 ? 1 : 2);
+ if (status)
+ {
+ status = PDU2.Read(&DCOR);
+ if (status)
+ {
+ EventStorageCommitmentPushResponse.Read(&DCOR, &PDU2, NULL);
+ PDU2.Close();
+ return FALSE;
+ }
+ }
+
+ PDU2.Close();
+ return FALSE;
+ }
+
+ // is this a storage commitment action request ?
+
+ vr = DCO->GetVR(0x0000, 0x0003);
+ if (!vr) return FALSE;
+ strncpy(Sop, (char*)vr->Data, vr->Length);
+ Sop[vr->Length] = 0;
+ if (strcmp(Sop, "1.2.840.10008.1.20.1")!=0) return FALSE;
+
+ vr = DCO->GetVR(0x0000, 0x1001);
+ if (!vr) return FALSE;
+ strncpy(Sop, (char*)vr->Data, vr->Length);
+ Sop[vr->Length] = 0;
+ if (strcmp(Sop, "1.2.840.10008.1.20.1.1")!=0) return FALSE;
+
+ vr = DCO->GetVR(0x0000, 0x1008);
+ if (!vr) return FALSE;
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ if ((int)(*((unsigned short*)vr->Data))!=1) return FALSE;
+#else //Big Endian like Apple power pc
+ if ((int)SwitchEndian(*((unsigned short*)vr->Data))!=1) return FALSE;
+#endif
+
+ // read and acknowledge the action
+
+ *CommitData = new DICOMDataObject;
+ if (ActionStorageCommitmentPushRequest.Read(DCO, PDU, *CommitData))
+ {
+ OperatorConsole.printf("Storage commitment request recieved\n");
+ if (!ActionStorageCommitmentPushResponse.Write(PDU, DCO, &StorageCommitmentPushModelInstanceUID, 1, 0, NULL))
+ return FALSE;
+
+ // delete retired study component sequence if there
+
+ vr = (*CommitData)->GetVR(0x0008, 0x1111);
+ if (vr) (*CommitData)->DeleteVR(vr);
+
+ // add AE title
+
+ SetStringVR(&vr, 0x0008, 0x0054, (char*)MYACRNEMA);
+ (*CommitData)->Push(vr);
+
+ // todo:
+ // check presence of each SOPInstance 0008,1155 in sequence 0008,1199
+ // move failures from sequence 0008,1199 to sequence 0008,1198
+ // count failures in nfail
+
+ // write an event (on same association) with results
+
+ Sleep(200);
+
+ status = EventStorageCommitmentPushRequest.Write(PDU, *CommitData, &StorageCommitmentPushModelInstanceUID, nfail==0 ? 1 : 2);
+
+ if (status)
+ {
+ status = PDU->Read(&DCOR);
+ if (status)
+ {
+ EventStorageCommitmentPushResponse.Read(&DCOR, PDU, NULL);
+ delete *CommitData;
+ *CommitData = NULL;
+ return TRUE;
+ }
+ }
+
+ // in this case, the link was closed: create a new link and try to send response again
+ return FALSE;
+ }
+
+ return FALSE;
+ }
+
+void CloneDB(char *AE)
+{ VR *vr1;
+ VR *vr;
+ DICOMDataObject DDO;
+ Array < DICOMDataObject * > ADDO;
+ char patid[66];
+ int len;
+
+ SetStringVR(&vr1, 0x0010, 0x0020, "");
+ DDO.Push(vr1);
+ SetStringVR(&vr1, 0x0008, 0x0052, "PATIENT");
+ DDO.Push(vr1);
+ VirtualQuery(&DDO, "PATIENT", 0, &ADDO, AE);
+
+ for (unsigned int i=0; i<ADDO.GetSize(); i++)
+ { while((vr=ADDO.Get(i)->Pop()))
+ { if (0x0020==vr->Element && 0x0010==vr->Group)
+ { strncpy(patid, (char*)vr->Data, vr->Length);
+ patid[vr->Length] = 0;
+ len = vr->Length - 1;
+ while(len>0)
+ { if (patid[len] == ' ')
+ patid[len] = 0;
+ else
+ break;
+ len--;
+ }
+
+ OperatorConsole.printf("cloning db for patient id=%s\n", patid);
+
+ DDO.Reset();
+ SetStringVR(&vr1, 0x0010, 0x0020, patid);
+ DDO.Push(vr1);
+ SetStringVR(&vr1, 0x0008, 0x0052, "IMAGE");
+ DDO.Push(vr1);
+ VirtualQueryToDB(&DDO, 0, AE);
+ }
+
+ delete vr;
+ }
+ delete ADDO.Get(i);
+ }
+
+ OperatorConsole.printf("clone db done\n");
+}
+
+static void NewTempFile(char *name, const char *ext)
+ {
+ int i;
+ char name2[70], szTemp[256], szRootSC[256];
+
+ MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile);
+ MyGetPrivateProfileString(szRootSC, "TempDir", "", szTemp, 64, ConfigFile);
+
+ if (szTemp[0]==0)
+ {
+ name[0]=0;
+ GetPhysicalDevice("MAG0", name);
+ strcat(name, "printer_files");
+ }
+ else
+ strcpy(name, szTemp);
+
+ mkdir(name);
+
+ i = strlen(name);
+ name[i] = PATHSEPCHAR;
+ name[i+1] = 0;
+
+ GenUID(name2);
+ strcat(name2, ext);
+
+ strcat(name, name2);
+ }
+
+BOOL
+MakeQueryString ( DBENTRY *DBE, char *s)
+ {
+ UINT Index;
+// char TempString [ 128 ];
+
+ s[0] = '\0';
+
+ Index = 0;
+ while ( TRUE )
+ {
+ if(!DBE [ Index ].Element)
+ return ( TRUE );
+
+ if (DBE[Index].DICOMType!=DT_STARTSEQUENCE && DBE[Index].DICOMType!=DT_ENDSEQUENCE)
+ {
+ if(Index)
+ strcat(s, ", ");
+
+ strcat ( s, DBE [ Index ].SQLColumn);
+ }
+
+ ++Index;
+ }
+
+ return ( TRUE );
+ }
+
+BOOL MakeSafeStringValues (VR *vr, char *string);
+static BOOL DcmEcho(const char *AE);
+
+static char* CommaInFilenameWorkAround(char* SilentText)
+{ char* pComma;
+ char* pCopy;
+
+ pComma = strchr(SilentText, ',');
+ while (pComma)
+ { /* */
+ pCopy = strdup(pComma);
+ strlwr(pCopy);
+ if ((strstr(pCopy, ".dcm") != NULL) || (strstr(pCopy, ".v2") != NULL) ||
+ (strstr(pCopy, ".hl7") != NULL) || (strstr(pCopy, ".gz") != NULL))
+ { /* The comma is apparently part of a filename; search for the next comma */
+ free(pCopy);
+ pComma = strchr(pComma + 1, ',');
+ }
+ else
+ { free(pCopy);
+ break;
+ }
+ }
+ return pComma;
+}
+
+BOOL StorageApp :: ServerChild (int theArg )
+ {
+ ExtendedPDU_Service PDU ( SOPClassFile );
+ DICOMCommandObject DCO;
+ DICOMDataObject *DDO;
+ VR *vr;
+// VR *vr1;
+ VR *vrsilent;
+ UINT16 val, messageid, orgmessageid;
+ Database DB1;
+ int socketfd = theArg;
+ char SilentText[64000];
+ char TimeString[128];
+ time_t TimeOfDay, TimeOfDay2;
+ int FirstTime=1;
+ int ThreadNum;
+ DICOMDataObject *PrintData[100];
+ char OrgMoveAE[17], OwnAE[17];
+ char blank[] = "";
+
+#ifdef __GNUC__ //Warnings
+ vrsilent = NULL;
+ ThreadNum = 0;
+#endif
+ DebugLevel=DebugVRs;
+ TimeOfDay = time(NULL);
+
+ PDU.AttachRTC(&VRType);
+ PDU.SetTimeOut(TCPIPTimeOut);
+
+ // defined here to make thread safe: multiple instances of SOPUnknownStorage.DB required
+ MyUnknownStorage SOPUnknownStorage;
+
+ Verification SOPVerification;
+ MyPatientRootQuery SOPPatientRootQuery;
+ MyPatientRootRetrieve SOPPatientRootRetrieve;
+ MyPatientRootRetrieveNKI SOPPatientRootRetrieveNKI;
+ MyPatientRootRetrieveGeneric SOPPatientRootRetrieveGeneric;
+
+ MyStudyRootQuery SOPStudyRootQuery;
+ MyStudyRootRetrieve SOPStudyRootRetrieve;
+ MyStudyRootRetrieveNKI SOPStudyRootRetrieveNKI;
+ MyStudyRootRetrieveGeneric SOPStudyRootRetrieveGeneric;
+
+ MyPatientStudyOnlyQuery SOPPatientStudyOnlyQuery;
+ MyPatientStudyOnlyRetrieve SOPPatientStudyOnlyRetrieve;
+ MyPatientStudyOnlyRetrieveNKI SOPPatientStudyOnlyRetrieveNKI;
+ MyPatientStudyOnlyRetrieveGeneric SOPPatientStudyOnlyRetrieveGeneric;
+
+ MyModalityWorkListQuery SOPModalityWorkListQuery;
+
+ struct ReadAheadThreadData ratd;
+
+ WipeStack();
+ if(!PDU.Multiplex ( socketfd ))
+ {
+ OperatorConsole.printf("*** multiplex: connection terminated\n");
+ return ( FALSE );
+ }
+
+ memset(&ratd, 0, sizeof(ratd));
+
+ if (!DB1.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ SystemDebug.printf("***Error connecting: %s %s/%s\nRetrying\n",
+ DataSource, UserName, Password );
+ if (!DB1.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ OperatorConsole.printf("***Error connecting datasource:%s user:%s password:%s\n",
+ DataSource, UserName, Password );
+
+#ifdef FAILSAFE_STORAGE
+ FailSafeStorage(&PDU);
+#endif
+
+ PDU.Close();
+ return ( FALSE );
+ }
+ }
+
+ ThreadNum = ThreadCount++;
+ PDU.ThreadNum = ThreadNum;
+ OpenThreadCount++;
+
+ char lua_association[1024];
+ char lua_command[1024];
+ char lua_endassociation[1024];
+ char lua_clienterror[1024];
+
+ MyGetPrivateProfileString("lua", "association", "", lua_association, 1024, ConfigFile);
+ MyGetPrivateProfileString("lua", "command", "", lua_command, 1024, ConfigFile);
+ MyGetPrivateProfileString("lua", "endassociation", "", lua_endassociation, 1024, ConfigFile);
+ MyGetPrivateProfileString("lua", "clienterror", "", lua_clienterror, 1024, ConfigFile);
+
+ struct scriptdata sd1 = {&PDU, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, 0, ConnectedIP};
+ do_lua(&(PDU.L), lua_association, &sd1);
+ if (sd1.DDO) delete sd1.DDO;
+ if (sd1.rc==2 || sd1.rc==6) return TRUE; // reject association
+
+ // pass the DB to the read ahead thread for getting filenames.
+ // NOTE: THIS MEANS THAT THE DB MAY NOT BE USED WHILE RATD IS ACTIVE TO BE THREAD SAFE
+ ratd.DB = &DB1;
+
+ while(TRUE)
+ {
+#ifdef UNIX
+#ifndef DARWIN
+#ifndef SOLARIS
+ if (DebugLevel>0)
+ malloc_stats();
+#endif //SOLARIS
+#endif //DARWIN
+#endif
+ DCO.Reset();
+
+ if (!PDU.Read(&DCO))
+ {
+ if (FirstTime)
+ {
+ char buf[64];
+ UNUSED_ARGUMENT(buf);//Stop gcc4.2 warning bcb
+ strcpy(TimeString, ctime_r(&TimeOfDay, buf));
+ TimeString[strlen(TimeString)-1] = '\0';
+ OperatorConsole.printf("\n");
+ OperatorConsole.printf("UPACS THREAD %d: STARTED AT: %s\n", ThreadNum, TimeString);
+ if (PDU.ValidPresContexts)
+ OperatorConsole.printf("*** connection terminated\n");
+ else
+ {
+ IARQ ( PDU, TRUE );
+ OperatorConsole.printf("*** Association rejected: you may need to add the listed presentation context as sop to dgatesop.lst\n");
+ }
+ }
+
+ PDU.Link.Connected = FALSE;
+
+ // Indicates that the connection is closed and avoids an attempt
+ // to send and receive data while the socket is closed. Alternatively,
+ // call Link.Close() in PDU_Service::Read() after handling A-RELEASE-RQ.
+ // See the following statements in pdu.cxx:
+ //
+ // BOOL PDU_Service :: Read(DICOMObject *DCMObject)
+ // relevant statements:
+ // case 0x05: // A-RELEASE-RQ
+ // AReleaseRQ :: ReadDynamic(*this);
+ // // also drop
+ // AReleaseRP :: Write(*this);
+ // return ( FALSE );
+ //
+ // and
+ //
+ // BOOL PDU_Service :: Close()
+ // relevant statements:
+ // if ( Link.Connected )
+ // {
+ // AReleaseRQ :: Write ( *this );
+ // AReleaseRP :: Read ( *this );
+ // }
+ //
+ // which is called by:
+ // PDU_Service :: ~PDU_Service()
+ // {
+ // if(Link.Connected)
+ // Close();
+ // (..)
+
+ break;
+ }
+
+ struct scriptdata sd2 = {&PDU, &DCO, NULL, 0, NULL, NULL, NULL, NULL, NULL, 0, ConnectedIP};
+ do_lua(&(PDU.L), lua_command, &sd2);
+ if (sd2.DDO) delete sd2.DDO;
+ if (sd2.rc==2 || sd2.rc==6) return TRUE; // reject comnmand - closes connection
+
+ // 20060607 mvh Fix for multiple moves on same assoc (thanks Andrej Savelov)
+ ratd.TimeOut = FALSE;
+ ratd.ForceEnd = FALSE;
+ ratd.Busy = FALSE;
+
+ SilentText[0]=0;
+ vrsilent = DCO.GetVR(0x9999, 0x0400);
+ if (vrsilent)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ if ( *((unsigned int*)vrsilent->Data) == 0x44414544)
+#else //Big Endian like Apple power pc
+ if ( SwitchEndian(*((unsigned int*)vrsilent->Data)) == 0x44414544)
+#endif
+ { FirstTime = FirstTime-1;
+ FirstTime = (FirstTime+1) / FirstTime;
+ }
+
+ if(vrsilent->Length)
+ { memcpy(SilentText, vrsilent->Data, vrsilent->Length);
+ SilentText[vrsilent->Length]=0;
+ if (SilentText[vrsilent->Length-1]==' ') SilentText[vrsilent->Length-1]=0;
+ }
+ }
+ else
+ IncomingAssociations++; // do not count associations from GUI
+
+ if (FirstTime)
+ {
+ if (!vrsilent)
+ {
+ // Print Date / Time in Log file
+ char buf[64];
+ UNUSED_ARGUMENT(buf);//Stop gcc4.2 warning bcb
+ strcpy(TimeString, ctime_r(&TimeOfDay, buf));
+ TimeString[strlen(TimeString)-1] = '\0';
+ OperatorConsole.printf("\n");
+ OperatorConsole.printf("UPACS THREAD %d: STARTED AT: %s\n", ThreadNum, TimeString);
+
+ IARQ ( PDU, FALSE );
+ }
+ FirstTime = 0;
+ }
+
+ messageid = DCO.GetUINT16(0x0000, 0x0110);
+ orgmessageid = DCO.GetUINT16(0x0000, 0x1031);
+
+ /* get OrgMoveAE */
+ OrgMoveAE[0]=0;
+ vr = DCO.GetVR(0x0000, 0x1030);
+ if (vr)
+ {
+ memset(OrgMoveAE, ' ', 16); OrgMoveAE[16]=0;
+ memcpy(OrgMoveAE, (char *)(vr->Data), vr->Length);
+ }
+
+ if (!vrsilent)
+ {
+ val = DCO.GetUINT16(0x0000, 0x0100);
+ SystemDebug.printf("Server Command := %4.4x\n", val);
+ SystemDebug.printf("Message ID := %4.4x\n", messageid);
+ if (orgmessageid) SystemDebug.printf("Move Originator Message ID := %4.4x\n", orgmessageid);
+ if (OrgMoveAE[0]) SystemDebug.printf("Move Originator AE := %s\n", OrgMoveAE);
+ }
+
+ /* print C-Move destination to console */
+ VR *vr1 = DCO.GetVR(0x0000, 0x0600);
+ if (vr1 && !vrsilent)
+ {
+ char text[256];
+ memset(text, 0, 256);
+ memcpy(text, (char *)(vr1->Data), vr1->Length);
+ OperatorConsole.printf("\tC-Move Destination: \"%s\"\n", text);
+ }
+
+ if (DebugLevel>=1) NonDestructiveDumpDICOMObject(&DCO);
+
+ /* check for NKI specific command command vr: echo to console */
+ vr = DCO.GetVR(0x9999, 0x0300);
+ if (vr)
+ {
+ char text[1024];
+ memset(text, 0, 1024);
+ memcpy(text, (char *)(vr->Data), vr->Length);
+ OperatorConsole.printf("%s\n", text);
+ }
+
+ DDO = new DICOMDataObject;
+ SOPUnknownStorage.DB = &DB1;
+
+ SOPUnknownStorage.nopreget = FALSE;
+
+ // special: moves to self are blocked from triggering a move to self
+ if (orgmessageid==0xfbad)
+ {
+ sprintf(OwnAE, "%-16s", MYACRNEMA);
+ SOPUnknownStorage.nopreget = memcmp(OwnAE, OrgMoveAE, 16)==0; // avoid loops
+ }
+
+ // special: moves to self for WADO bridge: image is saved, converted and deleted
+ if (orgmessageid==0x2bad)
+ {
+ sprintf(OwnAE, "%-16s", MYACRNEMA);
+ if (memcmp(OwnAE, OrgMoveAE, 16)==0)
+ {
+ MyBridgeStorage SOPBridgeStorage;
+ SOPBridgeStorage.Read(&PDU, &DCO, DDO);
+ continue;
+ }
+ }
+
+ if(SOPUnknownStorage.Read(&PDU, &DCO, DDO))
+ {
+ LogUser("C-Store", &PDU, &DCO);
+ continue;
+ }
+ else
+ {
+ if(DCO.GetUINT16(0x0000, 0x0100)==1)
+ {
+ DebugLevel += 4;
+ SystemDebug.printf("Failed STORAGE\n");
+ NonDestructiveDumpDICOMObject(DDO);
+ DebugLevel -= 4;
+
+ delete DDO; // 20090926
+ continue;
+ }
+ delete DDO; // moved one line down: leak !!!!
+ }
+ // delete DDO; was double 20030704
+
+ if (SOPVerification.ReadRequest(&PDU, &DCO))
+ {
+ char Response[512];
+ Response[0]=0;
+ char tempfile[256];
+ tempfile[0]=0;
+
+ if (!vrsilent)
+ {
+ OperatorConsole.printf("C-Echo\n");
+ EchoRequest++;
+ }
+
+ if (SilentText[0])
+ {
+ char *p = strchr(SilentText, ','), *q=NULL, *r1=NULL, *s1=NULL, *t1=NULL;
+ GuiRequest++;
+
+ if (memcmp(SilentText, "lua:", 4)==0)
+ {
+ struct scriptdata sd = {&PDU, &DCO, NULL, -1, NULL, NULL, NULL, NULL, NULL, 0, ConnectedIP};
+ do_lua(&(PDU.L), SilentText+4, &sd);
+ if (sd.DDO) delete sd.DDO;
+ }
+
+ if (memcmp(SilentText, "luastart:", 9)==0)
+ {
+ struct scriptdata sd = {&PDU, &DCO, NULL, -1, NULL, NULL, NULL, NULL, NULL, 0, ConnectedIP};
+ PDU.Link.Close();
+ do_lua(&(PDU.L), SilentText+9, &sd);
+ if (sd.DDO) delete sd.DDO;
+ }
+
+ else if (memcmp(SilentText, "extract:", 8)==0)
+ {
+ char t[512], u[512];
+ Database DB;
+ char fld[48][256];
+ SQLLEN SQLResultLength;
+
+ if (DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ if (DB.db_type == DT_DBASEIII && SilentText[8])
+ {
+ sprintf(t, "%sX%s.DBF", DataSource, PatientTableName);
+ DB.ExtractRecords("DICOMPatients",SilentText+8, t);
+ sprintf(t, "%sX%s.DBF", DataSource, StudyTableName);
+ DB.ExtractRecords("DICOMStudies", SilentText+8, t);
+ sprintf(t, "%sX%s.DBF", DataSource, SeriesTableName);
+ DB.ExtractRecords("DICOMSeries", SilentText+8, t);
+ sprintf(t, "%sX%s.DBF", DataSource, ImageTableName);
+ DB.ExtractRecords("DICOMImages", SilentText+8, t);
+ //sprintf(t, "%sX%s.DBF", DataSource, WorkListTableName);
+ //DB.ExtractRecords(WorkListTableName, SilentText+8, t);
+ }
+ else
+ {
+ char s[8192];
+ char TempString[512];
+ char Physical[512];
+ Database DB2(DT_DBASEIIINOINDEX);
+ GetPhysicalDevice("MAG0", Physical);
+ sprintf(Physical+strlen(Physical), "dbase%c", PATHSEPCHAR);
+ DB2.Open ( Physical, "", "", "");
+ DBENTRY *dbe;
+ char *tabname;
+ int i, k;
+
+ dbe = NULL;
+ tabname = NULL;
+ for (int j=0; j<5; j++)
+ {
+ switch(j)
+ {
+ case 0: dbe = PatientDB; tabname = PatientTableName; break;
+ case 1: dbe = PatientDB; tabname = PatientTableName; break;
+ case 2: dbe = StudyDB; tabname = StudyTableName; break;
+ case 3: dbe = SeriesDB; tabname = SeriesTableName; break;
+ case 4: dbe = ImageDB; tabname = ImageTableName; break;
+ }
+
+ MakeTableString(dbe, s, 1);
+ MakeQueryString(dbe, t);
+ strcat(s, ", AccessTime int, qTimeStamp int, qFlags int, qSpare varchar(64)" );
+ strcat(t, ", AccessTime, qTimeStamp, qFlags, qSpare" );
+ if (j==4)
+ {
+ strcat(s, ", ObjectFile varchar(255), DeviceName varchar(32)");
+ strcat(t, ", ObjectFile, DeviceName");
+ }
+
+ for (i=0, k=0; i<999 && dbe[i].Group!=0; i++) k++; // count fields
+ if (j==4) k+=6; else k+=4;
+
+ if (j==0) sprintf(u, "XA%s", tabname); // all patients
+ else sprintf(u, "X%s", tabname);
+ DB2.CreateTable (u, s);
+
+ if (j==3)
+ { p = strstr(SilentText+8, "PatientID");
+ if (p) memcpy(p, "SeriesPat", 9);
+ }
+ else if (j==4)
+ { p = strstr(SilentText+8, "SeriesPat");
+ if (p) memcpy(p, "ImagePat ", 9);
+ }
+
+ if (j!=0) DB.Query(tabname, t, SilentText+8, NULL);
+ else DB.Query(tabname, t, NULL, NULL); // all patients
+
+ for (i=0; i<k; i++)
+ DB.BindField(i+1, SQL_C_CHAR, fld[i], 255, &SQLResultLength);
+ memset(fld, 0, sizeof(fld));
+
+ while (DB.NextRecord())
+ {
+ s[0]=0;
+ for (int i1=0; i1<k; i1++)
+ {
+ VR vr2;
+ vr2.Data = fld[i1];
+ vr2.Length = strlen(fld[i1]);
+ if (i1) strcat ( s, ", ");
+
+ MakeSafeStringValues ( &vr2, TempString );
+ vr2.Data = NULL;
+ vr2.Length = 0;
+ strcat ( s, TempString );
+ }
+ DB2.AddRecord(u, t, s);
+ }
+
+ if (SilentText[8]==0) break;
+ }
+ }
+ ExtractFromGui++;
+ }
+ }
+
+ else if (memcmp(SilentText, "query:", 6)==0 || memcmp(SilentText, "query2:", 7)==0 )
+ {
+ int n=1;
+ unsigned int i, L, mx, flds=1;
+ char *items[6];
+ SQLLEN SQLResultLength;
+ memset(items, 0, sizeof(items));
+
+ p = strchr(SilentText, ':')+1;
+ items[0]=p;
+ L = strlen(p);
+ for (i=0; i<L; i++)
+ {
+ if (p[i]=='|')
+ {
+ p[i]=0;
+ items[n++] = p+i+1;
+ if(n==6) break;
+ }
+ }
+
+ if (memcmp(SilentText, "query2:", 7)==0) p=items[5], mx=items[4] ? atoi(items[4]): 0;
+ else p=items[4], mx=0;
+
+ if (items[1])
+ for (i=0; i<strlen(items[1]); i++)
+ if (items[1][i]==',') flds++;
+
+ Database DB;
+ if (DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ char fld[48][256];
+ FILE *f;
+ char format[8192];
+ int pstars, first=1;
+
+ if (items[3]) strcpy(format, items[3]);
+ else for (i=0; i<flds; i++) strcat (format, "%s ");
+
+ pstars = format[strlen(format)-1] == '*';
+ if (!pstars) strcat(format, "\n"); else format[strlen(format)-1]=0;
+ memset(fld, 0, sizeof(fld));
+
+ if (items[2])
+ if (*items[2]==0) items[2]=NULL;
+
+ if (mx)
+ {
+ DB.Query(items[0], items[1], items[2], NULL);
+ for (i=0; i<flds; i++)
+ DB.BindField (i+1, SQL_C_CHAR, fld[i], 255, &SQLResultLength);
+ i = 0;
+ while (DB.NextRecord()) i++;
+ if (i>mx) mx=(i+mx-1)/mx; else mx=0;
+ }
+
+ DB.Query(items[0], items[1], items[2], NULL);
+ for (i=0; i<flds; i++)
+ DB.BindField (i+1, SQL_C_CHAR, fld[i], 255, &SQLResultLength);
+ if (p==NULL || *p==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ }
+ else if (strcmp(p, "cgi")==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ fprintf(f, "Content-type: text/html\n\n");
+ }
+ else
+ f = fopen(p, "wt");
+
+ n=0;
+ for (i=0; i<48; i++) fld[i][0]=0;
+ while (DB.NextRecord())
+ {
+ if (mx) if ((n++) % mx) continue;
+ for (i=flds; i<48; i++) strcpy(fld[i], fld[i%flds]); // duplicate fields
+
+ if (!first && pstars) fprintf(f, "*");
+ first=0;
+
+ fprintf(f, format, fld[0], fld[1], fld[2], fld[3], fld[4], fld[5], fld[6], fld[7],
+ fld[8], fld[9], fld[10],fld[11],fld[12],fld[13],fld[14],fld[15],
+ fld[16],fld[17],fld[18],fld[19],fld[20],fld[21],fld[22],fld[23],
+ fld[24],fld[25],fld[26],fld[27],fld[28],fld[29],fld[30],fld[31],
+ fld[32],fld[33],fld[34],fld[35],fld[36],fld[37],fld[38],fld[39],
+ fld[40],fld[41],fld[42],fld[43],fld[44],fld[45],fld[46],fld[47]);
+ for (i=0; i<48; i++) fld[i][0]=0;
+ }
+
+ fclose(f);
+ DB.Close();
+ QueryFromGui++;
+ }
+ }
+
+ else if (memcmp(SilentText, "patientfinder:", 14)==0 ||
+ memcmp(SilentText, "studyfinder:", 12)==0 ||
+ memcmp(SilentText, "seriesfinder:", 13)==0 ||
+ memcmp(SilentText, "imagefinder:", 12)==0 )
+ {
+ char ps2[] = "%s %s";
+ char ps5[] = "%s %s %s %s %s";
+ char ps7[] = "%s %s %s %s %s %s %s";
+ int i, n=1, L;//, flds=1, mx;
+ char *items[6];
+ FILE *f;
+ char format[1024];
+
+ memset(items, 0, sizeof(items));
+
+ p = strchr(SilentText, ':')+1;
+ items[0]=p;
+ L = strlen(p);
+ for (i=0; i<L; i++)
+ {
+ if (p[i]=='|')
+ {
+ p[i]=0;
+ items[n++] = p+i+1;
+ if(n==6) break;
+ }
+ }
+ p = items[3];
+
+ if (items[2]==0 || *items[2]==0)
+ {
+ if (memcmp(SilentText, "pat", 3)==0) items[2]=ps2;
+ if (memcmp(SilentText, "stu", 3)==0) items[2]=ps5;
+ if (memcmp(SilentText, "ser", 3)==0) items[2]=ps7;
+ if (memcmp(SilentText, "ima", 3)==0) items[2]=ps7;
+ }
+ strcpy(format, items[2]);
+ strcat(format, "\n");
+
+ if (p==NULL || *p==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ }
+ else if (strcmp(p, "cgi")==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ fprintf(f, "Content-type: text/html\n\n");
+ }
+ else
+ f = fopen(p, "wt");
+
+ if (items[1]==NULL) items[1] = blank;
+ if (memcmp(SilentText, "pat", 3)==0) PatientStudyFinder(items[0], items[1], format, f, "PATIENT");
+ if (memcmp(SilentText, "stu", 3)==0) PatientStudyFinder(items[0], items[1], format, f, "STUDY");
+ if (memcmp(SilentText, "ser", 3)==0) PatientStudyFinder(items[0], items[1], format, f, "SERIES");
+ if (memcmp(SilentText, "ima", 3)==0) PatientStudyFinder(items[0], items[1], format, f, "IMAGE");
+ fclose(f);
+ }
+
+ else if (memcmp(SilentText, "imagelister:", 12)==0 ||
+ memcmp(SilentText, "serieslister:", 13)==0 )
+ {
+ int i, n=1, L;//, flds=1, mx;
+ char *items[6];
+ FILE *f;
+ char format[256];
+
+ memset(items, 0, sizeof(items));
+
+ p = strchr(SilentText, ':')+1;
+ items[0]=p;
+ L = strlen(p);
+ for (i=0; i<L; i++)
+ {
+ if (p[i]=='|')
+ {
+ p[i]=0;
+ items[n++] = p+i+1;
+ if(n==6) break;
+ }
+ }
+ p = items[4];
+
+ if (items[3]==0 || *items[3]==0)
+ strcpy(format, "%s*");
+ else
+ strcpy(format, items[3]);
+ if (format[0]!='$' && format[strlen(format)-1]!='*') strcat(format, "\n");
+
+ if (p==NULL || *p==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ }
+ else if (strcmp(p, "cgi")==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ fprintf(f, "Content-type: text/html\n\n");
+ }
+ else
+ f = fopen(p, "wt");
+
+ if (SilentText[1]=='m') ImageFileLister(items[0], items[1], NULL, items[2], NULL, format, f);
+ else SeriesUIDLister(items[0], items[1], items[2], format, f);
+ fclose(f);
+ }
+
+ else if (memcmp(SilentText, "addrecord:", 10)==0)
+ {
+ int i, n=1, L;
+ char *items[3];
+ memset(items, 0, sizeof(items));
+
+ p = SilentText+10;
+ items[0]=p;
+ L = strlen(p);
+ for (i=0; i<L; i++)
+ {
+ if (p[i]=='|')
+ {
+ p[i]=0;
+ items[n++] = p+i+1;
+ if(n==3) break;
+ }
+ }
+
+ Database DB;
+ if (DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ DB.AddRecord(items[0], items[1], items[2]);
+ DB.Close();
+ QueryFromGui++;
+ }
+ }
+
+ else if (memcmp(SilentText, "deleterecord:", 13)==0)
+ {
+ Database DB;
+ if (DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ if (p) *p++=0; // points after 1st comma
+ DB.DeleteRecord(SilentText+13, p);
+ DB.Close();
+ QueryFromGui++;
+ }
+ }
+
+ else if (memcmp(SilentText, "deleteimagefromdb:", 18)==0)
+ {
+ DeleteImageFile(SilentText+18, TRUE);
+ }
+
+ else if (memcmp(SilentText, "deletesopfromdb:", 16)==0)
+ {
+ Database DB;
+ if (DB.Open ( DataSource, UserName, Password, DataHost ) )
+ { if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ r1 = strchr(q, ',');
+ if (r1)
+ { *r1++=0; // points after 3rd comma
+ NewDeleteSopFromDB(SilentText+16, p, q, r1, DB);
+ }
+ }
+ }
+ }
+ }
+
+ else if (memcmp(SilentText, "deleteimagefile:", 16)==0)
+ {
+ DeleteImageFile(SilentText+16, FALSE);
+ DeleteImageFromGui++;
+ }
+
+ else if (memcmp(SilentText, "deletepatient:", 14)==0)
+ {
+ DeletePatient(SilentText+14, FALSE);
+ DeletePatientFromGui++;
+ }
+
+ else if (memcmp(SilentText, "deletestudy:", 12)==0)
+ {
+ DeleteStudy(SilentText+12, FALSE);
+ DeleteStudyFromGui++;
+ }
+
+ else if (memcmp(SilentText, "deletestudies:", 14)==0)
+ {
+ DeleteStudies(SilentText+14, FALSE);
+ DeleteStudiesFromGui++;
+ }
+
+ else if (memcmp(SilentText, "deleteseries:", 13)==0)
+ {
+ DeleteSeries(SilentText+13, FALSE);
+ DeleteSeriesFromGui++;
+ }
+
+ else if (memcmp(SilentText, "movepatient:", 12)==0)
+ {
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ if (DcmMove(q, SilentText+12, p, "", "", "", "", "", "", "", "", 6, ""))
+ sprintf(Response, "Move failed from %s to %s", SilentText+12, p);
+ MovePatientFromGui++;
+ }
+ }
+ }
+
+ else if (memcmp(SilentText, "movestudy:", 10)==0)
+ {
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ s1 = strchr(q, ':'); // patid optional
+ if (s1)
+ { *s1=0;
+ r1 = q;
+ q = s1+1;
+ }
+ else
+ r1 = blank;
+
+ if (DcmMove(r1, SilentText+10, p, q, "", "", "", "", "", "", "", 7, ""))
+ sprintf(Response, "Move failed from %s to %s", SilentText+10, p);
+ MoveStudyFromGui++;
+ }
+ }
+ }
+
+ else if (memcmp(SilentText, "moveaccession:", 14)==0)
+ {
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ s1 = strchr(q, ':'); // patid optional
+ if (s1)
+ { *s1=0;
+ r1 = q;
+ q = s1+1;
+ }
+ else
+ r1 = blank;
+
+ // 7777 is a magic number
+ if (DcmMove(r1, SilentText+10, p, q, "", "", "", "", "", "", "", 7777, ""))
+ sprintf(Response, "Move failed from %s to %s", SilentText+10, p);
+ MoveStudyFromGui++;
+ }
+ }
+ }
+
+ else if (memcmp(SilentText, "movestudies:", 12)==0)
+ {
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ if (DcmMove("", SilentText+12, p, "", "", "", "", q, "", "", "", 8, ""))
+ sprintf(Response, "Move failed from %s to %s", SilentText+12, p);
+ MoveStudiesFromGui++;
+ }
+ }
+ }
+
+ else if (memcmp(SilentText, "moveseries:", 11)==0)
+ {
+ t1 = blank;
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ t1 = strchr(q, ',');
+ if (t1) *t1++=0; // points after 3rd comma
+ else t1 = blank;
+
+ s1 = strchr(q, ':'); // patid optional
+ if (s1)
+ { *s1=0;
+ r1 = q;
+ q = s1+1;
+ }
+ else
+ r1 = blank;
+
+ if (DcmMove(r1, SilentText+11, p, t1, q, "", "", "", "", "", "", 9, ""))
+ sprintf(Response, "Move failed from %s to %s", SilentText+11, p);
+
+ MoveSeriesFromGui++;
+ }
+ }
+ }
+
+ else if (memcmp(SilentText, "packdbf:", 8)==0)
+ {
+ Database DB;
+ NeedPack = 3; // pack and threaded index creation
+ DB.Open ( DataSource, UserName, Password, DataHost);
+ }
+
+ else if (memcmp(SilentText, "clonedb:", 8)==0)
+ {
+ CloneDB(SilentText+8);
+ }
+
+ else if (memcmp(SilentText, "indexdbf:", 9)==0)
+ {
+ Database DB;
+ NeedPack = 4; // threaded index creation - used after full regen from GUI
+ DB.Open ( DataSource, UserName, Password, DataHost);
+ }
+
+ else if (memcmp(SilentText, "browsepatient:", 14)==0)
+ {
+ OperatorConsole.printf("Browse patient: %s\n", SilentText+14);
+ }
+
+ else if (memcmp(SilentText, "regenfile:", 10)==0)
+ RegenFile(SilentText+10);
+
+ else if (memcmp(SilentText, "addimagefile:", 13)==0)
+ {
+ p = CommaInFilenameWorkAround(SilentText);
+ //p = strchr(SilentText+13, '|');
+ if (p) *p++ = 0;
+ if ((vr = DCO.GetVR(0x9999,0x0402)))
+ {
+ char *p1 = strrchr(SilentText+13, '.');
+ if (p1) NewTempFile(tempfile, p1);
+ else NewTempFile(tempfile, "");
+ FILE *f = fopen(tempfile, "wb");
+ fwrite(vr->Data, vr->Length, 1, f);
+ fclose(f);
+ if (p) AddImageFile(tempfile, p, &PDU);
+ else AddImageFile(tempfile, NULL, &PDU);
+ unlink(tempfile);
+ tempfile[0]=0;
+ }
+ else
+ AddImageFile(SilentText+13, p, &PDU);
+ AddedFileFromGui++;
+ }
+
+ else if (memcmp(SilentText, "loadanddeletedir:", 17)==0)
+ {
+ p = CommaInFilenameWorkAround(SilentText);
+ if (p) *p++ = 0;
+ LoadAndDeleteDir(SilentText+17, p, &PDU);
+ }
+
+ else if (memcmp(SilentText, "modifypatid:", 12)==0 && p)
+ {
+ if (p) *p++=0; // points after 1st comma
+ if (p) ModifyPATIDofImageFile(p, SilentText+12, TRUE, NULL, &PDU);
+ }
+
+ else if (memcmp(SilentText, "modifyimage:", 12)==0 && p)
+ {
+ if (p)
+ { *p++=0; // points after 1st comma
+ char test[1024];
+
+ strcpy(test, p); strlwr(test);
+ if ((strstr(test, "set 0010,0020") || strstr(test, "set 0020,000d") || strstr(test, "set 0020,000e")) && strstr(test, "newuids")==0)
+ {
+ OperatorConsole.printf("[modifyimage]: can't change patientID, study or series UID without using newuids\n");
+ }
+ else
+ {
+ // used ' instead of "; detect this (set xxx to 'yyy') or (set xxx if 'yyy') and replace
+ if (strstr(test, " to '") || strstr(test, " if '"))
+ for (unsigned int i=0; i<strlen(p); i++) if (p[i]=='\'') p[i] = '"';
+
+ ModifyImageFile(SilentText+12, p, &PDU);
+ }
+ }
+ }
+
+ else if (memcmp(SilentText, "modifystudy:", 12)==0)
+ {
+ char *r2=NULL, *r3=NULL;
+ if (p) // study
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ','); // script
+ if (q)
+ { *q++=0; // points after 2nd comma
+ }
+ }
+
+ ModifyData(SilentText+12, p, NULL, q, &PDU);
+ }
+
+ else if (memcmp(SilentText, "modifyseries:", 13)==0)
+ {
+ char *r2=NULL, *r3=NULL;
+ if (p) // study
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ','); // script
+ if (q)
+ { *q++=0; // points after 2nd comma
+ }
+ }
+
+ ModifyData(SilentText+13, NULL, p, q, &PDU);
+ }
+
+ else if (memcmp(SilentText, "anonymize:", 10)==0 && p)
+ {
+ *p++=0; // points after 1st comma
+
+ lua_setvar(&PDU, "command_line", SilentText+10);
+ lua_setvar(&PDU, "version", DGATE_VERSION);
+
+ FILE *f = fopen("anonymize_script.cq", "rt");
+ if (f)
+ { char anonscript2[] = "call anonymize_script.cq;";
+ fclose(f);
+ ModifyPATIDofImageFile(p, SilentText+10, TRUE, anonscript2, &PDU);
+ }
+ else if (f = fopen("anonymize_script.lua", "rt"))
+ { char anonscript2[] = "anonymize_script.lua";
+ fclose(f);
+ ModifyPATIDofImageFile(p, SilentText+10, TRUE, anonscript2, &PDU);
+ }
+ else
+ { char anonscript[] =
+ "set 0010,0010 to \"anonymous\";"
+ "set 0010,0030 to \"19010101\";"
+ "set 0008,0090 to \"\";"
+ "set 0020,1020 to \"\";"
+ "set 0051,1010 to \"\";"
+ "set 0010,1040 to \"\";"
+ "set 0009,1200 to \"\";";
+ ModifyPATIDofImageFile(p, SilentText+10, TRUE, anonscript, &PDU);
+ }
+ }
+
+ else if (memcmp(SilentText, "mergeseriesfile:", 16)==0)
+ MergeUIDofImageFile(SilentText+16, TRUE, "SeriesUID", "", NULL, &PDU);
+
+ else if (memcmp(SilentText, "mergestudyfile:", 15)==0)
+ MergeUIDofImageFile(SilentText+15, TRUE, "StudyUID", "", NULL, &PDU);
+
+ else if (memcmp(SilentText, "mergeseries:", 12)==0)
+ {
+ char temp[128];
+ int i, n=1, L;
+ char *uids[1000];
+ p = SilentText+12;
+ uids[0]=p;
+ L = strlen(p);
+ for (i=0; i<L; i++)
+ {
+ if (p[i]==',')
+ {
+ p[i]=0;
+ uids[n++] = p+i+1;
+ if(n==1000) break;
+ }
+ }
+ if (uids[0][0]) MergeUIDs(uids, n, "SeriesUID", temp);
+ }
+
+ else if (memcmp(SilentText, "mergestudy:", 11)==0)
+ {
+ char temp[128];
+ int i, n=1, L;
+ char *uids[16];
+ p = SilentText+11;
+ uids[0]=p;
+ L = strlen(p);
+ for (i=0; i<L; i++)
+ {
+ if (p[i]==',')
+ {
+ p[i]=0;
+ uids[n++] = p+i+1;
+ if(n==16) break;
+ }
+ }
+
+ if (uids[0][0]) MergeUIDs(uids, n, "StudyUID", temp);
+ }
+
+ else if (memcmp(SilentText, "initializetables:", 17)==0)
+ InitializeTables (atoi(SilentText+17));
+
+ else if (memcmp(SilentText, "regen:", 6)==0)
+ Regen();
+
+ else if (memcmp(SilentText, "regendevice:", 12)==0)
+ Regen(SilentText+12, FALSE);
+
+ else if (memcmp(SilentText, "regendir:", 9)==0)
+ {
+ if (p) *p++=0; // points after 1st comma
+ Regen(SilentText+9, FALSE, p);
+ }
+
+ else if (memcmp(SilentText, "makespace:", 10)==0)
+ {
+ if (LargestFreeMAG()<(unsigned int)atoi(SilentText+10))
+ PanicKillOff((unsigned int)atoi(SilentText+10));
+ }
+
+ else if (memcmp(SilentText, "selectlruforarchival:", 21)==0 && p)
+ {
+ if (p) *p++=0; // points after 1st comma
+ if (p) SelectLRUForArchival(p, atoi(SilentText+21), &PDU);
+ }
+
+ else if (memcmp(SilentText, "selectseriestomove:", 19)==0 && p)
+ {
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q) *q++=0; // points after 2nd comma
+ }
+ if (p && q) SelectSeriesForArchival(SilentText+19, atoi(p), atoi(q));
+ }
+
+ else if (memcmp(SilentText, "preparebunchforburning:", 23)==0 && p)
+ {
+ if (p) *p++=0; // points after 1st comma
+ if (p) PrepareBunchForBurning(p, SilentText+23);
+ }
+
+ else if (memcmp(SilentText, "movedatatodevice:", 17)==0 && p)
+ {
+ if (p) *p++=0; // points after 1st comma
+ if (p) MoveDataToDevice(p, SilentText+17);
+ }
+
+ else if (memcmp(SilentText, "moveseriestodevice:", 19)==0 && p)
+ {
+ if (p) *p++=0; // points after 1st comma
+ if (p) MoveSeriesToDevice(p, SilentText+19);
+ }
+
+ else if (memcmp(SilentText, "restoremagflags:", 16)==0)
+ RestoreMAGFlags();
+
+ else if (memcmp(SilentText, "comparebunchafterburning:", 25)==0)
+ CompareBunchAfterBurning(SilentText+25);
+
+ else if (memcmp(SilentText, "verifymirrordisk:", 17)==0)
+ VerifyMirrorDisk(SilentText+17);
+
+ else if (memcmp(SilentText, "testimages:", 11)==0)
+ TestImages(SilentText+11);
+
+ else if (memcmp(SilentText, "deletebunchafterburning:", 24)==0)
+ DeleteBunchAfterBurning(SilentText+24);
+
+ else if (memcmp(SilentText, "renamedevice:", 13)==0 && p)
+ {
+ if (p) *p++=0; // points after 1st comma
+ if (p) RenameDevice(SilentText+13, p);
+ }
+
+ else if (memcmp(SilentText, "testcompress:", 13)==0)
+#ifdef HAVE_J2K
+ TestCompress(SilentText+13, "unasn1n2n3n4j1j2j3j4j5j6jkjlk1k2k4k8", &PDU);
+#else
+ TestCompress(SilentText+13, "unasn1n2n3n4j1j2j3j4j5j6k1k2k4k8", &PDU);
+#endif
+
+ else if (memcmp(SilentText, "debuglevel:", 11)==0)
+ DebugVRs = DebugLevel = atoi(SilentText+11);
+
+ else if (memcmp(SilentText, "testmode:", 9)==0)
+ strcpy(TestMode, SilentText+9);
+
+ else if (memcmp(SilentText, "debuglog_on:", 12)==0)
+ {
+ if (SilentText[12]>='0' && SilentText[12]<='9')
+ {
+ SystemDebug.Off();
+ OperatorConsole.Off();
+ OperatorConsole.OnUDP(OCPipeName, SilentText+12);
+ SystemDebug.OnUDP(OCPipeName, SilentText+12);
+ OperatorConsole.AddTimeStamps(0);
+ SystemDebug.AddTimeStamps(0);
+ StopZipThread();
+ }
+ else if (SilentText[12] == PATHSEPCHAR)
+ {
+ SystemDebug.Off();
+ OperatorConsole.Off();
+ OperatorConsole.OnMsgPipe(SilentText+12);
+ SystemDebug.OnMsgPipe(SilentText+12);
+ OperatorConsole.AddTimeStamps(0);
+ SystemDebug.AddTimeStamps(0);
+ StopZipThread();
+ }
+ else
+ {
+ SystemDebug.Off();
+ OperatorConsole.Off();
+ OperatorConsole.On(SilentText+12);
+ SystemDebug.On(SilentText+12);
+ OperatorConsole.AddTimeStamps(1);
+ SystemDebug.AddTimeStamps(1);
+ StartZipThread();
+ }
+ }
+
+ else if (memcmp(SilentText, "log_on:", 7)==0)
+ {
+ if (SilentText[7]>='0' && SilentText[7]<='9')
+ {
+ SystemDebug.Off();
+ OperatorConsole.Off();
+ OperatorConsole.OnUDP(OCPipeName, SilentText+7);
+ OperatorConsole.AddTimeStamps(0);
+ StopZipThread();
+ }
+ else if (SilentText[7] == PATHSEPCHAR)
+ {
+ SystemDebug.Off();
+ OperatorConsole.Off();
+ OperatorConsole.OnMsgPipe(SilentText+7);
+ OperatorConsole.AddTimeStamps(0);
+ StopZipThread();
+ }
+ else
+ {
+ SystemDebug.Off();
+ OperatorConsole.Off();
+ OperatorConsole.On(SilentText+7);
+ OperatorConsole.AddTimeStamps(1);
+ StartZipThread();
+ }
+ }
+
+ else if (memcmp(SilentText, "read_amap:", 10)==0)
+ {
+ CloseACRNemaAddressArray();
+ if(!InitACRNemaAddressArray())
+ {
+ OperatorConsole.printf("***Error loading acr-nema map file:%s\n",ACRNEMAMAP);
+ }
+ }
+
+ else if (memcmp(SilentText, "read_ini:", 9)==0)
+ {
+ ConfigDgate();
+ ConfigMicroPACS();
+ }
+
+ else if (memcmp(SilentText, "get_ini:", 8)==0)
+ {
+ char ps[]="%s";
+ FILE *f, *g;
+ char line[512];
+ p = SilentText+8;
+ if (*p==0) p = ps;
+ f = fopen(ConfigFile, "rt");
+ NewTempFile(tempfile, ".txt");
+ g = fopen(tempfile, "wt");
+ while(fgets(line, sizeof(line), f) != NULL)
+ fprintf(g, p, line);
+ fclose(f);
+ fclose(g);
+ }
+
+ else if (memcmp(SilentText, "get_param:", 10)==0)
+ {
+ char ps[] = "%s";
+ char szRootSC[64], Parameter[512];
+ if (p) *p++=0; // points after 1st comma
+ if (p==NULL) p = ps;
+ if (MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile))
+ {
+ if (MyGetPrivateProfileString(szRootSC, SilentText+10, "", Parameter, 512, ConfigFile))
+ sprintf(Response, p, Parameter);
+ }
+
+ }
+
+ else if (memcmp(SilentText, "get_ini_param:", 14)==0)
+ {
+ char ps[] = "%s";
+ char szRootSC[64], Parameter[512];
+ if (p) *p++=0; // points after 1st comma
+ if (p==NULL) p = ps;
+ if (MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile))
+ {
+ if (MyGetPrivateProfileString(szRootSC, SilentText+14, "", Parameter, 512, ConfigFile))
+ sprintf(Response, p, Parameter);
+ }
+
+ }
+
+ else if (memcmp(SilentText, "get_ini_num:", 12)==0)
+ {
+ char ps[] = "%s";
+// char szRootSC[64], Parameter[512];
+ int r, i;
+ FILE *f;
+ char line[512];
+ if (p) *p++=0; // points after 1st comma
+ if (p==NULL) p = ps;
+ i = 0;
+ r = atoi(SilentText+12);
+ f = fopen(ConfigFile, "rt");
+ while(fgets(line, sizeof(line), f) != NULL && i <= r)
+ {
+ if (i == r)
+ sprintf(Response, p, line);
+ i++;
+ }
+ fclose(f);
+ }
+
+ else if (memcmp(SilentText, "put_param:", 10)==0)
+ {
+ FILE *f, *g;
+ char line[512];
+ BOOL written=FALSE;
+ time_t TimeOfDay3;
+ char TimeString1[128], buf[64];
+ char newConfigFile[512];
+ TimeOfDay3 = time(NULL);
+ UNUSED_ARGUMENT(buf);//Stop gcc4.2 warning bcb
+ strcpy(TimeString1, ctime_r(&TimeOfDay3, buf));
+ TimeString1[strlen(TimeString1)-1] = '\0';
+
+ if (p) *p++=0; // points after 1st comma
+ strcpy(newConfigFile, ConfigFile);
+ strcat(newConfigFile, ".new");
+
+ f = fopen(ConfigFile, "rt");
+ g = fopen(newConfigFile, "wt");
+
+ sprintf(line, "# Written by put_param on %s\n", TimeString1);
+ fputs(line, g);
+
+ while(fgets(line, sizeof(line), f) != NULL)
+ {
+ if (memicmp(line, "# Written by put_param on ", strlen("# Written by put_param on "))==0)
+ continue;
+ if (memicmp(line, SilentText+10, strlen(SilentText+10))==0 && isspace(line[strlen(SilentText+10)]))
+ {
+ sprintf(line, "%-24s = %s\n", SilentText+10, p);
+ written=TRUE;
+ }
+ fputs(line, g);
+ }
+ if (!written)
+ {
+ fputs("\n", g);
+ sprintf(line, "# Parameter added by put_param on %s\n", TimeString1);
+ fputs(line, g);
+ sprintf(line, "%-24s = %s\n", SilentText+10, p);
+ fputs(line, g);
+ }
+
+ fclose(f);
+ fclose(g);
+ unlink(ConfigFile);
+ rename(newConfigFile, ConfigFile);
+ FlushPrivateProfileStringCache();
+ }
+
+ else if (memcmp(SilentText, "delete_param:", 13)==0)
+ {
+ FILE *f, *g;
+ char line[512];
+ time_t TimeOfDay3;
+ char TimeString1[128], buf[64];
+ char newConfigFile[512];
+ TimeOfDay3 = time(NULL);
+ UNUSED_ARGUMENT(buf);//Stop gcc4.2 warning bcb
+ strcpy(TimeString1, ctime_r(&TimeOfDay3, buf));
+ TimeString1[strlen(TimeString1)-1] = '\0';
+ strcpy(newConfigFile, ConfigFile);
+ strcat(newConfigFile, ".new");
+
+ f = fopen(ConfigFile, "rt");
+ g = fopen(newConfigFile, "wt");
+
+ sprintf(line, "# Written by put_param on %s\n", TimeString1);
+ fputs(line, g);
+
+ while(fgets(line, sizeof(line), f) != NULL)
+ {
+ if (memicmp(line, "# Written by put_param on ", strlen("# Written by put_param on "))==0)
+ continue;
+ if (memicmp(line, SilentText+13, strlen(SilentText+13))==0 && isspace(line[strlen(SilentText+13)]))
+ continue;
+ fputs(line, g);
+ }
+
+ fclose(f);
+ fclose(g);
+ unlink(ConfigFile);
+ rename(newConfigFile, ConfigFile);
+ FlushPrivateProfileStringCache();
+ }
+
+ else if (memcmp(SilentText, "get_freestore:", 14)==0)
+ {
+ char pd[] = "%d";
+ int r = -1;
+ if (p) *p++=0; // points after 1st comma
+ if (p==NULL) p = pd;
+ if (memicmp("MAG", SilentText+14, 3)==0)
+ r = CheckFreeStoreOnMAGDevice(atoi(SilentText+17));
+ if (memicmp("CACHE", SilentText+14, 5)==0)
+ r = CheckFreeStoreOnCACHEDevice(atoi(SilentText+19));
+ if (memicmp("MIRROR", SilentText+14, 6)==0)
+ r = CheckFreeStoreOnMIRRORDevice(atoi(SilentText+20));
+ sprintf(Response, p, r);
+ }
+
+ else if (memcmp(SilentText, "get_amap:", 9)==0)
+ {
+ char pq[] = "%-17s %-30s %-10s %-16s";
+ if (p) *p++=0; // points after 1st comma
+ unsigned int r = atoi(SilentText+9);
+ if (p==NULL) p = pq;
+ if (r < ACRNemaAddressArray.GetSize() )
+ {
+ ACRNemaAddress *AAPtr = ACRNemaAddressArray.Get(r);
+ sprintf(Response, p, AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress,
+ AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress,
+ AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress);
+ }
+ }
+
+ else if (memcmp(SilentText, "get_amaps:", 10)==0)
+ {
+ char pq[] = "%-17s %-30s %-10s %-16s\n";
+ FILE *g;
+ p = SilentText+10;
+ if (*p==0) p = pq;
+ NewTempFile(tempfile, ".txt");
+ g = fopen(tempfile, "wt");
+ for (unsigned int r=0; r< ACRNemaAddressArray.GetSize(); r++ )
+ {
+ ACRNemaAddress *AAPtr = ACRNemaAddressArray.Get(r);
+ if (strchr(AAPtr->Name, '*')==NULL)
+ fprintf(g, p, AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress,
+ AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress,
+ AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress);
+ }
+ fclose(g);
+ }
+
+ else if (memcmp(SilentText, "write_amap:", 11)==0)
+ {
+ char pq[]="%-17s %-30s %-10s %-16s\n";
+ unsigned int r = 0;
+ if (p) *p++=0; // points after 1st comma
+ p = pq;
+ time_t TimeOfDay3;
+ char TimeString1[128], buf[64];
+ TimeOfDay3 = time(NULL);
+ UNUSED_ARGUMENT(buf);//Stop gcc4.2 warning bcb
+ strcpy(TimeString1, ctime_r(&TimeOfDay3, buf));
+ TimeString1[strlen(TimeString1)-1] = '\0';
+
+ FILE *f = fopen("acrnema.map", "wt");
+ fprintf(f, "/* **********************************************************\n");
+ fprintf(f, " * *\n");
+ fprintf(f, " * DICOM AE (Application entity) -> IP address / Port map *\n");
+ fprintf(f, " * (This is file ACRNEMA.MAP) *\n");
+ fprintf(f, " * Written by write_amap on %-32s*\n", TimeString);
+ fprintf(f, " * *\n");
+ fprintf(f, " * All DICOM systems that want to retrieve images from the *\n");
+ fprintf(f, " * Conquest DICOM server must be listed here with correct *\n");
+ fprintf(f, " * AE name, (IP adress or hostname) and port number. *\n");
+ fprintf(f, " * The first entry is the Conquest system as example. *\n");
+ fprintf(f, " * *\n");
+ fprintf(f, " * *\n");
+ fprintf(f, " * The syntax for each entry is : *\n");
+ fprintf(f, " * AE <IP adress|Host name> port number compression *\n");
+ fprintf(f, " * *\n");
+ fprintf(f, " * For compression see manual. Values are un=uncompressed; *\n");
+ fprintf(f, " * ul=littleendianexplicit,ub=bigendianexplicit,ue=both *\n");
+ fprintf(f, " * j1,j2=lossless jpeg;j3..j6=lossy jpeg;n1..n4=nki private *\n");
+#ifdef HAVE_J2K
+ fprintf(f, " * jk = jpeg2000 lossless, jl = jpeg2000 lossy *\n");
+#endif
+ fprintf(f, " * *\n");
+ fprintf(f, " ********************************************************** */\n");
+ fprintf(f, "\n");
+ while (r < ACRNemaAddressArray.GetSize() )
+ {
+ ACRNemaAddress *AAPtr = ACRNemaAddressArray.Get(r);
+ fprintf(f, p, AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress);
+ r++;
+ }
+ fclose(f);
+ }
+
+ else if (memcmp(SilentText, "put_amap:", 9)==0)
+ {
+ int i, n=1, L;
+ char *items[5];
+ ACRNemaAddress *AAPtr;
+
+ memset(items, 0, sizeof(items));
+
+ p = SilentText+9;
+ items[0]=p;
+ L = strlen(p);
+ for (i=0; i<L; i++)
+ {
+ if (p[i]==',')
+ {
+ p[i]=0;
+ items[n++] = p+i+1;
+ if(n==5) break;
+ }
+ }
+
+ unsigned int r = atoi(items[0]);
+ if (r < ACRNemaAddressArray.GetSize() )
+ AAPtr = ACRNemaAddressArray.Get(r);
+ else
+ {
+ AAPtr = new ACRNemaAddress;
+ strcpy(AAPtr->Name, "");
+ strcpy(AAPtr->IP, "");
+ strcpy(AAPtr->Port, "");
+ strcpy(AAPtr->Compress, "un");
+ ACRNemaAddressArray.Add(AAPtr);
+ r = ACRNemaAddressArray.GetSize()-1;
+ }
+
+ if (items[1]) strcpy(AAPtr->Name, items[1]);
+ if (items[2]) strcpy(AAPtr->IP, items[2]);
+ if (items[3]) strcpy(AAPtr->Port, items[3]);
+ if (items[4]) strcpy(AAPtr->Compress, items[4]);
+ }
+
+ else if (memcmp(SilentText, "delete_amap:", 12)==0)
+ {
+ ACRNemaAddress *AAPtr;
+
+ unsigned int r = atoi(SilentText+12);
+ if (r < ACRNemaAddressArray.GetSize() )
+ {
+ AAPtr = ACRNemaAddressArray.Get(r);
+ delete AAPtr;
+ ACRNemaAddressArray.RemoveAt(r);
+ }
+ }
+
+ else if (memcmp(SilentText, "get_sqldef:", 11)==0)
+ {
+ char pq[] = "0x%4.4x, 0x%4.4x %20s %4d %10s %12s";
+ int r=0;
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q) *q++=0; // points after 2nd comma
+ }
+
+ if (p) r = atoi(p);
+ if (q==NULL) q = pq;
+ DBENTRY *DBE = NULL;
+ if (stricmp(SilentText+11, "patient" )==0) DBE = PatientDB;
+ if (stricmp(SilentText+11, "study" )==0) DBE = StudyDB;
+ if (stricmp(SilentText+11, "series" )==0) DBE = SeriesDB;
+ if (stricmp(SilentText+11, "image" )==0) DBE = ImageDB;
+ if (stricmp(SilentText+11, "worklist")==0) DBE = WorkListDB;
+ if (DBE)
+ if (DBE[r].Group)
+ sprintf(Response, q, DBE[r].Group, DBE[r].Element, DBE[r].SQLColumn,
+ DBE[r].SQLLength, SQLTypeSymName(DBE[r].SQLType), DICOMTypeSymName(DBE[r].DICOMType));
+ }
+
+ else if (memcmp(SilentText, "get_sop:", 8)==0)
+ {
+ char ps2[]="%s %s";
+ if (p) *p++=0; // points after 1st comma
+ unsigned int r = atoi(SilentText+8);
+ if (p==NULL) p = ps2;
+ if (r<PDU.SOPUIDListCount)
+ sprintf(Response, p, PDU.SOPUIDList[r], PDU.SOPUIDListNames[r]);
+ }
+
+ else if (memcmp(SilentText, "put_sop:", 8)==0 ||
+ memcmp(SilentText, "put_transfer:", 13)==0 ||
+ memcmp(SilentText, "put_localae:", 12)==0 ||
+ memcmp(SilentText, "put_remoteae:", 13)==0 ||
+ memcmp(SilentText, "put_application:", 16)==0
+ )
+ {
+ unsigned int r = atoi(strchr(SilentText, ':')+1);
+ char **List, **ListNames;
+ unsigned int *Count;
+#ifdef __GNUC__ //Warnings
+ List = NULL;
+ ListNames = NULL;
+ Count = NULL;
+#endif
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q) *q++=0; // points after 2nd comma
+ }
+
+ if (memcmp(SilentText, "put_sop:", 8)==0)
+ {
+ Count = &PDU.SOPUIDListCount;
+ List = PDU.SOPUIDList;
+ ListNames = PDU.SOPUIDListNames;
+ }
+ else if (memcmp(SilentText, "put_transfer:", 13)==0)
+ {
+ Count = &PDU.TransferUIDListCount;
+ List = PDU.TransferUIDList;
+ ListNames = PDU.TransferUIDListNames;
+ }
+ else if (memcmp(SilentText, "put_application:", 16)==0)
+ {
+ Count = &PDU.ApplicationUIDListCount;
+ List = PDU.ApplicationUIDList;
+ ListNames = PDU.ApplicationUIDListNames;
+ }
+ else if (memcmp(SilentText, "put_localae:", 12)==0)
+ {
+ Count = &PDU.LocalAEListCount;
+ List = PDU.LocalAEList;
+ ListNames = PDU.LocalAEListNames;
+ }
+ else if (memcmp(SilentText, "put_remoteae:", 12)==0)
+ {
+ Count = &PDU.RemoteAEListCount;
+ List = PDU.RemoteAEList;
+ ListNames = PDU.RemoteAEListNames;
+ }
+
+ if (r<*Count)
+ {
+ delete List[r];
+ delete ListNames[r];
+ }
+ else
+ r = *Count++;
+
+ List[r] = new char[strlen(p)+1];
+ strcpy(List[r], p);
+ ListNames[r] = new char[strlen(q)+1];
+ strcpy(ListNames[r], q);
+
+ time_t TimeOfDay3;
+ char TimeString1[128], buf[64];
+ UNUSED_ARGUMENT(buf);//Stop gcc4.2 warning bcb
+ TimeOfDay3 = time(NULL);
+ strcpy(TimeString1, ctime_r(&TimeOfDay3, buf));
+ TimeString1[strlen(TimeString1)-1] = '\0';
+
+ FILE *f = fopen(SOPClassFile, "wt");
+ fprintf(f, "#\n");
+ fprintf(f, "# DICOM Application / sop / transfer UID list.\n");
+ fprintf(f, "#\n");
+ fprintf(f, "# This list is used by the server (CheckedPDU_Service class).\n");
+ fprintf(f, "# All incoming associations are verified against this file.\n");
+ fprintf(f, "# File written by %s on: %s\n", SilentText, TimeString1);
+ fprintf(f, "#\n");
+
+ for (r=0; r<PDU.RemoteAEListCount; r++)
+ fprintf(f, "%-42s %-44s RemoteAe\n", PDU.RemoteAEListNames[r], PDU.RemoteAEList[r]);
+ for (r=0; r<PDU.LocalAEListCount; r++)
+ fprintf(f, "%-42s %-44s LocalAe\n", PDU.LocalAEListNames[r], PDU.LocalAEList[r]);
+ for (r=0; r<PDU.ApplicationUIDListCount; r++)
+ fprintf(f, "%-42s %-44s application\n", PDU.ApplicationUIDListNames[r], PDU.ApplicationUIDList[r]);
+ for (r=0; r<PDU.SOPUIDListCount; r++)
+ fprintf(f, "%-42s %-44s sop\n", PDU.SOPUIDListNames[r], PDU.SOPUIDList[r]);
+ for (r=0; r<PDU.TransferUIDListCount; r++)
+ fprintf(f, "%-42s %-44s transfer\n", PDU.TransferUIDListNames[r], PDU.TransferUIDList[r]);
+ fclose(f);
+ }
+
+ else if (memcmp(SilentText, "delete_sop:", 11)==0 ||
+ memcmp(SilentText, "delete_transfer:", 16)==0 ||
+ memcmp(SilentText, "delete_localae:", 15)==0 ||
+ memcmp(SilentText, "delete_remoteae:", 16)==0 ||
+ memcmp(SilentText, "delete_application:", 19)==0
+ )
+ {
+ unsigned int r = atoi(strchr(SilentText, ':')+1), i;
+ char **List, **ListNames;
+ unsigned int *Count;
+#ifdef __GNUC__ //Warnings
+ List = NULL;
+ ListNames = NULL;
+ Count = NULL;
+#endif
+
+ if (memcmp(SilentText, "delete_sop:", 11)==0)
+ {
+ Count = &PDU.SOPUIDListCount;
+ List = PDU.SOPUIDList;
+ ListNames = PDU.SOPUIDListNames;
+ }
+ else if (memcmp(SilentText, "delete_transfer:", 16)==0)
+ {
+ Count = &PDU.TransferUIDListCount;
+ List = PDU.TransferUIDList;
+ ListNames = PDU.TransferUIDListNames;
+ }
+ else if (memcmp(SilentText, "delete_application:", 19)==0)
+ {
+ Count = &PDU.ApplicationUIDListCount;
+ List = PDU.ApplicationUIDList;
+ ListNames = PDU.ApplicationUIDListNames;
+ }
+ else if (memcmp(SilentText, "delete_localae:", 15)==0)
+ {
+ Count = &PDU.LocalAEListCount;
+ List = PDU.LocalAEList;
+ ListNames = PDU.LocalAEListNames;
+ }
+ else if (memcmp(SilentText, "delete_remoteae:", 16)==0)
+ {
+ Count = &PDU.RemoteAEListCount;
+ List = PDU.RemoteAEList;
+ ListNames = PDU.RemoteAEListNames;
+ }
+
+ if (r<*Count)
+ {
+ delete List[r];
+ delete ListNames[r];
+ for (i=r+1; i<*Count; i++)
+ {
+ List[i+1] = List[i];
+ ListNames[i+1] = ListNames[i];
+ }
+ (*Count)--;
+ }
+
+ time_t TimeOfDay3;
+ char TimeString1[128], buf[64];
+ TimeOfDay3 = time(NULL);
+ UNUSED_ARGUMENT(buf);//Stop gcc4.2 warning bcb
+ strcpy(TimeString1, ctime_r(&TimeOfDay3, buf));
+ TimeString1[strlen(TimeString1)-1] = '\0';
+
+ FILE *f = fopen(SOPClassFile, "wt");
+ fprintf(f, "#\n");
+ fprintf(f, "# DICOM Application / sop / transfer UID list.\n");
+ fprintf(f, "#\n");
+ fprintf(f, "# This list is used by the server (CheckedPDU_Service class).\n");
+ fprintf(f, "# All incoming associations are verified against this file.\n");
+ fprintf(f, "# File written by %s on: %s\n", SilentText, TimeString1);
+ fprintf(f, "#\n");
+
+ for (r=0; r<PDU.RemoteAEListCount; r++)
+ fprintf(f, "%-42s %-44s RemoteAe\n", PDU.RemoteAEListNames[r], PDU.RemoteAEList[r]);
+ for (r=0; r<PDU.LocalAEListCount; r++)
+ fprintf(f, "%-42s %-44s LocalAe\n", PDU.LocalAEListNames[r], PDU.LocalAEList[r]);
+ for (r=0; r<PDU.ApplicationUIDListCount; r++)
+ fprintf(f, "%-42s %-44s application\n", PDU.ApplicationUIDListNames[r], PDU.ApplicationUIDList[r]);
+ for (r=0; r<PDU.SOPUIDListCount; r++)
+ fprintf(f, "%-42s %-44s sop\n", PDU.SOPUIDListNames[r], PDU.SOPUIDList[r]);
+ for (r=0; r<PDU.TransferUIDListCount; r++)
+ fprintf(f, "%-42s %-44s transfer\n", PDU.TransferUIDListNames[r], PDU.TransferUIDList[r]);
+ fclose(f);
+ }
+
+ else if (memcmp(SilentText, "get_transfer:", 13)==0)
+ {
+ char ps2[]="%s %s";
+ if (p) *p++=0; // points after 1st comma
+ unsigned int r = atoi(SilentText+13);
+ if (p==NULL) p = ps2;
+ if (r<PDU.TransferUIDListCount)
+ sprintf(Response, p, PDU.TransferUIDList[r], PDU.TransferUIDListNames[r]);
+ }
+
+ else if (memcmp(SilentText, "get_application:", 16)==0)
+ {
+ char ps2[]="%s %s";
+ if (p) *p++=0; // points after 1st comma
+ unsigned int r = atoi(SilentText+16);
+ if (p==NULL) p = ps2;
+ if (r<PDU.ApplicationUIDListCount)
+ sprintf(Response, p, PDU.ApplicationUIDList[r], PDU.ApplicationUIDListNames[r]);
+ }
+
+ else if (memcmp(SilentText, "get_localae:", 12)==0)
+ {
+ char ps2[]="%s %s";
+ if (p) *p++=0; // points after 1st comma
+ unsigned int r = atoi(SilentText+12);
+ if (p==NULL) p = ps2;
+ if (r<PDU.LocalAEListCount)
+ sprintf(Response, p, PDU.LocalAEList[r], PDU.LocalAEListNames[r]);
+ }
+
+ else if (memcmp(SilentText, "get_remoteae:", 13)==0)
+ {
+ char ps2[]="%s %s";
+ if (p) *p++=0; // points after 1st comma
+ unsigned int r = atoi(SilentText+13);
+ if (p==NULL) p = ps2;
+ if (r<PDU.RemoteAEListCount)
+ sprintf(Response, p, PDU.RemoteAEList[r], PDU.RemoteAEListNames[r]);
+ }
+
+ else if (memcmp(SilentText, "get_dic:", 8)==0)
+ {
+ char ps3[]="%04x %04x %c%c %s";
+ if (p) *p++=0; // points after 1st comma
+ unsigned int r = atoi(SilentText+8);
+ if (p==NULL) p = ps3;
+ if (r<VRType.TypeCodes->GetSize())
+ {
+ RTCElement *e;
+ e = &(VRType.TypeCodes->Get(r));
+ sprintf(Response, p, VRType.TypeCodes->Get(r).Group, VRType.TypeCodes->Get(r).Element, VRType.TypeCodes->Get(r).TypeCode>>8, VRType.TypeCodes->Get(r).TypeCode&255, VRType.TypeCodes->Get(r).Description);
+ }
+ }
+
+
+ else if (memcmp(SilentText, "dump_header:", 12)==0)
+ {
+ FILE *f;
+ if (p) *p++=0; // points after 1st comma
+ if (p==NULL || *p==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ }
+ else if (strcmp(p, "cgi")==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ fprintf(f, "Content-type: text/html\n\n<pre>");
+ }
+ else if (strcmp(p, "pre")==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ fprintf(f, "<pre>");
+ }
+ else
+ f = fopen(p, "wt");
+ DICOMDataObject *pDDO = LoadForGUI(SilentText+12);
+ if (pDDO) NonDestructiveDumpDICOMObject(pDDO, f);
+ if (f) fclose(f);
+ if (pDDO) delete pDDO;
+ DumpHeaderFromGui++;
+ }
+
+ else if (memcmp(SilentText, "display_status:", 15)==0)
+ {
+ FILE *f;
+ p = SilentText+15;
+ if (p==NULL || *p==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ }
+ else if (strcmp(p, "cgi")==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ fprintf(f, "Content-type: text/html\n\n<pre>");
+ }
+ else if (strcmp(p, "pre")==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ fprintf(f, "<pre>");
+ }
+ else
+ f = fopen(p, "wt");
+ StatusDisplay(f);
+ if (f) fclose(f);
+ }
+
+ else if (memcmp(SilentText, "status_string:", 14)==0)
+ {
+ FILE *f;
+ p = SilentText+14;
+ if (p==NULL || *p==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ }
+ else if (strcmp(p, "cgi")==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ fprintf(f, "Content-type: text/plain\n\n<pre>");
+ }
+ else if (strcmp(p, "pre")==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ fprintf(f, "<pre>");
+ }
+ else
+ f = fopen(p, "wt");
+ fprintf(f, "%s", StatusString);
+ if (strcmp(p, "cgi")==0) // 20120829
+ {
+ fputc(' ', f);
+ strcpy(SilentText, "text/plain");
+ }
+ if (f) fclose(f);
+ }
+
+ else if (memcmp(SilentText, "echo:", 5)==0)
+ {
+ FILE *f;
+ if (p) *p++=0; // points after 1st comma (file)
+ if (p==NULL || *p==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ }
+ else if (strcmp(p, "cgi")==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ fprintf(f, "Content-type: text/html\n\n<pre>");
+ }
+ else if (strcmp(p, "pre")==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ f = fopen(tempfile, "wt");
+ fprintf(f, "<pre>");
+ }
+ else
+ f = fopen(p, "wt");
+ if (DcmEcho(SilentText+5))
+ fprintf(f, "%s is UP", SilentText+5);
+ else
+ fprintf(f, "%s is DOWN", SilentText+5);
+ if (f) fclose(f);
+ }
+
+ else if (memcmp(SilentText, "forward:", 8)==0)
+ {
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ TestForward(SilentText+8, p, q, &PDU);
+ ForwardFromGui++;
+ }
+ }
+ }
+
+ else if (memcmp(SilentText, "convert_to_gif:", 15)==0)
+ {
+ int level, window;
+ unsigned int frame;
+ DICOMDataObject *pDDO;
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ r1 = strchr(q, ',');
+ if (r1) *r1++=0; // points after 3rd comma
+ }
+ }
+
+ pDDO = LoadForGUI(SilentText+15);
+ if (pDDO)
+ {
+ char p256[]="256";
+ //char p32[]="32";
+ char p00[]="0/0";
+ char p0[]="0";
+ if (p==NULL) p = p256;
+ //if (atoi(p)==0) p = p32;
+ if (r1==NULL) r1 = p00;
+ level = atoi(r1);
+ r1 = strchr(r1, '/');
+ if (r1==NULL) r1 = p0; else r1++;
+ window = atoi(r1);
+ r1 = strchr(r1, '/');
+ if (r1==NULL) r1 = p0; else r1++;
+ frame = (unsigned int)atoi(r1);
+
+ if (q==NULL || *q==0)
+ {
+ NewTempFile(tempfile, ".gif");
+ ToGif(pDDO, tempfile, atoi(p), 0, level, window, frame);
+ }
+ else if (strcmp(q, "cgi")==0)
+ {
+ NewTempFile(tempfile, ".gif");
+ FILE *f = fopen(tempfile, "wb");
+ fprintf(f, "Content-type: image/gif\n\n");
+ fclose(f);
+ ToGif(pDDO, tempfile, atoi(p), 1, level, window, frame);
+ }
+ else
+ ToGif(pDDO, q, atoi(p), 0, level, window, frame);
+ ImagesToGifFromGui++;
+ delete pDDO;
+ }
+ }
+
+ else if (memcmp(SilentText, "convert_to_bmp:", 15)==0)
+ {
+ int level, window;
+ unsigned int frame;
+ DICOMDataObject *pDDO;
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ r1 = strchr(q, ',');
+ if (r1) *r1++=0; // points after 3rd comma
+ }
+ }
+
+ pDDO = LoadForGUI(SilentText+15);
+ if (pDDO)
+ {
+ char p256[]="256";
+ //char p32[]="32";
+ char r00[]="0/0";
+ char r0[]="0";
+ if (p==NULL) p = p256;
+ //if (atoi(p)==0) p = p32;
+ if (r1==NULL) r1 = r00;
+ level = atoi(r1);
+ r1 = strchr(r1, '/');
+ if (r1==NULL) r1 = r0; else r1++;
+ window = atoi(r1);
+ r1 = strchr(r1, '/');
+ if (r1==NULL) r1 = r0; else r1++;
+ frame = (unsigned int)atoi(r1);
+
+ if (q==NULL || *q==0)
+ {
+ NewTempFile(tempfile, ".bmp");
+ ToBMP(pDDO, tempfile, atoi(p), 0, level, window, frame);
+ }
+ else if (strcmp(q, "cgi")==0)
+ {
+ NewTempFile(tempfile, ".bmp");
+ FILE *f = fopen(tempfile, "wb");
+ fprintf(f, "Content-type: image/bmp\n\n");
+ fclose(f);
+ ToBMP(pDDO, tempfile, atoi(p), 1, level, window, frame);
+ }
+ else
+ ToBMP(pDDO, q, atoi(p), 0, level, window, frame);
+ ImagesToGifFromGui++;
+ delete pDDO;
+ }
+ }
+
+ else if (memcmp(SilentText, "convert_to_jpg:", 15)==0)
+ {
+ int level, window;
+ unsigned int frame;
+ DICOMDataObject *pDDO;
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ r1 = strchr(q, ',');
+ if (r1) *r1++=0; // points after 3rd comma
+ }
+ }
+
+ pDDO = LoadForGUI(SilentText+15);
+ if (pDDO)
+ {
+ char p256[]="256";
+ //char p32[]="32";
+ char p00[]="0/0";
+ char p0[]="0";
+ if (p==NULL) p = p256;
+ //if (atoi(p)==0) p = p32;
+ if (r1==NULL) r1 = p00;
+ level = atoi(r1);
+ r1 = strchr(r1, '/');
+ if (r1==NULL) r1 = p0; else r1++;
+ window = atoi(r1);
+ r1 = strchr(r1, '/');
+ if (r1==NULL) r1 = p0; else r1++;
+ frame = (unsigned int)atoi(r1);
+
+ if (q==NULL || *q==0)
+ {
+ NewTempFile(tempfile, ".jpg");
+ ToJPG(pDDO, tempfile, atoi(p), 0, level, window, frame, 95);
+ }
+ else if (strcmp(q, "cgi")==0)
+ {
+ NewTempFile(tempfile, ".jpg");
+ FILE *f = fopen(tempfile, "wb");
+ fprintf(f, "Content-type: image/jpeg\n\n");
+ fclose(f);
+ ToJPG(pDDO, tempfile, atoi(p), 1, level, window, frame, 95);
+ }
+ else
+ ToJPG(pDDO, q, atoi(p), 0, level, window, frame, 95);
+ ImagesToGifFromGui++;
+ delete pDDO;
+ }
+ }
+
+ else if (memcmp(SilentText, "convert_to_dicom:", 17)==0)
+ {
+ DICOMDataObject *pDDO;
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ r1 = strchr(q, ',');
+ if (r1) *r1++=0; // points after 3nd comma
+ }
+ }
+ pDDO = LoadForGUI(SilentText+17);
+
+ if (pDDO)
+ {
+ char un[]="un";
+ char p0[]="0";
+ if (p==NULL) p = p0;
+ if (q==NULL) q = un;
+ NewTempFile(tempfile, ".dcm");
+ if (r1) ExtractFrame(pDDO, (unsigned int)atoi(r1));
+ MaybeDownsize(pDDO, NULL, atoi(p));
+ recompress(&pDDO, q, "", q[0]=='n' || q[0]=='N', &PDU);
+ SaveDICOMDataObject(tempfile, pDDO);
+ ImagesToDicomFromGui++;
+ delete pDDO;
+ }
+ }
+
+ else if (memcmp(SilentText, "uncompress:", 11)==0)
+ {
+ DICOMDataObject *pDDO;
+ if (p)
+ *p++=0; // points after 1st comma
+ pDDO = LoadForGUI(SilentText+11);
+
+ if (pDDO)
+ {
+ char un[]="un";
+ recompress(&pDDO, un, "", FALSE, &PDU);
+ SaveDICOMDataObject(p, pDDO);
+ ImagesToDicomFromGui++;
+ delete pDDO;
+ }
+ }
+
+ else if (memcmp(SilentText, "extract_frames:", 15)==0)
+ {
+ DICOMDataObject *pDDO;
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ r1 = strchr(q, ',');
+ if (r1) *r1++=0; // points after 3nd comma
+ }
+ }
+ pDDO = LoadForGUI(SilentText+17);
+ if (pDDO)
+ {
+// char blank[]="";// Shadow, not needed
+ if (q==NULL) q = blank;
+ if (r1==NULL) r1 = q;
+ ExtractFrames(pDDO, (unsigned int)atoi(q), (unsigned int)atoi(r1), 1);
+ SaveDICOMDataObject(p, pDDO);
+ delete pDDO;
+ }
+ }
+
+ else if (memcmp(SilentText, "wadorequest:", 12)==0)
+ {
+ DICOMDataObject *pDDO;
+ char *r2=NULL, *r3=NULL, *r4=NULL, *r5=NULL, *r6=NULL;
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ r1 = strchr(q, ',');
+ if (r1)
+ { *r1++=0; // points after 3rd comma
+ r2 = strchr(r1, ',');
+ if (r2)
+ { *r2++=0; // points after 4th comma
+ r3 = strchr(r2, ',');
+ if (r3)
+ { *r3++=0; // points after 5th comma
+ r4 = strchr(r3, ',');
+ if (r4)
+ { *r4++=0;
+ r5 = strchr(r4, ',');
+ if (r5)
+ { *r5++=0;
+ r6 = strchr(r5, ',');
+ if (r6)
+ { *r6++=0;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // sprintf(command, "wadorequest:%s,%s,%s,%s,%s,%s,%s,%s,%s",
+ // obj, lwfq, size, region, contentType, transferSyntax, anonymize, annotation, bridge);
+
+ int level=0, window=0, frame=0, quality=0;
+ if (p) sscanf(p, "%d/%d/%d/%d", &level, &window, &frame, &quality);
+
+ int rows=0, cols=0;
+ if (q) sscanf(q, "%d/%d", &rows, &cols);
+ int size = max(rows, cols);
+ if (size==0) size=1600;
+
+ if (r6==NULL || *r6==0)
+ pDDO = LoadForGUI(SilentText+12);
+ else
+ pDDO = LoadForBridge(SilentText+12, r6);
+ if (pDDO)
+ {
+ int nf = GetNumberOfFrames(pDDO);
+ if (r1 && *r1)
+ {
+ int startx, endx, starty, endy;
+ float sx, ex, sy, ey;
+ sscanf(r1, "%f/%f/%f/%f", &sx, &ex, &sy, &ey);
+ startx = (int)(sx * pDDO->GetUINT16(0x0028, 0x0010)+0.5);
+ endx = (int)(ex * pDDO->GetUINT16(0x0028, 0x0010)+0.5);
+ starty = (int)(sy * pDDO->GetUINT16(0x0028, 0x0011)+0.5);
+ endy = (int)(ey * pDDO->GetUINT16(0x0028, 0x0011)+0.5);
+ DcmConvertPixelData(pDDO, FALSE, TRUE, startx, endx, starty, endy, 0.0, 0.0, 0.0);
+ }
+ if (strcmp(r4, "yes")==0)
+ CallImportConverterN(pDDO, -1, NULL, NULL, NULL, NULL, &PDU, NULL, "call anonymize_script.cq");
+ // AnnotateDICOMObject(pDDO, r5);
+ if (r2 && strcmp(r2, "image/gif")==0 && nf<2)
+ {
+ NewTempFile(tempfile, ".gif");
+ FILE *f = fopen(tempfile, "wb");
+ fprintf(f, "Content-type: image/gif\nAccess-Control-Allow-Origin: *\n\n");
+ fclose(f);
+ ToGif(pDDO, tempfile, size, 1, level, window, frame);
+ }
+ if (r2 && strcmp(r2, "image/gif")==0 && nf>=2)
+ {
+ NewTempFile(tempfile, ".gif");
+ FILE *f = fopen(tempfile, "wb");
+ fprintf(f, "Content-type: image/gif\nAccess-Control-Allow-Origin: *\n\n");
+ fclose(f);
+ ToGif(pDDO, tempfile, size, 1, level, window, 10000+5);
+ }
+ if (r2 && strcmp(r2, "image/jpeg")==0 || strcmp(r2, "image/png")==0 || strcmp(r2, "image/jp2")==0)
+ {
+ NewTempFile(tempfile, ".jpg");
+ FILE *f = fopen(tempfile, "wb");
+ // ODD HEADER LENGHT AVOIDED HERE
+ fprintf(f, "Content-type: image/jpeg\nAccess-Control-Allow-Origin:*\n\n");
+ fclose(f);
+ ToJPG(pDDO, tempfile, size, 1, level, window, frame, 95);
+ }
+ if (r2 && strcmp(r2, "application/dicom")==0)
+ {
+ NewTempFile(tempfile, ".dcm");
+ if (strcmp(r3, "1.2.840.10008.1.2.4.50")==0) recompress(&pDDO, "j3", "", FALSE, &PDU);
+ else if (strcmp(r3, "1.2.840.10008.1.2.4.51")==0) recompress(&pDDO, "j4", "", FALSE, &PDU);
+ else if (strcmp(r3, "1.2.840.10008.1.2.4.53")==0) recompress(&pDDO, "j5", "", FALSE, &PDU);
+ else if (strcmp(r3, "1.2.840.10008.1.2.4.55")==0) recompress(&pDDO, "j1", "", FALSE, &PDU);
+ else if (strcmp(r3, "1.2.840.10008.1.2.4.57")==0) recompress(&pDDO, "j2", "", FALSE, &PDU);
+ else if (strcmp(r3, "1.2.840.10008.1.2.4.70")==0) recompress(&pDDO, "j1", "", FALSE, &PDU);
+ else if (strcmp(r3, "1.2.840.10008.1.2.4.90")==0) recompress(&pDDO, "jk", "", FALSE, &PDU);
+ else if (strcmp(r3, "1.2.840.10008.1.2.4.91")==0) recompress(&pDDO, "jl", "", FALSE, &PDU);
+ else recompress(&pDDO, "un", "", FALSE, &PDU);
+ SaveDICOMDataObject(tempfile, pDDO);
+ strcpy(SilentText, "convert_to_dicom:"); // force application/dicom header
+ }
+ if (r2 && strcmp(r2, "video/mpeg")==0 && nf>=2)
+ {
+ NewTempFile(tempfile, ".mpg");
+ FILE *f = fopen(tempfile, "wb");
+ // ODD HEADER LENGHT AVOIDED HERE
+ fprintf(f, "Content-type: video/mpeg\nAccess-Control-Allow-Origin:*\n\n");
+ fclose(f);
+ // ToMPEG(tempfile, pDDO);
+ }
+ if (r2 && strcmp(r2, "text/plain")==0)
+ {
+ NewTempFile(tempfile, ".txt");
+ FILE *f = fopen(tempfile, "wb");
+ fprintf(f, "Content-type: text/plain\nAccess-Control-Allow-Origin: *\n\n");
+ NonDestructiveDumpDICOMObject(pDDO, f);
+ fputc(' ', f); // 20120829 help to make even length
+ strcpy(SilentText, "text/plain");
+ fclose(f);
+ }
+ if (r2 && strcmp(r2, "text/html")==0)
+ {
+ NewTempFile(tempfile, ".html");
+ FILE *f = fopen(tempfile, "wb");
+ // ODD HEADER LENGHT AVOIDED HERE
+ fprintf(f, "Content-type: text/html\nAccess-Control-Allow-Origin:*\n\n");
+ NonDestructiveDumpDICOMObject(pDDO, f);
+ fclose(f);
+ }
+ delete pDDO;
+ }
+ }
+
+ else if (memcmp(SilentText, "count_frames:", 13)==0)
+ {
+ DICOMDataObject *pDDO;
+ pDDO = LoadForGUI(SilentText+13);
+ if (pDDO)
+ {
+ sprintf(Response, "%d", GetNumberOfFrames(pDDO));
+ delete pDDO;
+ }
+ }
+ else if (memcmp(SilentText, "grabimagesfromserver:", 21)==0)
+ {
+ if (p) *p++=0; // points after 1st comma
+ GrabImagesFromServer((unsigned char *)SilentText+21, p, (char *)MYACRNEMA);
+ GrabFromGui++;
+ }
+ else if (memcmp(SilentText, "prefetch:", 9)==0)
+ {
+ PrefetchPatientData((char *)SilentText+9, 0);
+ }
+ else if (memcmp(SilentText, "loadhl7:", 8)==0)
+ {
+ unsigned int len = DFileSize(SilentText+8);
+ if (len)
+ {
+ char *p2=(char*) malloc(len+1);
+ FILE *f;
+ f = fopen(SilentText+8, "rb");
+ fread(p2, 1, len, f);
+ p2[len]=0;
+ fclose(f);
+ ProcessHL7Data(p2);
+ free(p2);
+ }
+ }
+ else if (memcmp(SilentText, "quit:", 5)==0)
+ {
+ exit(0);
+ }
+ else if (memcmp(SilentText, "safequit:", 9)==0)
+ {
+ while (OpenThreadCount>1) Sleep(1000);
+ exit(0);
+ }
+ else if (memcmp(SilentText, "checklargestmalloc:", 19)==0)
+ {
+ // mvh: on 32 bits system the malloc will fail before size_t(32 bits) overflows
+ // on 64 bits the test will happily continue to 8 GB and further
+ for(long long i=0; i<1000; i++)
+ { char *p2 = (char *)malloc((size_t)(i*10*1024*1024));
+ if (p2) free(p2);
+ else
+ {
+ OperatorConsole.printf("Largest malloc = %d MB\n", (int)((i-1)*10));
+ break;
+ }
+ }
+ }
+ else if (memcmp(SilentText, "genuid:", 7)==0)
+ {
+ char uid[70];
+ GenUID(uid);
+ sprintf(Response, "%s", uid);
+ }
+ else if (memcmp(SilentText, "changeuid:", 10)==0)
+ {
+ char uid[70];
+ ChangeUID(SilentText+10, "--changeuid", uid);
+ sprintf(Response, "%s", uid);
+ }
+ else if (memcmp(SilentText, "changeuidback:", 14)==0)
+ {
+ char uid[70];
+ ChangeUIDBack(SilentText+14, uid);
+ sprintf(Response, "%s", uid);
+ }
+ else if (memcmp(SilentText, "scheduletransfer:", 17)==0)
+ {
+ char scr[] = "call submit.cq"; // default script
+ char *r2=NULL, *r3=NULL, *r4=NULL;
+ if (p)
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ',');
+ if (q)
+ { *q++=0; // points after 2nd comma
+ r1 = strchr(q, ',');
+ if (r1)
+ { *r1++=0; // points after 3nd comma
+ r2 = strchr(r1, ',');
+ if (r2)
+ { *r2++=0; // points after 4nd comma
+ r3 = strchr(r2, ',');
+ if (r3)
+ { *r3++=0;
+ r4 = strchr(r3, ','); // optional script
+ if (!r4) r4=scr;
+ else *r4++ = 0;
+ }
+ }
+ }
+ }
+ }
+ // prefetch_queue("submit patient ", SilentText+17, "", p, q, "", "", "", r1, r2, r3, 1, "call submit.cq");
+ prefetch_queue("submit patient ", SilentText+17, "", p, q, "", "", "", r1, r2, r3, 1, r4);
+ /*
+ char fields[2048];
+ char values[2048];
+ strcpy(fields, "HostDicom,PortDicom,HostWebsrv,PortWebSrv" );
+ strcat(fields, ",ModeSubmit,HostSubmit,PortSubmit,Ident" );
+ strcat(fields, ",PatientID,StudyUID,SeriesUID,ObjInstUID" );
+ strcpy(values, SilentText + 17);
+
+ Database DB;
+ if (DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ DB.AddRecord("SUBMISSIONS", fields, values);
+ DB.Close();
+ }
+ */
+ }
+ else if (memcmp(SilentText, "checksum:", 9)==0)
+ {
+ sprintf(Response, "%u", ComputeCRC(SilentText+9, strlen(SilentText+9)));
+ }
+ else if (memcmp(SilentText, "attachrtplantortstruct:", 23)==0)
+ {
+ if (p) *p++=0; // points after 1st comma
+ AttachRTPLANToRTSTRUCT(SilentText+23, p, &PDU);
+ }
+ else if (memcmp(SilentText, "attachanytopatient:", 19)==0)
+ {
+ if (p) *p++=0;
+ AttachAnyToPatient(SilentText+19, p, &PDU);
+ }
+ else if (memcmp(SilentText, "attachanytostudy:", 17)==0)
+ {
+ if (p) *p++=0;
+ AttachAnyToStudy(SilentText+17, p, &PDU);
+ }
+ else if (memcmp(SilentText, "attachanytoseries:", 18)==0)
+ {
+ if (p) *p++=0;
+ AttachAnyToSeries(SilentText+18, p, &PDU);
+ }
+ else if (memcmp(SilentText, "submit:", 7)==0)
+ {
+ char scr[] = "call submit.cq"; // default script
+ char *r2=NULL, *r3=NULL, *r4=NULL;
+ if (p) // study
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ','); // series
+ if (q)
+ { *q++=0; // points after 2nd comma
+ r1 = strchr(q, ','); // sop
+ if (r1)
+ { *r1++=0; // points after 3nd comma
+ r2 = strchr(r1, ','); // host
+ if (r2)
+ { *r2++=0; // points after 4th comma
+ r3 = strchr(r2, ','); // password
+ if (r3)
+ { *r3++=0; // points after 5th comma
+ r4 = strchr(r3, ','); // optional script
+ if (!r4) r4=scr;
+ else *r4++=0;
+ }
+ }
+ }
+ }
+ }
+ // DcmSubmitData(SilentText+7, p, q, r1, "call submit.cq", "sftp", r2, 22, r3);
+ DcmSubmitData(SilentText+7, p, q, r1, r4, "sftp", r2, 22, r3);
+ }
+ else if (memcmp(SilentText, "submit2:", 7)==0)
+ {
+ char scr[] = "call submit.cq"; // default script
+ char *r2=NULL, *r3=NULL, *r4=NULL;
+ if (p) // study
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ','); // series
+ if (q)
+ { *q++=0; // points after 2nd comma
+ r1 = strchr(q, ','); // sop
+ if (r1)
+ { *r1++=0; // points after 3nd comma
+ r2 = strchr(r1, ','); // host
+ if (r2)
+ { *r2++=0; // points after 4th comma
+ r3 = strchr(r2, ','); // command line
+ if (r3)
+ { *r3++=0; // points after 5th comma
+ r4 = strchr(r3, ','); // optional script
+ if (!r4) r4=scr;
+ else *r4++=0;
+ }
+ }
+ }
+ }
+ }
+ DcmSubmitData(SilentText+8, p, q, r1, r4, "other", r2, 22, r3);
+ }
+ else if (memcmp(SilentText, "export:", 7)==0)
+ {
+ char *r2=NULL, *r3=NULL;
+ if (p) // study
+ { *p++=0; // points after 1st comma
+ q = strchr(p, ','); // series
+ if (q)
+ { *q++=0; // points after 2nd comma
+ r1 = strchr(q, ','); // sop
+ if (r1)
+ { *r1++=0; // points after 3nd comma
+ r2 = strchr(r1, ','); // target file
+ if (r2)
+ { *r2++=0; // points after 4nd comma
+ r3 = strchr(r2, ','); // script
+ if (r3) *r3++=0;
+ }
+ }
+ }
+ }
+
+ if (r2==NULL || *r2==0)
+ { NewTempFile(tempfile, ".zip");
+ r2 = tempfile;
+ }
+ else if (strcmp(r2, "cgi")==0)
+ { NewTempFile(tempfile, ".zip");
+ r2 = tempfile;
+ }
+
+ DcmSubmitData(SilentText+7, p, q, r1, r3, "zip", r2, 0, NULL);
+ }
+ }
+
+ if (tempfile[0])
+ {
+ unsigned int len = DFileSize(tempfile);
+ if (len)
+ {
+ unsigned int extra=0;
+ if (memcmp(SilentText, "convert_to_dicom:", 17)==0) extra=64;
+ if (memcmp(SilentText, "export:", 7)==0) extra=62;
+ if (memcmp(SilentText, "text/plain", 10)==0) // 20120829 force even
+ { if (len & 1) len--;
+ }
+ VR *vr2 = new VR(0x9999, 0x0401, len+extra, TRUE);
+ FILE *f;
+ f = fopen(tempfile, "rb");
+ if (extra==64) sprintf((char *)(vr2->Data),
+ "Content-type: application/dicom\nAccess-Control-Allow-Origin: *\n\n");
+ // 64 extra bytes
+ if (extra==62) sprintf((char *)(vr2->Data),
+ "Content-type: application/zip\nAccess-Control-Allow-Origin: *\n\n");
+ // 62 extra bytes
+ fread((char*)(vr2->Data)+extra, 1, len, f);
+ fclose(f);
+ SOPVerification.WriteResponse(&PDU, &DCO, vr2);
+ }
+ else
+ SOPVerification.WriteResponse(&PDU, &DCO, NULL);
+ unlink(tempfile);
+ }
+ else if (Response[0])
+ {
+ VR *vr2 = new VR(0x9999, 0x0401, strlen(Response), (void *)Response, FALSE);
+ SOPVerification.WriteResponse(&PDU, &DCO, vr2);
+ }
+ else
+ SOPVerification.WriteResponse(&PDU, &DCO, NULL);
+ continue;
+ }
+
+ if(SOPPatientRootQuery.Read (&PDU, &DCO))
+ {
+#ifdef DEBUG_MODE
+ if (!vrsilent)
+ OperatorConsole.printf("C-Find (PatientRoot) located %d records\n", SOPPatientRootQuery.RecordsFound);
+#endif
+ C_Find_PatientRoot++;
+ continue;
+ }
+ if(SOPPatientRootRetrieveNKI.Read (&PDU, &DCO, (void *)&ratd))
+ {
+#ifdef DEBUG_MODE
+ if (!vrsilent)
+ OperatorConsole.printf("C-Move (PatientRootNKI)\n");
+#endif
+ LogUser("C-Move ", &PDU, &DCO);
+ C_Move_PatientRootNKI++;
+ continue;
+ }
+ if(SOPPatientRootRetrieveGeneric.Read (&PDU, &DCO, (void *)&ratd))
+ {
+#ifdef DEBUG_MODE
+ if (!vrsilent)
+ OperatorConsole.printf("C-Move (PatientRoot)\n");
+#endif
+ LogUser("C-Move ", &PDU, &DCO);
+ C_Move_PatientRoot++;
+ continue;
+ }
+
+ if(SOPStudyRootQuery.Read (&PDU, &DCO))
+ {
+#ifdef DEBUG_MODE
+ if (!vrsilent)
+ OperatorConsole.printf("C-Find (StudyRoot) located %d records\n", SOPStudyRootQuery.RecordsFound);
+#endif
+ C_Find_StudyRoot++;
+ continue;
+ }
+ if(SOPStudyRootRetrieveNKI.Read (&PDU, &DCO, (void *)&ratd))
+ {
+#ifdef DEBUG_MODE
+ if (!vrsilent)
+ OperatorConsole.printf("C-Move (StudyRootNKI)\n");
+#endif
+ LogUser("C-Move ", &PDU, &DCO);
+ C_Move_StudyRootNKI++;
+ continue;
+ }
+ if(SOPStudyRootRetrieveGeneric.Read (&PDU, &DCO, (void *)&ratd))
+ {
+#ifdef DEBUG_MODE
+ if (!vrsilent)
+ OperatorConsole.printf("C-Move (StudyRoot)\n");
+#endif
+ LogUser("C-Move ", &PDU, &DCO);
+ C_Move_StudyRoot++;
+ continue;
+ }
+
+ if(SOPPatientStudyOnlyQuery.Read (&PDU, &DCO))
+ {
+#ifdef DEBUG_MODE
+ if (!vrsilent)
+ OperatorConsole.printf("C-Find (PatientStudyOnly) located %d records\n", SOPPatientStudyOnlyQuery.RecordsFound);
+#endif
+ C_Find_PatientStudyOnly++;
+ continue;
+ }
+
+ if(SOPModalityWorkListQuery.Read (&PDU, &DCO))
+ {
+#ifdef DEBUG_MODE
+ if (!vrsilent)
+ OperatorConsole.printf("C-Find (Modality Work List) located %d records\n", SOPModalityWorkListQuery.RecordsFound);
+#endif
+ C_Find_ModalityWorkList++;
+ continue;
+ }
+
+ if(SOPPatientStudyOnlyRetrieveNKI.Read (&PDU, &DCO, (void *)&ratd))
+ {
+#ifdef DEBUG_MODE
+ if (!vrsilent)
+ OperatorConsole.printf("C-Move (PatientStudyOnlyNKI)\n");
+#endif
+ LogUser("C-Move ", &PDU, &DCO);
+ C_Move_PatientStudyOnlyNKI++;
+ continue;
+ }
+ if(SOPPatientStudyOnlyRetrieveGeneric.Read (&PDU, &DCO, (void *)&ratd))
+ {
+#ifdef DEBUG_MODE
+ if (!vrsilent)
+ OperatorConsole.printf("C-Move (PatientStudyOnly)\n");
+#endif
+ LogUser("C-Move ", &PDU, &DCO);
+ C_Move_PatientStudyOnly++;
+ continue;
+ }
+
+ vr = DCO.GetVR(0x0000, 0x0100);
+ if(vr && vr->Data)
+ {
+ val = (* ((UINT16*)vr->Data) );
+#if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian like Apple power pc
+ val = SwitchEndian(val);
+#endif
+ }
+ else
+ val = 0xffff;
+
+ if(val==0x0fff) // C-CANCEL = cancel request
+ {
+#ifdef DEBUG_MODE
+ if (!vrsilent)
+ OperatorConsole.printf("Cancel request\n"); // (ignored)\n");
+#endif
+ continue;
+ }
+
+ if(PrinterSupport (&PDU, &DCO, PrintData))
+ {
+ continue;
+ }
+
+
+// DICOMDataObject *CommitData = NULL;
+// if(StorageCommitmentSupport (&PDU, &DCO, &CommitData))
+// {
+// continue;
+// }
+
+// if (CommitData)
+// {
+// PDU.Close();
+//OperatorConsole.printf("hi\n");
+// StorageCommitmentSupport (&PDU, &DCO, &CommitData);
+// break;
+// }
+
+ //Note: Changed print val to hex, easier to read.
+ OperatorConsole.printf("\n***Client Error: command %4.4x failed **\n", val);
+ OperatorConsole.printf("***Connection Terminated\n");
+ UnknownRequest++;
+
+ DebugLevel += 4;
+ NonDestructiveDumpDICOMObject(&DCO);
+ DebugLevel -= 4;
+
+ PDU.Close();
+
+ struct scriptdata sd3 = {&PDU, &DCO, NULL, 0, NULL, NULL, NULL, NULL, NULL, 0, ConnectedIP};
+ do_lua(&(PDU.L), lua_clienterror, &sd3);
+ if (sd3.DDO) delete sd3.DDO;
+
+ OpenThreadCount--;
+ return ( FALSE );
+ }
+
+ // wait for the read ahead thread to end (otherwise ratd would point to nothing)
+
+ ratd.ForceEnd = TRUE;
+ while (ratd.Busy) Sleep(50);
+
+ // free memory associated with thread if not already done so
+ if (ratd.Devices)
+ {
+ if (ratd.pDCO) delete ratd.pDCO; ratd.pDCO = NULL;
+ for (int i=0; i<ratd.NumToRead; i++)
+ if (ratd.DDOOutPtr[i] && (ratd.Status[i] == STATUS_READ))
+ delete ratd.DDOOutPtr[i];
+ free(ratd.DDOOutPtr); ratd.DDOOutPtr = NULL;
+ free(ratd.Filenames); ratd.Filenames = NULL;
+ free(ratd.ObjectFiles);ratd.ObjectFiles = NULL;
+ free(ratd.Devices); ratd.Devices = NULL;
+ free(ratd.Status); ratd.Status = NULL;
+
+ // 20060405 mvh Fix for multiple moves on same assoc (thanks Andrej Savelov)
+ free(ratd.SOPs); ratd.SOPs = NULL;
+ free(ratd.Series); ratd.Series = NULL;
+ free(ratd.Studies); ratd.Studies = NULL;
+ free(ratd.pats); ratd.pats = NULL;
+
+ CloseHandle(ratd.Handle); ratd.Handle = NULLHANDLE;
+ }
+
+ // 20060405 mvh Fix for multiple moves on same assoc (thanks Andrej Savelov)
+ ratd.TimeOut = FALSE;
+ ratd.Busy = FALSE;
+
+ struct scriptdata sd4 = {&PDU, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, 0, ConnectedIP};
+ do_lua(&(PDU.L), lua_endassociation, &sd4);
+ if (sd4.DDO) delete sd4.DDO;
+
+ OpenThreadCount--;
+
+ TimeOfDay2 = time(NULL);
+ TotalTime += TimeOfDay2 - TimeOfDay;
+ if (!vrsilent)
+ {
+ char buf[64];
+ UNUSED_ARGUMENT(buf);//Stop gcc4.2 warning bcb
+ strcpy(TimeString, ctime_r(&TimeOfDay2, buf));
+ TimeString[strlen(TimeString)-1] = '\0';
+ OperatorConsole.printf("UPACS THREAD %d: ENDED AT: %s\n", ThreadNum, TimeString);
+ OperatorConsole.printf("UPACS THREAD %d: TOTAL RUNNING TIME: %d SECONDS\n", ThreadNum, TimeOfDay2 - TimeOfDay);
+ // this call to provide timely close given ForwardAssociationLevel for ImportConverters
+ if (OpenThreadCount==0) CallImportConverters(NULL, NULL, NULL, NULL, NULL, NULL, NULL);
+ }
+#ifdef __BORLANDC__
+ {
+ int i = _heapchk();
+ if (i<0) OperatorConsole.printf("*** heap error *** : %d", i);
+ }
+#endif
+
+ return ( TRUE );
+ }
+
+StorageApp ServerApp;
+
+void ConfigDgate(void)
+ {
+ char szRootSC[64];
+ char szTemp[32], szTemp2[32];
+ int i;
+
+ // allow enable/disable of read ahead thread
+ if (!MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig,
+ szRootSC, 64, ConfigFile)) return;
+
+ if (!MyGetPrivateProfileString(szRootSC, "EnableReadAheadThread", "1",
+ szTemp, 32, ConfigFile)) return;
+ EnableReadAheadThread = atoi(szTemp);
+
+ if (!MyGetPrivateProfileString(szRootSC, "WorkListMode", "0",
+ szTemp, 32, ConfigFile)) return;
+ WorkListMode = atoi(szTemp);
+
+ // archive compression setting (new); note: returns length of entry; can be zero - is still OK!
+ MyGetPrivateProfileString(szRootSC, "ArchiveCompression", "", ArchiveCompression, 16, ConfigFile);
+
+ // compression default empty (same as as is)
+ DroppedFileCompression[0] = 0;
+ IncomingCompression [0] = 0;
+
+ // still accept obsolete FileCompressMode - 1..4 interpreted as nki compression n1..n4
+ MyGetPrivateProfileString(szRootSC, "FileCompressMode", "0", szTemp, 32, ConfigFile);
+ FileCompressMode = atoi(szTemp);
+ if (FileCompressMode)
+ {
+ sprintf(DroppedFileCompression, "n%d", FileCompressMode);
+ sprintf(IncomingCompression, "n%d", FileCompressMode);
+ }
+
+ // default no change of these settings
+ MyGetPrivateProfileString(szRootSC, "DroppedFileCompression",
+ DroppedFileCompression, DroppedFileCompression, 16, ConfigFile);
+ MyGetPrivateProfileString(szRootSC, "IncomingCompression",
+ IncomingCompression, IncomingCompression, 16, ConfigFile);
+
+ MyGetPrivateProfileString(szRootSC, "StorageFailedErrorCode", "272", szTemp, 32, ConfigFile);
+ StorageFailedErrorCode = atoi(szTemp);
+
+ MyGetPrivateProfileString(szRootSC, "TCPIPTimeOut", "300", szTemp, 32, ConfigFile);
+ TCPIPTimeOut = atoi(szTemp);
+
+ MyGetPrivateProfileString(szRootSC, "FailHoldOff", "60", szTemp, 32, ConfigFile);
+ FailHoldOff = atoi(szTemp);
+
+ MyGetPrivateProfileString(szRootSC, "RetryDelay", "100", szTemp, 32, ConfigFile);
+ RetryDelay = atoi(szTemp);
+
+ MyGetPrivateProfileString(szRootSC, "QueueSize", "128", szTemp, 32, ConfigFile);
+ QueueSize = atoi(szTemp);
+
+ MyGetPrivateProfileString(szRootSC, "ForwardCollectDelay", "600", szTemp, 32, ConfigFile);
+ ForwardCollectDelay = atoi(szTemp);
+
+ for (i=0; i<10; i++)
+ {
+ sprintf(szTemp, "VirtualServerFor%d", i);
+ MyGetPrivateProfileString(szRootSC, szTemp, "", VirtualServerFor[i], 48, ConfigFile);
+
+ sprintf(szTemp, "VirtualServerPerSeries%d", i);
+ MyGetPrivateProfileString(szRootSC, szTemp, "", szTemp2, 32, ConfigFile);
+ VirtualServerPerSeries[i]=atoi(szTemp2);
+ }
+
+ MyGetPrivateProfileString(szRootSC, "CacheVirtualData", "1", szTemp, 32, ConfigFile);
+ CacheVirtualData = atoi(szTemp);
+
+ MyGetPrivateProfileString(szRootSC, "PadAEWithZeros", "0", szTemp, 32, ConfigFile);
+ ConfigPadAEWithZeros = atoi(szTemp);
+
+//To speed things up, I get what I need only once.
+#ifdef HAVE_BOTH_J2KLIBS
+ MyGetPrivateProfileString ( szRootSC, "UseOpenJPG", "0", szTemp, 32, ConfigFile);
+ gUseOpenJpeg = atoi(szTemp);
+#endif
+#ifdef HAVE_LIBJPEG // JPEG stuff
+ MyGetPrivateProfileString ( szRootSC, "LossyQuality", DEFAULT_LOSSY, szTemp, 32, ConfigFile);
+ gJpegQuality = atoi(szTemp);
+#endif
+#ifdef HAVE_J2K // Also used in jpeg 2000
+#ifndef HAVE_LIBJPEG// Don't want it twice
+ MyGetPrivateProfileString ( szRootSC, "LossyQuality", DEFAULT_LOSSY, szTemp, 32, ConfigFile);
+ gJpegQuality = atoi(szTemp);
+#endif
+#endif
+ }
+
+// main as console app or child process
+static void DgateCgi(char *query_string, char *ext); // forward reference
+
+int
+main ( int argc, char *argv[] )
+ {
+ char TimeString1[128];
+ time_t TimeOfDay, TimeOfDay2;
+
+ char szRootSC[64];
+ char szTemp[32];
+ int i, j;
+ BOOL MissingDict=FALSE;
+ char tempStr[1024];
+ int valid_argc, slen;
+ struct stat st;
+
+ for (i=0; i<MAXExportConverters; i++)
+ for (j=0; j<MAXExportConverters; j++)
+ import_c_init[i][j]=FALSE;
+
+ char *query_string = getenv( "CONTENT_LENGTH" );
+ if (query_string && *query_string && argc==1)
+ {
+#ifdef UNIX
+ char *ext="";
+#else
+ char *ext=strrchr(argv[0], '.');
+#endif
+ DgateCgi(query_string, ext);
+ exit(0);
+ }
+
+ query_string = getenv( "QUERY_STRING" );
+ if (query_string && argc==1)
+ {
+#ifdef UNIX
+ char *ext="";
+#else
+ char *ext=strrchr(argv[0], '.');
+#endif
+ DgateCgi(query_string, ext);
+ exit(0);
+ }
+
+ StartTime = time(NULL);
+ //SetDicomErrorHandler(MyDcmError);
+
+ slen = 0;
+ BaseDir[0] = 0;
+
+ // Search for -w to set root dir and/or dicom.ini, allows dgate to be in the "bin" or any other dir.
+ // Output: BaseDir with PATHSEPCHAR and ConfigFile with full path
+ for (valid_argc = 1; valid_argc < argc; valid_argc++ )
+ {
+ if((argv[valid_argc][0]=='-') || (argv[valid_argc][0]=='/'))
+ {
+ if( argv[valid_argc][1] == 'w' || argv[valid_argc][1] == 'W')
+ {
+ strncpy(BaseDir, (argv[valid_argc] + 2), 255); // Drop the -w.
+ ConfigFile[255] = 0;
+
+ slen = strlen(BaseDir);
+ if(slen < 4 || stricmp(BaseDir + slen - 4, ".ini") != 0)
+ { // No ini file, check if directory.
+ if(BaseDir[slen - 1] == PATHSEPCHAR)
+ BaseDir[--slen] = 0; // Drop the path char for testing
+ if(stat(BaseDir, &st) != 0)
+ {
+ printf("Directory %s does not exist.\n", BaseDir);
+ exit(0);
+ }
+ if (!(st.st_mode & S_IFDIR))
+ {
+ printf("%s is not a directory.\n", BaseDir);
+ exit(0);
+ }
+ BaseDir[slen++] = PATHSEPCHAR;
+ BaseDir[slen] = 0;
+
+ strncpy(ConfigFile, BaseDir, 246); // - length of /dicom.ini.
+ ConfigFile[246] = 0;
+ strcat(ConfigFile, "dicom.ini"); // Add the default
+ }
+ else
+ { // Its the full file name or a name change.
+ if(strrchr(BaseDir, PATHSEPCHAR))
+ { //Its the full file name, .ini and a PATHSEPCHAR.
+ strncpy(ConfigFile, BaseDir, 255);
+ ConfigFile[255] = 0;
+ *(strrchr(BaseDir, PATHSEPCHAR) + 1) = 0; // Keep the PATHSEPCHAR.
+ }
+ else
+ { //Just a name change, no PATHSEPCHAR
+ strcpy(ConfigFile, BaseDir);
+ BaseDir[0] = 0;
+ slen = 0;
+ }
+ }
+ }
+ }
+ }
+
+ // no -w: set BaseDir to and get ini file from same directory as binary
+ if (slen == 0)
+ {
+ if (strrchr(argv[0], PATHSEPCHAR))
+ {
+ strcpy(ConfigFile, argv[0]);
+ *(strrchr(ConfigFile, PATHSEPCHAR) + 1) = 0;
+ strcpy(BaseDir, ConfigFile);
+ strcat(ConfigFile, "dicom.ini");
+ }
+ }
+
+#ifndef UNIX
+ char *path = getenv("PATH");
+ if (path)
+ {
+ char newpath[2048];
+ strcpy(newpath, BaseDir);
+ strcat(newpath, "clibs\\;");
+ strcat(newpath, path);
+ SetEnvironmentVariable("PATH", newpath);
+ }
+#endif
+
+ // Check if dicom.ini exists and contains key entry
+ // Does anything work without it?
+ if(stat(ConfigFile, &st) != 0)
+ {
+ printf("Configuration file %s not found, but required.\n", ConfigFile);
+ exit(0);
+ }
+
+ if (!MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig,
+ szRootSC, 64, ConfigFile))
+ {
+ printf("MicroPACS entry in %s not found, but required.\n", ConfigFile);
+ exit(0);
+ }
+
+ // Load dictionary dgate.dic like other config files
+ MyGetPrivateProfileString ( szRootSC, "Dictionary", "dgate.dic",
+ tempStr, 64, ConfigFile);
+
+ if (strrchr(tempStr, PATHSEPCHAR))
+ strcpy ((char*) DicomDict, tempStr);
+ else
+ {
+ strncpy ((char*) DicomDict, BaseDir, 256 - strlen(tempStr));
+ KFACTORFILE[256 - strlen(tempStr)] = 0;
+ strcat((char*) DicomDict, tempStr);
+ }
+
+ if (!VRType.AttachRTC(DicomDict))
+ {
+ MissingDict = TRUE;
+ printf("Dictionary file %s is missing, some server functions will not work correctly\n", DicomDict);
+ }
+
+ MyGetPrivateProfileString ( szRootSC, "NoDicomCheck", "0",
+ tempStr, 64, ConfigFile);
+ NoDicomCheck = atoi(tempStr);
+ if (!NoDicomCheck)
+ SetDicomErrorHandler(MyDcmError);
+
+ ConfigDgate();
+
+ // autostart lua file with same name as executable
+ strcpy(tempStr, argv[0]);
+ char *p = strrchr(tempStr, PATHSEPCHAR);
+ if (!p) p = tempStr; else p++;
+ char *q = strchr(p, '.');
+ if (!q) q = p+strlen(p);
+ strcpy(q, ".lua");
+ if(stat(p, &st) != 0)
+ {
+ memmove(p+4, p, strlen(p)+1);
+ strcpy(p, "lua");
+ p[3] = PATHSEPCHAR;
+ }
+ if(stat(p, &st) == 0)
+ {
+ char cmd[1024];
+ sprintf(cmd, "dofile([[%s]])", p);
+ OperatorConsole.On();
+ LoadKFactorFile((char*)KFACTORFILE);
+ InitACRNemaAddressArray();
+ globalPDU.SetLocalAddress ( (BYTE *)"standalone" );
+ globalPDU.SetRemoteAddress ( (BYTE *)"standalone" );
+ globalPDU.ThreadNum = 0;
+ struct scriptdata sd = {&globalPDU, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, 0, 0};
+ lua_setvar(&globalPDU, "version", DGATE_VERSION);
+ lua_createtable (globalPDU.L, 0, 0);
+ for (int i=0; i<argc; i++)
+ {
+ lua_pushinteger(globalPDU.L, i+1);
+ lua_pushstring (globalPDU.L, argv[i]);
+ lua_settable (globalPDU.L, -3);
+ }
+ lua_setglobal (globalPDU.L, "arg");
+ do_lua(&(globalPDU.L), cmd, &sd);
+ if (sd.DDO) delete sd.DDO;
+ if (sd.rc==2 || sd.rc==6) exit(0); // reject on startup
+ }
+
+ char cmd[1024];
+ MyGetPrivateProfileString("lua", "startup", "", cmd, 1024, ConfigFile);
+ globalPDU.SetLocalAddress ( (BYTE *)"global" );
+ globalPDU.SetRemoteAddress ( (BYTE *)"global" );
+ globalPDU.ThreadNum = 0;
+ struct scriptdata sd = {&globalPDU, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, 0, 0};
+ do_lua(&(globalPDU.L), cmd, &sd);
+ if (sd.DDO) delete sd.DDO;
+ if (sd.rc==2 || sd.rc==6) exit(0); // reject on startup
+
+#ifdef UNIX
+ // set that pesky broken pipe signal to be ignored
+ // I/O that would have generated a SIGPIPE will return EPIPE instead
+ // this applies to named pipe writes and read/write of sockets
+
+ signal(SIGPIPE, SIG_IGN);
+#endif
+
+ int Socketfd;
+
+#if defined(DO_LEAK_DETECTION) || defined(DO_VIOLATION_DETECTION)
+ int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
+
+#ifdef DO_LEAK_DETECTION
+ tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
+#endif
+
+#ifdef DO_VIOLATION_DETECTION
+ tmpDbgFlag |= _CRTDBG_CHECK_ALWAYS_DF;
+#endif
+
+ _CrtSetDbgFlag(tmpDbgFlag);
+ /* If a leak is detected, run again after specifying the serial num of the
+ leak using _CrtSetBreakAlloc(<id>); */
+// _CrtSetBreakAlloc(37);
+#endif
+
+ if ( ! (Socketfd = ParseArgs(argc, argv, &globalPDU) ))
+ {
+ if (RunServer)
+ {
+ struct stat statbuf;
+ char TimeString[100], buf[64];
+ int iNbConverters;
+
+ UNUSED_ARGUMENT(buf);//Stop gcc4.2 warning bcb
+ memset((void *)&statbuf, 0, sizeof(statbuf));
+
+ // Start queue for export converters (may reprocess previously failed requests)
+ stat(argv[0], &statbuf);
+ strcpy(TimeString, ctime_r(&statbuf.st_mtime, buf));
+ TimeString[strlen(TimeString)-1] = '\0';
+ if (!(statbuf.st_mode & S_IFREG)) strcpy(TimeString, "?");
+ if (NoThread)
+ OperatorConsole.printf("DGATE (%s, build %s, bits %d) runs in non-threaded debug mode\n", DGATE_VERSION, TimeString, 8*sizeof(void *));
+ else
+ OperatorConsole.printf("DGATE (%s, build %s, bits %d) is running as threaded server\n", DGATE_VERSION, TimeString, 8*sizeof(void *));
+
+ {
+ Database testDB;
+ if (testDB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ switch(testDB.db_type)
+ {
+ case DT_ODBC: OperatorConsole.printf("Database type: ODBC connection\n"); break;
+ case DT_POSTGRES: OperatorConsole.printf("Database type: native PostGres connection\n"); break;
+ case DT_MYSQL: OperatorConsole.printf("Database type: native MySQL connection\n"); break;
+ case DT_SQLITE: OperatorConsole.printf("Database type: built-in SQLite driver\n"); break;
+ case DT_DBASEIII: OperatorConsole.printf("Database type: built-in Dbase driver\n"); break;
+ case DT_DBASEIIINOINDEX: OperatorConsole.printf("Database type: built-in Dbase driver (indices disabled)\n"); break;
+ case DT_NULL: OperatorConsole.printf("Database type: NULL driver (black hole)\n"); break;
+ }
+ };
+ }
+
+ if (MissingDict)
+ OperatorConsole.printf("*** File dgate.dic is missing, some server functions will not work correctly\n");
+
+ MyGetPrivateProfileString(szRootSC, "ExportConverters", "0", szTemp, 32, ConfigFile);
+ iNbConverters = atoi(szTemp);
+ if (iNbConverters>MAXExportConverters) iNbConverters=MAXExportConverters;
+
+ if (iNbConverters && !NoThread)
+ { eqN = (struct conquest_queue **)malloc(iNbConverters * sizeof(struct conquest_queue *));
+ memset(eqN, 0, iNbConverters * sizeof(struct conquest_queue *));
+ for(i=0; i<iNbConverters; i++)
+ export_queueN(&eqN[i], NULL, i, NULL, NULL, NULL, NULL, NULL, NULL);
+ OperatorConsole.printf("Started %d export queue thread(s)\n", iNbConverters);
+ }
+
+ // Start queue for mirror copy (may reprocess previously failed requests)
+ MyGetPrivateProfileString(szRootSC, "MIRROR0", "-1", szTemp, 32, ConfigFile);
+ if (atoi(szTemp)!=-1 && !NoThread)
+ { mirrorcopy_queue(NULL, NULL);
+ OperatorConsole.printf("Started mirror copy queue thread\n");
+ }
+
+ // Start prefetcher queue
+ MyGetPrivateProfileString(szRootSC, "Prefetcher", "0", szTemp, 32, ConfigFile);
+ if (atoi(szTemp) && !NoThread)
+ { prefetchermode = atoi(szTemp);
+ prefetcher(NULL, FALSE);
+ OperatorConsole.printf("Started prefetcher queue thread\n");
+ }
+
+ MyGetPrivateProfileString ( szRootSC, "WatchFolder", "",
+ tempStr, 1024, ConfigFile);
+ if (tempStr[0])
+ { strcpy(monitorfolder2, tempStr);
+ OperatorConsole.printf("Also monitoring for files in: %s\n", tempStr);
+ StartMonitorThread(monitorfolder2);
+ }
+
+ if (NoThread)
+ while ( TRUE )
+ ServerApp.Server(Port);
+ else
+ ServerApp.Server(Port);
+ }
+ return(0);
+ }
+
+ // run a child from a driver application
+ OperatorConsole.printf("Child: Socketfd = %d\n", Socketfd);
+
+ // Print Date / Time in Log file
+ char buf[64];
+ UNUSED_ARGUMENT(buf);//Stop gcc4.2 warning bcb
+ TimeOfDay = time(NULL);
+ strcpy(TimeString1, ctime_r(&TimeOfDay, buf));
+ TimeString1[strlen(TimeString1)-1] = '\0';
+ OperatorConsole.printf("UPACS: %s: STARTED AT: %s\n", argv[1], TimeString1);
+
+ ServerApp.ServerChild(Socketfd);
+
+ TimeOfDay2 = time(NULL);
+ strcpy(TimeString1, ctime_r(&TimeOfDay2, buf));
+ TimeString1[strlen(TimeString1)-1] = '\0';
+ OperatorConsole.printf("UPACS: %s: ENDED AT: %s\n", argv[1], TimeString1);
+ OperatorConsole.printf("UPACS: %s: TOTAL RUNNING TIME: %d SECONDS\n", argv[1], TimeOfDay2 - TimeOfDay );
+
+ return ( 0 );
+ }
+
+///////////////////////////////////////////////////////////////////////////////
+// grabbing code
+///////////////////////////////////////////////////////////////////////////////
+
+void SetStringVR(VR **vr, int g, int e, const char *String)
+{ unsigned int len;
+ char* pCopy;
+
+ /* NOTE:
+ Uneven length strings must be padded with a space.
+ Uneven length UIDs must be padded with \0.
+ */
+ len = strlen(String);
+ pCopy = strdup(String);
+
+ if ((g==0x0008 && e==0x0018) || (g==0x0020 && e==0x000d) || (g==0x0020 && e==0x000e))
+ { if (len & 1) len++;
+ }
+ else
+ { if (len & 1)
+ pCopy[len++] = ' ';
+ }
+
+ *vr = new VR(g, e, len, (void*)pCopy, (BOOL) TRUE);
+}
+
+
+BOOL GrabImagesFromServer(BYTE *calledae, const char *studydate, char *destination)
+ {
+ BOOL quit, quit2;
+ PDU_Service PDU, PDU2;
+ DICOMCommandObject DCO;
+ DICOMCommandObject DCOR, DCOR2;
+ DICOMDataObject DDO;
+ DICOMDataObject DDOR, DDOR2;
+ UID uid, uid2;
+ VR *vr1;
+ LE_UINT16 command, datasettype, messageid, priority;
+ BYTE SOP[66];
+ unsigned char ip[64], port[64], compress[64];
+
+ PDU.AttachRTC(&VRType);
+ PDU2.AttachRTC(&VRType);
+
+ if(!GetACRNema((char *)calledae, (char *)ip, (char *)port, (char *)compress))
+ return FALSE;
+
+ // Start setting up connection for C-FIND
+ PDU.ClearAbstractSyntaxs();
+ PDU.SetLocalAddress(MYACRNEMA);
+ PDU.SetRemoteAddress(calledae);
+
+ uid.Set("1.2.840.10008.3.1.1.1"); // Application context (DICOM App)
+ PDU.SetApplicationContext(uid);
+
+ uid.Set("1.2.840.10008.5.1.4.1.2.2.1"); // StudyRootQuery (C-Find SOP)
+ PDU.AddAbstractSyntax(uid);
+
+ // idem for the C-MOVE
+ PDU2.ClearAbstractSyntaxs();
+ PDU2.SetLocalAddress(MYACRNEMA);
+ PDU2.SetRemoteAddress(calledae);
+
+ uid2.Set("1.2.840.10008.3.1.1.1"); // Application context (DICOM App)
+ PDU2.SetApplicationContext(uid2);
+
+ uid2.Set("1.2.840.10008.5.1.4.1.2.2.2"); // StudyRootRetrieve (C-Move SOP)
+ PDU2.AddAbstractSyntax(uid2);
+
+ PDU.SetTimeOut(TCPIPTimeOut);
+ PDU2.SetTimeOut(TCPIPTimeOut);
+
+ // Make the association for the FIND on port/ip
+ if(!PDU.Connect(ip, port))
+ {
+ OperatorConsole.printf("*** Grab - failed to connect for C-FIND\n");
+ return ( FALSE );
+ }
+
+ // Make the association for the MOVE on port/ip
+ if(!PDU2.Connect(ip, port))
+ {
+ PDU.Close();
+ OperatorConsole.printf("*** Grab - failed to connect for C-MOVE\n");
+ return(FALSE);
+ }
+
+ // Start a StudyRootQuery
+
+ strcpy((char*) SOP, "1.2.840.10008.5.1.4.1.2.2.1"); // StudyRootQuery (C-Find SOP)
+ vr1 = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE);
+ DCO.Push(vr1);
+ command = 0x0020;
+ vr1 = new VR (0x0000, 0x0100, 0x0002, &command, FALSE);
+ DCO.Push(vr1);
+ priority = 0; // MEDIUM
+ vr1 = new VR (0x0000, 0x0700, 0x0002, &priority, FALSE);
+ DCO.Push(vr1);
+ datasettype = 0x0102;
+ vr1 = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE);
+ DCO.Push(vr1);
+ messageid = 0x0003;
+ vr1 = new VR (0x0000, 0x0110, 0x0002, &messageid, FALSE);
+ DCO.Push(vr1);
+
+ // Start of data object. Query level is image; ask for image UIDs and patid
+
+ SetStringVR(&vr1, 0x0008, 0x0052, "IMAGE");
+ DDO.Push(vr1);
+ SetStringVR(&vr1, 0x0008, 0x0020, studydate);
+ DDO.Push(vr1);
+ SetStringVR(&vr1, 0x0008, 0x0018, "");
+ DDO.Push(vr1);
+ SetStringVR(&vr1, 0x0010, 0x0020, "");
+ DDO.Push(vr1);
+
+ // Write query command object and data object
+
+ PDU.Write(&DCO, uid);
+ PDU.Write(&DDO, uid);
+
+ // Get response
+
+ quit = 0;
+ while(!quit)
+ {
+ if(!PDU.Read(&DCOR))
+ {
+ PDU2.Close();
+ OperatorConsole.printf("*** Grab - association lost in C-FIND\n");
+ return ( FALSE ); // association lost
+ }
+ // is this a C-Find-RSP ?
+ if(DCOR.GetUINT16(0x0000, 0x0100)!=0x8020)
+ {
+ PDU.Close();
+ PDU2.Close();
+ OperatorConsole.printf("*** Grab - wrong response for C-FIND\n");
+ return(FALSE);
+ }
+ // is there a data set?
+ if(DCOR.GetUINT16(0x0000, 0x0800)==0x0101)
+ {
+ PDU.Close();
+ PDU2.Close();
+ OperatorConsole.printf("Grab - finished\n");
+ return( TRUE );
+ }
+ // no success
+ if(DCOR.GetUINT16(0x0000, 0x0900)==0x0000)
+ {
+ PDU.Close();
+ PDU2.Close();
+ OperatorConsole.printf("*** Grab - C-FIND failed\n");
+ return ( FALSE );
+ }
+ // read response data
+ if(!PDU.Read(&DDOR))
+ {
+ PDU.Close();
+ PDU2.Close();
+ OperatorConsole.printf("*** Grab - C-FIND failed\n");
+ return(FALSE);
+ }
+
+ while((vr1 = DCOR.Pop()))
+ delete vr1;
+
+ while((vr1 = DDOR.Pop()))
+ {
+ if(vr1->Group == 0x0000) // error response
+ {
+ PDU.Close();
+ PDU2.Close();
+ OperatorConsole.printf("*** Grab - C-FIND error\n");
+ return ( TRUE );
+ }
+
+ // recieving a SOPInstanceUID
+ if (vr1->Group == 0x0008 && vr1->Element == 0x0018)
+ {
+ char s[255], none[] = "";
+ memset(s, 0, 255);
+ memcpy(s, vr1->Data, vr1->Length);
+
+ // is it on the local server (note: test may be speeded by passing patid) ?
+ if (!TestFilter(none, s, 10))
+ {
+ VR *vr;
+
+ // move it to the destination if it is not
+ strcpy((char*) SOP, "1.2.840.10008.5.1.4.1.2.2.2"); // StudyRootMove (C-Move SOP)
+ vr = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE);
+ DCO.Push(vr);
+ command = 0x0021;
+ vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE);
+ DCO.Push(vr);
+ priority = 0; // MEDIUM
+ vr = new VR (0x0000, 0x0700, 0x0002, &priority, FALSE);
+ DCO.Push(vr);
+ datasettype = 0x0102;
+ vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE);
+ DCO.Push(vr);
+ messageid++;
+ vr = new VR (0x0000, 0x0110, 0x0002, &messageid, FALSE);
+ DCO.Push(vr);
+ vr = new VR(0x0000, 0x0600, 16, (void*)destination, FALSE);
+ DCO.Push(vr);
+
+ // Data object. Query level is image; ask for date and SopInstanceUID
+ SetStringVR(&vr, 0x0008, 0x0052, "IMAGE");
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0008, 0x0020, studydate);
+ DDO.Push(vr);
+ SetStringVR(&vr, 0x0008, 0x0018, s);
+ DDO.Push(vr);
+
+ // Write command object and data object
+ PDU2.Write(&DCO, uid2);
+ PDU2.Write(&DDO, uid2);
+
+ // Get response
+ quit2 = 0;
+ while(!quit2)
+ {
+ if(!PDU2.Read(&DCOR2))
+ {
+ PDU.Close();
+ OperatorConsole.printf("*** Grab - C-MOVE association lost\n");
+ return ( FALSE ); // associate lost
+ }
+ if(DCOR2.GetUINT16(0x0000, 0x0100)!=0x8021)
+ {
+ PDU.Close();
+ PDU2.Close();
+ OperatorConsole.printf("*** Grab - C-MOVE got a wrong response\n");
+ return(FALSE);
+ }
+ // ignore the data set
+ if(DCOR2.GetUINT16(0x0000, 0x0800)!=0x0101)
+ {
+ PDU2.Read(&DDOR2);
+ DDOR2.Reset();
+ }
+ if(DCOR2.GetUINT16(0x0000, 0x0900)==0x0000) // success ?
+ {
+ OperatorConsole.printf("Grabbed %s\n", s);
+ quit2=1;
+ }
+ else if (DCOR2.GetUINT16(0x0000, 0x0900)==0xff00) // continuing no problem
+ {
+ }
+ else
+ {
+ UINT16 RemoteError = DCOR2.GetUINT16(0x0000, 0x0900); // mvh 20051208
+ OperatorConsole.printf("*** Grab - remote C-MOVE DICOM Error code %x (%d)\n", RemoteError, RemoteError);
+ NonDestructiveDumpDICOMObject(&DCOR2);
+ PDU.Close();
+ PDU2.Close();
+ return ( FALSE );
+ }
+ DCOR2.Reset();
+ }
+
+ }
+ }
+
+ delete vr1;
+ }
+ }
+
+ PDU.Close();
+ PDU2.Close();
+ return ( TRUE );
+ }
+
+/////////////////////////////////////////////////////////////////////////////////////////////
+// Used to send commands (e.g, from linux gui to be developed) to running server without reindexing
+/////////////////////////////////////////////////////////////////////////////////////////////
+
+int processhtml(char *out, char *in, int len)
+ {
+ int i, outlen=0, instring=0;
+ for (i=0; i<len; i++)
+ {
+ if (i>3 && in[i-3]=='<' && in[i-2]=='A' && instring==0) instring=1;
+ if (in[i]=='>' && instring==1) instring=0;
+
+ if (in[i]==' ' && instring) { out[outlen++] = '%'; out[outlen++] = '2'; out[outlen++] = '0'; }
+ else out[outlen++] = in[i];
+ }
+ return outlen;
+ }
+
+static BOOL SendServerCommand(const char *NKIcommand1, const char *NKIcommand2, int con, char *buf, BOOL html, BOOL upload)
+ {
+ PDU_Service PDU;
+ DICOMCommandObject DCO;
+ DICOMCommandObject DCOR;
+ UID uid;
+ VR *vr;
+ LE_UINT16 command, datasettype, messageid;//, tuint16;
+ BYTE SOP[64];
+
+ PDU.ClearAbstractSyntaxs();
+ PDU.SetLocalAddress(MYACRNEMA);
+ PDU.SetRemoteAddress(MYACRNEMA);
+ uid.Set("1.2.840.10008.3.1.1.1"); // Dicom APP
+ PDU.SetApplicationContext(uid);
+ uid.Set("1.2.840.10008.1.1"); // Verification
+ PDU.AddAbstractSyntax(uid);
+
+ if(!PDU.Connect((unsigned char *)ServerCommandAddress, Port))
+ return ( FALSE );
+
+ strcpy((char*) SOP, "1.2.840.10008.1.1"); // Verification
+ vr = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE);
+ DCO.Push(vr);
+
+ if (strlen(NKIcommand1))
+ { vr = new VR (0x9999, 0x0300, strlen((char*)NKIcommand1), (void*)NKIcommand1, FALSE);
+ DCO.Push(vr);
+ }
+
+ if (strlen(NKIcommand2))
+ { vr = new VR (0x9999, 0x0400, strlen((char*)NKIcommand2), (void*)NKIcommand2, FALSE);
+ DCO.Push(vr);
+ }
+
+ command = 0x0030;
+ vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE);
+ DCO.Push(vr);
+
+ datasettype = 0x0101;
+ vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE);
+ DCO.Push(vr);
+
+ messageid = 0x0001;
+ vr = new VR (0x0000, 0x0110, 0x0002, &messageid, FALSE);
+ DCO.Push(vr);
+
+ if (upload && buf)
+ { unsigned int len = DFileSize(buf);
+ vr = new VR(0x9999, 0x0402, len, TRUE);
+ FILE *f;
+ f = fopen(buf, "rb");
+ fread((char*)(vr->Data), 1, len, f);
+ fclose(f);
+ DCO.Push(vr);
+ }
+
+ if (buf) *buf=0;
+ PDU.Write(&DCO, uid);
+
+ if(!PDU.Read(&DCOR))
+ return ( FALSE ); // associate lost
+
+ while((vr = DCOR.Pop()))
+ {
+ if (vr->Group == 0x9999 && vr->Element == 0x0401)
+ {
+ if (buf)
+ {
+ int len;
+ if (html) len = processhtml(buf, (char *)vr->Data, vr->Length);
+ else memcpy(buf, vr->Data, len = vr->Length);
+ buf[len]=0;
+ if (len>1 && buf[len-1]==' ') len--;
+ }
+ else
+ {
+ if (con==0)
+ {
+ con = fileno(stdout);
+#ifdef WIN32
+ setmode(con, O_BINARY);
+#endif
+ }
+
+ if (html)
+ { char *buf1 = (char *)malloc(1000000);
+ int len = processhtml(buf1, (char *)vr->Data, vr->Length);
+ if (len>1 && buf1[len-1]==0 && (len&1)==0) len--;
+ write(con, buf1, len);
+ free(buf1);
+ }
+ else
+ { int len = vr->Length;
+ // assume header is EVEN for application/dicom
+ //if (len>33)
+ //if (memcmp(vr->Data, "Content-type: application/dicom\n", 32)==0)
+ //len--;
+ write(con, vr->Data, len);
+ }
+ }
+ }
+ delete vr;
+ }
+
+ PDU.Close();
+ return ( TRUE );
+ }
+
+static BOOL DcmEcho(const char *AE)
+ {
+ PDU_Service PDU;
+ DICOMCommandObject DCO;
+ DICOMCommandObject DCOR;
+ UID uid;
+ VR *vr;
+ LE_UINT16 command, datasettype, messageid;//, tuint16;
+ BYTE SOP[64], host[64], port[64], compr[64];
+
+ PDU.ClearAbstractSyntaxs();
+ PDU.SetLocalAddress(MYACRNEMA);
+ PDU.SetRemoteAddress((BYTE *)AE);
+ uid.Set("1.2.840.10008.3.1.1.1"); // Dicom APP
+ PDU.SetApplicationContext(uid);
+ uid.Set("1.2.840.10008.1.1"); // Verification
+ PDU.AddAbstractSyntax(uid);
+
+ if(!GetACRNema((char *)AE, (char *)host, (char *)port, (char *)compr))
+ return FALSE;
+
+ if(!PDU.Connect(host, port))
+ return ( FALSE );
+
+ strcpy((char*) SOP, "1.2.840.10008.1.1"); // Verification
+ vr = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE);
+ DCO.Push(vr);
+
+ command = 0x0030;
+ vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE);
+ DCO.Push(vr);
+
+ datasettype = 0x0101;
+ vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE);
+ DCO.Push(vr);
+
+ messageid = 0x0002;
+ vr = new VR (0x0000, 0x0110, 0x0002, &messageid, FALSE);
+ DCO.Push(vr);
+
+ PDU.Write(&DCO, uid);
+
+ if(!PDU.Read(&DCOR))
+ return ( FALSE ); // associate lost
+
+ while((vr = DCOR.Pop()))
+ {
+ delete vr;
+ }
+
+ PDU.Close();
+ return ( TRUE );
+ }
+
+/////////////////////////////////////////////////////////////////////////////////////////////
+// Elementary web interface
+/////////////////////////////////////////////////////////////////////////////////////////////
+
+static int isxdig(char ch)
+{ if ((ch>='0' && ch<='9') ||
+ (ch>='A' && ch<='F') ||
+ (ch>='a' && ch<='f'))
+ return 1;
+ else
+ return 0;
+}
+
+static int xdigit(char ch)
+{ if (ch>='0' && ch<='9')
+ return ch - '0';
+ else
+ return (ch & 15) + 9;
+}
+
+static int htoin(const char *value, int len)
+{ int i, result;
+
+ result = 0;
+ i = 0;
+ while (i < len && value[i] == ' ') i++;
+
+ while (i < len && isxdig(value[i]))
+ { result = result * 16 + xdigit(value[i]);
+ i++;
+ }
+
+ return result;
+}
+
+int console;
+
+static void HTML(const char *string, ...)
+{ char n[2]="\n";
+ char s[1250];
+ va_list vargs;
+
+ va_start(vargs, string);
+ vsprintf(s, string, vargs);
+ va_end(vargs);
+
+ write(console, s, strlen(s));
+ write(console, n, 1);
+}
+
+static char *post_buf=NULL;
+static char uploadedfile[256];
+
+static int CGI(char *out, const char *name, const char *def)
+{ char *p = getenv( "QUERY_STRING" );
+ char *q = getenv( "CONTENT_LENGTH" );
+ char *r = getenv( "REQUEST_METHOD" );
+ char tmp[512];
+ int i, j, len=0;
+ char *fstart=NULL;
+ int flen=0;
+
+//FILE *g = fopen("c:\\temp\\postbuf.txt", "wt");
+//fprintf(g, "%s\n%s\n%s\n", p,q,r);
+//fclose(g);
+
+ if (out!=def) *out = 0;
+
+ if (r!=NULL && memcmp(r, "POST", 3)==0)
+ { if (q!=NULL && *q!=0 && post_buf==NULL)
+ { len = atoi(q);
+ post_buf = (char *)malloc(len+1);
+ post_buf[len]=0;
+#ifdef WIN32
+ setmode(fileno(stdin), O_BINARY);
+#endif
+ fread(post_buf, len, 1, stdin);
+ p = post_buf;
+
+//FILE *g = fopen("c:\\temp\\postbuf.bin", "wb");
+//fwrite(post_buf, len, 1, g);
+//fclose(g);
+ }
+ else
+ if (post_buf) p = post_buf;
+
+ if (p==NULL) return 0;
+
+ if (p[0]=='-') // multipart data, locate the file (one assumed)
+ { q = strstr(p, "filename=");
+
+ if (q)
+ { *q=0; // cut contents short to allow fast read of other entries
+
+ char *ext = strchr(q+1, 0x0d); // parse extension from filename
+ q = ext+1;
+ if (ext)
+ { *ext--=0;
+ if (ext[0]=='"')
+ { *ext--=0;
+ }
+ while (*ext!='.' && *ext!=0) ext--;
+ }
+
+ q = strchr(q+1, 0x0a); // file starts after three newlines
+ if (q)
+ { q = strchr(q+1, 0x0a);
+ *q = 0;
+ fstart = q+1;
+ // file ends after two newlines (one at end)
+ flen = len - (fstart-post_buf);
+ flen-=4;
+ while (fstart[flen]!=0x0d && flen>0) flen--;
+
+ NewTempFile(uploadedfile, ext);
+ FILE *g = fopen(uploadedfile, "wb");
+ fwrite(fstart, flen, 1, g);
+ fclose(g);
+ }
+ }
+
+ strcpy(tmp, "name=\"");
+ strcat(tmp, name);
+ strcat(tmp, "\x22\x0d\x0a\x0d\x0a");
+
+ p = strstr(p, tmp); // parse data
+ if (p)
+ { p += strlen(tmp);
+ q = strchr(p, 0x0d);
+ if (q) *q=0;
+ strcpy(out, p);
+ return 0;
+ }
+
+ if (out!=def) strcpy(out, def);
+ return 0;
+ }
+ else if (*uploadedfile==0 && p[0]=='<') // xml
+ { NewTempFile(uploadedfile, ".xml");
+ FILE *g = fopen(uploadedfile, "wb");
+ fwrite(p, len, 1, g);
+ fclose(g);
+ p = getenv( "QUERY_STRING" );
+ }
+ else if (*uploadedfile==0) // any other type
+ { NewTempFile(uploadedfile, ".dat");
+ FILE *g = fopen(uploadedfile, "wb");
+ fwrite(p, len, 1, g);
+ fclose(g);
+ p = getenv( "QUERY_STRING" );
+ }
+ else
+ p = getenv( "QUERY_STRING" );
+ }
+
+
+ strcpy(tmp, "&"); // & only hits on second item
+ strcat(tmp, name);
+ strcat(tmp, "=");
+
+ // check first item
+ if (p)
+ { if (strlen(p)>=strlen(tmp+1) && memcmp(p, tmp+1, strlen(tmp+1))==0) q=p-1;
+ else q = strstr(p, tmp);
+ }
+ else
+ q=NULL;
+
+ if (q==NULL)
+ { if (out!=def) strcpy(out, def);
+ return 0;
+ }
+
+ q = q + strlen(tmp);
+
+ i = 0; j = 0;
+ while (q[i] != 0 && q[i] != '&')
+ { if (q[i] == '%')
+ { tmp[j++] = (char)(htoin(q+i+1, 2));
+ i = i+3;
+ }
+ else if (q[i] == '+')
+ { tmp[j++] = ' ';
+ i++;
+ }
+ else
+ tmp[j++] = q[i++];
+ }
+ tmp[j++] = 0;
+
+ strcpy(out, tmp);
+
+ return 0;
+}
+
+static BOOL Tabulate(const char *c1, const char *par, const char *c4, BOOL edit=FALSE)
+{ const char *p=strchr(par, ':');
+ char buf[512];
+
+ SendServerCommand("", par, 0, buf);
+ if (buf[0])
+ { if (edit) HTML("<TR><TD>%s<TD>%s<TD><INPUT SIZE=64 NAME=\"%s\" VALUE=\"%s\"><TD>%s<TD></TR>", c1, p+1, p+1, buf, c4, p+1);
+ else HTML("<TR><TD>%s<TD>%s<TD>%s<TD>%s<TD></TR>", c1, p+1, buf, c4, p+1);
+ return TRUE;
+ }
+ else
+ return FALSE;
+}
+
+static void replace(char *string, const char *key, const char *value)
+{ char temp[1000];
+ char *p = strstr(string, key), *q = string;
+
+ if (p==NULL) return;
+ if (value==NULL) return;
+
+ temp[0] = 0;
+ while(p)
+ { *p = 0;
+ strcat(temp, string);
+ *p = key[0];
+ strcat(temp, value);
+ string = p + strlen(key);
+ p = strstr(string, key);
+ };
+
+ strcat(temp, string);
+ strcpy(q, temp);
+}
+
+static BOOL DgateWADO(char *query_string, char *ext);
+
+static void DgateCgi(char *query_string, char *ext)
+{ char mode[512], command[8192], size[32], dsize[32], iconsize[32], slice[512], slice2[512], query[512], buf[512],
+ patientidmatch[512], patientnamematch[512], studydatematch[512], startdatematch[512],
+ db[256], series[512], study[512], compress[64], WebScriptAddress[256], WebMAG0Address[256],
+ WebServerFor[64], WebCodeBase[512], lw[64], source[64], dest[64], series2[512], study2[512],
+ DefaultPage[256], AnyPage[256], key[512];
+ char ex[128], extra[256], graphic[32], viewer[128], studyviewer[128];
+ unsigned int i, j;
+ DBENTRY *DBE;
+ char RootSC[64];
+ char Temp[128];
+ char *p1;
+
+ *uploadedfile=0;
+ if (DgateWADO(query_string, ext)) return;
+
+ BOOL ReadOnly=FALSE;
+ BOOL WebPush=TRUE;
+
+ UNUSED_ARGUMENT(query_string);
+
+ console = fileno(stdout);
+#ifdef WIN32
+ strcpy(ex, ".exe");
+ if (ext) strcpy(ex, ext);
+ setmode(console, O_BINARY);
+#else
+ ex[0]=0;
+ if (ext) strcpy(ex, ext);
+#endif
+
+ ConfigMicroPACS();
+ LoadKFactorFile((char*)KFACTORFILE);
+
+ MyGetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig, RootSC, 64, ConfigFile);
+ MyGetPrivateProfileString ( RootSC, "Dictionary", "", Temp, 64, ConfigFile);
+ if (Temp[0])
+ { VRType.AttachRTC(Temp);
+ globalPDU.AttachRTC(&VRType);
+ InitACRNemaAddressArray();
+ }
+
+ MyGetPrivateProfileString ( RootSC, "WEBReadOnly", "1", Temp, 64, ConfigFile);
+ ReadOnly = atoi(Temp);
+ MyGetPrivateProfileString ( RootSC, "WEBPush", "1", Temp, 64, ConfigFile);
+ WebPush = atoi(Temp);
+
+ sprintf(WebScriptAddress, "http://%s/cgi-bin/dgate%s", getenv("SERVER_NAME"), ex);
+ MyGetPrivateProfileString ( RootSC, "WEBScriptAddress", WebScriptAddress, WebScriptAddress, 256, ConfigFile);
+
+ sprintf(WebMAG0Address, "http://%s/mag0", getenv("SERVER_NAME"));//, ex); bcb, only 1 %s
+ MyGetPrivateProfileString ( RootSC, "WEBMAG0Address", WebMAG0Address, WebMAG0Address, 256, ConfigFile);
+
+ sprintf(WebServerFor, "127.0.0.1");
+ MyGetPrivateProfileString ( RootSC, "WebServerFor", WebServerFor, WebServerFor, 256, ConfigFile);
+ MyGetPrivateProfileString ( "webdefaults", "address", WebServerFor, WebServerFor, 256, ConfigFile);
+ strcpy(ServerCommandAddress, WebServerFor);
+
+ strcpy(WebCodeBase, WebScriptAddress); // note: WebCodeBase should include trailing slash or backslash
+ p1 = strrchr(WebCodeBase, '/');
+ if (p1) p1[0]=0;
+ p1 = strrchr(WebCodeBase, '/');
+ if (p1) p1[1]=0;
+ MyGetPrivateProfileString ( RootSC, "WebCodeBase", WebCodeBase, WebCodeBase, 256, ConfigFile);
+
+ // If no mode is specified, go to this page
+ // MyGetPrivateProfileString ( RootSC, "DefaultPage", "", DefaultPage, 256, ConfigFile);
+ *DefaultPage=0;
+ MyGetPrivateProfileString ( "DefaultPage", "source", "", buf, 512, ConfigFile);
+ MyGetPrivateProfileString ( "DefaultPage", "line0", buf, buf, 512, ConfigFile);
+ if (buf[0]) strcpy(DefaultPage, "DefaultPage");
+
+ // If this page is specified, all requests land here (effectively disabling the built-in web pages)
+ // MyGetPrivateProfileString ( RootSC, "AnyPage", "", AnyPage, 256, ConfigFile);
+ *AnyPage=0;
+ MyGetPrivateProfileString ( "AnyPage", "source", "", buf, 512, ConfigFile);
+ MyGetPrivateProfileString ( "AnyPage", "line0", buf, buf, 512, ConfigFile);
+ if (buf[0]) strcpy(AnyPage, "AnyPage");
+
+ MyGetPrivateProfileString ( "webdefaults", "port", (char *)Port, (char*)Port, 256, ConfigFile);
+
+ CGI((char *)Port, "port", (char *)Port); // allow serving any server
+ CGI(ServerCommandAddress, "address", ServerCommandAddress);
+
+ CGI(mode, "mode", ""); // web page
+ if (AnyPage[0]) strcpy(mode, AnyPage);// AnyPage redirects all requests to one page
+
+ CGI(query, "query", ""); // query for most db selectors
+ CGI(slice2, "slice", ""); // patid:sop for slice
+ CGI(series2, "series", ""); // patid:seriesuid for seriesviewer/move/delete
+ CGI(study2, "study", ""); // patid:studyuid for move/delete
+ CGI(db, "db", ""); // database to edit or list
+ CGI(lw, "lw", "0/0"); // level/window
+ CGI(source, "source", "(local)"); // source for move
+ CGI(dest, "dest", ""); // destination for move
+ CGI(key, "key", ""); // key for mark
+
+ j = 0;
+ for(i=0; i<strlen(slice2); i++) if (slice2[i]==' ') { slice[j++]='%'; slice[j++]='2'; slice[j++]='0'; } else slice[j++]=slice2[i];
+ slice[j++]=0;
+
+ j = 0;
+ for(i=0; i<strlen(series2); i++) if (series2[i]==' ') { series[j++]='%'; series[j++]='2'; series[j++]='0'; } else series[j++]=series2[i];
+ series[j++]=0;
+
+ j = 0;
+ for(i=0; i<strlen(study2); i++) if (study2[i]==' ') { study[j++]='%'; study[j++]='2'; study[j++]='0'; } else study[j++]=study2[i];
+ study[j++]=0;
+
+ MyGetPrivateProfileString ( "webdefaults", "size", "512", size, 256, ConfigFile);
+ MyGetPrivateProfileString ( "webdefaults", "dsize", "0", dsize, 256, ConfigFile);
+ MyGetPrivateProfileString ( "webdefaults", "compress", "n4", compress, 256, ConfigFile);
+ MyGetPrivateProfileString ( "webdefaults", "iconsize", "48", iconsize, 256, ConfigFile);
+ MyGetPrivateProfileString ( "webdefaults", "graphic", "bmp", graphic, 32, ConfigFile);
+ MyGetPrivateProfileString ( "webdefaults", "viewer", "seriesviewer", viewer, 128, ConfigFile);
+ MyGetPrivateProfileString ( "webdefaults", "studyviewer", "", studyviewer, 128, ConfigFile);
+
+ CGI(size, "size", size); // size of viewer in pixels or %
+ CGI(dsize, "dsize", dsize); // max size of transmitted dicom images in pixels, 0=original
+ CGI(compress,"compress", compress); // compression of transmitted dicom images to (our) web viewer
+ CGI(iconsize,"iconsize", iconsize); // size of icons in image table
+ CGI(graphic, "graphic", graphic); // style of transmitting thumbnails and slices (gif, bmp, or jpg)
+ CGI(viewer, "viewer", viewer); // mode of used viewer
+
+ CGI(patientidmatch, "patientidmatch", ""); // search strings
+ CGI(patientnamematch, "patientnamematch", "");
+ CGI(studydatematch, "studydatematch", "");
+ CGI(startdatematch, "startdatematch", "");
+
+ sprintf(extra, "port=%s&address=%s", Port, ServerCommandAddress);
+
+ if (patientidmatch[0]!=0)
+ { if (query[0]) strcat(query, " and ");
+ strcat(query, "PatientID like '%");
+ strcat(query, patientidmatch);
+ strcat(query, "%'");
+ };
+
+ if (patientnamematch[0]!=0)
+ { if (query[0]) strcat(query, " and ");
+ strcat(query, "PatientNam like '%");
+ strcat(query, patientnamematch);
+ strcat(query, "%'");
+ };
+
+ if (studydatematch[0]!=0)
+ { if (query[0]) strcat(query, " and ");
+ strcat(query, "StudyDate like '%");
+ strcat(query, studydatematch);
+ strcat(query, "%'");
+ };
+
+ if (startdatematch[0]!=0)
+ { if (query[0]) strcat(query, " and ");
+ strcat(query, "StartDate like '%");
+ strcat(query, startdatematch);
+ strcat(query, "%'");
+ };
+
+ if (stricmp(db, "dicomworklist")==0) DBE=WorkListDB;
+ else if (stricmp(db, "dicompatients")==0) DBE=PatientDB;
+ else if (stricmp(db, "dicomstudies" )==0) DBE=StudyDB;
+ else if (stricmp(db, "dicomseries" )==0) DBE=SeriesDB;
+ else if (stricmp(db, "dicomimages" )==0) DBE=ImageDB;
+ else DBE=WorkListDB;
+
+ /************************** top page **************************/
+
+ if ((strcmp(mode, "")==0 && !DefaultPage[0]) || strcmp(mode, "top")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H1>Welcome to the Conquest DICOM server - version %s</H1>", DGATE_VERSION);
+ HTML("<IMG SRC='%sconquest.jpg' ALT='Developed in the Conquest project'>", WebCodeBase);
+ HTML("<HR>");
+ HTML("<PRE>");
+ SendServerCommand("", "display_status:", console);
+ HTML("</PRE>");
+
+ HTML("<HR>");
+
+ HTML("<table>");
+ HTML("<tr>");
+ //HTML("<FORM ACTION=\"dgate%s\" METHOD=POST>", ex);
+ HTML("<FORM ACTION=\"dgate%s\">", ex);
+ HTML("<INPUT NAME=mode TYPE=HIDDEN VALUE=querypatients>");
+ HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port);
+ HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress);
+ HTML("<INPUT NAME=key TYPE=HIDDEN VALUE=%s>", key);
+ HTML("<td>List local patients");
+ HTML("<td>Patient ID: <INPUT NAME=patientidmatch TYPE=Text VALUE=>");
+ HTML("<td>Name: <INPUT NAME=patientnamematch TYPE=Text VALUE=>");
+ HTML("<td>");
+ HTML("<td><INPUT TYPE=SUBMIT VALUE=Go>");
+ HTML("</FORM>");
+ HTML("</tr>");
+
+ HTML("<tr>");
+ HTML("<FORM ACTION=\"dgate%s\">", ex);
+ HTML("<INPUT NAME=mode TYPE=HIDDEN VALUE=querystudies>");
+ HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port);
+ HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress);
+ HTML("<INPUT NAME=key TYPE=HIDDEN VALUE=%s>", key);
+ HTML("<td>List local studies");
+ HTML("<td>Patient ID: <INPUT NAME=patientidmatch TYPE=Text VALUE=>");
+ HTML("<td>Name: <INPUT NAME=patientnamematch TYPE=Text VALUE=>");
+ HTML("<td>Date: <INPUT NAME=studydatematch TYPE=Text VALUE=>");
+ HTML("<td><INPUT TYPE=SUBMIT VALUE=Go>");
+ HTML("</FORM>");
+ HTML("</tr>");
+
+ HTML("<tr>");
+ HTML("<FORM ACTION=\"dgate%s\">", ex);
+ HTML("<INPUT NAME=mode TYPE=HIDDEN VALUE=queryworklist>");
+ HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port);
+ HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress);
+ HTML("<td>List local worklist");
+ HTML("<td>Patient ID: <INPUT NAME=patientidmatch TYPE=Text VALUE=>");
+ HTML("<td>Name: <INPUT NAME=patientnamematch TYPE=Text VALUE=>");
+ HTML("<td>Date: <INPUT NAME=startdatematch TYPE=Text VALUE=>");
+ HTML("<td><INPUT TYPE=SUBMIT VALUE=Go>");
+ HTML("</FORM>");
+ HTML("</tr>");
+
+ HTML("<tr>");
+ HTML("<FORM ACTION=\"dgate%s\">", ex);
+ HTML("<td>Find ");
+ HTML("<select name=mode>");
+ HTML(" <option value='patientfinder'>Patient</option>");
+ HTML(" <option value='studyfinder'>Study</option>");
+ HTML(" <option value='seriesfinder'>Series</option>");
+ HTML("</select>");
+ HTML("<td>on server");
+ HTML("<select name=dest>");
+ SendServerCommand("", "get_amaps:<option value='%s'>%0.0s%0.0s%0.0s%s</option>", console);
+ HTML("</select>");
+ HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port);
+ HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress);
+ HTML("<INPUT NAME=source TYPE=HIDDEN VALUE=%s>", source);
+ HTML("<INPUT NAME=dest TYPE=HIDDEN VALUE=%s>", dest);
+ HTML("<INPUT NAME=key TYPE=HIDDEN VALUE=%s>", key);
+ HTML("<td>Search: <INPUT NAME=query TYPE=Text VALUE=>");
+ HTML("<td><td><INPUT TYPE=SUBMIT VALUE=Go>");
+ HTML("</FORM>");
+ HTML("</tr>");
+ HTML("</table>");
+
+ HTML("<FORM ACTION=\"dgate%s\" METHOD=POST ENCTYPE=\"multipart/form-data\">", ex);
+ HTML("<INPUT NAME=mode TYPE=HIDDEN VALUE=addlocalfile>");
+ HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port);
+ HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress);
+ HTML("Upload file to enter into server (dcm/v2/HL7/zip/7z/gz/tar): <INPUT NAME=filetoupload SIZE=40 TYPE=file VALUE=>");
+ HTML("<INPUT TYPE=SUBMIT VALUE=Go>");
+ HTML("</FORM>");
+
+ HTML("<HR>");
+ HTML("<BR><A HREF=\"dgate%s?%s&mode=showconfig\">Show server configuration</A>", ex, extra);
+ HTML("<BR><A HREF=\"dgate%s?%s&mode=showsops\">Show server accepted SOPs</A>", ex, extra);
+ HTML("<BR><A HREF=\"dgate%s?%s&mode=showdb\">Show database layout</A>", ex, extra);
+ HTML("<BR><A HREF=\"dgate%s?%s&mode=showdictionary\">Show DICOM dictionary (Long!)</A>", ex, extra);
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ /************************** configuration **************************/
+
+ if (strcmp(mode, "showconfig")==0)
+ { ReadOnly = TRUE;
+
+ HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H1>Welcome to the Conquest DICOM server - version %s</H1>", DGATE_VERSION);
+ HTML("<FORM ACTION=\"dgate%s\">", ex);
+ if (!ReadOnly) HTML("<INPUT NAME=mode TYPE=HIDDEN VALUE=updateconfig>");
+ HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port);
+ HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress);
+ HTML("<HR>");
+ HTML("<table RULES=ALL BORDER=1>");
+
+ HTML("<Caption>List of configuration parameters</caption>");
+ HTML("<TR><TD>File<TD>Parameter<TD>Value<TD>Description</TR>");
+ Tabulate("dicom.ini", "get_param:MyACRNema", "DICOM name of server", !ReadOnly);
+ Tabulate("dicom.ini", "get_param:TCPPort", "TCP/IP port where server listens", !ReadOnly);
+ Tabulate("dicom.ini", "get_param:FileNameSyntax", "Determines name for new files", !ReadOnly);
+ Tabulate("dicom.ini", "get_param:FixPhilips", "Strip leading zeros from 10 digit patient ID", !ReadOnly);
+ Tabulate("dicom.ini", "get_param:FixKodak", "Strip leading zeros from 8 digit patient ID", !ReadOnly);
+ Tabulate("dicom.ini", "get_param:IncomingCompression", "Compression mode for incoming files", !ReadOnly);
+ Tabulate("dicom.ini", "get_param:ArchiveCompression", "Compression mode for acrhived files", !ReadOnly);
+ Tabulate("dicom.ini", "get_param:MAGDevices", "Number of storage devices", !ReadOnly);
+ for (i=0; i<100; i++)
+ { sprintf(command, "get_param:MAGDevice%d", i);
+ if (!Tabulate("dicom.ini", command, "Directory where data is stored", !ReadOnly)) break;
+ }
+ for (i=0; i<10; i++)
+ { sprintf(command, "get_param:VirtualServerFor%d", i);
+ if (!Tabulate("dicom.ini", command, "Act as pass through for this server", !ReadOnly)) break;
+ }
+ for (i=0; i<100; i++)
+ { sprintf(command, "get_param:ExportConverter%d", i);
+ if (!Tabulate("dicom.ini", command, "Script applied to just saved data", !ReadOnly)) break;
+ }
+ for (i=0; i<100; i++)
+ { sprintf(command, "get_param:ImportConverter%d", i);
+ if (!Tabulate("dicom.ini", command, "Script applied to incoming images", !ReadOnly)) break;
+ }
+ Tabulate("dicom.ini", "get_param:QueryConverter0", "Script applied to queries", !ReadOnly);
+ Tabulate("dicom.ini", "get_param:WorkListQueryConverter0", "Script applied to worklist queries", !ReadOnly);
+ Tabulate("dicom.ini", "get_param:RetrieveConverter0", "Script applied to transmitted images", !ReadOnly);
+ Tabulate("dicom.ini", "get_param:RetrieveResultConverter0", "Script applied to query results", !ReadOnly);
+ Tabulate("dicom.ini", "get_param:ModalityWorkListQueryResultConverter0", "Script applied to worklist query results", !ReadOnly);
+ HTML("<TR></TR>");
+ for (i=0; i<1000; i++)
+ { sprintf(command, "get_amap:%d", i);
+ if (!Tabulate("acrnema.map", command, "Known DICOM provider")) break;
+ }
+
+ HTML("</table>");
+ if (!ReadOnly) HTML("<INPUT TYPE=SUBMIT VALUE=Update>");
+ HTML("</FORM>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "showsops")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H1>Welcome to the Conquest DICOM server - version %s</H1>", DGATE_VERSION);
+ HTML("<HR>");
+ HTML("<table RULES=ALL BORDER=1>");
+
+ HTML("<Caption>List of uids</caption>");
+ HTML("<TR><TD>File<TD>Parameter<TD>Value<TD>Description</TR>");
+ for (i=0; i<1000; i++)
+ { sprintf(command, "get_sop:%d", i);
+ if (!Tabulate("dgatesop.lst", command, "Accepted SOP class uid")) break;
+ }
+ for (i=0; i<1000; i++)
+ { sprintf(command, "get_transfer:%d", i);
+ if (!Tabulate("dgatesop.lst", command, "Accepted transfer syntax ")) break;
+ }
+ for (i=0; i<1000; i++)
+ { sprintf(command, "get_application:%d", i);
+ if (!Tabulate("dgatesop.lst", command, "Accepted application uid")) break;
+ }
+ for (i=0; i<1000; i++)
+ { sprintf(command, "get_localae:%d", i);
+ if (!Tabulate("dgatesop.lst", command, "Accepted called AE title")) break;
+ }
+ for (i=0; i<1000; i++)
+ { sprintf(command, "get_remotea:%d", i);
+ if (!Tabulate("dgatesop.lst", command, "Accepted calling AE title")) break;
+ }
+ HTML("</table>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "showdb")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H1>Welcome to the Conquest DICOM server - version %s</H1>", DGATE_VERSION);
+ HTML("<HR>");
+ HTML("<table RULES=ALL BORDER=1>");
+
+ HTML("<Caption>List of configuration parameters</caption>");
+ HTML("<TR><TD>File<TD>Parameter<TD>Value<TD>Description</TR>");
+ for (i=0; i<1000; i++)
+ { sprintf(command, "get_sqldef:PATIENT,%d", i);
+ if (!Tabulate("dicom.sql", command, "Patient database field definition")) break;
+ }
+ for (i=0; i<1000; i++)
+ { sprintf(command, "get_sqldef:STUDY,%d", i);
+ if (!Tabulate("dicom.sql", command, "Study database field definition")) break;
+ }
+ for (i=0; i<1000; i++)
+ { sprintf(command, "get_sqldef:SERIES,%d", i);
+ if (!Tabulate("dicom.sql", command, "Series database field definition")) break;
+ }
+ for (i=0; i<1000; i++)
+ { sprintf(command, "get_sqldef:IMAGE,%d", i);
+ if (!Tabulate("dicom.sql", command, "Image database field definition")) break;
+ }
+ for (i=0; i<1000; i++)
+ { sprintf(command, "get_sqldef:WORKLIST,%d", i);
+ if (!Tabulate("dicom.sql", command, "Worklist database field definition")) break;
+ }
+ HTML("</table>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "showdictionary")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H1>Welcome to the Conquest DICOM server - version %s</H1>", DGATE_VERSION);
+ HTML("<HR>");
+ HTML("<table RULES=ALL BORDER=1>");
+
+ HTML("<Caption>List of configuration parameters</caption>");
+ HTML("<TR><TD>File<TD>Parameter<TD>Value<TD>Description</TR>");
+ for (i=0; i<9000; i++)
+ { sprintf(command, "get_dic:%d", i);
+ if (!Tabulate("dgate.dic", command, "Dictionary item")) break;
+ }
+ HTML("</table>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "updateconfig")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H1>Welcome to the Conquest DICOM server - version %s</H1>", DGATE_VERSION);
+ HTML("<HR>");
+ if (!ReadOnly) HTML("Updating the configuration through the WEB interface is not yet supported");
+ else HTML("Updating the configuration through the WEB interface is not allowed");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ /************************** local browsers **************************/
+
+ if (strcmp(mode, "querypatients")==0)
+ { HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>",DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<table RULES=ALL BORDER=1>");
+ if (query[0]) HTML("<Caption>List of selected patients on local server</caption>");
+ else HTML("<Caption>List of all patients on local server</caption>");
+ HTML("<TR><TD>Patient ID<TD>Name<TD>Sex<TD>Birth date</TR>");
+
+ strcpy(command, "query:DICOMPatients|patientid,patientnam,patientsex,patientbir|");
+ strcpy(command+strlen(command), query);
+ sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=querystudies&key=%s&query=patientid+=+'%%s'>%%0.0s %%0.0s %%0.0s", ex, extra, key);
+ strcpy(command+strlen(command), "%s</A><TD>%s<TD>%s<TD>%s</TR>");
+ SendServerCommand("", command, console);
+
+ HTML("</table>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "querystudies")==0)
+ { HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<table RULES=ALL BORDER=1>");
+ if (query[0]) HTML("<Caption>List of selected studies on local server</caption>");
+ else HTML("<Caption>List of all studies on local server</caption>");
+ HTML("<TR><TD>Patient ID<TD>Name<TD>Study date<TD>Study description<TD>Study modality</TR>");
+
+ strcpy(command, "query:DICOMStudies|patientid,studyinsta,patientnam,studydate,studydescr,studymodal|");
+ strcpy(command+strlen(command), query);
+ sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=queryseries&key=%s&query=DICOMStudies.patientid+=+'%%s'+and+DICOMSeries.studyinsta+=+'%%s'>%%0.0s %%0.0s %%0.0s %%0.0s", ex, extra, key);
+ strcpy(command+strlen(command), "%s</A><TD>%0.0s %s<TD>%s<TD>%s<TD>%s");
+ if (studyviewer[0])
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=%s&study=%%s:%%s&size=%s>view%%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra, studyviewer, size);
+ if (WebPush)
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=studymover&study=%%s:%%s&source=%s&key=%s>push%%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra, source, key);
+ MyGetPrivateProfileString ( "markstudy", "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( "markstudy", "line0", buf, buf, 1000, ConfigFile);
+ if (buf[0] && key[0])
+ { MyGetPrivateProfileString ( "markstudy", "caption", "Mark", buf, 1000, ConfigFile);
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=markstudy&study=%%s:%%s&source=%s&key=%s>%s%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra, source, key, buf);
+ }
+ if (!ReadOnly)
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=studydeleter&study=%%s:%%s>delete%%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra);
+ strcpy(command+strlen(command), "</TR>");
+ SendServerCommand("", command, console);
+
+ HTML("</table>");
+
+ MyGetPrivateProfileString ( "shoppingcart", "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( "shoppingcart", "line0", buf, buf, 1000, ConfigFile);
+ if (buf[0] && key[0])
+ { MyGetPrivateProfileString ( "shoppingcart", "caption", "Shopping cart", buf, 1000, ConfigFile);
+ sprintf(command, "<A HREF=dgate%s?%s&mode=shoppingcart&key=%s>%s</A>", ex, extra, key, buf);
+ HTML("%s", command);
+ }
+
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "queryseries")==0)
+ { HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<table RULES=ALL BORDER=1>");
+ HTML("<Caption>List of series on local server</caption>");
+ HTML("<TR><TD>Patient ID<TD>Name<TD>Series date<TD>Series time<TD>Series description<TD>Modality</TR>");
+
+ strcpy(command, "query:DICOMSeries,DICOMStudies|DICOMStudies.patientid,DICOMSeries.seriesinst,DICOMStudies.patientnam,DICOMSeries.seriesdate,DICOMSeries.seriestime,DICOMSeries.seriesdesc,DICOMSeries.modality|");
+ strcpy(command+strlen(command), query);
+ strcpy(command+strlen(command), " and DICOMStudies.studyinsta=DICOMSeries.studyinsta");
+ sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=queryallimages&key=%s&query=DICOMStudies.patientid+=+'%%s'+and+DICOMSeries.seriesinst+=+'%%s'>%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s %%s %%0.0s</A>", ex, extra, key);
+ strcpy(command+strlen(command), "<TD>%s<TD>%s<TD>%s<TD>%s<TD>%s");
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=queryimages&query=DICOMStudies.patientid+=+'%%s'+and+DICOMSeries.seriesinst+=+'%%s'&size=%s>thumbs%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra, size);
+ if (viewer[0])
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=%s&series=%%s:%%s&size=%s>view%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra, viewer, size);
+ if (WebPush)
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=seriesmover&series=%%s:%%s&source=%s&key=%s>push%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra, source, key);
+ MyGetPrivateProfileString ( "markseries", "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( "markseries", "line0", buf, buf, 1000, ConfigFile);
+ if (buf[0] && key[0])
+ { MyGetPrivateProfileString ( "markseries", "caption", "Mark", buf, 1000, ConfigFile);
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=markseries&series=%%s:%%s&source=%s&key=%s>%s%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra, source, key, buf);
+ }
+ if (!ReadOnly)
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=seriesdeleter&series=%%s:%%s>delete%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra);
+ strcpy(command+strlen(command), "</TR>");
+ SendServerCommand("", command, console);
+
+ HTML("</table>");
+
+ MyGetPrivateProfileString ( "shoppingcart", "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( "shoppingcart", "line0", buf, buf, 1000, ConfigFile);
+ if (buf[0] && key[0])
+ { MyGetPrivateProfileString ( "shoppingcart", "caption", "Shopping cart", buf, 1000, ConfigFile);
+ sprintf(command, "<A HREF=dgate%s?%s&mode=shoppingcart&key=%s>%s</A>", ex, extra, key, buf);
+ HTML("%s", command);
+ }
+
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "queryimages")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<table RULES=ALL BORDER=1>");
+ HTML("<Caption>List of images with thumbnails on local server (maximal 50)</caption>");
+ HTML("<TR><TD>Patient ID<TD>Name<TD>Date<TD>Image number<TD>Slice location<TD>Icon</TR>");
+
+ strcpy(command, "query2:DICOMImages,DICOMSeries,DICOMStudies|DICOMStudies.patientid,DICOMImages.sopinstanc,DICOMStudies.patientnam,DICOMSeries.seriesdate,DICOMImages.imagenumbe,DICOMImages.slicelocat|");
+ strcpy(command+strlen(command), query);
+ strcpy(command+strlen(command), " and DICOMStudies.studyinsta=DICOMSeries.studyinsta and DICOMSeries.seriesinst=DICOMImages.seriesinst");
+ sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=sliceviewer&slice=%%s:%%s&size=%s&graphic=%s>%%0.0s %%0.0s %%0.0s %%0.0s", ex, extra, size, graphic);
+ strcpy(command+strlen(command), "%s</A><TD>%0.0s %s<TD>%s<TD>%s<TD>%s");
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=headerdump&slice=%%s:%%s %%0.0s %%0.0s %%0.0s %%0.0s>", ex, extra);
+ sprintf(command+strlen(command), "<IMG SRC=dgate%s?%s&mode=slice&slice=%%s:%%s&size=%s&graphic=%s></A></TR>", ex, extra, iconsize, graphic);
+ strcpy(command+strlen(command), "|50");
+ SendServerCommand("", command, console);
+
+ HTML("</table>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "queryallimages")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<table RULES=ALL BORDER=1>");
+ HTML("<Caption>List of images on local server (all)</caption>");
+ HTML("<TR><TD>Patient ID<TD>Name<TD>Date<TD>Image number<TD>Slice location<TD>Header</TR>");
+
+ strcpy(command, "query:DICOMImages,DICOMSeries,DICOMStudies|DICOMStudies.patientid,DICOMImages.sopinstanc,DICOMStudies.patientnam,DICOMSeries.seriesdate,DICOMImages.imagenumbe,DICOMImages.slicelocat|");
+ strcpy(command+strlen(command), query);
+ strcpy(command+strlen(command), " and DICOMStudies.studyinsta=DICOMSeries.studyinsta and DICOMSeries.seriesinst=DICOMImages.seriesinst");
+ sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=sliceviewer&slice=%%s:%%s&size=%s&graphic=%s>%%0.0s %%0.0s %%0.0s %%0.0s", ex, extra, size, graphic);
+ strcpy(command+strlen(command), "%s</A><TD>%0.0s %s<TD>%s<TD>%s<TD>%s");
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=headerdump&slice=%%s:%%s %%0.0s %%0.0s %%0.0s %%0.0s>", ex, extra);
+ strcpy(command+strlen(command), "*</A></TR>");
+ SendServerCommand("", command, console);
+
+ HTML("</table>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ /************************** remote query **************************/
+
+ if (strcmp(mode, "patientfinder")==0)
+ { HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<table RULES=ALL BORDER=1>");
+ if (query[0]) HTML("<Caption>List of selected patients on %s</caption>", dest);
+ else HTML("<Caption>List of all patients on %s</caption>", dest);
+ HTML("<TR><TD>ID<TD>Name</TR>");
+
+ sprintf(command, "patientfinder:%s|%s", dest, query);
+ sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=studyfinder&dest=%s&key=%s&query==%%0.0s%%s>", ex, extra, dest, key);
+ strcpy(command+strlen(command), "%0.0s%s</A><TD>%s");
+ SendServerCommand("", command, console);
+
+ HTML("</table>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "studyfinder")==0)
+ { HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<table RULES=ALL BORDER=1>");
+ if (query[0]) HTML("<Caption>List of selected studies on %s</caption>", dest);
+ else HTML("<Caption>List of all studies on %s</caption>", dest);
+ HTML("<TR><TD>Date<TD>Modality<TD>Name<TD>Id<TD>UID</TR>");
+
+ sprintf(command, "studyfinder:%s|%s", dest, query);
+ sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=seriesfinder&dest=%s&key=%s&query==%%0.0s%%0.0s%%0.0s%%0.0s%%s>", ex, extra, dest, key);
+ strcpy(command+strlen(command), "%s</A><TD>%s<TD>%s<TD>%s<TD>%s");
+ if (WebPush)
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=studymover&study=%%0.0s%%0.0s%%0.0s%%s:%%s&source=%s&key=%s>push</A>", ex, extra, dest, key);
+ MyGetPrivateProfileString ( "markstudy", "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( "markstudy", "line0", buf, buf, 1000, ConfigFile);
+ if (buf[0] && key[0])
+ { MyGetPrivateProfileString ( "markstudy", "caption", "Mark", buf, 1000, ConfigFile);
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=markstudy&study=%%0.0s%%0.0s%%0.0s%%s:%%s&source=%s&key=%s>%s</A>", ex, extra, dest, key, buf);
+ }
+ strcpy(command+strlen(command), "</TR>");
+ SendServerCommand("", command, console);
+
+ HTML("</table>");
+
+ MyGetPrivateProfileString ( "shoppingcart", "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( "shoppingcart", "line0", buf, buf, 1000, ConfigFile);
+ if (buf[0] && key[0])
+ { MyGetPrivateProfileString ( "shoppingcart", "caption", "Shopping cart", buf, 1000, ConfigFile);
+ sprintf(command, "<A HREF=dgate%s?%s&mode=shoppingcart&key=%s>%s</A>", ex, extra, key, buf);
+ HTML("%s", command);
+ }
+
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "seriesfinder")==0)
+ { HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<table RULES=ALL BORDER=1>");
+ if (query[0]) HTML("<Caption>List of selected series on %s</caption>", dest);
+ else HTML("<Caption>List of all series on %s</caption>", dest);
+ HTML("<TR><TD>Date<TD>Time<TD>Modality<TD>Name<TD>ID<TD>UID</TR>");
+
+ sprintf(command, "seriesfinder:%s|%s", dest, query);
+ sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=imagefinder&dest=%s&key=%s&query==%%0.0s%%0.0s%%0.0s%%0.0s%%0.0s%%0.0s%%s>%%s</A><TD>%%s<TD>%%s<TD>%%s<TD>%%s%%0.0s<TD>%%s</TR>", ex, extra, dest, key);
+ MyGetPrivateProfileString ( "markseries", "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( "markseries", "line0", buf, buf, 1000, ConfigFile);
+ if (WebPush)
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=seriesmover&series=%%0.0s%%0.0s%%0.0s%%0.0s%%s:%%0.0s%%s&study=%%0.0s%%0.0s%%0.0s%%0.0s%%s:%%s%%0.0s&source=%s&key=%s>push</A>", ex, extra, dest, key);
+ if (buf[0] && key[0])
+ { MyGetPrivateProfileString ( "markseries", "caption", "Mark", buf, 1000, ConfigFile);
+ sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=markseries&series=%%0.0s%%0.0s%%0.0s%%0.0s%%s:%%0.0s%%s&study=%%0.0s%%0.0s%%0.0s%%0.0s%%s:%%s%%0.0s&source=%s&key=%s>%s</A>", ex, extra, dest, key, buf);
+ }
+ SendServerCommand("", command, console);
+
+ HTML("</table>");
+
+ MyGetPrivateProfileString ( "shoppingcart", "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( "shoppingcart", "line0", buf, buf, 1000, ConfigFile);
+ if (buf[0] && key[0])
+ { MyGetPrivateProfileString ( "shoppingcart", "caption", "Shopping cart", buf, 1000, ConfigFile);
+ sprintf(command, "<A HREF=dgate%s?%s&mode=shoppingcart&key=%s>%s</A>", ex, extra, key, buf);
+ HTML("%s", command);
+ }
+
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "imagefinder")==0)
+ { char WADOserver[256];
+ sprintf(WADOserver, "dgate%s?%s", ex, extra);
+ MyGetPrivateProfileString ( "wadoservers", dest, WADOserver, WADOserver, 256, ConfigFile);
+
+ HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<table RULES=ALL BORDER=1>");
+ if (query[0]) HTML("<Caption>List of selected images on %s</caption>", dest);
+ else HTML("<Caption>List of all images on %s</caption>", dest);
+ HTML("<TR><TD>Sop<TD>ID<TD>Slice<TD>Location</TR>");
+
+ sprintf(command, "imagefinder:%s|%s", dest, query);
+ strcpy(command+strlen(command), "|<TR><TD>%s%0.0s<TD>%s%0.0s%0.0s<TD>%s<TD>%s</TR>");
+ sprintf(command+strlen(command), "<TD><A HREF=%s&requestType=WADO&objectUID=%%s%%0.0s%%0.0s&studyUID=%%s&seriesUID=%%s&contentType=image/gif>view (WADO)</A>", WADOserver);
+ SendServerCommand("", command, console);
+
+ HTML("</table>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ /* unused */
+ if (strcmp(mode, "dicomfind")==0)
+ { HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<FORM ACTION=\"dgate%s\">", ex);
+
+ HTML("Find ");
+ HTML("<select name=mode>");
+ HTML(" <option value='patientfinder'>Patient</option>");
+ HTML(" <option value='studyfinder'>Study</option>");
+ HTML(" <option value='seriesfinder'>Series</option>");
+ HTML("</select>");
+ HTML("on server");
+
+ HTML("<select name=dest>");
+ SendServerCommand("", "get_amaps:<option value='%s'>%0.0s%0.0s%0.0s%s</option>", console);
+ HTML("</select>");
+
+ HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port);
+ HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress);
+ HTML("<INPUT NAME=source TYPE=HIDDEN VALUE=%s>", source);
+ HTML("<INPUT NAME=dest TYPE=HIDDEN VALUE=%s>", dest);
+ HTML("Search: <INPUT NAME=query TYPE=Text VALUE=>");
+ HTML("<INPUT TYPE=SUBMIT VALUE=Go>");
+ HTML("</FORM>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ /************************** movers **************************/
+
+ if (strcmp(mode, "studymover")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<table RULES=ALL BORDER=1>");
+ HTML("<Caption>Send study: %s</caption>", study2);
+ HTML("<TR><TD>Source<TD>Destination</TR>");
+
+ for (i=0; i<1000; i++)
+ { char com[80], buf1[80];
+ sprintf(com, "get_amap:%d,%%s", i);
+ SendServerCommand("", com, 0, buf1);
+ if (buf1[0]==0) break;
+ if (strchr(buf1, '*')==NULL && strcmp(source, buf1)!=0)
+ { sprintf(command, "<TR><TD>%s<TD><A HREF=dgate%s?%s&mode=movestudy&study=%s&source=%s&dest=%s>%s</A></TR>", source, ex, extra, study, source, buf1, buf1);
+ HTML("%s", command);
+ }
+ }
+
+ if (strcmp(source, "(local)")==0)
+ { sprintf(command, "<TR><TD>(local)<TD><A HREF=dgate%s?%s&mode=zipstudy&study=%s&dum=.zip>Zip file</A></TR>", ex, extra, study2);
+ HTML("%s", command);
+ }
+
+ MyGetPrivateProfileString ( "markstudy", "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( "markstudy", "line0", buf, buf, 1000, ConfigFile);
+ if (buf[0] && key[0])
+ { MyGetPrivateProfileString ( "markstudy", "caption", "mark", buf, 1000, ConfigFile);
+ sprintf(command, "<TR><TD>%s<TD><A HREF=dgate%s?%s&mode=markstudy&study=%s&source=%s&key=%s>%s</A></TR>", source, ex, extra, study2, source, key, buf);
+ HTML("%s", command);
+ }
+
+ HTML("</table>");
+
+ MyGetPrivateProfileString ( "shoppingcart", "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( "shoppingcart", "line0", buf, buf, 1000, ConfigFile);
+ if (buf[0] && key[0])
+ { MyGetPrivateProfileString ( "shoppingcart", "caption", "Shopping cart", buf, 1000, ConfigFile);
+ sprintf(command, "<A HREF=dgate%s?%s&mode=shoppingcart&key=%s>%s</A>", ex, extra, key, buf);
+ HTML("%s", command);
+ }
+
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "seriesmover")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<table RULES=ALL BORDER=1>");
+ HTML("<Caption>Send series: %s</caption>", series2);
+ HTML("<TR><TD>Source<TD>Destination</TR>");
+
+ for (i=0; i<1000; i++)
+ { char com[80], buf1[80];
+ sprintf(com, "get_amap:%d,%%s", i);
+ SendServerCommand("", com, 0, buf1);
+ if (buf1[0]==0) break;
+ if (strchr(buf1, '*')==NULL && strcmp(source, buf1)!=0)
+ { sprintf(command, "<TR><TD>%s<TD><A HREF=dgate%s?%s&mode=moveseries&series=%s&study=%s&source=%s&dest=%s>%s</A></TR>", source, ex, extra, series, study, source, buf1, buf1);
+ HTML("%s", command);
+ }
+ }
+
+ if (strcmp(source, "(local)")==0)
+ { sprintf(command, "<TR><TD>(local)<TD><A HREF=dgate%s?%s&mode=zipseries&series=%s&dum=.zip>Zip file</A></TR>", ex, extra, series);
+ HTML("%s", command);
+ }
+
+ MyGetPrivateProfileString ( "markseries", "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( "markseries", "line0", buf, buf, 1000, ConfigFile);
+ if (buf[0] && key[0])
+ { MyGetPrivateProfileString ( "markseries", "caption", "mark", buf, 1000, ConfigFile);
+ sprintf(command, "<TR><TD>%s<TD><A HREF=dgate%s?%s&mode=markseries&series=%s&source=%s&key=%s>%s</A></TR>", source, ex, extra, series, source, key, buf);
+ HTML("%s", command);
+ }
+
+ HTML("</table>");
+
+ MyGetPrivateProfileString ( "shoppingcart", "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( "shoppingcart", "line0", buf, buf, 1000, ConfigFile);
+ if (buf[0] && key[0])
+ { MyGetPrivateProfileString ( "shoppingcart", "caption", "Shopping cart", buf, 1000, ConfigFile);
+ sprintf(command, "<A HREF=dgate%s?%s&mode=shoppingcart&key=%s>%s</A>", ex, extra, key, buf);
+ HTML("%s", command);
+ }
+
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "movestudy")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+ sprintf(command, "movestudy:%s,%s,%s", source, dest, study2);
+ SendServerCommand("", command, 0, buf);
+ HTML("%s", command);
+ HTML("<BR>");
+ HTML("Done %s", study2);
+ HTML("</BODY>");
+ exit(0);
+ }
+
+ if (strcmp(mode, "moveseries")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+ sprintf(command, "moveseries:%s,%s,%s", source, dest, series2);
+ if (study2[0])
+ { p1 = strchr(study2, ':'); if(!p1) p1 = study2; else p1++;
+ sprintf(command+strlen(command), ",%s", p1);
+ }
+ SendServerCommand("", command, 0, buf);
+ HTML("%s", command);
+ HTML("<BR>");
+ HTML("Done %s", series2);
+ HTML("</BODY>");
+ exit(0);
+ }
+
+ if (strcmp(mode, "addlocalfile")==0)
+ { HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+ HTML("</BODY>");
+ HTML("Uploaded and processed file:");
+ HTML(uploadedfile);
+ char com[512], file[512];
+ sprintf(com, "addimagefile:%s", uploadedfile);
+ strcpy(file, uploadedfile);
+ SendServerCommand("", com, 0, uploadedfile, FALSE, TRUE);
+ unlink(file);
+ exit(0);
+ };
+
+ /************************** delete **************************/
+
+ if (!ReadOnly)
+ { if (strcmp(mode, "studydeleter")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+ HTML("<Caption>Delete study: %s</caption>", study);
+
+ HTML("<FORM ACTION=\"dgate%s\">", ex);
+ HTML("<INPUT NAME=mode TYPE=HIDDEN VALUE=deletestudy>");
+ HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port);
+ HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress);
+ HTML("<INPUT NAME=study TYPE=HIDDEN VALUE='%s'>", study);
+ HTML("<INPUT TYPE=SUBMIT VALUE='Delete the study'>");
+ HTML("</FORM>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "seriesdeleter")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+ HTML("<Caption>Delete series: %s</caption>", series);
+
+ HTML("<FORM ACTION=\"dgate%s\">", ex);
+ HTML("<INPUT NAME=mode TYPE=HIDDEN VALUE=deleteseries>");
+ HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port);
+ HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress);
+ HTML("<INPUT NAME=series TYPE=HIDDEN VALUE='%s'>", series);
+ HTML("<INPUT TYPE=SUBMIT VALUE='Delete the series'>");
+ HTML("</FORM>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "deletestudy")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+ sprintf(command, "deletestudy:%s", study2);
+ SendServerCommand("", command, 0, buf);
+ HTML(command);
+ HTML("<BR>");
+ HTML("Done");
+ HTML("</BODY>");
+ exit(0);
+ }
+
+ if (strcmp(mode, "deleteseries")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+ sprintf(command, "deleteseries:%s", series2);
+ SendServerCommand("", command, 0, buf);
+ HTML(command);
+ HTML("<BR>");
+ HTML("Done");
+ HTML("</BODY>");
+ exit(0);
+ }
+ }
+
+ /************************** worklist browser and editor **************************/
+
+ if (strcmp(mode, "queryworklist")==0)
+ { HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<table RULES=ALL BORDER=1>");
+ if (query[0]) HTML("<Caption>List of selected worklist entries</caption>");
+ else HTML("<Caption>List of all worklist entries (not all fields displayed)</caption>");
+ HTML("<TR><TD>AccessionN<TD>Patient ID<TD>Name<TD>Birth date<TD>Sex<TD>Physician<TD>Description<TD>Modality<TD>Date<TD>Time</TR>");
+
+ strcpy(command, "query:dicomworklist|AccessionN,PatientID,PatientNam,PatientBir,PatientSex,ReqPhysici,ReqProcDes,Modality,StartDate,StartTime|");
+ strcpy(command+strlen(command), query);
+ sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=editrecord&db=dicomworklist&query=AccessionN+=+'%%s'>%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s %%0.0s %%0.0s %%0.0s %%0.0s", ex, extra);
+ sprintf(command+strlen(command), "%%s</A><TD>%%s<TD>%%s<TD>%%s<TD>%%s<TD>%%s<TD>%%s<TD>%%s<TD>%%s<TD>%%s<TD><A HREF=dgate%s?%s&mode=deleterecord&db=dicomworklist&query=AccessionN+=+'%%s'>Delete</A></TR>", ex, extra);
+ SendServerCommand("", command, console);
+
+ HTML("</table>");
+
+ sprintf(command, "<A HREF=dgate%s?%s&mode=addrecord&db=dicomworklist>Add worklist entry</A>", ex, extra);
+ HTML(command);
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ /************************** general purpose database editing **************************/
+
+ if (strcmp(mode, "editrecord")==0)
+ { HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ if (!DBE)
+ { HTML("<H2>File DICOM.SQL not found - please check configuration</H2>");
+ exit(0);
+ }
+
+ HTML("<FORM ACTION=\"dgate%s\">", ex);
+ if (!ReadOnly) HTML("<INPUT TYPE=HIDDEN NAME=mode VALUE=saverecord>");
+ HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port);
+ HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress);
+ HTML("<INPUT NAME=db TYPE=HIDDEN VALUE=%s>", db);
+ HTML("<INPUT NAME=query TYPE=HIDDEN VALUE=%s>", query);
+
+ HTML("<table RULES=ALL BORDER=2>");
+ HTML("<Caption>Edit %s entry</caption>", db);
+ HTML("<TR><TD>Field<TD>Value</TR>");
+
+ strcpy(command, "query2:");
+ strcat(command, db);
+ strcat(command, "|");
+ i = 0;
+ while ( TRUE )
+ { if(!DBE[i].Element) break; // end of fields
+ if (DBE[i].DICOMType!=DT_STARTSEQUENCE && DBE[i].DICOMType!=DT_ENDSEQUENCE)
+ { strcat(command, DBE[i].SQLColumn);
+ strcat(command, ",");
+ }
+ ++i;
+ }
+ command[strlen(command)-1]=0; // remove trailing ,
+
+ strcat(command, "|");
+ strcat(command, query);
+ strcat(command, "|");
+
+ i = 0;
+ while ( TRUE )
+ { if(!DBE[i].Element) break; // end of fields
+ if (DBE[i].DICOMType!=DT_STARTSEQUENCE && DBE[i].DICOMType!=DT_ENDSEQUENCE)
+ { strcat(command, "<TR><TD>");
+ strcat(command, DBE[i].SQLColumn);
+ strcat(command, "<TD><INPUT NAME=");
+ strcat(command, DBE[i].SQLColumn);
+ strcat(command, " TYPE=Text VALUE='%s'></TR>");
+ }
+ ++i;
+ };
+ strcat(command, "|1"); // max 1 record !!!!!
+
+ SendServerCommand("", command, console);
+
+ HTML("</table>");
+ if (!ReadOnly) HTML("<INPUT TYPE=SUBMIT VALUE=Save>");
+ HTML("</FORM>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "addrecord")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ if (!DBE)
+ { HTML("<H2>File DICOM.SQL not found - please check configuration</H2>");
+ exit(0);
+ }
+
+ HTML("<FORM ACTION=\"dgate%s\">", ex);
+ if (!ReadOnly) HTML("<INPUT TYPE=HIDDEN NAME=mode VALUE=saverecord>");
+ HTML("<INPUT NAME=db TYPE=HIDDEN VALUE=%s>", db);
+ HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port);
+ HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress);
+
+ HTML("<table RULES=ALL BORDER=2>");
+ sprintf(command, "<Caption>Add %s entry</caption>", db);
+ HTML(command);
+
+ HTML("<TR><TD>Field<TD>Value</TR>");
+
+ i = 0;
+ while ( TRUE )
+ { if(!DBE[i].Element) break; // end of fields
+ if (DBE[i].DICOMType!=DT_STARTSEQUENCE && DBE[i].DICOMType!=DT_ENDSEQUENCE)
+ { strcpy(command, "<TR><TD>");
+ strcat(command, DBE[i].SQLColumn);
+ strcat(command, "<TD><INPUT NAME=");
+ strcat(command, DBE[i].SQLColumn);
+ strcat(command, " TYPE=Text VALUE=''></TR>");
+ HTML(command);
+ }
+ ++i;
+ }
+
+ HTML("</table>");
+ if (!ReadOnly) HTML("<INPUT TYPE=SUBMIT VALUE=Save>");
+ HTML("</FORM>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "saverecord")==0)
+ { HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ if (!DBE)
+ { HTML("<H2>File DICOM.SQL not found - please check configuration</H2>");
+ exit(0);
+ }
+
+ if (ReadOnly || DBE!=WorkListDB)
+ { HTML("<H2>This table is readonly</H2>");
+ exit(0);
+ }
+
+ if (strlen(query))
+ { sprintf(command, "deleterecord:%s,%s", db, query);
+ SendServerCommand("", command, console);
+ sprintf(command, "Updated/added %s entry for %s", db, query);
+ HTML(command);
+ }
+ else
+ { sprintf(command, "Added new record in %s", db);
+ HTML(command);
+ };
+
+ sprintf(command, "addrecord:%s|", db);
+ i = 0;
+ while ( TRUE )
+ { if(!DBE[i].Element) break; // end of fields
+ if (DBE[i].DICOMType!=DT_STARTSEQUENCE && DBE[i].DICOMType!=DT_ENDSEQUENCE)
+ { strcat(command, DBE[i].SQLColumn);
+ strcat(command, ",");
+ }
+ ++i;
+ }
+ command[strlen(command)-1]=0; // remove trailing ,
+ strcat(command, "|");
+
+ i = 0;
+ while ( TRUE )
+ { if(!DBE[i].Element) break; // end of fields
+ if (DBE[i].DICOMType!=DT_STARTSEQUENCE && DBE[i].DICOMType!=DT_ENDSEQUENCE)
+ { strcat(command, "'");
+ CGI(buf, DBE[i].SQLColumn, "");
+ strcat(command, buf);
+ strcat(command, "', ");
+ }
+ ++i;
+ }
+ command[strlen(command)-2]=0; // remove trailing , and space
+
+ SendServerCommand("", command, console);
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "deleterecord")==0)
+ { HTML("Content-type: text/html\nCache-Control: no-cache\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ if (ReadOnly || DBE!=WorkListDB)
+ { HTML("<H2>This table is readonly</H2>");
+ exit(0);
+ }
+
+ sprintf(command, "deleterecord:%s,%s", db, query);
+ SendServerCommand("", command, console);
+ HTML("Deleted record entry for ");
+ HTML(db);
+ HTML("Where ");
+ HTML(query);
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ /************************** viewers **************************/
+
+ /* page with one slice */
+ if (strcmp(mode, "sliceviewer")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<A HREF=dgate%s?%s&mode=headerdump&slice=%s>", ex, extra, slice);
+ if (size[0])
+ HTML("<IMG SRC=dgate%s?%s&mode=slice&slice=%s&size=%s&graphic=%s&lw=%s HEIGHT=%s>", ex, extra, slice, dsize, graphic, lw, size);
+ else
+ HTML("<IMG SRC=dgate%s?%s&mode=slice&slice=%s&size=%s&graphic=%s&lw=%s>", ex, extra, slice, dsize, graphic, lw);
+ HTML("</A>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ if (strcmp(mode, "headerdump")==0)
+ { HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+ HTML("<BR>Header dump of DICOM object:<BR>");
+ HTML("<PRE>");
+
+ sprintf(command, "dump_header:%s", slice2);
+ SendServerCommand("", command, console, NULL, FALSE);
+
+ HTML("</PRE>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ /* just generates the bitmap */
+ if (strcmp(mode, "slice")==0)
+ { sprintf(command, "convert_to_%s:%s,%s,cgi,%s", graphic, slice2, size, lw); // 1.4.16i: use size instead of dsize
+ SendServerCommand("", command, console, NULL, FALSE);
+ exit(0);
+ };
+
+ /* transmits the image contents in dicom format */
+ if (strcmp(mode, "dicom")==0)
+ { sprintf(command, "convert_to_dicom:%s,%s,%s", slice2, dsize, compress);
+ SendServerCommand("", command, console, NULL, FALSE);
+ exit(0);
+ };
+
+ /* transmits the series in zipped dicom format */
+ if (strcmp(mode, "zipseries")==0)
+ { char *p = strchr(series2, ':');
+ if (p)
+ { *p++ = ',';
+ memmove(p, p-1, strlen(p-1)+1);
+ *p++ = ',';
+ }
+
+ sprintf(command, "export:%s,,cgi,call zip.cq", series2);
+ SendServerCommand("", command, console, NULL, FALSE);
+ exit(0);
+ };
+
+ /* transmits the study in zipped dicom format */
+ if (strcmp(mode, "zipstudy")==0)
+ { char *p = strchr(study2, ':');
+ if (p) *p = ',';
+
+ sprintf(command, "export:%s,,,cgi,call zip.cq", study2);
+ SendServerCommand("", command, console, NULL, FALSE);
+ exit(0);
+ };
+
+ /* transmits the image list with urls in text format */
+ if (strcmp(mode, "imagelisturls")==0)
+ { char *p;
+
+ p = strchr(series2, ':');
+ if (p) *p = '|';
+
+ sprintf(command, "imagelister:local|%s|:%s?%s&mode=dicom&slice=%%s:%%s&dsize=%s&compress=%s&dum=.dcm|cgi", series2, WebScriptAddress, extra, dsize, compress);
+ SendServerCommand("", command, console, NULL, FALSE);
+ exit(0);
+ };
+
+ /* transmits the image list with http references in text format */
+ if (strcmp(mode, "imagelisthttp")==0)
+ { char *p;
+
+ p = strchr(series2, ':');
+ if (p) *p = '|';
+
+ sprintf(command, "imagelister:local|%s|@%s/%%0.0s%%s*|cgi", series2, WebMAG0Address);
+ SendServerCommand("", command, console, NULL, FALSE);
+ exit(0);
+ };
+
+ /* transmits the image list with filenames in text format */
+ if (strcmp(mode, "imagelistfiles")==0)
+ { char *p;
+
+ p = strchr(series2, ':');
+ if (p) *p = '|';
+
+ sprintf(command, "imagelister:local|%s|%%s|cgi", series2);// %% warning, bcb -> ok but wrong change ;->>> mvh
+// sprintf(command, "imagelister:local|%s|%%s|cgi", series2, WebMAG0Address);
+ SendServerCommand("", command, console, NULL, FALSE);
+ exit(0);
+ };
+
+ /* k-pacs viewer in an OCX; internet explorer only */
+ if (strcmp(mode, "seriesviewer")==0)
+ { char *p;
+
+ if (size[0]==0) strcpy(size, "80%25%25");
+
+ HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+
+ HTML("<OBJECT");
+ HTML(" classid=\"clsid:0AA480F2-78EB-4A31-B4C8-F981C5004BBB\"");
+ HTML(" codebase=\"%sActiveFormProj1.ocx\"", WebCodeBase);
+ HTML(" width=%s", size);
+ HTML(" height=%s", size);
+ HTML(" align=center");
+ HTML(" hspace=0");
+ HTML(" vspace=0");
+ HTML(">");
+ HTML("<PARAM name=DCMFilelist value=");
+
+ p = strchr(series2, ':');
+ if (p) *p = '|';
+ sprintf(command, "imagelister:local|%s|:%s?%s&mode=dicom&slice=%%s:%%s&dsize=%s&compress=%s*", series2, WebScriptAddress, extra, dsize, compress);
+ SendServerCommand("", command, console);
+
+ HTML(">");
+ HTML("</OBJECT>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ /* k-pacs viewer in an OCX; internet explorer only; data access through http served image files */
+ if (strcmp(mode, "seriesviewer2")==0)
+ { char wwwserveraddress[512] = "http://";
+ strcat(wwwserveraddress, getenv("SERVER_NAME"));
+
+ if (size[0]==0) strcpy(size, "80%25%25");
+
+ HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+ HTML("<OBJECT");
+ HTML(" classid=\"clsid:0AA480F2-78EB-4A31-B4C8-F981C5004BBB\"");
+ HTML(" codebase=\"%sActiveFormProj1.ocx\"", WebCodeBase);
+ HTML(" width=%s", size);
+ HTML(" height=%s", size);
+ HTML(" align=center");
+ HTML(" hspace=0");
+ HTML(" vspace=0");
+ HTML(">");
+ HTML("<PARAM name=DCMFilelist value=");
+
+ char *p = strchr(series2, ':');
+ if (p) *p = '|';
+
+ if (memcmp(wwwserveraddress, "file", 4)==0)
+ sprintf(command, "imagelister:local|%s", series2);
+ else
+ sprintf(command, "imagelister:local|%s|@%s/%%0.0s%%s*", series2, WebMAG0Address);
+
+ SendServerCommand("", command, console);
+
+ HTML(">");
+ HTML("</OBJECT>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ /* no viewer */
+ if (strcmp(mode, "noviewer")==0)
+ { //char *p;
+
+ HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+ HTML("<HR>");
+ HTML("<H2>No viewer is installed</H2>");
+ HTML("</OBJECT>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ /* The Japanese java-based viewer; requires some modifications to work */
+ if (strcmp(mode, "aiviewer")==0)
+ { char *p;
+
+ HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s with AiViewer</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s with AiViewer</H2>", DGATE_VERSION);
+
+ HTML("<APPLET");
+ HTML(" CODEBASE = '%sdicomviewer100'", WebCodeBase);
+ HTML(" CODE = 'dicomviewer.Viewer.class'");
+ HTML(" NAME = 'Viewer.java'");
+ HTML(" WIDTH = '100%%'");
+ HTML(" HEIGHT = '90%%'");
+ HTML(" HSPACE = 0");
+ HTML(" VSPACE = 0");
+ HTML(" ALIGN = middle >");
+ HTML("<PARAM NAME = tmpSize VALUE = 1>");
+ HTML("<PARAM NAME = NUM VALUE = 0>");
+ HTML("<PARAM NAME = currentNo VALUE = 0>");
+ HTML("<PARAM NAME = dicURL VALUE = '%sdicomviewer100/Dicom.dic'>", WebCodeBase);
+ HTML("<PARAM NAME = imgURL0 VALUE = ");
+
+ p = strchr(series2, ':');
+ if (p) *p = '|';
+ sprintf(command, "imagelister:local|%s|:%s?%s&mode=dicom&slice=%%s:%%s&dsize=%s&compress=%s*", series2, WebScriptAddress, extra, dsize, "un");
+ SendServerCommand("", command, console);
+
+ HTML(">");
+
+ HTML("</APPLET>");
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ /* very simple jave-script based viewer with server side processing */
+ if (strcmp(mode, "serversideviewer")==0)
+ { char *p;
+
+ p = strchr(series2, ':');
+ if (p) *p = '|';
+
+ if (size[0]==0) strcpy(size, "80%25%25");
+
+ HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s server side viewer</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s server side viewer</H2>", DGATE_VERSION);
+
+ HTML("<SCRIPT language=JavaScript>");
+ char s[] = "var frames, nframes ='";
+ write(console, s, strlen(s));
+ sprintf(command, "imagelister:local|%s|$%%04d", series2);
+ SendServerCommand("", command, console);
+ HTML("';");
+ HTML("function load()");
+ HTML("{ document.images[0].src = 'dgate%s?%s&mode=slice'+", ex, extra);
+ HTML(" '&graphic=' + document.forms[0].graphic.value +");
+ HTML(" '&slice=' + document.forms[0].slice.value +");
+ HTML(" '&dsize=%s' +", dsize);
+ HTML(" '&lw=' + document.forms[0].level.value + '/' + document.forms[0].window.value + '/' + document.forms[0].frame.value;");
+ HTML(" frames = parseInt(nframes.slice(document.forms[0].slice.selectedIndex*4, document.forms[0].slice.selectedIndex*4+4), 10);");
+ HTML(" if (frames < 2) document.forms[0].frame.style.visibility = 'hidden'; else document.forms[0].frame.style.visibility = 'visible';");
+ HTML(" if (frames < 2) document.forms[0].nframe.style.visibility = 'hidden'; else document.forms[0].nframe.style.visibility = 'visible';");
+ HTML(" if (frames < 2) document.forms[0].pframe.style.visibility = 'hidden'; else document.forms[0].pframe.style.visibility = 'visible';");
+ HTML("}");
+ HTML("function nextslice()");
+ HTML("{ if (document.forms[0].slice.selectedIndex == document.forms[0].slice.length-1) document.forms[0].slice.selectedIndex = 0; else document.forms[0].slice.selectedIndex = document.forms[0].slice.selectedIndex + 1; load()");
+ HTML("}");
+ HTML("function nextframe()");
+ HTML("{ if (parseInt(document.forms[0].frame.value, 10) == frames-1) document.forms[0].frame.value = 0; else document.forms[0].frame.value = parseInt(document.forms[0].frame.value, 10)+1; load()");
+ HTML("}");
+ HTML("function prevframe()");
+ HTML("{ document.forms[0].frame.value = parseInt(document.forms[0].frame.value, 10)-1; if (document.forms[0].frame.value<0) document.forms[0].frame.value = 0; load()");
+ HTML("}");
+ HTML("</SCRIPT>");
+
+ HTML("<IMG SRC=loading.jpg BORDER=0 HEIGHT=%s>", size);
+
+ HTML("<FORM>");
+ HTML("Slice: ");
+ HTML(" <select name=slice onchange=load()>");
+
+ sprintf(command, "imagelister:local|%s|:<option value=%%s:%%s>%%s</option>", series2);
+ SendServerCommand("", command, console);
+
+ HTML(" </select>");
+ HTML(" <INPUT TYPE=BUTTON VALUE='>' onclick=nextslice() >");
+
+ HTML("Level:");
+ HTML(" <INPUT name=level size=4 onchange=load() >");
+ HTML("Window:");
+ HTML(" <INPUT name=window size=4 onchange=load() >");
+ HTML("Frame:");
+ HTML(" <INPUT name=pframe TYPE=BUTTON VALUE='<' onclick=prevframe() >");
+ HTML(" <INPUT name=frame size=3 onchange=load() value=0>");
+ HTML(" <INPUT name=nframe TYPE=BUTTON VALUE='>' onclick=nextframe() >");
+ HTML("Color:");
+ HTML(" <select name=graphic onchange=load()>");
+ if (strcmp(graphic, "bmp")==0)
+ { HTML(" <option value=bmp>yes</option>");
+ HTML(" <option value=gif>no</option>");
+ HTML(" <option value=jpg>jpg</option>");
+ }
+ else if (strcmp(graphic, "gif")==0)
+ { HTML(" <option value=gif>no</option>");
+ HTML(" <option value=bmp>yes</option>");
+ HTML(" <option value=jpg>jpg</option>");
+ }
+ else if (strcmp(graphic, "jpg")==0)
+ { HTML(" <option value=jpg>jpg</option>");
+ HTML(" <option value=bmp>yes</option>");
+ HTML(" <option value=gif>no</option>");
+ }
+ HTML(" </select>");
+ HTML(" <INPUT TYPE=BUTTON VALUE=load onclick=load() >");
+ HTML("</FORM>");
+
+ HTML("<SCRIPT language=JavaScript>");
+ HTML(" document.onload=load()");
+ HTML("</SCRIPT>");
+
+ HTML("</BODY>");
+ exit(0);
+ };
+
+ /************************** general purpose web scripting **************************/
+
+/*
+This is a general purpose web script processor; it can be used to create any web page, not just viewers.
+
+This is a sample from dicom.ini:
+
+[flexviewer]
+line0 = <HEAD><TITLE>Conquest DICOM server - version %version% and %windowname%</TITLE></HEAD>
+line1 = <BODY BGCOLOR='CFDFCF'>
+line2 = <H2>Conquest DICOM server - version %version% and AiViewer v1.00</H2>
+line3 = <APPLET CODEBASE=%webcodebase%dicomviewer100 CODE='dicomviewer.Viewer.class'
+line4 = NAME='Viewer.java' WIDTH='100%' HEIGHT='90%' HSPACE=0 VSPACE=0 ALIGN=middle >
+line5 = <PARAM NAME = tmpSize VALUE = 10>
+line6 = <PARAM NAME = NUM VALUE = 0>
+line7 = <PARAM NAME = currentNo VALUE = 0>
+line8 = <PARAM NAME = dicURL VALUE = '%webcodebase%dicomviewer100/Dicom.dic'>
+line9 = <PARAM NAME = imgURL0 VALUE =
+line10 = --imagelister:local|%patid%|%seruid%|:%webscriptadress%?%extra%&mode=dicom&slice=%s:%s&compress=un*
+line11 = >
+line12 = </APPLET>
+line13 = </BODY>
+# this is the default; the variable can be passed in the url
+windowname = AiViewer V1.00
+
+[flexviewer2]
+source = flexviewer2.cq
+windowname = AiViewer V1.00
+
+;[AnyPage]
+;source = anypage.cq
+
+;[DefaultPage]
+;source = ecrf\*.lua
+*/
+
+ /* check mode of web page against dicom.ini sections */
+ MyGetPrivateProfileString ( mode, "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( mode, "line0", buf, buf, 1000, ConfigFile);
+ if (buf[0]==0)
+ { strcpy(mode, DefaultPage);
+ MyGetPrivateProfileString ( mode, "source", "", buf, 1000, ConfigFile);
+ MyGetPrivateProfileString ( mode, "line0", buf, buf, 1000, ConfigFile);
+ }
+
+ /* if source contains a * substitute the mode */
+ char *p = strchr(buf, '*');
+ if (p)
+ { char tmp[256];
+ *p=0;
+ CGI(tmp, "mode", "");
+ strcat(tmp, p+1);
+ strcat(buf, tmp);
+ }
+
+ if (buf[0])
+ { char string[1000], temp[1000], server[1000], patid[66], patid2[200], seruid[66], studyuid[66], sopuid[66], chunk[8192];
+ FILE *f=NULL;
+
+ /* create several variables useful for scripting */
+
+ sprintf(server, "%s?%s", WebScriptAddress, extra);
+
+ patid[0] = seruid[0] = studyuid[0] = sopuid[0] = 0;
+
+ if (study2[0])
+ { strcpy(temp, study2);
+ p = strchr(temp, ':');
+ if (p)
+ { *p = 0;
+ strcpy(patid2, temp);
+ *p = '|';
+ strcpy(studyuid, p+1);
+ }
+
+ strcpy(temp, study);
+ p = strchr(temp, ':');
+ if (p)
+ { *p = 0;
+ strcpy(patid, temp);
+ }
+ }
+
+ if (series2[0])
+ { strcpy(temp, series2);
+ p = strchr(temp, ':');
+ if (p)
+ { *p = 0;
+ strcpy(patid2, temp);
+ *p = '|';
+ strcpy(seruid, p+1);
+ }
+
+ strcpy(temp, series);
+ p = strchr(temp, ':');
+ if (p)
+ { *p = 0;
+ strcpy(patid, temp);
+ }
+ }
+
+ if (slice2[0])
+ { strcpy(temp, slice2);
+ p = strchr(temp, ':');
+ if (p)
+ { *p = 0;
+ strcpy(patid2, temp);
+ *p = '|';
+ strcpy(sopuid, p+1);
+ }
+
+ strcpy(temp, slice);
+ p = strchr(temp, ':');
+ if (p)
+ { *p = 0;
+ strcpy(patid, temp);
+ }
+ }
+
+ /* contents may come from file (lua extension runs lua script) or from dicom.ini */
+ MyGetPrivateProfileString ( mode, "source", buf, temp, 1000, ConfigFile);
+ strcpy(temp, buf);
+ if (strcmp(temp+strlen(temp)-4, ".lua")==0)
+ { MyGetPrivateProfileString ( mode, "header", "", buf, 1000, ConfigFile);
+ while ((p = strstr(buf, "\\"))) p[0]='\n';
+ if (buf[0]) HTML(buf);
+
+ struct scriptdata sd1 = {&globalPDU, NULL, NULL, -1, NULL, NULL, NULL, NULL, NULL, 0, 0};
+ char script[512]; int i, n;
+ strcpy(script, "dofile('");
+ for (i=0, n=8; i<strlen(temp); i++)
+ { if (temp[i]=='\\')
+ { script[n++] = '\\';
+ script[n++] = '\\';
+ }
+ else
+ { script[n++] = temp[i];
+ }
+ }
+ script[n++] = 0;
+ strcat(script, "')");
+ OperatorConsole.On();
+
+ lua_setvar(&globalPDU, "query_string", getenv( "QUERY_STRING"));
+ lua_setvar(&globalPDU, "server_name", getenv( "SERVER_NAME" ));
+ lua_setvar(&globalPDU, "script_name", getenv( "SCRIPT_NAME" ));
+ lua_setvar(&globalPDU, "path_translated", getenv( "PATH_TRANSLATED" ));
+ lua_setvar(&globalPDU, "port", (char *)Port);
+ lua_setvar(&globalPDU, "address", ServerCommandAddress);
+ lua_setvar(&globalPDU, "webcodebase", WebCodeBase);
+ lua_setvar(&globalPDU, "webscriptadress", WebScriptAddress);
+ lua_setvar(&globalPDU, "webscriptaddress",WebScriptAddress); // was misspelled
+ lua_setvar(&globalPDU, "extra", extra);
+ lua_setvar(&globalPDU, "version", DGATE_VERSION);
+ lua_setvar(&globalPDU, "mode", mode);
+ lua_setvar(&globalPDU, "uploadedfile", uploadedfile);
+
+ lua_setvar(&globalPDU, "series", series);
+ lua_setvar(&globalPDU, "series2", series2);
+ lua_setvar(&globalPDU, "slice", slice);
+ lua_setvar(&globalPDU, "slice2", slice2);
+ lua_setvar(&globalPDU, "study", study);
+ lua_setvar(&globalPDU, "study2", study2);
+ lua_setvar(&globalPDU, "patid", patid);
+ lua_setvar(&globalPDU, "patid2", patid2);
+ lua_setvar(&globalPDU, "seruid", seruid);
+ lua_setvar(&globalPDU, "studyuid", studyuid);
+ lua_setvar(&globalPDU, "sopuid", sopuid);
+
+ lua_setvar(&globalPDU, "size", size);
+ lua_setvar(&globalPDU, "dsize", dsize);
+ lua_setvar(&globalPDU, "compress", compress);
+ lua_setvar(&globalPDU, "iconsize", iconsize);
+ lua_setvar(&globalPDU, "graphic", graphic);
+ lua_setvar(&globalPDU, "viewer", viewer);
+ lua_setvar(&globalPDU, "lw", lw);
+ lua_setvar(&globalPDU, "query", query);
+ lua_setvar(&globalPDU, "db", db);
+ lua_setvar(&globalPDU, "source", source);
+ lua_setvar(&globalPDU, "dest", dest);
+ lua_setvar(&globalPDU, "patientidmatch", patientidmatch);
+ lua_setvar(&globalPDU, "patientnamematch",patientnamematch);
+ lua_setvar(&globalPDU, "studydatematch", studydatematch);
+ lua_setvar(&globalPDU, "startdatematch", startdatematch);
+
+ do_lua(&(globalPDU.L), script, &sd1);
+
+ exit(0);
+ }
+
+ if (temp[0]) f = fopen(temp, "rt");
+
+ MyGetPrivateProfileString ( mode, "header", "Content-type: text/html\n", temp, 1000, ConfigFile);
+ while ((p = strstr(temp, "\\"))) p[0]='\n';
+ HTML(temp);
+
+ int inlua=0;
+
+ for (i=0; i<10000; i++)
+ { if (f)
+ { if (fgets(string, sizeof(string), f) == NULL)
+ break;
+ if (!inlua && string[strlen(string)-1]=='\n') string[strlen(string)-1]=0;
+ }
+ else
+ { sprintf(temp, "line%d", i);
+ MyGetPrivateProfileString ( mode, temp, "", string, 1000, ConfigFile);
+ if (string[0]==0) break;
+ }
+
+ if (inlua)
+ { char *p = strstr(string, "?>");
+ if (p)
+ { *p=0;
+ strcat(chunk, string);
+ inlua=0;
+ struct scriptdata sd1 = {&globalPDU, NULL, NULL, -1, NULL, NULL, NULL, NULL, NULL, 0, 0};
+
+ lua_setvar(&globalPDU, "query_string", getenv( "QUERY_STRING"));
+ lua_setvar(&globalPDU, "server_name", getenv( "SERVER_NAME" ));
+ lua_setvar(&globalPDU, "script_name", getenv( "SCRIPT_NAME" ));
+ lua_setvar(&globalPDU, "path_translated", getenv( "PATH_TRANSLATED" ));
+ lua_setvar(&globalPDU, "port", (char *)Port);
+ lua_setvar(&globalPDU, "address", ServerCommandAddress);
+ lua_setvar(&globalPDU, "webcodebase", WebCodeBase);
+ lua_setvar(&globalPDU, "webscriptadress", WebScriptAddress);
+ lua_setvar(&globalPDU, "extra", extra);
+ lua_setvar(&globalPDU, "version", DGATE_VERSION);
+ lua_setvar(&globalPDU, "mode", mode);
+ lua_setvar(&globalPDU, "uploadedfile", uploadedfile);
+
+ lua_setvar(&globalPDU, "series", series);
+ lua_setvar(&globalPDU, "series2", series2);
+ lua_setvar(&globalPDU, "slice", slice);
+ lua_setvar(&globalPDU, "slice2", slice2);
+ lua_setvar(&globalPDU, "study", study);
+ lua_setvar(&globalPDU, "study2", study2);
+ lua_setvar(&globalPDU, "patid", patid);
+ lua_setvar(&globalPDU, "patid2", patid2);
+ lua_setvar(&globalPDU, "seruid", seruid);
+ lua_setvar(&globalPDU, "studyuid", studyuid);
+ lua_setvar(&globalPDU, "sopuid", sopuid);
+
+ lua_setvar(&globalPDU, "size", size);
+ lua_setvar(&globalPDU, "dsize", dsize);
+ lua_setvar(&globalPDU, "compress", compress);
+ lua_setvar(&globalPDU, "iconsize", iconsize);
+ lua_setvar(&globalPDU, "graphic", graphic);
+ lua_setvar(&globalPDU, "viewer", viewer);
+ lua_setvar(&globalPDU, "lw", lw);
+ lua_setvar(&globalPDU, "query", query);
+ lua_setvar(&globalPDU, "db", db);
+ lua_setvar(&globalPDU, "source", source);
+ lua_setvar(&globalPDU, "dest", dest);
+ lua_setvar(&globalPDU, "patientidmatch", patientidmatch);
+ lua_setvar(&globalPDU, "patientnamematch",patientnamematch);
+ lua_setvar(&globalPDU, "studydatematch", studydatematch);
+ lua_setvar(&globalPDU, "startdatematch", startdatematch);
+
+ do_lua(&(globalPDU.L), chunk, &sd1);
+ }
+ else
+ strcat(chunk, string);
+ }
+
+ /* fill in predefined scripting variables */
+
+ replace(string, "%query_string%", getenv( "QUERY_STRING" ));
+ replace(string, "%server_name%", getenv( "SERVER_NAME" ));
+ replace(string, "%script_name%", getenv( "SCRIPT_NAME" ));
+ replace(string, "%path_translated%", getenv( "PATH_TRANSLATED" ));
+ replace(string, "%uploadedfile%", uploadedfile);
+
+ replace(string, "%port%", (char *)Port);
+ replace(string, "%address%", ServerCommandAddress);
+ replace(string, "%webcodebase%", WebCodeBase);
+ replace(string, "%webscriptadress%", WebScriptAddress);
+ replace(string, "%extra%", extra);
+ replace(string, "%server%", server);
+ replace(string, "%version%", DGATE_VERSION);
+ replace(string, "%mode%", mode);
+
+ replace(string, "%series%", series2); // unprocessed
+ replace(string, "%series2%", series); // replaced spaces by %20
+ replace(string, "%slice%", slice2); // unprocessed
+ replace(string, "%slice2%", slice); // replaced spaces by %20
+ replace(string, "%study%", study2); // unprocessed
+ replace(string, "%study2%", study); // replaced spaces by %20
+ replace(string, "%patid%", patid2); // unprocessed
+ replace(string, "%patid2%", patid); // replaced spaces by %20
+ replace(string, "%seruid%", seruid);
+ replace(string, "%studyuid%", studyuid);
+ replace(string, "%sopuid%", sopuid);
+
+ replace(string, "%size%", size);
+ replace(string, "%dsize%", dsize);
+ replace(string, "%compress%", compress);
+ replace(string, "%iconsize%", iconsize);
+ replace(string, "%graphic%", graphic);
+ replace(string, "%viewer%", viewer);
+ replace(string, "%lw%", lw);
+
+ replace(string, "%query%", query);
+ replace(string, "%db%", db);
+ replace(string, "%source%", source);
+ replace(string, "%dest%", dest);
+ replace(string, "%patientidmatch%", patientidmatch);
+ replace(string, "%patientnamematch%",patientnamematch);
+ replace(string, "%studydatematch%", studydatematch);
+ replace(string, "%startdatematch%", startdatematch);
+
+ /* this code will substitute any other %var% with a cgi variable
+ with a default given in section for this server mode in dicom.ini
+
+ or substitute ... with the string result of a lua expression
+ <%= .... %>
+ */
+
+ char *p = strstr(string, "<%=");
+ if (p)
+ { char *p2 = strstr(string, "%>");
+ char script[1000];
+ *p=0;
+ *p2=0;
+ struct scriptdata sd1 = {&globalPDU, NULL, NULL, -1, NULL, NULL, NULL, NULL, NULL, 0, 0};
+ strcpy(script, "return ");
+ strcat(script, p+3);
+ HTML("%s", string);
+ HTML("%s", do_lua(&(globalPDU.L), script, &sd1));
+ HTML("%s", p2+2);
+ string[0] = '#';
+ }
+ else
+ { char *p2 = strchr(string, '%');
+ if (p2)
+ { char *q = strchr(p2+1, '%');
+ if (q && q!=p2+1)
+ { char var[512], val[512], var2[512];
+ *q=0;
+ strcpy(var, p2+1);
+ *q='%';;
+ strcpy(var2, "%");
+ strcat(var2, var);
+ strcat(var2, "%");
+
+ MyGetPrivateProfileString ( mode, var, var2, val, 512, ConfigFile);
+ CGI(val, var, val);
+ replace(string, var2, val);
+ }
+ }
+ }
+
+ /* runs: #comment, --servercommand, <?lua .... ?> as lua, or straight HTML output */
+ if (!inlua && string[0]=='#') strcpy(string, "");
+ else if (!inlua && string[0]=='-' && string[1]=='-') SendServerCommand("", string+2, console);
+ else if (!inlua && (p=strstr(string, "<?lua"))) {*p=0; HTML("%s", string); inlua=1; strcpy(chunk, p+5); strcat(chunk, "\n");}
+ else if (!inlua) HTML("%s", string);
+ };
+
+ if (f) fclose(f);
+ exit(0);
+ };
+
+ exit(0);
+}
+
+/* Dicom web viewer works as follows:
+
+client -> webserver url http://127.0.0.1/scripts/dgate.exe?mode=seriesviewer&series=...
+webserver -> dicomserver query imagelister:local|.....
+client <- webserver <- dicomserver query results (to build list of urls of dicom slices)
+client <- webserver activex control http://127.0.0.1/ActiveFormProj1.ocx
+
+Then for each slice that is required:
+
+control -> webserver url of slice http://127.0.0.1/scripts/dgate.exe?mode=dicom&slice=......
+webserver -> dicomserver dicom request convert_to_dicom:....
+control <- webserver <- dicomserver dicom data
+
+*/
+
+static BOOL DgateWADO(char *query_string, char *ext)
+{ UNUSED_ARGUMENT(query_string);
+ UNUSED_ARGUMENT(ext);
+
+ char requestType[256];
+ CGI(requestType, "requestType", ""); // is this a WADO request?
+ if (strcmp(requestType, "WADO")!=0) return FALSE;
+
+ char studyUID[256];
+ CGI(studyUID, "studyUID", "");
+
+ char seriesUID[256];
+ CGI(seriesUID, "seriesUID", "");
+
+ char objectUID[256];
+ CGI(objectUID, "objectUID", "");
+
+ char contentType[256];
+ CGI(contentType, "contentType", "");
+
+ char rows[256];
+ CGI(rows, "rows", "");
+
+ char columns[256];
+ CGI(columns, "columns", "");
+
+ char region[256];
+ CGI(region, "region", "");
+ for (unsigned int i=0; i<strlen(region); i++) if (region[i]==',') region[i] = '/';
+
+ char windowCenter[256];
+ CGI(windowCenter, "windowCenter", "");
+
+ char windowWidth[256];
+ CGI(windowWidth, "windowWidth", "");
+
+ char frameNumber[256];
+ CGI(frameNumber, "frameNumber", "");
+
+ char transferSyntax[256];
+ CGI(transferSyntax, "transferSyntax", "");
+
+ char anonymize[256];
+ CGI(anonymize, "anonymize", "");
+
+ char annotation[256];
+ CGI(annotation, "annotation", "");
+ for (unsigned int i=0; i<strlen(annotation); i++) if (annotation[i]==',') annotation[i] = '/';
+
+ char imageQuality[256];
+ CGI(imageQuality, "imageQuality", "");
+
+ char charset[256];
+ CGI(charset, "charset", ""); // ignored for now
+
+ char presentationUID[256];
+ CGI(presentationUID, "presentationUID", ""); // ignored for now
+
+ char bridge[256];
+ MyGetPrivateProfileString ( "wadoservers", "bridge", "", bridge, 256, ConfigFile);
+ CGI(bridge, "bridge", bridge);
+
+ console = fileno(stdout);
+#ifdef WIN32
+ setmode(console, O_BINARY);
+#endif
+
+ ConfigMicroPACS();
+ LoadKFactorFile((char*)KFACTORFILE);
+
+ char RootSC[256];
+ MyGetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig, RootSC, 64, ConfigFile);
+
+ char WebServerFor[256];
+ sprintf(WebServerFor, "127.0.0.1");
+ MyGetPrivateProfileString ( RootSC, "WebServerFor", WebServerFor, WebServerFor, 256, ConfigFile);
+ MyGetPrivateProfileString ( "webdefaults", "address", WebServerFor, WebServerFor, 256, ConfigFile);
+ strcpy(ServerCommandAddress, WebServerFor);
+
+ char obj[256];
+ sprintf(obj, "%s\\%s\\%s", studyUID, seriesUID, objectUID);
+
+ char lwfq[256];
+ sprintf(lwfq, "%d/%d/%d/%d", atoi(windowCenter), atoi(windowWidth)/2, atoi(frameNumber), atoi(imageQuality));
+
+ char size[256];
+ sprintf(size, "%d/%d", atoi(rows), atoi(columns));
+
+ char command[512];
+ sprintf(command, "wadorequest:%s,%s,%s,%s,%s,%s,%s,%s,%s", obj, lwfq, size, region, contentType, transferSyntax, anonymize, annotation, bridge);
+
+#if 1
+ SendServerCommand("", command, console, NULL, FALSE);
+#else
+ HTML("Content-type: text/html\n");
+ HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", DGATE_VERSION);
+ HTML("<BODY BGCOLOR='CFDFCF'>");
+ HTML("<H2>Conquest DICOM server - version %s</H2>", DGATE_VERSION);
+ HTML("<HR>");
+ HTML("<H2>WADO is not yet available</H2>");
+ HTML("command: %s", command);
+ HTML("</OBJECT>");
+ HTML("</BODY>");
+#endif
+
+ exit(0);
+};
+
+//////////////////////////////////////////////////////////////////
+// Elementary HL7 interface
+//////////////////////////////////////////////////////////////////
+
+// These contain HL7 DateTime code: provide .DATE and .TIME split, note: should start/end with |
+
+static char HL7DateTimeTypes[]=
+"|OBR.7|OBR.8|OBR.22|PID.7|PID.29|PV1.44|PV1.45|TXA.4|TXA.6|TXA.7|TXA.8|OBR.6|OBR.36|MSH.6|OBX.12|OBX.14|ORC.9|ORC.15|";
+
+// read next item from data passed in p; data->item, type->name, tmp->internal
+// note that data, type, and tmp are also used to maintain the parser state
+
+void parseHL7(char **p, char *data, char *type, char *tmp, char *HL7FieldSep, char *HL7SubFieldSep, char *HL7RepeatSep)
+{ int field;
+ char *q;
+ char t[32];
+ unsigned int i, dots=0;
+
+ sprintf(t, "|%s|", type); // to seek types
+ if (strlen(type)>2) // count .N
+ for (i=0; i<strlen(type)-1; i++) dots += (type[i]=='.' && type[i+1]>='0' && type[i+1]<='9');
+
+ if (**p==0)
+ { strcpy(type, "EOM"); // end of message
+ data[0]=0;
+ }
+ else if (strstr(HL7DateTimeTypes, t)) // translate datetime type
+ { tmp[0] = 0;
+ if (strlen(data)>8) strcpy(tmp, data+8); // get time for later use
+ data[8]=0;
+ strcat(type, ".DATE"); // XXX.N.DATE
+ }
+ else if (strstr(type, ".DATE")>0) // date was returned, now get time
+ { strcpy(data, tmp); // time
+ strcpy(type+strlen(type)-4, "TIME"); // XXX.N.TIME
+ }
+ else if (strchr(data, *HL7SubFieldSep)) // translate field type, first entry
+ { q = strchr(data, *HL7SubFieldSep);
+ if (q) *q=0;
+ if (q) strcpy(tmp, q+1);
+ else tmp[0]=0;
+
+ strcat(type, ".0"); // XXX.N.0
+ }
+ else if (strchr(data, *HL7RepeatSep)) // translate repeat type, first entry
+ { q = strchr(data, *HL7RepeatSep);
+ if (q) *q=0;
+ if (q) strcpy(tmp, q+1);
+ else tmp[0]=0;
+
+ strcat(type, ".0"); // XXX.N.0
+ }
+ else if (dots>1) // process subfields/repeats
+ { if (tmp[0]==0)
+ { q = strrchr(type, '.');
+ if (q) *q=0;
+ strcat(type, ".END"); // internal token
+ data[0]=0;
+ }
+ else
+ { strcpy(data, tmp);
+ q = strchr(data, *HL7SubFieldSep);
+ if (!q) q = strchr(data, *HL7RepeatSep);
+ if (q) *q=0;
+ if (q) strcpy(tmp, q+1);
+ else tmp[0]=0;
+
+ q = strrchr(type, '.');
+ sprintf(q+1, "%d", atoi(q+1)+1); // XXX.N.M
+ }
+ }
+ else if (**p==0x0d)
+ { strcpy(type, "EOS"); strcpy(data, ""); (*p)+=1; // end of segment
+ if (**p==0x0a) (*p)+=1;
+ if (strncmp(*p, "MSH", 3)==0) strcpy(type, "EOM"); // peek ahead for end of message
+ }
+ else if (strcmp(type, "EOS")==0 || strcmp(type, "EOM")==0 || strcmp(type, "")==0) // new segment
+ { field = 0;
+ if (strncmp(*p, "MSH", 3)==0)
+ { *HL7FieldSep = (*p)[3];
+ *HL7SubFieldSep = (*p)[4];
+ *HL7RepeatSep = (*p)[5];
+ strncpy(type, *p, 3); strcat(type, ".0");
+ strncpy(data, *p, 3);
+ (*p)+=4;
+ }
+ else if ((*p)[0]>='A' && (*p)[0] <='Z' && // message header
+ (*p)[1]>='A' && (*p)[1] <='Z' &&
+ (((*p)[2]>='A' && (*p)[2] <='Z') || ((*p)[2]>='0' && (*p)[2] <='9')))
+ { strncpy(type, *p, 3); strcat(type, ".0");
+ strncpy(data, *p, 3);
+ (*p)+=4;
+ }
+ else
+ { strcpy(type, "UNK.0");
+ data[0]=0;
+ }
+ }
+ else
+ { field = atoi(type+4); // genererate new segment
+ sprintf(type+4, "%d", field+1);
+
+ q = strchr(*p, *HL7FieldSep); // upto segment separator
+ if (q)
+ { *q=0;
+ strncpy(data, *p, 255);
+ data[255]=0;
+ *q = *HL7FieldSep;
+ *p = q+1;
+ }
+ else
+ { q = strchr(*p, 0x0d); // or 0x0d
+ if (q)
+ { *q = 0;
+ strncpy(data, *p, 255);
+ data[255]=0;
+ *q = 0x0d;
+ *p = q; // process 0x0d again
+ }
+ else
+ { strcpy(data, "");
+ strcpy(type, "ERR"); // internal token
+ }
+ }
+ }
+
+ SystemDebug.printf("HL7 item: %s, contents: %s\n", type, data);
+}
+
+// load HL7 data into modality worklist using the translation table from dicom.sql
+
+void ProcessHL7Data(char *data)
+{ char *p=data;
+ char fields[1024], values[4096], type[32], item[256], uid[66], tmp[256];//, command[8192];
+ int i;
+
+ char HL7FieldSep = '|';
+ char HL7SubFieldSep = '^';
+ char HL7RepeatSep = '~';
+
+ Database DB;
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ { OperatorConsole.printf("*** HL7 import: cannot open database");
+ return;
+ }
+
+ fields[0]=0;
+ values[0]=0;
+ type[0]=0; // used for context of parser
+ tmp[0]=0;
+
+ while (TRUE)
+ { parseHL7(&p, item, type, tmp, &HL7FieldSep, &HL7SubFieldSep, &HL7RepeatSep);
+ if (strcmp(type, "ERR")==0) break; // error
+
+ // search type in database; if found prepare strings to write
+ i = 0;
+ while ( TRUE )
+ { if(!WorkListDB[i].Element) break;
+ if (WorkListDB[i].DICOMType!=DT_STARTSEQUENCE && WorkListDB[i].DICOMType!=DT_ENDSEQUENCE)
+ { if (strcmp(type, WorkListDB[i].HL7Tag)==0)
+ { strcat(fields, WorkListDB[i].SQLColumn);
+ strcat(fields, ",");
+
+ strcat(values, "'");
+ item[WorkListDB[i].SQLLength]=0; // truncate data to make fit
+ strcat(values, item);
+ strcat(values, "',");
+ }
+ }
+ ++i;
+ }
+
+ // on end of message save the data into the database
+
+ if (strcmp(type, "EOM")==0)
+ { // search for special items (start with *) that are not read from the HL7 parser
+ i = 0;
+ while ( TRUE )
+ { if(!WorkListDB[i].Element) break;
+
+ if (WorkListDB[i].DICOMType!=DT_STARTSEQUENCE && WorkListDB[i].DICOMType!=DT_ENDSEQUENCE)
+ { if (WorkListDB[i].HL7Tag[0]=='*')
+ { strcat(fields, WorkListDB[i].SQLColumn);
+ strcat(fields, ",");
+
+ strcat(values, "'");
+
+ if (strcmp("*AN", WorkListDB[i].HL7Tag)==0) // generate new accession number
+ { GenUID(uid);
+ strcat(values, uid + strlen(uid)-16);
+ }
+ else if (strcmp("*UI", WorkListDB[i].HL7Tag)==0) // generate new uid
+ { GenUID(uid);
+ strcat(values, uid);
+ }
+
+ strcat(values, "',");
+ }
+ }
+ ++i;
+ }
+
+ fields[strlen(fields)-1]=0; // remove trailing ,
+ values[strlen(values)-1]=0; // remove trailing ,
+
+ DB.AddRecord(WorkListTableName, fields, values);
+ SystemDebug.printf("Entering modality worklist fields: %s\n", fields);
+ QueryFromGui++;
+
+ fields[0]=0;
+ values[0]=0;
+
+ HL7FieldSep = '|';
+ HL7SubFieldSep = '^';
+ HL7RepeatSep = '~';
+ }
+
+ if (strcmp(type, "EOM")==0) // end of message
+ if (*p==0) break; // end of file
+ }
+
+ DB.Close();
+}
+
+
+#ifdef WIN32
+
+#include <stdio.h>
+#include <malloc.h>
+
+char *heapinfo( void )
+{ UINT32 stot=0, sn=0, mtot=0, mn=0, ltot=0, ln=0;
+ static char s[256];
+
+HeapLock(GetProcessHeap());
+
+ _HEAPINFO hinfo;
+ int heapstatus;
+ hinfo._pentry = NULL;
+ while( ( heapstatus = _heapwalk( &hinfo ) ) == _HEAPOK )
+ { if (hinfo._useflag == _USEDENTRY)
+ { if (hinfo._size < 256)
+ { sn++, stot += hinfo._size;
+//if (hinfo._size == 100)
+//{ FILE *f;
+// f = fopen("c:\\debug.bin", "ab");
+// fwrite(hinfo._pentry, hinfo._size, 1, f);
+// fclose(f);
+//}
+ }
+ else if (hinfo._size < 4096) mn++, mtot += hinfo._size;
+ else ln++, ltot += hinfo._size;
+ }
+ }
+
+HeapUnlock(GetProcessHeap());
+
+ sprintf(s, "%d small (%d); %d medium (%d) %d large (%d) ", sn, stot, mn, mtot, ln, ltot);
+
+ switch( heapstatus )
+ {
+ case _HEAPEMPTY:
+ strcat(s, "OK - empty heap\n" );
+ break;
+ case _HEAPEND:
+ strcat(s, "OK - end of heap\n" );
+ break;
+ case _HEAPBADPTR:
+ strcat(s, "*** ERROR - bad heap ptr\n" );
+ break;
+ case _HEAPBADBEGIN:
+ strcat(s, "*** ERROR - bad heap start\n" );
+ break;
+ case _HEAPBADNODE:
+ strcat(s, "*** ERROR - bad heap node\n" );
+ break;
+ }
+
+ return s;
+}
+
+#else
+
+char *heapinfo( void )
+{ static char s[] = "not available";
+ return s;
+}
+
+#endif WIN32
diff --git a/dgate.dic b/dgate.dic
new file mode 100644
index 0000000..8b79856
--- /dev/null
+++ b/dgate.dic
@@ -0,0 +1,4025 @@
+# mvh mist :
+# PET: 0018,0073....
+# QUEUE management: 2100,0010....
+# visible light: 0008,0105....
+# modality performed step: 0008,2229, 0040,0220....
+# presentation LUT: 2050,0010....
+# structured reporting: 0040,a007...
+# stored print related SOP classes: 0018,1011....
+# waveform interchange: 0008,0062....
+# correction proposal 71: 0008,0061
+# correction proposal 72: 0040,0020
+# correction proposal 74: 0020,1209
+# correction proposal 101: 0008,0051....
+# 19990915 ljz Moved all uneven (private) group-codes to dd-private.txt
+# 20030706 mvh Add NKI Pixel Data
+# 20030802 ljz Adjusted to dicom 2001 (retired elements still in lib)
+# 20060913 ljz Adjusted to dicom 2005
+# 20090812 lmb Added Philips private tags
+# 20090828 ljz Put those private tags in alphabetical order
+# 20091124 lmb Added more Philips private tags
+# 20100909 ljz Changed two MRI private tags (2005,100d) (2005,100e)
+# 20101004 ljz Added
+# 20120628 ljz Adjusted to dicom 2011 (VERS="4")
+# 20121016 mvh Added conquest private commands
+
+(0000,0000) VERS="3" VR="UL" VM="1" Keyword="GroupLength" Name="Group Length"
+(0000,0001) VERS="2" VR="UL" VM="1" Keyword="CommandLengthToEnd" Name="Command Length to End"
+(0000,0002) VERS="3" VR="UI" VM="1" Keyword="AffectedSOPClassUID" Name="Affected SOP Class UID"
+(0000,0003) VERS="3" VR="UI" VM="1" Keyword="RequestedSOPClassUID" Name="Requested SOP Class UID"
+(0000,0010) VERS="2" VR="LO" VM="1" Keyword="CommandRecognitionCode" Name="Command Recognition Code"
+(0000,0100) VERS="3" VR="US" VM="1" Keyword="CommandField" Name="Command Field"
+(0000,0110) VERS="3" VR="US" VM="1" Keyword="MessageID" Name="Message ID"
+(0000,0120) VERS="3" VR="US" VM="1" Keyword="MessageIDBeingRespondedTo" Name="Message ID Being Responded To"
+(0000,0200) VERS="2" VR="AE" VM="1" Keyword="Initiator" Name="Initiator"
+(0000,0300) VERS="2" VR="AE" VM="1" Keyword="Receiver" Name="Receiver"
+(0000,0400) VERS="2" VR="AE" VM="1" Keyword="FindLocation" Name="Find Location"
+(0000,0600) VERS="3" VR="AE" VM="1" Keyword="MoveDestination" Name="Move Destination"
+(0000,0700) VERS="3" VR="US" VM="1" Keyword="Priority" Name="Priority"
+(0000,0800) VERS="3" VR="US" VM="1" Keyword="DataSetType" Name="Data Set Type"
+(0000,0850) VERS="2" VR="US" VM="1" Keyword="NumberOfMatches" Name="Number Of Matches"
+(0000,0860) VERS="2" VR="US" VM="1" Keyword="ResponseSequenceNumber" Name="Response Sequence Number"
+(0000,0900) VERS="3" VR="US" VM="1" Keyword="Status" Name="Status"
+(0000,0901) VERS="3" VR="AT" VM="1-n" Keyword="OffendingElement" Name="Offending Element"
+(0000,0902) VERS="3" VR="LO" VM="1" Keyword="ErrorComment" Name="Error Comment"
+(0000,0903) VERS="3" VR="US" VM="1" Keyword="ErrorID" Name="Error ID"
+(0000,1000) VERS="3" VR="UI" VM="1" Keyword="AffectedSOPInstanceUID" Name="Affected SOP Instance UID"
+(0000,1001) VERS="3" VR="UI" VM="1" Keyword="RequestedSOPInstanceUID" Name="Requested SOP Instance UID"
+(0000,1002) VERS="3" VR="US" VM="1" Keyword="EventTypeID" Name="Event Type ID"
+(0000,1005) VERS="3" VR="AT" VM="1-n" Keyword="AttributeIdentifierList" Name="Attribute Identifier List"
+(0000,1008) VERS="3" VR="US" VM="1" Keyword="ActionTypeID" Name="Action Type ID"
+(0000,1020) VERS="3" VR="US" VM="1" Keyword="NumberOfRemainingSuboperations" Name="Number Of Remaining Suboperations"
+(0000,1021) VERS="3" VR="US" VM="1" Keyword="NumberOfCompletedSuboperations" Name="Number Of Completed Suboperations"
+(0000,1022) VERS="3" VR="US" VM="1" Keyword="NumberOfFailedSuboperations" Name="Number Of Failed Suboperations"
+(0000,1023) VERS="3" VR="US" VM="1" Keyword="NumberOfWarningSuboperations" Name="Number Of Warning Suboperations"
+(0000,1030) VERS="3" VR="AE" VM="1" Keyword="MoveOriginatorApplicationEntityTitle" Name="Move Originator Application Entity Title"
+(0000,1031) VERS="3" VR="US" VM="1" Keyword="MoveOriginatorMessageID" Name="Move Originator Message ID"
+(0000,4000) VERS="2" VR="LO" VM="1" Keyword="DialogReceiver" Name="Dialog Receiver"
+(0000,4010) VERS="2" VR="LO" VM="1" Keyword="TerminalType" Name="Terminal Type"
+(0000,5010) VERS="3" VR="SH" VM="1" Keyword="MessageSetID" Name="Message Set ID"
+(0000,5020) VERS="3" VR="SH" VM="1" Keyword="EndMessageSet" Name="End Message Set"
+(0000,5110) VERS="2" VR="LO" VM="1" Keyword="DisplayFormat" Name="Display Format"
+(0000,5120) VERS="2" VR="LO" VM="1" Keyword="PagePositionID" Name="Page Position ID"
+(0000,5130) VERS="2" VR="LO" VM="1" Keyword="TextFormatID" Name="Text Format ID"
+(0000,5140) VERS="2" VR="LO" VM="1" Keyword="NormalReverse" Name="Normal Reverse"
+(0000,5150) VERS="2" VR="LO" VM="1" Keyword="AddGrayScale" Name="Add Gray Scale"
+(0000,5160) VERS="2" VR="LO" VM="1" Keyword="Borders" Name="Borders"
+(0000,5170) VERS="2" VR="IS" VM="1" Keyword="Copies" Name="Copies"
+(0000,5180) VERS="2" VR="LO" VM="1" Keyword="OldMagnificationType" Name="OldMagnificationType"
+(0000,5190) VERS="2" VR="LO" VM="1" Keyword="Erase" Name="Erase"
+(0000,51A0) VERS="2" VR="LO" VM="1" Keyword="Print" Name="Print"
+(0000,51B0) VERS="2" VR="US" VM="1-n" Keyword="Overlays" Name="Overlays"
+(0002,0000) VERS="4" VR="UL" VM="1" Keyword="FileMetaInformationGroupLength" Name="File Meta Information Group Length"
+(0002,0001) VERS="4" VR="OB" VM="1" Keyword="FileMetaInformationVersion" Name="File Meta Information Version"
+(0002,0001) VERS="3" VR="OB" VM="1" Keyword="FileMetaInformationVersion" Name="File Meta Information Version"
+(0002,0002) VERS="4" VR="UI" VM="1" Keyword="MediaStorageSOPClassUID" Name="Media Storage SOP Class UID"
+(0002,0003) VERS="4" VR="UI" VM="1" Keyword="MediaStorageSOPInstanceUID" Name="Media Storage SOP Instance UID"
+(0002,0010) VERS="4" VR="UI" VM="1" Keyword="TransferSyntaxUID" Name="Transfer Syntax UID"
+(0002,0012) VERS="4" VR="UI" VM="1" Keyword="ImplementationClassUID" Name="Implementation Class UID"
+(0002,0013) VERS="4" VR="SH" VM="1" Keyword="ImplementationVersionName" Name="Implementation Version Name"
+(0002,0016) VERS="4" VR="AE" VM="1" Keyword="SourceApplicationEntityTitle" Name="Source Application Entity Title"
+(0002,0100) VERS="4" VR="UI" VM="1" Keyword="PrivateInformationCreatorUID" Name="Private Information Creator UID"
+(0002,0102) VERS="4" VR="OB" VM="1" Keyword="PrivateInformation" Name="Private Information"
+(0004,0000) VERS="3" VR="UL" VM="1" Keyword="FileSetGroupLength" Name="File Set Group Length"
+(0004,1130) VERS="4" VR="CS" VM="1" Keyword="FileSetID" Name="File-set ID"
+(0004,1141) VERS="4" VR="CS" VM="1-8" Keyword="FileSetDescriptorFileID" Name="File-set Descriptor File ID"
+(0004,1142) VERS="4" VR="CS" VM="1" Keyword="SpecificCharacterSetOfFileSetDescriptorFile" Name="Specific Character Set of File-set Descriptor File"
+(0004,1200) VERS="4" VR="UL" VM="1" Keyword="OffsetOfTheFirstDirectoryRecordOfTheRootDirectoryEntity" Name="Offset of the First Directory Record of the Root Directory Entity"
+(0004,1202) VERS="4" VR="UL" VM="1" Keyword="OffsetOfTheLastDirectoryRecordOfTheRootDirectoryEntity" Name="Offset of the Last Directory Record of the Root Directory Entity"
+(0004,1212) VERS="4" VR="US" VM="1" Keyword="FileSetConsistencyFlag" Name="File-set Consistency Flag"
+(0004,1220) VERS="4" VR="SQ" VM="1" Keyword="DirectoryRecordSequence" Name="Directory Record Sequence"
+(0004,1400) VERS="4" VR="UL" VM="1" Keyword="OffsetOfTheNextDirectoryRecord" Name="Offset of the Next Directory Record"
+(0004,1410) VERS="4" VR="US" VM="1" Keyword="RecordInUseFlag" Name="Record In-use Flag"
+(0004,1420) VERS="4" VR="UL" VM="1" Keyword="OffsetOfReferencedLowerLevelDirectoryEntity" Name="Offset of Referenced Lower-Level Directory Entity"
+(0004,1430) VERS="4" VR="CS" VM="1" Keyword="DirectoryRecordType" Name="Directory Record Type"
+(0004,1432) VERS="4" VR="UI" VM="1" Keyword="PrivateRecordUID" Name="Private Record UID"
+(0004,1500) VERS="4" VR="CS" VM="1-8" Keyword="ReferencedFileID" Name="Referenced File ID"
+(0004,1504) VERS="4RET" VR="UL" VM="1" Keyword="MRDRDirectoryRecordOffset" Name="MRDR Directory Record Offset"
+(0004,1510) VERS="4" VR="UI" VM="1" Keyword="ReferencedSOPClassUIDInFile" Name="Referenced SOP Class UID in File"
+(0004,1511) VERS="4" VR="UI" VM="1" Keyword="ReferencedSOPInstanceUIDInFile" Name="Referenced SOP Instance UID in File"
+(0004,1512) VERS="4" VR="UI" VM="1" Keyword="ReferencedTransferSyntaxUIDInFile" Name="Referenced Transfer Syntax UID in File"
+(0004,151A) VERS="4" VR="UI" VM="1-n" Keyword="ReferencedRelatedGeneralSOPClassUIDInFile" Name="Referenced Related General SOP Class UID in File"
+(0004,1600) VERS="4RET" VR="UL" VM="1" Keyword="NumberOfReferences" Name="Number of References"
+(0008,0000) VERS="3" VR="UL" VM="1" Keyword="IdentifyingGroupLength" Name="Identifying Group Length"
+(0008,0001) VERS="4RET" VR="UL" VM="1" Keyword="LengthToEnd" Name="Length to End"
+(0008,0005) VERS="4" VR="CS" VM="1-n" Keyword="SpecificCharacterSet" Name="Specific Character Set"
+(0008,0006) VERS="4" VR="SQ" VM="1" Keyword="LanguageCodeSequence" Name="Language Code Sequence"
+(0008,0008) VERS="4" VR="CS" VM="2-n" Keyword="ImageType" Name="Image Type"
+(0008,0010) VERS="4RET" VR="SH" VM="1" Keyword="RecognitionCode" Name="Recognition Code"
+(0008,0012) VERS="4" VR="DA" VM="1" Keyword="InstanceCreationDate" Name="Instance Creation Date"
+(0008,0013) VERS="4" VR="TM" VM="1" Keyword="InstanceCreationTime" Name="Instance Creation Time"
+(0008,0014) VERS="4" VR="UI" VM="1" Keyword="InstanceCreatorUID" Name="Instance Creator UID"
+(0008,0016) VERS="4" VR="UI" VM="1" Keyword="SOPClassUID" Name="SOP Class UID"
+(0008,0018) VERS="4" VR="UI" VM="1" Keyword="SOPInstanceUID" Name="SOP Instance UID"
+(0008,001A) VERS="4" VR="UI" VM="1-n" Keyword="RelatedGeneralSOPClassUID" Name="Related General SOP Class UID"
+(0008,001B) VERS="4" VR="UI" VM="1" Keyword="OriginalSpecializedSOPClassUID" Name="Original Specialized SOP Class UID"
+(0008,0020) VERS="4" VR="DA" VM="1" Keyword="StudyDate" Name="Study Date"
+(0008,0021) VERS="4" VR="DA" VM="1" Keyword="SeriesDate" Name="Series Date"
+(0008,0022) VERS="4" VR="DA" VM="1" Keyword="AcquisitionDate" Name="Acquisition Date"
+(0008,0023) VERS="4" VR="DA" VM="1" Keyword="ContentDate" Name="Content Date"
+(0008,0024) VERS="4RET" VR="DA" VM="1" Keyword="OverlayDate" Name="Overlay Date"
+(0008,0025) VERS="4RET" VR="DA" VM="1" Keyword="CurveDate" Name="Curve Date"
+(0008,002A) VERS="4" VR="DT" VM="1" Keyword="AcquisitionDateTime" Name="Acquisition DateTime"
+(0008,0030) VERS="4" VR="TM" VM="1" Keyword="StudyTime" Name="Study Time"
+(0008,0031) VERS="4" VR="TM" VM="1" Keyword="SeriesTime" Name="Series Time"
+(0008,0032) VERS="4" VR="TM" VM="1" Keyword="AcquisitionTime" Name="Acquisition Time"
+(0008,0033) VERS="4" VR="TM" VM="1" Keyword="ContentTime" Name="Content Time"
+(0008,0034) VERS="4RET" VR="TM" VM="1" Keyword="OverlayTime" Name="Overlay Time"
+(0008,0035) VERS="4RET" VR="TM" VM="1" Keyword="CurveTime" Name="Curve Time"
+(0008,0040) VERS="4RET" VR="US" VM="1" Keyword="DataSetType" Name="Data Set Type"
+(0008,0041) VERS="4RET" VR="LO" VM="1" Keyword="DataSetSubtype" Name="Data Set Subtype"
+(0008,0042) VERS="4RET" VR="CS" VM="1" Keyword="NuclearMedicineSeriesType" Name="Nuclear Medicine Series Type"
+(0008,0050) VERS="4" VR="SH" VM="1" Keyword="AccessionNumber" Name="Accession Number"
+(0008,0051) VERS="4" VR="SQ" VM="1" Keyword="IssuerOfAccessionNumberSequence" Name="Issuer of Accession Number Sequence"
+(0008,0052) VERS="4" VR="CS" VM="1" Keyword="QueryRetrieveLevel" Name="Query/Retrieve Level"
+(0008,0054) VERS="4" VR="AE" VM="1-n" Keyword="RetrieveAETitle" Name="Retrieve AE Title"
+(0008,0056) VERS="4" VR="CS" VM="1" Keyword="InstanceAvailability" Name="Instance Availability"
+(0008,0058) VERS="4" VR="UI" VM="1-n" Keyword="FailedSOPInstanceUIDList" Name="Failed SOP Instance UID List"
+(0008,0060) VERS="4" VR="CS" VM="1" Keyword="Modality" Name="Modality"
+(0008,0061) VERS="4" VR="CS" VM="1-n" Keyword="ModalitiesInStudy" Name="Modalities in Study"
+(0008,0062) VERS="4" VR="UI" VM="1-n" Keyword="SOPClassesInStudy" Name="SOP Classes in Study"
+(0008,0064) VERS="4" VR="CS" VM="1" Keyword="ConversionType" Name="Conversion Type"
+(0008,0068) VERS="4" VR="CS" VM="1" Keyword="PresentationIntentType" Name="Presentation Intent Type"
+(0008,0070) VERS="4" VR="LO" VM="1" Keyword="Manufacturer" Name="Manufacturer"
+(0008,0080) VERS="4" VR="LO" VM="1" Keyword="InstitutionName" Name="Institution Name"
+(0008,0081) VERS="4" VR="ST" VM="1" Keyword="InstitutionAddress" Name="Institution Address"
+(0008,0082) VERS="4" VR="SQ" VM="1" Keyword="InstitutionCodeSequence" Name="Institution Code Sequence"
+(0008,0090) VERS="4" VR="PN" VM="1" Keyword="ReferringPhysicianName" Name="Referring Physician�s Name"
+(0008,0092) VERS="4" VR="ST" VM="1" Keyword="ReferringPhysicianAddress" Name="Referring Physician�s Address"
+(0008,0094) VERS="4" VR="SH" VM="1-n" Keyword="ReferringPhysicianTelephoneNumbers" Name="Referring Physician�s Telephone Numbers"
+(0008,0096) VERS="4" VR="SQ" VM="1" Keyword="ReferringPhysicianIdentificationSequence" Name="Referring Physician Identification Sequence"
+(0008,0100) VERS="4" VR="SH" VM="1" Keyword="CodeValue" Name="Code Value"
+(0008,0102) VERS="4" VR="SH" VM="1" Keyword="CodingSchemeDesignator" Name="Coding Scheme Designator"
+(0008,0103) VERS="4" VR="SH" VM="1" Keyword="CodingSchemeVersion" Name="Coding Scheme Version"
+(0008,0104) VERS="4" VR="LO" VM="1" Keyword="CodeMeaning" Name="Code Meaning"
+(0008,0105) VERS="4" VR="CS" VM="1" Keyword="MappingResource" Name="Mapping Resource"
+(0008,0106) VERS="4" VR="DT" VM="1" Keyword="ContextGroupVersion" Name="Context Group Version"
+(0008,0107) VERS="4" VR="DT" VM="1" Keyword="ContextGroupLocalVersion" Name="Context Group Local Version"
+(0008,010B) VERS="4" VR="CS" VM="1" Keyword="ContextGroupExtensionFlag" Name="Context Group Extension Flag"
+(0008,010C) VERS="4" VR="UI" VM="1" Keyword="CodingSchemeUID" Name="Coding Scheme UID"
+(0008,010D) VERS="4" VR="UI" VM="1" Keyword="ContextGroupExtensionCreatorUID" Name="Context Group Extension Creator UID"
+(0008,010F) VERS="4" VR="CS" VM="1" Keyword="ContextIdentifier" Name="Context Identifier"
+(0008,0110) VERS="4" VR="SQ" VM="1" Keyword="CodingSchemeIdentificationSequence" Name="Coding Scheme Identification Sequence"
+(0008,0112) VERS="4" VR="LO" VM="1" Keyword="CodingSchemeRegistry" Name="Coding Scheme Registry"
+(0008,0114) VERS="4" VR="ST" VM="1" Keyword="CodingSchemeExternalID" Name="Coding Scheme External ID"
+(0008,0115) VERS="4" VR="ST" VM="1" Keyword="CodingSchemeName" Name="Coding Scheme Name"
+(0008,0116) VERS="4" VR="ST" VM="1" Keyword="CodingSchemeResponsibleOrganization" Name="Coding Scheme Responsible Organization"
+(0008,0117) VERS="4" VR="UI" VM="1" Keyword="ContextUID" Name="Context UID"
+(0008,0201) VERS="4" VR="SH" VM="1" Keyword="TimezoneOffsetFromUTC" Name="Timezone Offset From UTC"
+(0008,1000) VERS="4RET" VR="AE" VM="1" Keyword="NetworkID" Name="Network ID"
+(0008,1010) VERS="4" VR="SH" VM="1" Keyword="StationName" Name="Station Name"
+(0008,1030) VERS="4" VR="LO" VM="1" Keyword="StudyDescription" Name="Study Description"
+(0008,1032) VERS="4" VR="SQ" VM="1" Keyword="ProcedureCodeSequence" Name="Procedure Code Sequence"
+(0008,103E) VERS="4" VR="LO" VM="1" Keyword="SeriesDescription" Name="Series Description"
+(0008,103F) VERS="4" VR="SQ" VM="1" Keyword="SeriesDescriptionCodeSequence" Name="Series Description Code Sequence"
+(0008,1040) VERS="4" VR="LO" VM="1" Keyword="InstitutionalDepartmentName" Name="Institutional Department Name"
+(0008,1048) VERS="4" VR="PN" VM="1-n" Keyword="PhysiciansOfRecord" Name="Physician(s) of Record"
+(0008,1049) VERS="4" VR="SQ" VM="1" Keyword="PhysiciansOfRecordIdentificationSequence" Name="Physician(s) of Record Identification Sequence"
+(0008,1050) VERS="4" VR="PN" VM="1-n" Keyword="PerformingPhysicianName" Name="Performing Physician�s Name"
+(0008,1052) VERS="4" VR="SQ" VM="1" Keyword="PerformingPhysicianIdentificationSequence" Name="Performing Physician Identification Sequence"
+(0008,1060) VERS="4" VR="PN" VM="1-n" Keyword="NameOfPhysiciansReadingStudy" Name="Name of Physician(s) Reading Study"
+(0008,1062) VERS="4" VR="SQ" VM="1" Keyword="PhysiciansReadingStudyIdentificationSequence" Name="Physician(s) Reading Study Identification Sequence"
+(0008,1070) VERS="4" VR="PN" VM="1-n" Keyword="OperatorsName" Name="Operators� Name"
+(0008,1072) VERS="4" VR="SQ" VM="1" Keyword="OperatorIdentificationSequence" Name="Operator Identification Sequence"
+(0008,1080) VERS="4" VR="LO" VM="1-n" Keyword="AdmittingDiagnosesDescription" Name="Admitting Diagnoses Description"
+(0008,1084) VERS="4" VR="SQ" VM="1" Keyword="AdmittingDiagnosesCodeSequence" Name="Admitting Diagnoses Code Sequence"
+(0008,1090) VERS="4" VR="LO" VM="1" Keyword="ManufacturerModelName" Name="Manufacturer�s Model Name"
+(0008,1100) VERS="4RET" VR="SQ" VM="1" Keyword="ReferencedResultsSequence" Name="Referenced Results Sequence"
+(0008,1110) VERS="4" VR="SQ" VM="1" Keyword="ReferencedStudySequence" Name="Referenced Study Sequence"
+(0008,1111) VERS="4" VR="SQ" VM="1" Keyword="ReferencedPerformedProcedureStepSequence" Name="Referenced Performed Procedure Step Sequence"
+(0008,1115) VERS="4" VR="SQ" VM="1" Keyword="ReferencedSeriesSequence" Name="Referenced Series Sequence"
+(0008,1120) VERS="4" VR="SQ" VM="1" Keyword="ReferencedPatientSequence" Name="Referenced Patient Sequence"
+(0008,1125) VERS="4" VR="SQ" VM="1" Keyword="ReferencedVisitSequence" Name="Referenced Visit Sequence"
+(0008,1130) VERS="4RET" VR="SQ" VM="1" Keyword="ReferencedOverlaySequence" Name="Referenced Overlay Sequence"
+(0008,1134) VERS="4" VR="SQ" VM="1" Keyword="ReferencedStereometricInstanceSequence" Name="Referenced Stereometric Instance Sequence"
+(0008,113A) VERS="4" VR="SQ" VM="1" Keyword="ReferencedWaveformSequence" Name="Referenced Waveform Sequence"
+(0008,1140) VERS="4" VR="SQ" VM="1" Keyword="ReferencedImageSequence" Name="Referenced Image Sequence"
+(0008,1145) VERS="4RET" VR="SQ" VM="1" Keyword="ReferencedCurveSequence" Name="Referenced Curve Sequence"
+(0008,114A) VERS="4" VR="SQ" VM="1" Keyword="ReferencedInstanceSequence" Name="Referenced Instance Sequence"
+(0008,114B) VERS="4" VR="SQ" VM="1" Keyword="ReferencedRealWorldValueMappingInstanceSequence" Name="Referenced Real World Value Mapping Instance Sequence"
+(0008,1150) VERS="4" VR="UI" VM="1" Keyword="ReferencedSOPClassUID" Name="Referenced SOP Class UID"
+(0008,1155) VERS="4" VR="UI" VM="1" Keyword="ReferencedSOPInstanceUID" Name="Referenced SOP Instance UID"
+(0008,115A) VERS="4" VR="UI" VM="1-n" Keyword="SOPClassesSupported" Name="SOP Classes Supported"
+(0008,1160) VERS="4" VR="IS" VM="1-n" Keyword="ReferencedFrameNumber" Name="Referenced Frame Number"
+(0008,1161) VERS="4" VR="UL" VM="1-n" Keyword="SimpleFrameList" Name="Simple Frame List"
+(0008,1162) VERS="4" VR="UL" VM="3-3n" Keyword="CalculatedFrameList" Name="Calculated Frame List"
+(0008,1163) VERS="4" VR="FD" VM="2" Keyword="TimeRange" Name="Time Range"
+(0008,1164) VERS="4" VR="SQ" VM="1" Keyword="FrameExtractionSequence" Name="Frame Extraction Sequence"
+(0008,1167) VERS="4" VR="UI" VM="1" Keyword="MultiFrameSourceSOPInstanceUID" Name="Multi-Frame Source SOP Instance UID "
+(0008,1195) VERS="4" VR="UI" VM="1" Keyword="TransactionUID" Name="Transaction UID"
+(0008,1197) VERS="4" VR="US" VM="1" Keyword="FailureReason" Name="Failure Reason"
+(0008,1198) VERS="4" VR="SQ" VM="1" Keyword="FailedSOPSequence" Name="Failed SOP Sequence"
+(0008,1199) VERS="4" VR="SQ" VM="1" Keyword="ReferencedSOPSequence" Name="Referenced SOP Sequence"
+(0008,1200) VERS="4" VR="SQ" VM="1" Keyword="StudiesContainingOtherReferencedInstancesSequence" Name="Studies Containing Other Referenced Instances Sequence"
+(0008,1250) VERS="4" VR="SQ" VM="1" Keyword="RelatedSeriesSequence" Name="Related Series Sequence"
+(0008,2110) VERS="4RET" VR="CS" VM="1" Keyword="LossyImageCompressionRetired" Name="Lossy Image Compression (Retired)"
+(0008,2111) VERS="4" VR="ST" VM="1" Keyword="DerivationDescription" Name="Derivation Description"
+(0008,2112) VERS="4" VR="SQ" VM="1" Keyword="SourceImageSequence" Name="Source Image Sequence"
+(0008,2120) VERS="4" VR="SH" VM="1" Keyword="StageName" Name="Stage Name"
+(0008,2122) VERS="4" VR="IS" VM="1" Keyword="StageNumber" Name="Stage Number"
+(0008,2124) VERS="4" VR="IS" VM="1" Keyword="NumberOfStages" Name="Number of Stages"
+(0008,2127) VERS="4" VR="SH" VM="1" Keyword="ViewName" Name="View Name"
+(0008,2128) VERS="4" VR="IS" VM="1" Keyword="ViewNumber" Name="View Number"
+(0008,2129) VERS="4" VR="IS" VM="1" Keyword="NumberOfEventTimers" Name="Number of Event Timers"
+(0008,212A) VERS="4" VR="IS" VM="1" Keyword="NumberOfViewsInStage" Name="Number of Views in Stage"
+(0008,2130) VERS="4" VR="DS" VM="1-n" Keyword="EventElapsedTimes" Name="Event Elapsed Time(s)"
+(0008,2132) VERS="4" VR="LO" VM="1-n" Keyword="EventTimerNames" Name="Event Timer Name(s)"
+(0008,2133) VERS="4" VR="SQ" VM="1" Keyword="EventTimerSequence" Name="Event Timer Sequence"
+(0008,2134) VERS="4" VR="FD" VM="1" Keyword="EventTimeOffset" Name="Event Time Offset"
+(0008,2135) VERS="4" VR="SQ" VM="1" Keyword="EventCodeSequence" Name="Event Code Sequence"
+(0008,2142) VERS="4" VR="IS" VM="1" Keyword="StartTrim" Name="Start Trim"
+(0008,2143) VERS="4" VR="IS" VM="1" Keyword="StopTrim" Name="Stop Trim"
+(0008,2144) VERS="4" VR="IS" VM="1" Keyword="RecommendedDisplayFrameRate" Name="Recommended Display Frame Rate"
+(0008,2200) VERS="4RET" VR="CS" VM="1" Keyword="TransducerPosition" Name="Transducer Position"
+(0008,2204) VERS="4RET" VR="CS" VM="1" Keyword="TransducerOrientation" Name="Transducer Orientation"
+(0008,2208) VERS="4RET" VR="CS" VM="1" Keyword="AnatomicStructure" Name="Anatomic Structure"
+(0008,2218) VERS="4" VR="SQ" VM="1" Keyword="AnatomicRegionSequence" Name="Anatomic Region Sequence"
+(0008,2220) VERS="4" VR="SQ" VM="1" Keyword="AnatomicRegionModifierSequence" Name="Anatomic Region Modifier Sequence"
+(0008,2228) VERS="4" VR="SQ" VM="1" Keyword="PrimaryAnatomicStructureSequence" Name="Primary Anatomic Structure Sequence"
+(0008,2229) VERS="4" VR="SQ" VM="1" Keyword="AnatomicStructureSpaceOrRegionSequence" Name="Anatomic Structure, Space or Region Sequence"
+(0008,2230) VERS="4" VR="SQ" VM="1" Keyword="PrimaryAnatomicStructureModifierSequence" Name="Primary Anatomic Structure Modifier Sequence"
+(0008,2240) VERS="4RET" VR="SQ" VM="1" Keyword="TransducerPositionSequence" Name="Transducer Position Sequence"
+(0008,2242) VERS="4RET" VR="SQ" VM="1" Keyword="TransducerPositionModifierSequence" Name="Transducer Position Modifier Sequence"
+(0008,2244) VERS="4RET" VR="SQ" VM="1" Keyword="TransducerOrientationSequence" Name="Transducer Orientation Sequence"
+(0008,2246) VERS="4RET" VR="SQ" VM="1" Keyword="TransducerOrientationModifierSequence" Name="Transducer Orientation Modifier Sequence"
+(0008,2251) VERS="4RET" VR="SQ" VM="1" Keyword="AnatomicStructureSpaceOrRegionCodeSequenceTrial" Name="Anatomic Structure Space Or Region Code Sequence (Trial)"
+(0008,2253) VERS="4RET" VR="SQ" VM="1" Keyword="AnatomicPortalOfEntranceCodeSequenceTrial" Name="Anatomic Portal Of Entrance Code Sequence (Trial)"
+(0008,2255) VERS="4RET" VR="SQ" VM="1" Keyword="AnatomicApproachDirectionCodeSequenceTrial" Name="Anatomic Approach Direction Code Sequence (Trial)"
+(0008,2256) VERS="4RET" VR="ST" VM="1" Keyword="AnatomicPerspectiveDescriptionTrial" Name="Anatomic Perspective Description (Trial)"
+(0008,2257) VERS="4RET" VR="SQ" VM="1" Keyword="AnatomicPerspectiveCodeSequenceTrial" Name="Anatomic Perspective Code Sequence (Trial)"
+(0008,2258) VERS="4RET" VR="ST" VM="1" Keyword="AnatomicLocationOfExaminingInstrumentDescriptionTrial" Name="Anatomic Location Of Examining Instrument Description (Trial)"
+(0008,2259) VERS="4RET" VR="SQ" VM="1" Keyword="AnatomicLocationOfExaminingInstrumentCodeSequenceTrial" Name="Anatomic Location Of Examining Instrument Code Sequence (Trial)"
+(0008,225A) VERS="4RET" VR="SQ" VM="1" Keyword="AnatomicStructureSpaceOrRegionModifierCodeSequenceTrial" Name="Anatomic Structure Space Or Region Modifier Code Sequence (Trial)"
+(0008,225C) VERS="4RET" VR="SQ" VM="1" Keyword="OnAxisBackgroundAnatomicStructureCodeSequenceTrial" Name="OnAxis Background Anatomic Structure Code Sequence (Trial)"
+(0008,3001) VERS="4" VR="SQ" VM="1" Keyword="AlternateRepresentationSequence" Name="Alternate Representation Sequence"
+(0008,3010) VERS="4" VR="UI" VM="1" Keyword="IrradiationEventUID" Name="Irradiation Event UID"
+(0008,4000) VERS="4RET" VR="LT" VM="1" Keyword="IdentifyingComments" Name="Identifying Comments"
+(0008,9007) VERS="4" VR="CS" VM="4" Keyword="FrameType" Name="Frame Type"
+(0008,9092) VERS="4" VR="SQ" VM="1" Keyword="ReferencedImageEvidenceSequence" Name="Referenced Image Evidence Sequence"
+(0008,9121) VERS="4" VR="SQ" VM="1" Keyword="ReferencedRawDataSequence" Name="Referenced Raw Data Sequence"
+(0008,9123) VERS="4" VR="UI" VM="1" Keyword="CreatorVersionUID" Name="Creator-Version UID"
+(0008,9124) VERS="4" VR="SQ" VM="1" Keyword="DerivationImageSequence" Name="Derivation Image Sequence"
+(0008,9154) VERS="4" VR="SQ" VM="1" Keyword="SourceImageEvidenceSequence" Name="Source Image Evidence Sequence"
+(0008,9205) VERS="4" VR="CS" VM="1" Keyword="PixelPresentation" Name="Pixel Presentation"
+(0008,9206) VERS="4" VR="CS" VM="1" Keyword="VolumetricProperties" Name="Volumetric Properties"
+(0008,9207) VERS="4" VR="CS" VM="1" Keyword="VolumeBasedCalculationTechnique" Name="Volume Based Calculation Technique"
+(0008,9208) VERS="4" VR="CS" VM="1" Keyword="ComplexImageComponent" Name="Complex Image Component"
+(0008,9209) VERS="4" VR="CS" VM="1" Keyword="AcquisitionContrast" Name="Acquisition Contrast"
+(0008,9215) VERS="4" VR="SQ" VM="1" Keyword="DerivationCodeSequence" Name="Derivation Code Sequence"
+(0008,9237) VERS="4" VR="SQ" VM="1" Keyword="ReferencedPresentationStateSequence" Name="Referenced Presentation State Sequence"
+(0008,9410) VERS="4" VR="SQ" VM="1" Keyword="ReferencedOtherPlaneSequence" Name="Referenced Other Plane Sequence"
+(0008,9458) VERS="4" VR="SQ" VM="1" Keyword="FrameDisplaySequence" Name="Frame Display Sequence"
+(0008,9459) VERS="4" VR="FL" VM="1" Keyword="RecommendedDisplayFrameRateInFloat" Name="Recommended Display Frame Rate in Float"
+(0008,9460) VERS="4" VR="CS" VM="1" Keyword="SkipFrameRangeFlag" Name="Skip Frame Range Flag"
+(0010,0000) VERS="3" VR="UL" VM="1" Keyword="PatientGroupLength" Name="Patient Group Length"
+(0010,0010) VERS="4" VR="PN" VM="1" Keyword="PatientName" Name="Patient�s Name"
+(0010,0020) VERS="4" VR="LO" VM="1" Keyword="PatientID" Name="Patient ID"
+(0010,0021) VERS="4" VR="LO" VM="1" Keyword="IssuerOfPatientID" Name="Issuer of Patient ID"
+(0010,0022) VERS="4" VR="CS" VM="1" Keyword="TypeOfPatientID" Name="Type of Patient ID"
+(0010,0024) VERS="4" VR="SQ" VM="1" Keyword="IssuerOfPatientIDQualifiersSequence" Name="Issuer of Patient ID Qualifiers Sequence"
+(0010,0030) VERS="4" VR="DA" VM="1" Keyword="PatientBirthDate" Name="Patient�s Birth Date"
+(0010,0032) VERS="4" VR="TM" VM="1" Keyword="PatientBirthTime" Name="Patient�s Birth Time"
+(0010,0040) VERS="4" VR="CS" VM="1" Keyword="PatientSex" Name="Patient�s Sex"
+(0010,0050) VERS="4" VR="SQ" VM="1" Keyword="PatientInsurancePlanCodeSequence" Name="Patient�s Insurance Plan Code Sequence"
+(0010,0101) VERS="4" VR="SQ" VM="1" Keyword="PatientPrimaryLanguageCodeSequence" Name="Patient�s Primary Language Code Sequence"
+(0010,0102) VERS="4" VR="SQ" VM="1" Keyword="PatientPrimaryLanguageModifierCodeSequence" Name="Patient�s Primary Language Modifier Code Sequence"
+(0010,1000) VERS="4" VR="LO" VM="1-n" Keyword="OtherPatientIDs" Name="Other Patient IDs"
+(0010,1001) VERS="4" VR="PN" VM="1-n" Keyword="OtherPatientNames" Name="Other Patient Names"
+(0010,1002) VERS="4" VR="SQ" VM="1" Keyword="OtherPatientIDsSequence" Name="Other Patient IDs Sequence"
+(0010,1005) VERS="4" VR="PN" VM="1" Keyword="PatientBirthName" Name="Patient�s Birth Name"
+(0010,1010) VERS="4" VR="AS" VM="1" Keyword="PatientAge" Name="Patient�s Age"
+(0010,1020) VERS="4" VR="DS" VM="1" Keyword="PatientSize" Name="Patient�s Size"
+(0010,1021) VERS="4" VR="SQ" VM="1" Keyword="PatientSizeCodeSequence" Name="Patient�s Size Code Sequence"
+(0010,1030) VERS="4" VR="DS" VM="1" Keyword="PatientWeight" Name="Patient�s Weight"
+(0010,1040) VERS="4" VR="LO" VM="1" Keyword="PatientAddress" Name="Patient�s Address"
+(0010,1050) VERS="4RET" VR="LO" VM="1-n" Keyword="InsurancePlanIdentification" Name="Insurance Plan Identification"
+(0010,1060) VERS="4" VR="PN" VM="1" Keyword="PatientMotherBirthName" Name="Patient�s Mother�s Birth Name"
+(0010,1080) VERS="4" VR="LO" VM="1" Keyword="MilitaryRank" Name="Military Rank"
+(0010,1081) VERS="4" VR="LO" VM="1" Keyword="BranchOfService" Name="Branch of Service"
+(0010,1090) VERS="4" VR="LO" VM="1" Keyword="MedicalRecordLocator" Name="Medical Record Locator"
+(0010,2000) VERS="4" VR="LO" VM="1-n" Keyword="MedicalAlerts" Name="Medical Alerts"
+(0010,2110) VERS="4" VR="LO" VM="1-n" Keyword="Allergies" Name="Allergies"
+(0010,2150) VERS="4" VR="LO" VM="1" Keyword="CountryOfResidence" Name="Country of Residence"
+(0010,2152) VERS="4" VR="LO" VM="1" Keyword="RegionOfResidence" Name="Region of Residence"
+(0010,2154) VERS="4" VR="SH" VM="1-n" Keyword="PatientTelephoneNumbers" Name="Patient�s Telephone Numbers"
+(0010,2160) VERS="4" VR="SH" VM="1" Keyword="EthnicGroup" Name="Ethnic Group"
+(0010,2180) VERS="4" VR="SH" VM="1" Keyword="Occupation" Name="Occupation"
+(0010,21A0) VERS="4" VR="CS" VM="1" Keyword="SmokingStatus" Name="Smoking Status"
+(0010,21B0) VERS="4" VR="LT" VM="1" Keyword="AdditionalPatientHistory" Name="Additional Patient History"
+(0010,21C0) VERS="4" VR="US" VM="1" Keyword="PregnancyStatus" Name="Pregnancy Status"
+(0010,21D0) VERS="4" VR="DA" VM="1" Keyword="LastMenstrualDate" Name="Last Menstrual Date"
+(0010,21F0) VERS="4" VR="LO" VM="1" Keyword="PatientReligiousPreference" Name="Patient�s Religious Preference"
+(0010,2201) VERS="4" VR="LO" VM="1" Keyword="PatientSpeciesDescription" Name="Patient Species Description"
+(0010,2202) VERS="4" VR="SQ" VM="1" Keyword="PatientSpeciesCodeSequence" Name="Patient Species Code Sequence"
+(0010,2203) VERS="4" VR="CS" VM="1" Keyword="PatientSexNeutered" Name="Patient�s Sex Neutered"
+(0010,2210) VERS="4" VR="CS" VM="1" Keyword="AnatomicalOrientationType" Name="Anatomical Orientation Type"
+(0010,2292) VERS="4" VR="LO" VM="1" Keyword="PatientBreedDescription" Name="Patient Breed Description"
+(0010,2293) VERS="4" VR="SQ" VM="1" Keyword="PatientBreedCodeSequence" Name="Patient Breed Code Sequence"
+(0010,2294) VERS="4" VR="SQ" VM="1" Keyword="BreedRegistrationSequence" Name="Breed Registration Sequence"
+(0010,2295) VERS="4" VR="LO" VM="1" Keyword="BreedRegistrationNumber" Name="Breed Registration Number"
+(0010,2296) VERS="4" VR="SQ" VM="1" Keyword="BreedRegistryCodeSequence" Name="Breed Registry Code Sequence"
+(0010,2297) VERS="4" VR="PN" VM="1" Keyword="ResponsiblePerson" Name="Responsible Person"
+(0010,2298) VERS="4" VR="CS" VM="1" Keyword="ResponsiblePersonRole" Name="Responsible Person Role"
+(0010,2299) VERS="4" VR="LO" VM="1" Keyword="ResponsibleOrganization" Name="Responsible Organization"
+(0010,4000) VERS="4" VR="LT" VM="1" Keyword="PatientComments" Name="Patient Comments"
+(0010,9431) VERS="4" VR="FL" VM="1" Keyword="ExaminedBodyThickness" Name="Examined Body Thickness"
+(0012,0010) VERS="4" VR="LO" VM="1" Keyword="ClinicalTrialSponsorName" Name="Clinical Trial Sponsor Name"
+(0012,0020) VERS="4" VR="LO" VM="1" Keyword="ClinicalTrialProtocolID" Name="Clinical Trial Protocol ID"
+(0012,0021) VERS="4" VR="LO" VM="1" Keyword="ClinicalTrialProtocolName" Name="Clinical Trial Protocol Name"
+(0012,0030) VERS="4" VR="LO" VM="1" Keyword="ClinicalTrialSiteID" Name="Clinical Trial Site ID"
+(0012,0031) VERS="4" VR="LO" VM="1" Keyword="ClinicalTrialSiteName" Name="Clinical Trial Site Name"
+(0012,0040) VERS="4" VR="LO" VM="1" Keyword="ClinicalTrialSubjectID" Name="Clinical Trial Subject ID"
+(0012,0042) VERS="4" VR="LO" VM="1" Keyword="ClinicalTrialSubjectReadingID" Name="Clinical Trial Subject Reading ID"
+(0012,0050) VERS="4" VR="LO" VM="1" Keyword="ClinicalTrialTimePointID" Name="Clinical Trial Time Point ID"
+(0012,0051) VERS="4" VR="ST" VM="1" Keyword="ClinicalTrialTimePointDescription" Name="Clinical Trial Time Point Description"
+(0012,0060) VERS="4" VR="LO" VM="1" Keyword="ClinicalTrialCoordinatingCenterName" Name="Clinical Trial Coordinating Center Name"
+(0012,0062) VERS="4" VR="CS" VM="1" Keyword="PatientIdentityRemoved" Name="Patient Identity Removed"
+(0012,0063) VERS="4" VR="LO" VM="1-n" Keyword="DeidentificationMethod" Name="De-identification Method"
+(0012,0064) VERS="4" VR="SQ" VM="1" Keyword="DeidentificationMethodCodeSequence" Name="De-identification Method Code Sequence"
+(0012,0071) VERS="4" VR="LO" VM="1" Keyword="ClinicalTrialSeriesID" Name="Clinical Trial Series ID"
+(0012,0072) VERS="4" VR="LO" VM="1" Keyword="ClinicalTrialSeriesDescription" Name="Clinical Trial Series Description"
+(0012,0081) VERS="4" VR="LO" VM="1" Keyword="ClinicalTrialProtocolEthicsCommitteeName" Name="Clinical Trial Protocol Ethics Committee Name"
+(0012,0082) VERS="4" VR="LO" VM="1" Keyword="ClinicalTrialProtocolEthicsCommitteeApprovalNumber" Name="Clinical Trial Protocol Ethics Committee Approval Number"
+(0012,0083) VERS="4" VR="SQ" VM="1" Keyword="ConsentForClinicalTrialUseSequence" Name="Consent for Clinical Trial Use Sequence"
+(0012,0084) VERS="4" VR="CS" VM="1" Keyword="DistributionType" Name="Distribution Type"
+(0012,0085) VERS="4" VR="CS" VM="1" Keyword="ConsentForDistributionFlag" Name="Consent for Distribution Flag"
+(0014,0023) VERS="4" VR="ST" VM="1-n" Keyword="CADFileFormat" Name="CAD File Format"
+(0014,0024) VERS="4" VR="ST" VM="1-n" Keyword="ComponentReferenceSystem" Name="Component Reference System"
+(0014,0025) VERS="4" VR="ST" VM="1-n" Keyword="ComponentManufacturingProcedure" Name="Component Manufacturing Procedure"
+(0014,0028) VERS="4" VR="ST" VM="1-n" Keyword="ComponentManufacturer" Name="Component Manufacturer"
+(0014,0030) VERS="4" VR="DS" VM="1-n" Keyword="MaterialThickness" Name="Material Thickness"
+(0014,0032) VERS="4" VR="DS" VM="1-n" Keyword="MaterialPipeDiameter" Name="Material Pipe Diameter"
+(0014,0034) VERS="4" VR="DS" VM="1-n" Keyword="MaterialIsolationDiameter" Name="Material Isolation Diameter"
+(0014,0042) VERS="4" VR="ST" VM="1-n" Keyword="MaterialGrade" Name="Material Grade"
+(0014,0044) VERS="4" VR="ST" VM="1-n" Keyword="MaterialPropertiesFileID" Name="Material Properties File ID"
+(0014,0045) VERS="4" VR="ST" VM="1-n" Keyword="MaterialPropertiesFileFormat" Name="Material Properties File Format"
+(0014,0046) VERS="4" VR="LT" VM="1" Keyword="MaterialNotes" Name="Material Notes"
+(0014,0050) VERS="4" VR="CS" VM="1" Keyword="ComponentShape" Name="Component Shape"
+(0014,0052) VERS="4" VR="CS" VM="1" Keyword="CurvatureType" Name="Curvature Type"
+(0014,0054) VERS="4" VR="DS" VM="1" Keyword="OuterDiameter" Name="Outer Diameter"
+(0014,0056) VERS="4" VR="DS" VM="1" Keyword="InnerDiameter" Name="Inner Diameter"
+(0014,1010) VERS="4" VR="ST" VM="1" Keyword="ActualEnvironmentalConditions" Name="Actual Environmental Conditions"
+(0014,1020) VERS="4" VR="DA" VM="1" Keyword="ExpiryDate" Name="Expiry Date"
+(0014,1040) VERS="4" VR="ST" VM="1" Keyword="EnvironmentalConditions" Name="Environmental Conditions"
+(0014,2002) VERS="4" VR="SQ" VM="1" Keyword="EvaluatorSequence" Name="Evaluator Sequence"
+(0014,2004) VERS="4" VR="IS" VM="1" Keyword="EvaluatorNumber" Name="Evaluator Number"
+(0014,2006) VERS="4" VR="PN" VM="1" Keyword="EvaluatorName" Name="Evaluator Name"
+(0014,2008) VERS="4" VR="IS" VM="1" Keyword="EvaluationAttempt" Name="Evaluation Attempt"
+(0014,2012) VERS="4" VR="SQ" VM="1" Keyword="IndicationSequence" Name="Indication Sequence"
+(0014,2014) VERS="4" VR="IS" VM="1" Keyword="IndicationNumber " Name="Indication Number "
+(0014,2016) VERS="4" VR="SH" VM="1" Keyword="IndicationLabel" Name="Indication Label"
+(0014,2018) VERS="4" VR="ST" VM="1" Keyword="IndicationDescription" Name="Indication Description"
+(0014,201A) VERS="4" VR="CS" VM="1-n" Keyword="IndicationType" Name="Indication Type"
+(0014,201C) VERS="4" VR="CS" VM="1" Keyword="IndicationDisposition" Name="Indication Disposition"
+(0014,201E) VERS="4" VR="SQ" VM="1" Keyword="IndicationROISequence" Name="Indication ROI Sequence"
+(0014,2030) VERS="4" VR="SQ" VM="1" Keyword="IndicationPhysicalPropertySequence" Name="Indication Physical Property Sequence"
+(0014,2032) VERS="4" VR="SH" VM="1" Keyword="PropertyLabel" Name="Property Label"
+(0014,2202) VERS="4" VR="IS" VM="1" Keyword="CoordinateSystemNumberOfAxes " Name="Coordinate System Number of Axes "
+(0014,2204) VERS="4" VR="SQ" VM="1" Keyword="CoordinateSystemAxesSequence" Name="Coordinate System Axes Sequence"
+(0014,2206) VERS="4" VR="ST" VM="1" Keyword="CoordinateSystemAxisDescription" Name="Coordinate System Axis Description"
+(0014,2208) VERS="4" VR="CS" VM="1" Keyword="CoordinateSystemDataSetMapping" Name="Coordinate System Data Set Mapping"
+(0014,220A) VERS="4" VR="IS" VM="1" Keyword="CoordinateSystemAxisNumber" Name="Coordinate System Axis Number"
+(0014,220C) VERS="4" VR="CS" VM="1" Keyword="CoordinateSystemAxisType" Name="Coordinate System Axis Type"
+(0014,220E) VERS="4" VR="CS" VM="1" Keyword="CoordinateSystemAxisUnits" Name="Coordinate System Axis Units"
+(0014,2210) VERS="4" VR="OB" VM="1" Keyword="CoordinateSystemAxisValues" Name="Coordinate System Axis Values"
+(0014,2220) VERS="4" VR="SQ" VM="1" Keyword="CoordinateSystemTransformSequence" Name="Coordinate System Transform Sequence"
+(0014,2222) VERS="4" VR="ST" VM="1" Keyword="TransformDescription" Name="Transform Description"
+(0014,2224) VERS="4" VR="IS" VM="1" Keyword="TransformNumberOfAxes" Name="Transform Number of Axes"
+(0014,2226) VERS="4" VR="IS" VM="1-n" Keyword="TransformOrderOfAxes" Name="Transform Order of Axes"
+(0014,2228) VERS="4" VR="CS" VM="1" Keyword="TransformedAxisUnits" Name="Transformed Axis Units"
+(0014,222A) VERS="4" VR="DS" VM="1-n" Keyword="CoordinateSystemTransformRotationAndScaleMatrix" Name="Coordinate System Transform Rotation and Scale Matrix"
+(0014,222C) VERS="4" VR="DS" VM="1-n" Keyword="CoordinateSystemTransformTranslationMatrix" Name="Coordinate System Transform Translation Matrix"
+(0014,3011) VERS="4" VR="DS" VM="1" Keyword="InternalDetectorFrameTime" Name="Internal Detector Frame Time"
+(0014,3012) VERS="4" VR="DS" VM="1" Keyword="NumberOfFramesIntegrated" Name="Number of Frames Integrated"
+(0014,3020) VERS="4" VR="SQ" VM="1" Keyword="DetectorTemperatureSequence" Name="Detector Temperature Sequence"
+(0014,3022) VERS="4" VR="DS" VM="1" Keyword="SensorName" Name="Sensor Name"
+(0014,3024) VERS="4" VR="DS" VM="1" Keyword="HorizontalOffsetOfSensor" Name="Horizontal Offset of Sensor"
+(0014,3026) VERS="4" VR="DS" VM="1" Keyword="VerticalOffsetOfSensor" Name="Vertical Offset of Sensor"
+(0014,3028) VERS="4" VR="DS" VM="1" Keyword="SensorTemperature" Name="Sensor Temperature"
+(0014,3040) VERS="4" VR="SQ" VM="1" Keyword="DarkCurrentSequence" Name="Dark Current Sequence"
+(0014,3050) VERS="4" VR="OB/OW" VM="1" Keyword="DarkCurrentCounts" Name="Dark Current Counts"
+(0014,3060) VERS="4" VR="SQ" VM="1" Keyword="GainCorrectionReferenceSequence" Name="Gain Correction Reference Sequence"
+(0014,3070) VERS="4" VR="OB/OW" VM="1" Keyword="AirCounts" Name="Air Counts"
+(0014,3071) VERS="4" VR="DS" VM="1" Keyword="KVUsedInGainCalibration" Name="KV Used in Gain Calibration"
+(0014,3072) VERS="4" VR="DS" VM="1" Keyword="MAUsedInGainCalibration" Name="MA Used in Gain Calibration"
+(0014,3073) VERS="4" VR="DS" VM="1" Keyword="NumberOfFramesUsedForIntegration" Name="Number of Frames Used for Integration"
+(0014,3074) VERS="4" VR="LO" VM="1" Keyword="FilterMaterialUsedInGainCalibration" Name="Filter Material Used in Gain Calibration"
+(0014,3075) VERS="4" VR="DS" VM="1" Keyword="FilterThicknessUsedInGainCalibration" Name="Filter Thickness Used in Gain Calibration"
+(0014,3076) VERS="4" VR="DA" VM="1" Keyword="DateOfGainCalibration" Name="Date of Gain Calibration"
+(0014,3077) VERS="4" VR="TM" VM="1" Keyword="TimeOfGainCalibration" Name="Time of Gain Calibration"
+(0014,3080) VERS="4" VR="OB" VM="1" Keyword="BadPixelImage" Name="Bad Pixel Image"
+(0014,3099) VERS="4" VR="LT" VM="1" Keyword="CalibrationNotes" Name="Calibration Notes"
+(0014,4002) VERS="4" VR="SQ" VM="1" Keyword="PulserEquipmentSequence" Name="Pulser Equipment Sequence"
+(0014,4004) VERS="4" VR="CS" VM="1" Keyword="PulserType" Name="Pulser Type"
+(0014,4006) VERS="4" VR="LT" VM="1" Keyword="PulserNotes" Name="Pulser Notes"
+(0014,4008) VERS="4" VR="SQ" VM="1" Keyword="ReceiverEquipmentSequence" Name="Receiver Equipment Sequence"
+(0014,400A) VERS="4" VR="CS" VM="1" Keyword="AmplifierType" Name="Amplifier Type"
+(0014,400C) VERS="4" VR="LT" VM="1" Keyword="ReceiverNotes" Name="Receiver Notes"
+(0014,400E) VERS="4" VR="SQ" VM="1" Keyword="PreAmplifierEquipmentSequence" Name="Pre-Amplifier Equipment Sequence"
+(0014,400F) VERS="4" VR="LT" VM="1" Keyword="PreAmplifierNotes" Name="Pre-Amplifier Notes"
+(0014,4010) VERS="4" VR="SQ" VM="1" Keyword="TransmitTransducerSequence" Name="Transmit Transducer Sequence"
+(0014,4011) VERS="4" VR="SQ" VM="1" Keyword="ReceiveTransducerSequence" Name="Receive Transducer Sequence"
+(0014,4012) VERS="4" VR="US" VM="1" Keyword="NumberOfElements" Name="Number of Elements"
+(0014,4013) VERS="4" VR="CS" VM="1" Keyword="ElementShape" Name="Element Shape"
+(0014,4014) VERS="4" VR="DS" VM="1" Keyword="ElementDimensionA" Name="Element Dimension A"
+(0014,4015) VERS="4" VR="DS" VM="1" Keyword="ElementDimensionB" Name="Element Dimension B"
+(0014,4016) VERS="4" VR="DS" VM="1" Keyword="ElementPitch" Name="Element Pitch"
+(0014,4017) VERS="4" VR="DS" VM="1" Keyword="MeasuredBeamDimensionA" Name="Measured Beam Dimension A"
+(0014,4018) VERS="4" VR="DS" VM="1" Keyword="MeasuredBeamDimensionB" Name="Measured Beam Dimension B"
+(0014,4019) VERS="4" VR="DS" VM="1" Keyword="LocationOfMeasuredBeamDiameter" Name="Location of Measured Beam Diameter"
+(0014,401A) VERS="4" VR="DS" VM="1" Keyword="NominalFrequency" Name="Nominal Frequency"
+(0014,401B) VERS="4" VR="DS" VM="1" Keyword="MeasuredCenterFrequency" Name="Measured Center Frequency"
+(0014,401C) VERS="4" VR="DS" VM="1" Keyword="MeasuredBandwidth" Name="Measured Bandwidth"
+(0014,4020) VERS="4" VR="SQ" VM="1" Keyword="PulserSettingsSequence" Name="Pulser Settings Sequence"
+(0014,4022) VERS="4" VR="DS" VM="1" Keyword="PulseWidth" Name="Pulse Width"
+(0014,4024) VERS="4" VR="DS" VM="1" Keyword="ExcitationFrequency" Name="Excitation Frequency"
+(0014,4026) VERS="4" VR="CS" VM="1" Keyword="ModulationType" Name="Modulation Type"
+(0014,4028) VERS="4" VR="DS" VM="1" Keyword="Damping" Name="Damping"
+(0014,4030) VERS="4" VR="SQ" VM="1" Keyword="ReceiverSettingsSequence" Name="Receiver Settings Sequence"
+(0014,4031) VERS="4" VR="DS" VM="1" Keyword="AcquiredSoundpathLength" Name="Acquired Soundpath Length"
+(0014,4032) VERS="4" VR="CS" VM="1" Keyword="AcquisitionCompressionType" Name="Acquisition Compression Type"
+(0014,4033) VERS="4" VR="IS" VM="1" Keyword="AcquisitionSampleSize" Name="Acquisition Sample Size"
+(0014,4034) VERS="4" VR="DS" VM="1" Keyword="RectifierSmoothing" Name="Rectifier Smoothing"
+(0014,4035) VERS="4" VR="SQ" VM="1" Keyword="DACSequence" Name="DAC Sequence"
+(0014,4036) VERS="4" VR="CS" VM="1" Keyword="DACType" Name="DAC Type"
+(0014,4038) VERS="4" VR="DS" VM="1-n" Keyword="DACGainPoints" Name="DAC Gain Points"
+(0014,403A) VERS="4" VR="DS" VM="1-n" Keyword="DACTimePoints" Name="DAC Time Points"
+(0014,403C) VERS="4" VR="DS" VM="1-n" Keyword="DACAmplitude" Name="DAC Amplitude"
+(0014,4040) VERS="4" VR="SQ" VM="1" Keyword="PreAmplifierSettingsSequence" Name="Pre-Amplifier Settings Sequence"
+(0014,4050) VERS="4" VR="SQ" VM="1" Keyword="TransmitTransducerSettingsSequence" Name="Transmit Transducer Settings Sequence"
+(0014,4051) VERS="4" VR="SQ" VM="1" Keyword="ReceiveTransducerSettingsSequence" Name="Receive Transducer Settings Sequence"
+(0014,4052) VERS="4" VR="DS" VM="1" Keyword="IncidentAngle" Name="Incident Angle"
+(0014,4054) VERS="4" VR="ST" VM="1" Keyword="CouplingTechnique" Name="Coupling Technique"
+(0014,4056) VERS="4" VR="ST" VM="1" Keyword="CouplingMedium" Name="Coupling Medium"
+(0014,4057) VERS="4" VR="DS" VM="1" Keyword="CouplingVelocity" Name="Coupling Velocity"
+(0014,4058) VERS="4" VR="DS" VM="1" Keyword="CrystalCenterLocationX" Name="Crystal Center Location X"
+(0014,4059) VERS="4" VR="DS" VM="1" Keyword="CrystalCenterLocationZ" Name="Crystal Center Location Z"
+(0014,405A) VERS="4" VR="DS" VM="1" Keyword="SoundPathLength" Name="Sound Path Length"
+(0014,405C) VERS="4" VR="ST" VM="1" Keyword="DelayLawIdentifier" Name="Delay Law Identifier"
+(0014,4060) VERS="4" VR="SQ" VM="1" Keyword="GateSettingsSequence" Name="Gate Settings Sequence"
+(0014,4062) VERS="4" VR="DS" VM="1" Keyword="GateThreshold" Name="Gate Threshold"
+(0014,4064) VERS="4" VR="DS" VM="1" Keyword="VelocityOfSound" Name="Velocity of Sound"
+(0014,4070) VERS="4" VR="SQ" VM="1" Keyword="CalibrationSettingsSequence" Name="Calibration Settings Sequence"
+(0014,4072) VERS="4" VR="ST" VM="1" Keyword="CalibrationProcedure" Name="Calibration Procedure"
+(0014,4074) VERS="4" VR="SH" VM="1" Keyword="ProcedureVersion" Name="Procedure Version"
+(0014,4076) VERS="4" VR="DA" VM="1" Keyword="ProcedureCreationDate" Name="Procedure Creation Date"
+(0014,4078) VERS="4" VR="DA" VM="1" Keyword="ProcedureExpirationDate" Name="Procedure Expiration Date"
+(0014,407A) VERS="4" VR="DA" VM="1" Keyword="ProcedureLastModifiedDate" Name="Procedure Last Modified Date"
+(0014,407C) VERS="4" VR="TM" VM="1-n" Keyword="CalibrationTime" Name="Calibration Time"
+(0014,407E) VERS="4" VR="DA" VM="1-n" Keyword="CalibrationDate" Name="Calibration Date"
+(0014,5002) VERS="4" VR="IS" VM="1" Keyword="LINACEnergy" Name="LINAC Energy"
+(0014,5004) VERS="4" VR="IS" VM="1" Keyword="LINACOutput" Name="LINAC Output"
+(0018,0000) VERS="3" VR="UL" VM="1" Keyword="AcquisitionGroupLength" Name="Acquisition Group Length"
+(0018,0010) VERS="4" VR="LO" VM="1" Keyword="ContrastBolusAgent" Name="Contrast/Bolus Agent"
+(0018,0012) VERS="4" VR="SQ" VM="1" Keyword="ContrastBolusAgentSequence" Name="Contrast/Bolus Agent Sequence"
+(0018,0014) VERS="4" VR="SQ" VM="1" Keyword="ContrastBolusAdministrationRouteSequence" Name="Contrast/Bolus Administration Route Sequence"
+(0018,0015) VERS="4" VR="CS" VM="1" Keyword="BodyPartExamined" Name="Body Part Examined"
+(0018,0020) VERS="4" VR="CS" VM="1-n" Keyword="ScanningSequence" Name="Scanning Sequence"
+(0018,0021) VERS="4" VR="CS" VM="1-n" Keyword="SequenceVariant" Name="Sequence Variant"
+(0018,0022) VERS="4" VR="CS" VM="1-n" Keyword="ScanOptions" Name="Scan Options"
+(0018,0023) VERS="4" VR="CS" VM="1" Keyword="MRAcquisitionType" Name="MR Acquisition Type"
+(0018,0024) VERS="4" VR="SH" VM="1" Keyword="SequenceName" Name="Sequence Name"
+(0018,0025) VERS="4" VR="CS" VM="1" Keyword="AngioFlag" Name="Angio Flag"
+(0018,0026) VERS="4" VR="SQ" VM="1" Keyword="InterventionDrugInformationSequence" Name="Intervention Drug Information Sequence"
+(0018,0027) VERS="4" VR="TM" VM="1" Keyword="InterventionDrugStopTime" Name="Intervention Drug Stop Time"
+(0018,0028) VERS="4" VR="DS" VM="1" Keyword="InterventionDrugDose" Name="Intervention Drug Dose"
+(0018,0029) VERS="4" VR="SQ" VM="1" Keyword="InterventionDrugCodeSequence" Name="Intervention Drug Code Sequence"
+(0018,002A) VERS="4" VR="SQ" VM="1" Keyword="AdditionalDrugSequence" Name="Additional Drug Sequence"
+(0018,0030) VERS="4RET" VR="LO" VM="1-n" Keyword="Radionuclide" Name="Radionuclide"
+(0018,0031) VERS="4" VR="LO" VM="1" Keyword="Radiopharmaceutical" Name="Radiopharmaceutical"
+(0018,0032) VERS="4RET" VR="DS" VM="1" Keyword="EnergyWindowCenterline" Name="Energy Window Centerline"
+(0018,0033) VERS="4RET" VR="DS" VM="1-n" Keyword="EnergyWindowTotalWidth" Name="Energy Window Total Width"
+(0018,0034) VERS="4" VR="LO" VM="1" Keyword="InterventionDrugName" Name="Intervention Drug Name"
+(0018,0035) VERS="4" VR="TM" VM="1" Keyword="InterventionDrugStartTime" Name="Intervention Drug Start Time"
+(0018,0036) VERS="4" VR="SQ" VM="1" Keyword="InterventionSequence" Name="Intervention Sequence"
+(0018,0037) VERS="4RET" VR="CS" VM="1" Keyword="TherapyType" Name="Therapy Type"
+(0018,0038) VERS="4" VR="CS" VM="1" Keyword="InterventionStatus" Name="Intervention Status"
+(0018,0039) VERS="4RET" VR="CS" VM="1" Keyword="TherapyDescription" Name="Therapy Description"
+(0018,003A) VERS="4" VR="ST" VM="1" Keyword="InterventionDescription" Name="Intervention Description"
+(0018,0040) VERS="4" VR="IS" VM="1" Keyword="CineRate" Name="Cine Rate "
+(0018,0042) VERS="4" VR="CS" VM="1" Keyword="InitialCineRunState" Name="Initial Cine Run State"
+(0018,0050) VERS="4" VR="DS" VM="1" Keyword="SliceThickness" Name="Slice Thickness"
+(0018,0060) VERS="4" VR="DS" VM="1" Keyword="KVP" Name="KVP"
+(0018,0070) VERS="4" VR="IS" VM="1" Keyword="CountsAccumulated" Name="Counts Accumulated"
+(0018,0071) VERS="4" VR="CS" VM="1" Keyword="AcquisitionTerminationCondition" Name="Acquisition Termination Condition"
+(0018,0072) VERS="4" VR="DS" VM="1" Keyword="EffectiveDuration" Name="Effective Duration"
+(0018,0073) VERS="4" VR="CS" VM="1" Keyword="AcquisitionStartCondition" Name="Acquisition Start Condition"
+(0018,0074) VERS="4" VR="IS" VM="1" Keyword="AcquisitionStartConditionData" Name="Acquisition Start Condition Data"
+(0018,0075) VERS="4" VR="IS" VM="1" Keyword="AcquisitionTerminationConditionData" Name="Acquisition Termination Condition Data"
+(0018,0080) VERS="4" VR="DS" VM="1" Keyword="RepetitionTime" Name="Repetition Time"
+(0018,0081) VERS="4" VR="DS" VM="1" Keyword="EchoTime" Name="Echo Time"
+(0018,0082) VERS="4" VR="DS" VM="1" Keyword="InversionTime" Name="Inversion Time"
+(0018,0083) VERS="4" VR="DS" VM="1" Keyword="NumberOfAverages" Name="Number of Averages"
+(0018,0084) VERS="4" VR="DS" VM="1" Keyword="ImagingFrequency" Name="Imaging Frequency"
+(0018,0085) VERS="4" VR="SH" VM="1" Keyword="ImagedNucleus" Name="Imaged Nucleus"
+(0018,0086) VERS="4" VR="IS" VM="1-n" Keyword="EchoNumbers" Name="Echo Number(s)"
+(0018,0087) VERS="4" VR="DS" VM="1" Keyword="MagneticFieldStrength" Name="Magnetic Field Strength"
+(0018,0088) VERS="4" VR="DS" VM="1" Keyword="SpacingBetweenSlices" Name="Spacing Between Slices"
+(0018,0089) VERS="4" VR="IS" VM="1" Keyword="NumberOfPhaseEncodingSteps" Name="Number of Phase Encoding Steps"
+(0018,0090) VERS="4" VR="DS" VM="1" Keyword="DataCollectionDiameter" Name="Data Collection Diameter"
+(0018,0091) VERS="4" VR="IS" VM="1" Keyword="EchoTrainLength" Name="Echo Train Length"
+(0018,0093) VERS="4" VR="DS" VM="1" Keyword="PercentSampling" Name="Percent Sampling"
+(0018,0094) VERS="4" VR="DS" VM="1" Keyword="PercentPhaseFieldOfView" Name="Percent Phase Field of View"
+(0018,0095) VERS="4" VR="DS" VM="1" Keyword="PixelBandwidth" Name="Pixel Bandwidth"
+(0018,1000) VERS="4" VR="LO" VM="1" Keyword="DeviceSerialNumber" Name="Device Serial Number"
+(0018,1002) VERS="4" VR="UI" VM="1" Keyword="DeviceUID" Name="Device UID"
+(0018,1003) VERS="4" VR="LO" VM="1" Keyword="DeviceID" Name="Device ID"
+(0018,1004) VERS="4" VR="LO" VM="1" Keyword="PlateID" Name="Plate ID"
+(0018,1005) VERS="4" VR="LO" VM="1" Keyword="GeneratorID" Name="Generator ID"
+(0018,1006) VERS="4" VR="LO" VM="1" Keyword="GridID" Name="Grid ID"
+(0018,1007) VERS="4" VR="LO" VM="1" Keyword="CassetteID" Name="Cassette ID"
+(0018,1008) VERS="4" VR="LO" VM="1" Keyword="GantryID" Name="Gantry ID"
+(0018,1010) VERS="4" VR="LO" VM="1" Keyword="SecondaryCaptureDeviceID" Name="Secondary Capture Device ID"
+(0018,1011) VERS="4RET" VR="LO" VM="1" Keyword="HardcopyCreationDeviceID" Name="Hardcopy Creation Device ID"
+(0018,1012) VERS="4" VR="DA" VM="1" Keyword="DateOfSecondaryCapture" Name="Date of Secondary Capture"
+(0018,1014) VERS="4" VR="TM" VM="1" Keyword="TimeOfSecondaryCapture" Name="Time of Secondary Capture"
+(0018,1016) VERS="4" VR="LO" VM="1" Keyword="SecondaryCaptureDeviceManufacturer" Name="Secondary Capture Device Manufacturer"
+(0018,1017) VERS="4RET" VR="LO" VM="1" Keyword="HardcopyDeviceManufacturer" Name="Hardcopy Device Manufacturer"
+(0018,1018) VERS="4" VR="LO" VM="1" Keyword="SecondaryCaptureDeviceManufacturerModelName" Name="Secondary Capture Device Manufacturer�s Model Name"
+(0018,1019) VERS="4" VR="LO" VM="1-n" Keyword="SecondaryCaptureDeviceSoftwareVersions" Name="Secondary Capture Device Software Versions"
+(0018,101A) VERS="4RET" VR="LO" VM="1-n" Keyword="HardcopyDeviceSoftwareVersion" Name="Hardcopy Device Software Version"
+(0018,101B) VERS="4RET" VR="LO" VM="1" Keyword="HardcopyDeviceManufacturerModelName" Name="Hardcopy Device Manufacturer�s Model Name"
+(0018,1020) VERS="4" VR="LO" VM="1-n" Keyword="SoftwareVersions" Name="Software Version(s)"
+(0018,1022) VERS="4" VR="SH" VM="1" Keyword="VideoImageFormatAcquired" Name="Video Image Format Acquired"
+(0018,1023) VERS="4" VR="LO" VM="1" Keyword="DigitalImageFormatAcquired" Name="Digital Image Format Acquired"
+(0018,1030) VERS="4" VR="LO" VM="1" Keyword="ProtocolName" Name="Protocol Name"
+(0018,1040) VERS="4" VR="LO" VM="1" Keyword="ContrastBolusRoute" Name="Contrast/Bolus Route"
+(0018,1041) VERS="4" VR="DS" VM="1" Keyword="ContrastBolusVolume" Name="Contrast/Bolus Volume"
+(0018,1042) VERS="4" VR="TM" VM="1" Keyword="ContrastBolusStartTime" Name="Contrast/Bolus Start Time "
+(0018,1043) VERS="4" VR="TM" VM="1" Keyword="ContrastBolusStopTime" Name="Contrast/Bolus Stop Time "
+(0018,1044) VERS="4" VR="DS" VM="1" Keyword="ContrastBolusTotalDose" Name="Contrast/Bolus Total Dose"
+(0018,1045) VERS="4" VR="IS" VM="1" Keyword="SyringeCounts" Name="Syringe Counts"
+(0018,1046) VERS="4" VR="DS" VM="1-n" Keyword="ContrastFlowRate" Name="Contrast Flow Rate"
+(0018,1047) VERS="4" VR="DS" VM="1-n" Keyword="ContrastFlowDuration" Name="Contrast Flow Duration"
+(0018,1048) VERS="4" VR="CS" VM="1" Keyword="ContrastBolusIngredient" Name="Contrast/Bolus Ingredient"
+(0018,1049) VERS="4" VR="DS" VM="1" Keyword="ContrastBolusIngredientConcentration" Name="Contrast/Bolus Ingredient Concentration"
+(0018,1050) VERS="4" VR="DS" VM="1" Keyword="SpatialResolution" Name="Spatial Resolution"
+(0018,1060) VERS="4" VR="DS" VM="1" Keyword="TriggerTime" Name="Trigger Time"
+(0018,1061) VERS="4" VR="LO" VM="1" Keyword="TriggerSourceOrType" Name="Trigger Source or Type"
+(0018,1062) VERS="4" VR="IS" VM="1" Keyword="NominalInterval" Name="Nominal Interval"
+(0018,1063) VERS="4" VR="DS" VM="1" Keyword="FrameTime" Name="Frame Time"
+(0018,1064) VERS="4" VR="LO" VM="1" Keyword="CardiacFramingType" Name="Cardiac Framing Type"
+(0018,1065) VERS="4" VR="DS" VM="1-n" Keyword="FrameTimeVector" Name="Frame Time Vector"
+(0018,1066) VERS="4" VR="DS" VM="1" Keyword="FrameDelay" Name="Frame Delay"
+(0018,1067) VERS="4" VR="DS" VM="1" Keyword="ImageTriggerDelay" Name="Image Trigger Delay"
+(0018,1068) VERS="4" VR="DS" VM="1" Keyword="MultiplexGroupTimeOffset" Name="Multiplex Group Time Offset"
+(0018,1069) VERS="4" VR="DS" VM="1" Keyword="TriggerTimeOffset" Name="Trigger Time Offset"
+(0018,106A) VERS="4" VR="CS" VM="1" Keyword="SynchronizationTrigger" Name="Synchronization Trigger"
+(0018,106C) VERS="4" VR="US" VM="2" Keyword="SynchronizationChannel" Name="Synchronization Channel"
+(0018,106E) VERS="4" VR="UL" VM="1" Keyword="TriggerSamplePosition" Name="Trigger Sample Position"
+(0018,1070) VERS="4" VR="LO" VM="1" Keyword="RadiopharmaceuticalRoute" Name="Radiopharmaceutical Route"
+(0018,1071) VERS="4" VR="DS" VM="1" Keyword="RadiopharmaceuticalVolume" Name="Radiopharmaceutical Volume"
+(0018,1072) VERS="4" VR="TM" VM="1" Keyword="RadiopharmaceuticalStartTime" Name="Radiopharmaceutical Start Time"
+(0018,1073) VERS="4" VR="TM" VM="1" Keyword="RadiopharmaceuticalStopTime" Name="Radiopharmaceutical Stop Time"
+(0018,1074) VERS="4" VR="DS" VM="1" Keyword="RadionuclideTotalDose" Name="Radionuclide Total Dose"
+(0018,1075) VERS="4" VR="DS" VM="1" Keyword="RadionuclideHalfLife" Name="Radionuclide Half Life"
+(0018,1076) VERS="4" VR="DS" VM="1" Keyword="RadionuclidePositronFraction" Name="Radionuclide Positron Fraction"
+(0018,1077) VERS="4" VR="DS" VM="1" Keyword="RadiopharmaceuticalSpecificActivity" Name="Radiopharmaceutical Specific Activity"
+(0018,1078) VERS="4" VR="DT" VM="1" Keyword="RadiopharmaceuticalStartDateTime" Name="Radiopharmaceutical Start DateTime"
+(0018,1079) VERS="4" VR="DT" VM="1" Keyword="RadiopharmaceuticalStopDateTime" Name="Radiopharmaceutical Stop DateTime"
+(0018,1080) VERS="4" VR="CS" VM="1" Keyword="BeatRejectionFlag" Name="Beat Rejection Flag"
+(0018,1081) VERS="4" VR="IS" VM="1" Keyword="LowRRValue" Name="Low R-R Value"
+(0018,1082) VERS="4" VR="IS" VM="1" Keyword="HighRRValue" Name="High R-R Value"
+(0018,1083) VERS="4" VR="IS" VM="1" Keyword="IntervalsAcquired" Name="Intervals Acquired"
+(0018,1084) VERS="4" VR="IS" VM="1" Keyword="IntervalsRejected" Name="Intervals Rejected"
+(0018,1085) VERS="4" VR="LO" VM="1" Keyword="PVCRejection" Name="PVC Rejection"
+(0018,1086) VERS="4" VR="IS" VM="1" Keyword="SkipBeats" Name="Skip Beats"
+(0018,1088) VERS="4" VR="IS" VM="1" Keyword="HeartRate" Name="Heart Rate"
+(0018,1090) VERS="4" VR="IS" VM="1" Keyword="CardiacNumberOfImages" Name="Cardiac Number of Images"
+(0018,1094) VERS="4" VR="IS" VM="1" Keyword="TriggerWindow" Name="Trigger Window"
+(0018,1100) VERS="4" VR="DS" VM="1" Keyword="ReconstructionDiameter" Name="Reconstruction Diameter"
+(0018,1110) VERS="4" VR="DS" VM="1" Keyword="DistanceSourceToDetector" Name="Distance Source to Detector"
+(0018,1111) VERS="4" VR="DS" VM="1" Keyword="DistanceSourceToPatient" Name="Distance Source to Patient"
+(0018,1114) VERS="4" VR="DS" VM="1" Keyword="EstimatedRadiographicMagnificationFactor" Name="Estimated Radiographic Magnification Factor"
+(0018,1120) VERS="4" VR="DS" VM="1" Keyword="GantryDetectorTilt" Name="Gantry/Detector Tilt"
+(0018,1121) VERS="4" VR="DS" VM="1" Keyword="GantryDetectorSlew" Name="Gantry/Detector Slew"
+(0018,1122) VERS="3" VR="LO" VM="1" Keyword="GantryDetectorMotion" Name="Gantry/Detector Motion"
+(0018,1130) VERS="4" VR="DS" VM="1" Keyword="TableHeight" Name="Table Height"
+(0018,1131) VERS="4" VR="DS" VM="1" Keyword="TableTraverse" Name="Table Traverse"
+(0018,1134) VERS="4" VR="CS" VM="1" Keyword="TableMotion" Name="Table Motion"
+(0018,1135) VERS="4" VR="DS" VM="1-n" Keyword="TableVerticalIncrement" Name="Table Vertical Increment"
+(0018,1136) VERS="4" VR="DS" VM="1-n" Keyword="TableLateralIncrement" Name="Table Lateral Increment"
+(0018,1137) VERS="4" VR="DS" VM="1-n" Keyword="TableLongitudinalIncrement" Name="Table Longitudinal Increment"
+(0018,1138) VERS="4" VR="DS" VM="1" Keyword="TableAngle" Name="Table Angle"
+(0018,113A) VERS="4" VR="CS" VM="1" Keyword="TableType" Name="Table Type"
+(0018,1140) VERS="4" VR="CS" VM="1" Keyword="RotationDirection" Name="Rotation Direction"
+(0018,1141) VERS="4RET" VR="DS" VM="1" Keyword="AngularPosition" Name="Angular Position"
+(0018,1142) VERS="4" VR="DS" VM="1-n" Keyword="RadialPosition" Name="Radial Position"
+(0018,1143) VERS="4" VR="DS" VM="1" Keyword="ScanArc" Name="Scan Arc"
+(0018,1144) VERS="4" VR="DS" VM="1" Keyword="AngularStep" Name="Angular Step"
+(0018,1145) VERS="4" VR="DS" VM="1" Keyword="CenterOfRotationOffset" Name="Center of Rotation Offset"
+(0018,1146) VERS="4RET" VR="DS" VM="1-n" Keyword="RotationOffset" Name="Rotation Offset"
+(0018,1147) VERS="4" VR="CS" VM="1" Keyword="FieldOfViewShape" Name="Field of View Shape"
+(0018,1149) VERS="4" VR="IS" VM="1-2" Keyword="FieldOfViewDimensions" Name="Field of View Dimension(s)"
+(0018,1150) VERS="4" VR="IS" VM="1" Keyword="ExposureTime" Name="Exposure Time"
+(0018,1151) VERS="4" VR="IS" VM="1" Keyword="XRayTubeCurrent" Name="X-Ray Tube Current"
+(0018,1152) VERS="4" VR="IS" VM="1" Keyword="Exposure" Name="Exposure "
+(0018,1153) VERS="4" VR="IS" VM="1" Keyword="ExposureInuAs" Name="Exposure in �As"
+(0018,1154) VERS="4" VR="DS" VM="1" Keyword="AveragePulseWidth" Name="Average Pulse Width"
+(0018,1155) VERS="4" VR="CS" VM="1" Keyword="RadiationSetting" Name="Radiation Setting"
+(0018,1156) VERS="4" VR="CS" VM="1" Keyword="RectificationType" Name="Rectification Type"
+(0018,115A) VERS="4" VR="CS" VM="1" Keyword="RadiationMode" Name="Radiation Mode"
+(0018,115E) VERS="4" VR="DS" VM="1" Keyword="ImageAndFluoroscopyAreaDoseProduct" Name="Image and Fluoroscopy Area Dose Product"
+(0018,1160) VERS="4" VR="SH" VM="1" Keyword="FilterType" Name="Filter Type"
+(0018,1161) VERS="4" VR="LO" VM="1-n" Keyword="TypeOfFilters" Name="Type of Filters"
+(0018,1162) VERS="4" VR="DS" VM="1" Keyword="IntensifierSize" Name="Intensifier Size"
+(0018,1164) VERS="4" VR="DS" VM="2" Keyword="ImagerPixelSpacing" Name="Imager Pixel Spacing"
+(0018,1166) VERS="4" VR="CS" VM="1-n" Keyword="Grid" Name="Grid"
+(0018,1170) VERS="4" VR="IS" VM="1" Keyword="GeneratorPower" Name="Generator Power"
+(0018,1180) VERS="4" VR="SH" VM="1" Keyword="CollimatorGridName" Name="Collimator/grid Name "
+(0018,1181) VERS="4" VR="CS" VM="1" Keyword="CollimatorType" Name="Collimator Type"
+(0018,1182) VERS="4" VR="IS" VM="1-2" Keyword="FocalDistance" Name="Focal Distance"
+(0018,1183) VERS="4" VR="DS" VM="1-2" Keyword="XFocusCenter" Name="X Focus Center"
+(0018,1184) VERS="4" VR="DS" VM="1-2" Keyword="YFocusCenter" Name="Y Focus Center"
+(0018,1190) VERS="4" VR="DS" VM="1-n" Keyword="FocalSpots" Name="Focal Spot(s)"
+(0018,1191) VERS="4" VR="CS" VM="1" Keyword="AnodeTargetMaterial" Name="Anode Target Material"
+(0018,11A0) VERS="4" VR="DS" VM="1" Keyword="BodyPartThickness" Name="Body Part Thickness"
+(0018,11A2) VERS="4" VR="DS" VM="1" Keyword="CompressionForce" Name="Compression Force"
+(0018,1200) VERS="4" VR="DA" VM="1-n" Keyword="DateOfLastCalibration" Name="Date of Last Calibration"
+(0018,1201) VERS="4" VR="TM" VM="1-n" Keyword="TimeOfLastCalibration" Name="Time of Last Calibration"
+(0018,1210) VERS="4" VR="SH" VM="1-n" Keyword="ConvolutionKernel" Name="Convolution Kernel"
+(0018,1240) VERS="4RET" VR="IS" VM="1-n" Keyword="UpperLowerPixelValues" Name="Upper/Lower Pixel Values"
+(0018,1242) VERS="4" VR="IS" VM="1" Keyword="ActualFrameDuration" Name="Actual Frame Duration"
+(0018,1243) VERS="4" VR="IS" VM="1" Keyword="CountRate" Name="Count Rate"
+(0018,1244) VERS="4" VR="US" VM="1" Keyword="PreferredPlaybackSequencing" Name="Preferred Playback Sequencing"
+(0018,1250) VERS="4" VR="SH" VM="1" Keyword="ReceiveCoilName" Name="Receive Coil Name"
+(0018,1251) VERS="4" VR="SH" VM="1" Keyword="TransmitCoilName" Name="Transmit Coil Name"
+(0018,1260) VERS="4" VR="SH" VM="1" Keyword="PlateType" Name="Plate Type"
+(0018,1261) VERS="4" VR="LO" VM="1" Keyword="PhosphorType" Name="Phosphor Type"
+(0018,1300) VERS="4" VR="DS" VM="1" Keyword="ScanVelocity" Name="Scan Velocity"
+(0018,1301) VERS="4" VR="CS" VM="1-n" Keyword="WholeBodyTechnique" Name="Whole Body Technique"
+(0018,1302) VERS="4" VR="IS" VM="1" Keyword="ScanLength" Name="Scan Length"
+(0018,1310) VERS="4" VR="US" VM="4" Keyword="AcquisitionMatrix" Name="Acquisition Matrix"
+(0018,1312) VERS="4" VR="CS" VM="1" Keyword="InPlanePhaseEncodingDirection" Name="In-plane Phase Encoding Direction"
+(0018,1314) VERS="4" VR="DS" VM="1" Keyword="FlipAngle" Name="Flip Angle"
+(0018,1315) VERS="4" VR="CS" VM="1" Keyword="VariableFlipAngleFlag" Name="Variable Flip Angle Flag"
+(0018,1316) VERS="4" VR="DS" VM="1" Keyword="SAR" Name="SAR"
+(0018,1318) VERS="4" VR="DS" VM="1" Keyword="dBdt" Name="dB/dt"
+(0018,1400) VERS="4" VR="LO" VM="1" Keyword="AcquisitionDeviceProcessingDescription" Name="Acquisition Device Processing Description "
+(0018,1401) VERS="4" VR="LO" VM="1" Keyword="AcquisitionDeviceProcessingCode" Name="Acquisition Device Processing Code"
+(0018,1402) VERS="4" VR="CS" VM="1" Keyword="CassetteOrientation" Name="Cassette Orientation"
+(0018,1403) VERS="4" VR="CS" VM="1" Keyword="CassetteSize" Name="Cassette Size"
+(0018,1404) VERS="4" VR="US" VM="1" Keyword="ExposuresOnPlate" Name="Exposures on Plate"
+(0018,1405) VERS="4" VR="IS" VM="1" Keyword="RelativeXRayExposure" Name="Relative X-Ray Exposure"
+(0018,1411) VERS="4" VR="DS" VM="1" Keyword="ExposureIndex" Name="Exposure Index"
+(0018,1412) VERS="4" VR="DS" VM="1" Keyword="TargetExposureIndex" Name="Target Exposure Index"
+(0018,1413) VERS="4" VR="DS" VM="1" Keyword="DeviationIndex" Name="Deviation Index"
+(0018,1450) VERS="4" VR="DS" VM="1" Keyword="ColumnAngulation" Name="Column Angulation"
+(0018,1460) VERS="4" VR="DS" VM="1" Keyword="TomoLayerHeight" Name="Tomo Layer Height"
+(0018,1470) VERS="4" VR="DS" VM="1" Keyword="TomoAngle" Name="Tomo Angle"
+(0018,1480) VERS="4" VR="DS" VM="1" Keyword="TomoTime" Name="Tomo Time"
+(0018,1490) VERS="4" VR="CS" VM="1" Keyword="TomoType" Name="Tomo Type"
+(0018,1491) VERS="4" VR="CS" VM="1" Keyword="TomoClass" Name="Tomo Class"
+(0018,1495) VERS="4" VR="IS" VM="1" Keyword="NumberOfTomosynthesisSourceImages" Name="Number of Tomosynthesis Source Images"
+(0018,1500) VERS="4" VR="CS" VM="1" Keyword="PositionerMotion" Name="Positioner Motion"
+(0018,1508) VERS="4" VR="CS" VM="1" Keyword="PositionerType" Name="Positioner Type"
+(0018,1510) VERS="4" VR="DS" VM="1" Keyword="PositionerPrimaryAngle" Name="Positioner Primary Angle"
+(0018,1511) VERS="4" VR="DS" VM="1" Keyword="PositionerSecondaryAngle" Name="Positioner Secondary Angle"
+(0018,1520) VERS="4" VR="DS" VM="1-n" Keyword="PositionerPrimaryAngleIncrement" Name="Positioner Primary Angle Increment"
+(0018,1521) VERS="4" VR="DS" VM="1-n" Keyword="PositionerSecondaryAngleIncrement" Name="Positioner Secondary Angle Increment"
+(0018,1530) VERS="4" VR="DS" VM="1" Keyword="DetectorPrimaryAngle" Name="Detector Primary Angle"
+(0018,1531) VERS="4" VR="DS" VM="1" Keyword="DetectorSecondaryAngle" Name="Detector Secondary Angle"
+(0018,1600) VERS="4" VR="CS" VM="1-3" Keyword="ShutterShape" Name="Shutter Shape"
+(0018,1602) VERS="4" VR="IS" VM="1" Keyword="ShutterLeftVerticalEdge" Name="Shutter Left Vertical Edge"
+(0018,1604) VERS="4" VR="IS" VM="1" Keyword="ShutterRightVerticalEdge" Name="Shutter Right Vertical Edge"
+(0018,1606) VERS="4" VR="IS" VM="1" Keyword="ShutterUpperHorizontalEdge" Name="Shutter Upper Horizontal Edge"
+(0018,1608) VERS="4" VR="IS" VM="1" Keyword="ShutterLowerHorizontalEdge" Name="Shutter Lower Horizontal Edge"
+(0018,1610) VERS="4" VR="IS" VM="2" Keyword="CenterOfCircularShutter" Name="Center of Circular Shutter"
+(0018,1612) VERS="4" VR="IS" VM="1" Keyword="RadiusOfCircularShutter" Name="Radius of Circular Shutter"
+(0018,1620) VERS="4" VR="IS" VM="2-2n" Keyword="VerticesOfThePolygonalShutter" Name="Vertices of the Polygonal Shutter"
+(0018,1622) VERS="4" VR="US" VM="1" Keyword="ShutterPresentationValue" Name="Shutter Presentation Value"
+(0018,1623) VERS="4" VR="US" VM="1" Keyword="ShutterOverlayGroup" Name="Shutter Overlay Group"
+(0018,1624) VERS="4" VR="US" VM="3" Keyword="ShutterPresentationColorCIELabValue" Name="Shutter Presentation Color CIELab Value"
+(0018,1700) VERS="4" VR="CS" VM="1-3" Keyword="CollimatorShape" Name="Collimator Shape"
+(0018,1702) VERS="4" VR="IS" VM="1" Keyword="CollimatorLeftVerticalEdge" Name="Collimator Left Vertical Edge"
+(0018,1704) VERS="4" VR="IS" VM="1" Keyword="CollimatorRightVerticalEdge" Name="Collimator Right Vertical Edge"
+(0018,1706) VERS="4" VR="IS" VM="1" Keyword="CollimatorUpperHorizontalEdge" Name="Collimator Upper Horizontal Edge"
+(0018,1708) VERS="4" VR="IS" VM="1" Keyword="CollimatorLowerHorizontalEdge" Name="Collimator Lower Horizontal Edge"
+(0018,1710) VERS="4" VR="IS" VM="2" Keyword="CenterOfCircularCollimator" Name="Center of Circular Collimator"
+(0018,1712) VERS="4" VR="IS" VM="1" Keyword="RadiusOfCircularCollimator" Name="Radius of Circular Collimator"
+(0018,1720) VERS="4" VR="IS" VM="2-2n" Keyword="VerticesOfThePolygonalCollimator" Name="Vertices of the Polygonal Collimator"
+(0018,1800) VERS="4" VR="CS" VM="1" Keyword="AcquisitionTimeSynchronized" Name="Acquisition Time Synchronized"
+(0018,1801) VERS="4" VR="SH" VM="1" Keyword="TimeSource" Name="Time Source"
+(0018,1802) VERS="4" VR="CS" VM="1" Keyword="TimeDistributionProtocol" Name="Time Distribution Protocol"
+(0018,1803) VERS="4" VR="LO" VM="1" Keyword="NTPSourceAddress" Name="NTP Source Address"
+(0018,2001) VERS="4" VR="IS" VM="1-n" Keyword="PageNumberVector" Name="Page Number Vector"
+(0018,2002) VERS="4" VR="SH" VM="1-n" Keyword="FrameLabelVector" Name="Frame Label Vector"
+(0018,2003) VERS="4" VR="DS" VM="1-n" Keyword="FramePrimaryAngleVector" Name="Frame Primary Angle Vector"
+(0018,2004) VERS="4" VR="DS" VM="1-n" Keyword="FrameSecondaryAngleVector" Name="Frame Secondary Angle Vector"
+(0018,2005) VERS="4" VR="DS" VM="1-n" Keyword="SliceLocationVector" Name="Slice Location Vector"
+(0018,2006) VERS="4" VR="SH" VM="1-n" Keyword="DisplayWindowLabelVector" Name="Display Window Label Vector"
+(0018,2010) VERS="4" VR="DS" VM="2" Keyword="NominalScannedPixelSpacing" Name="Nominal Scanned Pixel Spacing"
+(0018,2020) VERS="4" VR="CS" VM="1" Keyword="DigitizingDeviceTransportDirection" Name="Digitizing Device Transport Direction"
+(0018,2030) VERS="4" VR="DS" VM="1" Keyword="RotationOfScannedFilm" Name="Rotation of Scanned Film"
+(0018,3100) VERS="4" VR="CS" VM="1" Keyword="IVUSAcquisition" Name="IVUS Acquisition"
+(0018,3101) VERS="4" VR="DS" VM="1" Keyword="IVUSPullbackRate" Name="IVUS Pullback Rate"
+(0018,3102) VERS="4" VR="DS" VM="1" Keyword="IVUSGatedRate" Name="IVUS Gated Rate"
+(0018,3103) VERS="4" VR="IS" VM="1" Keyword="IVUSPullbackStartFrameNumber" Name="IVUS Pullback Start Frame Number"
+(0018,3104) VERS="4" VR="IS" VM="1" Keyword="IVUSPullbackStopFrameNumber" Name="IVUS Pullback Stop Frame Number"
+(0018,3105) VERS="4" VR="IS" VM="1-n" Keyword="LesionNumber" Name="Lesion Number "
+(0018,4000) VERS="4RET" VR="LT" VM="1" Keyword="AcquisitionComments" Name="Acquisition Comments"
+(0018,5000) VERS="4" VR="SH" VM="1-n" Keyword="OutputPower" Name="Output Power"
+(0018,5010) VERS="4" VR="LO" VM="1-n" Keyword="TransducerData" Name="Transducer Data"
+(0018,5012) VERS="4" VR="DS" VM="1" Keyword="FocusDepth" Name="Focus Depth"
+(0018,5020) VERS="4" VR="LO" VM="1" Keyword="ProcessingFunction" Name="Processing Function"
+(0018,5021) VERS="4RET" VR="LO" VM="1" Keyword="PostprocessingFunction" Name="Postprocessing Function"
+(0018,5022) VERS="4" VR="DS" VM="1" Keyword="MechanicalIndex" Name="Mechanical Index"
+(0018,5024) VERS="4" VR="DS" VM="1" Keyword="BoneThermalIndex" Name="Bone Thermal Index"
+(0018,5026) VERS="4" VR="DS" VM="1" Keyword="CranialThermalIndex" Name="Cranial Thermal Index"
+(0018,5027) VERS="4" VR="DS" VM="1" Keyword="SoftTissueThermalIndex" Name="Soft Tissue Thermal Index"
+(0018,5028) VERS="4" VR="DS" VM="1" Keyword="SoftTissueFocusThermalIndex" Name="Soft Tissue-focus Thermal Index"
+(0018,5029) VERS="4" VR="DS" VM="1" Keyword="SoftTissueSurfaceThermalIndex" Name="Soft Tissue-surface Thermal Index"
+(0018,5030) VERS="4RET" VR="DS" VM="1" Keyword="DynamicRange" Name="Dynamic Range"
+(0018,5040) VERS="4RET" VR="DS" VM="1" Keyword="TotalGain" Name="Total Gain"
+(0018,5050) VERS="4" VR="IS" VM="1" Keyword="DepthOfScanField" Name="Depth of Scan Field"
+(0018,5100) VERS="4" VR="CS" VM="1" Keyword="PatientPosition" Name="Patient Position"
+(0018,5101) VERS="4" VR="CS" VM="1" Keyword="ViewPosition" Name="View Position"
+(0018,5104) VERS="4" VR="SQ" VM="1" Keyword="ProjectionEponymousNameCodeSequence" Name="Projection Eponymous Name Code Sequence"
+(0018,5210) VERS="4RET" VR="DS" VM="6" Keyword="ImageTransformationMatrix" Name="Image Transformation Matrix"
+(0018,5212) VERS="4RET" VR="DS" VM="3" Keyword="ImageTranslationVector" Name="Image Translation Vector"
+(0018,6000) VERS="4" VR="DS" VM="1" Keyword="Sensitivity" Name="Sensitivity"
+(0018,6011) VERS="4" VR="SQ" VM="1" Keyword="SequenceOfUltrasoundRegions" Name="Sequence of Ultrasound Regions"
+(0018,6012) VERS="4" VR="US" VM="1" Keyword="RegionSpatialFormat" Name="Region Spatial Format"
+(0018,6014) VERS="4" VR="US" VM="1" Keyword="RegionDataType" Name="Region Data Type"
+(0018,6016) VERS="4" VR="UL" VM="1" Keyword="RegionFlags" Name="Region Flags"
+(0018,6018) VERS="4" VR="UL" VM="1" Keyword="RegionLocationMinX0" Name="Region Location Min X0"
+(0018,601A) VERS="4" VR="UL" VM="1" Keyword="RegionLocationMinY0" Name="Region Location Min Y0"
+(0018,601C) VERS="4" VR="UL" VM="1" Keyword="RegionLocationMaxX1" Name="Region Location Max X1"
+(0018,601E) VERS="4" VR="UL" VM="1" Keyword="RegionLocationMaxY1" Name="Region Location Max Y1"
+(0018,6020) VERS="4" VR="SL" VM="1" Keyword="ReferencePixelX0" Name="Reference Pixel X0"
+(0018,6022) VERS="4" VR="SL" VM="1" Keyword="ReferencePixelY0" Name="Reference Pixel Y0"
+(0018,6024) VERS="4" VR="US" VM="1" Keyword="PhysicalUnitsXDirection" Name="Physical Units X Direction"
+(0018,6026) VERS="4" VR="US" VM="1" Keyword="PhysicalUnitsYDirection" Name="Physical Units Y Direction"
+(0018,6028) VERS="4" VR="FD" VM="1" Keyword="ReferencePixelPhysicalValueX" Name="Reference Pixel Physical Value X"
+(0018,602A) VERS="4" VR="FD" VM="1" Keyword="ReferencePixelPhysicalValueY" Name="Reference Pixel Physical Value Y"
+(0018,602C) VERS="4" VR="FD" VM="1" Keyword="PhysicalDeltaX" Name="Physical Delta X"
+(0018,602E) VERS="4" VR="FD" VM="1" Keyword="PhysicalDeltaY" Name="Physical Delta Y"
+(0018,6030) VERS="4" VR="UL" VM="1" Keyword="TransducerFrequency" Name="Transducer Frequency"
+(0018,6031) VERS="4" VR="CS" VM="1" Keyword="TransducerType" Name="Transducer Type"
+(0018,6032) VERS="4" VR="UL" VM="1" Keyword="PulseRepetitionFrequency" Name="Pulse Repetition Frequency"
+(0018,6034) VERS="4" VR="FD" VM="1" Keyword="DopplerCorrectionAngle" Name="Doppler Correction Angle"
+(0018,6036) VERS="4" VR="FD" VM="1" Keyword="SteeringAngle" Name="Steering Angle"
+(0018,6038) VERS="4RET" VR="UL" VM="1" Keyword="DopplerSampleVolumeXPositionRetired" Name="Doppler Sample Volume X Position (Retired)"
+(0018,6039) VERS="4" VR="SL" VM="1" Keyword="DopplerSampleVolumeXPosition" Name="Doppler Sample Volume X Position"
+(0018,603A) VERS="4RET" VR="UL" VM="1" Keyword="DopplerSampleVolumeYPositionRetired" Name="Doppler Sample Volume Y Position (Retired)"
+(0018,603B) VERS="4" VR="SL" VM="1" Keyword="DopplerSampleVolumeYPosition" Name="Doppler Sample Volume Y Position"
+(0018,603C) VERS="4RET" VR="UL" VM="1" Keyword="TMLinePositionX0Retired" Name="TM-Line Position X0 (Retired)"
+(0018,603D) VERS="4" VR="SL" VM="1" Keyword="TMLinePositionX0" Name="TM-Line Position X0"
+(0018,603E) VERS="4RET" VR="UL" VM="1" Keyword="TMLinePositionY0Retired" Name="TM-Line Position Y0 (Retired)"
+(0018,603F) VERS="4" VR="SL" VM="1" Keyword="TMLinePositionY0" Name="TM-Line Position Y0"
+(0018,6040) VERS="4RET" VR="UL" VM="1" Keyword="TMLinePositionX1Retired" Name="TM-Line Position X1 (Retired)"
+(0018,6041) VERS="4" VR="SL" VM="1" Keyword="TMLinePositionX1" Name="TM-Line Position X1"
+(0018,6042) VERS="4RET" VR="UL" VM="1" Keyword="TMLinePositionY1Retired" Name="TM-Line Position Y1 (Retired)"
+(0018,6043) VERS="4" VR="SL" VM="1" Keyword="TMLinePositionY1" Name="TM-Line Position Y1"
+(0018,6044) VERS="4" VR="US" VM="1" Keyword="PixelComponentOrganization" Name="Pixel Component Organization"
+(0018,6046) VERS="4" VR="UL" VM="1" Keyword="PixelComponentMask" Name="Pixel Component Mask"
+(0018,6048) VERS="4" VR="UL" VM="1" Keyword="PixelComponentRangeStart" Name="Pixel Component Range Start"
+(0018,604A) VERS="4" VR="UL" VM="1" Keyword="PixelComponentRangeStop" Name="Pixel Component Range Stop"
+(0018,604C) VERS="4" VR="US" VM="1" Keyword="PixelComponentPhysicalUnits" Name="Pixel Component Physical Units"
+(0018,604E) VERS="4" VR="US" VM="1" Keyword="PixelComponentDataType" Name="Pixel Component Data Type"
+(0018,6050) VERS="4" VR="UL" VM="1" Keyword="NumberOfTableBreakPoints" Name="Number of Table Break Points"
+(0018,6052) VERS="4" VR="UL" VM="1-n" Keyword="TableOfXBreakPoints" Name="Table of X Break Points"
+(0018,6054) VERS="4" VR="FD" VM="1-n" Keyword="TableOfYBreakPoints" Name="Table of Y Break Points"
+(0018,6056) VERS="4" VR="UL" VM="1" Keyword="NumberOfTableEntries" Name="Number of Table Entries"
+(0018,6058) VERS="4" VR="UL" VM="1-n" Keyword="TableOfPixelValues" Name="Table of Pixel Values"
+(0018,605A) VERS="4" VR="FL" VM="1-n" Keyword="TableOfParameterValues" Name="Table of Parameter Values"
+(0018,6060) VERS="4" VR="FL" VM="1-n" Keyword="RWaveTimeVector" Name="R Wave Time Vector"
+(0018,7000) VERS="4" VR="CS" VM="1" Keyword="DetectorConditionsNominalFlag" Name="Detector Conditions Nominal Flag "
+(0018,7001) VERS="4" VR="DS" VM="1" Keyword="DetectorTemperature" Name="Detector Temperature"
+(0018,7004) VERS="4" VR="CS" VM="1" Keyword="DetectorType" Name="Detector Type"
+(0018,7005) VERS="4" VR="CS" VM="1" Keyword="DetectorConfiguration" Name="Detector Configuration"
+(0018,7006) VERS="4" VR="LT" VM="1" Keyword="DetectorDescription" Name="Detector Description"
+(0018,7008) VERS="4" VR="LT" VM="1" Keyword="DetectorMode" Name="Detector Mode"
+(0018,700A) VERS="4" VR="SH" VM="1" Keyword="DetectorID" Name="Detector ID"
+(0018,700C) VERS="4" VR="DA" VM="1" Keyword="DateOfLastDetectorCalibration" Name="Date of Last Detector Calibration "
+(0018,700E) VERS="4" VR="TM" VM="1" Keyword="TimeOfLastDetectorCalibration" Name="Time of Last Detector Calibration"
+(0018,7010) VERS="4" VR="IS" VM="1" Keyword="ExposuresOnDetectorSinceLastCalibration" Name="Exposures on Detector Since Last Calibration "
+(0018,7011) VERS="4" VR="IS" VM="1" Keyword="ExposuresOnDetectorSinceManufactured" Name="Exposures on Detector Since Manufactured "
+(0018,7012) VERS="4" VR="DS" VM="1" Keyword="DetectorTimeSinceLastExposure" Name="Detector Time Since Last Exposure "
+(0018,7014) VERS="4" VR="DS" VM="1" Keyword="DetectorActiveTime" Name="Detector Active Time "
+(0018,7016) VERS="4" VR="DS" VM="1" Keyword="DetectorActivationOffsetFromExposure" Name="Detector Activation Offset From Exposure"
+(0018,701A) VERS="4" VR="DS" VM="2" Keyword="DetectorBinning" Name="Detector Binning "
+(0018,7020) VERS="4" VR="DS" VM="2" Keyword="DetectorElementPhysicalSize" Name="Detector Element Physical Size"
+(0018,7022) VERS="4" VR="DS" VM="2" Keyword="DetectorElementSpacing" Name="Detector Element Spacing"
+(0018,7024) VERS="4" VR="CS" VM="1" Keyword="DetectorActiveShape" Name="Detector Active Shape"
+(0018,7026) VERS="4" VR="DS" VM="1-2" Keyword="DetectorActiveDimensions" Name="Detector Active Dimension(s)"
+(0018,7028) VERS="4" VR="DS" VM="2" Keyword="DetectorActiveOrigin" Name="Detector Active Origin"
+(0018,702A) VERS="4" VR="LO" VM="1" Keyword="DetectorManufacturerName" Name="Detector Manufacturer Name"
+(0018,702B) VERS="4" VR="LO" VM="1" Keyword="DetectorManufacturerModelName" Name="Detector Manufacturer�s Model Name"
+(0018,7030) VERS="4" VR="DS" VM="2" Keyword="FieldOfViewOrigin" Name="Field of View Origin"
+(0018,7032) VERS="4" VR="DS" VM="1" Keyword="FieldOfViewRotation" Name="Field of View Rotation"
+(0018,7034) VERS="4" VR="CS" VM="1" Keyword="FieldOfViewHorizontalFlip" Name="Field of View Horizontal Flip"
+(0018,7036) VERS="4" VR="FL" VM="2" Keyword="PixelDataAreaOriginRelativeToFOV" Name="Pixel Data Area Origin Relative To FOV"
+(0018,7038) VERS="4" VR="FL" VM="1" Keyword="PixelDataAreaRotationAngleRelativeToFOV" Name="Pixel Data Area Rotation Angle Relative To FOV"
+(0018,7040) VERS="4" VR="LT" VM="1" Keyword="GridAbsorbingMaterial" Name="Grid Absorbing Material"
+(0018,7041) VERS="4" VR="LT" VM="1" Keyword="GridSpacingMaterial" Name="Grid Spacing Material"
+(0018,7042) VERS="4" VR="DS" VM="1" Keyword="GridThickness" Name="Grid Thickness"
+(0018,7044) VERS="4" VR="DS" VM="1" Keyword="GridPitch" Name="Grid Pitch"
+(0018,7046) VERS="4" VR="IS" VM="2" Keyword="GridAspectRatio" Name="Grid Aspect Ratio"
+(0018,7048) VERS="4" VR="DS" VM="1" Keyword="GridPeriod" Name="Grid Period"
+(0018,704C) VERS="4" VR="DS" VM="1" Keyword="GridFocalDistance" Name="Grid Focal Distance"
+(0018,7050) VERS="4" VR="CS" VM="1-n" Keyword="FilterMaterial" Name="Filter Material"
+(0018,7052) VERS="4" VR="DS" VM="1-n" Keyword="FilterThicknessMinimum" Name="Filter Thickness Minimum"
+(0018,7054) VERS="4" VR="DS" VM="1-n" Keyword="FilterThicknessMaximum" Name="Filter Thickness Maximum"
+(0018,7056) VERS="4" VR="FL" VM="1-n" Keyword="FilterBeamPathLengthMinimum" Name="Filter Beam Path Length Minimum"
+(0018,7058) VERS="4" VR="FL" VM="1-n" Keyword="FilterBeamPathLengthMaximum" Name="Filter Beam Path Length Maximum"
+(0018,7060) VERS="4" VR="CS" VM="1" Keyword="ExposureControlMode" Name="Exposure Control Mode"
+(0018,7062) VERS="4" VR="LT" VM="1" Keyword="ExposureControlModeDescription" Name="Exposure Control Mode Description"
+(0018,7064) VERS="4" VR="CS" VM="1" Keyword="ExposureStatus" Name="Exposure Status"
+(0018,7065) VERS="4" VR="DS" VM="1" Keyword="PhototimerSetting" Name="Phototimer Setting"
+(0018,8150) VERS="4" VR="DS" VM="1" Keyword="ExposureTimeInuS" Name="Exposure Time in �S"
+(0018,8151) VERS="4" VR="DS" VM="1" Keyword="XRayTubeCurrentInuA" Name="X-Ray Tube Current in �A"
+(0018,9004) VERS="4" VR="CS" VM="1" Keyword="ContentQualification" Name="Content Qualification"
+(0018,9005) VERS="4" VR="SH" VM="1" Keyword="PulseSequenceName" Name="Pulse Sequence Name"
+(0018,9006) VERS="4" VR="SQ" VM="1" Keyword="MRImagingModifierSequence" Name="MR Imaging Modifier Sequence"
+(0018,9008) VERS="4" VR="CS" VM="1" Keyword="EchoPulseSequence" Name="Echo Pulse Sequence"
+(0018,9009) VERS="4" VR="CS" VM="1" Keyword="InversionRecovery" Name="Inversion Recovery"
+(0018,9010) VERS="4" VR="CS" VM="1" Keyword="FlowCompensation" Name="Flow Compensation"
+(0018,9011) VERS="4" VR="CS" VM="1" Keyword="MultipleSpinEcho" Name="Multiple Spin Echo"
+(0018,9012) VERS="4" VR="CS" VM="1" Keyword="MultiPlanarExcitation" Name="Multi-planar Excitation"
+(0018,9014) VERS="4" VR="CS" VM="1" Keyword="PhaseContrast" Name="Phase Contrast"
+(0018,9015) VERS="4" VR="CS" VM="1" Keyword="TimeOfFlightContrast" Name="Time of Flight Contrast"
+(0018,9016) VERS="4" VR="CS" VM="1" Keyword="Spoiling" Name="Spoiling"
+(0018,9017) VERS="4" VR="CS" VM="1" Keyword="SteadyStatePulseSequence" Name="Steady State Pulse Sequence"
+(0018,9018) VERS="4" VR="CS" VM="1" Keyword="EchoPlanarPulseSequence" Name="Echo Planar Pulse Sequence"
+(0018,9019) VERS="4" VR="FD" VM="1" Keyword="TagAngleFirstAxis" Name="Tag Angle First Axis"
+(0018,9020) VERS="4" VR="CS" VM="1" Keyword="MagnetizationTransfer" Name="Magnetization Transfer"
+(0018,9021) VERS="4" VR="CS" VM="1" Keyword="T2Preparation" Name="T2 Preparation"
+(0018,9022) VERS="4" VR="CS" VM="1" Keyword="BloodSignalNulling" Name="Blood Signal Nulling"
+(0018,9024) VERS="4" VR="CS" VM="1" Keyword="SaturationRecovery" Name="Saturation Recovery"
+(0018,9025) VERS="4" VR="CS" VM="1" Keyword="SpectrallySelectedSuppression" Name="Spectrally Selected Suppression"
+(0018,9026) VERS="4" VR="CS" VM="1" Keyword="SpectrallySelectedExcitation" Name="Spectrally Selected Excitation"
+(0018,9027) VERS="4" VR="CS" VM="1" Keyword="SpatialPresaturation" Name="Spatial Pre-saturation"
+(0018,9028) VERS="4" VR="CS" VM="1" Keyword="Tagging" Name="Tagging"
+(0018,9029) VERS="4" VR="CS" VM="1" Keyword="OversamplingPhase" Name="Oversampling Phase"
+(0018,9030) VERS="4" VR="FD" VM="1" Keyword="TagSpacingFirstDimension" Name="Tag Spacing First Dimension"
+(0018,9032) VERS="4" VR="CS" VM="1" Keyword="GeometryOfKSpaceTraversal" Name="Geometry of k-Space Traversal"
+(0018,9033) VERS="4" VR="CS" VM="1" Keyword="SegmentedKSpaceTraversal" Name="Segmented k-Space Traversal"
+(0018,9034) VERS="4" VR="CS" VM="1" Keyword="RectilinearPhaseEncodeReordering" Name="Rectilinear Phase Encode Reordering"
+(0018,9035) VERS="4" VR="FD" VM="1" Keyword="TagThickness" Name="Tag Thickness"
+(0018,9036) VERS="4" VR="CS" VM="1" Keyword="PartialFourierDirection" Name="Partial Fourier Direction"
+(0018,9037) VERS="4" VR="CS" VM="1" Keyword="CardiacSynchronizationTechnique" Name="Cardiac Synchronization Technique"
+(0018,9041) VERS="4" VR="LO" VM="1" Keyword="ReceiveCoilManufacturerName" Name="Receive Coil Manufacturer Name"
+(0018,9042) VERS="4" VR="SQ" VM="1" Keyword="MRReceiveCoilSequence" Name="MR Receive Coil Sequence"
+(0018,9043) VERS="4" VR="CS" VM="1" Keyword="ReceiveCoilType" Name="Receive Coil Type "
+(0018,9044) VERS="4" VR="CS" VM="1" Keyword="QuadratureReceiveCoil" Name="Quadrature Receive Coil "
+(0018,9045) VERS="4" VR="SQ" VM="1" Keyword="MultiCoilDefinitionSequence" Name="Multi-Coil Definition Sequence"
+(0018,9046) VERS="4" VR="LO" VM="1" Keyword="MultiCoilConfiguration" Name="Multi-Coil Configuration "
+(0018,9047) VERS="4" VR="SH" VM="1" Keyword="MultiCoilElementName" Name="Multi-Coil Element Name"
+(0018,9048) VERS="4" VR="CS" VM="1" Keyword="MultiCoilElementUsed" Name="Multi-Coil Element Used"
+(0018,9049) VERS="4" VR="SQ" VM="1" Keyword="MRTransmitCoilSequence" Name="MR Transmit Coil Sequence"
+(0018,9050) VERS="4" VR="LO" VM="1" Keyword="TransmitCoilManufacturerName" Name="Transmit Coil Manufacturer Name"
+(0018,9051) VERS="4" VR="CS" VM="1" Keyword="TransmitCoilType" Name="Transmit Coil Type"
+(0018,9052) VERS="4" VR="FD" VM="1-2" Keyword="SpectralWidth" Name="Spectral Width"
+(0018,9053) VERS="4" VR="FD" VM="1-2" Keyword="ChemicalShiftReference" Name="Chemical Shift Reference"
+(0018,9054) VERS="4" VR="CS" VM="1" Keyword="VolumeLocalizationTechnique" Name="Volume Localization Technique"
+(0018,9058) VERS="4" VR="US" VM="1" Keyword="MRAcquisitionFrequencyEncodingSteps" Name="MR Acquisition Frequency Encoding Steps"
+(0018,9059) VERS="4" VR="CS" VM="1" Keyword="Decoupling" Name="De-coupling"
+(0018,9060) VERS="4" VR="CS" VM="1-2" Keyword="DecoupledNucleus" Name="De-coupled Nucleus"
+(0018,9061) VERS="4" VR="FD" VM="1-2" Keyword="DecouplingFrequency" Name="De-coupling Frequency"
+(0018,9062) VERS="4" VR="CS" VM="1" Keyword="DecouplingMethod" Name="De-coupling Method"
+(0018,9063) VERS="4" VR="FD" VM="1-2" Keyword="DecouplingChemicalShiftReference" Name="De-coupling Chemical Shift Reference"
+(0018,9064) VERS="4" VR="CS" VM="1" Keyword="KSpaceFiltering" Name="k-space Filtering"
+(0018,9065) VERS="4" VR="CS" VM="1-2" Keyword="TimeDomainFiltering" Name="Time Domain Filtering"
+(0018,9066) VERS="4" VR="US" VM="1-2" Keyword="NumberOfZeroFills" Name="Number of Zero Fills"
+(0018,9067) VERS="4" VR="CS" VM="1" Keyword="BaselineCorrection" Name="Baseline Correction"
+(0018,9069) VERS="4" VR="FD" VM="1" Keyword="ParallelReductionFactorInPlane" Name="Parallel Reduction Factor In-plane"
+(0018,9070) VERS="4" VR="FD" VM="1" Keyword="CardiacRRIntervalSpecified" Name="Cardiac R-R Interval Specified"
+(0018,9073) VERS="4" VR="FD" VM="1" Keyword="AcquisitionDuration" Name="Acquisition Duration"
+(0018,9074) VERS="4" VR="DT" VM="1" Keyword="FrameAcquisitionDateTime" Name="Frame Acquisition DateTime"
+(0018,9075) VERS="4" VR="CS" VM="1" Keyword="DiffusionDirectionality" Name="Diffusion Directionality"
+(0018,9076) VERS="4" VR="SQ" VM="1" Keyword="DiffusionGradientDirectionSequence" Name="Diffusion Gradient Direction Sequence"
+(0018,9077) VERS="4" VR="CS" VM="1" Keyword="ParallelAcquisition" Name="Parallel Acquisition"
+(0018,9078) VERS="4" VR="CS" VM="1" Keyword="ParallelAcquisitionTechnique" Name="Parallel Acquisition Technique"
+(0018,9079) VERS="4" VR="FD" VM="1-n" Keyword="InversionTimes" Name="Inversion Times"
+(0018,9080) VERS="4" VR="ST" VM="1" Keyword="MetaboliteMapDescription" Name="Metabolite Map Description"
+(0018,9081) VERS="4" VR="CS" VM="1" Keyword="PartialFourier" Name="Partial Fourier"
+(0018,9082) VERS="4" VR="FD" VM="1" Keyword="EffectiveEchoTime" Name="Effective Echo Time"
+(0018,9083) VERS="4" VR="SQ" VM="1" Keyword="MetaboliteMapCodeSequence" Name="Metabolite Map Code Sequence"
+(0018,9084) VERS="4" VR="SQ" VM="1" Keyword="ChemicalShiftSequence" Name="Chemical Shift Sequence"
+(0018,9085) VERS="4" VR="CS" VM="1" Keyword="CardiacSignalSource" Name="Cardiac Signal Source"
+(0018,9087) VERS="4" VR="FD" VM="1" Keyword="DiffusionBValue" Name="Diffusion b-value"
+(0018,9089) VERS="4" VR="FD" VM="3" Keyword="DiffusionGradientOrientation" Name="Diffusion Gradient Orientation"
+(0018,9090) VERS="4" VR="FD" VM="3" Keyword="VelocityEncodingDirection" Name="Velocity Encoding Direction"
+(0018,9091) VERS="4" VR="FD" VM="1" Keyword="VelocityEncodingMinimumValue" Name="Velocity Encoding Minimum Value"
+(0018,9092) VERS="4" VR="SQ" VM="1" Keyword="VelocityEncodingAcquisitionSequence" Name="Velocity Encoding Acquisition Sequence"
+(0018,9093) VERS="4" VR="US" VM="1" Keyword="NumberOfKSpaceTrajectories" Name="Number of k-Space Trajectories"
+(0018,9094) VERS="4" VR="CS" VM="1" Keyword="CoverageOfKSpace" Name="Coverage of k-Space"
+(0018,9095) VERS="4" VR="UL" VM="1" Keyword="SpectroscopyAcquisitionPhaseRows" Name="Spectroscopy Acquisition Phase Rows"
+(0018,9096) VERS="4RET" VR="FD" VM="1" Keyword="ParallelReductionFactorInPlaneRetired" Name="Parallel Reduction Factor In-plane (Retired)"
+(0018,9098) VERS="4" VR="FD" VM="1-2" Keyword="TransmitterFrequency" Name="Transmitter Frequency"
+(0018,9100) VERS="4" VR="CS" VM="1-2" Keyword="ResonantNucleus" Name="Resonant Nucleus"
+(0018,9101) VERS="4" VR="CS" VM="1" Keyword="FrequencyCorrection" Name="Frequency Correction"
+(0018,9103) VERS="4" VR="SQ" VM="1" Keyword="MRSpectroscopyFOVGeometrySequence" Name="MR Spectroscopy FOV/Geometry Sequence"
+(0018,9104) VERS="4" VR="FD" VM="1" Keyword="SlabThickness" Name="Slab Thickness"
+(0018,9105) VERS="4" VR="FD" VM="3" Keyword="SlabOrientation" Name="Slab Orientation"
+(0018,9106) VERS="4" VR="FD" VM="3" Keyword="MidSlabPosition" Name="Mid Slab Position"
+(0018,9107) VERS="4" VR="SQ" VM="1" Keyword="MRSpatialSaturationSequence" Name="MR Spatial Saturation Sequence"
+(0018,9112) VERS="4" VR="SQ" VM="1" Keyword="MRTimingAndRelatedParametersSequence" Name="MR Timing and Related Parameters Sequence"
+(0018,9114) VERS="4" VR="SQ" VM="1" Keyword="MREchoSequence" Name="MR Echo Sequence"
+(0018,9115) VERS="4" VR="SQ" VM="1" Keyword="MRModifierSequence" Name="MR Modifier Sequence"
+(0018,9117) VERS="4" VR="SQ" VM="1" Keyword="MRDiffusionSequence" Name="MR Diffusion Sequence"
+(0018,9118) VERS="4" VR="SQ" VM="1" Keyword="CardiacSynchronizationSequence" Name="Cardiac Synchronization Sequence"
+(0018,9119) VERS="4" VR="SQ" VM="1" Keyword="MRAveragesSequence" Name="MR Averages Sequence"
+(0018,9125) VERS="4" VR="SQ" VM="1" Keyword="MRFOVGeometrySequence" Name="MR FOV/Geometry Sequence"
+(0018,9126) VERS="4" VR="SQ" VM="1" Keyword="VolumeLocalizationSequence" Name="Volume Localization Sequence"
+(0018,9127) VERS="4" VR="UL" VM="1" Keyword="SpectroscopyAcquisitionDataColumns" Name="Spectroscopy Acquisition Data Columns"
+(0018,9147) VERS="4" VR="CS" VM="1" Keyword="DiffusionAnisotropyType" Name="Diffusion Anisotropy Type"
+(0018,9151) VERS="4" VR="DT" VM="1" Keyword="FrameReferenceDateTime" Name="Frame Reference DateTime"
+(0018,9152) VERS="4" VR="SQ" VM="1" Keyword="MRMetaboliteMapSequence" Name="MR Metabolite Map Sequence"
+(0018,9155) VERS="4" VR="FD" VM="1" Keyword="ParallelReductionFactorOutOfPlane" Name="Parallel Reduction Factor out-of-plane"
+(0018,9159) VERS="4" VR="UL" VM="1" Keyword="SpectroscopyAcquisitionOutOfPlanePhaseSteps" Name="Spectroscopy Acquisition Out-of-plane Phase Steps"
+(0018,9166) VERS="4RET" VR="CS" VM="1" Keyword="BulkMotionStatus" Name="Bulk Motion Status"
+(0018,9168) VERS="4" VR="FD" VM="1" Keyword="ParallelReductionFactorSecondInPlane" Name="Parallel Reduction Factor Second In-plane"
+(0018,9169) VERS="4" VR="CS" VM="1" Keyword="CardiacBeatRejectionTechnique" Name="Cardiac Beat Rejection Technique"
+(0018,9170) VERS="4" VR="CS" VM="1" Keyword="RespiratoryMotionCompensationTechnique" Name="Respiratory Motion Compensation Technique"
+(0018,9171) VERS="4" VR="CS" VM="1" Keyword="RespiratorySignalSource" Name="Respiratory Signal Source"
+(0018,9172) VERS="4" VR="CS" VM="1" Keyword="BulkMotionCompensationTechnique" Name="Bulk Motion Compensation Technique"
+(0018,9173) VERS="4" VR="CS" VM="1" Keyword="BulkMotionSignalSource" Name="Bulk Motion Signal Source"
+(0018,9174) VERS="4" VR="CS" VM="1" Keyword="ApplicableSafetyStandardAgency" Name="Applicable Safety Standard Agency"
+(0018,9175) VERS="4" VR="LO" VM="1" Keyword="ApplicableSafetyStandardDescription" Name="Applicable Safety Standard Description"
+(0018,9176) VERS="4" VR="SQ" VM="1" Keyword="OperatingModeSequence" Name="Operating Mode Sequence"
+(0018,9177) VERS="4" VR="CS" VM="1" Keyword="OperatingModeType" Name="Operating Mode Type"
+(0018,9178) VERS="4" VR="CS" VM="1" Keyword="OperatingMode" Name="Operating Mode"
+(0018,9179) VERS="4" VR="CS" VM="1" Keyword="SpecificAbsorptionRateDefinition" Name="Specific Absorption Rate Definition"
+(0018,9180) VERS="4" VR="CS" VM="1" Keyword="GradientOutputType" Name="Gradient Output Type"
+(0018,9181) VERS="4" VR="FD" VM="1" Keyword="SpecificAbsorptionRateValue" Name="Specific Absorption Rate Value"
+(0018,9182) VERS="4" VR="FD" VM="1" Keyword="GradientOutput" Name="Gradient Output"
+(0018,9183) VERS="4" VR="CS" VM="1" Keyword="FlowCompensationDirection" Name="Flow Compensation Direction"
+(0018,9184) VERS="4" VR="FD" VM="1" Keyword="TaggingDelay" Name="Tagging Delay"
+(0018,9185) VERS="4" VR="ST" VM="1" Keyword="RespiratoryMotionCompensationTechniqueDescription" Name="Respiratory Motion Compensation Technique Description"
+(0018,9186) VERS="4" VR="SH" VM="1" Keyword="RespiratorySignalSourceID" Name="Respiratory Signal Source ID"
+(0018,9195) VERS="4RET" VR="FD" VM="1" Keyword="ChemicalShiftMinimumIntegrationLimitInHz" Name="Chemical Shift Minimum Integration Limit in Hz"
+(0018,9196) VERS="4RET" VR="FD" VM="1" Keyword="ChemicalShiftMaximumIntegrationLimitInHz" Name="Chemical Shift Maximum Integration Limit in Hz"
+(0018,9197) VERS="4" VR="SQ" VM="1" Keyword="MRVelocityEncodingSequence" Name="MR Velocity Encoding Sequence"
+(0018,9198) VERS="4" VR="CS" VM="1" Keyword="FirstOrderPhaseCorrection" Name="First Order Phase Correction"
+(0018,9199) VERS="4" VR="CS" VM="1" Keyword="WaterReferencedPhaseCorrection" Name="Water Referenced Phase Correction"
+(0018,9200) VERS="4" VR="CS" VM="1" Keyword="MRSpectroscopyAcquisitionType" Name="MR Spectroscopy Acquisition Type"
+(0018,9214) VERS="4" VR="CS" VM="1" Keyword="RespiratoryCyclePosition" Name="Respiratory Cycle Position"
+(0018,9217) VERS="4" VR="FD" VM="1" Keyword="VelocityEncodingMaximumValue" Name="Velocity Encoding Maximum Value"
+(0018,9218) VERS="4" VR="FD" VM="1" Keyword="TagSpacingSecondDimension" Name="Tag Spacing Second Dimension"
+(0018,9219) VERS="4" VR="SS" VM="1" Keyword="TagAngleSecondAxis" Name="Tag Angle Second Axis"
+(0018,9220) VERS="4" VR="FD" VM="1" Keyword="FrameAcquisitionDuration" Name="Frame Acquisition Duration"
+(0018,9226) VERS="4" VR="SQ" VM="1" Keyword="MRImageFrameTypeSequence" Name="MR Image Frame Type Sequence"
+(0018,9227) VERS="4" VR="SQ" VM="1" Keyword="MRSpectroscopyFrameTypeSequence" Name="MR Spectroscopy Frame Type Sequence"
+(0018,9231) VERS="4" VR="US" VM="1" Keyword="MRAcquisitionPhaseEncodingStepsInPlane" Name="MR Acquisition Phase Encoding Steps in-plane"
+(0018,9232) VERS="4" VR="US" VM="1" Keyword="MRAcquisitionPhaseEncodingStepsOutOfPlane" Name="MR Acquisition Phase Encoding Steps out-of-plane"
+(0018,9234) VERS="4" VR="UL" VM="1" Keyword="SpectroscopyAcquisitionPhaseColumns" Name="Spectroscopy Acquisition Phase Columns"
+(0018,9236) VERS="4" VR="CS" VM="1" Keyword="CardiacCyclePosition" Name="Cardiac Cycle Position"
+(0018,9239) VERS="4" VR="SQ" VM="1" Keyword="SpecificAbsorptionRateSequence" Name="Specific Absorption Rate Sequence"
+(0018,9240) VERS="4" VR="US" VM="1" Keyword="RFEchoTrainLength" Name="RF Echo Train Length"
+(0018,9241) VERS="4" VR="US" VM="1" Keyword="GradientEchoTrainLength" Name="Gradient Echo Train Length"
+(0018,9250) VERS="4" VR="CS" VM="1" Keyword="ArterialSpinLabelingContrast" Name="Arterial Spin Labeling Contrast"
+(0018,9251) VERS="4" VR="SQ" VM="1" Keyword="MRArterialSpinLabelingSequence" Name="MR Arterial Spin Labeling Sequence"
+(0018,9252) VERS="4" VR="LO" VM="1" Keyword="ASLTechniqueDescription" Name="ASL Technique Description"
+(0018,9253) VERS="4" VR="US" VM="1" Keyword="ASLSlabNumber" Name="ASL Slab Number"
+(0018,9254) VERS="4" VR="FD " VM="1 " Keyword="ASLSlabThickness" Name="ASL Slab Thickness"
+(0018,9255) VERS="4" VR="FD " VM="3 " Keyword="ASLSlabOrientation" Name="ASL Slab Orientation"
+(0018,9256) VERS="4" VR="FD " VM="3" Keyword="ASLMidSlabPosition" Name="ASL Mid Slab Position"
+(0018,9257) VERS="4" VR="CS" VM="1 " Keyword="ASLContext" Name="ASL Context"
+(0018,9258) VERS="4" VR="UL" VM="1" Keyword="ASLPulseTrainDuration" Name="ASL Pulse Train Duration"
+(0018,9259) VERS="4" VR="CS" VM="1 " Keyword="ASLCrusherFlag" Name="ASL Crusher Flag"
+(0018,925A) VERS="4" VR="FD" VM="1" Keyword="ASLCrusherFlow" Name="ASL Crusher Flow"
+(0018,925B) VERS="4" VR="LO" VM="1" Keyword="ASLCrusherDescription" Name="ASL Crusher Description"
+(0018,925C) VERS="4" VR="CS" VM="1 " Keyword="ASLBolusCutoffFlag" Name="ASL Bolus Cut-off Flag"
+(0018,925D) VERS="4" VR="SQ" VM="1" Keyword="ASLBolusCutoffTimingSequence" Name="ASL Bolus Cut-off Timing Sequence"
+(0018,925E) VERS="4" VR="LO" VM="1" Keyword="ASLBolusCutoffTechnique" Name="ASL Bolus Cut-off Technique"
+(0018,925F) VERS="4" VR="UL" VM="1" Keyword="ASLBolusCutoffDelayTime" Name="ASL Bolus Cut-off Delay Time"
+(0018,9260) VERS="4" VR="SQ" VM="1" Keyword="ASLSlabSequence" Name="ASL Slab Sequence"
+(0018,9295) VERS="4" VR="FD" VM="1" Keyword="ChemicalShiftMinimumIntegrationLimitInppm" Name="Chemical Shift Minimum Integration Limit in ppm"
+(0018,9296) VERS="4" VR="FD" VM="1" Keyword="ChemicalShiftMaximumIntegrationLimitInppm" Name="Chemical Shift Maximum Integration Limit in ppm"
+(0018,9301) VERS="4" VR="SQ" VM="1" Keyword="CTAcquisitionTypeSequence" Name="CT Acquisition Type Sequence"
+(0018,9302) VERS="4" VR="CS" VM="1" Keyword="AcquisitionType" Name="Acquisition Type"
+(0018,9303) VERS="4" VR="FD" VM="1" Keyword="TubeAngle" Name="Tube Angle"
+(0018,9304) VERS="4" VR="SQ" VM="1" Keyword="CTAcquisitionDetailsSequence" Name="CT Acquisition Details Sequence"
+(0018,9305) VERS="4" VR="FD" VM="1" Keyword="RevolutionTime" Name="Revolution Time"
+(0018,9306) VERS="4" VR="FD" VM="1" Keyword="SingleCollimationWidth" Name="Single Collimation Width"
+(0018,9307) VERS="4" VR="FD" VM="1" Keyword="TotalCollimationWidth" Name="Total Collimation Width"
+(0018,9308) VERS="4" VR="SQ" VM="1" Keyword="CTTableDynamicsSequence" Name="CT Table Dynamics Sequence"
+(0018,9309) VERS="4" VR="FD" VM="1" Keyword="TableSpeed" Name="Table Speed"
+(0018,9310) VERS="4" VR="FD" VM="1" Keyword="TableFeedPerRotation" Name="Table Feed per Rotation"
+(0018,9311) VERS="4" VR="FD" VM="1" Keyword="SpiralPitchFactor" Name="Spiral Pitch Factor"
+(0018,9312) VERS="4" VR="SQ" VM="1" Keyword="CTGeometrySequence" Name="CT Geometry Sequence"
+(0018,9313) VERS="4" VR="FD" VM="3" Keyword="DataCollectionCenterPatient" Name="Data Collection Center (Patient)"
+(0018,9314) VERS="4" VR="SQ" VM="1" Keyword="CTReconstructionSequence" Name="CT Reconstruction Sequence"
+(0018,9315) VERS="4" VR="CS" VM="1" Keyword="ReconstructionAlgorithm" Name="Reconstruction Algorithm"
+(0018,9316) VERS="4" VR="CS" VM="1" Keyword="ConvolutionKernelGroup" Name="Convolution Kernel Group"
+(0018,9317) VERS="4" VR="FD" VM="2" Keyword="ReconstructionFieldOfView" Name="Reconstruction Field of View"
+(0018,9318) VERS="4" VR="FD" VM="3" Keyword="ReconstructionTargetCenterPatient" Name="Reconstruction Target Center (Patient)"
+(0018,9319) VERS="4" VR="FD" VM="1" Keyword="ReconstructionAngle" Name="Reconstruction Angle"
+(0018,9320) VERS="4" VR="SH" VM="1" Keyword="ImageFilter" Name="Image Filter"
+(0018,9321) VERS="4" VR="SQ" VM="1" Keyword="CTExposureSequence" Name="CT Exposure Sequence"
+(0018,9322) VERS="4" VR="FD" VM="2" Keyword="ReconstructionPixelSpacing" Name="Reconstruction Pixel Spacing "
+(0018,9323) VERS="4" VR="CS" VM="1" Keyword="ExposureModulationType" Name="Exposure Modulation Type"
+(0018,9324) VERS="4" VR="FD" VM="1" Keyword="EstimatedDoseSaving" Name="Estimated Dose Saving"
+(0018,9325) VERS="4" VR="SQ" VM="1" Keyword="CTXRayDetailsSequence" Name="CT X-Ray Details Sequence"
+(0018,9326) VERS="4" VR="SQ" VM="1" Keyword="CTPositionSequence" Name="CT Position Sequence"
+(0018,9327) VERS="4" VR="FD" VM="1" Keyword="TablePosition" Name="Table Position"
+(0018,9328) VERS="4" VR="FD" VM="1" Keyword="ExposureTimeInms" Name="Exposure Time in ms"
+(0018,9329) VERS="4" VR="SQ" VM="1" Keyword="CTImageFrameTypeSequence" Name="CT Image Frame Type Sequence"
+(0018,9330) VERS="4" VR="FD" VM="1" Keyword="XRayTubeCurrentInmA" Name="X-Ray Tube Current in mA"
+(0018,9332) VERS="4" VR="FD" VM="1" Keyword="ExposureInmAs" Name="Exposure in mAs"
+(0018,9333) VERS="4" VR="CS" VM="1" Keyword="ConstantVolumeFlag" Name="Constant Volume Flag "
+(0018,9334) VERS="4" VR="CS" VM="1" Keyword="FluoroscopyFlag" Name="Fluoroscopy Flag"
+(0018,9335) VERS="4" VR="FD" VM="1" Keyword="DistanceSourceToDataCollectionCenter" Name="Distance Source to Data Collection Center"
+(0018,9337) VERS="4" VR="US" VM="1" Keyword="ContrastBolusAgentNumber" Name="Contrast/Bolus Agent Number"
+(0018,9338) VERS="4" VR="SQ" VM="1" Keyword="ContrastBolusIngredientCodeSequence" Name="Contrast/Bolus Ingredient Code Sequence"
+(0018,9340) VERS="4" VR="SQ" VM="1" Keyword="ContrastAdministrationProfileSequence" Name="Contrast Administration Profile Sequence"
+(0018,9341) VERS="4" VR="SQ" VM="1" Keyword="ContrastBolusUsageSequence" Name="Contrast/Bolus Usage Sequence"
+(0018,9342) VERS="4" VR="CS" VM="1" Keyword="ContrastBolusAgentAdministered" Name="Contrast/Bolus Agent Administered"
+(0018,9343) VERS="4" VR="CS" VM="1" Keyword="ContrastBolusAgentDetected" Name="Contrast/Bolus Agent Detected"
+(0018,9344) VERS="4" VR="CS" VM="1" Keyword="ContrastBolusAgentPhase" Name="Contrast/Bolus Agent Phase"
+(0018,9345) VERS="4" VR="FD" VM="1" Keyword="CTDIvol" Name="CTDIvol"
+(0018,9346) VERS="4" VR="SQ" VM="1" Keyword="CTDIPhantomTypeCodeSequence" Name="CTDI Phantom Type Code Sequence"
+(0018,9351) VERS="4" VR="FL" VM="1" Keyword="CalciumScoringMassFactorPatient" Name="Calcium Scoring Mass Factor Patient"
+(0018,9352) VERS="4" VR="FL" VM="3" Keyword="CalciumScoringMassFactorDevice" Name="Calcium Scoring Mass Factor Device"
+(0018,9353) VERS="4" VR="FL" VM="1" Keyword="EnergyWeightingFactor" Name="Energy Weighting Factor"
+(0018,9360) VERS="4" VR="SQ" VM="1" Keyword="CTAdditionalXRaySourceSequence" Name="CT Additional X-Ray Source Sequence"
+(0018,9401) VERS="4" VR="SQ" VM="1" Keyword="ProjectionPixelCalibrationSequence" Name="Projection Pixel Calibration Sequence"
+(0018,9402) VERS="4" VR="FL" VM="1" Keyword="DistanceSourceToIsocenter" Name="Distance Source to Isocenter"
+(0018,9403) VERS="4" VR="FL" VM="1" Keyword="DistanceObjectToTableTop" Name="Distance Object to Table Top"
+(0018,9404) VERS="4" VR="FL" VM="2" Keyword="ObjectPixelSpacingInCenterOfBeam" Name="Object Pixel Spacing in Center of Beam"
+(0018,9405) VERS="4" VR="SQ" VM="1" Keyword="PositionerPositionSequence" Name="Positioner Position Sequence"
+(0018,9406) VERS="4" VR="SQ" VM="1" Keyword="TablePositionSequence" Name="Table Position Sequence"
+(0018,9407) VERS="4" VR="SQ" VM="1" Keyword="CollimatorShapeSequence" Name="Collimator Shape Sequence"
+(0018,9410) VERS="4" VR="CS" VM="1" Keyword="PlanesInAcquisition" Name="Planes in Acquisition"
+(0018,9412) VERS="4" VR="SQ" VM="1" Keyword="XAXRFFrameCharacteristicsSequence" Name="XA/XRF Frame Characteristics Sequence"
+(0018,9417) VERS="4" VR="SQ" VM="1" Keyword="FrameAcquisitionSequence" Name="Frame Acquisition Sequence"
+(0018,9420) VERS="4" VR="CS" VM="1" Keyword="XRayReceptorType" Name="X-Ray Receptor Type"
+(0018,9423) VERS="4" VR="LO" VM="1" Keyword="AcquisitionProtocolName" Name="Acquisition Protocol Name"
+(0018,9424) VERS="4" VR="LT" VM="1" Keyword="AcquisitionProtocolDescription" Name="Acquisition Protocol Description"
+(0018,9425) VERS="4" VR="CS" VM="1" Keyword="ContrastBolusIngredientOpaque" Name="Contrast/Bolus Ingredient Opaque"
+(0018,9426) VERS="4" VR="FL" VM="1" Keyword="DistanceReceptorPlaneToDetectorHousing" Name="Distance Receptor Plane to Detector Housing"
+(0018,9427) VERS="4" VR="CS" VM="1" Keyword="IntensifierActiveShape" Name="Intensifier Active Shape"
+(0018,9428) VERS="4" VR="FL" VM="1-2" Keyword="IntensifierActiveDimensions" Name="Intensifier Active Dimension(s)"
+(0018,9429) VERS="4" VR="FL" VM="2" Keyword="PhysicalDetectorSize" Name="Physical Detector Size"
+(0018,9430) VERS="4" VR="FL" VM="2" Keyword="PositionOfIsocenterProjection" Name="Position of Isocenter Projection"
+(0018,9432) VERS="4" VR="SQ" VM="1" Keyword="FieldOfViewSequence" Name="Field of View Sequence"
+(0018,9433) VERS="4" VR="LO" VM="1" Keyword="FieldOfViewDescription" Name="Field of View Description"
+(0018,9434) VERS="4" VR="SQ" VM="1" Keyword="ExposureControlSensingRegionsSequence" Name="Exposure Control Sensing Regions Sequence"
+(0018,9435) VERS="4" VR="CS" VM="1" Keyword="ExposureControlSensingRegionShape" Name="Exposure Control Sensing Region Shape"
+(0018,9436) VERS="4" VR="SS" VM="1" Keyword="ExposureControlSensingRegionLeftVerticalEdge" Name="Exposure Control Sensing Region Left Vertical Edge"
+(0018,9437) VERS="4" VR="SS" VM="1" Keyword="ExposureControlSensingRegionRightVerticalEdge" Name="Exposure Control Sensing Region Right Vertical Edge"
+(0018,9438) VERS="4" VR="SS" VM="1" Keyword="ExposureControlSensingRegionUpperHorizontalEdge" Name="Exposure Control Sensing Region Upper Horizontal Edge"
+(0018,9439) VERS="4" VR="SS" VM="1" Keyword="ExposureControlSensingRegionLowerHorizontalEdge" Name="Exposure Control Sensing Region Lower Horizontal Edge"
+(0018,9440) VERS="4" VR="SS" VM="2" Keyword="CenterOfCircularExposureControlSensingRegion" Name="Center of Circular Exposure Control Sensing Region"
+(0018,9441) VERS="4" VR="US" VM="1" Keyword="RadiusOfCircularExposureControlSensingRegion" Name="Radius of Circular Exposure Control Sensing Region"
+(0018,9442) VERS="4" VR="SS" VM="2-n" Keyword="VerticesOfThePolygonalExposureControlSensingRegion" Name="Vertices of the Polygonal Exposure Control Sensing Region"
+(0018,9445) VERS="4RET" VR="" VM="" Keyword="" Name=""
+(0018,9447) VERS="4" VR="FL" VM="1" Keyword="ColumnAngulationPatient" Name="Column Angulation (Patient)"
+(0018,9449) VERS="4" VR="FL" VM="1" Keyword="BeamAngle" Name="Beam Angle"
+(0018,9451) VERS="4" VR="SQ" VM="1" Keyword="FrameDetectorParametersSequence" Name="Frame Detector Parameters Sequence"
+(0018,9452) VERS="4" VR="FL" VM="1" Keyword="CalculatedAnatomyThickness" Name="Calculated Anatomy Thickness"
+(0018,9455) VERS="4" VR="SQ" VM="1" Keyword="CalibrationSequence" Name="Calibration Sequence"
+(0018,9456) VERS="4" VR="SQ" VM="1" Keyword="ObjectThicknessSequence" Name="Object Thickness Sequence"
+(0018,9457) VERS="4" VR="CS" VM="1" Keyword="PlaneIdentification" Name="Plane Identification"
+(0018,9461) VERS="4" VR="FL" VM="1-2" Keyword="FieldOfViewDimensionsInFloat" Name="Field of View Dimension(s) in Float"
+(0018,9462) VERS="4" VR="SQ" VM="1" Keyword="IsocenterReferenceSystemSequence" Name="Isocenter Reference System Sequence"
+(0018,9463) VERS="4" VR="FL" VM="1" Keyword="PositionerIsocenterPrimaryAngle" Name="Positioner Isocenter Primary Angle"
+(0018,9464) VERS="4" VR="FL" VM="1" Keyword="PositionerIsocenterSecondaryAngle" Name="Positioner Isocenter Secondary Angle"
+(0018,9465) VERS="4" VR="FL" VM="1" Keyword="PositionerIsocenterDetectorRotationAngle" Name="Positioner Isocenter Detector Rotation Angle"
+(0018,9466) VERS="4" VR="FL" VM="1" Keyword="TableXPositionToIsocenter" Name="Table X Position to Isocenter"
+(0018,9467) VERS="4" VR="FL" VM="1" Keyword="TableYPositionToIsocenter" Name="Table Y Position to Isocenter"
+(0018,9468) VERS="4" VR="FL" VM="1" Keyword="TableZPositionToIsocenter" Name="Table Z Position to Isocenter"
+(0018,9469) VERS="4" VR="FL" VM="1" Keyword="TableHorizontalRotationAngle" Name="Table Horizontal Rotation Angle"
+(0018,9470) VERS="4" VR="FL" VM="1" Keyword="TableHeadTiltAngle" Name="Table Head Tilt Angle"
+(0018,9471) VERS="4" VR="FL" VM="1" Keyword="TableCradleTiltAngle" Name="Table Cradle Tilt Angle"
+(0018,9472) VERS="4" VR="SQ" VM="1" Keyword="FrameDisplayShutterSequence" Name="Frame Display Shutter Sequence"
+(0018,9473) VERS="4" VR="FL" VM="1" Keyword="AcquiredImageAreaDoseProduct" Name="Acquired Image Area Dose Product"
+(0018,9474) VERS="4" VR="CS" VM="1" Keyword="CArmPositionerTabletopRelationship" Name="C-arm Positioner Tabletop Relationship"
+(0018,9476) VERS="4" VR="SQ" VM="1" Keyword="XRayGeometrySequence" Name="X-Ray Geometry Sequence"
+(0018,9477) VERS="4" VR="SQ" VM="1" Keyword="IrradiationEventIdentificationSequence" Name="Irradiation Event Identification Sequence"
+(0018,9504) VERS="4" VR="SQ" VM="1" Keyword="XRay3DFrameTypeSequence" Name="X-Ray 3D Frame Type Sequence"
+(0018,9506) VERS="4" VR="SQ" VM="1" Keyword="ContributingSourcesSequence" Name="Contributing Sources Sequence"
+(0018,9507) VERS="4" VR="SQ" VM="1" Keyword="XRay3DAcquisitionSequence" Name="X-Ray 3D Acquisition Sequence"
+(0018,9508) VERS="4" VR="FL" VM="1" Keyword="PrimaryPositionerScanArc" Name="Primary Positioner Scan Arc"
+(0018,9509) VERS="4" VR="FL" VM="1" Keyword="SecondaryPositionerScanArc" Name="Secondary Positioner Scan Arc"
+(0018,9510) VERS="4" VR="FL " VM="1" Keyword="PrimaryPositionerScanStartAngle" Name="Primary Positioner Scan Start Angle"
+(0018,9511) VERS="4" VR="FL" VM="1" Keyword="SecondaryPositionerScanStartAngle" Name="Secondary Positioner Scan Start Angle"
+(0018,9514) VERS="4" VR="FL" VM="1" Keyword="PrimaryPositionerIncrement" Name="Primary Positioner Increment"
+(0018,9515) VERS="4" VR="FL" VM="1" Keyword="SecondaryPositionerIncrement" Name="Secondary Positioner Increment"
+(0018,9516) VERS="4" VR="DT" VM="1" Keyword="StartAcquisitionDateTime" Name="Start Acquisition DateTime"
+(0018,9517) VERS="4" VR="DT" VM="1" Keyword="EndAcquisitionDateTime" Name="End Acquisition DateTime"
+(0018,9524) VERS="4" VR="LO" VM="1" Keyword="ApplicationName" Name="Application Name"
+(0018,9525) VERS="4" VR="LO" VM="1" Keyword="ApplicationVersion" Name="Application Version"
+(0018,9526) VERS="4" VR="LO" VM="1" Keyword="ApplicationManufacturer" Name="Application Manufacturer"
+(0018,9527) VERS="4" VR="CS" VM="1" Keyword="AlgorithmType" Name="Algorithm Type"
+(0018,9528) VERS="4" VR="LO" VM="1" Keyword="AlgorithmDescription" Name="Algorithm Description"
+(0018,9530) VERS="4" VR="SQ" VM="1" Keyword="XRay3DReconstructionSequence" Name="X-Ray 3D Reconstruction Sequence"
+(0018,9531) VERS="4" VR="LO" VM="1" Keyword="ReconstructionDescription" Name="Reconstruction Description"
+(0018,9538) VERS="4" VR="SQ" VM="1" Keyword="PerProjectionAcquisitionSequence" Name="Per Projection Acquisition Sequence"
+(0018,9601) VERS="4" VR="SQ" VM="1" Keyword="DiffusionBMatrixSequence" Name="Diffusion b-matrix Sequence"
+(0018,9602) VERS="4" VR="FD" VM="1" Keyword="DiffusionBValueXX" Name="Diffusion b-value XX"
+(0018,9603) VERS="4" VR="FD" VM="1" Keyword="DiffusionBValueXY" Name="Diffusion b-value XY"
+(0018,9604) VERS="4" VR="FD" VM="1" Keyword="DiffusionBValueXZ" Name="Diffusion b-value XZ"
+(0018,9605) VERS="4" VR="FD" VM="1" Keyword="DiffusionBValueYY" Name="Diffusion b-value YY"
+(0018,9606) VERS="4" VR="FD" VM="1" Keyword="DiffusionBValueYZ" Name="Diffusion b-value YZ"
+(0018,9607) VERS="4" VR="FD" VM="1" Keyword="DiffusionBValueZZ" Name="Diffusion b-value ZZ"
+(0018,9701) VERS="4" VR="DT" VM="1" Keyword="DecayCorrectionDateTime" Name="Decay Correction DateTime"
+(0018,9715) VERS="4" VR="FD" VM="1" Keyword="StartDensityThreshold" Name="Start Density Threshold"
+(0018,9716) VERS="4" VR="FD" VM="1" Keyword="StartRelativeDensityDifferenceThreshold" Name="Start Relative Density Difference Threshold"
+(0018,9717) VERS="4" VR="FD" VM="1" Keyword="StartCardiacTriggerCountThreshold" Name="Start Cardiac Trigger Count Threshold"
+(0018,9718) VERS="4" VR="FD" VM="1" Keyword="StartRespiratoryTriggerCountThreshold" Name="Start Respiratory Trigger Count Threshold"
+(0018,9719) VERS="4" VR="FD" VM="1" Keyword="TerminationCountsThreshold" Name="Termination Counts Threshold"
+(0018,9720) VERS="4" VR="FD" VM="1" Keyword="TerminationDensityThreshold" Name="Termination Density Threshold"
+(0018,9721) VERS="4" VR="FD" VM="1" Keyword="TerminationRelativeDensityThreshold" Name="Termination Relative Density Threshold"
+(0018,9722) VERS="4" VR="FD" VM="1" Keyword="TerminationTimeThreshold" Name="Termination Time Threshold"
+(0018,9723) VERS="4" VR="FD" VM="1" Keyword="TerminationCardiacTriggerCountThreshold" Name="Termination Cardiac Trigger Count Threshold"
+(0018,9724) VERS="4" VR="FD" VM="1" Keyword="TerminationRespiratoryTriggerCountThreshold" Name="Termination Respiratory Trigger Count Threshold"
+(0018,9725) VERS="4" VR="CS" VM="1" Keyword="DetectorGeometry" Name="Detector Geometry"
+(0018,9726) VERS="4" VR="FD" VM="1" Keyword="TransverseDetectorSeparation" Name="Transverse Detector Separation"
+(0018,9727) VERS="4" VR="FD" VM="1" Keyword="AxialDetectorDimension" Name="Axial Detector Dimension"
+(0018,9729) VERS="4" VR="US" VM="1" Keyword="RadiopharmaceuticalAgentNumber" Name="Radiopharmaceutical Agent Number"
+(0018,9732) VERS="4" VR="SQ" VM="1" Keyword="PETFrameAcquisitionSequence" Name="PET Frame Acquisition Sequence"
+(0018,9733) VERS="4" VR="SQ" VM="1" Keyword="PETDetectorMotionDetailsSequence" Name="PET Detector Motion Details Sequence"
+(0018,9734) VERS="4" VR="SQ" VM="1" Keyword="PETTableDynamicsSequence" Name="PET Table Dynamics Sequence"
+(0018,9735) VERS="4" VR="SQ" VM="1" Keyword="PETPositionSequence" Name="PET Position Sequence"
+(0018,9736) VERS="4" VR="SQ" VM="1" Keyword="PETFrameCorrectionFactorsSequence" Name="PET Frame Correction Factors Sequence"
+(0018,9737) VERS="4" VR="SQ" VM="1" Keyword="RadiopharmaceuticalUsageSequence" Name="Radiopharmaceutical Usage Sequence"
+(0018,9738) VERS="4" VR="CS" VM="1" Keyword="AttenuationCorrectionSource" Name="Attenuation Correction Source"
+(0018,9739) VERS="4" VR="US" VM="1" Keyword="NumberOfIterations" Name="Number of Iterations"
+(0018,9740) VERS="4" VR="US" VM="1" Keyword="NumberOfSubsets" Name="Number of Subsets"
+(0018,9749) VERS="4" VR="SQ" VM="1" Keyword="PETReconstructionSequence" Name="PET Reconstruction Sequence"
+(0018,9751) VERS="4" VR="SQ" VM="1" Keyword="PETFrameTypeSequence" Name="PET Frame Type Sequence"
+(0018,9755) VERS="4" VR="CS" VM="1" Keyword="TimeOfFlightInformationUsed" Name="Time of Flight Information Used"
+(0018,9756) VERS="4" VR="CS" VM="1" Keyword="ReconstructionType" Name="Reconstruction Type"
+(0018,9758) VERS="4" VR="CS" VM="1" Keyword="DecayCorrected" Name="Decay Corrected "
+(0018,9759) VERS="4" VR="CS" VM="1" Keyword="AttenuationCorrected" Name="Attenuation Corrected "
+(0018,9760) VERS="4" VR="CS" VM="1" Keyword="ScatterCorrected" Name="Scatter Corrected "
+(0018,9761) VERS="4" VR="CS" VM="1" Keyword="DeadTimeCorrected" Name="Dead Time Corrected "
+(0018,9762) VERS="4" VR="CS" VM="1" Keyword="GantryMotionCorrected" Name="Gantry Motion Corrected "
+(0018,9763) VERS="4" VR="CS" VM="1" Keyword="PatientMotionCorrected" Name="Patient Motion Corrected "
+(0018,9764) VERS="4" VR="CS" VM="1" Keyword="CountLossNormalizationCorrected" Name="Count Loss Normalization Corrected"
+(0018,9765) VERS="4" VR="CS" VM="1" Keyword="RandomsCorrected" Name="Randoms Corrected"
+(0018,9766) VERS="4" VR="CS" VM="1" Keyword="NonUniformRadialSamplingCorrected" Name="Non-uniform Radial Sampling Corrected"
+(0018,9767) VERS="4" VR="CS" VM="1" Keyword="SensitivityCalibrated" Name="Sensitivity Calibrated"
+(0018,9768) VERS="4" VR="CS" VM="1" Keyword="DetectorNormalizationCorrection" Name="Detector Normalization Correction"
+(0018,9769) VERS="4" VR="CS" VM="1" Keyword="IterativeReconstructionMethod" Name="Iterative Reconstruction Method "
+(0018,9770) VERS="4" VR="CS" VM="1" Keyword="AttenuationCorrectionTemporalRelationship" Name="Attenuation Correction Temporal Relationship"
+(0018,9771) VERS="4" VR="SQ" VM="1" Keyword="PatientPhysiologicalStateSequence" Name="Patient Physiological State Sequence"
+(0018,9772) VERS="4" VR="SQ" VM="1" Keyword="PatientPhysiologicalStateCodeSequence" Name="Patient Physiological State Code Sequence"
+(0018,9801) VERS="4" VR="FD" VM="1-n" Keyword="DepthsOfFocus" Name="Depth(s) of Focus"
+(0018,9803) VERS="4" VR="SQ" VM="1" Keyword="ExcludedIntervalsSequence" Name="Excluded Intervals Sequence"
+(0018,9804) VERS="4" VR="DT" VM="1" Keyword="ExclusionStartDatetime" Name="Exclusion Start Datetime"
+(0018,9805) VERS="4" VR="FD" VM="1" Keyword="ExclusionDuration" Name="Exclusion Duration"
+(0018,9806) VERS="4" VR="SQ" VM="1" Keyword="USImageDescriptionSequence" Name="US Image Description Sequence"
+(0018,9807) VERS="4" VR="SQ" VM="1" Keyword="ImageDataTypeSequence" Name="Image Data Type Sequence"
+(0018,9808) VERS="4" VR="CS" VM="1" Keyword="DataType" Name="Data Type"
+(0018,9809) VERS="4" VR="SQ" VM="1" Keyword="TransducerScanPatternCodeSequence" Name="Transducer Scan Pattern Code Sequence"
+(0018,980B) VERS="4" VR="CS" VM="1" Keyword="AliasedDataType" Name="Aliased Data Type"
+(0018,980C) VERS="4" VR="CS" VM="1" Keyword="PositionMeasuringDeviceUsed" Name="Position Measuring Device Used"
+(0018,980D) VERS="4" VR="SQ" VM="1" Keyword="TransducerGeometryCodeSequence" Name="Transducer Geometry Code Sequence"
+(0018,980E) VERS="4" VR="SQ" VM="1" Keyword="TransducerBeamSteeringCodeSequence" Name="Transducer Beam Steering Code Sequence"
+(0018,980F) VERS="4" VR="SQ" VM="1" Keyword="TransducerApplicationCodeSequence" Name="Transducer Application Code Sequence"
+(0018,A001) VERS="4" VR="SQ" VM="1" Keyword="ContributingEquipmentSequence" Name="Contributing Equipment Sequence"
+(0018,A002) VERS="4" VR="DT" VM="1" Keyword="ContributionDateTime" Name="Contribution Date Time"
+(0018,A003) VERS="4" VR="ST" VM="1" Keyword="ContributionDescription" Name="Contribution Description"
+(0020,0000) VERS="3" VR="UL" VM="1" Keyword="ImageGroupLength" Name="ImageGroup Length"
+(0020,000D) VERS="4" VR="UI" VM="1" Keyword="StudyInstanceUID" Name="Study Instance UID"
+(0020,000E) VERS="4" VR="UI" VM="1" Keyword="SeriesInstanceUID" Name="Series Instance UID"
+(0020,0010) VERS="4" VR="SH" VM="1" Keyword="StudyID" Name="Study ID"
+(0020,0011) VERS="4" VR="IS" VM="1" Keyword="SeriesNumber" Name="Series Number"
+(0020,0012) VERS="4" VR="IS" VM="1" Keyword="AcquisitionNumber" Name="Acquisition Number"
+(0020,0013) VERS="4" VR="IS" VM="1" Keyword="InstanceNumber" Name="Instance Number"
+(0020,0014) VERS="4RET" VR="IS" VM="1" Keyword="IsotopeNumber" Name="Isotope Number"
+(0020,0015) VERS="4RET" VR="IS" VM="1" Keyword="PhaseNumber" Name="Phase Number"
+(0020,0016) VERS="4RET" VR="IS" VM="1" Keyword="IntervalNumber" Name="Interval Number"
+(0020,0017) VERS="4RET" VR="IS" VM="1" Keyword="TimeSlotNumber" Name="Time Slot Number"
+(0020,0018) VERS="4RET" VR="IS" VM="1" Keyword="AngleNumber" Name="Angle Number"
+(0020,0019) VERS="4" VR="IS" VM="1" Keyword="ItemNumber" Name="Item Number"
+(0020,0020) VERS="4" VR="CS" VM="2" Keyword="PatientOrientation" Name="Patient Orientation"
+(0020,0022) VERS="4RET" VR="IS" VM="1" Keyword="OverlayNumber" Name="Overlay Number"
+(0020,0024) VERS="4RET" VR="IS" VM="1" Keyword="CurveNumber" Name="Curve Number"
+(0020,0026) VERS="4RET" VR="IS" VM="1" Keyword="LUTNumber" Name="LUT Number"
+(0020,0030) VERS="4RET" VR="DS" VM="3" Keyword="ImagePosition" Name="Image Position"
+(0020,0032) VERS="4" VR="DS" VM="3" Keyword="ImagePositionPatient" Name="Image Position (Patient)"
+(0020,0035) VERS="4RET" VR="DS" VM="6" Keyword="ImageOrientation" Name="Image Orientation"
+(0020,0037) VERS="4" VR="DS" VM="6" Keyword="ImageOrientationPatient" Name="Image Orientation (Patient)"
+(0020,0050) VERS="4RET" VR="DS" VM="1" Keyword="Location" Name="Location"
+(0020,0052) VERS="4" VR="UI" VM="1" Keyword="FrameOfReferenceUID" Name="Frame of Reference UID"
+(0020,0060) VERS="4" VR="CS" VM="1" Keyword="Laterality" Name="Laterality"
+(0020,0062) VERS="4" VR="CS" VM="1" Keyword="ImageLaterality" Name="Image Laterality"
+(0020,0070) VERS="4RET" VR="LO" VM="1" Keyword="ImageGeometryType" Name="Image Geometry Type"
+(0020,0080) VERS="4RET" VR="CS" VM="1-n" Keyword="MaskingImage" Name="Masking Image"
+(0020,00AA) VERS="4RET" VR="IS" VM="1" Keyword="ReportNumber" Name="Report Number"
+(0020,0100) VERS="4" VR="IS" VM="1" Keyword="TemporalPositionIdentifier" Name="Temporal Position Identifier"
+(0020,0105) VERS="4" VR="IS" VM="1" Keyword="NumberOfTemporalPositions" Name="Number of Temporal Positions"
+(0020,0110) VERS="4" VR="DS" VM="1" Keyword="TemporalResolution" Name="Temporal Resolution"
+(0020,0200) VERS="4" VR="UI" VM="1" Keyword="SynchronizationFrameOfReferenceUID" Name="Synchronization Frame of Reference UID"
+(0020,0242) VERS="4" VR="UI" VM="1" Keyword="SOPInstanceUIDOfConcatenationSource" Name="SOP Instance UID of Concatenation Source"
+(0020,1000) VERS="4RET" VR="IS" VM="1" Keyword="SeriesInStudy" Name="Series in Study"
+(0020,1001) VERS="4RET" VR="IS" VM="1" Keyword="AcquisitionsInSeries" Name="Acquisitions in Series"
+(0020,1002) VERS="4" VR="IS" VM="1" Keyword="ImagesInAcquisition" Name="Images in Acquisition"
+(0020,1003) VERS="4RET" VR="IS" VM="1" Keyword="ImagesInSeries" Name="Images in Series"
+(0020,1004) VERS="4RET" VR="IS" VM="1" Keyword="AcquisitionsInStudy" Name="Acquisitions in Study"
+(0020,1005) VERS="4RET" VR="IS" VM="1" Keyword="ImagesInStudy" Name="Images in Study"
+(0020,1020) VERS="4RET" VR="LO" VM="1-n" Keyword="Reference" Name="Reference"
+(0020,1040) VERS="4" VR="LO" VM="1" Keyword="PositionReferenceIndicator" Name="Position Reference Indicator"
+(0020,1041) VERS="4" VR="DS" VM="1" Keyword="SliceLocation" Name="Slice Location"
+(0020,1070) VERS="4RET" VR="IS" VM="1-n" Keyword="OtherStudyNumbers" Name="Other Study Numbers"
+(0020,1200) VERS="4" VR="IS" VM="1" Keyword="NumberOfPatientRelatedStudies" Name="Number of Patient Related Studies"
+(0020,1202) VERS="4" VR="IS" VM="1" Keyword="NumberOfPatientRelatedSeries" Name="Number of Patient Related Series"
+(0020,1204) VERS="4" VR="IS" VM="1" Keyword="NumberOfPatientRelatedInstances" Name="Number of Patient Related Instances"
+(0020,1206) VERS="4" VR="IS" VM="1" Keyword="NumberOfStudyRelatedSeries" Name="Number of Study Related Series"
+(0020,1208) VERS="4" VR="IS" VM="1" Keyword="NumberOfStudyRelatedInstances" Name="Number of Study Related Instances"
+(0020,1209) VERS="4" VR="IS" VM="1" Keyword="NumberOfSeriesRelatedInstances" Name="Number of Series Related Instances"
+(0020,31xx) VERS="4" VR="CS" VM="1-n" Keyword="SourceImageIDs" Name="Source Image IDs" RS="4"31FF) VERS="4"
+(0020,3401) VERS="4RET" VR="CS" VM="1" Keyword="ModifyingDeviceID" Name="Modifying Device ID"
+(0020,3402) VERS="4RET" VR="CS" VM="1" Keyword="ModifiedImageID" Name="Modified Image ID"
+(0020,3403) VERS="4RET" VR="DA" VM="1" Keyword="ModifiedImageDate" Name="Modified Image Date"
+(0020,3404) VERS="4RET" VR="LO" VM="1" Keyword="ModifyingDeviceManufacturer" Name="Modifying Device Manufacturer"
+(0020,3405) VERS="4RET" VR="TM" VM="1" Keyword="ModifiedImageTime" Name="Modified Image Time"
+(0020,3406) VERS="4RET" VR="LO" VM="1" Keyword="ModifiedImageDescription" Name="Modified Image Description"
+(0020,4000) VERS="4" VR="LT" VM="1" Keyword="ImageComments" Name="Image Comments"
+(0020,5000) VERS="4RET" VR="AT" VM="1-n" Keyword="OriginalImageIdentification" Name="Original Image Identification"
+(0020,5002) VERS="4RET" VR="LO" VM="1-n" Keyword="OriginalImageIdentificationNomenclature" Name="Original Image Identification Nomenclature"
+(0020,9056) VERS="4" VR="SH" VM="1" Keyword="StackID" Name="Stack ID"
+(0020,9057) VERS="4" VR="UL" VM="1" Keyword="InStackPositionNumber" Name="In-Stack Position Number"
+(0020,9071) VERS="4" VR="SQ" VM="1" Keyword="FrameAnatomySequence" Name="Frame Anatomy Sequence"
+(0020,9072) VERS="4" VR="CS" VM="1" Keyword="FrameLaterality" Name="Frame Laterality"
+(0020,9111) VERS="4" VR="SQ" VM="1" Keyword="FrameContentSequence" Name="Frame Content Sequence"
+(0020,9113) VERS="4" VR="SQ" VM="1" Keyword="PlanePositionSequence" Name="Plane Position Sequence"
+(0020,9116) VERS="4" VR="SQ" VM="1" Keyword="PlaneOrientationSequence" Name="Plane Orientation Sequence"
+(0020,9128) VERS="4" VR="UL" VM="1" Keyword="TemporalPositionIndex" Name="Temporal Position Index"
+(0020,9153) VERS="4" VR="FD" VM="1" Keyword="NominalCardiacTriggerDelayTime" Name="Nominal Cardiac Trigger Delay Time"
+(0020,9154) VERS="4" VR="FL" VM="1" Keyword="NominalCardiacTriggerTimePriorToRPeak" Name="Nominal Cardiac Trigger Time Prior To R-Peak"
+(0020,9155) VERS="4" VR="FL" VM="1" Keyword="ActualCardiacTriggerTimePriorToRPeak" Name="Actual Cardiac Trigger Time Prior To R-Peak"
+(0020,9156) VERS="4" VR="US" VM="1" Keyword="FrameAcquisitionNumber" Name="Frame Acquisition Number"
+(0020,9157) VERS="4" VR="UL" VM="1-n" Keyword="DimensionIndexValues" Name="Dimension Index Values"
+(0020,9158) VERS="4" VR="LT" VM="1" Keyword="FrameComments" Name="Frame Comments"
+(0020,9161) VERS="4" VR="UI" VM="1" Keyword="ConcatenationUID" Name="Concatenation UID"
+(0020,9162) VERS="4" VR="US" VM="1" Keyword="InConcatenationNumber" Name="In-concatenation Number"
+(0020,9163) VERS="4" VR="US" VM="1" Keyword="InConcatenationTotalNumber" Name="In-concatenation Total Number"
+(0020,9164) VERS="4" VR="UI" VM="1" Keyword="DimensionOrganizationUID" Name="Dimension Organization UID"
+(0020,9165) VERS="4" VR="AT" VM="1" Keyword="DimensionIndexPointer" Name="Dimension Index Pointer"
+(0020,9167) VERS="4" VR="AT" VM="1" Keyword="FunctionalGroupPointer" Name="Functional Group Pointer"
+(0020,9213) VERS="4" VR="LO" VM="1" Keyword="DimensionIndexPrivateCreator" Name="Dimension Index Private Creator"
+(0020,9221) VERS="4" VR="SQ" VM="1" Keyword="DimensionOrganizationSequence" Name="Dimension Organization Sequence"
+(0020,9222) VERS="4" VR="SQ" VM="1" Keyword="DimensionIndexSequence" Name="Dimension Index Sequence"
+(0020,9228) VERS="4" VR="UL" VM="1" Keyword="ConcatenationFrameOffsetNumber" Name="Concatenation Frame Offset Number"
+(0020,9238) VERS="4" VR="LO" VM="1" Keyword="FunctionalGroupPrivateCreator" Name="Functional Group Private Creator"
+(0020,9241) VERS="4" VR="FL" VM="1" Keyword="NominalPercentageOfCardiacPhase" Name="Nominal Percentage of Cardiac Phase"
+(0020,9245) VERS="4" VR="FL" VM="1" Keyword="NominalPercentageOfRespiratoryPhase" Name="Nominal Percentage of Respiratory Phase"
+(0020,9246) VERS="4" VR="FL" VM="1" Keyword="StartingRespiratoryAmplitude" Name="Starting Respiratory Amplitude"
+(0020,9247) VERS="4" VR="CS" VM="1" Keyword="StartingRespiratoryPhase" Name="Starting Respiratory Phase"
+(0020,9248) VERS="4" VR="FL" VM="1" Keyword="EndingRespiratoryAmplitude" Name="Ending Respiratory Amplitude"
+(0020,9249) VERS="4" VR="CS" VM="1" Keyword="EndingRespiratoryPhase" Name="Ending Respiratory Phase"
+(0020,9250) VERS="4" VR="CS" VM="1" Keyword="RespiratoryTriggerType" Name="Respiratory Trigger Type"
+(0020,9251) VERS="4" VR="FD" VM="1" Keyword="RRIntervalTimeNominal" Name="R-R Interval Time Nominal"
+(0020,9252) VERS="4" VR="FD" VM="1" Keyword="ActualCardiacTriggerDelayTime" Name="Actual Cardiac Trigger Delay Time"
+(0020,9253) VERS="4" VR="SQ" VM="1" Keyword="RespiratorySynchronizationSequence" Name="Respiratory Synchronization Sequence"
+(0020,9254) VERS="4" VR="FD" VM="1" Keyword="RespiratoryIntervalTime" Name="Respiratory Interval Time"
+(0020,9255) VERS="4" VR="FD" VM="1" Keyword="NominalRespiratoryTriggerDelayTime" Name="Nominal Respiratory Trigger Delay Time"
+(0020,9256) VERS="4" VR="FD" VM="1" Keyword="RespiratoryTriggerDelayThreshold" Name="Respiratory Trigger Delay Threshold"
+(0020,9257) VERS="4" VR="FD" VM="1" Keyword="ActualRespiratoryTriggerDelayTime" Name="Actual Respiratory Trigger Delay Time"
+(0020,9301) VERS="4" VR="FD" VM="3" Keyword="ImagePositionVolume" Name="Image Position (Volume)"
+(0020,9302) VERS="4" VR="FD" VM="6" Keyword="ImageOrientationVolume" Name="Image Orientation (Volume)"
+(0020,9307) VERS="4" VR="CS" VM="1" Keyword="UltrasoundAcquisitionGeometry" Name="Ultrasound Acquisition Geometry"
+(0020,9308) VERS="4" VR="FD" VM="3" Keyword="ApexPosition" Name="Apex Position"
+(0020,9309) VERS="4" VR="FD" VM="16" Keyword="VolumeToTransducerMappingMatrix" Name="Volume to Transducer Mapping Matrix"
+(0020,930A) VERS="4" VR="FD" VM="16" Keyword="VolumeToTableMappingMatrix" Name="Volume to Table Mapping Matrix"
+(0020,930C) VERS="4" VR="CS" VM="1" Keyword="PatientFrameOfReferenceSource" Name="Patient Frame of Reference Source"
+(0020,930D) VERS="4" VR="FD" VM="1" Keyword="TemporalPositionTimeOffset" Name="Temporal Position Time Offset"
+(0020,930E) VERS="4" VR="SQ" VM="1" Keyword="PlanePositionVolumeSequence" Name="Plane Position (Volume) Sequence"
+(0020,930F) VERS="4" VR="SQ" VM="1" Keyword="PlaneOrientationVolumeSequence" Name="Plane Orientation (Volume) Sequence"
+(0020,9310) VERS="4" VR="SQ" VM="1" Keyword="TemporalPositionSequence" Name="Temporal Position Sequence"
+(0020,9311) VERS="4" VR="CS" VM="1" Keyword="DimensionOrganizationType" Name="Dimension Organization Type"
+(0020,9312) VERS="4" VR="UI" VM="1" Keyword="VolumeFrameOfReferenceUID" Name="Volume Frame of Reference UID"
+(0020,9313) VERS="4" VR="UI" VM="1" Keyword="TableFrameOfReferenceUID" Name="Table Frame of Reference UID"
+(0020,9421) VERS="4" VR="LO" VM="1" Keyword="DimensionDescriptionLabel" Name="Dimension Description Label"
+(0020,9450) VERS="4" VR="SQ" VM="1" Keyword="PatientOrientationInFrameSequence" Name="Patient Orientation in Frame Sequence"
+(0020,9453) VERS="4" VR="LO" VM="1" Keyword="FrameLabel" Name="Frame Label"
+(0020,9518) VERS="4" VR="US" VM="1-n" Keyword="AcquisitionIndex" Name="Acquisition Index"
+(0020,9529) VERS="4" VR="SQ" VM="1" Keyword="ContributingSOPInstancesReferenceSequence" Name="Contributing SOP Instances Reference Sequence"
+(0020,9536) VERS="4" VR="US" VM="1" Keyword="ReconstructionIndex" Name="Reconstruction Index"
+(0022,0001) VERS="4" VR="US" VM="1" Keyword="LightPathFilterPassThroughWavelength" Name="Light Path Filter Pass-Through Wavelength"
+(0022,0002) VERS="4" VR="US" VM="2" Keyword="LightPathFilterPassBand" Name="Light Path Filter Pass Band"
+(0022,0003) VERS="4" VR="US" VM="1" Keyword="ImagePathFilterPassThroughWavelength" Name="Image Path Filter Pass-Through Wavelength"
+(0022,0004) VERS="4" VR="US" VM="2" Keyword="ImagePathFilterPassBand" Name="Image Path Filter Pass Band"
+(0022,0005) VERS="4" VR="CS" VM="1" Keyword="PatientEyeMovementCommanded" Name="Patient Eye Movement Commanded"
+(0022,0006) VERS="4" VR="SQ" VM="1" Keyword="PatientEyeMovementCommandCodeSequence" Name="Patient Eye Movement Command Code Sequence"
+(0022,0007) VERS="4" VR="FL" VM="1" Keyword="SphericalLensPower" Name="Spherical Lens Power"
+(0022,0008) VERS="4" VR="FL" VM="1" Keyword="CylinderLensPower" Name="Cylinder Lens Power"
+(0022,0009) VERS="4" VR="FL" VM="1" Keyword="CylinderAxis" Name="Cylinder Axis"
+(0022,000A) VERS="4" VR="FL" VM="1" Keyword="EmmetropicMagnification" Name="Emmetropic Magnification"
+(0022,000B) VERS="4" VR="FL" VM="1" Keyword="IntraOcularPressure" Name="Intra Ocular Pressure"
+(0022,000C) VERS="4" VR="FL" VM="1" Keyword="HorizontalFieldOfView" Name="Horizontal Field of View"
+(0022,000D) VERS="4" VR="CS" VM="1" Keyword="PupilDilated" Name="Pupil Dilated"
+(0022,000E) VERS="4" VR="FL" VM="1" Keyword="DegreeOfDilation" Name="Degree of Dilation"
+(0022,0010) VERS="4" VR="FL" VM="1" Keyword="StereoBaselineAngle" Name="Stereo Baseline Angle"
+(0022,0011) VERS="4" VR="FL" VM="1" Keyword="StereoBaselineDisplacement" Name="Stereo Baseline Displacement"
+(0022,0012) VERS="4" VR="FL" VM="1" Keyword="StereoHorizontalPixelOffset" Name="Stereo Horizontal Pixel Offset"
+(0022,0013) VERS="4" VR="FL" VM="1" Keyword="StereoVerticalPixelOffset" Name="Stereo Vertical Pixel Offset"
+(0022,0014) VERS="4" VR="FL" VM="1" Keyword="StereoRotation" Name="Stereo Rotation"
+(0022,0015) VERS="4" VR="SQ" VM="1" Keyword="AcquisitionDeviceTypeCodeSequence" Name="Acquisition Device Type Code Sequence"
+(0022,0016) VERS="4" VR="SQ" VM="1" Keyword="IlluminationTypeCodeSequence" Name="Illumination Type Code Sequence"
+(0022,0017) VERS="4" VR="SQ" VM="1" Keyword="LightPathFilterTypeStackCodeSequence" Name="Light Path Filter Type Stack Code Sequence"
+(0022,0018) VERS="4" VR="SQ" VM="1" Keyword="ImagePathFilterTypeStackCodeSequence" Name="Image Path Filter Type Stack Code Sequence"
+(0022,0019) VERS="4" VR="SQ" VM="1" Keyword="LensesCodeSequence" Name="Lenses Code Sequence"
+(0022,001A) VERS="4" VR="SQ" VM="1" Keyword="ChannelDescriptionCodeSequence" Name="Channel Description Code Sequence"
+(0022,001B) VERS="4" VR="SQ" VM="1" Keyword="RefractiveStateSequence" Name="Refractive State Sequence"
+(0022,001C) VERS="4" VR="SQ" VM="1" Keyword="MydriaticAgentCodeSequence" Name="Mydriatic Agent Code Sequence"
+(0022,001D) VERS="4" VR="SQ" VM="1" Keyword="RelativeImagePositionCodeSequence" Name="Relative Image Position Code Sequence"
+(0022,001E) VERS="4" VR="FL" VM="1" Keyword="CameraAngleOfView" Name="Camera Angle of View"
+(0022,0020) VERS="4" VR="SQ" VM="1" Keyword="StereoPairsSequence" Name="Stereo Pairs Sequence"
+(0022,0021) VERS="4" VR="SQ" VM="1" Keyword="LeftImageSequence" Name="Left Image Sequence"
+(0022,0022) VERS="4" VR="SQ" VM="1" Keyword="RightImageSequence" Name="Right Image Sequence"
+(0022,0030) VERS="4" VR="FL" VM="1" Keyword="AxialLengthOfTheEye" Name="Axial Length of the Eye"
+(0022,0031) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicFrameLocationSequence" Name="Ophthalmic Frame Location Sequence"
+(0022,0032) VERS="4" VR="FL" VM="2-2n" Keyword="ReferenceCoordinates" Name="Reference Coordinates"
+(0022,0035) VERS="4" VR="FL" VM="1" Keyword="DepthSpatialResolution" Name="Depth Spatial Resolution"
+(0022,0036) VERS="4" VR="FL" VM="1" Keyword="MaximumDepthDistortion" Name="Maximum Depth Distortion"
+(0022,0037) VERS="4" VR="FL" VM="1" Keyword="AlongScanSpatialResolution" Name="Along-scan Spatial Resolution"
+(0022,0038) VERS="4" VR="FL" VM="1" Keyword="MaximumAlongScanDistortion" Name="Maximum Along-scan Distortion"
+(0022,0039) VERS="4" VR="CS" VM="1" Keyword="OphthalmicImageOrientation" Name="Ophthalmic Image Orientation"
+(0022,0041) VERS="4" VR="FL" VM="1" Keyword="DepthOfTransverseImage" Name="Depth of Transverse Image"
+(0022,0042) VERS="4" VR="SQ" VM="1" Keyword="MydriaticAgentConcentrationUnitsSequence" Name="Mydriatic Agent Concentration Units Sequence"
+(0022,0048) VERS="4" VR="FL" VM="1" Keyword="AcrossScanSpatialResolution" Name="Across-scan Spatial Resolution"
+(0022,0049) VERS="4" VR="FL" VM="1" Keyword="MaximumAcrossScanDistortion" Name="Maximum Across-scan Distortion"
+(0022,004E) VERS="4" VR="DS" VM="1" Keyword="MydriaticAgentConcentration" Name="Mydriatic Agent Concentration"
+(0022,0055) VERS="4" VR="FL" VM="1" Keyword="IlluminationWaveLength" Name="Illumination Wave Length"
+(0022,0056) VERS="4" VR="FL" VM="1" Keyword="IlluminationPower" Name="Illumination Power"
+(0022,0057) VERS="4" VR="FL" VM="1" Keyword="IlluminationBandwidth" Name="Illumination Bandwidth"
+(0022,0058) VERS="4" VR="SQ" VM="1" Keyword="MydriaticAgentSequence" Name="Mydriatic Agent Sequence"
+(0022,1007) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicAxialMeasurementsRightEyeSequence" Name="Ophthalmic Axial Measurements Right Eye Sequence"
+(0022,1008) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicAxialMeasurementsLeftEyeSequence" Name="Ophthalmic Axial Measurements Left Eye Sequence"
+(0022,1010) VERS="4" VR="CS" VM="1" Keyword="OphthalmicAxialLengthMeasurementsType" Name="Ophthalmic Axial Length Measurements Type"
+(0022,1019) VERS="4" VR="FL" VM="1" Keyword="OphthalmicAxialLength" Name="Ophthalmic Axial Length "
+(0022,1024) VERS="4" VR="SQ" VM="1" Keyword="LensStatusCodeSequence" Name="Lens Status Code Sequence"
+(0022,1025) VERS="4" VR="SQ" VM="1" Keyword="VitreousStatusCodeSequence" Name="Vitreous Status Code Sequence"
+(0022,1028) VERS="4" VR="SQ" VM="1" Keyword="IOLFormulaCodeSequence" Name="IOL Formula Code Sequence"
+(0022,1029) VERS="4" VR="LO" VM="1" Keyword="IOLFormulaDetail" Name="IOL Formula Detail"
+(0022,1033) VERS="4" VR="FL" VM="1" Keyword="KeratometerIndex" Name="Keratometer Index"
+(0022,1035) VERS="4" VR="SQ" VM="1" Keyword="SourceOfOphthalmicAxialLengthCodeSequence" Name="Source of Ophthalmic Axial Length Code Sequence"
+(0022,1037) VERS="4" VR="FL" VM="1" Keyword="TargetRefraction" Name="Target Refraction "
+(0022,1039) VERS="4" VR="CS" VM="1" Keyword="RefractiveProcedureOccurred" Name="Refractive Procedure Occurred"
+(0022,1040) VERS="4" VR="SQ" VM="1" Keyword="RefractiveSurgeryTypeCodeSequence" Name="Refractive Surgery Type Code Sequence"
+(0022,1044) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicUltrasoundAxialMeasurementsTypeCodeSequence" Name="Ophthalmic Ultrasound Axial Measurements Type Code Sequence"
+(0022,1050) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicAxialLengthMeasurementsSequence" Name="Ophthalmic Axial Length Measurements Sequence"
+(0022,1053) VERS="4" VR="FL" VM="1" Keyword="IOLPower" Name="IOL Power"
+(0022,1054) VERS="4" VR="FL" VM="1" Keyword="PredictedRefractiveError" Name="Predicted Refractive Error"
+(0022,1059) VERS="4" VR="FL" VM="1" Keyword="OphthalmicAxialLengthVelocity" Name="Ophthalmic Axial Length Velocity"
+(0022,1065) VERS="4" VR="LO" VM="1" Keyword="LensStatusDescription" Name="Lens Status Description"
+(0022,1066) VERS="4" VR="LO" VM="1" Keyword="VitreousStatusDescription" Name="Vitreous Status Description"
+(0022,1090) VERS="4" VR="SQ" VM="1" Keyword="IOLPowerSequence" Name="IOL Power Sequence"
+(0022,1092) VERS="4" VR="SQ" VM="1" Keyword="LensConstantSequence" Name="Lens Constant Sequence"
+(0022,1093) VERS="4" VR="LO" VM="1" Keyword="IOLManufacturer" Name="IOL Manufacturer"
+(0022,1094) VERS="4" VR="LO" VM="1" Keyword="LensConstantDescription" Name="Lens Constant Description"
+(0022,1096) VERS="4" VR="SQ" VM="1" Keyword="KeratometryMeasurementTypeCodeSequence" Name="Keratometry Measurement Type Code Sequence "
+(0022,1100) VERS="4" VR="SQ" VM="1" Keyword="ReferencedOphthalmicAxialMeasurementsSequence" Name="Referenced Ophthalmic Axial Measurements Sequence"
+(0022,1101) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicAxialLengthMeasurementsSegmentNameCodeSequence" Name="Ophthalmic Axial Length Measurements Segment Name Code Sequence"
+(0022,1103) VERS="4" VR="SQ" VM="1" Keyword="RefractiveErrorBeforeRefractiveSurgeryCodeSequence" Name="Refractive Error Before Refractive Surgery Code Sequence"
+(0022,1121) VERS="4" VR="FL" VM="1" Keyword="IOLPowerForExactEmmetropia" Name="IOL Power For Exact Emmetropia"
+(0022,1122) VERS="4" VR="FL" VM="1" Keyword="IOLPowerForExactTargetRefraction" Name="IOL Power For Exact Target Refraction"
+(0022,1125) VERS="4" VR="SQ" VM="1" Keyword="AnteriorChamberDepthDefinitionCodeSequence" Name="Anterior Chamber Depth Definition Code Sequence"
+(0022,1130) VERS="4" VR="FL" VM="1" Keyword="LensThickness" Name="Lens Thickness"
+(0022,1131) VERS="4" VR="FL" VM="1" Keyword="AnteriorChamberDepth" Name="Anterior Chamber Depth"
+(0022,1132) VERS="4" VR="SQ" VM="1" Keyword="SourceOfLensThicknessDataCodeSequence" Name="Source of Lens Thickness Data Code Sequence"
+(0022,1133) VERS="4" VR="SQ" VM="1" Keyword="SourceOfAnteriorChamberDepthDataCodeSequence" Name="Source of Anterior Chamber Depth Data Code Sequence"
+(0022,1135) VERS="4" VR="SQ" VM="1" Keyword="SourceOfRefractiveErrorDataCodeSequence" Name="Source of Refractive Error Data Code Sequence"
+(0022,1140) VERS="4" VR="CS" VM="1" Keyword="OphthalmicAxialLengthMeasurementModified" Name="Ophthalmic Axial Length Measurement Modified"
+(0022,1150) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicAxialLengthDataSourceCodeSequence" Name="Ophthalmic Axial Length Data Source Code Sequence"
+(0022,1153) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicAxialLengthAcquisitionMethodCodeSequence" Name="Ophthalmic Axial Length Acquisition Method Code Sequence"
+(0022,1155) VERS="4" VR="FL" VM="1" Keyword="SignalToNoiseRatio" Name="Signal to Noise Ratio"
+(0022,1159) VERS="4" VR="LO" VM="1" Keyword="OphthalmicAxialLengthDataSourceDescription" Name="Ophthalmic Axial Length Data Source Description"
+(0022,1210) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicAxialLengthMeasurementsTotalLengthSequence" Name="Ophthalmic Axial Length Measurements Total Length Sequence"
+(0022,1211) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicAxialLengthMeasurementsSegmentalLengthSequence" Name="Ophthalmic Axial Length Measurements Segmental Length Sequence"
+(0022,1212) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicAxialLengthMeasurementsLengthSummationSequence" Name="Ophthalmic Axial Length Measurements Length Summation Sequence"
+(0022,1220) VERS="4" VR="SQ" VM="1" Keyword="UltrasoundOphthalmicAxialLengthMeasurementsSequence" Name="Ultrasound Ophthalmic Axial Length Measurements Sequence"
+(0022,1225) VERS="4" VR="SQ" VM="1" Keyword="OpticalOphthalmicAxialLengthMeasurementsSequence" Name="Optical Ophthalmic Axial Length Measurements Sequence"
+(0022,1230) VERS="4" VR="SQ" VM="1" Keyword="UltrasoundSelectedOphthalmicAxialLengthSequence" Name="Ultrasound Selected Ophthalmic Axial Length Sequence"
+(0022,1250) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicAxialLengthSelectionMethodCodeSequence" Name="Ophthalmic Axial Length Selection Method Code Sequence"
+(0022,1255) VERS="4" VR="SQ" VM="1" Keyword="OpticalSelectedOphthalmicAxialLengthSequence" Name="Optical Selected Ophthalmic Axial Length Sequence"
+(0022,1257) VERS="4" VR="SQ" VM="1" Keyword="SelectedSegmentalOphthalmicAxialLengthSequence" Name="Selected Segmental Ophthalmic Axial Length Sequence"
+(0022,1260) VERS="4" VR="SQ" VM="1" Keyword="SelectedTotalOphthalmicAxialLengthSequence" Name="Selected Total Ophthalmic Axial Length Sequence"
+(0022,1262) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicAxialLengthQualityMetricSequence" Name="Ophthalmic Axial Length Quality Metric Sequence"
+(0022,1273) VERS="4" VR="LO" VM="1" Keyword="OphthalmicAxialLengthQualityMetricTypeDescription" Name="Ophthalmic Axial Length Quality Metric Type Description"
+(0022,1300) VERS="4" VR="SQ" VM="1" Keyword="IntraocularLensCalculationsRightEyeSequence" Name="Intraocular Lens Calculations Right Eye Sequence"
+(0022,1310) VERS="4" VR="SQ" VM="1" Keyword="IntraocularLensCalculationsLeftEyeSequence" Name="Intraocular Lens Calculations Left Eye Sequence"
+(0022,1330) VERS="4" VR="SQ" VM="1" Keyword="ReferencedOphthalmicAxialLengthMeasurementQCImageSequence" Name="Referenced Ophthalmic Axial Length Measurement QC Image Sequence"
+(0024,0010) VERS="4" VR="FL" VM="1" Keyword="VisualFieldHorizontalExtent" Name="Visual Field Horizontal Extent "
+(0024,0011) VERS="4" VR="FL" VM="1" Keyword="VisualFieldVerticalExtent" Name="Visual Field Vertical Extent"
+(0024,0012) VERS="4" VR="CS" VM="1" Keyword="VisualFieldShape" Name="Visual Field Shape"
+(0024,0016) VERS="4" VR="SQ" VM="1" Keyword="ScreeningTestModeCodeSequence" Name="Screening Test Mode Code Sequence"
+(0024,0018) VERS="4" VR="FL" VM="1" Keyword="MaximumStimulusLuminance" Name="Maximum Stimulus Luminance"
+(0024,0020) VERS="4" VR="FL" VM="1" Keyword="BackgroundLuminance" Name="Background Luminance "
+(0024,0021) VERS="4" VR="SQ" VM="1" Keyword="StimulusColorCodeSequence" Name="Stimulus Color Code Sequence"
+(0024,0024) VERS="4" VR="SQ" VM="1" Keyword="BackgroundIlluminationColorCodeSequence" Name="Background Illumination Color Code Sequence "
+(0024,0025) VERS="4" VR="FL" VM="1" Keyword="StimulusArea" Name="Stimulus Area"
+(0024,0028) VERS="4" VR="FL" VM="1" Keyword="StimulusPresentationTime" Name="Stimulus Presentation Time"
+(0024,0032) VERS="4" VR="SQ" VM="1" Keyword="FixationSequence" Name="Fixation Sequence"
+(0024,0033) VERS="4" VR="SQ" VM="1" Keyword="FixationMonitoringCodeSequence" Name="Fixation Monitoring Code Sequence"
+(0024,0034) VERS="4" VR="SQ" VM="1" Keyword="VisualFieldCatchTrialSequence" Name="Visual Field Catch Trial Sequence"
+(0024,0035) VERS="4" VR="US" VM="1" Keyword="FixationCheckedQuantity" Name="Fixation Checked Quantity"
+(0024,0036) VERS="4" VR="US" VM="1" Keyword="PatientNotProperlyFixatedQuantity" Name="Patient Not Properly Fixated Quantity"
+(0024,0037) VERS="4" VR="CS" VM="1" Keyword="PresentedVisualStimuliDataFlag" Name="Presented Visual Stimuli Data Flag"
+(0024,0038) VERS="4" VR="US" VM="1" Keyword="NumberOfVisualStimuli" Name="Number of Visual Stimuli"
+(0024,0039) VERS="4" VR="CS" VM="1" Keyword="ExcessiveFixationLossesDataFlag" Name="Excessive Fixation Losses Data Flag"
+(0024,0040) VERS="4" VR="CS" VM="1" Keyword="ExcessiveFixationLosses" Name="Excessive Fixation Losses"
+(0024,0042) VERS="4" VR="US" VM="1" Keyword="StimuliRetestingQuantity" Name="Stimuli Retesting Quantity"
+(0024,0044) VERS="4" VR="LT" VM="1" Keyword="CommentsOnPatientPerformanceOfVisualField" Name="Comments on Patient�s Performance of Visual Field"
+(0024,0045) VERS="4" VR="CS" VM="1" Keyword="FalseNegativesEstimateFlag" Name="False Negatives Estimate Flag"
+(0024,0046) VERS="4" VR="FL" VM="1" Keyword="FalseNegativesEstimate" Name="False Negatives Estimate"
+(0024,0048) VERS="4" VR="US" VM="1" Keyword="NegativeCatchTrialsQuantity" Name="Negative Catch Trials Quantity"
+(0024,0050) VERS="4" VR="US" VM="1" Keyword="FalseNegativesQuantity" Name="False Negatives Quantity"
+(0024,0051) VERS="4" VR="CS" VM="1" Keyword="ExcessiveFalseNegativesDataFlag" Name="Excessive False Negatives Data Flag"
+(0024,0052) VERS="4" VR="CS" VM="1" Keyword="ExcessiveFalseNegatives" Name="Excessive False Negatives"
+(0024,0053) VERS="4" VR="CS" VM="1" Keyword="FalsePositivesEstimateFlag" Name="False Positives Estimate Flag"
+(0024,0054) VERS="4" VR="FL" VM="1" Keyword="FalsePositivesEstimate" Name="False Positives Estimate"
+(0024,0055) VERS="4" VR="CS" VM="1" Keyword="CatchTrialsDataFlag" Name="Catch Trials Data Flag"
+(0024,0056) VERS="4" VR="US" VM="1" Keyword="PositiveCatchTrialsQuantity" Name="Positive Catch Trials Quantity"
+(0024,0057) VERS="4" VR="CS" VM="1" Keyword="TestPointNormalsDataFlag" Name="Test Point Normals Data Flag"
+(0024,0058) VERS="4" VR="SQ" VM="1" Keyword="TestPointNormalsSequence" Name="Test Point Normals Sequence"
+(0024,0059) VERS="4" VR="CS" VM="1" Keyword="GlobalDeviationProbabilityNormalsFlag" Name="Global Deviation Probability Normals Flag"
+(0024,0060) VERS="4" VR="US" VM="1" Keyword="FalsePositivesQuantity" Name="False Positives Quantity"
+(0024,0061) VERS="4" VR="CS" VM="1" Keyword="ExcessiveFalsePositivesDataFlag" Name="Excessive False Positives Data Flag"
+(0024,0062) VERS="4" VR="CS" VM="1" Keyword="ExcessiveFalsePositives" Name="Excessive False Positives"
+(0024,0063) VERS="4" VR="CS" VM="1" Keyword="VisualFieldTestNormalsFlag" Name="Visual Field Test Normals Flag"
+(0024,0064) VERS="4" VR="SQ" VM="1" Keyword="ResultsNormalsSequence" Name="Results Normals Sequence"
+(0024,0065) VERS="4" VR="SQ" VM="1" Keyword="AgeCorrectedSensitivityDeviationAlgorithmSequence" Name="Age Corrected Sensitivity Deviation Algorithm Sequence"
+(0024,0066) VERS="4" VR="FL" VM="1" Keyword="GlobalDeviationFromNormal" Name="Global Deviation From Normal"
+(0024,0067) VERS="4" VR="SQ" VM="1" Keyword="GeneralizedDefectSensitivityDeviationAlgorithmSequence" Name="Generalized Defect Sensitivity Deviation Algorithm Sequence"
+(0024,0068) VERS="4" VR="FL" VM="1" Keyword="LocalizedDeviationfromNormal" Name="Localized Deviation from Normal"
+(0024,0069) VERS="4" VR="LO" VM="1" Keyword="PatientReliabilityIndicator" Name="Patient Reliability Indicator "
+(0024,0070) VERS="4" VR="FL" VM="1" Keyword="VisualFieldMeanSensitivity" Name="Visual Field Mean Sensitivity"
+(0024,0071) VERS="4" VR="FL" VM="1" Keyword="GlobalDeviationProbability" Name="Global Deviation Probability"
+(0024,0072) VERS="4" VR="CS" VM="1" Keyword="LocalDeviationProbabilityNormalsFlag" Name="Local Deviation Probability Normals Flag"
+(0024,0073) VERS="4" VR="FL" VM="1" Keyword="LocalizedDeviationProbability" Name="Localized Deviation Probability"
+(0024,0074) VERS="4" VR="CS" VM="1" Keyword="ShortTermFluctuationCalculated" Name="Short Term Fluctuation Calculated"
+(0024,0075) VERS="4" VR="FL" VM="1" Keyword="ShortTermFluctuation" Name="Short Term Fluctuation"
+(0024,0076) VERS="4" VR="CS" VM="1" Keyword="ShortTermFluctuationProbabilityCalculated" Name="Short Term Fluctuation Probability Calculated"
+(0024,0077) VERS="4" VR="FL" VM="1" Keyword="ShortTermFluctuationProbability" Name="Short Term Fluctuation Probability"
+(0024,0078) VERS="4" VR="CS" VM="1" Keyword="CorrectedLocalizedDeviationFromNormalCalculated" Name="Corrected Localized Deviation From Normal Calculated"
+(0024,0079) VERS="4" VR="FL" VM="1" Keyword="CorrectedLocalizedDeviationFromNormal" Name="Corrected Localized Deviation From Normal"
+(0024,0080) VERS="4" VR="CS" VM="1" Keyword="CorrectedLocalizedDeviationFromNormalProbabilityCalculated" Name="Corrected Localized Deviation From Normal Probability Calculated"
+(0024,0081) VERS="4" VR="FL" VM="1" Keyword="CorrectedLocalizedDeviationFromNormalProbability" Name="Corrected Localized Deviation From Normal Probability"
+(0024,0083) VERS="4" VR="SQ" VM="1" Keyword="GlobalDeviationProbabilitySequence" Name="Global Deviation Probability Sequence"
+(0024,0085) VERS="4" VR="SQ" VM="1" Keyword="LocalizedDeviationProbabilitySequence" Name="Localized Deviation Probability Sequence"
+(0024,0086) VERS="4" VR="CS" VM="1" Keyword="FovealSensitivityMeasured" Name="Foveal Sensitivity Measured"
+(0024,0087) VERS="4" VR="FL" VM="1" Keyword="FovealSensitivity" Name="Foveal Sensitivity"
+(0024,0088) VERS="4" VR="FL" VM="1" Keyword="VisualFieldTestDuration" Name="Visual Field Test Duration"
+(0024,0089) VERS="4" VR="SQ" VM="1" Keyword="VisualFieldTestPointSequence" Name="Visual Field Test Point Sequence"
+(0024,0090) VERS="4" VR="FL" VM="1" Keyword="VisualFieldTestPointXCoordinate" Name="Visual Field Test Point X-Coordinate"
+(0024,0091) VERS="4" VR="FL" VM="1" Keyword="VisualFieldTestPointYCoordinate" Name="Visual Field Test Point Y-Coordinate"
+(0024,0092) VERS="4" VR="FL" VM="1" Keyword="AgeCorrectedSensitivityDeviationValue" Name="Age Corrected Sensitivity Deviation Value"
+(0024,0093) VERS="4" VR="CS" VM="1" Keyword="StimulusResults" Name="Stimulus Results"
+(0024,0094) VERS="4" VR="FL" VM="1" Keyword="SensitivityValue" Name="Sensitivity Value"
+(0024,0095) VERS="4" VR="CS" VM="1" Keyword="RetestStimulusSeen" Name="Retest Stimulus Seen"
+(0024,0096) VERS="4" VR="FL" VM="1" Keyword="RetestSensitivityValue" Name="Retest Sensitivity Value"
+(0024,0097) VERS="4" VR="SQ" VM="1" Keyword="VisualFieldTestPointNormalsSequence" Name="Visual Field Test Point Normals Sequence"
+(0024,0098) VERS="4" VR="FL" VM="1" Keyword="QuantifiedDefect" Name="Quantified Defect"
+(0024,0100) VERS="4" VR="FL" VM="1" Keyword="AgeCorrectedSensitivityDeviationProbabilityValue" Name="Age Corrected Sensitivity Deviation Probability Value"
+(0024,0102) VERS="4" VR="CS" VM="1" Keyword="GeneralizedDefectCorrectedSensitivityDeviationFlag " Name="Generalized Defect Corrected Sensitivity Deviation Flag "
+(0024,0103) VERS="4" VR="FL" VM="1" Keyword="GeneralizedDefectCorrectedSensitivityDeviationValue " Name="Generalized Defect Corrected Sensitivity Deviation Value "
+(0024,0104) VERS="4" VR="FL" VM="1" Keyword="GeneralizedDefectCorrectedSensitivityDeviationProbabilityValue" Name="Generalized Defect Corrected Sensitivity Deviation Probability Value "
+(0024,0105) VERS="4" VR="FL " VM="1" Keyword="MinimumSensitivityValue" Name="Minimum Sensitivity Value"
+(0024,0106) VERS="4" VR="CS" VM="1" Keyword="BlindSpotLocalized" Name="Blind Spot Localized"
+(0024,0107) VERS="4" VR="FL" VM="1" Keyword="BlindSpotXCoordinate" Name="Blind Spot X-Coordinate"
+(0024,0108) VERS="4" VR="FL" VM="1" Keyword="BlindSpotYCoordinate " Name="Blind Spot Y-Coordinate "
+(0024,0110) VERS="4" VR="SQ" VM="1" Keyword="VisualAcuityMeasurementSequence" Name="Visual Acuity Measurement Sequence"
+(0024,0112) VERS="4" VR="SQ" VM="1" Keyword="RefractiveParametersUsedOnPatientSequence" Name="Refractive Parameters Used on Patient Sequence "
+(0024,0113) VERS="4" VR="CS" VM="1" Keyword="MeasurementLaterality" Name="Measurement Laterality"
+(0024,0114) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicPatientClinicalInformationLeftEyeSequence" Name="Ophthalmic Patient Clinical Information Left Eye Sequence"
+(0024,0115) VERS="4" VR="SQ" VM="1" Keyword="OphthalmicPatientClinicalInformationRightEyeSequence" Name="Ophthalmic Patient Clinical Information Right Eye Sequence"
+(0024,0117) VERS="4" VR="CS" VM="1" Keyword="FovealPointNormativeDataFlag" Name="Foveal Point Normative Data Flag"
+(0024,0118) VERS="4" VR="FL" VM="1" Keyword="FovealPointProbabilityValue" Name="Foveal Point Probability Value"
+(0024,0120) VERS="4" VR="CS" VM="1" Keyword="ScreeningBaselineMeasured" Name="Screening Baseline Measured"
+(0024,0122) VERS="4" VR="SQ" VM="1" Keyword="ScreeningBaselineMeasuredSequence" Name="Screening Baseline Measured Sequence"
+(0024,0124) VERS="4" VR="CS" VM="1" Keyword="ScreeningBaselineType" Name="Screening Baseline Type"
+(0024,0126) VERS="4" VR="FL" VM="1" Keyword="ScreeningBaselineValue" Name="Screening Baseline Value"
+(0024,0202) VERS="4" VR="LO" VM="1" Keyword="AlgorithmSource" Name="Algorithm Source"
+(0024,0306) VERS="4" VR="LO" VM="1" Keyword="DataSetName" Name="Data Set Name"
+(0024,0307) VERS="4" VR="LO" VM="1" Keyword="DataSetVersion" Name="Data Set Version"
+(0024,0308) VERS="4" VR="LO" VM="1" Keyword="DataSetSource" Name="Data Set Source"
+(0024,0309) VERS="4" VR="LO" VM="1" Keyword="DataSetDescription" Name="Data Set Description"
+(0024,0317) VERS="4" VR="SQ" VM="1" Keyword="VisualFieldTestReliabilityGlobalIndexSequence" Name="Visual Field Test Reliability Global Index Sequence"
+(0024,0320) VERS="4" VR="SQ" VM="1" Keyword="VisualFieldGlobalResultsIndexSequence" Name="Visual Field Global Results Index Sequence"
+(0024,0325) VERS="4" VR="SQ" VM="1" Keyword="DataObservationSequence" Name="Data Observation Sequence"
+(0024,0338) VERS="4" VR="CS" VM="1" Keyword="IndexNormalsFlag" Name="Index Normals Flag"
+(0024,0341) VERS="4" VR="FL" VM="1" Keyword="IndexProbability" Name="Index Probability"
+(0024,0344) VERS="4" VR="SQ" VM="1" Keyword="IndexProbabilitySequence" Name="Index Probability Sequence"
+(0028,0000) VERS="3" VR="UL" VM="1" Keyword="ImagePresentationGroupLength" Name="Image Presentation Group Length"
+(0028,0002) VERS="4" VR="US" VM="1" Keyword="SamplesPerPixel" Name="Samples per Pixel"
+(0028,0003) VERS="4" VR="US" VM="1" Keyword="SamplesPerPixelUsed" Name="Samples per Pixel Used"
+(0028,0004) VERS="4" VR="CS" VM="1" Keyword="PhotometricInterpretation" Name="Photometric Interpretation"
+(0028,0005) VERS="4RET" VR="US" VM="1" Keyword="ImageDimensions" Name="Image Dimensions"
+(0028,0006) VERS="4" VR="US" VM="1" Keyword="PlanarConfiguration" Name="Planar Configuration"
+(0028,0008) VERS="4" VR="IS" VM="1" Keyword="NumberOfFrames" Name="Number of Frames"
+(0028,0009) VERS="4" VR="AT" VM="1-n" Keyword="FrameIncrementPointer" Name="Frame Increment Pointer"
+(0028,000A) VERS="4" VR="AT" VM="1-n" Keyword="FrameDimensionPointer" Name="Frame Dimension Pointer"
+(0028,0010) VERS="4" VR="US" VM="1" Keyword="Rows" Name="Rows"
+(0028,0011) VERS="4" VR="US" VM="1" Keyword="Columns" Name="Columns"
+(0028,0012) VERS="4RET" VR="US" VM="1" Keyword="Planes" Name="Planes"
+(0028,0014) VERS="4" VR="US" VM="1" Keyword="UltrasoundColorDataPresent" Name="Ultrasound Color Data Present"
+(0028,0020) VERS="4RET" VR="" VM="" Keyword="" Name=""
+(0028,0030) VERS="4" VR="DS" VM="2" Keyword="PixelSpacing" Name="Pixel Spacing"
+(0028,0031) VERS="4" VR="DS" VM="2" Keyword="ZoomFactor" Name="Zoom Factor"
+(0028,0032) VERS="4" VR="DS" VM="2" Keyword="ZoomCenter" Name="Zoom Center"
+(0028,0034) VERS="4" VR="IS" VM="2" Keyword="PixelAspectRatio" Name="Pixel Aspect Ratio"
+(0028,0040) VERS="4RET" VR="CS" VM="1" Keyword="ImageFormat" Name="Image Format"
+(0028,0050) VERS="4RET" VR="LO" VM="1-n" Keyword="ManipulatedImage" Name="Manipulated Image"
+(0028,0051) VERS="4" VR="CS" VM="1-n" Keyword="CorrectedImage" Name="Corrected Image"
+(0028,005F) VERS="4RET" VR="LO" VM="1" Keyword="CompressionRecognitionCode" Name="Compression Recognition Code"
+(0028,0060) VERS="4RET" VR="CS" VM="1" Keyword="CompressionCode" Name="Compression Code"
+(0028,0061) VERS="4RET" VR="SH" VM="1" Keyword="CompressionOriginator" Name="Compression Originator"
+(0028,0062) VERS="4RET" VR="LO" VM="1" Keyword="CompressionLabel" Name="Compression Label"
+(0028,0063) VERS="4RET" VR="SH" VM="1" Keyword="CompressionDescription" Name="Compression Description"
+(0028,0065) VERS="4RET" VR="CS" VM="1-n" Keyword="CompressionSequence" Name="Compression Sequence"
+(0028,0066) VERS="4RET" VR="AT" VM="1-n" Keyword="CompressionStepPointers" Name="Compression Step Pointers"
+(0028,0068) VERS="4RET" VR="US" VM="1" Keyword="RepeatInterval" Name="Repeat Interval"
+(0028,0069) VERS="4RET" VR="US" VM="1" Keyword="BitsGrouped" Name="Bits Grouped"
+(0028,0070) VERS="4RET" VR="US" VM="1-n" Keyword="PerimeterTable" Name="Perimeter Table"
+(0028,0071) VERS="4RET" VR="US/SS" Keyword="PerimeterValue" Name="Perimeter Value"
+(0028,0080) VERS="4RET" VR="US" VM="1" Keyword="PredictorRows" Name="Predictor Rows"
+(0028,0081) VERS="4RET" VR="US" VM="1" Keyword="PredictorColumns" Name="Predictor Columns"
+(0028,0082) VERS="4RET" VR="US" VM="1-n" Keyword="PredictorConstants" Name="Predictor Constants"
+(0028,0090) VERS="4RET" VR="CS" VM="1" Keyword="BlockedPixels" Name="Blocked Pixels"
+(0028,0091) VERS="4RET" VR="US" VM="1" Keyword="BlockRows" Name="Block Rows"
+(0028,0092) VERS="4RET" VR="US" VM="1" Keyword="BlockColumns" Name="Block Columns"
+(0028,0093) VERS="4RET" VR="US" VM="1" Keyword="RowOverlap" Name="Row Overlap"
+(0028,0094) VERS="4RET" VR="US" VM="1" Keyword="ColumnOverlap" Name="Column Overlap"
+(0028,0100) VERS="4" VR="US" VM="1" Keyword="BitsAllocated" Name="Bits Allocated"
+(0028,0101) VERS="4" VR="US" VM="1" Keyword="BitsStored" Name="Bits Stored"
+(0028,0102) VERS="4" VR="US" VM="1" Keyword="HighBit" Name="High Bit"
+(0028,0103) VERS="4" VR="US" VM="1" Keyword="PixelRepresentation" Name="Pixel Representation"
+(0028,0104) VERS="4RET" VR="US/SS" VM="1" Keyword="SmallestValidPixelValue" Name="Smallest Valid Pixel Value"
+(0028,0105) VERS="4RET" VR="US/SS" VM="1" Keyword="LargestValidPixelValue" Name="Largest Valid Pixel Value"
+(0028,0106) VERS="4" VR="US/SS" VM="1" Keyword="SmallestImagePixelValue" Name="Smallest Image Pixel Value"
+(0028,0107) VERS="4" VR="US/SS" VM="1" Keyword="LargestImagePixelValue" Name="Largest Image Pixel Value"
+(0028,0108) VERS="4" VR="US/SS" VM="1" Keyword="SmallestPixelValueInSeries" Name="Smallest Pixel Value in Series"
+(0028,0109) VERS="4" VR="US/SS" VM="1" Keyword="LargestPixelValueInSeries" Name="Largest Pixel Value in Series"
+(0028,0110) VERS="4RET" VR="US/SS" VM="1" Keyword="SmallestImagePixelValueInPlane" Name="Smallest Image Pixel Value in Plane"
+(0028,0111) VERS="4RET" VR="US/SS" VM="1" Keyword="LargestImagePixelValueInPlane" Name="Largest Image Pixel Value in Plane"
+(0028,0120) VERS="4" VR="US/SS" VM="1" Keyword="ixelPaddingValue" Name="Pixel Padding Value"
+(0028,0121) VERS="4" VR="US/SS" VM="1" Keyword="PixelPaddingRangeLimit" Name="Pixel Padding Range Limit"
+(0028,0200) VERS="4RET" VR="US" VM="1" Keyword="ImageLocation" Name="Image Location"
+(0028,0300) VERS="4" VR="CS" VM="1" Keyword="QualityControlImage" Name="Quality Control Image"
+(0028,0301) VERS="4" VR="CS" VM="1" Keyword="BurnedInAnnotation" Name="Burned In Annotation"
+(0028,0302) VERS="4" VR="CS" VM="1" Keyword="RecognizableVisualFeatures" Name="Recognizable Visual Features"
+(0028,0303) VERS="4" VR="CS" VM="1" Keyword="LongitudinalTemporalInformationModified" Name="Longitudinal Temporal Information Modified"
+(0028,0400) VERS="4RET" VR="LO" VM="1" Keyword="TransformLabel" Name="Transform Label"
+(0028,0401) VERS="4RET" VR="LO" VM="1" Keyword="TransformVersionNumber" Name="Transform Version Number"
+(0028,0402) VERS="4RET" VR="US" VM="1" Keyword="NumberOfTransformSteps" Name="Number of Transform Steps"
+(0028,0403) VERS="4RET" VR="LO" VM="1-n" Keyword="SequenceOfCompressedData" Name="Sequence of Compressed Data"
+(0028,0404) VERS="4RET" VR="AT" VM="1-n" Keyword="DetailsOfCoefficients" Name="Details of Coefficients"
+(0028,04x0) VERS="4RET" VR="US" VM="1" Keyword="RowsForNthOrderCoefficients" Name="Rows For Nth Order Coefficients"
+(0028,04x1) VERS="4RET" VR="US" VM="1" Keyword="ColumnsForNthOrderCoefficients" Name="Columns For Nth Order Coefficients"
+(0028,04x2) VERS="4RET" VR="LO" VM="1-n" Keyword="CoefficientCoding" Name="Coefficient Coding"
+(0028,04x3) VERS="4RET" VR="AT" VM="1-n" Keyword="CoefficientCodingPointers" Name="Coefficient Coding Pointers"
+(0028,0700) VERS="4RET" VR="LO" VM="1" Keyword="DCTLabel" Name="DCT Label"
+(0028,0701) VERS="4RET" VR="CS" VM="1-n" Keyword="DataBlockDescription" Name="Data Block Description"
+(0028,0702) VERS="4RET" VR="AT" VM="1-n" Keyword="DataBlock" Name="Data Block"
+(0028,0710) VERS="4RET" VR="US" VM="1" Keyword="NormalizationFactorFormat" Name="Normalization Factor Format"
+(0028,0720) VERS="4RET" VR="US" VM="1" Keyword="ZonalMapNumberFormat" Name="Zonal Map Number Format"
+(0028,0721) VERS="4RET" VR="AT" VM="1-n" Keyword="ZonalMapLocation" Name="Zonal Map Location"
+(0028,0722) VERS="4RET" VR="US" VM="1" Keyword="ZonalMapFormat" Name="Zonal Map Format"
+(0028,0730) VERS="4RET" VR="US" VM="1" Keyword="AdaptiveMapFormat" Name="Adaptive Map Format"
+(0028,0740) VERS="4RET" VR="US" VM="1" Keyword="CodeNumberFormat" Name="Code Number Format"
+(0028,08x0) VERS="4RET" VR="CS" VM="1-n" Keyword="CodeLabel" Name="Code Label"
+(0028,08x2) VERS="4RET" VR="US" VM="1" Keyword="NumberOfTables" Name="Number of Tables"
+(0028,08x3) VERS="4RET" VR="AT" VM="1-n" Keyword="CodeTableLocation" Name="Code Table Location"
+(0028,08x4) VERS="4RET" VR="US" VM="1" Keyword="BitsForCodeWord" Name="Bits For Code Word"
+(0028,08x8) VERS="4RET" VR="AT" VM="1-n" Keyword="ImageDataLocation" Name="Image Data Location"
+(0028,0A02) VERS="4" VR="CS" VM="1" Keyword="PixelSpacingCalibrationType" Name="Pixel Spacing Calibration Type"
+(0028,0A04) VERS="4" VR="LO" VM="1" Keyword="PixelSpacingCalibrationDescription" Name="Pixel Spacing Calibration Description"
+(0028,1040) VERS="4" VR="CS" VM="1" Keyword="PixelIntensityRelationship" Name="Pixel Intensity Relationship"
+(0028,1041) VERS="4" VR="SS" VM="1" Keyword="PixelIntensityRelationshipSign" Name="Pixel Intensity Relationship Sign"
+(0028,1050) VERS="4" VR="DS" VM="1-n" Keyword="WindowCenter" Name="Window Center"
+(0028,1051) VERS="4" VR="DS" VM="1-n" Keyword="WindowWidth" Name="Window Width"
+(0028,1052) VERS="4" VR="DS" VM="1" Keyword="RescaleIntercept" Name="Rescale Intercept"
+(0028,1053) VERS="4" VR="DS" VM="1" Keyword="RescaleSlope" Name="Rescale Slope"
+(0028,1054) VERS="4" VR="LO" VM="1" Keyword="RescaleType" Name="Rescale Type"
+(0028,1055) VERS="4" VR="LO" VM="1-n" Keyword="WindowCenterWidthExplanation" Name="Window Center & Width Explanation"
+(0028,1056) VERS="4" VR="CS" VM="1" Keyword="VOILUTFunction" Name="VOI LUT Function"
+(0028,1080) VERS="4RET" VR="CS" VM="1" Keyword="GrayScale" Name="Gray Scale"
+(0028,1090) VERS="4" VR="CS" VM="1" Keyword="RecommendedViewingMode" Name="Recommended Viewing Mode"
+(0028,1100) VERS="4RET" VR="US/SS" VM="3" Keyword="GrayLookupTableDescriptor" Name="Gray Lookup Table Descriptor"
+(0028,1101) VERS="4" VR="US/SS" VM="3" Keyword="RedPaletteColorLookupTableDescriptor" Name="Red Palette Color Lookup Table Descriptor"
+(0028,1102) VERS="4" VR="US/SS" VM="3" Keyword="GreenPaletteColorLookupTableDescriptor" Name="Green Palette Color Lookup Table Descriptor"
+(0028,1103) VERS="4" VR="US/SS" VM="3" Keyword="BluePaletteColorLookupTableDescriptor" Name="Blue Palette Color Lookup Table Descriptor"
+(0028,1104) VERS="4" VR="US" VM="3" Keyword="AlphaPaletteColorLookupTableDescriptor" Name="Alpha Palette Color Lookup Table Descriptor"
+(0028,1111) VERS="4RET" VR="US/SS" VM="4" Keyword="LargeRedPaletteColorLookupTableDescriptor" Name="Large Red Palette Color Lookup Table Descriptor"
+(0028,1112) VERS="4RET" VR="US/SS" VM="4" Keyword="LargeGreenPaletteColorLookupTableDescriptor" Name="Large Green Palette Color Lookup Table Descriptor"
+(0028,1113) VERS="4RET" VR="US/SS" VM="4" Keyword="LargeBluePaletteColorLookupTableDescriptor" Name="Large Blue Palette Color Lookup Table Descriptor"
+(0028,1199) VERS="4" VR="UI" VM="1" Keyword="PaletteColorLookupTableUID" Name="Palette Color Lookup Table UID"
+(0028,1200) VERS="4"1 VR="US/SS/OW" VM="1-n" Keyword="GrayLookupTableData" Name="Gray Lookup Table Data"
+(0028,1201) VERS="4" VR="OW" VM="1" Keyword="RedPaletteColorLookupTableData" Name="Red Palette Color Lookup Table Data"
+(0028,1202) VERS="4" VR="OW" VM="1" Keyword="GreenPaletteColorLookupTableData" Name="Green Palette Color Lookup Table Data"
+(0028,1203) VERS="4" VR="OW" VM="1" Keyword="BluePaletteColorLookupTableData" Name="Blue Palette Color Lookup Table Data"
+(0028,1204) VERS="4" VR="OW" VM="1" Keyword="AlphaPaletteColorLookupTableData" Name="Alpha Palette Color Lookup Table Data"
+(0028,1211) VERS="4RET" VR="OW" VM="1" Keyword="LargeRedPaletteColorLookupTableData" Name="Large Red Palette Color Lookup Table Data"
+(0028,1212) VERS="4RET" VR="OW" VM="1" Keyword="LargeGreenPaletteColorLookupTableData" Name="Large Green Palette Color Lookup Table Data"
+(0028,1213) VERS="4RET" VR="OW" VM="1" Keyword="LargeBluePaletteColorLookupTableData" Name="Large Blue Palette Color Lookup Table Data"
+(0028,1214) VERS="4RET" VR="UI" VM="1" Keyword="LargePaletteColorLookupTableUID" Name="Large Palette Color Lookup Table UID"
+(0028,1221) VERS="4" VR="OW" VM="1" Keyword="SegmentedRedPaletteColorLookupTableData" Name="Segmented Red Palette Color Lookup Table Data"
+(0028,1222) VERS="4" VR="OW" VM="1" Keyword="SegmentedGreenPaletteColorLookupTableData" Name="Segmented Green Palette Color Lookup Table Data"
+(0028,1223) VERS="4" VR="OW" VM="1" Keyword="SegmentedBluePaletteColorLookupTableData" Name="Segmented Blue Palette Color Lookup Table Data"
+(0028,1300) VERS="4" VR="CS" VM="1" Keyword="BreastImplantPresent" Name="Breast Implant Present"
+(0028,1350) VERS="4" VR="CS" VM="1" Keyword="PartialView" Name="Partial View"
+(0028,1351) VERS="4" VR="ST" VM="1" Keyword="PartialViewDescription" Name="Partial View Description"
+(0028,1352) VERS="4" VR="SQ" VM="1" Keyword="PartialViewCodeSequence" Name="Partial View Code Sequence"
+(0028,135A) VERS="4" VR="CS" VM="1" Keyword="SpatialLocationsPreserved" Name="Spatial Locations Preserved"
+(0028,1401) VERS="4" VR="SQ" VM="1" Keyword="DataFrameAssignmentSequence" Name="Data Frame Assignment Sequence"
+(0028,1402) VERS="4" VR="CS" VM="1" Keyword="DataPathAssignment" Name="Data Path Assignment"
+(0028,1403) VERS="4" VR="US" VM="1" Keyword="BitsMappedToColorLookupTable" Name="Bits Mapped to Color Lookup Table"
+(0028,1404) VERS="4" VR="SQ" VM="1" Keyword="BlendingLUT1Sequence" Name="Blending LUT 1 Sequence"
+(0028,1405) VERS="4" VR="CS" VM="1" Keyword="BlendingLUT1TransferFunction" Name="Blending LUT 1 Transfer Function"
+(0028,1406) VERS="4" VR="FD" VM="1" Keyword="BlendingWeightConstant" Name="Blending Weight Constant"
+(0028,1407) VERS="4" VR="US" VM="3" Keyword="BlendingLookupTableDescriptor" Name="Blending Lookup Table Descriptor"
+(0028,1408) VERS="4" VR="OW" VM="1" Keyword="BlendingLookupTableData" Name="Blending Lookup Table Data"
+(0028,140B) VERS="4" VR="SQ" VM="1" Keyword="EnhancedPaletteColorLookupTableSequence" Name="Enhanced Palette Color Lookup Table Sequence"
+(0028,140C) VERS="4" VR="SQ" VM="1" Keyword="BlendingLUT2Sequence" Name="Blending LUT 2 Sequence"
+(0028,140D) VERS="4" VR="CS" VM="1" Keyword="BlendingLUT2TransferFunction" Name="Blending LUT 2 Transfer Function"
+(0028,140E) VERS="4" VR="CS" VM="1" Keyword="DataPathID" Name="Data Path ID"
+(0028,140F) VERS="4" VR="CS" VM="1" Keyword="RGBLUTTransferFunction" Name="RGB LUT Transfer Function"
+(0028,1410) VERS="4" VR="CS" VM="1" Keyword="AlphaLUTTransferFunction" Name="Alpha LUT Transfer Function"
+(0028,2000) VERS="4" VR="OB" VM="1" Keyword="ICCProfile" Name="ICC Profile"
+(0028,2110) VERS="4" VR="CS" VM="1" Keyword="LossyImageCompression" Name="Lossy Image Compression"
+(0028,2112) VERS="4" VR="DS" VM="1-n" Keyword="LossyImageCompressionRatio" Name="Lossy Image Compression Ratio"
+(0028,2114) VERS="4" VR="CS" VM="1-n" Keyword="LossyImageCompressionMethod" Name="Lossy Image Compression Method"
+(0028,3000) VERS="4" VR="SQ" VM="1" Keyword="ModalityLUTSequence" Name="Modality LUT Sequence"
+(0028,3002) VERS="4" VR="US/SS" VM="3" Keyword="LUTDescriptor" Name="LUT Descriptor"
+(0028,3003) VERS="4" VR="LO" VM="1" Keyword="LUTExplanation" Name="LUT Explanation"
+(0028,3004) VERS="4" VR="LO" VM="1" Keyword="ModalityLUTType" Name="Modality LUT Type"
+(0028,3006) VERS="4"1 VR="US/OW" VM="1-n" Keyword="LUTData" Name="LUT Data"
+(0028,3010) VERS="4" VR="SQ" VM="1" Keyword="VOILUTSequence" Name="VOI LUT Sequence"
+(0028,3110) VERS="4" VR="SQ" VM="1" Keyword="SoftcopyVOILUTSequence" Name="Softcopy VOI LUT Sequence"
+(0028,4000) VERS="4RET" VR="LT" VM="1" Keyword="ImagePresentationComments" Name="Image Presentation Comments"
+(0028,5000) VERS="4RET" VR="SQ" VM="1" Keyword="BiPlaneAcquisitionSequence" Name="Bi-Plane Acquisition Sequence"
+(0028,6010) VERS="4" VR="US" VM="1" Keyword="RepresentativeFrameNumber" Name="Representative Frame Number"
+(0028,6020) VERS="4" VR="US" VM="1-n" Keyword="FrameNumbersOfInterest" Name="Frame Numbers of Interest (FOI) "
+(0028,6022) VERS="4" VR="LO" VM="1-n" Keyword="FrameOfInterestDescription" Name="Frame of Interest Description"
+(0028,6023) VERS="4" VR="CS" VM="1-n" Keyword="FrameOfInterestType" Name="Frame of Interest Type"
+(0028,6030) VERS="4RET" VR="US" VM="1-n" Keyword="MaskPointers" Name="Mask Pointer(s)"
+(0028,6040) VERS="4" VR="US" VM="1-n" Keyword="RWavePointer" Name="R Wave Pointer"
+(0028,6100) VERS="4" VR="SQ" VM="1" Keyword="MaskSubtractionSequence" Name="Mask Subtraction Sequence"
+(0028,6101) VERS="4" VR="CS" VM="1" Keyword="MaskOperation" Name="Mask Operation"
+(0028,6102) VERS="4" VR="US" VM="2-2n" Keyword="ApplicableFrameRange" Name="Applicable Frame Range"
+(0028,6110) VERS="4" VR="US" VM="1-n" Keyword="MaskFrameNumbers" Name="Mask Frame Numbers"
+(0028,6112) VERS="4" VR="US" VM="1" Keyword="ContrastFrameAveraging" Name="Contrast Frame Averaging"
+(0028,6114) VERS="4" VR="FL" VM="2" Keyword="MaskSubPixelShift" Name="Mask Sub-pixel Shift"
+(0028,6120) VERS="4" VR="SS" VM="1" Keyword="TIDOffset" Name="TID Offset"
+(0028,6190) VERS="4" VR="ST" VM="1" Keyword="MaskOperationExplanation" Name="Mask Operation Explanation"
+(0028,7FE0) VERS="4" VR="UT" VM="1" Keyword="PixelDataProviderURL" Name="Pixel Data Provider URL"
+(0028,9001) VERS="4" VR="UL" VM="1" Keyword="DataPointRows" Name="Data Point Rows"
+(0028,9002) VERS="4" VR="UL" VM="1" Keyword="DataPointColumns" Name="Data Point Columns"
+(0028,9003) VERS="4" VR="CS" VM="1" Keyword="SignalDomainColumns" Name="Signal Domain Columns"
+(0028,9099) VERS="4RET" VR="US" VM="1" Keyword="LargestMonochromePixelValue" Name="Largest Monochrome Pixel Value"
+(0028,9108) VERS="4" VR="CS" VM="1" Keyword="DataRepresentation" Name="Data Representation"
+(0028,9110) VERS="4" VR="SQ" VM="1" Keyword="PixelMeasuresSequence" Name="Pixel Measures Sequence"
+(0028,9132) VERS="4" VR="SQ" VM="1" Keyword="FrameVOILUTSequence" Name="Frame VOI LUT Sequence"
+(0028,9145) VERS="4" VR="SQ" VM="1" Keyword="PixelValueTransformationSequence" Name="Pixel Value Transformation Sequence"
+(0028,9235) VERS="4" VR="CS" VM="1" Keyword="SignalDomainRows" Name="Signal Domain Rows"
+(0028,9411) VERS="4" VR="FL" VM="1" Keyword="DisplayFilterPercentage" Name="Display Filter Percentage"
+(0028,9415) VERS="4" VR="SQ" VM="1" Keyword="FramePixelShiftSequence" Name="Frame Pixel Shift Sequence"
+(0028,9416) VERS="4" VR="US" VM="1" Keyword="SubtractionItemID" Name="Subtraction Item ID"
+(0028,9422) VERS="4" VR="SQ" VM="1" Keyword="PixelIntensityRelationshipLUTSequence" Name="Pixel Intensity Relationship LUT Sequence"
+(0028,9443) VERS="4" VR="SQ" VM="1" Keyword="FramePixelDataPropertiesSequence" Name="Frame Pixel Data Properties Sequence"
+(0028,9444) VERS="4" VR="CS" VM="1" Keyword="GeometricalProperties" Name="Geometrical Properties"
+(0028,9445) VERS="4" VR="FL" VM="1" Keyword="GeometricMaximumDistortion" Name="Geometric Maximum Distortion"
+(0028,9446) VERS="4" VR="CS" VM="1-n" Keyword="ImageProcessingApplied" Name="Image Processing Applied"
+(0028,9454) VERS="4" VR="CS" VM="1" Keyword="MaskSelectionMode" Name="Mask Selection Mode"
+(0028,9474) VERS="4" VR="CS" VM="1" Keyword="LUTFunction" Name="LUT Function"
+(0028,9478) VERS="4" VR="FL" VM="1" Keyword="MaskVisibilityPercentage" Name="Mask Visibility Percentage"
+(0028,9501) VERS="4" VR="SQ" VM="1" Keyword="PixelShiftSequence" Name="Pixel Shift Sequence"
+(0028,9502) VERS="4" VR="SQ" VM="1" Keyword="RegionPixelShiftSequence" Name="Region Pixel Shift Sequence"
+(0028,9503) VERS="4" VR="SS" VM="2-2n" Keyword="VerticesOfTheRegion" Name="Vertices of the Region"
+(0028,9505) VERS="4" VR="SQ" VM="1" Keyword="MultiFramePresentationSequence" Name="Multi-frame Presentation Sequence"
+(0028,9506) VERS="4" VR="US" VM="2-2n" Keyword="PixelShiftFrameRange" Name="Pixel Shift Frame Range"
+(0028,9507) VERS="4" VR="US" VM="2-2n" Keyword="LUTFrameRange" Name="LUT Frame Range"
+(0028,9520) VERS="4" VR="DS" VM="16" Keyword="ImageToEquipmentMappingMatrix" Name="Image to Equipment Mapping Matrix"
+(0028,9537) VERS="4" VR="CS" VM="1" Keyword="EquipmentCoordinateSystemIdentification" Name="Equipment Coordinate System Identification"
+(0032,0000) VERS="3" VR="UL" VM="1" Keyword="StudyGroupLength" Name="Study Group Length"
+(0032,000A) VERS="4RET" VR="CS" VM="1" Keyword="StudyStatusID" Name="Study Status ID"
+(0032,000C) VERS="4RET" VR="CS" VM="1" Keyword="StudyPriorityID" Name="Study Priority ID"
+(0032,0012) VERS="4RET" VR="LO" VM="1" Keyword="StudyIDIssuer" Name="Study ID Issuer"
+(0032,0032) VERS="4RET" VR="DA" VM="1" Keyword="StudyVerifiedDate" Name="Study Verified Date"
+(0032,0033) VERS="4RET" VR="TM" VM="1" Keyword="StudyVerifiedTime" Name="Study Verified Time"
+(0032,0034) VERS="4RET" VR="DA" VM="1" Keyword="StudyReadDate" Name="Study Read Date"
+(0032,0035) VERS="4RET" VR="TM" VM="1" Keyword="StudyReadTime" Name="Study Read Time"
+(0032,1000) VERS="4RET" VR="DA" VM="1" Keyword="ScheduledStudyStartDate" Name="Scheduled Study Start Date"
+(0032,1001) VERS="4RET" VR="TM" VM="1" Keyword="ScheduledStudyStartTime" Name="Scheduled Study Start Time"
+(0032,1010) VERS="4RET" VR="DA" VM="1" Keyword="ScheduledStudyStopDate" Name="Scheduled Study Stop Date"
+(0032,1011) VERS="4RET" VR="TM" VM="1" Keyword="ScheduledStudyStopTime" Name="Scheduled Study Stop Time"
+(0032,1020) VERS="4RET" VR="LO" VM="1" Keyword="ScheduledStudyLocation" Name="Scheduled Study Location"
+(0032,1021) VERS="4RET" VR="AE" VM="1-n" Keyword="ScheduledStudyLocationAETitle" Name="Scheduled Study Location AE Title"
+(0032,1030) VERS="4RET" VR="LO" VM="1" Keyword="ReasonForStudy" Name="Reason for Study"
+(0032,1031) VERS="4" VR="SQ" VM="1" Keyword="RequestingPhysicianIdentificationSequence" Name="Requesting Physician Identification Sequence"
+(0032,1032) VERS="4" VR="PN" VM="1" Keyword="RequestingPhysician" Name="Requesting Physician"
+(0032,1033) VERS="4" VR="LO" VM="1" Keyword="RequestingService" Name="Requesting Service"
+(0032,1034) VERS="4" VR="SQ" VM="1" Keyword="RequestingServiceCodeSequence" Name="Requesting Service Code Sequence"
+(0032,1040) VERS="4RET" VR="DA" VM="1" Keyword="StudyArrivalDate" Name="Study Arrival Date"
+(0032,1041) VERS="4RET" VR="TM" VM="1" Keyword="StudyArrivalTime" Name="Study Arrival Time"
+(0032,1050) VERS="4RET" VR="DA" VM="1" Keyword="StudyCompletionDate" Name="Study Completion Date"
+(0032,1051) VERS="4RET" VR="TM" VM="1" Keyword="StudyCompletionTime" Name="Study Completion Time"
+(0032,1055) VERS="4RET" VR="CS" VM="1" Keyword="StudyComponentStatusID" Name="Study Component Status ID"
+(0032,1060) VERS="4" VR="LO" VM="1" Keyword="RequestedProcedureDescription" Name="Requested Procedure Description"
+(0032,1064) VERS="4" VR="SQ" VM="1" Keyword="RequestedProcedureCodeSequence" Name="Requested Procedure Code Sequence"
+(0032,1070) VERS="4" VR="LO" VM="1" Keyword="RequestedContrastAgent" Name="Requested Contrast Agent"
+(0032,4000) VERS="4RET" VR="LT" VM="1" Keyword="StudyComments" Name="Study Comments"
+(0038,0000) VERS="3" VR="UL" VM="1" Keyword="VisitGroupLength" Name="Visit Group Length"
+(0038,0004) VERS="4" VR="SQ" VM="1" Keyword="ReferencedPatientAliasSequence" Name="Referenced Patient Alias Sequence"
+(0038,0008) VERS="4" VR="CS" VM="1" Keyword="VisitStatusID" Name="Visit Status ID"
+(0038,0010) VERS="4" VR="LO" VM="1" Keyword="AdmissionID" Name="Admission ID"
+(0038,0011) VERS="4RET" VR="LO" VM="1" Keyword="IssuerOfAdmissionID" Name="Issuer of Admission ID"
+(0038,0014) VERS="4" VR="SQ" VM="1" Keyword="IssuerOfAdmissionIDSequence" Name="Issuer of Admission ID Sequence"
+(0038,0016) VERS="4" VR="LO" VM="1" Keyword="RouteOfAdmissions" Name="Route of Admissions"
+(0038,001A) VERS="4RET" VR="DA" VM="1" Keyword="ScheduledAdmissionDate" Name="Scheduled Admission Date"
+(0038,001B) VERS="4RET" VR="TM" VM="1" Keyword="ScheduledAdmissionTime" Name="Scheduled Admission Time"
+(0038,001C) VERS="4RET" VR="DA" VM="1" Keyword="ScheduledDischargeDate" Name="Scheduled Discharge Date"
+(0038,001D) VERS="4RET" VR="TM" VM="1" Keyword="ScheduledDischargeTime" Name="Scheduled Discharge Time"
+(0038,001E) VERS="4RET" VR="LO" VM="1" Keyword="ScheduledPatientInstitutionResidence" Name="Scheduled Patient Institution Residence"
+(0038,0020) VERS="4" VR="DA" VM="1" Keyword="AdmittingDate" Name="Admitting Date"
+(0038,0021) VERS="4" VR="TM" VM="1" Keyword="AdmittingTime" Name="Admitting Time"
+(0038,0030) VERS="4RET" VR="DA" VM="1" Keyword="DischargeDate" Name="Discharge Date"
+(0038,0032) VERS="4RET" VR="TM" VM="1" Keyword="DischargeTime" Name="Discharge Time"
+(0038,0040) VERS="4RET" VR="LO" VM="1" Keyword="DischargeDiagnosisDescription" Name="Discharge Diagnosis Description"
+(0038,0044) VERS="4RET" VR="SQ" VM="1" Keyword="DischargeDiagnosisCodeSequence" Name="Discharge Diagnosis Code Sequence"
+(0038,0050) VERS="4" VR="LO" VM="1" Keyword="SpecialNeeds" Name="Special Needs"
+(0038,0060) VERS="4" VR="LO" VM="1" Keyword="ServiceEpisodeID" Name="Service Episode ID"
+(0038,0061) VERS="4RET" VR="LO" VM="1" Keyword="IssuerOfServiceEpisodeID" Name="Issuer of Service Episode ID"
+(0038,0062) VERS="4" VR="LO" VM="1" Keyword="ServiceEpisodeDescription" Name="Service Episode Description"
+(0038,0064) VERS="4" VR="SQ" VM="1" Keyword="IssuerOfServiceEpisodeIDSequence" Name="Issuer of Service Episode ID Sequence"
+(0038,0100) VERS="4" VR="SQ" VM="1" Keyword="PertinentDocumentsSequence" Name="Pertinent Documents Sequence"
+(0038,0300) VERS="4" VR="LO" VM="1" Keyword="CurrentPatientLocation" Name="Current Patient Location"
+(0038,0400) VERS="4" VR="LO" VM="1" Keyword="PatientInstitutionResidence" Name="Patient�s Institution Residence"
+(0038,0500) VERS="4" VR="LO" VM="1" Keyword="PatientState" Name="Patient State"
+(0038,0502) VERS="4" VR="SQ" VM="1" Keyword="PatientClinicalTrialParticipationSequence" Name="Patient Clinical Trial Participation Sequence"
+(0038,4000) VERS="4" VR="LT" VM="1" Keyword="VisitComments" Name="Visit Comments"
+(003A,0004) VERS="4" VR="CS" VM="1" Keyword="WaveformOriginality" Name="Waveform Originality"
+(003A,0005) VERS="4" VR="US" VM="1" Keyword="NumberOfWaveformChannels" Name="Number of Waveform Channels "
+(003A,0010) VERS="4" VR="UL" VM="1" Keyword="NumberOfWaveformSamples" Name="Number of Waveform Samples "
+(003A,001A) VERS="4" VR="DS" VM="1" Keyword="SamplingFrequency" Name="Sampling Frequency "
+(003A,0020) VERS="4" VR="SH" VM="1" Keyword="MultiplexGroupLabel" Name="Multiplex Group Label "
+(003A,0200) VERS="4" VR="SQ" VM="1" Keyword="ChannelDefinitionSequence" Name="Channel Definition Sequence"
+(003A,0202) VERS="4" VR="IS" VM="1" Keyword="WaveformChannelNumber" Name="Waveform Channel Number "
+(003A,0203) VERS="4" VR="SH" VM="1" Keyword="ChannelLabel" Name="Channel Label"
+(003A,0205) VERS="4" VR="CS" VM="1-n" Keyword="ChannelStatus" Name="Channel Status"
+(003A,0208) VERS="4" VR="SQ" VM="1" Keyword="ChannelSourceSequence" Name="Channel Source Sequence"
+(003A,0209) VERS="4" VR="SQ" VM="1" Keyword="ChannelSourceModifiersSequence" Name="Channel Source Modifiers Sequence"
+(003A,020A) VERS="4" VR="SQ" VM="1" Keyword="SourceWaveformSequence" Name="Source Waveform Sequence"
+(003A,020C) VERS="4" VR="LO" VM="1" Keyword="ChannelDerivationDescription" Name="Channel Derivation Description"
+(003A,0210) VERS="4" VR="DS" VM="1" Keyword="ChannelSensitivity" Name="Channel Sensitivity "
+(003A,0211) VERS="4" VR="SQ" VM="1" Keyword="ChannelSensitivityUnitsSequence" Name="Channel Sensitivity Units Sequence"
+(003A,0212) VERS="4" VR="DS" VM="1" Keyword="ChannelSensitivityCorrectionFactor" Name="Channel Sensitivity Correction Factor"
+(003A,0213) VERS="4" VR="DS" VM="1" Keyword="ChannelBaseline" Name="Channel Baseline "
+(003A,0214) VERS="4" VR="DS" VM="1" Keyword="ChannelTimeSkew" Name="Channel Time Skew"
+(003A,0215) VERS="4" VR="DS" VM="1" Keyword="ChannelSampleSkew" Name="Channel Sample Skew"
+(003A,0218) VERS="4" VR="DS" VM="1" Keyword="ChannelOffset" Name="Channel Offset"
+(003A,021A) VERS="4" VR="US" VM="1" Keyword="WaveformBitsStored" Name="Waveform Bits Stored"
+(003A,0220) VERS="4" VR="DS" VM="1" Keyword="FilterLowFrequency" Name="Filter Low Frequency"
+(003A,0221) VERS="4" VR="DS" VM="1" Keyword="FilterHighFrequency" Name="Filter High Frequency"
+(003A,0222) VERS="4" VR="DS" VM="1" Keyword="NotchFilterFrequency" Name="Notch Filter Frequency"
+(003A,0223) VERS="4" VR="DS" VM="1" Keyword="NotchFilterBandwidth" Name="Notch Filter Bandwidth"
+(003A,0230) VERS="4" VR="FL" VM="1" Keyword="WaveformDataDisplayScale" Name="Waveform Data Display Scale"
+(003A,0231) VERS="4" VR="US" VM="3" Keyword="WaveformDisplayBackgroundCIELabValue" Name="Waveform Display Background CIELab Value"
+(003A,0240) VERS="4" VR="SQ" VM="1" Keyword="WaveformPresentationGroupSequence" Name="Waveform Presentation Group Sequence"
+(003A,0241) VERS="4" VR="US" VM="1" Keyword="PresentationGroupNumber" Name="Presentation Group Number"
+(003A,0242) VERS="4" VR="SQ" VM="1" Keyword="ChannelDisplaySequence" Name="Channel Display Sequence"
+(003A,0244) VERS="4" VR="US" VM="3" Keyword="ChannelRecommendedDisplayCIELabValue" Name="Channel Recommended Display CIELab Value"
+(003A,0245) VERS="4" VR="FL" VM="1" Keyword="ChannelPosition" Name="Channel Position"
+(003A,0246) VERS="4" VR="CS" VM="1" Keyword="DisplayShadingFlag" Name="Display Shading Flag"
+(003A,0247) VERS="4" VR="FL" VM="1" Keyword="FractionalChannelDisplayScale" Name="Fractional Channel Display Scale"
+(003A,0248) VERS="4" VR="FL" VM="1" Keyword="AbsoluteChannelDisplayScale" Name="Absolute Channel Display Scale"
+(003A,0300) VERS="4" VR="SQ" VM="1" Keyword="MultiplexedAudioChannelsDescriptionCodeSequence" Name="Multiplexed Audio Channels Description Code Sequence"
+(003A,0301) VERS="4" VR="IS" VM="1" Keyword="ChannelIdentificationCode" Name="Channel Identification Code"
+(003A,0302) VERS="4" VR="CS" VM="1" Keyword="ChannelMode" Name="Channel Mode"
+(0040,0000) VERS="3" VR="UL" VM="1" Keyword="ModalityWorklistGroupLength" Name="Modality Worklist Group Length"
+(0040,0001) VERS="4" VR="AE" VM="1-n" Keyword="ScheduledStationAETitle" Name="Scheduled Station AE Title"
+(0040,0002) VERS="4" VR="DA" VM="1" Keyword="ScheduledProcedureStepStartDate" Name="Scheduled Procedure Step Start Date"
+(0040,0003) VERS="4" VR="TM" VM="1" Keyword="ScheduledProcedureStepStartTime" Name="Scheduled Procedure Step Start Time"
+(0040,0004) VERS="4" VR="DA" VM="1" Keyword="ScheduledProcedureStepEndDate" Name="Scheduled Procedure Step End Date"
+(0040,0005) VERS="4" VR="TM" VM="1" Keyword="ScheduledProcedureStepEndTime" Name="Scheduled Procedure Step End Time"
+(0040,0006) VERS="4" VR="PN" VM="1" Keyword="ScheduledPerformingPhysicianName" Name="Scheduled Performing Physician�s Name"
+(0040,0007) VERS="4" VR="LO" VM="1" Keyword="ScheduledProcedureStepDescription" Name="Scheduled Procedure Step Description"
+(0040,0008) VERS="4" VR="SQ" VM="1" Keyword="ScheduledProtocolCodeSequence" Name="Scheduled Protocol Code Sequence"
+(0040,0009) VERS="4" VR="SH" VM="1" Keyword="ScheduledProcedureStepID" Name="Scheduled Procedure Step ID"
+(0040,000A) VERS="4" VR="SQ" VM="1" Keyword="StageCodeSequence" Name="Stage Code Sequence"
+(0040,000B) VERS="4" VR="SQ" VM="1" Keyword="ScheduledPerformingPhysicianIdentificationSequence" Name="Scheduled Performing Physician Identification Sequence"
+(0040,0010) VERS="4" VR="SH" VM="1-n" Keyword="ScheduledStationName" Name="Scheduled Station Name"
+(0040,0011) VERS="4" VR="SH" VM="1" Keyword="ScheduledProcedureStepLocation" Name="Scheduled Procedure Step Location"
+(0040,0012) VERS="4" VR="LO" VM="1" Keyword="PreMedication" Name="Pre-Medication"
+(0040,0020) VERS="4" VR="CS" VM="1" Keyword="ScheduledProcedureStepStatus" Name="Scheduled Procedure Step Status"
+(0040,0026) VERS="4" VR="SQ" VM="1" Keyword="OrderPlacerIdentifierSequence" Name="Order Placer Identifier Sequence"
+(0040,0027) VERS="4" VR="SQ" VM="1" Keyword="OrderFillerIdentifierSequence" Name="Order Filler Identifier Sequence"
+(0040,0031) VERS="4" VR="UT" VM="1" Keyword="LocalNamespaceEntityID" Name="Local Namespace Entity ID"
+(0040,0032) VERS="4" VR="UT" VM="1" Keyword="UniversalEntityID" Name="Universal Entity ID"
+(0040,0033) VERS="4" VR="CS" VM="1" Keyword="UniversalEntityIDType" Name="Universal Entity ID Type"
+(0040,0035) VERS="4" VR="CS" VM="1" Keyword="IdentifierTypeCode" Name="Identifier Type Code"
+(0040,0036) VERS="4" VR="SQ" VM="1" Keyword="AssigningFacilitySequence" Name="Assigning Facility Sequence"
+(0040,0039) VERS="4" VR="SQ" VM="1" Keyword="AssigningJurisdictionCodeSequence" Name="Assigning Jurisdiction Code Sequence"
+(0040,003A) VERS="4" VR="SQ" VM="1" Keyword="AssigningAgencyOrDepartmentCodeSequence" Name="Assigning Agency or Department Code Sequence"
+(0040,0100) VERS="4" VR="SQ" VM="1" Keyword="ScheduledProcedureStepSequence" Name="Scheduled Procedure Step Sequence"
+(0040,0220) VERS="4" VR="SQ" VM="1" Keyword="ReferencedNonImageCompositeSOPInstanceSequence" Name="Referenced Non-Image Composite SOP Instance Sequence "
+(0040,0241) VERS="4" VR="AE" VM="1" Keyword="PerformedStationAETitle" Name="Performed Station AE Title"
+(0040,0242) VERS="4" VR="SH" VM="1" Keyword="PerformedStationName" Name="Performed Station Name"
+(0040,0243) VERS="4" VR="SH" VM="1" Keyword="PerformedLocation" Name="Performed Location"
+(0040,0244) VERS="4" VR="DA" VM="1" Keyword="PerformedProcedureStepStartDate" Name="Performed Procedure Step Start Date"
+(0040,0245) VERS="4" VR="TM" VM="1" Keyword="PerformedProcedureStepStartTime" Name="Performed Procedure Step Start Time"
+(0040,0250) VERS="4" VR="DA" VM="1" Keyword="PerformedProcedureStepEndDate" Name="Performed Procedure Step End Date"
+(0040,0251) VERS="4" VR="TM" VM="1" Keyword="PerformedProcedureStepEndTime" Name="Performed Procedure Step End Time"
+(0040,0252) VERS="4" VR="CS" VM="1" Keyword="PerformedProcedureStepStatus" Name="Performed Procedure Step Status"
+(0040,0253) VERS="4" VR="SH" VM="1" Keyword="PerformedProcedureStepID" Name="Performed Procedure Step ID"
+(0040,0254) VERS="4" VR="LO" VM="1" Keyword="PerformedProcedureStepDescription" Name="Performed Procedure Step Description"
+(0040,0255) VERS="4" VR="LO" VM="1" Keyword="PerformedProcedureTypeDescription" Name="Performed Procedure Type Description"
+(0040,0260) VERS="4" VR="SQ" VM="1" Keyword="PerformedProtocolCodeSequence" Name="Performed Protocol Code Sequence"
+(0040,0261) VERS="4" VR="CS" VM="1" Keyword="PerformedProtocolType" Name="Performed Protocol Type"
+(0040,0270) VERS="4" VR="SQ" VM="1" Keyword="ScheduledStepAttributesSequence" Name="Scheduled Step Attributes Sequence"
+(0040,0275) VERS="4" VR="SQ" VM="1" Keyword="RequestAttributesSequence" Name="Request Attributes Sequence"
+(0040,0280) VERS="4" VR="ST" VM="1" Keyword="CommentsOnThePerformedProcedureStep" Name="Comments on the Performed Procedure Step"
+(0040,0281) VERS="4" VR="SQ" VM="1" Keyword="PerformedProcedureStepDiscontinuationReasonCodeSequence" Name="Performed Procedure Step Discontinuation Reason Code Sequence"
+(0040,0293) VERS="4" VR="SQ" VM="1" Keyword="QuantitySequence" Name="Quantity Sequence"
+(0040,0294) VERS="4" VR="DS" VM="1" Keyword="Quantity" Name="Quantity"
+(0040,0295) VERS="4" VR="SQ" VM="1" Keyword="MeasuringUnitsSequence" Name="Measuring Units Sequence"
+(0040,0296) VERS="4" VR="SQ" VM="1" Keyword="BillingItemSequence" Name="Billing Item Sequence"
+(0040,0300) VERS="4" VR="US" VM="1" Keyword="TotalTimeOfFluoroscopy" Name="Total Time of Fluoroscopy"
+(0040,0301) VERS="4" VR="US" VM="1" Keyword="TotalNumberOfExposures" Name="Total Number of Exposures"
+(0040,0302) VERS="4" VR="US" VM="1" Keyword="EntranceDose" Name="Entrance Dose"
+(0040,0303) VERS="4" VR="US" VM="1-2" Keyword="ExposedArea" Name="Exposed Area"
+(0040,0306) VERS="4" VR="DS" VM="1" Keyword="DistanceSourceToEntrance" Name="Distance Source to Entrance"
+(0040,0307) VERS="4RET" VR="DS" VM="1" Keyword="DistanceSourceToSupport" Name="Distance Source to Support"
+(0040,030E) VERS="4" VR="SQ" VM="1" Keyword="ExposureDoseSequence" Name="Exposure Dose Sequence"
+(0040,0310) VERS="4" VR="ST" VM="1" Keyword="CommentsOnRadiationDose" Name="Comments on Radiation Dose"
+(0040,0312) VERS="4" VR="DS" VM="1" Keyword="XRayOutput" Name="X-Ray Output"
+(0040,0314) VERS="4" VR="DS" VM="1" Keyword="HalfValueLayer" Name="Half Value Layer"
+(0040,0316) VERS="4" VR="DS" VM="1" Keyword="OrganDose" Name="Organ Dose"
+(0040,0318) VERS="4" VR="CS" VM="1" Keyword="OrganExposed" Name="Organ Exposed"
+(0040,0320) VERS="4" VR="SQ" VM="1" Keyword="BillingProcedureStepSequence" Name="Billing Procedure Step Sequence"
+(0040,0321) VERS="4" VR="SQ" VM="1" Keyword="FilmConsumptionSequence" Name="Film Consumption Sequence"
+(0040,0324) VERS="4" VR="SQ" VM="1" Keyword="BillingSuppliesAndDevicesSequence" Name="Billing Supplies and Devices Sequence"
+(0040,0330) VERS="4RET" VR="SQ" VM="1" Keyword="ReferencedProcedureStepSequence" Name="Referenced Procedure Step Sequence"
+(0040,0340) VERS="4" VR="SQ" VM="1" Keyword="PerformedSeriesSequence" Name="Performed Series Sequence"
+(0040,0400) VERS="4" VR="LT" VM="1" Keyword="CommentsOnTheScheduledProcedureStep" Name="Comments on the Scheduled Procedure Step"
+(0040,0440) VERS="4" VR="SQ" VM="1" Keyword="ProtocolContextSequence" Name="Protocol Context Sequence"
+(0040,0441) VERS="4" VR="SQ" VM="1" Keyword="ContentItemModifierSequence" Name="Content Item Modifier Sequence"
+(0040,0500) VERS="4" VR="SQ" VM="1" Keyword="ScheduledSpecimenSequence" Name="Scheduled Specimen Sequence"
+(0040,050A) VERS="4RET" VR="LO" VM="1" Keyword="SpecimenAccessionNumber" Name="Specimen Accession Number"
+(0040,0512) VERS="4" VR="LO" VM="1" Keyword="ContainerIdentifier" Name="Container Identifier"
+(0040,0513) VERS="4" VR="SQ" VM="1" Keyword="IssuerOfTheContainerIdentifierSequence" Name="Issuer of the Container Identifier Sequence"
+(0040,0515) VERS="4" VR="SQ" VM="1" Keyword="AlternateContainerIdentifierSequence" Name="Alternate Container Identifier Sequence"
+(0040,0518) VERS="4" VR="SQ" VM="1" Keyword="ContainerTypeCodeSequence" Name="Container Type Code Sequence"
+(0040,051A) VERS="4" VR="LO" VM="1" Keyword="ContainerDescription" Name="Container Description"
+(0040,0520) VERS="4" VR="SQ" VM="1" Keyword="ContainerComponentSequence" Name="Container Component Sequence"
+(0040,0550) VERS="4RET" VR="SQ" VM="1" Keyword="SpecimenSequence" Name="Specimen Sequence"
+(0040,0551) VERS="4" VR="LO" VM="1" Keyword="SpecimenIdentifier" Name="Specimen Identifier"
+(0040,0552) VERS="4RET" VR="SQ" VM="1" Keyword="SpecimenDescriptionSequenceTrial" Name="Specimen Description Sequence (Trial)"
+(0040,0553) VERS="4RET" VR="ST" VM="1" Keyword="SpecimenDescriptionTrial" Name="Specimen Description (Trial)"
+(0040,0554) VERS="4" VR="UI" VM="1" Keyword="SpecimenUID" Name="Specimen UID"
+(0040,0555) VERS="4" VR="SQ" VM="1" Keyword="AcquisitionContextSequence" Name="Acquisition Context Sequence"
+(0040,0556) VERS="4" VR="ST" VM="1" Keyword="AcquisitionContextDescription" Name="Acquisition Context Description"
+(0040,0560) VERS="4" VR="SQ" VM="1" Keyword="SpecimenDescriptionSequence" Name="Specimen Description Sequence"
+(0040,0562) VERS="4" VR="SQ" VM="1" Keyword="IssuerOfTheSpecimenIdentifierSequence" Name="Issuer of the Specimen Identifier Sequence"
+(0040,059A) VERS="4" VR="SQ" VM="1" Keyword="SpecimenTypeCodeSequence" Name="Specimen Type Code Sequence"
+(0040,0600) VERS="4" VR="LO" VM="1" Keyword="SpecimenShortDescription" Name="Specimen Short Description "
+(0040,0602) VERS="4" VR="UT" VM="1" Keyword="SpecimenDetailedDescription" Name="Specimen Detailed Description "
+(0040,0610) VERS="4" VR="SQ" VM="1" Keyword="SpecimenPreparationSequence" Name="Specimen Preparation Sequence"
+(0040,0612) VERS="4" VR="SQ" VM="1" Keyword="SpecimenPreparationStepContentItemSequence" Name="Specimen Preparation Step Content Item Sequence"
+(0040,0620) VERS="4" VR="SQ" VM="1" Keyword="SpecimenLocalizationContentItemSequence" Name="Specimen Localization Content Item Sequence"
+(0040,06FA) VERS="4RET" VR="LO" VM="1" Keyword="SlideIdentifier" Name="Slide Identifier"
+(0040,071A) VERS="4" VR="SQ" VM="1" Keyword="ImageCenterPointCoordinatesSequence" Name="Image Center Point Coordinates Sequence"
+(0040,072A) VERS="4" VR="DS" VM="1" Keyword="XOffsetInSlideCoordinateSystem" Name="X Offset in Slide Coordinate System"
+(0040,073A) VERS="4" VR="DS" VM="1" Keyword="YOffsetInSlideCoordinateSystem" Name="Y Offset in Slide Coordinate System"
+(0040,074A) VERS="4" VR="DS" VM="1" Keyword="ZOffsetInSlideCoordinateSystem" Name="Z Offset in Slide Coordinate System"
+(0040,08D8) VERS="4RET" VR="SQ" VM="1" Keyword="PixelSpacingSequence" Name="Pixel Spacing Sequence"
+(0040,08DA) VERS="4RET" VR="SQ" VM="1" Keyword="CoordinateSystemAxisCodeSequence" Name="Coordinate System Axis Code Sequence"
+(0040,08EA) VERS="4" VR="SQ" VM="1" Keyword="MeasurementUnitsCodeSequence" Name="Measurement Units Code Sequence"
+(0040,09F8) VERS="4RET" VR="SQ" VM="1" Keyword="VitalStainCodeSequenceTrial" Name="Vital Stain Code Sequence (Trial)"
+(0040,1001) VERS="4" VR="SH" VM="1" Keyword="RequestedProcedureID" Name="Requested Procedure ID"
+(0040,1002) VERS="4" VR="LO" VM="1" Keyword="ReasonForTheRequestedProcedure" Name="Reason for the Requested Procedure"
+(0040,1003) VERS="4" VR="SH" VM="1" Keyword="RequestedProcedurePriority" Name="Requested Procedure Priority "
+(0040,1004) VERS="4" VR="LO" VM="1" Keyword="PatientTransportArrangements" Name="Patient Transport Arrangements"
+(0040,1005) VERS="4" VR="LO" VM="1" Keyword="RequestedProcedureLocation" Name="Requested Procedure Location"
+(0040,1006) VERS="4RET" VR="SH" VM="1" Keyword="PlacerOrderNumberProcedure" Name="Placer Order Number / Procedure"
+(0040,1007) VERS="4RET" VR="SH" VM="1" Keyword="FillerOrderNumberProcedure" Name="Filler Order Number / Procedure"
+(0040,1008) VERS="4" VR="LO" VM="1" Keyword="ConfidentialityCode" Name="Confidentiality Code"
+(0040,1009) VERS="4" VR="SH" VM="1" Keyword="ReportingPriority" Name="Reporting Priority"
+(0040,100A) VERS="4" VR="SQ" VM="1" Keyword="ReasonForRequestedProcedureCodeSequence" Name="Reason for Requested Procedure Code Sequence"
+(0040,1010) VERS="4" VR="PN" VM="1-n" Keyword="NamesOfIntendedRecipientsOfResults" Name="Names of Intended Recipients of Results"
+(0040,1011) VERS="4" VR="SQ" VM="1" Keyword="IntendedRecipientsOfResultsIdentificationSequence" Name="Intended Recipients of Results Identification Sequence"
+(0040,1012) VERS="4" VR="SQ" VM="1" Keyword="ReasonForPerformedProcedureCodeSequence" Name="Reason For Performed Procedure Code Sequence"
+(0040,1060) VERS="4RET" VR="LO" VM="1" Keyword="RequestedProcedureDescriptionTrial" Name="Requested Procedure Description (Trial)"
+(0040,1101) VERS="4" VR="SQ" VM="1" Keyword="PersonIdentificationCodeSequence" Name="Person Identification Code Sequence"
+(0040,1102) VERS="4" VR="ST" VM="1" Keyword="PersonAddress" Name="Person�s Address"
+(0040,1103) VERS="4" VR="LO" VM="1-n" Keyword="PersonTelephoneNumbers" Name="Person�s Telephone Numbers"
+(0040,1400) VERS="4" VR="LT" VM="1" Keyword="RequestedProcedureComments" Name="Requested Procedure Comments"
+(0040,2001) VERS="4RET" VR="LO" VM="1" Keyword="ReasonForTheImagingServiceRequest" Name="Reason for the Imaging Service Request"
+(0040,2002) VERS="3" VR="LO" VM="1" Keyword="ImagingServiceRequestDescription" Name="Imaging Service Request Description"
+(0040,2004) VERS="4" VR="DA" VM="1" Keyword="IssueDateOfImagingServiceRequest" Name="Issue Date of Imaging Service Request"
+(0040,2005) VERS="4" VR="TM" VM="1" Keyword="IssueTimeOfImagingServiceRequest" Name="Issue Time of Imaging Service Request"
+(0040,2006) VERS="4RET" VR="SH" VM="1" Keyword="PlacerOrderNumberImagingServiceRequestRetired" Name="Placer Order Number / Imaging Service Request (Retired)"
+(0040,2007) VERS="4RET" VR="SH" VM="1" Keyword="FillerOrderNumberImagingServiceRequestRetired" Name="Filler Order Number / Imaging Service Request (Retired)"
+(0040,2008) VERS="4" VR="PN" VM="1" Keyword="OrderEnteredBy" Name="Order Entered By"
+(0040,2009) VERS="4" VR="SH" VM="1" Keyword="OrderEntererLocation" Name="Order Enterer�s Location"
+(0040,2010) VERS="4" VR="SH" VM="1" Keyword="OrderCallbackPhoneNumber" Name="Order Callback Phone Number"
+(0040,2016) VERS="4" VR="LO" VM="1" Keyword="PlacerOrderNumberImagingServiceRequest" Name="Placer Order Number / Imaging Service Request"
+(0040,2017) VERS="4" VR="LO" VM="1" Keyword="FillerOrderNumberImagingServiceRequest" Name="Filler Order Number / Imaging Service Request"
+(0040,2400) VERS="4" VR="LT" VM="1" Keyword="ImagingServiceRequestComments" Name="Imaging Service Request Comments"
+(0040,3001) VERS="4" VR="LO" VM="1" Keyword="ConfidentialityConstraintOnPatientDataDescription" Name="Confidentiality Constraint on Patient Data Description"
+(0040,4001) VERS="4" VR="CS" VM="1" Keyword="GeneralPurposeScheduledProcedureStepStatus" Name="General Purpose Scheduled Procedure Step Status"
+(0040,4002) VERS="4" VR="CS" VM="1" Keyword="GeneralPurposePerformedProcedureStepStatus" Name="General Purpose Performed Procedure Step Status"
+(0040,4003) VERS="4" VR="CS" VM="1" Keyword="GeneralPurposeScheduledProcedureStepPriority" Name="General Purpose Scheduled Procedure Step Priority"
+(0040,4004) VERS="4" VR="SQ" VM="1" Keyword="ScheduledProcessingApplicationsCodeSequence" Name="Scheduled Processing Applications Code Sequence"
+(0040,4005) VERS="4" VR="DT" VM="1" Keyword="ScheduledProcedureStepStartDateTime" Name="Scheduled Procedure Step Start DateTime"
+(0040,4006) VERS="4" VR="CS" VM="1" Keyword="MultipleCopiesFlag" Name="Multiple Copies Flag"
+(0040,4007) VERS="4" VR="SQ" VM="1" Keyword="PerformedProcessingApplicationsCodeSequence" Name="Performed Processing Applications Code Sequence"
+(0040,4009) VERS="4" VR="SQ" VM="1" Keyword="HumanPerformerCodeSequence" Name="Human Performer Code Sequence"
+(0040,4010) VERS="4" VR="DT" VM="1" Keyword="ScheduledProcedureStepModificationDateTime" Name="Scheduled Procedure Step Modification Date Time"
+(0040,4011) VERS="4" VR="DT" VM="1" Keyword="ExpectedCompletionDateTime" Name="Expected Completion Date Time"
+(0040,4015) VERS="4" VR="SQ" VM="1" Keyword="ResultingGeneralPurposePerformedProcedureStepsSequence" Name="Resulting General Purpose Performed Procedure Steps Sequence"
+(0040,4016) VERS="4" VR="SQ" VM="1" Keyword="ReferencedGeneralPurposeScheduledProcedureStepSequence" Name="Referenced General Purpose Scheduled Procedure Step Sequence"
+(0040,4018) VERS="4" VR="SQ" VM="1" Keyword="ScheduledWorkitemCodeSequence" Name="Scheduled Workitem Code Sequence"
+(0040,4019) VERS="4" VR="SQ" VM="1" Keyword="PerformedWorkitemCodeSequence" Name="Performed Workitem Code Sequence"
+(0040,4020) VERS="4" VR="CS" VM="1" Keyword="InputAvailabilityFlag" Name="Input Availability Flag"
+(0040,4021) VERS="4" VR="SQ" VM="1" Keyword="InputInformationSequence" Name="Input Information Sequence"
+(0040,4022) VERS="4" VR="SQ" VM="1" Keyword="RelevantInformationSequence" Name="Relevant Information Sequence"
+(0040,4023) VERS="4" VR="UI" VM="1" Keyword="ReferencedGeneralPurposeScheduledProcedureStepTransactionUID" Name="Referenced General Purpose Scheduled Procedure Step Transaction UID"
+(0040,4025) VERS="4" VR="SQ" VM="1" Keyword="ScheduledStationNameCodeSequence" Name="Scheduled Station Name Code Sequence"
+(0040,4026) VERS="4" VR="SQ" VM="1" Keyword="ScheduledStationClassCodeSequence" Name="Scheduled Station Class Code Sequence"
+(0040,4027) VERS="4" VR="SQ" VM="1" Keyword="ScheduledStationGeographicLocationCodeSequence" Name="Scheduled Station Geographic Location Code Sequence"
+(0040,4028) VERS="4" VR="SQ" VM="1" Keyword="PerformedStationNameCodeSequence" Name="Performed Station Name Code Sequence"
+(0040,4029) VERS="4" VR="SQ" VM="1" Keyword="PerformedStationClassCodeSequence" Name="Performed Station Class Code Sequence"
+(0040,4030) VERS="4" VR="SQ" VM="1" Keyword="PerformedStationGeographicLocationCodeSequence" Name="Performed Station Geographic Location Code Sequence"
+(0040,4031) VERS="4" VR="SQ" VM="1" Keyword="RequestedSubsequentWorkitemCodeSequence" Name="Requested Subsequent Workitem Code Sequence"
+(0040,4032) VERS="4" VR="SQ" VM="1" Keyword="NonDICOMOutputCodeSequence" Name="Non-DICOM Output Code Sequence"
+(0040,4033) VERS="4" VR="SQ" VM="1" Keyword="OutputInformationSequence" Name="Output Information Sequence"
+(0040,4034) VERS="4" VR="SQ" VM="1" Keyword="ScheduledHumanPerformersSequence" Name="Scheduled Human Performers Sequence"
+(0040,4035) VERS="4" VR="SQ" VM="1" Keyword="ActualHumanPerformersSequence" Name="Actual Human Performers Sequence"
+(0040,4036) VERS="4" VR="LO" VM="1" Keyword="HumanPerformerOrganization" Name="Human Performer�s Organization"
+(0040,4037) VERS="4" VR="PN" VM="1" Keyword="HumanPerformerName" Name="Human Performer�s Name"
+(0040,4040) VERS="4" VR="CS" VM="1" Keyword="RawDataHandling" Name="Raw Data Handling"
+(0040,4041) VERS="4" VR="CS" VM="1" Keyword="InputReadinessState" Name="Input Readiness State"
+(0040,4050) VERS="4" VR="DT" VM="1" Keyword="PerformedProcedureStepStartDateTime" Name="Performed Procedure Step Start DateTime"
+(0040,4051) VERS="4" VR="DT" VM="1" Keyword="PerformedProcedureStepEndDateTime" Name="Performed Procedure Step End DateTime"
+(0040,4052) VERS="4" VR="DT" VM="1" Keyword="ProcedureStepCancellationDateTime" Name="Procedure Step Cancellation DateTime"
+(0040,8302) VERS="4" VR="DS" VM="1" Keyword="EntranceDoseInmGy" Name="Entrance Dose in mGy"
+(0040,9094) VERS="4" VR="SQ" VM="1" Keyword="ReferencedImageRealWorldValueMappingSequence" Name="Referenced Image Real World Value Mapping Sequence"
+(0040,9096) VERS="4" VR="SQ" VM="1" Keyword="RealWorldValueMappingSequence" Name="Real World Value Mapping Sequence "
+(0040,9098) VERS="4" VR="SQ" VM="1" Keyword="PixelValueMappingCodeSequence" Name="Pixel Value Mapping Code Sequence"
+(0040,9210) VERS="4" VR="SH" VM="1" Keyword="LUTLabel" Name="LUT Label"
+(0040,9211) VERS="4" VR="US/SS" VM="1" Keyword="RealWorldValueLastValueMapped" Name="Real World Value Last Value Mapped"
+(0040,9212) VERS="4" VR="FD" VM="1-n" Keyword="RealWorldValueLUTData" Name="Real World Value LUT Data"
+(0040,9216) VERS="4" VR="US/SS" VM="1" Keyword="RealWorldValueFirstValueMapped" Name="Real World Value First Value Mapped"
+(0040,9224) VERS="4" VR="FD" VM="1" Keyword="RealWorldValueIntercept" Name="Real World Value Intercept"
+(0040,9225) VERS="4" VR="FD" VM="1" Keyword="RealWorldValueSlope" Name="Real World Value Slope"
+(0040,A007) VERS="4RET" VR="CS" VM="1" Keyword="FindingsFlagTrial" Name="Findings Flag (Trial)"
+(0040,A010) VERS="4" VR="CS" VM="1" Keyword="RelationshipType" Name="Relationship Type"
+(0040,A020) VERS="4RET" VR="SQ" VM="1" Keyword="FindingsSequenceTrial" Name="Findings Sequence (Trial)"
+(0040,A021) VERS="4RET" VR="UI" VM="1" Keyword="FindingsGroupUIDTrial" Name="Findings Group UID (Trial)"
+(0040,A022) VERS="4RET" VR="UI" VM="1" Keyword="ReferencedFindingsGroupUIDTrial" Name="Referenced Findings Group UID (Trial)"
+(0040,A023) VERS="4RET" VR="DA" VM="1" Keyword="FindingsGroupRecordingDateTrial" Name="Findings Group Recording Date (Trial)"
+(0040,A024) VERS="4RET" VR="TM" VM="1" Keyword="FindingsGroupRecordingTimeTrial" Name="Findings Group Recording Time (Trial)"
+(0040,A026) VERS="4RET" VR="SQ" VM="1" Keyword="FindingsSourceCategoryCodeSequenceTrial" Name="Findings Source Category Code Sequence (Trial)"
+(0040,A027) VERS="4" VR="LO" VM="1" Keyword="VerifyingOrganization" Name="Verifying Organization"
+(0040,A028) VERS="4RET" VR="SQ" VM="1" Keyword="DocumentingOrganizationIdentifierCodeSequenceTrial" Name="Documenting Organization Identifier Code Sequence (Trial)"
+(0040,A030) VERS="4" VR="DT" VM="1" Keyword="VerificationDateTime" Name="Verification Date Time"
+(0040,A032) VERS="4" VR="DT" VM="1" Keyword="ObservationDateTime" Name="Observation Date Time"
+(0040,A040) VERS="4" VR="CS" VM="1" Keyword="ValueType" Name="Value Type"
+(0040,A043) VERS="4" VR="SQ" VM="1" Keyword="ConceptNameCodeSequence" Name="Concept Name Code Sequence"
+(0040,A047) VERS="4RET" VR="LO" VM="1" Keyword="MeasurementPrecisionDescriptionTrial" Name="Measurement Precision Description (Trial)"
+(0040,A050) VERS="4" VR="CS" VM="1" Keyword="ContinuityOfContent" Name="Continuity Of Content"
+(0040,A057) VERS="4RET" VR="CS" VM="1-n" Keyword="UrgencyOrPriorityAlertsTrial" Name="Urgency or Priority Alerts (Trial)"
+(0040,A060) VERS="4RET" VR="LO" VM="1" Keyword="SequencingIndicatorTrial" Name="Sequencing Indicator (Trial)"
+(0040,A066) VERS="4RET" VR="SQ" VM="1" Keyword="DocumentIdentifierCodeSequenceTrial" Name="Document Identifier Code Sequence (Trial)"
+(0040,A067) VERS="4RET" VR="PN" VM="1" Keyword="DocumentAuthorTrial" Name="Document Author (Trial)"
+(0040,A068) VERS="4RET" VR="SQ" VM="1" Keyword="DocumentAuthorIdentifierCodeSequenceTrial" Name="Document Author Identifier Code Sequence (Trial)"
+(0040,A070) VERS="4RET" VR="SQ" VM="1" Keyword="IdentifierCodeSequenceTrial" Name="Identifier Code Sequence (Trial)"
+(0040,A073) VERS="4" VR="SQ" VM="1" Keyword="VerifyingObserverSequence" Name="Verifying Observer Sequence"
+(0040,A074) VERS="4RET" VR="OB" VM="1" Keyword="ObjectBinaryIdentifierTrial" Name="Object Binary Identifier (Trial)"
+(0040,A075) VERS="4" VR="PN" VM="1" Keyword="VerifyingObserverName" Name="Verifying Observer Name"
+(0040,A076) VERS="4RET" VR="SQ" VM="1" Keyword="DocumentingObserverIdentifierCodeSequenceTrial" Name="Documenting Observer Identifier Code Sequence (Trial)"
+(0040,A078) VERS="4" VR="SQ" VM="1" Keyword="AuthorObserverSequence" Name="Author Observer Sequence"
+(0040,A07A) VERS="4" VR="SQ" VM="1" Keyword="ParticipantSequence" Name="Participant Sequence"
+(0040,A07C) VERS="4" VR="SQ" VM="1" Keyword="CustodialOrganizationSequence" Name="Custodial Organization Sequence"
+(0040,A080) VERS="4" VR="CS" VM="1" Keyword="ParticipationType" Name="Participation Type"
+(0040,A082) VERS="4" VR="DT" VM="1" Keyword="ParticipationDateTime" Name="Participation DateTime"
+(0040,A084) VERS="4" VR="CS" VM="1" Keyword="ObserverType" Name="Observer Type"
+(0040,A085) VERS="4RET" VR="SQ" VM="1" Keyword="ProcedureIdentifierCodeSequenceTrial" Name="Procedure Identifier Code Sequence (Trial)"
+(0040,A088) VERS="4" VR="SQ" VM="1" Keyword="VerifyingObserverIdentificationCodeSequence" Name="Verifying Observer Identification Code Sequence"
+(0040,A089) VERS="4RET" VR="OB" VM="1" Keyword="ObjectDirectoryBinaryIdentifierTrial" Name="Object Directory Binary Identifier (Trial)"
+(0040,A090) VERS="4RET" VR="SQ" VM="1" Keyword="EquivalentCDADocumentSequence" Name="Equivalent CDA Document Sequence"
+(0040,A0B0) VERS="4" VR="US" VM="2-2n" Keyword="ReferencedWaveformChannels" Name="Referenced Waveform Channels"
+(0040,A110) VERS="4RET" VR="DA" VM="1" Keyword="DateOfDocumentOrVerbalTransactionTrial" Name="Date of Document or Verbal Transaction (Trial)"
+(0040,A112) VERS="4RET" VR="TM" VM="1" Keyword="TimeOfDocumentCreationOrVerbalTransactionTrial" Name="Time of Document Creation or Verbal Transaction (Trial)"
+(0040,A120) VERS="4" VR="DT" VM="1" Keyword="DateTime" Name="DateTime"
+(0040,A121) VERS="4" VR="DA" VM="1" Keyword="Date" Name="Date"
+(0040,A122) VERS="4" VR="TM" VM="1" Keyword="Time" Name="Time"
+(0040,A123) VERS="4" VR="PN" VM="1" Keyword="PersonName" Name="Person Name"
+(0040,A124) VERS="4" VR="UI" VM="1" Keyword="UID" Name="UID"
+(0040,A125) VERS="4RET" VR="CS" VM="2" Keyword="ReportStatusIDTrial" Name="Report Status ID (Trial)"
+(0040,A130) VERS="4" VR="CS" VM="1" Keyword="TemporalRangeType" Name="Temporal Range Type"
+(0040,A132) VERS="4" VR="UL" VM="1-n" Keyword="ReferencedSamplePositions" Name="Referenced Sample Positions"
+(0040,A136) VERS="4" VR="US" VM="1-n" Keyword="ReferencedFrameNumbers" Name="Referenced Frame Numbers"
+(0040,A138) VERS="4" VR="DS" VM="1-n" Keyword="ReferencedTimeOffsets" Name="Referenced Time Offsets"
+(0040,A13A) VERS="4" VR="DT" VM="1-n" Keyword="ReferencedDateTime" Name="Referenced DateTime "
+(0040,A160) VERS="4" VR="UT" VM="1" Keyword="TextValue" Name="Text Value"
+(0040,A167) VERS="4RET" VR="SQ" VM="1" Keyword="ObservationCategoryCodeSequenceTrial" Name="Observation Category Code Sequence (Trial)"
+(0040,A168) VERS="4" VR="SQ" VM="1" Keyword="ConceptCodeSequence" Name="Concept Code Sequence"
+(0040,A16A) VERS="4RET" VR="ST" VM="1" Keyword="BibliographicCitationTrial" Name="Bibliographic Citation (Trial)"
+(0040,A170) VERS="4" VR="SQ" VM="1" Keyword="PurposeOfReferenceCodeSequence" Name="Purpose of Reference Code Sequence"
+(0040,A171) VERS="4RET" VR="UI" VM="1" Keyword="ObservationUIDTrial" Name="Observation UID (Trial)"
+(0040,A172) VERS="4RET" VR="UI" VM="1" Keyword="ReferencedObservationUIDTrial" Name="Referenced Observation UID (Trial)"
+(0040,A173) VERS="4RET" VR="CS" VM="1" Keyword="ReferencedObservationClassTrial" Name="Referenced Observation Class (Trial)"
+(0040,A174) VERS="4RET" VR="CS" VM="1" Keyword="ReferencedObjectObservationClassTrial" Name="Referenced Object Observation Class (Trial)"
+(0040,A180) VERS="4" VR="US" VM="1" Keyword="AnnotationGroupNumber" Name="Annotation Group Number"
+(0040,A192) VERS="4RET" VR="DA" VM="1" Keyword="ObservationDateTrial" Name="Observation Date (Trial)"
+(0040,A193) VERS="4RET" VR="TM" VM="1" Keyword="ObservationTimeTrial" Name="Observation Time (Trial)"
+(0040,A194) VERS="4RET" VR="CS" VM="1" Keyword="MeasurementAutomationTrial" Name="Measurement Automation (Trial)"
+(0040,A195) VERS="4" VR="SQ" VM="1" Keyword="ModifierCodeSequence" Name="Modifier Code Sequence "
+(0040,A224) VERS="4RET" VR="ST" VM="1" Keyword="IdentificationDescriptionTrial" Name="Identification Description (Trial)"
+(0040,A290) VERS="4RET" VR="CS" VM="1" Keyword="CoordinatesSetGeometricTypeTrial" Name="Coordinates Set Geometric Type (Trial)"
+(0040,A296) VERS="4RET" VR="SQ" VM="1" Keyword="AlgorithmCodeSequenceTrial" Name="Algorithm Code Sequence (Trial)"
+(0040,A297) VERS="4RET" VR="ST" VM="1" Keyword="AlgorithmDescriptionTrial" Name="Algorithm Description (Trial)"
+(0040,A29A) VERS="4RET" VR="SL" VM="2-2n" Keyword="PixelCoordinatesSetTrial" Name="Pixel Coordinates Set (Trial)"
+(0040,A300) VERS="4" VR="SQ" VM="1" Keyword="MeasuredValueSequence" Name="Measured Value Sequence"
+(0040,A301) VERS="4" VR="SQ" VM="1" Keyword="NumericValueQualifierCodeSequence" Name="Numeric Value Qualifier Code Sequence"
+(0040,A307) VERS="4RET" VR="PN" VM="1" Keyword="CurrentObserverTrial" Name="Current Observer (Trial)"
+(0040,A30A) VERS="4" VR="DS" VM="1-n" Keyword="NumericValue" Name="Numeric Value"
+(0040,A313) VERS="4RET" VR="SQ" VM="1" Keyword="ReferencedAccessionSequenceTrial" Name="Referenced Accession Sequence (Trial)"
+(0040,A33A) VERS="4RET" VR="ST" VM="1" Keyword="ReportStatusCommentTrial" Name="Report Status Comment (Trial)"
+(0040,A340) VERS="4RET" VR="SQ" VM="1" Keyword="ProcedureContextSequenceTrial" Name="Procedure Context Sequence (Trial)"
+(0040,A352) VERS="4RET" VR="PN" VM="1" Keyword="VerbalSourceTrial" Name="Verbal Source (Trial)"
+(0040,A353) VERS="4RET" VR="ST" VM="1" Keyword="AddressTrial" Name="Address (Trial)"
+(0040,A354) VERS="4RET" VR="LO" VM="1" Keyword="TelephoneNumberTrial" Name="Telephone Number (Trial)"
+(0040,A358) VERS="4RET" VR="SQ" VM="1" Keyword="VerbalSourceIdentifierCodeSequenceTrial" Name="Verbal Source Identifier Code Sequence (Trial)"
+(0040,A360) VERS="4" VR="SQ" VM="1" Keyword="PredecessorDocumentsSequence" Name="Predecessor Documents Sequence"
+(0040,A370) VERS="4" VR="SQ" VM="1" Keyword="ReferencedRequestSequence" Name="Referenced Request Sequence"
+(0040,A372) VERS="4" VR="SQ" VM="1" Keyword="PerformedProcedureCodeSequence" Name="Performed Procedure Code Sequence"
+(0040,A375) VERS="4" VR="SQ" VM="1" Keyword="CurrentRequestedProcedureEvidenceSequence" Name="Current Requested Procedure Evidence Sequence"
+(0040,A380) VERS="4RET" VR="SQ" VM="1" Keyword="ReportDetailSequenceTrial" Name="Report Detail Sequence (Trial)"
+(0040,A385) VERS="4" VR="SQ" VM="1" Keyword="PertinentOtherEvidenceSequence" Name="Pertinent Other Evidence Sequence"
+(0040,A390) VERS="4" VR="SQ" VM="1" Keyword="HL7StructuredDocumentReferenceSequence" Name="HL7 Structured Document Reference Sequence"
+(0040,A402) VERS="4RET" VR="UI" VM="1" Keyword="ObservationSubjectUIDTrial" Name="Observation Subject UID (Trial)"
+(0040,A403) VERS="4RET" VR="CS" VM="1" Keyword="ObservationSubjectClassTrial" Name="Observation Subject Class (Trial)"
+(0040,A404) VERS="4RET" VR="SQ" VM="1" Keyword="ObservationSubjectTypeCodeSequenceTrial" Name="Observation Subject Type Code Sequence (Trial)"
+(0040,A491) VERS="4" VR="CS" VM="1" Keyword="CompletionFlag" Name="Completion Flag"
+(0040,A492) VERS="4" VR="LO" VM="1" Keyword="CompletionFlagDescription" Name="Completion Flag Description"
+(0040,A493) VERS="4" VR="CS" VM="1" Keyword="VerificationFlag" Name="Verification Flag"
+(0040,A494) VERS="4" VR="CS" VM="1" Keyword="ArchiveRequested" Name="Archive Requested"
+(0040,A496) VERS="4" VR="CS" VM="1" Keyword="PreliminaryFlag" Name="Preliminary Flag"
+(0040,A504) VERS="4" VR="SQ" VM="1" Keyword="ContentTemplateSequence" Name="Content Template Sequence"
+(0040,A525) VERS="4" VR="SQ" VM="1" Keyword="IdenticalDocumentsSequence" Name="Identical Documents Sequence"
+(0040,A600) VERS="4RET" VR="CS" VM="1" Keyword="ObservationSubjectContextFlagTrial" Name="Observation Subject Context Flag (Trial)"
+(0040,A601) VERS="4RET" VR="CS" VM="1" Keyword="ObserverContextFlagTrial" Name="Observer Context Flag (Trial)"
+(0040,A603) VERS="4RET" VR="CS" VM="1" Keyword="ProcedureContextFlagTrial" Name="Procedure Context Flag (Trial)"
+(0040,A730) VERS="4" VR="SQ" VM="1" Keyword="ContentSequence" Name="Content Sequence"
+(0040,A731) VERS="4RET" VR="SQ" VM="1" Keyword="RelationshipSequenceTrial" Name="Relationship Sequence (Trial)"
+(0040,A732) VERS="4RET" VR="SQ" VM="1" Keyword="RelationshipTypeCodeSequenceTrial" Name="Relationship Type Code Sequence (Trial)"
+(0040,A744) VERS="4RET" VR="SQ" VM="1" Keyword="LanguageCodeSequenceTrial" Name="Language Code Sequence (Trial)"
+(0040,A992) VERS="4RET" VR="ST" VM="1" Keyword="UniformResourceLocatorTrial" Name="Uniform Resource Locator (Trial)"
+(0040,B020) VERS="4" VR="SQ" VM="1" Keyword="WaveformAnnotationSequence" Name="Waveform Annotation Sequence"
+(0040,DB00) VERS="4" VR="CS" VM="1" Keyword="TemplateIdentifier" Name="Template Identifier"
+(0040,DB06) VERS="4RET" VR="DT" VM="1" Keyword="TemplateVersion" Name="Template Version"
+(0040,DB07) VERS="4RET" VR="DT" VM="1" Keyword="TemplateLocalVersion" Name="Template Local Version"
+(0040,DB0B) VERS="4RET" VR="CS" VM="1" Keyword="TemplateExtensionFlag" Name="Template Extension Flag"
+(0040,DB0C) VERS="4RET" VR="UI" VM="1" Keyword="TemplateExtensionOrganizationUID" Name="Template Extension Organization UID"
+(0040,DB0D) VERS="4RET" VR="UI" VM="1" Keyword="TemplateExtensionCreatorUID" Name="Template Extension Creator UID"
+(0040,DB73) VERS="4" VR="UL" VM="1-n" Keyword="ReferencedContentItemIdentifier" Name="Referenced Content Item Identifier"
+(0040,E001) VERS="4" VR="ST" VM="1" Keyword="HL7InstanceIdentifier" Name="HL7 Instance Identifier "
+(0040,E004) VERS="4" VR="DT" VM="1" Keyword="HL7DocumentEffectiveTime" Name="HL7 Document Effective Time"
+(0040,E006) VERS="4" VR="SQ" VM="1" Keyword="HL7DocumentTypeCodeSequence" Name="HL7 Document Type Code Sequence"
+(0040,E008) VERS="4" VR="SQ" VM="1" Keyword="DocumentClassCodeSequence" Name="Document Class Code Sequence"
+(0040,E010) VERS="4" VR="UT" VM="1" Keyword="RetrieveURI" Name="Retrieve URI "
+(0040,E011) VERS="4" VR="UI" VM="1" Keyword="RetrieveLocationUID" Name="Retrieve Location UID"
+(0040,E020) VERS="4" VR="CS" VM="1" Keyword="TypeOfInstances" Name="Type of Instances"
+(0040,E021) VERS="4" VR="SQ" VM="1" Keyword="DICOMRetrievalSequence" Name="DICOM Retrieval Sequence"
+(0040,E022) VERS="4" VR="SQ" VM="1" Keyword="DICOMMediaRetrievalSequence" Name="DICOM Media Retrieval Sequence"
+(0040,E023) VERS="4" VR="SQ" VM="1" Keyword="WADORetrievalSequence" Name="WADO Retrieval Sequence"
+(0040,E024) VERS="4" VR="SQ" VM="1" Keyword="XDSRetrievalSequence" Name="XDS Retrieval Sequence"
+(0040,E030) VERS="4" VR="UI" VM="1" Keyword="RepositoryUniqueID" Name="Repository Unique ID"
+(0040,E031) VERS="4" VR="UI" VM="1" Keyword="HomeCommunityID" Name="Home Community ID"
+(0042,0010) VERS="4" VR="ST" VM="1" Keyword="DocumentTitle" Name="Document Title"
+(0042,0011) VERS="4" VR="OB" VM="1" Keyword="EncapsulatedDocument" Name="Encapsulated Document"
+(0042,0012) VERS="4" VR="LO" VM="1" Keyword="MIMETypeOfEncapsulatedDocument" Name="MIME Type of Encapsulated Document"
+(0042,0013) VERS="4" VR="SQ" VM="1" Keyword="SourceInstanceSequence" Name="Source Instance Sequence"
+(0042,0014) VERS="4" VR="LO" VM="1-n" Keyword="ListOfMIMETypes" Name="List of MIME Types"
+(0044,0001) VERS="4" VR="ST" VM="1" Keyword="ProductPackageIdentifier" Name="Product Package Identifier"
+(0044,0002) VERS="4" VR="CS" VM="1" Keyword="SubstanceAdministrationApproval" Name="Substance Administration Approval"
+(0044,0003) VERS="4" VR="LT" VM="1" Keyword="ApprovalStatusFurtherDescription" Name="Approval Status Further Description"
+(0044,0004) VERS="4" VR="DT" VM="1" Keyword="ApprovalStatusDateTime" Name="Approval Status DateTime "
+(0044,0007) VERS="4" VR="SQ" VM="1" Keyword="ProductTypeCodeSequence" Name="Product Type Code Sequence"
+(0044,0008) VERS="4" VR="LO" VM="1-n" Keyword="ProductName" Name="Product Name"
+(0044,0009) VERS="4" VR="LT" VM="1" Keyword="ProductDescription" Name="Product Description"
+(0044,000A) VERS="4" VR="LO" VM="1" Keyword="ProductLotIdentifier" Name="Product Lot Identifier"
+(0044,000B) VERS="4" VR="DT" VM="1" Keyword="ProductExpirationDateTime" Name="Product Expiration DateTime"
+(0044,0010) VERS="4" VR="DT" VM="1" Keyword="SubstanceAdministrationDateTime" Name="Substance Administration DateTime"
+(0044,0011) VERS="4" VR="LO" VM="1" Keyword="SubstanceAdministrationNotes" Name="Substance Administration Notes"
+(0044,0012) VERS="4" VR="LO" VM="1" Keyword="SubstanceAdministrationDeviceID" Name="Substance Administration Device ID"
+(0044,0013) VERS="4" VR="SQ" VM="1" Keyword="ProductParameterSequence" Name="Product Parameter Sequence"
+(0044,0019) VERS="4" VR="SQ" VM="1" Keyword="SubstanceAdministrationParameterSequence" Name="Substance Administration Parameter Sequence"
+(0046,0012) VERS="4" VR="LO" VM="1" Keyword="LensDescription" Name="Lens Description"
+(0046,0014) VERS="4" VR="SQ" VM="1" Keyword="RightLensSequence" Name="Right Lens Sequence"
+(0046,0015) VERS="4" VR="SQ" VM="1" Keyword="LeftLensSequence" Name="Left Lens Sequence"
+(0046,0016) VERS="4" VR="SQ" VM="1" Keyword="UnspecifiedLateralityLensSequence" Name="Unspecified Laterality Lens Sequence"
+(0046,0018) VERS="4" VR="SQ" VM="1" Keyword="CylinderSequence" Name="Cylinder Sequence"
+(0046,0028) VERS="4" VR="SQ" VM="1" Keyword="PrismSequence" Name="Prism Sequence"
+(0046,0030) VERS="4" VR="FD" VM="1" Keyword="HorizontalPrismPower" Name="Horizontal Prism Power"
+(0046,0032) VERS="4" VR="CS" VM="1" Keyword="HorizontalPrismBase" Name="Horizontal Prism Base"
+(0046,0034) VERS="4" VR="FD" VM="1" Keyword="VerticalPrismPower" Name="Vertical Prism Power"
+(0046,0036) VERS="4" VR="CS" VM="1" Keyword="VerticalPrismBase" Name="Vertical Prism Base"
+(0046,0038) VERS="4" VR="CS" VM="1" Keyword="LensSegmentType" Name="Lens Segment Type"
+(0046,0040) VERS="4" VR="FD" VM="1" Keyword="OpticalTransmittance" Name="Optical Transmittance"
+(0046,0042) VERS="4" VR="FD" VM="1" Keyword="ChannelWidth" Name="Channel Width"
+(0046,0044) VERS="4" VR="FD" VM="1" Keyword="PupilSize" Name="Pupil Size"
+(0046,0046) VERS="4" VR="FD" VM="1" Keyword="CornealSize" Name="Corneal Size"
+(0046,0050) VERS="4" VR="SQ" VM="1" Keyword="AutorefractionRightEyeSequence" Name="Autorefraction Right Eye Sequence"
+(0046,0052) VERS="4" VR="SQ" VM="1" Keyword="AutorefractionLeftEyeSequence" Name="Autorefraction Left Eye Sequence"
+(0046,0060) VERS="4" VR="FD" VM="1" Keyword="DistancePupillaryDistance" Name="Distance Pupillary Distance"
+(0046,0062) VERS="4" VR="FD" VM="1" Keyword="NearPupillaryDistance" Name="Near Pupillary Distance"
+(0046,0063) VERS="4" VR="FD" VM="1" Keyword="IntermediatePupillaryDistance" Name="Intermediate Pupillary Distance"
+(0046,0064) VERS="4" VR="FD" VM="1" Keyword="OtherPupillaryDistance" Name="Other Pupillary Distance"
+(0046,0070) VERS="4" VR="SQ" VM="1" Keyword="KeratometryRightEyeSequence" Name="Keratometry Right Eye Sequence"
+(0046,0071) VERS="4" VR="SQ" VM="1" Keyword="KeratometryLeftEyeSequence" Name="Keratometry Left Eye Sequence"
+(0046,0074) VERS="4" VR="SQ" VM="1" Keyword="SteepKeratometricAxisSequence" Name="Steep Keratometric Axis Sequence"
+(0046,0075) VERS="4" VR="FD" VM="1" Keyword="RadiusOfCurvature" Name="Radius of Curvature"
+(0046,0076) VERS="4" VR="FD" VM="1" Keyword="KeratometricPower" Name="Keratometric Power"
+(0046,0077) VERS="4" VR="FD" VM="1" Keyword="KeratometricAxis" Name="Keratometric Axis"
+(0046,0080) VERS="4" VR="SQ" VM="1" Keyword="FlatKeratometricAxisSequence" Name="Flat Keratometric Axis Sequence"
+(0046,0092) VERS="4" VR="CS" VM="1" Keyword="BackgroundColor" Name="Background Color"
+(0046,0094) VERS="4" VR="CS" VM="1" Keyword="Optotype" Name="Optotype"
+(0046,0095) VERS="4" VR="CS" VM="1" Keyword="OptotypePresentation" Name="Optotype Presentation"
+(0046,0097) VERS="4" VR="SQ" VM="1" Keyword="SubjectiveRefractionRightEyeSequence" Name="Subjective Refraction Right Eye Sequence"
+(0046,0098) VERS="4" VR="SQ" VM="1" Keyword="SubjectiveRefractionLeftEyeSequence" Name="Subjective Refraction Left Eye Sequence"
+(0046,0100) VERS="4" VR="SQ" VM="1" Keyword="AddNearSequence" Name="Add Near Sequence"
+(0046,0101) VERS="4" VR="SQ" VM="1" Keyword="AddIntermediateSequence" Name="Add Intermediate Sequence"
+(0046,0102) VERS="4" VR="SQ" VM="1" Keyword="AddOtherSequence" Name="Add Other Sequence"
+(0046,0104) VERS="4" VR="FD" VM="1" Keyword="AddPower" Name="Add Power"
+(0046,0106) VERS="4" VR="FD" VM="1" Keyword="ViewingDistance" Name="Viewing Distance"
+(0046,0121) VERS="4" VR="SQ" VM="1" Keyword="VisualAcuityTypeCodeSequence" Name="Visual Acuity Type Code Sequence"
+(0046,0122) VERS="4" VR="SQ" VM="1" Keyword="VisualAcuityRightEyeSequence" Name="Visual Acuity Right Eye Sequence"
+(0046,0123) VERS="4" VR="SQ" VM="1" Keyword="VisualAcuityLeftEyeSequence" Name="Visual Acuity Left Eye Sequence"
+(0046,0124) VERS="4" VR="SQ" VM="1" Keyword="VisualAcuityBothEyesOpenSequence" Name="Visual Acuity Both Eyes Open Sequence"
+(0046,0125) VERS="4" VR="CS" VM="1" Keyword="ViewingDistanceType" Name="Viewing Distance Type"
+(0046,0135) VERS="4" VR="SS" VM="2" Keyword="VisualAcuityModifiers" Name="Visual Acuity Modifiers"
+(0046,0137) VERS="4" VR="FD" VM="1" Keyword="DecimalVisualAcuity" Name="Decimal Visual Acuity"
+(0046,0139) VERS="4" VR="LO" VM="1" Keyword="OptotypeDetailedDefinition" Name="Optotype Detailed Definition"
+(0046,0145) VERS="4" VR="SQ" VM="1" Keyword="ReferencedRefractiveMeasurementsSequence" Name="Referenced Refractive Measurements Sequence"
+(0046,0146) VERS="4" VR="FD" VM="1" Keyword="SpherePower" Name="Sphere Power"
+(0046,0147) VERS="4" VR="FD" VM="1" Keyword="CylinderPower" Name="Cylinder Power"
+(0048,0001) VERS="4" VR="FL" VM="1" Keyword="ImagedVolumeWidth" Name="Imaged Volume Width"
+(0048,0002) VERS="4" VR="FL" VM="1" Keyword="ImagedVolumeHeight" Name="Imaged Volume Height"
+(0048,0003) VERS="4" VR="FL" VM="1" Keyword="ImagedVolumeDepth" Name="Imaged Volume Depth"
+(0048,0006) VERS="4" VR="UL" VM="1" Keyword="TotalPixelMatrixColumns" Name="Total Pixel Matrix Columns"
+(0048,0007) VERS="4" VR="UL" VM="1" Keyword="TotalPixelMatrixRows" Name="Total Pixel Matrix Rows"
+(0048,0008) VERS="4" VR="SQ" VM="1" Keyword="TotalPixelMatrixOriginSequence" Name="Total Pixel Matrix Origin Sequence"
+(0048,0010) VERS="4" VR="CS" VM="1" Keyword="SpecimenLabelInImage" Name="Specimen Label in Image"
+(0048,0011) VERS="4" VR="CS" VM="1" Keyword="FocusMethod" Name="Focus Method"
+(0048,0012) VERS="4" VR="CS" VM="1" Keyword="ExtendedDepthOfField" Name="Extended Depth of Field"
+(0048,0013) VERS="4" VR="US" VM="1" Keyword="NumberOfFocalPlanes" Name="Number of Focal Planes"
+(0048,0014) VERS="4" VR="FL" VM="1" Keyword="DistanceBetweenFocalPlanes" Name="Distance Between Focal Planes"
+(0048,0015) VERS="4" VR="US" VM="3" Keyword="RecommendedAbsentPixelCIELabValue" Name="Recommended Absent Pixel CIELab Value"
+(0048,0100) VERS="4" VR="SQ" VM="1" Keyword="IlluminatorTypeCodeSequence" Name="Illuminator Type Code Sequence"
+(0048,0102) VERS="4" VR="DS" VM="6" Keyword="ImageOrientationSlide" Name="Image Orientation (Slide)"
+(0048,0105) VERS="4" VR="SQ" VM="1" Keyword="OpticalPathSequence" Name="Optical Path Sequence"
+(0048,0106) VERS="4" VR="SH" VM="1" Keyword="OpticalPathIdentifier" Name="Optical Path Identifier"
+(0048,0107) VERS="4" VR="ST" VM="1" Keyword="OpticalPathDescription" Name="Optical Path Description"
+(0048,0108) VERS="4" VR="SQ" VM="1" Keyword="IlluminationColorCodeSequence" Name="Illumination Color Code Sequence"
+(0048,0110) VERS="4" VR="SQ" VM="1" Keyword="SpecimenReferenceSequence" Name="Specimen Reference Sequence"
+(0048,0111) VERS="4" VR="DS" VM="1" Keyword="CondenserLensPower" Name="Condenser Lens Power"
+(0048,0112) VERS="4" VR="DS" VM="1" Keyword="ObjectiveLensPower" Name="Objective Lens Power"
+(0048,0113) VERS="4" VR="DS" VM="1" Keyword="ObjectiveLensNumericalAperture" Name="Objective Lens Numerical Aperture"
+(0048,0120) VERS="4" VR="SQ" VM="1" Keyword="PaletteColorLookupTableSequence" Name="Palette Color Lookup Table Sequence"
+(0048,0200) VERS="4" VR="SQ" VM="1" Keyword="ReferencedImageNavigationSequence" Name="Referenced Image Navigation Sequence"
+(0048,0201) VERS="4" VR="US" VM="2" Keyword="TopLeftHandCornerOfLocalizerArea" Name="Top Left Hand Corner of Localizer Area"
+(0048,0202) VERS="4" VR="US" VM="2" Keyword="BottomRightHandCornerOfLocalizerArea" Name="Bottom Right Hand Corner of Localizer Area"
+(0048,0207) VERS="4" VR="SQ" VM="1" Keyword="OpticalPathIdentificationSequence" Name="Optical Path Identification Sequence"
+(0048,021A) VERS="4" VR="SQ" VM="1" Keyword="PlanePositionSlideSequence" Name="Plane Position (Slide) Sequence"
+(0048,021E) VERS="4" VR="SL" VM="1" Keyword="RowPositionInTotalImagePixelMatrix" Name="Row Position In Total Image Pixel Matrix"
+(0048,021F) VERS="4" VR="SL" VM="1" Keyword="ColumnPositionInTotalImagePixelMatrix" Name="Column Position In Total Image Pixel Matrix"
+(0048,0301) VERS="4" VR="CS" VM="1" Keyword="PixelOriginInterpretation" Name="Pixel Origin Interpretation"
+(0050,0000) VERS="3" VR="UL" VM="1" Keyword="CalibrationGroupLength" Name="Calibration Group Length"
+(0050,0004) VERS="4" VR="CS" VM="1" Keyword="CalibrationImage" Name="Calibration Image"
+(0050,0010) VERS="4" VR="SQ" VM="1" Keyword="DeviceSequence" Name="Device Sequence"
+(0050,0012) VERS="4" VR="SQ" VM="1" Keyword="ContainerComponentTypeCodeSequence" Name="Container Component Type Code Sequence"
+(0050,0013) VERS="4" VR="FD" VM="1" Keyword="ContainerComponentThickness" Name="Container Component Thickness"
+(0050,0014) VERS="4" VR="DS" VM="1" Keyword="DeviceLength" Name="Device Length"
+(0050,0015) VERS="4" VR="FD" VM="1" Keyword="ContainerComponentWidth" Name="Container Component Width"
+(0050,0016) VERS="4" VR="DS" VM="1" Keyword="DeviceDiameter" Name="Device Diameter"
+(0050,0017) VERS="4" VR="CS" VM="1" Keyword="DeviceDiameterUnits" Name="Device Diameter Units"
+(0050,0018) VERS="4" VR="DS" VM="1" Keyword="DeviceVolume" Name="Device Volume"
+(0050,0019) VERS="4" VR="DS" VM="1" Keyword="InterMarkerDistance" Name="Inter-Marker Distance"
+(0050,001A) VERS="4" VR="CS" VM="1" Keyword="ContainerComponentMaterial" Name="Container Component Material"
+(0050,001B) VERS="4" VR="LO" VM="1" Keyword="ContainerComponentID" Name="Container Component ID"
+(0050,001C) VERS="4" VR="FD" VM="1" Keyword="ContainerComponentLength" Name="Container Component Length"
+(0050,001D) VERS="4" VR="FD" VM="1" Keyword="ContainerComponentDiameter" Name="Container Component Diameter"
+(0050,001E) VERS="4" VR="LO" VM="1" Keyword="ContainerComponentDescription" Name="Container Component Description"
+(0050,0020) VERS="4" VR="LO" VM="1" Keyword="DeviceDescription" Name="Device Description"
+(0050,0030) VERS="3" VR="SQ" VM="1" Keyword="CodedInterventionDeviceSequence" Name="Coded Intervention Device Sequence"
+(0052,0001) VERS="4" VR="FL" VM="1" Keyword="ContrastBolusIngredientPercentByVolume" Name="Contrast/Bolus Ingredient Percent by Volume "
+(0052,0002) VERS="4" VR="FD" VM="1" Keyword="OCTFocalDistance" Name="OCT Focal Distance"
+(0052,0003) VERS="4" VR="FD" VM="1" Keyword="BeamSpotSize" Name="Beam Spot Size"
+(0052,0004) VERS="4" VR="FD" VM="1" Keyword="EffectiveRefractiveIndex" Name="Effective Refractive Index"
+(0052,0006) VERS="4" VR="CS" VM="1" Keyword="OCTAcquisitionDomain" Name="OCT Acquisition Domain"
+(0052,0007) VERS="4" VR="FD" VM="1" Keyword="OCTOpticalCenterWavelength" Name="OCT Optical Center Wavelength"
+(0052,0008) VERS="4" VR="FD" VM="1" Keyword="AxialResolution" Name="Axial Resolution"
+(0052,0009) VERS="4" VR="FD" VM="1" Keyword="RangingDepth" Name="Ranging Depth"
+(0052,0011) VERS="4" VR="FD" VM="1" Keyword="ALineRate" Name="A line Rate"
+(0052,0012) VERS="4" VR="US" VM="1" Keyword="ALinesPerFrame" Name="A lines Per Frame"
+(0052,0013) VERS="4" VR="FD" VM="1" Keyword="CatheterRotationalRate" Name="Catheter Rotational Rate"
+(0052,0014) VERS="4" VR="FD" VM="1" Keyword="ALinePixelSpacing" Name="A line Pixel Spacing"
+(0052,0016) VERS="4" VR="SQ" VM="1" Keyword="ModeOfPercutaneousAccessSequence" Name="Mode of Percutaneous Access Sequence"
+(0052,0025) VERS="4" VR="SQ" VM="1" Keyword="IntravascularOCTFrameTypeSequence" Name="Intravascular OCT Frame Type Sequence"
+(0052,0026) VERS="4" VR="CS" VM="1" Keyword="OCTZOffsetApplied" Name="OCT Z Offset Applied"
+(0052,0027) VERS="4" VR="SQ" VM="1" Keyword="IntravascularFrameContentSequence" Name="Intravascular Frame Content Sequence"
+(0052,0028) VERS="4" VR="FD" VM="1" Keyword="IntravascularLongitudinalDistance" Name="Intravascular Longitudinal Distance"
+(0052,0029) VERS="4" VR="SQ" VM="1" Keyword="IntravascularOCTFrameContentSequence" Name="Intravascular OCT Frame Content Sequence"
+(0052,0030) VERS="4" VR="SS" VM="1" Keyword="OCTZOffsetCorrection" Name="OCT Z Offset Correction"
+(0052,0031) VERS="4" VR="CS" VM="1" Keyword="CatheterDirectionOfRotation" Name="Catheter Direction of Rotation"
+(0052,0033) VERS="4" VR="FD" VM="1" Keyword="SeamLineLocation" Name="Seam Line Location"
+(0052,0034) VERS="4" VR="FD" VM="1" Keyword="FirstALineLocation" Name="First A line Location"
+(0052,0036) VERS="4" VR="US" VM="1" Keyword="SeamLineIndex" Name="Seam Line Index"
+(0052,0038) VERS="4" VR="US" VM="1" Keyword="NumberOfPaddedAlines" Name="Number of Padded A lines"
+(0052,0039) VERS="4" VR="CS" VM="1" Keyword="InterpolationType" Name="Interpolation Type"
+(0052,003A) VERS="4" VR="CS" VM="1" Keyword="RefractiveIndexApplied" Name="Refractive Index Applied"
+(0054,0000) VERS="3" VR="UL" VM="1" Keyword="NuclearAcquisitionGroupLength" Name="Nuclear Acquisition Group Length"
+(0054,0010) VERS="4" VR="US" VM="1-n" Keyword="EnergyWindowVector" Name="Energy Window Vector"
+(0054,0011) VERS="4" VR="US" VM="1" Keyword="NumberOfEnergyWindows" Name="Number of Energy Windows"
+(0054,0012) VERS="4" VR="SQ" VM="1" Keyword="EnergyWindowInformationSequence" Name="Energy Window Information Sequence"
+(0054,0013) VERS="4" VR="SQ" VM="1" Keyword="EnergyWindowRangeSequence" Name="Energy Window Range Sequence"
+(0054,0014) VERS="4" VR="DS" VM="1" Keyword="EnergyWindowLowerLimit" Name="Energy Window Lower Limit"
+(0054,0015) VERS="4" VR="DS" VM="1" Keyword="EnergyWindowUpperLimit" Name="Energy Window Upper Limit"
+(0054,0016) VERS="4" VR="SQ" VM="1" Keyword="RadiopharmaceuticalInformationSequence" Name="Radiopharmaceutical Information Sequence"
+(0054,0017) VERS="4" VR="IS" VM="1" Keyword="ResidualSyringeCounts" Name="Residual Syringe Counts"
+(0054,0018) VERS="4" VR="SH" VM="1" Keyword="EnergyWindowName" Name="Energy Window Name"
+(0054,0020) VERS="4" VR="US" VM="1-n" Keyword="DetectorVector" Name="Detector Vector"
+(0054,0021) VERS="4" VR="US" VM="1" Keyword="NumberOfDetectors" Name="Number of Detectors"
+(0054,0022) VERS="4" VR="SQ" VM="1" Keyword="DetectorInformationSequence" Name="Detector Information Sequence"
+(0054,0030) VERS="4" VR="US" VM="1-n" Keyword="PhaseVector" Name="Phase Vector"
+(0054,0031) VERS="4" VR="US" VM="1" Keyword="NumberOfPhases" Name="Number of Phases"
+(0054,0032) VERS="4" VR="SQ" VM="1" Keyword="PhaseInformationSequence" Name="Phase Information Sequence"
+(0054,0033) VERS="4" VR="US" VM="1" Keyword="NumberOfFramesInPhase" Name="Number of Frames in Phase"
+(0054,0036) VERS="4" VR="IS" VM="1" Keyword="PhaseDelay" Name="Phase Delay"
+(0054,0038) VERS="4" VR="IS" VM="1" Keyword="PauseBetweenFrames" Name="Pause Between Frames"
+(0054,0039) VERS="4" VR="CS" VM="1" Keyword="PhaseDescription" Name="Phase Description"
+(0054,0050) VERS="4" VR="US" VM="1-n" Keyword="RotationVector" Name="Rotation Vector"
+(0054,0051) VERS="4" VR="US" VM="1" Keyword="NumberOfRotations" Name="Number of Rotations"
+(0054,0052) VERS="4" VR="SQ" VM="1" Keyword="RotationInformationSequence" Name="Rotation Information Sequence"
+(0054,0053) VERS="4" VR="US" VM="1" Keyword="NumberOfFramesInRotation" Name="Number of Frames in Rotation"
+(0054,0060) VERS="4" VR="US" VM="1-n" Keyword="RRIntervalVector" Name="R-R Interval Vector"
+(0054,0061) VERS="4" VR="US" VM="1" Keyword="NumberOfRRIntervals" Name="Number of R-R Intervals"
+(0054,0062) VERS="4" VR="SQ" VM="1" Keyword="GatedInformationSequence" Name="Gated Information Sequence"
+(0054,0063) VERS="4" VR="SQ" VM="1" Keyword="DataInformationSequence" Name="Data Information Sequence"
+(0054,0070) VERS="4" VR="US" VM="1-n" Keyword="TimeSlotVector" Name="Time Slot Vector"
+(0054,0071) VERS="4" VR="US" VM="1" Keyword="NumberOfTimeSlots" Name="Number of Time Slots"
+(0054,0072) VERS="4" VR="SQ" VM="1" Keyword="TimeSlotInformationSequence" Name="Time Slot Information Sequence"
+(0054,0073) VERS="4" VR="DS" VM="1" Keyword="TimeSlotTime" Name="Time Slot Time"
+(0054,0080) VERS="4" VR="US" VM="1-n" Keyword="SliceVector" Name="Slice Vector"
+(0054,0081) VERS="4" VR="US" VM="1" Keyword="NumberOfSlices" Name="Number of Slices"
+(0054,0090) VERS="4" VR="US" VM="1-n" Keyword="AngularViewVector" Name="Angular View Vector"
+(0054,0100) VERS="4" VR="US" VM="1-n" Keyword="TimeSliceVector" Name="Time Slice Vector"
+(0054,0101) VERS="4" VR="US" VM="1" Keyword="NumberOfTimeSlices" Name="Number of Time Slices"
+(0054,0200) VERS="4" VR="DS" VM="1" Keyword="StartAngle" Name="Start Angle"
+(0054,0202) VERS="4" VR="CS" VM="1" Keyword="TypeOfDetectorMotion" Name="Type of Detector Motion"
+(0054,0210) VERS="4" VR="IS" VM="1-n" Keyword="TriggerVector" Name="Trigger Vector"
+(0054,0211) VERS="4" VR="US" VM="1" Keyword="NumberOfTriggersInPhase" Name="Number of Triggers in Phase"
+(0054,0220) VERS="4" VR="SQ" VM="1" Keyword="ViewCodeSequence" Name="View Code Sequence"
+(0054,0222) VERS="4" VR="SQ" VM="1" Keyword="ViewModifierCodeSequence" Name="View Modifier Code Sequence"
+(0054,0300) VERS="4" VR="SQ" VM="1" Keyword="RadionuclideCodeSequence" Name="Radionuclide Code Sequence"
+(0054,0302) VERS="4" VR="SQ" VM="1" Keyword="AdministrationRouteCodeSequence" Name="Administration Route Code Sequence"
+(0054,0304) VERS="4" VR="SQ" VM="1" Keyword="RadiopharmaceuticalCodeSequence" Name="Radiopharmaceutical Code Sequence"
+(0054,0306) VERS="4" VR="SQ" VM="1" Keyword="CalibrationDataSequence" Name="Calibration Data Sequence"
+(0054,0308) VERS="4" VR="US" VM="1" Keyword="EnergyWindowNumber" Name="Energy Window Number"
+(0054,0400) VERS="4" VR="SH" VM="1" Keyword="ImageID" Name="Image ID"
+(0054,0410) VERS="4" VR="SQ" VM="1" Keyword="PatientOrientationCodeSequence" Name="Patient Orientation Code Sequence"
+(0054,0412) VERS="4" VR="SQ" VM="1" Keyword="PatientOrientationModifierCodeSequence" Name="Patient Orientation Modifier Code Sequence"
+(0054,0414) VERS="4" VR="SQ" VM="1" Keyword="PatientGantryRelationshipCodeSequence" Name="Patient Gantry Relationship Code Sequence"
+(0054,0500) VERS="4" VR="CS" VM="1" Keyword="SliceProgressionDirection" Name="Slice Progression Direction"
+(0054,1000) VERS="4" VR="CS" VM="2" Keyword="SeriesType" Name="Series Type"
+(0054,1001) VERS="4" VR="CS" VM="1" Keyword="Units" Name="Units"
+(0054,1002) VERS="4" VR="CS" VM="1" Keyword="CountsSource" Name="Counts Source"
+(0054,1004) VERS="4" VR="CS" VM="1" Keyword="ReprojectionMethod" Name="Reprojection Method"
+(0054,1006) VERS="4" VR="CS" VM="1" Keyword="SUVType" Name="SUV Type"
+(0054,1100) VERS="4" VR="CS" VM="1" Keyword="RandomsCorrectionMethod" Name="Randoms Correction Method"
+(0054,1101) VERS="4" VR="LO" VM="1" Keyword="AttenuationCorrectionMethod" Name="Attenuation Correction Method"
+(0054,1102) VERS="4" VR="CS" VM="1" Keyword="DecayCorrection" Name="Decay Correction"
+(0054,1103) VERS="4" VR="LO" VM="1" Keyword="ReconstructionMethod" Name="Reconstruction Method"
+(0054,1104) VERS="4" VR="LO" VM="1" Keyword="DetectorLinesOfResponseUsed" Name="Detector Lines of Response Used"
+(0054,1105) VERS="4" VR="LO" VM="1" Keyword="ScatterCorrectionMethod" Name="Scatter Correction Method"
+(0054,1200) VERS="4" VR="DS" VM="1" Keyword="AxialAcceptance" Name="Axial Acceptance"
+(0054,1201) VERS="4" VR="IS" VM="2" Keyword="AxialMash" Name="Axial Mash"
+(0054,1202) VERS="4" VR="IS" VM="1" Keyword="TransverseMash" Name="Transverse Mash"
+(0054,1203) VERS="4" VR="DS" VM="2" Keyword="DetectorElementSize" Name="Detector Element Size"
+(0054,1210) VERS="4" VR="DS" VM="1" Keyword="CoincidenceWindowWidth" Name="Coincidence Window Width"
+(0054,1220) VERS="4" VR="CS" VM="1-n" Keyword="SecondaryCountsType" Name="Secondary Counts Type"
+(0054,1300) VERS="4" VR="DS" VM="1" Keyword="FrameReferenceTime" Name="Frame Reference Time"
+(0054,1310) VERS="4" VR="IS" VM="1" Keyword="PrimaryPromptsCountsAccumulated" Name="Primary (Prompts) Counts Accumulated"
+(0054,1311) VERS="4" VR="IS" VM="1-n" Keyword="SecondaryCountsAccumulated" Name="Secondary Counts Accumulated"
+(0054,1320) VERS="4" VR="DS" VM="1" Keyword="SliceSensitivityFactor" Name="Slice Sensitivity Factor"
+(0054,1321) VERS="4" VR="DS" VM="1" Keyword="DecayFactor" Name="Decay Factor"
+(0054,1322) VERS="4" VR="DS" VM="1" Keyword="DoseCalibrationFactor" Name="Dose Calibration Factor"
+(0054,1323) VERS="4" VR="DS" VM="1" Keyword="ScatterFractionFactor" Name="Scatter Fraction Factor"
+(0054,1324) VERS="4" VR="DS" VM="1" Keyword="DeadTimeFactor" Name="Dead Time Factor"
+(0054,1330) VERS="4" VR="US" VM="1" Keyword="ImageIndex" Name="Image Index"
+(0054,1400) VERS="4RET" VR="CS" VM="1-n" Keyword="CountsIncluded" Name="Counts Included"
+(0054,1401) VERS="4RET" VR="CS" VM="1" Keyword="DeadTimeCorrectionFlag" Name="Dead Time Correction Flag"
+(0060,0000) VERS="3" VR="UL" VM="1" Keyword="HistogramGroupLength" Name="Histogram Group Length"
+(0060,3000) VERS="4" VR="SQ" VM="1" Keyword="HistogramSequence" Name="Histogram Sequence"
+(0060,3002) VERS="4" VR="US" VM="1" Keyword="HistogramNumberOfBins" Name="Histogram Number of Bins"
+(0060,3004) VERS="4" VR="US/SS" VM="1" Keyword="HistogramFirstBinValue" Name="Histogram First Bin Value"
+(0060,3006) VERS="4" VR="US/SS" VM="1" Keyword="HistogramLastBinValue" Name="Histogram Last Bin Value"
+(0060,3008) VERS="4" VR="US" VM="1" Keyword="HistogramBinWidth" Name="Histogram Bin Width"
+(0060,3010) VERS="4" VR="LO" VM="1" Keyword="HistogramExplanation" Name="Histogram Explanation"
+(0060,3020) VERS="4" VR="UL" VM="1-n" Keyword="HistogramData" Name="Histogram Data"
+(0062,0001) VERS="4" VR="CS" VM="1" Keyword="SegmentationType" Name="Segmentation Type"
+(0062,0002) VERS="4" VR="SQ" VM="1" Keyword="SegmentSequence" Name="Segment Sequence"
+(0062,0003) VERS="4" VR="SQ" VM="1" Keyword="SegmentedPropertyCategoryCodeSequence" Name="Segmented Property Category Code Sequence"
+(0062,0004) VERS="4" VR="US" VM="1" Keyword="SegmentNumber" Name="Segment Number"
+(0062,0005) VERS="4" VR="LO" VM="1" Keyword="SegmentLabel" Name="Segment Label"
+(0062,0006) VERS="4" VR="ST" VM="1" Keyword="SegmentDescription" Name="Segment Description"
+(0062,0008) VERS="4" VR="CS" VM="1" Keyword="SegmentAlgorithmType" Name="Segment Algorithm Type"
+(0062,0009) VERS="4" VR="LO" VM="1" Keyword="SegmentAlgorithmName" Name="Segment Algorithm Name"
+(0062,000A) VERS="4" VR="SQ" VM="1" Keyword="SegmentIdentificationSequence" Name="Segment Identification Sequence"
+(0062,000B) VERS="4" VR="US" VM="1-n" Keyword="ReferencedSegmentNumber" Name="Referenced Segment Number"
+(0062,000C) VERS="4" VR="US" VM="1" Keyword="RecommendedDisplayGrayscaleValue" Name="Recommended Display Grayscale Value"
+(0062,000D) VERS="4" VR="US" VM="3" Keyword="RecommendedDisplayCIELabValue" Name="Recommended Display CIELab Value"
+(0062,000E) VERS="4" VR="US" VM="1" Keyword="MaximumFractionalValue" Name="Maximum Fractional Value"
+(0062,000F) VERS="4" VR="SQ" VM="1" Keyword="SegmentedPropertyTypeCodeSequence" Name="Segmented Property Type Code Sequence"
+(0062,0010) VERS="4" VR="CS" VM="1" Keyword="SegmentationFractionalType" Name="Segmentation Fractional Type"
+(0064,0002) VERS="4" VR="SQ" VM="1" Keyword="DeformableRegistrationSequence" Name="Deformable Registration Sequence"
+(0064,0003) VERS="4" VR="UI" VM="1" Keyword="SourceFrameOfReferenceUID" Name="Source Frame of Reference UID"
+(0064,0005) VERS="4" VR="SQ" VM="1" Keyword="DeformableRegistrationGridSequence" Name="Deformable Registration Grid Sequence"
+(0064,0007) VERS="4" VR="UL" VM="3" Keyword="GridDimensions" Name="Grid Dimensions"
+(0064,0008) VERS="4" VR="FD" VM="3" Keyword="GridResolution" Name="Grid Resolution"
+(0064,0009) VERS="4" VR="OF" VM="1" Keyword="VectorGridData" Name="Vector Grid Data"
+(0064,000F) VERS="4" VR="SQ" VM="1" Keyword="PreDeformationMatrixRegistrationSequence" Name="Pre Deformation Matrix Registration Sequence"
+(0064,0010) VERS="4" VR="SQ" VM="1" Keyword="PostDeformationMatrixRegistrationSequence" Name="Post Deformation Matrix Registration Sequence"
+(0066,0001) VERS="4" VR="UL" VM="1" Keyword="NumberOfSurfaces" Name="Number of Surfaces"
+(0066,0002) VERS="4" VR="SQ" VM="1" Keyword="SurfaceSequence" Name="Surface Sequence"
+(0066,0003) VERS="4" VR="UL" VM="1" Keyword="SurfaceNumber" Name="Surface Number"
+(0066,0004) VERS="4" VR="LT" VM="1" Keyword="SurfaceComments" Name="Surface Comments"
+(0066,0009) VERS="4" VR="CS" VM="1" Keyword="SurfaceProcessing" Name="Surface Processing"
+(0066,000A) VERS="4" VR="FL" VM="1" Keyword="SurfaceProcessingRatio" Name="Surface Processing Ratio"
+(0066,000B) VERS="4" VR="LO" VM="1" Keyword="SurfaceProcessingDescription" Name="Surface Processing Description"
+(0066,000C) VERS="4" VR="FL" VM="1" Keyword="RecommendedPresentationOpacity" Name="Recommended Presentation Opacity"
+(0066,000D) VERS="4" VR="CS" VM="1" Keyword="RecommendedPresentationType" Name="Recommended Presentation Type"
+(0066,000E) VERS="4" VR="CS" VM="1" Keyword="FiniteVolume" Name="Finite Volume"
+(0066,0010) VERS="4" VR="CS" VM="1" Keyword="Manifold" Name="Manifold"
+(0066,0011) VERS="4" VR="SQ" VM="1" Keyword="SurfacePointsSequence" Name="Surface Points Sequence"
+(0066,0012) VERS="4" VR="SQ" VM="1" Keyword="SurfacePointsNormalsSequence" Name="Surface Points Normals Sequence"
+(0066,0013) VERS="4" VR="SQ" VM="1" Keyword="SurfaceMeshPrimitivesSequence" Name="Surface Mesh Primitives Sequence"
+(0066,0015) VERS="4" VR="UL" VM="1" Keyword="NumberOfSurfacePoints" Name="Number of Surface Points"
+(0066,0016) VERS="4" VR="OF" VM="1" Keyword="PointCoordinatesData" Name="Point Coordinates Data"
+(0066,0017) VERS="4" VR="FL" VM="3" Keyword="PointPositionAccuracy" Name="Point Position Accuracy"
+(0066,0018) VERS="4" VR="FL" VM="1" Keyword="MeanPointDistance" Name="Mean Point Distance"
+(0066,0019) VERS="4" VR="FL" VM="1" Keyword="MaximumPointDistance" Name="Maximum Point Distance"
+(0066,001A) VERS="4" VR="FL" VM="6" Keyword="PointsBoundingBoxCoordinates" Name="Points Bounding Box Coordinates"
+(0066,001B) VERS="4" VR="FL" VM="3" Keyword="AxisOfRotation" Name="Axis of Rotation"
+(0066,001C) VERS="4" VR="FL" VM="3" Keyword="CenterOfRotation" Name="Center of Rotation"
+(0066,001E) VERS="4" VR="UL" VM="1" Keyword="NumberOfVectors" Name="Number of Vectors"
+(0066,001F) VERS="4" VR="US" VM="1" Keyword="VectorDimensionality" Name="Vector Dimensionality"
+(0066,0020) VERS="4" VR="FL" VM="1-n" Keyword="VectorAccuracy" Name="Vector Accuracy"
+(0066,0021) VERS="4" VR="OF" VM="1" Keyword="VectorCoordinateData" Name="Vector Coordinate Data"
+(0066,0023) VERS="4" VR="OW" VM="1" Keyword="TrianglePointIndexList" Name="Triangle Point Index List"
+(0066,0024) VERS="4" VR="OW" VM="1" Keyword="EdgePointIndexList" Name="Edge Point Index List"
+(0066,0025) VERS="4" VR="OW" VM="1" Keyword="VertexPointIndexList" Name="Vertex Point Index List"
+(0066,0026) VERS="4" VR="SQ" VM="1" Keyword="TriangleStripSequence" Name="Triangle Strip Sequence"
+(0066,0027) VERS="4" VR="SQ" VM="1" Keyword="TriangleFanSequence" Name="Triangle Fan Sequence"
+(0066,0028) VERS="4" VR="SQ" VM="1" Keyword="LineSequence" Name="Line Sequence"
+(0066,0029) VERS="4" VR="OW" VM="1" Keyword="PrimitivePointIndexList" Name="Primitive Point Index List"
+(0066,002A) VERS="4" VR="UL" VM="1" Keyword="SurfaceCount" Name="Surface Count"
+(0066,002B) VERS="4" VR="SQ" VM="1" Keyword="ReferencedSurfaceSequence" Name="Referenced Surface Sequence"
+(0066,002C) VERS="4" VR="UL" VM="1" Keyword="ReferencedSurfaceNumber" Name="Referenced Surface Number"
+(0066,002D) VERS="4" VR="SQ" VM="1" Keyword="SegmentSurfaceGenerationAlgorithmIdentificationSequence" Name="Segment Surface Generation Algorithm Identification Sequence"
+(0066,002E) VERS="4" VR="SQ" VM="1" Keyword="SegmentSurfaceSourceInstanceSequence" Name="Segment Surface Source Instance Sequence"
+(0066,002F) VERS="4" VR="SQ" VM="1" Keyword="AlgorithmFamilyCodeSequence" Name="Algorithm Family Code Sequence"
+(0066,0030) VERS="4" VR="SQ" VM="1" Keyword="AlgorithmNameCodeSequence" Name="Algorithm Name Code Sequence"
+(0066,0031) VERS="4" VR="LO" VM="1" Keyword="AlgorithmVersion" Name="Algorithm Version"
+(0066,0032) VERS="4" VR="LT" VM="1" Keyword="AlgorithmParameters" Name="Algorithm Parameters"
+(0066,0034) VERS="4" VR="SQ" VM="1" Keyword="FacetSequence" Name="Facet Sequence"
+(0066,0035) VERS="4" VR="SQ" VM="1" Keyword="SurfaceProcessingAlgorithmIdentificationSequence" Name="Surface Processing Algorithm Identification Sequence"
+(0066,0036) VERS="4" VR="LO" VM="1" Keyword="AlgorithmName" Name="Algorithm Name"
+(0068,6210) VERS="4" VR="LO" VM="1" Keyword="ImplantSize" Name="Implant Size"
+(0068,6221) VERS="4" VR="LO" VM="1" Keyword="ImplantTemplateVersion" Name="Implant Template Version"
+(0068,6222) VERS="4" VR="SQ" VM="1" Keyword="ReplacedImplantTemplateSequence" Name="Replaced Implant Template Sequence"
+(0068,6223) VERS="4" VR="CS" VM="1" Keyword="ImplantType" Name="Implant Type"
+(0068,6224) VERS="4" VR="SQ" VM="1" Keyword="DerivationImplantTemplateSequence" Name="Derivation Implant Template Sequence "
+(0068,6225) VERS="4" VR="SQ" VM="1" Keyword="OriginalImplantTemplateSequence" Name="Original Implant Template Sequence "
+(0068,6226) VERS="4" VR="DT" VM="1" Keyword="EffectiveDateTime" Name="Effective DateTime"
+(0068,6230) VERS="4" VR="SQ" VM="1" Keyword="ImplantTargetAnatomySequence" Name="Implant Target Anatomy Sequence"
+(0068,6260) VERS="4" VR="SQ" VM="1" Keyword="InformationFromManufacturerSequence" Name="Information From Manufacturer Sequence"
+(0068,6265) VERS="4" VR="SQ" VM="1" Keyword="NotificationFromManufacturerSequence" Name="Notification From Manufacturer Sequence"
+(0068,6270) VERS="4" VR="DT" VM="1" Keyword="InformationIssueDateTime" Name="Information Issue DateTime"
+(0068,6280) VERS="4" VR="ST" VM="1" Keyword="InformationSummary" Name="Information Summary"
+(0068,62A0) VERS="4" VR="SQ" VM="1" Keyword="ImplantRegulatoryDisapprovalCodeSequence" Name="Implant Regulatory Disapproval Code Sequence"
+(0068,62A5) VERS="4" VR="FD" VM="1" Keyword="OverallTemplateSpatialTolerance" Name="Overall Template Spatial Tolerance"
+(0068,62C0) VERS="4" VR="SQ" VM="1" Keyword="HPGLDocumentSequence" Name="HPGL Document Sequence"
+(0068,62D0) VERS="4" VR="US" VM="1" Keyword="HPGLDocumentID" Name="HPGL Document ID"
+(0068,62D5) VERS="4" VR="LO" VM="1" Keyword="HPGLDocumentLabel" Name="HPGL Document Label"
+(0068,62E0) VERS="4" VR="SQ" VM="1" Keyword="ViewOrientationCodeSequence" Name="View Orientation Code Sequence"
+(0068,62F0) VERS="4" VR="FD" VM="9" Keyword="ViewOrientationModifier" Name="View Orientation Modifier"
+(0068,62F2) VERS="4" VR="FD" VM="1" Keyword="HPGLDocumentScaling" Name="HPGL Document Scaling"
+(0068,6300) VERS="4" VR="OB" VM="1" Keyword="HPGLDocument" Name="HPGL Document"
+(0068,6310) VERS="4" VR="US" VM="1" Keyword="HPGLContourPenNumber" Name="HPGL Contour Pen Number"
+(0068,6320) VERS="4" VR="SQ" VM="1" Keyword="HPGLPenSequence" Name="HPGL Pen Sequence"
+(0068,6330) VERS="4" VR="US" VM="1" Keyword="HPGLPenNumber" Name="HPGL Pen Number"
+(0068,6340) VERS="4" VR="LO" VM="1" Keyword="HPGLPenLabel" Name="HPGL Pen Label"
+(0068,6345) VERS="4" VR="ST" VM="1" Keyword="HPGLPenDescription" Name="HPGL Pen Description"
+(0068,6346) VERS="4" VR="FD" VM="2" Keyword="RecommendedRotationPoint" Name="Recommended Rotation Point"
+(0068,6347) VERS="4" VR="FD" VM="4" Keyword="BoundingRectangle" Name="Bounding Rectangle"
+(0068,6350) VERS="4" VR="US" VM="1-n" Keyword="ImplantTemplate3DModelSurfaceNumber" Name="Implant Template 3D Model Surface Number"
+(0068,6360) VERS="4" VR="SQ" VM="1" Keyword="SurfaceModelDescriptionSequence" Name="Surface Model Description Sequence"
+(0068,6380) VERS="4" VR="LO" VM="1" Keyword="SurfaceModelLabel" Name="Surface Model Label"
+(0068,6390) VERS="4" VR="FD" VM="1" Keyword="SurfaceModelScalingFactor" Name="Surface Model Scaling Factor"
+(0068,63A0) VERS="4" VR="SQ" VM="1" Keyword="MaterialsCodeSequence" Name="Materials Code Sequence"
+(0068,63A4) VERS="4" VR="SQ" VM="1" Keyword="CoatingMaterialsCodeSequence" Name="Coating Materials Code Sequence"
+(0068,63A8) VERS="4" VR="SQ" VM="1" Keyword="ImplantTypeCodeSequence" Name="Implant Type Code Sequence"
+(0068,63AC) VERS="4" VR="SQ" VM="1" Keyword="FixationMethodCodeSequence" Name="Fixation Method Code Sequence"
+(0068,63B0) VERS="4" VR="SQ" VM="1" Keyword="MatingFeatureSetsSequence" Name="Mating Feature Sets Sequence"
+(0068,63C0) VERS="4" VR="US" VM="1" Keyword="MatingFeatureSetID" Name="Mating Feature Set ID"
+(0068,63D0) VERS="4" VR="LO" VM="1" Keyword="MatingFeatureSetLabel" Name="Mating Feature Set Label"
+(0068,63E0) VERS="4" VR="SQ" VM="1" Keyword="MatingFeatureSequence" Name="Mating Feature Sequence"
+(0068,63F0) VERS="4" VR="US" VM="1" Keyword="MatingFeatureID" Name="Mating Feature ID"
+(0068,6400) VERS="4" VR="SQ" VM="1" Keyword="MatingFeatureDegreeOfFreedomSequence" Name="Mating Feature Degree of Freedom Sequence"
+(0068,6410) VERS="4" VR="US" VM="1" Keyword="DegreeOfFreedomID" Name="Degree of Freedom ID"
+(0068,6420) VERS="4" VR="CS" VM="1" Keyword="DegreeOfFreedomType" Name="Degree of Freedom Type"
+(0068,6430) VERS="4" VR="SQ" VM="1" Keyword="TwoDMatingFeatureCoordinatesSequence" Name="2D Mating Feature Coordinates Sequence"
+(0068,6440) VERS="4" VR="US" VM="1" Keyword="ReferencedHPGLDocumentID" Name="Referenced HPGL Document ID"
+(0068,6450) VERS="4" VR="FD" VM="2" Keyword="TwoDMatingPoint" Name="2D Mating Point"
+(0068,6460) VERS="4" VR="FD" VM="4" Keyword="TwoDMatingAxes" Name="2D Mating Axes"
+(0068,6470) VERS="4" VR="SQ" VM="1" Keyword="TwoDDegreeOfFreedomSequence" Name="2D Degree of Freedom Sequence"
+(0068,6490) VERS="4" VR="FD" VM="3" Keyword="ThreeDDegreeOfFreedomAxis" Name="3D Degree of Freedom Axis"
+(0068,64A0) VERS="4" VR="FD" VM="2" Keyword="RangeOfFreedom" Name="Range of Freedom"
+(0068,64C0) VERS="4" VR="FD" VM="3" Keyword="ThreeDMatingPoint" Name="3D Mating Point"
+(0068,64D0) VERS="4" VR="FD" VM="9" Keyword="ThreeDMatingAxes" Name="3D Mating Axes"
+(0068,64F0) VERS="4" VR="FD" VM="3" Keyword="TwoDDegreeOfFreedomAxis" Name="2D Degree of Freedom Axis"
+(0068,6500) VERS="4" VR="SQ" VM="1" Keyword="PlanningLandmarkPointSequence" Name="Planning Landmark Point Sequence"
+(0068,6510) VERS="4" VR="SQ" VM="1" Keyword="PlanningLandmarkLineSequence" Name="Planning Landmark Line Sequence"
+(0068,6520) VERS="4" VR="SQ" VM="1" Keyword="PlanningLandmarkPlaneSequence" Name="Planning Landmark Plane Sequence"
+(0068,6530) VERS="4" VR="US" VM="1" Keyword="PlanningLandmarkID" Name="Planning Landmark ID"
+(0068,6540) VERS="4" VR="LO" VM="1" Keyword="PlanningLandmarkDescription" Name="Planning Landmark Description"
+(0068,6545) VERS="4" VR="SQ" VM="1" Keyword="PlanningLandmarkIdentificationCodeSequence" Name="Planning Landmark Identification Code Sequence"
+(0068,6550) VERS="4" VR="SQ" VM="1" Keyword="TwoDPointCoordinatesSequence" Name="2D Point Coordinates Sequence"
+(0068,6560) VERS="4" VR="FD" VM="2" Keyword="TwoDPointCoordinates" Name="2D Point Coordinates"
+(0068,6590) VERS="4" VR="FD" VM="3" Keyword="ThreeDPointCoordinates" Name="3D Point Coordinates"
+(0068,65A0) VERS="4" VR="SQ" VM="1" Keyword="TwoDLineCoordinatesSequence" Name="2D Line Coordinates Sequence"
+(0068,65B0) VERS="4" VR="FD" VM="4" Keyword="TwoDLineCoordinates" Name="2D Line Coordinates"
+(0068,65D0) VERS="4" VR="FD" VM="6" Keyword="ThreeDLineCoordinates" Name="3D Line Coordinates"
+(0068,65E0) VERS="4" VR="SQ" VM="1" Keyword="TwoDPlaneCoordinatesSequence" Name="2D Plane Coordinates Sequence"
+(0068,65F0) VERS="4" VR="FD" VM="4" Keyword="TwoDPlaneIntersection" Name="2D Plane Intersection"
+(0068,6610) VERS="4" VR="FD" VM="3" Keyword="ThreeDPlaneOrigin" Name="3D Plane Origin"
+(0068,6620) VERS="4" VR="FD" VM="3" Keyword="ThreeDPlaneNormal" Name="3D Plane Normal"
+(0070,0000) VERS="3" VR="UL" VM="1" Keyword="PresentationStateGroupLength" Name="Presentation State Group Length"
+(0070,0001) VERS="4" VR="SQ" VM="1" Keyword="GraphicAnnotationSequence" Name="Graphic Annotation Sequence"
+(0070,0002) VERS="4" VR="CS" VM="1" Keyword="GraphicLayer" Name="Graphic Layer"
+(0070,0003) VERS="4" VR="CS" VM="1" Keyword="BoundingBoxAnnotationUnits" Name="Bounding Box Annotation Units"
+(0070,0004) VERS="4" VR="CS" VM="1" Keyword="AnchorPointAnnotationUnits" Name="Anchor Point Annotation Units"
+(0070,0005) VERS="4" VR="CS" VM="1" Keyword="GraphicAnnotationUnits" Name="Graphic Annotation Units"
+(0070,0006) VERS="4" VR="ST" VM="1" Keyword="UnformattedTextValue" Name="Unformatted Text Value"
+(0070,0008) VERS="4" VR="SQ" VM="1" Keyword="TextObjectSequence" Name="Text Object Sequence"
+(0070,0009) VERS="4" VR="SQ" VM="1" Keyword="GraphicObjectSequence" Name="Graphic Object Sequence"
+(0070,0010) VERS="4" VR="FL" VM="2" Keyword="BoundingBoxTopLeftHandCorner" Name="Bounding Box Top Left Hand Corner"
+(0070,0011) VERS="4" VR="FL" VM="2" Keyword="BoundingBoxBottomRightHandCorner" Name="Bounding Box Bottom Right Hand Corner"
+(0070,0012) VERS="4" VR="CS" VM="1" Keyword="BoundingBoxTextHorizontalJustification" Name="Bounding Box Text Horizontal Justification"
+(0070,0014) VERS="4" VR="FL" VM="2" Keyword="AnchorPoint" Name="Anchor Point"
+(0070,0015) VERS="4" VR="CS" VM="1" Keyword="AnchorPointVisibility" Name="Anchor Point Visibility"
+(0070,0020) VERS="4" VR="US" VM="1" Keyword="GraphicDimensions" Name="Graphic Dimensions "
+(0070,0021) VERS="4" VR="US" VM="1" Keyword="NumberOfGraphicPoints" Name="Number of Graphic Points"
+(0070,0022) VERS="4" VR="FL" VM="2-n" Keyword="GraphicData" Name="Graphic Data"
+(0070,0023) VERS="4" VR="CS" VM="1" Keyword="GraphicType" Name="Graphic Type"
+(0070,0024) VERS="4" VR="CS" VM="1" Keyword="GraphicFilled" Name="Graphic Filled"
+(0070,0040) VERS="4RET" VR="IS" VM="1" Keyword="ImageRotationRetired" Name="Image Rotation (Retired)"
+(0070,0041) VERS="4" VR="CS" VM="1" Keyword="ImageHorizontalFlip" Name="Image Horizontal Flip"
+(0070,0042) VERS="4" VR="US" VM="1" Keyword="ImageRotation" Name="Image Rotation "
+(0070,0050) VERS="4RET" VR="US" VM="2" Keyword="DisplayedAreaTopLeftHandCornerTrial" Name="Displayed Area Top Left Hand Corner (Trial)"
+(0070,0051) VERS="4RET" VR="US" VM="2" Keyword="DisplayedAreaBottomRightHandCornerTrial" Name="Displayed Area Bottom Right Hand Corner (Trial)"
+(0070,0052) VERS="4" VR="SL" VM="2" Keyword="DisplayedAreaTopLeftHandCorner" Name="Displayed Area Top Left Hand Corner"
+(0070,0053) VERS="4" VR="SL" VM="2" Keyword="DisplayedAreaBottomRightHandCorner" Name="Displayed Area Bottom Right Hand Corner"
+(0070,005A) VERS="4" VR="SQ" VM="1" Keyword="DisplayedAreaSelectionSequence" Name="Displayed Area Selection Sequence"
+(0070,0060) VERS="4" VR="SQ" VM="1" Keyword="GraphicLayerSequence" Name="Graphic Layer Sequence"
+(0070,0062) VERS="4" VR="IS" VM="1" Keyword="GraphicLayerOrder" Name="Graphic Layer Order"
+(0070,0066) VERS="4" VR="US" VM="1" Keyword="GraphicLayerRecommendedDisplayGrayscaleValue" Name="Graphic Layer Recommended Display Grayscale Value"
+(0070,0067) VERS="4RET" VR="US" VM="3" Keyword="GraphicLayerRecommendedDisplayRGBValue" Name="Graphic Layer Recommended Display RGB Value"
+(0070,0068) VERS="4" VR="LO" VM="1" Keyword="GraphicLayerDescription" Name="Graphic Layer Description"
+(0070,0080) VERS="4" VR="CS" VM="1" Keyword="ContentLabel" Name="Content Label"
+(0070,0081) VERS="4" VR="LO" VM="1" Keyword="ContentDescription" Name="Content Description"
+(0070,0082) VERS="4" VR="DA" VM="1" Keyword="PresentationCreationDate" Name="Presentation Creation Date"
+(0070,0083) VERS="4" VR="TM" VM="1" Keyword="PresentationCreationTime" Name="Presentation Creation Time"
+(0070,0084) VERS="4" VR="PN" VM="1" Keyword="ContentCreatorName" Name="Content Creator�s Name"
+(0070,0086) VERS="4" VR="SQ" VM="1" Keyword="ContentCreatorIdentificationCodeSequence" Name="Content Creator�s Identification Code Sequence"
+(0070,0087) VERS="4" VR="SQ" VM="1" Keyword="AlternateContentDescriptionSequence" Name="Alternate Content Description Sequence"
+(0070,0100) VERS="4" VR="CS" VM="1" Keyword="PresentationSizeMode" Name="Presentation Size Mode"
+(0070,0101) VERS="4" VR="DS" VM="2" Keyword="PresentationPixelSpacing" Name="Presentation Pixel Spacing"
+(0070,0102) VERS="4" VR="IS" VM="2" Keyword="PresentationPixelAspectRatio" Name="Presentation Pixel Aspect Ratio"
+(0070,0103) VERS="4" VR="FL" VM="1" Keyword="PresentationPixelMagnificationRatio" Name="Presentation Pixel Magnification Ratio"
+(0070,0207) VERS="4" VR="LO" VM="1" Keyword="GraphicGroupLabel" Name="Graphic Group Label"
+(0070,0208) VERS="4" VR="ST" VM="1" Keyword="GraphicGroupDescription" Name="Graphic Group Description"
+(0070,0209) VERS="4" VR="SQ" VM="1" Keyword="CompoundGraphicSequence" Name="Compound Graphic Sequence"
+(0070,0226) VERS="4" VR="UL" VM="1" Keyword="CompoundGraphicInstanceID" Name="Compound Graphic Instance ID"
+(0070,0227) VERS="4" VR="LO" VM="1" Keyword="FontName" Name="Font Name"
+(0070,0228) VERS="4" VR="CS" VM="1" Keyword="FontNameType" Name="Font Name Type"
+(0070,0229) VERS="4" VR="LO" VM="1" Keyword="CSSFontName" Name="CSS Font Name"
+(0070,0230) VERS="4" VR="FD" VM="1" Keyword="RotationAngle" Name="Rotation Angle"
+(0070,0231) VERS="4" VR="SQ" VM="1" Keyword="TextStyleSequence" Name="Text Style Sequence"
+(0070,0232) VERS="4" VR="SQ" VM="1" Keyword="LineStyleSequence" Name="Line Style Sequence"
+(0070,0233) VERS="4" VR="SQ" VM="1" Keyword="FillStyleSequence" Name="Fill Style Sequence"
+(0070,0234) VERS="4" VR="SQ" VM="1" Keyword="GraphicGroupSequence" Name="Graphic Group Sequence"
+(0070,0241) VERS="4" VR="US" VM="3" Keyword="TextColorCIELabValue" Name="Text Color CIELab Value"
+(0070,0242) VERS="4" VR="CS" VM="1" Keyword="HorizontalAlignment" Name="Horizontal Alignment"
+(0070,0243) VERS="4" VR="CS" VM="1" Keyword="VerticalAlignment" Name="Vertical Alignment"
+(0070,0244) VERS="4" VR="CS" VM="1" Keyword="ShadowStyle" Name="Shadow Style"
+(0070,0245) VERS="4" VR="FL" VM="1" Keyword="ShadowOffsetX" Name="Shadow Offset X"
+(0070,0246) VERS="4" VR="FL" VM="1" Keyword="ShadowOffsetY" Name="Shadow Offset Y"
+(0070,0247) VERS="4" VR="US" VM="3" Keyword="ShadowColorCIELabValue" Name="Shadow Color CIELab Value"
+(0070,0248) VERS="4" VR="CS" VM="1" Keyword="Underlined" Name="Underlined"
+(0070,0249) VERS="4" VR="CS" VM="1" Keyword="Bold" Name="Bold"
+(0070,0250) VERS="4" VR="CS" VM="1" Keyword="Italic" Name="Italic"
+(0070,0251) VERS="4" VR="US" VM="3" Keyword="PatternOnColorCIELabValue" Name="Pattern On Color CIELab Value"
+(0070,0252) VERS="4" VR="US" VM="3" Keyword="PatternOffColorCIELabValue" Name="Pattern Off Color CIELab Value"
+(0070,0253) VERS="4" VR="FL" VM="1" Keyword="LineThickness" Name="Line Thickness"
+(0070,0254) VERS="4" VR="CS" VM="1" Keyword="LineDashingStyle" Name="Line Dashing Style"
+(0070,0255) VERS="4" VR="UL" VM="1" Keyword="LinePattern" Name="Line Pattern"
+(0070,0256) VERS="4" VR="OB" VM="1" Keyword="FillPattern" Name="Fill Pattern"
+(0070,0257) VERS="4" VR="CS" VM="1" Keyword="FillMode" Name="Fill Mode"
+(0070,0258) VERS="4" VR="FL" VM="1" Keyword="ShadowOpacity" Name="Shadow Opacity"
+(0070,0261) VERS="4" VR="FL" VM="1" Keyword="GapLength" Name="Gap Length"
+(0070,0262) VERS="4" VR="FL" VM="1" Keyword="DiameterOfVisibility" Name="Diameter of Visibility"
+(0070,0273) VERS="4" VR="FL" VM="2" Keyword="RotationPoint" Name="Rotation Point"
+(0070,0274) VERS="4" VR="CS" VM="1" Keyword="TickAlignment" Name="Tick Alignment"
+(0070,0278) VERS="4" VR="CS" VM="1" Keyword="ShowTickLabel" Name="Show Tick Label"
+(0070,0279) VERS="4" VR="CS" VM="1" Keyword="TickLabelAlignment" Name="Tick Label Alignment"
+(0070,0282) VERS="4" VR="CS" VM="1" Keyword="CompoundGraphicUnits" Name="Compound Graphic Units"
+(0070,0284) VERS="4" VR="FL" VM="1" Keyword="PatternOnOpacity" Name="Pattern On Opacity"
+(0070,0285) VERS="4" VR="FL" VM="1" Keyword="PatternOffOpacity" Name="Pattern Off Opacity"
+(0070,0287) VERS="4" VR="SQ" VM="1" Keyword="MajorTicksSequence" Name="Major Ticks Sequence"
+(0070,0288) VERS="4" VR="FL" VM="1" Keyword="TickPosition" Name="Tick Position"
+(0070,0289) VERS="4" VR="SH" VM="1" Keyword="TickLabel" Name="Tick Label"
+(0070,0294) VERS="4" VR="CS" VM="1" Keyword="CompoundGraphicType" Name="Compound Graphic Type"
+(0070,0295) VERS="4" VR="UL" VM="1" Keyword="GraphicGroupID" Name="Graphic Group ID"
+(0070,0306) VERS="4" VR="CS" VM="1" Keyword="ShapeType" Name="Shape Type"
+(0070,0308) VERS="4" VR="SQ" VM="1" Keyword="RegistrationSequence" Name="Registration Sequence"
+(0070,0309) VERS="4" VR="SQ" VM="1" Keyword="MatrixRegistrationSequence" Name="Matrix Registration Sequence"
+(0070,030A) VERS="4" VR="SQ" VM="1" Keyword="MatrixSequence" Name="Matrix Sequence"
+(0070,030C) VERS="4" VR="CS" VM="1" Keyword="FrameOfReferenceTransformationMatrixType" Name="Frame of Reference Transformation Matrix Type"
+(0070,030D) VERS="4" VR="SQ" VM="1" Keyword="RegistrationTypeCodeSequence" Name="Registration Type Code Sequence"
+(0070,030F) VERS="4" VR="ST" VM="1" Keyword="FiducialDescription" Name="Fiducial Description"
+(0070,0310) VERS="4" VR="SH" VM="1" Keyword="FiducialIdentifier" Name="Fiducial Identifier"
+(0070,0311) VERS="4" VR="SQ" VM="1" Keyword="FiducialIdentifierCodeSequence" Name="Fiducial Identifier Code Sequence"
+(0070,0312) VERS="4" VR="FD" VM="1" Keyword="ContourUncertaintyRadius" Name="Contour Uncertainty Radius"
+(0070,0314) VERS="4" VR="SQ" VM="1" Keyword="UsedFiducialsSequence" Name="Used Fiducials Sequence"
+(0070,0318) VERS="4" VR="SQ" VM="1" Keyword="GraphicCoordinatesDataSequence" Name="Graphic Coordinates Data Sequence"
+(0070,031A) VERS="4" VR="UI" VM="1" Keyword="FiducialUID" Name="Fiducial UID"
+(0070,031C) VERS="4" VR="SQ" VM="1" Keyword="FiducialSetSequence" Name="Fiducial Set Sequence"
+(0070,031E) VERS="4" VR="SQ" VM="1" Keyword="FiducialSequence" Name="Fiducial Sequence"
+(0070,0401) VERS="4" VR="US" VM="3" Keyword="GraphicLayerRecommendedDisplayCIELabValue" Name="Graphic Layer Recommended Display CIELab Value"
+(0070,0402) VERS="4" VR="SQ" VM="1" Keyword="BlendingSequence" Name="Blending Sequence"
+(0070,0403) VERS="4" VR="FL" VM="1" Keyword="RelativeOpacity" Name="Relative Opacity"
+(0070,0404) VERS="4" VR="SQ" VM="1" Keyword="ReferencedSpatialRegistrationSequence" Name="Referenced Spatial Registration Sequence"
+(0070,0405) VERS="4" VR="CS" VM="1" Keyword="BlendingPosition" Name="Blending Position"
+(0072,0002) VERS="4" VR="SH" VM="1" Keyword="HangingProtocolName" Name="Hanging Protocol Name"
+(0072,0004) VERS="4" VR="LO" VM="1" Keyword="HangingProtocolDescription" Name="Hanging Protocol Description"
+(0072,0006) VERS="4" VR="CS" VM="1" Keyword="HangingProtocolLevel" Name="Hanging Protocol Level"
+(0072,0008) VERS="4" VR="LO" VM="1" Keyword="HangingProtocolCreator" Name="Hanging Protocol Creator"
+(0072,000A) VERS="4" VR="DT" VM="1" Keyword="HangingProtocolCreationDateTime" Name="Hanging Protocol Creation DateTime"
+(0072,000C) VERS="4" VR="SQ" VM="1" Keyword="HangingProtocolDefinitionSequence" Name="Hanging Protocol Definition Sequence"
+(0072,000E) VERS="4" VR="SQ" VM="1" Keyword="HangingProtocolUserIdentificationCodeSequence" Name="Hanging Protocol User Identification Code Sequence"
+(0072,0010) VERS="4" VR="LO" VM="1" Keyword="HangingProtocolUserGroupName" Name="Hanging Protocol User Group Name"
+(0072,0012) VERS="4" VR="SQ" VM="1" Keyword="SourceHangingProtocolSequence" Name="Source Hanging Protocol Sequence"
+(0072,0014) VERS="4" VR="US" VM="1" Keyword="NumberOfPriorsReferenced" Name="Number of Priors Referenced"
+(0072,0020) VERS="4" VR="SQ" VM="1" Keyword="ImageSetsSequence" Name="Image Sets Sequence"
+(0072,0022) VERS="4" VR="SQ" VM="1" Keyword="ImageSetSelectorSequence" Name="Image Set Selector Sequence"
+(0072,0024) VERS="4" VR="CS" VM="1" Keyword="ImageSetSelectorUsageFlag" Name="Image Set Selector Usage Flag"
+(0072,0026) VERS="4" VR="AT" VM="1" Keyword="SelectorAttribute" Name="Selector Attribute"
+(0072,0028) VERS="4" VR="US" VM="1" Keyword="SelectorValueNumber" Name="Selector Value Number"
+(0072,0030) VERS="4" VR="SQ" VM="1" Keyword="TimeBasedImageSetsSequence" Name="Time Based Image Sets Sequence"
+(0072,0032) VERS="4" VR="US" VM="1" Keyword="ImageSetNumber" Name="Image Set Number"
+(0072,0034) VERS="4" VR="CS" VM="1" Keyword="ImageSetSelectorCategory" Name="Image Set Selector Category"
+(0072,0038) VERS="4" VR="US" VM="2" Keyword="RelativeTime" Name="Relative Time"
+(0072,003A) VERS="4" VR="CS" VM="1" Keyword="RelativeTimeUnits" Name="Relative Time Units"
+(0072,003C) VERS="4" VR="SS" VM="2" Keyword="AbstractPriorValue" Name="Abstract Prior Value"
+(0072,003E) VERS="4" VR="SQ" VM="1" Keyword="AbstractPriorCodeSequence" Name="Abstract Prior Code Sequence"
+(0072,0040) VERS="4" VR="LO" VM="1" Keyword="ImageSetLabel" Name="Image Set Label"
+(0072,0050) VERS="4" VR="CS" VM="1" Keyword="SelectorAttributeVR" Name="Selector Attribute VR"
+(0072,0052) VERS="4" VR="AT" VM="1-n" Keyword="SelectorSequencePointer" Name="Selector Sequence Pointer"
+(0072,0054) VERS="4" VR="LO" VM="1-n" Keyword="SelectorSequencePointerPrivateCreator" Name="Selector Sequence Pointer Private Creator"
+(0072,0056) VERS="4" VR="LO" VM="1" Keyword="SelectorAttributePrivateCreator" Name="Selector Attribute Private Creator"
+(0072,0060) VERS="4" VR="AT" VM="1-n" Keyword="SelectorATValue" Name="Selector AT Value"
+(0072,0062) VERS="4" VR="CS" VM="1-n" Keyword="SelectorCSValue" Name="Selector CS Value"
+(0072,0064) VERS="4" VR="IS" VM="1-n" Keyword="SelectorISValue" Name="Selector IS Value"
+(0072,0066) VERS="4" VR="LO" VM="1-n" Keyword="SelectorLOValue" Name="Selector LO Value"
+(0072,0068) VERS="4" VR="LT" VM="1" Keyword="SelectorLTValue" Name="Selector LT Value"
+(0072,006A) VERS="4" VR="PN" VM="1-n" Keyword="SelectorPNValue" Name="Selector PN Value"
+(0072,006C) VERS="4" VR="SH" VM="1-n" Keyword="SelectorSHValue" Name="Selector SH Value"
+(0072,006E) VERS="4" VR="ST" VM="1" Keyword="SelectorSTValue" Name="Selector ST Value"
+(0072,0070) VERS="4" VR="UT" VM="1" Keyword="SelectorUTValue" Name="Selector UT Value"
+(0072,0072) VERS="4" VR="DS" VM="1-n" Keyword="SelectorDSValue" Name="Selector DS Value"
+(0072,0074) VERS="4" VR="FD" VM="1-n" Keyword="SelectorFDValue" Name="Selector FD Value"
+(0072,0076) VERS="4" VR="FL" VM="1-n" Keyword="SelectorFLValue" Name="Selector FL Value"
+(0072,0078) VERS="4" VR="UL" VM="1-n" Keyword="SelectorULValue" Name="Selector UL Value"
+(0072,007A) VERS="4" VR="US" VM="1-n" Keyword="SelectorUSValue" Name="Selector US Value"
+(0072,007C) VERS="4" VR="SL" VM="1-n" Keyword="SelectorSLValue" Name="Selector SL Value"
+(0072,007E) VERS="4" VR="SS" VM="1-n" Keyword="SelectorSSValue" Name="Selector SS Value"
+(0072,0080) VERS="4" VR="SQ" VM="1" Keyword="SelectorCodeSequenceValue" Name="Selector Code Sequence Value"
+(0072,0100) VERS="4" VR="US" VM="1" Keyword="NumberOfScreens" Name="Number of Screens"
+(0072,0102) VERS="4" VR="SQ" VM="1" Keyword="NominalScreenDefinitionSequence" Name="Nominal Screen Definition Sequence"
+(0072,0104) VERS="4" VR="US" VM="1" Keyword="NumberOfVerticalPixels" Name="Number of Vertical Pixels"
+(0072,0106) VERS="4" VR="US" VM="1" Keyword="NumberOfHorizontalPixels" Name="Number of Horizontal Pixels"
+(0072,0108) VERS="4" VR="FD" VM="4" Keyword="DisplayEnvironmentSpatialPosition" Name="Display Environment Spatial Position"
+(0072,010A) VERS="4" VR="US" VM="1" Keyword="ScreenMinimumGrayscaleBitDepth" Name="Screen Minimum Grayscale Bit Depth"
+(0072,010C) VERS="4" VR="US" VM="1" Keyword="ScreenMinimumColorBitDepth" Name="Screen Minimum Color Bit Depth"
+(0072,010E) VERS="4" VR="US" VM="1" Keyword="ApplicationMaximumRepaintTime" Name="Application Maximum Repaint Time"
+(0072,0200) VERS="4" VR="SQ" VM="1" Keyword="DisplaySetsSequence" Name="Display Sets Sequence"
+(0072,0202) VERS="4" VR="US" VM="1" Keyword="DisplaySetNumber" Name="Display Set Number"
+(0072,0203) VERS="4" VR="LO" VM="1" Keyword="DisplaySetLabel" Name="Display Set Label"
+(0072,0204) VERS="4" VR="US" VM="1" Keyword="DisplaySetPresentationGroup" Name="Display Set Presentation Group"
+(0072,0206) VERS="4" VR="LO" VM="1" Keyword="DisplaySetPresentationGroupDescription" Name="Display Set Presentation Group Description"
+(0072,0208) VERS="4" VR="CS" VM="1" Keyword="PartialDataDisplayHandling" Name="Partial Data Display Handling"
+(0072,0210) VERS="4" VR="SQ" VM="1" Keyword="SynchronizedScrollingSequence" Name="Synchronized Scrolling Sequence"
+(0072,0212) VERS="4" VR="US" VM="2-n" Keyword="DisplaySetScrollingGroup" Name="Display Set Scrolling Group"
+(0072,0214) VERS="4" VR="SQ" VM="1" Keyword="NavigationIndicatorSequence" Name="Navigation Indicator Sequence"
+(0072,0216) VERS="4" VR="US" VM="1" Keyword="NavigationDisplaySet" Name="Navigation Display Set "
+(0072,0218) VERS="4" VR="US" VM="1-n" Keyword="ReferenceDisplaySets" Name="Reference Display Sets"
+(0072,0300) VERS="4" VR="SQ" VM="1" Keyword="ImageBoxesSequence" Name="Image Boxes Sequence"
+(0072,0302) VERS="4" VR="US" VM="1" Keyword="ImageBoxNumber" Name="Image Box Number"
+(0072,0304) VERS="4" VR="CS" VM="1" Keyword="ImageBoxLayoutType" Name="Image Box Layout Type"
+(0072,0306) VERS="4" VR="US" VM="1" Keyword="ImageBoxTileHorizontalDimension" Name="Image Box Tile Horizontal Dimension"
+(0072,0308) VERS="4" VR="US" VM="1" Keyword="ImageBoxTileVerticalDimension" Name="Image Box Tile Vertical Dimension"
+(0072,0310) VERS="4" VR="CS" VM="1" Keyword="ImageBoxScrollDirection" Name="Image Box Scroll Direction"
+(0072,0312) VERS="4" VR="CS" VM="1" Keyword="ImageBoxSmallScrollType" Name="Image Box Small Scroll Type"
+(0072,0314) VERS="4" VR="US" VM="1" Keyword="ImageBoxSmallScrollAmount" Name="Image Box Small Scroll Amount"
+(0072,0316) VERS="4" VR="CS" VM="1" Keyword="ImageBoxLargeScrollType" Name="Image Box Large Scroll Type"
+(0072,0318) VERS="4" VR="US" VM="1" Keyword="ImageBoxLargeScrollAmount" Name="Image Box Large Scroll Amount"
+(0072,0320) VERS="4" VR="US" VM="1" Keyword="ImageBoxOverlapPriority" Name="Image Box Overlap Priority"
+(0072,0330) VERS="4" VR="FD" VM="1" Keyword="CineRelativeToRealTime" Name="Cine Relative to Real-Time"
+(0072,0400) VERS="4" VR="SQ" VM="1" Keyword="FilterOperationsSequence" Name="Filter Operations Sequence"
+(0072,0402) VERS="4" VR="CS" VM="1" Keyword="FilterByCategory" Name="Filter-by Category"
+(0072,0404) VERS="4" VR="CS" VM="1" Keyword="FilterByAttributePresence" Name="Filter-by Attribute Presence"
+(0072,0406) VERS="4" VR="CS" VM="1" Keyword="FilterByOperator" Name="Filter-by Operator"
+(0072,0420) VERS="4" VR="US" VM="3" Keyword="StructuredDisplayBackgroundCIELabValue" Name="Structured Display Background CIELab Value"
+(0072,0421) VERS="4" VR="US" VM="3" Keyword="EmptyImageBoxCIELabValue" Name="Empty Image Box CIELab Value"
+(0072,0422) VERS="4" VR="SQ" VM="1" Keyword="StructuredDisplayImageBoxSequence" Name="Structured Display Image Box Sequence"
+(0072,0424) VERS="4" VR="SQ" VM="1" Keyword="StructuredDisplayTextBoxSequence" Name="Structured Display Text Box Sequence"
+(0072,0427) VERS="4" VR="SQ" VM="1" Keyword="ReferencedFirstFrameSequence" Name="Referenced First Frame Sequence"
+(0072,0430) VERS="4" VR="SQ" VM="1" Keyword="ImageBoxSynchronizationSequence" Name="Image Box Synchronization Sequence"
+(0072,0432) VERS="4" VR="US" VM="2-n" Keyword="SynchronizedImageBoxList" Name="Synchronized Image Box List"
+(0072,0434) VERS="4" VR="CS" VM="1" Keyword="TypeOfSynchronization" Name="Type of Synchronization"
+(0072,0500) VERS="4" VR="CS" VM="1" Keyword="BlendingOperationType" Name="Blending Operation Type"
+(0072,0510) VERS="4" VR="CS" VM="1" Keyword="ReformattingOperationType" Name="Reformatting Operation Type"
+(0072,0512) VERS="4" VR="FD" VM="1" Keyword="ReformattingThickness" Name="Reformatting Thickness"
+(0072,0514) VERS="4" VR="FD" VM="1" Keyword="ReformattingInterval" Name="Reformatting Interval"
+(0072,0516) VERS="4" VR="CS" VM="1" Keyword="ReformattingOperationInitialViewDirection" Name="Reformatting Operation Initial View Direction"
+(0072,0520) VERS="4" VR="CS" VM="1-n" Keyword="ThreeDRenderingType" Name="3D Rendering Type"
+(0072,0600) VERS="4" VR="SQ" VM="1" Keyword="SortingOperationsSequence" Name="Sorting Operations Sequence"
+(0072,0602) VERS="4" VR="CS" VM="1" Keyword="SortByCategory" Name="Sort-by Category"
+(0072,0604) VERS="4" VR="CS" VM="1" Keyword="SortingDirection" Name="Sorting Direction"
+(0072,0700) VERS="4" VR="CS" VM="2" Keyword="DisplaySetPatientOrientation" Name="Display Set Patient Orientation"
+(0072,0702) VERS="4" VR="CS" VM="1" Keyword="VOIType" Name="VOI Type"
+(0072,0704) VERS="4" VR="CS" VM="1" Keyword="PseudoColorType" Name="Pseudo-Color Type"
+(0072,0705) VERS="4" VR="SQ" VM="1" Keyword="PseudoColorPaletteInstanceReferenceSequence" Name="Pseudo-Color Palette Instance Reference Sequence"
+(0072,0706) VERS="4" VR="CS" VM="1" Keyword="ShowGrayscaleInverted" Name="Show Grayscale Inverted"
+(0072,0710) VERS="4" VR="CS" VM="1" Keyword="ShowImageTrueSizeFlag" Name="Show Image True Size Flag"
+(0072,0712) VERS="4" VR="CS" VM="1" Keyword="ShowGraphicAnnotationFlag" Name="Show Graphic Annotation Flag"
+(0072,0714) VERS="4" VR="CS" VM="1" Keyword="ShowPatientDemographicsFlag" Name="Show Patient Demographics Flag"
+(0072,0716) VERS="4" VR="CS" VM="1" Keyword="ShowAcquisitionTechniquesFlag" Name="Show Acquisition Techniques Flag"
+(0072,0717) VERS="4" VR="CS" VM="1" Keyword="DisplaySetHorizontalJustification" Name="Display Set Horizontal Justification "
+(0072,0718) VERS="4" VR="CS" VM="1" Keyword="DisplaySetVerticalJustification" Name="Display Set Vertical Justification"
+(0074,0120) VERS="4" VR="FD" VM="1" Keyword="ContinuationStartMeterset" Name="Continuation Start Meterset"
+(0074,0121) VERS="4" VR="FD" VM="1" Keyword="ContinuationEndMeterset" Name="Continuation End Meterset"
+(0074,1000) VERS="4" VR="CS" VM="1" Keyword="ProcedureStepState" Name="Procedure Step State"
+(0074,1002) VERS="4" VR="SQ" VM="1" Keyword="ProcedureStepProgressInformationSequence" Name="Procedure Step Progress Information Sequence"
+(0074,1004) VERS="4" VR="DS" VM="1" Keyword="ProcedureStepProgress" Name="Procedure Step Progress"
+(0074,1006) VERS="4" VR="ST" VM="1" Keyword="ProcedureStepProgressDescription" Name="Procedure Step Progress Description"
+(0074,1008) VERS="4" VR="SQ" VM="1" Keyword="ProcedureStepCommunicationsURISequence" Name="Procedure Step Communications URI Sequence"
+(0074,100a) VERS="4" VR="ST" VM="1" Keyword="ContactURI" Name="Contact URI"
+(0074,100c) VERS="4" VR="LO" VM="1" Keyword="ContactDisplayName" Name="Contact Display Name"
+(0074,100e) VERS="4" VR="SQ" VM="1" Keyword="ProcedureStepDiscontinuationReasonCodeSequence" Name="Procedure Step Discontinuation Reason Code Sequence"
+(0074,1020) VERS="4" VR="SQ" VM="1" Keyword="BeamTaskSequence" Name="Beam Task Sequence"
+(0074,1022) VERS="4" VR="CS" VM="1" Keyword="BeamTaskType" Name="Beam Task Type"
+(0074,1024) VERS="4RET" VR="IS" VM="1" Keyword="BeamOrderIndexTrial" Name="Beam Order Index (Trial)"
+(0074,1026) VERS="4" VR="FD" VM="1" Keyword="TableTopVerticalAdjustedPosition" Name="Table Top Vertical Adjusted Position"
+(0074,1027) VERS="4" VR="FD" VM="1" Keyword="TableTopLongitudinalAdjustedPosition" Name="Table Top Longitudinal Adjusted Position"
+(0074,1028) VERS="4" VR="FD" VM="1" Keyword="TableTopLateralAdjustedPosition" Name="Table Top Lateral Adjusted Position"
+(0074,102A) VERS="4" VR="FD" VM="1" Keyword="PatientSupportAdjustedAngle" Name="Patient Support Adjusted Angle"
+(0074,102B) VERS="4" VR="FD" VM="1" Keyword="TableTopEccentricAdjustedAngle" Name="Table Top Eccentric Adjusted Angle"
+(0074,102C) VERS="4" VR="FD" VM="1" Keyword="TableTopPitchAdjustedAngle" Name="Table Top Pitch Adjusted Angle"
+(0074,102D) VERS="4" VR="FD" VM="1" Keyword="TableTopRollAdjustedAngle" Name="Table Top Roll Adjusted Angle"
+(0074,1030) VERS="4" VR="SQ" VM="1" Keyword="DeliveryVerificationImageSequence" Name="Delivery Verification Image Sequence"
+(0074,1032) VERS="4" VR="CS" VM="1" Keyword="VerificationImageTiming" Name="Verification Image Timing"
+(0074,1034) VERS="4" VR="CS" VM="1" Keyword="DoubleExposureFlag" Name="Double Exposure Flag"
+(0074,1036) VERS="4" VR="CS" VM="1" Keyword="DoubleExposureOrdering" Name="Double Exposure Ordering"
+(0074,1038) VERS="4RET" VR="DS" VM="1" Keyword="DoubleExposureMetersetTrial" Name="Double Exposure Meterset (Trial)"
+(0074,103A) VERS="4RET" VR="DS" VM="4" Keyword="DoubleExposureFieldDeltaTrial" Name="Double Exposure Field Delta (Trial)"
+(0074,1040) VERS="4" VR="SQ" VM="1" Keyword="RelatedReferenceRTImageSequence" Name="Related Reference RT Image Sequence"
+(0074,1042) VERS="4" VR="SQ" VM="1" Keyword="GeneralMachineVerificationSequence" Name="General Machine Verification Sequence"
+(0074,1044) VERS="4" VR="SQ" VM="1" Keyword="ConventionalMachineVerificationSequence" Name="Conventional Machine Verification Sequence"
+(0074,1046) VERS="4" VR="SQ" VM="1" Keyword="IonMachineVerificationSequence" Name="Ion Machine Verification Sequence"
+(0074,1048) VERS="4" VR="SQ" VM="1" Keyword="FailedAttributesSequence" Name="Failed Attributes Sequence"
+(0074,104A) VERS="4" VR="SQ" VM="1" Keyword="OverriddenAttributesSequence" Name="Overridden Attributes Sequence"
+(0074,104C) VERS="4" VR="SQ" VM="1" Keyword="ConventionalControlPointVerificationSequence" Name="Conventional Control Point Verification Sequence"
+(0074,104E) VERS="4" VR="SQ" VM="1" Keyword="IonControlPointVerificationSequence" Name="Ion Control Point Verification Sequence"
+(0074,1050) VERS="4" VR="SQ" VM="1" Keyword="AttributeOccurrenceSequence" Name="Attribute Occurrence Sequence"
+(0074,1052) VERS="4" VR="AT" VM="1" Keyword="AttributeOccurrencePointer" Name="Attribute Occurrence Pointer"
+(0074,1054) VERS="4" VR="UL" VM="1" Keyword="AttributeItemSelector" Name="Attribute Item Selector"
+(0074,1056) VERS="4" VR="LO" VM="1" Keyword="AttributeOccurrencePrivateCreator" Name="Attribute Occurrence Private Creator"
+(0074,1057) VERS="4" VR="IS" VM="1-n" Keyword="SelectorSequencePointerItems" Name="Selector Sequence Pointer Items"
+(0074,1200) VERS="4" VR="CS" VM="1" Keyword="ScheduledProcedureStepPriority" Name="Scheduled Procedure Step Priority"
+(0074,1202) VERS="4" VR="LO" VM="1" Keyword="WorklistLabel" Name="Worklist Label"
+(0074,1204) VERS="4" VR="LO" VM="1" Keyword="ProcedureStepLabel" Name="Procedure Step Label"
+(0074,1210) VERS="4" VR="SQ" VM="1" Keyword="ScheduledProcessingParametersSequence" Name="Scheduled Processing Parameters Sequence"
+(0074,1212) VERS="4" VR="SQ" VM="1" Keyword="PerformedProcessingParametersSequence" Name="Performed Processing Parameters Sequence"
+(0074,1216) VERS="4" VR="SQ" VM="1" Keyword="UnifiedProcedureStepPerformedProcedureSequence" Name="Unified Procedure Step Performed Procedure Sequence"
+(0074,1220) VERS="4RET" VR="SQ" VM="1" Keyword="RelatedProcedureStepSequence" Name="Related Procedure Step Sequence"
+(0074,1222) VERS="4RET" VR="LO" VM="1" Keyword="ProcedureStepRelationshipType" Name="Procedure Step Relationship Type"
+(0074,1224) VERS="4" VR="SQ" VM="1" Keyword="ReplacedProcedureStepSequence" Name="Replaced Procedure Step Sequence"
+(0074,1230) VERS="4" VR="LO" VM="1" Keyword="DeletionLock" Name="Deletion Lock"
+(0074,1234) VERS="4" VR="AE" VM="1" Keyword="ReceivingAE" Name="Receiving AE"
+(0074,1236) VERS="4" VR="AE" VM="1" Keyword="RequestingAE" Name="Requesting AE"
+(0074,1238) VERS="4" VR="LT" VM="1" Keyword="ReasonForCancellation" Name="Reason for Cancellation"
+(0074,1242) VERS="4" VR="CS" VM="1" Keyword="SCPStatus" Name="SCP Status"
+(0074,1244) VERS="4" VR="CS" VM="1" Keyword="SubscriptionListStatus" Name="Subscription List Status"
+(0074,1246) VERS="4" VR="CS" VM="1" Keyword="UnifiedProcedureStepListStatus" Name="Unified Procedure Step List Status"
+(0074,1324) VERS="4" VR="UL" VM="1" Keyword="BeamOrderIndex" Name="Beam Order Index"
+(0074,1338) VERS="4" VR="FD" VM="1" Keyword="DoubleExposureMeterset" Name="Double Exposure Meterset"
+(0074,133A) VERS="4" VR="FD" VM="4" Keyword="DoubleExposureFieldDelta" Name="Double Exposure Field Delta"
+(0076,0001) VERS="4" VR="LO" VM="1" Keyword="ImplantAssemblyTemplateName" Name="Implant Assembly Template Name"
+(0076,0003) VERS="4" VR="LO" VM="1" Keyword="ImplantAssemblyTemplateIssuer" Name="Implant Assembly Template Issuer"
+(0076,0006) VERS="4" VR="LO" VM="1" Keyword="ImplantAssemblyTemplateVersion" Name="Implant Assembly Template Version"
+(0076,0008) VERS="4" VR="SQ" VM="1" Keyword="ReplacedImplantAssemblyTemplateSequence" Name="Replaced Implant Assembly Template Sequence "
+(0076,000A) VERS="4" VR="CS" VM="1" Keyword="ImplantAssemblyTemplateType" Name="Implant Assembly Template Type"
+(0076,000C) VERS="4" VR="SQ" VM="1" Keyword="OriginalImplantAssemblyTemplateSequence" Name="Original Implant Assembly Template Sequence "
+(0076,000E) VERS="4" VR="SQ" VM="1" Keyword="DerivationImplantAssemblyTemplateSequence" Name="Derivation Implant Assembly Template Sequence "
+(0076,0010) VERS="4" VR="SQ" VM="1" Keyword="ImplantAssemblyTemplateTargetAnatomySequence" Name="Implant Assembly Template Target Anatomy Sequence"
+(0076,0020) VERS="4" VR="SQ" VM="1" Keyword="ProcedureTypeCodeSequence" Name="Procedure Type Code Sequence"
+(0076,0030) VERS="4" VR="LO" VM="1" Keyword="SurgicalTechnique" Name="Surgical Technique "
+(0076,0032) VERS="4" VR="SQ" VM="1" Keyword="ComponentTypesSequence" Name="Component Types Sequence"
+(0076,0034) VERS="4" VR="CS" VM="1" Keyword="ComponentTypeCodeSequence" Name="Component Type Code Sequence"
+(0076,0036) VERS="4" VR="CS" VM="1" Keyword="ExclusiveComponentType" Name="Exclusive Component Type"
+(0076,0038) VERS="4" VR="CS" VM="1" Keyword="MandatoryComponentType" Name="Mandatory Component Type"
+(0076,0040) VERS="4" VR="SQ" VM="1" Keyword="ComponentSequence" Name="Component Sequence"
+(0076,0055) VERS="4" VR="US" VM="1" Keyword="ComponentID" Name="Component ID"
+(0076,0060) VERS="4" VR="SQ" VM="1" Keyword="ComponentAssemblySequence" Name="Component Assembly Sequence"
+(0076,0070) VERS="4" VR="US" VM="1" Keyword="Component1ReferencedID" Name="Component 1 Referenced ID"
+(0076,0080) VERS="4" VR="US" VM="1" Keyword="Component1ReferencedMatingFeatureSetID" Name="Component 1 Referenced Mating Feature Set ID"
+(0076,0090) VERS="4" VR="US" VM="1" Keyword="Component1ReferencedMatingFeatureID" Name="Component 1 Referenced Mating Feature ID"
+(0076,00A0) VERS="4" VR="US" VM="1" Keyword="Component2ReferencedID" Name="Component 2 Referenced ID"
+(0076,00B0) VERS="4" VR="US" VM="1" Keyword="Component2ReferencedMatingFeatureSetID" Name="Component 2 Referenced Mating Feature Set ID"
+(0076,00C0) VERS="4" VR="US" VM="1" Keyword="Component2ReferencedMatingFeatureID" Name="Component 2 Referenced Mating Feature ID "
+(0078,0001) VERS="4" VR="LO" VM="1" Keyword="ImplantTemplateGroupName" Name="Implant Template Group Name"
+(0078,0010) VERS="4" VR="ST" VM="1" Keyword="ImplantTemplateGroupDescription" Name="Implant Template Group Description"
+(0078,0020) VERS="4" VR="LO" VM="1" Keyword="ImplantTemplateGroupIssuer" Name="Implant Template Group Issuer"
+(0078,0024) VERS="4" VR="LO" VM="1" Keyword="ImplantTemplateGroupVersion" Name="Implant Template Group Version"
+(0078,0026) VERS="4" VR="SQ" VM="1" Keyword="ReplacedImplantTemplateGroupSequence" Name="Replaced Implant Template Group Sequence "
+(0078,0028) VERS="4" VR="SQ" VM="1" Keyword="ImplantTemplateGroupTargetAnatomySequence" Name="Implant Template Group Target Anatomy Sequence"
+(0078,002A) VERS="4" VR="SQ" VM="1" Keyword="ImplantTemplateGroupMembersSequence" Name="Implant Template Group Members Sequence"
+(0078,002E) VERS="4" VR="US" VM="1" Keyword="ImplantTemplateGroupMemberID" Name="Implant Template Group Member ID"
+(0078,0050) VERS="4" VR="FD" VM="3" Keyword="ThreeDImplantTemplateGroupMemberMatchingPoint" Name="3D Implant Template Group Member Matching Point"
+(0078,0060) VERS="4" VR="FD" VM="9" Keyword="ThreeDImplantTemplateGroupMemberMatchingAxes" Name="3D Implant Template Group Member Matching Axes"
+(0078,0070) VERS="4" VR="SQ" VM="1" Keyword="ImplantTemplateGroupMemberMatching2DCoordinatesSequence" Name="Implant Template Group Member Matching 2D Coordinates Sequence"
+(0078,0090) VERS="4" VR="FD" VM="2" Keyword="TwoDImplantTemplateGroupMemberMatchingPoint" Name="2D Implant Template Group Member Matching Point "
+(0078,00A0) VERS="4" VR="FD" VM="4" Keyword="TwoDImplantTemplateGroupMemberMatchingAxes" Name="2D Implant Template Group Member Matching Axes"
+(0078,00B0) VERS="4" VR="SQ" VM="1" Keyword="ImplantTemplateGroupVariationDimensionSequence" Name="Implant Template Group Variation Dimension Sequence"
+(0078,00B2) VERS="4" VR="LO" VM="1" Keyword="ImplantTemplateGroupVariationDimensionName" Name="Implant Template Group Variation Dimension Name"
+(0078,00B4) VERS="4" VR="SQ" VM="1" Keyword="ImplantTemplateGroupVariationDimensionRankSequence" Name="Implant Template Group Variation Dimension Rank Sequence"
+(0078,00B6) VERS="4" VR="US" VM="1" Keyword="ReferencedImplantTemplateGroupMemberID" Name="Referenced Implant Template Group Member ID"
+(0078,00B8) VERS="4" VR="US" VM="1" Keyword="ImplantTemplateGroupVariationDimensionRank" Name="Implant Template Group Variation Dimension Rank"
+(0088,0000) VERS="3" VR="UL" VM="1" Keyword="StorageGroupLength" Name="Storage Group Length"
+(0088,0130) VERS="4" VR="SH" VM="1" Keyword="StorageMediaFileSetID" Name="Storage Media File-set ID"
+(0088,0140) VERS="4" VR="UI" VM="1" Keyword="StorageMediaFileSetUID" Name="Storage Media File-set UID"
+(0088,0200) VERS="4" VR="SQ" VM="1" Keyword="IconImageSequence" Name="Icon Image Sequence"
+(0088,0904) VERS="4RET" VR="LO" VM="1" Keyword="TopicTitle" Name="Topic Title"
+(0088,0906) VERS="4RET" VR="ST" VM="1" Keyword="TopicSubject" Name="Topic Subject"
+(0088,0910) VERS="4RET" VR="LO" VM="1" Keyword="TopicAuthor" Name="Topic Author"
+(0088,0912) VERS="4RET" VR="LO" VM="1-32" Keyword="TopicKeywords" Name="Topic Keywords"
+(0100,0410) VERS="4" VR="CS" VM="1" Keyword="SOPInstanceStatus" Name="SOP Instance Status"
+(0100,0420) VERS="4" VR="DT" VM="1" Keyword="SOPAuthorizationDateTime" Name="SOP Authorization DateTime"
+(0100,0424) VERS="4" VR="LT" VM="1" Keyword="SOPAuthorizationComment" Name="SOP Authorization Comment"
+(0100,0426) VERS="4" VR="LO" VM="1" Keyword="AuthorizationEquipmentCertificationNumber" Name="Authorization Equipment Certification Number"
+(0400,0005) VERS="4" VR="US" VM="1" Keyword="MACIDNumber" Name="MAC ID Number"
+(0400,0010) VERS="4" VR="UI" VM="1" Keyword="MACCalculationTransferSyntaxUID" Name="MAC Calculation Transfer Syntax UID"
+(0400,0015) VERS="4" VR="CS" VM="1" Keyword="MACAlgorithm" Name="MAC Algorithm"
+(0400,0020) VERS="4" VR="AT" VM="1-n" Keyword="DataElementsSigned" Name="Data Elements Signed"
+(0400,0100) VERS="4" VR="UI" VM="1" Keyword="DigitalSignatureUID" Name="Digital Signature UID"
+(0400,0105) VERS="4" VR="DT" VM="1" Keyword="DigitalSignatureDateTime" Name="Digital Signature DateTime"
+(0400,0110) VERS="4" VR="CS" VM="1" Keyword="CertificateType" Name="Certificate Type"
+(0400,0115) VERS="4" VR="OB" VM="1" Keyword="CertificateOfSigner" Name="Certificate of Signer"
+(0400,0120) VERS="4" VR="OB" VM="1" Keyword="Signature" Name="Signature"
+(0400,0305) VERS="4" VR="CS" VM="1" Keyword="CertifiedTimestampType" Name="Certified Timestamp Type"
+(0400,0310) VERS="4" VR="OB" VM="1" Keyword="CertifiedTimestamp" Name="Certified Timestamp"
+(0400,0401) VERS="4" VR="SQ" VM="1" Keyword="DigitalSignaturePurposeCodeSequence" Name="Digital Signature Purpose Code Sequence"
+(0400,0402) VERS="4" VR="SQ" VM="1" Keyword="ReferencedDigitalSignatureSequence" Name="Referenced Digital Signature Sequence"
+(0400,0403) VERS="4" VR="SQ" VM="1" Keyword="ReferencedSOPInstanceMACSequence" Name="Referenced SOP Instance MAC Sequence"
+(0400,0404) VERS="4" VR="OB" VM="1" Keyword="MAC" Name="MAC"
+(0400,0500) VERS="4" VR="SQ" VM="1" Keyword="EncryptedAttributesSequence" Name="Encrypted Attributes Sequence"
+(0400,0510) VERS="4" VR="UI" VM="1" Keyword="EncryptedContentTransferSyntaxUID" Name="Encrypted Content Transfer Syntax UID"
+(0400,0520) VERS="4" VR="OB" VM="1" Keyword="EncryptedContent" Name="Encrypted Content"
+(0400,0550) VERS="4" VR="SQ" VM="1" Keyword="ModifiedAttributesSequence" Name="Modified Attributes Sequence"
+(0400,0561) VERS="4" VR="SQ" VM="1" Keyword="OriginalAttributesSequence" Name="Original Attributes Sequence"
+(0400,0562) VERS="4" VR="DT" VM="1" Keyword="AttributeModificationDateTime" Name="Attribute Modification DateTime"
+(0400,0563) VERS="4" VR="LO" VM="1" Keyword="ModifyingSystem" Name="Modifying System"
+(0400,0564) VERS="4" VR="LO" VM="1" Keyword="SourceOfPreviousValues" Name="Source of Previous Values"
+(0400,0565) VERS="4" VR="CS" VM="1" Keyword="ReasonForTheAttributeModification" Name="Reason for the Attribute Modification"
+(07A1,0010) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A1,102A) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A1,1040) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A1,1043) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A1,1050) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A1,1070) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A1,1085) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A3,0010) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A3,1001) VERS="3" VR="SH" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A3,1003) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A3,1014) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A3,1017) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A3,1034) VERS="3" VR="TM" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A3,1055) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A3,1099) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(07A3,109C) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(1000,0000) VERS="2C" VR="UL" VM="1" Keyword="CodeTableGroupLength" Name="Code Table Group Length"
+(1000,xxx0) VERS="4RET" VR="US" VM="3" Keyword="EscapeTriplet" Name="Escape Triplet"
+(1000,xxx1) VERS="4RET" VR="US" VM="3" Keyword="RunLengthTriplet" Name="Run Length Triplet"
+(1000,xxx2) VERS="4RET" VR="US" VM="1" Keyword="HuffmanTableSize" Name="Huffman Table Size"
+(1000,xxx3) VERS="4RET" VR="US" VM="3" Keyword="HuffmanTableTriplet" Name="Huffman Table Triplet"
+(1000,xxx4) VERS="4RET" VR="US" VM="1" Keyword="ShiftTableSize" Name="Shift Table Size"
+(1000,xxx5) VERS="4RET" VR="US" VM="3" Keyword="ShiftTableTriplet" Name="Shift Table Triplet"
+(1010,0000) VERS="2C" VR="UL" VM="1" Keyword="ZonalMapGroupLength" Name="Zonal Map Group Length"
+(1010,xxxx) VERS="4RET" VR="US" VM="1-n" Keyword="ZonalMap" Name="Zonal Map"
+(2000,0000) VERS="3" VR="UL" VM="1" Keyword="FilmSessionGroupLength" Name="Film Session Group Length"
+(2000,0010) VERS="4" VR="IS" VM="1" Keyword="NumberOfCopies" Name="Number of Copies"
+(2000,001E) VERS="4" VR="SQ" VM="1" Keyword="PrinterConfigurationSequence" Name="Printer Configuration Sequence"
+(2000,0020) VERS="4" VR="CS" VM="1" Keyword="PrintPriority" Name="Print Priority"
+(2000,0030) VERS="4" VR="CS" VM="1" Keyword="MediumType" Name="Medium Type"
+(2000,0040) VERS="4" VR="CS" VM="1" Keyword="FilmDestination" Name="Film Destination"
+(2000,0050) VERS="4" VR="LO" VM="1" Keyword="FilmSessionLabel" Name="Film Session Label"
+(2000,0060) VERS="4" VR="IS" VM="1" Keyword="MemoryAllocation" Name="Memory Allocation"
+(2000,0061) VERS="4" VR="IS" VM="1" Keyword="MaximumMemoryAllocation" Name="Maximum Memory Allocation"
+(2000,0062) VERS="4RET" VR="CS" VM="1" Keyword="ColorImagePrintingFlag" Name="Color Image Printing Flag"
+(2000,0063) VERS="4RET" VR="CS" VM="1" Keyword="CollationFlag" Name="Collation Flag"
+(2000,0065) VERS="4RET" VR="CS" VM="1" Keyword="AnnotationFlag" Name="Annotation Flag"
+(2000,0067) VERS="4RET" VR="CS" VM="1" Keyword="ImageOverlayFlag" Name="Image Overlay Flag"
+(2000,0069) VERS="4RET" VR="CS" VM="1" Keyword="PresentationLUTFlag" Name="Presentation LUT Flag"
+(2000,006A) VERS="4RET" VR="CS" VM="1" Keyword="ImageBoxPresentationLUTFlag" Name="Image Box Presentation LUT Flag"
+(2000,00A0) VERS="4" VR="US" VM="1" Keyword="MemoryBitDepth" Name="Memory Bit Depth"
+(2000,00A1) VERS="4" VR="US" VM="1" Keyword="PrintingBitDepth" Name="Printing Bit Depth"
+(2000,00A2) VERS="4" VR="SQ" VM="1" Keyword="MediaInstalledSequence" Name="Media Installed Sequence"
+(2000,00A4) VERS="4" VR="SQ" VM="1" Keyword="OtherMediaAvailableSequence" Name="Other Media Available Sequence"
+(2000,00A8) VERS="4" VR="SQ" VM="1" Keyword="SupportedImageDisplayFormatsSequence" Name="Supported Image Display Formats Sequence"
+(2000,0500) VERS="4" VR="SQ" VM="1" Keyword="ReferencedFilmBoxSequence" Name="Referenced Film Box Sequence"
+(2000,0510) VERS="4RET" VR="SQ" VM="1" Keyword="ReferencedStoredPrintSequence" Name="Referenced Stored Print Sequence"
+(2001,0000) VERS="3" VR="UL" VM="1" Keyword="GroupLength" Name="Group Length"
+(2001,0010) VERS="3" VR="LO" VM="1" Keyword="PrivateCreatorGroup2001" Name="Private Creator Group 2001"
+(2001,00e0) VERS="3" VR="LO" VM="1" Keyword="PrivateCreatorGroup2001" Name="Private Creator Group 2001"
+(2001,1001) VERS="3" VR="FL" VM="1" Keyword="ChemicalShift" Name="Chemical Shift"
+(2001,1002) VERS="3" VR="IS" VM="1" Keyword="ChemicalShiftNumberMR" Name="Chemical Shift Number MR"
+(2001,1003) VERS="3" VR="FL" VM="1" Keyword="DiffusionB-Factor" Name="Diffusion B-Factor"
+(2001,1004) VERS="3" VR="CS" VM="1" Keyword="DiffusionDirection" Name="Diffusion Direction"
+(2001,1006) VERS="3" VR="CS" VM="1" Keyword="ImageEnhanced" Name="Image Enhanced"
+(2001,1007) VERS="3" VR="CS" VM="1" Keyword="ImageTypeEDES" Name="Image Type ED ES"
+(2001,1008) VERS="3" VR="IS" VM="1" Keyword="PhaseNumber" Name="Phase Number"
+(2001,1009) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,100a) VERS="3" VR="IS" VM="1" Keyword="SliceNumberMR" Name="Slice Number MR"
+(2001,100b) VERS="3" VR="CS" VM="1" Keyword="SliceOrientation" Name="Slice Orientation"
+(2001,100C) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,100E) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,100F) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,1010) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,1011) VERS="3" VR="FL" VM="1" Keyword="DiffusionEchoTime" Name="Diffusion Echo Time"
+(2001,1012) VERS="3" VR="CS" VM="1" Keyword="DynamicSeries" Name="Dynamic Series"
+(2001,1013) VERS="3" VR="SL" VM="1" Keyword="EPIFactor" Name="EPI Factor"
+(2001,1014) VERS="3" VR="SL" VM="1" Keyword="NumberOfEchoes" Name="Number of Echoes"
+(2001,1015) VERS="3" VR="SS" VM="1" Keyword="NumberOfLocations" Name="Number of Locations"
+(2001,1016) VERS="3" VR="SS" VM="1" Keyword="NumberOfPCDirections" Name="Number of PC Directions"
+(2001,1017) VERS="3" VR="SL" VM="1" Keyword="NumberOfPhasesMR" Name="Number of Phases MR"
+(2001,1018) VERS="3" VR="SL" VM="1" Keyword="NumberOfSlicesMR" Name="Number of Slices MR"
+(2001,1019) VERS="3" VR="CS" VM="1" Keyword="PartialMatrixScanned" Name="Partial Matrix Scanned"
+(2001,101a) VERS="3" VR="FL" VM="1-n" Keyword="PCVelocity" Name="PC Velocity"
+(2001,101b) VERS="3" VR="FL" VM="1" Keyword="PrepulseDelay" Name="Prepulse Delay"
+(2001,101c) VERS="3" VR="CS" VM="1" Keyword="PrepulseType" Name="Prepulse Type"
+(2001,101d) VERS="3" VR="IS" VM="1" Keyword="ReconstructionNumberMR" Name="Reconstruction Number MR"
+(2001,101f) VERS="3" VR="CS" VM="1" Keyword="RespirationSync" Name="Respiration Sync"
+(2001,1020) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,1021) VERS="3" VR="CS" VM="1" Keyword="SPIR" Name="SPIR"
+(2001,1022) VERS="3" VR="FL" VM="1" Keyword="WaterFatShift" Name="Water Fat Shift"
+(2001,1023) VERS="3" VR="DS" VM="1" Keyword="FlipAnglePhilips" Name="Flip Angle Philips"
+(2001,1024) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,1025) VERS="3" VR="SH" VM="1" Keyword="EchoTimeDisplayMR" Name="Echo Time Display MR"
+(2001,102d) VERS="3" VR="SS" VM="1" Keyword="StackNumberOfSlices" Name="Stack Number of Slices"
+(2001,1032) VERS="3" VR="FL" VM="1" Keyword="StackRadialAngle" Name="Stack Radial Angle"
+(2001,1033) VERS="3" VR="CS" VM="1" Keyword="StackRadialAxis" Name="Stack Radial Axis"
+(2001,1035) VERS="3" VR="SS" VM="1" Keyword="StackSliceNumber" Name="Stack Slice Number"
+(2001,1036) VERS="3" VR="CS" VM="1" Keyword="StackType" Name="Stack Type"
+(2001,103f) VERS="3" VR="CS" VM="1" Keyword="ZoomMode" Name="Zoom Mode"
+(2001,105f) VERS="3" VR="SQ" VM="1" Keyword="StackSequence" Name="Stack Sequence"
+(2001,1060) VERS="3" VR="SL" VM="1" Keyword="NumberOfStacks" Name="Number of Stacks"
+(2001,1061) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,1062) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,1063) VERS="3" VR="CS" VM="1" Keyword="ExaminationSource" Name="Examination Source"
+(2001,107b) VERS="3" VR="IS" VM="1" Keyword="AcquisitionNumber" Name="Acquisition Number"
+(2001,1081) VERS="3" VR="IS" VM="1" Keyword="NumberOfDynamicScans" Name="Number of Dynamic Scans"
+(2001,1082) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,1083) VERS="3" VR="DS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,1084) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,1085) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,1086) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,1087) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,1088) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,1089) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,108A) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,108B) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,10F1) VERS="3" VR="OB" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2001,e001) VERS="3" VR="FL" VM="1" Keyword="ChemicalShift" Name="Chemical Shift"
+(2001,e002) VERS="3" VR="IS" VM="1" Keyword="ChemicalShiftNumberMR" Name="Chemical Shift Number MR"
+(2001,e003) VERS="3" VR="FL" VM="1" Keyword="DiffusionB-Factor" Name="Diffusion B-Factor"
+(2001,e004) VERS="3" VR="CS" VM="1" Keyword="DiffusionDirection" Name="Diffusion Direction"
+(2001,e006) VERS="3" VR="CS" VM="1" Keyword="ImageEnhanced" Name="Image Enhanced"
+(2001,e007) VERS="3" VR="CS" VM="1" Keyword="ImageTypeEDES" Name="Image Type ED ES"
+(2001,e008) VERS="3" VR="IS" VM="1" Keyword="PhaseNumber" Name="Phase Number"
+(2001,e00a) VERS="3" VR="IS" VM="1" Keyword="SliceNumberMR" Name="Slice Number MR"
+(2001,e00b) VERS="3" VR="CS" VM="1" Keyword="SliceOrientation" Name="Slice Orientation"
+(2001,e011) VERS="3" VR="FL" VM="1" Keyword="DiffusionEchoTime" Name="Diffusion Echo Time"
+(2001,e012) VERS="3" VR="CS" VM="1" Keyword="DynamicSeries" Name="Dynamic Series"
+(2001,e013) VERS="3" VR="SL" VM="1" Keyword="EPIFactor" Name="EPI Factor"
+(2001,e014) VERS="3" VR="SL" VM="1" Keyword="NumberOfEchoes" Name="Number of Echoes"
+(2001,e015) VERS="3" VR="SS" VM="1" Keyword="NumberOfLocations" Name="Number of Locations"
+(2001,e016) VERS="3" VR="SS" VM="1" Keyword="NumberOfPCDirections" Name="Number of PC Directions"
+(2001,e017) VERS="3" VR="SL" VM="1" Keyword="NumberOfPhasesMR" Name="Number of Phases MR"
+(2001,e018) VERS="3" VR="SL" VM="1" Keyword="NumberOfSlicesMR" Name="Number of Slices MR"
+(2001,e019) VERS="3" VR="CS" VM="1" Keyword="PartialMatrixScanned" Name="Partial Matrix Scanned"
+(2001,e01a) VERS="3" VR="FL" VM="1-n" Keyword="PCVelocity" Name="PC Velocity"
+(2001,e01b) VERS="3" VR="FL" VM="1" Keyword="PrepulseDelay" Name="Prepulse Delay"
+(2001,e01c) VERS="3" VR="CS" VM="1" Keyword="PrepulseType" Name="Prepulse Type"
+(2001,e01d) VERS="3" VR="IS" VM="1" Keyword="ReconstructionNumberMR" Name="Reconstruction Number MR"
+(2001,e01f) VERS="3" VR="CS" VM="1" Keyword="RespirationSync" Name="Respiration Sync"
+(2001,e021) VERS="3" VR="CS" VM="1" Keyword="SPIR" Name="SPIR"
+(2001,e022) VERS="3" VR="FL" VM="1" Keyword="WaterFatShift" Name="Water Fat Shift"
+(2001,e023) VERS="3" VR="DS" VM="1" Keyword="FlipAnglePhilips" Name="Flip Angle Philips"
+(2001,e025) VERS="3" VR="SH" VM="1" Keyword="EchoTimeDisplayMR" Name="Echo Time Display MR"
+(2001,e02d) VERS="3" VR="SS" VM="1" Keyword="StackNumberOfSlices" Name="Stack Number of Slices"
+(2001,e032) VERS="3" VR="FL" VM="1" Keyword="StackRadialAngle" Name="Stack Radial Angle"
+(2001,e033) VERS="3" VR="CS" VM="1" Keyword="StackRadialAxis" Name="Stack Radial Axis"
+(2001,e035) VERS="3" VR="SS" VM="1" Keyword="StackSliceNumber" Name="Stack Slice Number"
+(2001,e036) VERS="3" VR="CS" VM="1" Keyword="StackType" Name="Stack Type"
+(2001,e03f) VERS="3" VR="CS" VM="1" Keyword="ZoomMode" Name="Zoom Mode"
+(2001,e05f) VERS="3" VR="SQ" VM="1" Keyword="StackSequence" Name="Stack Sequence"
+(2001,e060) VERS="3" VR="SL" VM="1" Keyword="NumberOfStacks" Name="Number of Stacks"
+(2001,e063) VERS="3" VR="CS" VM="1" Keyword="ExaminationSource" Name="Examination Source"
+(2001,e07b) VERS="3" VR="IS" VM="1" Keyword="AcquisitionNumber" Name="Acquisition Number"
+(2001,e081) VERS="3" VR="IS" VM="1" Keyword="NumberOfDynamicScans" Name="Number of Dynamic Scans"
+(2005,0000) VERS="3" VR="UL" VM="1" Keyword="GroupLength" Name="Group Length"
+(2005,0010) VERS="3" VR="LO" VM="1" Keyword="PrivateCreatorGroup2005" Name="Private Creator Group 2005"
+(2005,0011) VERS="3" VR="LO" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,0012) VERS="3" VR="LO" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,0013) VERS="3" VR="LO" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,0014) VERS="3" VR="LO" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1000) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1001) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1002) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1004) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1005) VERS="3" VR="CS" VM="1" Keyword="SynergyReconstructionType" Name="Synergy Reconstruction Type"
+(2005,1008) VERS="3" VR="SL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1009) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,100A) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,100B) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,100C) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,100D) VERS="3" VR="FL" VM="1" Keyword="ScaleIntercept" Name="Scale Intercept"
+(2005,100E) VERS="3" VR="FL" VM="1" Keyword="ScaleSlope" Name="Scale Slope"
+(2005,100F) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1010) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1011) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1012) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1013) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1014) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1015) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1016) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1017) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1019) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,101A) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,101B) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,101C) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,101D) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,101E) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,101F) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1020) VERS="3" VR="SL" VM="1" Keyword="NumberOfChemicalShifts" Name="Number of Chemical Shifts"
+(2005,1021) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1022) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1023) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1025) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1026) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1027) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1028) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1029) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,102A) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,102B) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,102C) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,102D) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,102E) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,102F) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1030) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1031) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1033) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1034) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1035) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1036) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1037) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1038) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1039) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,103B) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,103C) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,103D) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,103E) VERS="3" VR="OB" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,105F) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1060) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1061) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1063) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,106E) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,106F) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1080) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1083) VERS="3" VR="SQ" VM="1" Keyword="TemporarySQ1" Name="Temporary SQ 1"
+(2005,1084) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1085) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1086) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,109E) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,10A0) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,10a1) VERS="3" VR="CS" VM="1" Keyword="SyncraScanType" Name="Syncra Scan Type"
+(2005,10A2) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,10A8) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,10A9) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,10B0) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,10B1) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,10B2) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,10C0) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1199) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1200) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1201) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1213) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1245) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1249) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1251) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1252) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1253) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1325) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1326) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1327) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1328) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1329) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1330) VERS="3" VR="LO" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1331) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1333) VERS="3" VR="OB" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1334) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1335) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1336) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1337) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1338) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1339) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1340) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1341) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1342) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1343) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1344) VERS="3" VR="OB" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1345) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1346) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1347) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1348) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1349) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1350) VERS="3" VR="FD" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1351) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1352) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1355) VERS="3" VR="OB" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1356) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1357) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1359) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1360) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1361) VERS="3" VR="FD" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1362) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1363) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1364) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1370) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1371) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1381) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1382) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1391) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1392) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1393) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1396) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1397) VERS="3" VR="LO" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1398) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1399) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1400) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1401) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1402) VERS="3" VR="SQ" VM="1" Keyword="TemporarySQ2" Name="Temporary SQ 2"
+(2005,1403) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1406) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1409) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,140A) VERS="3" VR="DS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,140B) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,140E) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,140F) VERS="3" VR="OB" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1412) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1413) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1414) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1415) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1416) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1418) VERS="3" VR="LO" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1419) VERS="3" VR="LO" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,141B) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,141C) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,141D) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1426) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1428) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,142A) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,142B) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,142C) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,142D) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1432) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1435) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,143A) VERS="3" VR="LO" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,143B) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,143F) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1440) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1441) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1442) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1443) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1444) VERS="3" VR="IS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1445) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1447) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,144A) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,144B) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,144C) VERS="3" VR="UL" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,144D) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,144E) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,144F) VERS="3" VR="CS" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2005,1450) VERS="3" VR="US" VM="1" Keyword="Unknown" Name="Unknown tag"
+(2010,0000) VERS="3" VR="UL" VM="1" Keyword="FilmBoxGroupLength" Name="Film Box Group Length"
+(2010,0010) VERS="4" VR="ST" VM="1" Keyword="ImageDisplayFormat" Name="Image Display Format"
+(2010,0030) VERS="4" VR="CS" VM="1" Keyword="AnnotationDisplayFormatID" Name="Annotation Display Format ID"
+(2010,0040) VERS="4" VR="CS" VM="1" Keyword="FilmOrientation" Name="Film Orientation"
+(2010,0050) VERS="4" VR="CS" VM="1" Keyword="FilmSizeID" Name="Film Size ID"
+(2010,0052) VERS="4" VR="CS" VM="1" Keyword="PrinterResolutionID" Name="Printer Resolution ID"
+(2010,0054) VERS="4" VR="CS" VM="1" Keyword="DefaultPrinterResolutionID" Name="Default Printer Resolution ID"
+(2010,0060) VERS="4" VR="CS" VM="1" Keyword="MagnificationType" Name="Magnification Type"
+(2010,0080) VERS="4" VR="CS" VM="1" Keyword="SmoothingType" Name="Smoothing Type "
+(2010,00A6) VERS="4" VR="CS" VM="1" Keyword="DefaultMagnificationType" Name="Default Magnification Type"
+(2010,00A7) VERS="4" VR="CS" VM="1-n" Keyword="OtherMagnificationTypesAvailable" Name="Other Magnification Types Available"
+(2010,00A8) VERS="4" VR="CS" VM="1" Keyword="DefaultSmoothingType" Name="Default Smoothing Type"
+(2010,00A9) VERS="4" VR="CS" VM="1-n" Keyword="OtherSmoothingTypesAvailable" Name="Other Smoothing Types Available"
+(2010,0100) VERS="4" VR="CS" VM="1" Keyword="BorderDensity" Name="Border Density"
+(2010,0110) VERS="4" VR="CS" VM="1" Keyword="EmptyImageDensity" Name="Empty Image Density"
+(2010,0120) VERS="4" VR="US" VM="1" Keyword="MinDensity" Name="Min Density"
+(2010,0130) VERS="4" VR="US" VM="1" Keyword="MaxDensity" Name="Max Density"
+(2010,0140) VERS="4" VR="CS" VM="1" Keyword="Trim" Name="Trim"
+(2010,0150) VERS="4" VR="ST" VM="1" Keyword="ConfigurationInformation" Name="Configuration Information"
+(2010,0152) VERS="4" VR="LT" VM="1" Keyword="ConfigurationInformationDescription" Name="Configuration Information Description"
+(2010,0154) VERS="4" VR="IS" VM="1" Keyword="MaximumCollatedFilms" Name="Maximum Collated Films"
+(2010,015E) VERS="4" VR="US" VM="1" Keyword="Illumination" Name="Illumination"
+(2010,0160) VERS="4" VR="US" VM="1" Keyword="ReflectedAmbientLight" Name="Reflected Ambient Light"
+(2010,0376) VERS="4" VR="DS" VM="2" Keyword="PrinterPixelSpacing" Name="Printer Pixel Spacing"
+(2010,0500) VERS="4" VR="SQ" VM="1" Keyword="ReferencedFilmSessionSequence" Name="Referenced Film Session Sequence"
+(2010,0510) VERS="4" VR="SQ" VM="1" Keyword="ReferencedImageBoxSequence" Name="Referenced Image Box Sequence"
+(2010,0520) VERS="4" VR="SQ" VM="1" Keyword="ReferencedBasicAnnotationBoxSequence" Name="Referenced Basic Annotation Box Sequence"
+(2020,0000) VERS="3" VR="UL" VM="1" Keyword="ImageBoxGroupLength" Name="Image Box Group Length"
+(2020,0010) VERS="4" VR="US" VM="1" Keyword="ImageBoxPosition" Name="Image Box Position"
+(2020,0020) VERS="4" VR="CS" VM="1" Keyword="Polarity" Name="Polarity"
+(2020,0030) VERS="4" VR="DS" VM="1" Keyword="RequestedImageSize" Name="Requested Image Size"
+(2020,0040) VERS="4" VR="CS" VM="1" Keyword="RequestedDecimateCropBehavior" Name="Requested Decimate/Crop Behavior"
+(2020,0050) VERS="4" VR="CS" VM="1" Keyword="RequestedResolutionID" Name="Requested Resolution ID"
+(2020,00A0) VERS="4" VR="CS" VM="1" Keyword="RequestedImageSizeFlag" Name="Requested Image Size Flag"
+(2020,00A2) VERS="4" VR="CS" VM="1" Keyword="DecimateCropResult" Name="Decimate/Crop Result"
+(2020,0110) VERS="4" VR="SQ" VM="1" Keyword="BasicGrayscaleImageSequence" Name="Basic Grayscale Image Sequence"
+(2020,0111) VERS="4" VR="SQ" VM="1" Keyword="BasicColorImageSequence" Name="Basic Color Image Sequence"
+(2020,0130) VERS="4RET" VR="SQ" VM="1" Keyword="ReferencedImageOverlayBoxSequence" Name="Referenced Image Overlay Box Sequence"
+(2020,0140) VERS="4RET" VR="SQ" VM="1" Keyword="ReferencedVOILUTBoxSequence" Name="Referenced VOI LUT Box Sequence "
+(2030,0000) VERS="3" VR="UL" VM="1" Keyword="AnnotationGroupLength" Name="Annotation Group Length"
+(2030,0010) VERS="4" VR="US" VM="1" Keyword="AnnotationPosition" Name="Annotation Position"
+(2030,0020) VERS="4" VR="LO" VM="1" Keyword="TextString" Name="Text String"
+(2040,0000) VERS="3" VR="UL" VM="1" Keyword="OverlayBoxGroupLength" Name="Overlay Box Group Length"
+(2040,0010) VERS="4RET" VR="SQ" VM="1" Keyword="ReferencedOverlayPlaneSequence" Name="Referenced Overlay Plane Sequence"
+(2040,0011) VERS="4RET" VR="US" VM="1-99" Keyword="ReferencedOverlayPlaneGroups" Name="Referenced Overlay Plane Groups"
+(2040,0020) VERS="4RET" VR="SQ" VM="1" Keyword="OverlayPixelDataSequence" Name="Overlay Pixel Data Sequence"
+(2040,0060) VERS="4RET" VR="CS" VM="1" Keyword="OverlayMagnificationType" Name="Overlay Magnification Type"
+(2040,0070) VERS="4RET" VR="CS" VM="1" Keyword="OverlaySmoothingType" Name="Overlay Smoothing Type"
+(2040,0072) VERS="4RET" VR="CS" VM="1" Keyword="OverlayOrImageMagnification" Name="Overlay or Image Magnification"
+(2040,0074) VERS="4RET" VR="US" VM="1" Keyword="MagnifyToNumberOfColumns" Name="Magnify to Number of Columns"
+(2040,0080) VERS="4RET" VR="CS" VM="1" Keyword="OverlayForegroundDensity" Name="Overlay Foreground Density"
+(2040,0082) VERS="4RET" VR="CS" VM="1" Keyword="OverlayBackgroundDensity" Name="Overlay Background Density"
+(2040,0090) VERS="4RET" VR="CS" VM="1" Keyword="OverlayMode" Name="Overlay Mode"
+(2040,0100) VERS="4RET" VR="CS" VM="1" Keyword="ThresholdDensity" Name="Threshold Density"
+(2040,0500) VERS="4RET" VR="SQ" VM="1" Keyword="ReferencedImageBoxSequenceRetired" Name="Referenced Image Box Sequence (Retired)"
+(2050,0000) VERS="3" VR="UL" VM="1" Keyword="PresentationLUTGroupLength" Name="Presentation LUT Group Length"
+(2050,0010) VERS="4" VR="SQ" VM="1" Keyword="PresentationLUTSequence" Name="Presentation LUT Sequence"
+(2050,0020) VERS="4" VR="CS" VM="1" Keyword="PresentationLUTShape" Name="Presentation LUT Shape"
+(2050,0500) VERS="4" VR="SQ" VM="1" Keyword="ReferencedPresentationLUTSequence" Name="Referenced Presentation LUT Sequence"
+(2100,0000) VERS="3" VR="UL" VM="1" Keyword="PrintJobGroupLength" Name="Print Job Group Length"
+(2100,0010) VERS="4RET" VR="SH" VM="1" Keyword="PrintJobID" Name="Print Job ID"
+(2100,0020) VERS="4" VR="CS" VM="1" Keyword="ExecutionStatus" Name="Execution Status"
+(2100,0030) VERS="4" VR="CS" VM="1" Keyword="ExecutionStatusInfo" Name="Execution Status Info"
+(2100,0040) VERS="4" VR="DA" VM="1" Keyword="CreationDate" Name="Creation Date"
+(2100,0050) VERS="4" VR="TM" VM="1" Keyword="CreationTime" Name="Creation Time"
+(2100,0070) VERS="4" VR="AE" VM="1" Keyword="Originator" Name="Originator"
+(2100,0140) VERS="4RET" VR="AE" VM="1" Keyword="DestinationAE" Name="Destination AE"
+(2100,0160) VERS="4" VR="SH" VM="1" Keyword="OwnerID" Name="Owner ID"
+(2100,0170) VERS="4" VR="IS" VM="1" Keyword="NumberOfFilms" Name="Number of Films"
+(2100,0500) VERS="4RET" VR="SQ" VM="1" Keyword="ReferencedPrintJobSequencePullStoredPrint" Name="Referenced Print Job Sequence (Pull Stored Print)"
+(2110,0000) VERS="3" VR="UL" VM="1" Keyword="PrinterGroupLength" Name="PrinterGroup Length"
+(2110,0010) VERS="4" VR="CS" VM="1" Keyword="PrinterStatus" Name="Printer Status"
+(2110,0020) VERS="4" VR="CS" VM="1" Keyword="PrinterStatusInfo" Name="Printer Status Info"
+(2110,0030) VERS="4" VR="LO" VM="1" Keyword="PrinterName" Name="Printer Name"
+(2110,0099) VERS="4RET" VR="SH" VM="1" Keyword="PrintQueueID" Name="Print Queue ID"
+(2120,0000) VERS="3" VR="UL" VM="1" Keyword="QueueGroupLength" Name="Queue Group Length"
+(2120,0010) VERS="4RET" VR="CS" VM="1" Keyword="QueueStatus" Name="Queue Status"
+(2120,0050) VERS="4RET" VR="SQ" VM="1" Keyword="PrintJobDescriptionSequence" Name="Print Job Description Sequence"
+(2120,0070) VERS="4RET" VR="SQ" VM="1" Keyword="ReferencedPrintJobSequence" Name="Referenced Print Job Sequence"
+(2130,0000) VERS="3" VR="UL" VM="1" Keyword="PrintContentGroupLength" Name="Print Content Group Length"
+(2130,0010) VERS="4RET" VR="SQ" VM="1" Keyword="PrintManagementCapabilitiesSequence" Name="Print Management Capabilities Sequence"
+(2130,0015) VERS="4RET" VR="SQ" VM="1" Keyword="PrinterCharacteristicsSequence" Name="Printer Characteristics Sequence"
+(2130,0030) VERS="4RET" VR="SQ" VM="1" Keyword="FilmBoxContentSequence" Name="Film Box Content Sequence"
+(2130,0040) VERS="4RET" VR="SQ" VM="1" Keyword="ImageBoxContentSequence" Name="Image Box Content Sequence"
+(2130,0050) VERS="4RET" VR="SQ" VM="1" Keyword="AnnotationContentSequence" Name="Annotation Content Sequence"
+(2130,0060) VERS="4RET" VR="SQ" VM="1" Keyword="ImageOverlayBoxContentSequence" Name="Image Overlay Box Content Sequence"
+(2130,0080) VERS="4RET" VR="SQ" VM="1" Keyword="PresentationLUTContentSequence" Name="Presentation LUT Content Sequence"
+(2130,00A0) VERS="4RET" VR="SQ" VM="1" Keyword="ProposedStudySequence" Name="Proposed Study Sequence"
+(2130,00C0) VERS="4RET" VR="SQ" VM="1" Keyword="OriginalImageSequence" Name="Original Image Sequence"
+(2200,0001) VERS="4" VR="CS" VM="1" Keyword="LabelUsingInformationExtractedFromInstances" Name="Label Using Information Extracted From Instances"
+(2200,0002) VERS="4" VR="UT" VM="1" Keyword="LabelText" Name="Label Text"
+(2200,0003) VERS="4" VR="CS" VM="1" Keyword="LabelStyleSelection" Name="Label Style Selection"
+(2200,0004) VERS="4" VR="LT" VM="1" Keyword="MediaDisposition" Name="Media Disposition"
+(2200,0005) VERS="4" VR="LT" VM="1" Keyword="BarcodeValue" Name="Barcode Value"
+(2200,0006) VERS="4" VR="CS" VM="1" Keyword="BarcodeSymbology" Name="Barcode Symbology"
+(2200,0007) VERS="4" VR="CS" VM="1" Keyword="AllowMediaSplitting" Name="Allow Media Splitting"
+(2200,0008) VERS="4" VR="CS" VM="1" Keyword="IncludeNonDICOMObjects" Name="Include Non-DICOM Objects"
+(2200,0009) VERS="4" VR="CS" VM="1" Keyword="IncludeDisplayApplication" Name="Include Display Application"
+(2200,000A) VERS="4" VR="CS" VM="1" Keyword="PreserveCompositeInstancesAfterMediaCreation" Name="Preserve Composite Instances After Media Creation"
+(2200,000B) VERS="4" VR="US" VM="1" Keyword="TotalNumberOfPiecesOfMediaCreated" Name="Total Number of Pieces of Media Created"
+(2200,000C) VERS="4" VR="LO" VM="1" Keyword="RequestedMediaApplicationProfile" Name="Requested Media Application Profile"
+(2200,000D) VERS="4" VR="SQ" VM="1" Keyword="ReferencedStorageMediaSequence" Name="Referenced Storage Media Sequence"
+(2200,000E) VERS="4" VR="AT" VM="1-n" Keyword="FailureAttributes" Name="Failure Attributes"
+(2200,000F) VERS="4" VR="CS" VM="1" Keyword="AllowLossyCompression" Name="Allow Lossy Compression"
+(2200,0020) VERS="4" VR="CS" VM="1" Keyword="RequestPriority" Name="Request Priority"
+(3002,0000) VERS="3" VR="UL" VM="1" Keyword="RTImageGroupLength" Name="RT Image Group Length"
+(3002,0002) VERS="4" VR="SH" VM="1" Keyword="RTImageLabel" Name="RT Image Label"
+(3002,0003) VERS="4" VR="LO" VM="1" Keyword="RTImageName" Name="RT Image Name"
+(3002,0004) VERS="4" VR="ST" VM="1" Keyword="RTImageDescription" Name="RT Image Description"
+(3002,000A) VERS="4" VR="CS" VM="1" Keyword="ReportedValuesOrigin" Name="Reported Values Origin"
+(3002,000C) VERS="4" VR="CS" VM="1" Keyword="RTImagePlane" Name="RT Image Plane"
+(3002,000D) VERS="4" VR="DS" VM="3" Keyword="XRayImageReceptorTranslation" Name="X-Ray Image Receptor Translation"
+(3002,000E) VERS="4" VR="DS" VM="1" Keyword="XRayImageReceptorAngle" Name="X-Ray Image Receptor Angle"
+(3002,0010) VERS="4" VR="DS" VM="6" Keyword="RTImageOrientation" Name="RT Image Orientation"
+(3002,0011) VERS="4" VR="DS" VM="2" Keyword="ImagePlanePixelSpacing" Name="Image Plane Pixel Spacing"
+(3002,0012) VERS="4" VR="DS" VM="2" Keyword="RTImagePosition" Name="RT Image Position"
+(3002,0020) VERS="4" VR="SH" VM="1" Keyword="RadiationMachineName" Name="Radiation Machine Name"
+(3002,0022) VERS="4" VR="DS" VM="1" Keyword="RadiationMachineSAD" Name="Radiation Machine SAD"
+(3002,0024) VERS="4" VR="DS" VM="1" Keyword="RadiationMachineSSD" Name="Radiation Machine SSD"
+(3002,0026) VERS="4" VR="DS" VM="1" Keyword="RTImageSID" Name="RT Image SID"
+(3002,0028) VERS="4" VR="DS" VM="1" Keyword="SourceToReferenceObjectDistance" Name="Source to Reference Object Distance"
+(3002,0029) VERS="4" VR="IS" VM="1" Keyword="FractionNumber" Name="Fraction Number"
+(3002,0030) VERS="4" VR="SQ" VM="1" Keyword="ExposureSequence" Name="Exposure Sequence"
+(3002,0032) VERS="4" VR="DS" VM="1" Keyword="MetersetExposure" Name="Meterset Exposure"
+(3002,0034) VERS="4" VR="DS" VM="4" Keyword="DiaphragmPosition" Name="Diaphragm Position"
+(3002,0040) VERS="4" VR="SQ" VM="1" Keyword="FluenceMapSequence" Name="Fluence Map Sequence"
+(3002,0041) VERS="4" VR="CS" VM="1" Keyword="FluenceDataSource" Name="Fluence Data Source"
+(3002,0042) VERS="4" VR="DS" VM="1" Keyword="FluenceDataScale" Name="Fluence Data Scale"
+(3002,0050) VERS="4" VR="SQ" VM="1" Keyword="PrimaryFluenceModeSequence" Name="Primary Fluence Mode Sequence"
+(3002,0051) VERS="4" VR="CS" VM="1" Keyword="FluenceMode" Name="Fluence Mode"
+(3002,0052) VERS="4" VR="SH" VM="1" Keyword="FluenceModeID" Name="Fluence Mode ID"
+(3004,0000) VERS="3" VR="UL" VM="1" Keyword="RTDoseGroupLength" Name="RT Dose Group Length"
+(3004,0001) VERS="4" VR="CS" VM="1" Keyword="DVHType" Name="DVH Type"
+(3004,0002) VERS="4" VR="CS" VM="1" Keyword="DoseUnits" Name="Dose Units"
+(3004,0004) VERS="4" VR="CS" VM="1" Keyword="DoseType" Name="Dose Type"
+(3004,0006) VERS="4" VR="LO" VM="1" Keyword="DoseComment" Name="Dose Comment"
+(3004,0008) VERS="4" VR="DS" VM="3" Keyword="NormalizationPoint" Name="Normalization Point"
+(3004,000A) VERS="4" VR="CS" VM="1" Keyword="DoseSummationType" Name="Dose Summation Type"
+(3004,000C) VERS="4" VR="DS" VM="2-n" Keyword="GridFrameOffsetVector" Name="Grid Frame Offset Vector"
+(3004,000E) VERS="4" VR="DS" VM="1" Keyword="DoseGridScaling" Name="Dose Grid Scaling"
+(3004,0010) VERS="4" VR="SQ" VM="1" Keyword="RTDoseROISequence" Name="RT Dose ROI Sequence"
+(3004,0012) VERS="4" VR="DS" VM="1" Keyword="DoseValue" Name="Dose Value"
+(3004,0014) VERS="4" VR="CS" VM="1-3" Keyword="TissueHeterogeneityCorrection" Name="Tissue Heterogeneity Correction"
+(3004,0040) VERS="4" VR="DS" VM="3" Keyword="DVHNormalizationPoint" Name="DVH Normalization Point"
+(3004,0042) VERS="4" VR="DS" VM="1" Keyword="DVHNormalizationDoseValue" Name="DVH Normalization Dose Value"
+(3004,0050) VERS="4" VR="SQ" VM="1" Keyword="DVHSequence" Name="DVH Sequence"
+(3004,0052) VERS="4" VR="DS" VM="1" Keyword="DVHDoseScaling" Name="DVH Dose Scaling"
+(3004,0054) VERS="4" VR="CS" VM="1" Keyword="DVHVolumeUnits" Name="DVH Volume Units"
+(3004,0056) VERS="4" VR="IS" VM="1" Keyword="DVHNumberOfBins" Name="DVH Number of Bins"
+(3004,0058) VERS="4" VR="DS" VM="2-2n" Keyword="DVHData" Name="DVH Data"
+(3004,0060) VERS="4" VR="SQ" VM="1" Keyword="DVHReferencedROISequence" Name="DVH Referenced ROI Sequence"
+(3004,0062) VERS="4" VR="CS" VM="1" Keyword="DVHROIContributionType" Name="DVH ROI Contribution Type"
+(3004,0070) VERS="4" VR="DS" VM="1" Keyword="DVHMinimumDose" Name="DVH Minimum Dose"
+(3004,0072) VERS="4" VR="DS" VM="1" Keyword="DVHMaximumDose" Name="DVH Maximum Dose"
+(3004,0074) VERS="4" VR="DS" VM="1" Keyword="DVHMeanDose" Name="DVH Mean Dose"
+(3006,0000) VERS="3" VR="UL" VM="1" Keyword="RTStructureSetGroupLength" Name="RT Structure Set Group Length"
+(3006,0002) VERS="4" VR="SH" VM="1" Keyword="StructureSetLabel" Name="Structure Set Label"
+(3006,0004) VERS="4" VR="LO" VM="1" Keyword="StructureSetName" Name="Structure Set Name"
+(3006,0006) VERS="4" VR="ST" VM="1" Keyword="StructureSetDescription" Name="Structure Set Description"
+(3006,0008) VERS="4" VR="DA" VM="1" Keyword="StructureSetDate" Name="Structure Set Date"
+(3006,0009) VERS="4" VR="TM" VM="1" Keyword="StructureSetTime" Name="Structure Set Time"
+(3006,0010) VERS="4" VR="SQ" VM="1" Keyword="ReferencedFrameOfReferenceSequence" Name="Referenced Frame of Reference Sequence"
+(3006,0012) VERS="4" VR="SQ" VM="1" Keyword="RTReferencedStudySequence" Name="RT Referenced Study Sequence"
+(3006,0014) VERS="4" VR="SQ" VM="1" Keyword="RTReferencedSeriesSequence" Name="RT Referenced Series Sequence"
+(3006,0016) VERS="4" VR="SQ" VM="1" Keyword="ContourImageSequence" Name="Contour Image Sequence"
+(3006,0020) VERS="4" VR="SQ" VM="1" Keyword="StructureSetROISequence" Name="Structure Set ROI Sequence"
+(3006,0022) VERS="4" VR="IS" VM="1" Keyword="ROINumber" Name="ROI Number"
+(3006,0024) VERS="4" VR="UI" VM="1" Keyword="ReferencedFrameOfReferenceUID" Name="Referenced Frame of Reference UID"
+(3006,0026) VERS="4" VR="LO" VM="1" Keyword="ROIName" Name="ROI Name"
+(3006,0028) VERS="4" VR="ST" VM="1" Keyword="ROIDescription" Name="ROI Description"
+(3006,002A) VERS="4" VR="IS" VM="3" Keyword="ROIDisplayColor" Name="ROI Display Color"
+(3006,002C) VERS="4" VR="DS" VM="1" Keyword="ROIVolume" Name="ROI Volume"
+(3006,0030) VERS="4" VR="SQ" VM="1" Keyword="RTRelatedROISequence" Name="RT Related ROI Sequence"
+(3006,0033) VERS="4" VR="CS" VM="1" Keyword="RTROIRelationship" Name="RT ROI Relationship"
+(3006,0036) VERS="4" VR="CS" VM="1" Keyword="ROIGenerationAlgorithm" Name="ROI Generation Algorithm"
+(3006,0038) VERS="4" VR="LO" VM="1" Keyword="ROIGenerationDescription" Name="ROI Generation Description"
+(3006,0039) VERS="4" VR="SQ" VM="1" Keyword="ROIContourSequence" Name="ROI Contour Sequence"
+(3006,0040) VERS="4" VR="SQ" VM="1" Keyword="ContourSequence" Name="Contour Sequence"
+(3006,0042) VERS="4" VR="CS" VM="1" Keyword="ContourGeometricType" Name="Contour Geometric Type"
+(3006,0044) VERS="4" VR="DS" VM="1" Keyword="ContourSlabThickness" Name="Contour Slab Thickness"
+(3006,0045) VERS="4" VR="DS" VM="3" Keyword="ContourOffsetVector" Name="Contour Offset Vector"
+(3006,0046) VERS="4" VR="IS" VM="1" Keyword="NumberOfContourPoints" Name="Number of Contour Points"
+(3006,0048) VERS="4" VR="IS" VM="1" Keyword="ContourNumber" Name="Contour Number"
+(3006,0049) VERS="4" VR="IS" VM="1-n" Keyword="AttachedContours" Name="Attached Contours"
+(3006,0050) VERS="4" VR="DS" VM="3-3n" Keyword="ContourData" Name="Contour Data"
+(3006,0080) VERS="4" VR="SQ" VM="1" Keyword="RTROIObservationsSequence" Name="RT ROI Observations Sequence"
+(3006,0082) VERS="4" VR="IS" VM="1" Keyword="ObservationNumber" Name="Observation Number"
+(3006,0084) VERS="4" VR="IS" VM="1" Keyword="ReferencedROINumber" Name="Referenced ROI Number"
+(3006,0085) VERS="4" VR="SH" VM="1" Keyword="ROIObservationLabel" Name="ROI Observation Label"
+(3006,0086) VERS="4" VR="SQ" VM="1" Keyword="RTROIIdentificationCodeSequence" Name="RT ROI Identification Code Sequence"
+(3006,0088) VERS="4" VR="ST" VM="1" Keyword="ROIObservationDescription" Name="ROI Observation Description"
+(3006,00A0) VERS="4" VR="SQ" VM="1" Keyword="RelatedRTROIObservationsSequence" Name="Related RT ROI Observations Sequence"
+(3006,00A4) VERS="4" VR="CS" VM="1" Keyword="RTROIInterpretedType" Name="RT ROI Interpreted Type"
+(3006,00A6) VERS="4" VR="PN" VM="1" Keyword="ROIInterpreter" Name="ROI Interpreter"
+(3006,00B0) VERS="4" VR="SQ" VM="1" Keyword="ROIPhysicalPropertiesSequence" Name="ROI Physical Properties Sequence"
+(3006,00B2) VERS="4" VR="CS" VM="1" Keyword="ROIPhysicalProperty" Name="ROI Physical Property"
+(3006,00B4) VERS="4" VR="DS" VM="1" Keyword="ROIPhysicalPropertyValue" Name="ROI Physical Property Value"
+(3006,00B6) VERS="4" VR="SQ" VM="1" Keyword="ROIElementalCompositionSequence" Name="ROI Elemental Composition Sequence"
+(3006,00B7) VERS="4" VR="US" VM="1" Keyword="ROIElementalCompositionAtomicNumber" Name="ROI Elemental Composition Atomic Number"
+(3006,00B8) VERS="4" VR="FL" VM="1" Keyword="ROIElementalCompositionAtomicMassFraction" Name="ROI Elemental Composition Atomic Mass Fraction"
+(3006,00C0) VERS="4" VR="SQ" VM="1" Keyword="FrameOfReferenceRelationshipSequence" Name="Frame of Reference Relationship Sequence"
+(3006,00C2) VERS="4" VR="UI" VM="1" Keyword="RelatedFrameOfReferenceUID" Name="Related Frame of Reference UID"
+(3006,00C4) VERS="4" VR="CS" VM="1" Keyword="FrameOfReferenceTransformationType" Name="Frame of Reference Transformation Type"
+(3006,00C6) VERS="4" VR="DS" VM="16" Keyword="FrameOfReferenceTransformationMatrix" Name="Frame of Reference Transformation Matrix"
+(3006,00C8) VERS="4" VR="LO" VM="1" Keyword="FrameOfReferenceTransformationComment" Name="Frame of Reference Transformation Comment"
+(3008,0010) VERS="4" VR="SQ" VM="1" Keyword="MeasuredDoseReferenceSequence" Name="Measured Dose Reference Sequence"
+(3008,0012) VERS="4" VR="ST" VM="1" Keyword="MeasuredDoseDescription" Name="Measured Dose Description"
+(3008,0014) VERS="4" VR="CS" VM="1" Keyword="MeasuredDoseType" Name="Measured Dose Type"
+(3008,0016) VERS="4" VR="DS" VM="1" Keyword="MeasuredDoseValue" Name="Measured Dose Value"
+(3008,0020) VERS="4" VR="SQ" VM="1" Keyword="TreatmentSessionBeamSequence" Name="Treatment Session Beam Sequence"
+(3008,0021) VERS="4" VR="SQ" VM="1" Keyword="TreatmentSessionIonBeamSequence" Name="Treatment Session Ion Beam Sequence"
+(3008,0022) VERS="4" VR="IS" VM="1" Keyword="CurrentFractionNumber" Name="Current Fraction Number"
+(3008,0024) VERS="4" VR="DA" VM="1" Keyword="TreatmentControlPointDate" Name="Treatment Control Point Date"
+(3008,0025) VERS="4" VR="TM" VM="1" Keyword="TreatmentControlPointTime" Name="Treatment Control Point Time"
+(3008,002A) VERS="4" VR="CS" VM="1" Keyword="TreatmentTerminationStatus" Name="Treatment Termination Status"
+(3008,002B) VERS="4" VR="SH" VM="1" Keyword="TreatmentTerminationCode" Name="Treatment Termination Code"
+(3008,002C) VERS="4" VR="CS" VM="1" Keyword="TreatmentVerificationStatus" Name="Treatment Verification Status"
+(3008,0030) VERS="4" VR="SQ" VM="1" Keyword="ReferencedTreatmentRecordSequence" Name="Referenced Treatment Record Sequence"
+(3008,0032) VERS="4" VR="DS" VM="1" Keyword="SpecifiedPrimaryMeterset" Name="Specified Primary Meterset "
+(3008,0033) VERS="4" VR="DS" VM="1" Keyword="SpecifiedSecondaryMeterset" Name="Specified Secondary Meterset "
+(3008,0036) VERS="4" VR="DS" VM="1" Keyword="DeliveredPrimaryMeterset" Name="Delivered Primary Meterset "
+(3008,0037) VERS="4" VR="DS" VM="1" Keyword="DeliveredSecondaryMeterset" Name="Delivered Secondary Meterset "
+(3008,003A) VERS="4" VR="DS" VM="1" Keyword="SpecifiedTreatmentTime" Name="Specified Treatment Time"
+(3008,003B) VERS="4" VR="DS" VM="1" Keyword="DeliveredTreatmentTime" Name="Delivered Treatment Time"
+(3008,0040) VERS="4" VR="SQ" VM="1" Keyword="ControlPointDeliverySequence" Name="Control Point Delivery Sequence"
+(3008,0041) VERS="4" VR="SQ" VM="1" Keyword="IonControlPointDeliverySequence" Name="Ion Control Point Delivery Sequence"
+(3008,0042) VERS="4" VR="DS" VM="1" Keyword="SpecifiedMeterset" Name="Specified Meterset"
+(3008,0044) VERS="4" VR="DS" VM="1" Keyword="DeliveredMeterset" Name="Delivered Meterset"
+(3008,0045) VERS="4" VR="FL" VM="1" Keyword="MetersetRateSet" Name="Meterset Rate Set"
+(3008,0046) VERS="4" VR="FL" VM="1" Keyword="MetersetRateDelivered" Name="Meterset Rate Delivered"
+(3008,0047) VERS="4" VR="FL" VM="1-n" Keyword="ScanSpotMetersetsDelivered" Name="Scan Spot Metersets Delivered"
+(3008,0048) VERS="4" VR="DS" VM="1" Keyword="DoseRateDelivered" Name="Dose Rate Delivered"
+(3008,0050) VERS="4" VR="SQ" VM="1" Keyword="TreatmentSummaryCalculatedDoseReferenceSequence" Name="Treatment Summary Calculated Dose Reference Sequence"
+(3008,0052) VERS="4" VR="DS" VM="1" Keyword="CumulativeDoseToDoseReference" Name="Cumulative Dose to Dose Reference"
+(3008,0054) VERS="4" VR="DA" VM="1" Keyword="FirstTreatmentDate" Name="First Treatment Date"
+(3008,0056) VERS="4" VR="DA" VM="1" Keyword="MostRecentTreatmentDate" Name="Most Recent Treatment Date"
+(3008,005A) VERS="4" VR="IS" VM="1" Keyword="NumberOfFractionsDelivered" Name="Number of Fractions Delivered"
+(3008,0060) VERS="4" VR="SQ" VM="1" Keyword="OverrideSequence" Name="Override Sequence"
+(3008,0061) VERS="4" VR="AT" VM="1" Keyword="ParameterSequencePointer" Name="Parameter Sequence Pointer"
+(3008,0062) VERS="4" VR="AT" VM="1" Keyword="OverrideParameterPointer" Name="Override Parameter Pointer"
+(3008,0063) VERS="4" VR="IS" VM="1" Keyword="ParameterItemIndex" Name="Parameter Item Index"
+(3008,0064) VERS="4" VR="IS" VM="1" Keyword="MeasuredDoseReferenceNumber" Name="Measured Dose Reference Number"
+(3008,0065) VERS="4" VR="AT" VM="1" Keyword="ParameterPointer" Name="Parameter Pointer"
+(3008,0066) VERS="4" VR="ST" VM="1" Keyword="OverrideReason" Name="Override Reason"
+(3008,0068) VERS="4" VR="SQ" VM="1" Keyword="CorrectedParameterSequence" Name="Corrected Parameter Sequence"
+(3008,006A) VERS="4" VR="FL" VM="1" Keyword="CorrectionValue" Name="Correction Value"
+(3008,0070) VERS="4" VR="SQ" VM="1" Keyword="CalculatedDoseReferenceSequence" Name="Calculated Dose Reference Sequence"
+(3008,0072) VERS="4" VR="IS" VM="1" Keyword="CalculatedDoseReferenceNumber" Name="Calculated Dose Reference Number"
+(3008,0074) VERS="4" VR="ST" VM="1" Keyword="CalculatedDoseReferenceDescription" Name="Calculated Dose Reference Description"
+(3008,0076) VERS="4" VR="DS" VM="1" Keyword="CalculatedDoseReferenceDoseValue" Name="Calculated Dose Reference Dose Value"
+(3008,0078) VERS="4" VR="DS" VM="1" Keyword="StartMeterset" Name="Start Meterset"
+(3008,007A) VERS="4" VR="DS" VM="1" Keyword="EndMeterset" Name="End Meterset"
+(3008,0080) VERS="4" VR="SQ" VM="1" Keyword="ReferencedMeasuredDoseReferenceSequence" Name="Referenced Measured Dose Reference Sequence"
+(3008,0082) VERS="4" VR="IS" VM="1" Keyword="ReferencedMeasuredDoseReferenceNumber" Name="Referenced Measured Dose Reference Number"
+(3008,0090) VERS="4" VR="SQ" VM="1" Keyword="ReferencedCalculatedDoseReferenceSequence" Name="Referenced Calculated Dose Reference Sequence"
+(3008,0092) VERS="4" VR="IS" VM="1" Keyword="ReferencedCalculatedDoseReferenceNumber" Name="Referenced Calculated Dose Reference Number"
+(3008,00A0) VERS="4" VR="SQ" VM="1" Keyword="BeamLimitingDeviceLeafPairsSequence" Name="Beam Limiting Device Leaf Pairs Sequence"
+(3008,00B0) VERS="4" VR="SQ" VM="1" Keyword="RecordedWedgeSequence" Name="Recorded Wedge Sequence"
+(3008,00C0) VERS="4" VR="SQ" VM="1" Keyword="RecordedCompensatorSequence" Name="Recorded Compensator Sequence"
+(3008,00D0) VERS="4" VR="SQ" VM="1" Keyword="RecordedBlockSequence" Name="Recorded Block Sequence"
+(3008,00E0) VERS="4" VR="SQ" VM="1" Keyword="TreatmentSummaryMeasuredDoseReferenceSequence" Name="Treatment Summary Measured Dose Reference Sequence"
+(3008,00F0) VERS="4" VR="SQ" VM="1" Keyword="RecordedSnoutSequence" Name="Recorded Snout Sequence"
+(3008,00F2) VERS="4" VR="SQ" VM="1" Keyword="RecordedRangeShifterSequence" Name="Recorded Range Shifter Sequence"
+(3008,00F4) VERS="4" VR="SQ" VM="1" Keyword="RecordedLateralSpreadingDeviceSequence" Name="Recorded Lateral Spreading Device Sequence"
+(3008,00F6) VERS="4" VR="SQ" VM="1" Keyword="RecordedRangeModulatorSequence" Name="Recorded Range Modulator Sequence"
+(3008,0100) VERS="4" VR="SQ" VM="1" Keyword="RecordedSourceSequence" Name="Recorded Source Sequence"
+(3008,0105) VERS="4" VR="LO" VM="1" Keyword="SourceSerialNumber" Name="Source Serial Number"
+(3008,0110) VERS="4" VR="SQ" VM="1" Keyword="TreatmentSessionApplicationSetupSequence" Name="Treatment Session Application Setup Sequence"
+(3008,0116) VERS="4" VR="CS" VM="1" Keyword="ApplicationSetupCheck" Name="Application Setup Check"
+(3008,0120) VERS="4" VR="SQ" VM="1" Keyword="RecordedBrachyAccessoryDeviceSequence" Name="Recorded Brachy Accessory Device Sequence"
+(3008,0122) VERS="4" VR="IS" VM="1" Keyword="ReferencedBrachyAccessoryDeviceNumber" Name="Referenced Brachy Accessory Device Number"
+(3008,0130) VERS="4" VR="SQ" VM="1" Keyword="RecordedChannelSequence" Name="Recorded Channel Sequence"
+(3008,0132) VERS="4" VR="DS" VM="1" Keyword="SpecifiedChannelTotalTime" Name="Specified Channel Total Time"
+(3008,0134) VERS="4" VR="DS" VM="1" Keyword="DeliveredChannelTotalTime" Name="Delivered Channel Total Time"
+(3008,0136) VERS="4" VR="IS" VM="1" Keyword="SpecifiedNumberOfPulses" Name="Specified Number of Pulses"
+(3008,0138) VERS="4" VR="IS" VM="1" Keyword="DeliveredNumberOfPulses" Name="Delivered Number of Pulses"
+(3008,013A) VERS="4" VR="DS" VM="1" Keyword="SpecifiedPulseRepetitionInterval" Name="Specified Pulse Repetition Interval"
+(3008,013C) VERS="4" VR="DS" VM="1" Keyword="DeliveredPulseRepetitionInterval" Name="Delivered Pulse Repetition Interval"
+(3008,0140) VERS="4" VR="SQ" VM="1" Keyword="RecordedSourceApplicatorSequence" Name="Recorded Source Applicator Sequence"
+(3008,0142) VERS="4" VR="IS" VM="1" Keyword="ReferencedSourceApplicatorNumber" Name="Referenced Source Applicator Number"
+(3008,0150) VERS="4" VR="SQ" VM="1" Keyword="RecordedChannelShieldSequence" Name="Recorded Channel Shield Sequence"
+(3008,0152) VERS="4" VR="IS" VM="1" Keyword="ReferencedChannelShieldNumber" Name="Referenced Channel Shield Number"
+(3008,0160) VERS="4" VR="SQ" VM="1" Keyword="BrachyControlPointDeliveredSequence" Name="Brachy Control Point Delivered Sequence"
+(3008,0162) VERS="4" VR="DA" VM="1" Keyword="SafePositionExitDate" Name="Safe Position Exit Date"
+(3008,0164) VERS="4" VR="TM" VM="1" Keyword="SafePositionExitTime" Name="Safe Position Exit Time"
+(3008,0166) VERS="4" VR="DA" VM="1" Keyword="SafePositionReturnDate" Name="Safe Position Return Date"
+(3008,0168) VERS="4" VR="TM" VM="1" Keyword="SafePositionReturnTime" Name="Safe Position Return Time"
+(3008,0200) VERS="4" VR="CS" VM="1" Keyword="CurrentTreatmentStatus" Name="Current Treatment Status"
+(3008,0202) VERS="4" VR="ST" VM="1" Keyword="TreatmentStatusComment" Name="Treatment Status Comment"
+(3008,0220) VERS="4" VR="SQ" VM="1" Keyword="FractionGroupSummarySequence" Name="Fraction Group Summary Sequence"
+(3008,0223) VERS="4" VR="IS" VM="1" Keyword="ReferencedFractionNumber" Name="Referenced Fraction Number"
+(3008,0224) VERS="4" VR="CS" VM="1" Keyword="FractionGroupType" Name="Fraction Group Type"
+(3008,0230) VERS="4" VR="CS" VM="1" Keyword="BeamStopperPosition" Name="Beam Stopper Position"
+(3008,0240) VERS="4" VR="SQ" VM="1" Keyword="FractionStatusSummarySequence" Name="Fraction Status Summary Sequence"
+(3008,0250) VERS="4" VR="DA" VM="1" Keyword="TreatmentDate" Name="Treatment Date"
+(3008,0251) VERS="4" VR="TM" VM="1" Keyword="TreatmentTime" Name="Treatment Time"
+(300A,0000) VERS="3" VR="UL" VM="1" Keyword="RTPlanGroupLength" Name="RTPlanGroupLength"
+(300A,0002) VERS="4" VR="SH" VM="1" Keyword="RTPlanLabel" Name="RT Plan Label"
+(300A,0003) VERS="4" VR="LO" VM="1" Keyword="RTPlanName" Name="RT Plan Name"
+(300A,0004) VERS="4" VR="ST" VM="1" Keyword="RTPlanDescription" Name="RT Plan Description"
+(300A,0006) VERS="4" VR="DA" VM="1" Keyword="RTPlanDate" Name="RT Plan Date"
+(300A,0007) VERS="4" VR="TM" VM="1" Keyword="RTPlanTime" Name="RT Plan Time"
+(300A,0009) VERS="4" VR="LO" VM="1-n" Keyword="TreatmentProtocols" Name="Treatment Protocols"
+(300A,000A) VERS="4" VR="CS" VM="1" Keyword="PlanIntent" Name="Plan Intent"
+(300A,000B) VERS="4" VR="LO" VM="1-n" Keyword="TreatmentSites" Name="Treatment Sites"
+(300A,000C) VERS="4" VR="CS" VM="1" Keyword="RTPlanGeometry" Name="RT Plan Geometry"
+(300A,000E) VERS="4" VR="ST" VM="1" Keyword="PrescriptionDescription" Name="Prescription Description"
+(300A,0010) VERS="4" VR="SQ" VM="1" Keyword="DoseReferenceSequence" Name="Dose Reference Sequence"
+(300A,0012) VERS="4" VR="IS" VM="1" Keyword="DoseReferenceNumber" Name="Dose Reference Number"
+(300A,0013) VERS="4" VR="UI" VM="1" Keyword="DoseReferenceUID" Name="Dose Reference UID"
+(300A,0014) VERS="4" VR="CS" VM="1" Keyword="DoseReferenceStructureType" Name="Dose Reference Structure Type"
+(300A,0015) VERS="4" VR="CS" VM="1" Keyword="NominalBeamEnergyUnit" Name="Nominal Beam Energy Unit"
+(300A,0016) VERS="4" VR="LO" VM="1" Keyword="DoseReferenceDescription" Name="Dose Reference Description"
+(300A,0018) VERS="4" VR="DS" VM="3" Keyword="DoseReferencePointCoordinates" Name="Dose Reference Point Coordinates"
+(300A,001A) VERS="4" VR="DS" VM="1" Keyword="NominalPriorDose" Name="Nominal Prior Dose"
+(300A,0020) VERS="4" VR="CS" VM="1" Keyword="DoseReferenceType" Name="Dose Reference Type"
+(300A,0021) VERS="4" VR="DS" VM="1" Keyword="ConstraintWeight" Name="Constraint Weight"
+(300A,0022) VERS="4" VR="DS" VM="1" Keyword="DeliveryWarningDose" Name="Delivery Warning Dose"
+(300A,0023) VERS="4" VR="DS" VM="1" Keyword="DeliveryMaximumDose" Name="Delivery Maximum Dose"
+(300A,0025) VERS="4" VR="DS" VM="1" Keyword="TargetMinimumDose" Name="Target Minimum Dose"
+(300A,0026) VERS="4" VR="DS" VM="1" Keyword="TargetPrescriptionDose" Name="Target Prescription Dose"
+(300A,0027) VERS="4" VR="DS" VM="1" Keyword="TargetMaximumDose" Name="Target Maximum Dose"
+(300A,0028) VERS="4" VR="DS" VM="1" Keyword="TargetUnderdoseVolumeFraction" Name="Target Underdose Volume Fraction"
+(300A,002A) VERS="4" VR="DS" VM="1" Keyword="OrganAtRiskFullVolumeDose" Name="Organ at Risk Full-volume Dose"
+(300A,002B) VERS="4" VR="DS" VM="1" Keyword="OrganAtRiskLimitDose" Name="Organ at Risk Limit Dose"
+(300A,002C) VERS="4" VR="DS" VM="1" Keyword="OrganAtRiskMaximumDose" Name="Organ at Risk Maximum Dose"
+(300A,002D) VERS="4" VR="DS" VM="1" Keyword="OrganAtRiskOverdoseVolumeFraction" Name="Organ at Risk Overdose Volume Fraction"
+(300A,0040) VERS="4" VR="SQ" VM="1" Keyword="ToleranceTableSequence" Name="Tolerance Table Sequence"
+(300A,0042) VERS="4" VR="IS" VM="1" Keyword="ToleranceTableNumber" Name="Tolerance Table Number"
+(300A,0043) VERS="4" VR="SH" VM="1" Keyword="ToleranceTableLabel" Name="Tolerance Table Label"
+(300A,0044) VERS="4" VR="DS" VM="1" Keyword="GantryAngleTolerance" Name="Gantry Angle Tolerance"
+(300A,0046) VERS="4" VR="DS" VM="1" Keyword="BeamLimitingDeviceAngleTolerance" Name="Beam Limiting Device Angle Tolerance"
+(300A,0048) VERS="4" VR="SQ" VM="1" Keyword="BeamLimitingDeviceToleranceSequence" Name="Beam Limiting Device Tolerance Sequence"
+(300A,004A) VERS="4" VR="DS" VM="1" Keyword="BeamLimitingDevicePositionTolerance" Name="Beam Limiting Device Position Tolerance"
+(300A,004B) VERS="4" VR="FL" VM="1" Keyword="SnoutPositionTolerance" Name="Snout Position Tolerance"
+(300A,004C) VERS="4" VR="DS" VM="1" Keyword="PatientSupportAngleTolerance" Name="Patient Support Angle Tolerance"
+(300A,004E) VERS="4" VR="DS" VM="1" Keyword="TableTopEccentricAngleTolerance" Name="Table Top Eccentric Angle Tolerance"
+(300A,004F) VERS="4" VR="FL" VM="1" Keyword="TableTopPitchAngleTolerance" Name="Table Top Pitch Angle Tolerance"
+(300A,0050) VERS="4" VR="FL" VM="1" Keyword="TableTopRollAngleTolerance" Name="Table Top Roll Angle Tolerance"
+(300A,0051) VERS="4" VR="DS" VM="1" Keyword="TableTopVerticalPositionTolerance" Name="Table Top Vertical Position Tolerance"
+(300A,0052) VERS="4" VR="DS" VM="1" Keyword="TableTopLongitudinalPositionTolerance" Name="Table Top Longitudinal Position Tolerance"
+(300A,0053) VERS="4" VR="DS" VM="1" Keyword="TableTopLateralPositionTolerance" Name="Table Top Lateral Position Tolerance"
+(300A,0055) VERS="4" VR="CS" VM="1" Keyword="RTPlanRelationship" Name="RT Plan Relationship"
+(300A,0070) VERS="4" VR="SQ" VM="1" Keyword="FractionGroupSequence" Name="Fraction Group Sequence"
+(300A,0071) VERS="4" VR="IS" VM="1" Keyword="FractionGroupNumber" Name="Fraction Group Number"
+(300A,0072) VERS="4" VR="LO" VM="1" Keyword="FractionGroupDescription" Name="Fraction Group Description"
+(300A,0078) VERS="4" VR="IS" VM="1" Keyword="NumberOfFractionsPlanned" Name="Number of Fractions Planned"
+(300A,0079) VERS="4" VR="IS" VM="1" Keyword="NumberOfFractionPatternDigitsPerDay" Name="Number of Fraction Pattern Digits Per Day"
+(300A,007A) VERS="4" VR="IS" VM="1" Keyword="RepeatFractionCycleLength" Name="Repeat Fraction Cycle Length"
+(300A,007B) VERS="4" VR="LT" VM="1" Keyword="FractionPattern" Name="Fraction Pattern"
+(300A,0080) VERS="4" VR="IS" VM="1" Keyword="NumberOfBeams" Name="Number of Beams"
+(300A,0082) VERS="4" VR="DS" VM="3" Keyword="BeamDoseSpecificationPoint" Name="Beam Dose Specification Point"
+(300A,0084) VERS="4" VR="DS" VM="1" Keyword="BeamDose" Name="Beam Dose"
+(300A,0086) VERS="4" VR="DS" VM="1" Keyword="BeamMeterset" Name="Beam Meterset"
+(300A,0088) VERS="4" VR="FL" VM="1" Keyword="BeamDosePointDepth" Name="Beam Dose Point Depth"
+(300A,0089) VERS="4" VR="FL" VM="1" Keyword="BeamDosePointEquivalentDepth" Name="Beam Dose Point Equivalent Depth"
+(300A,008A) VERS="4" VR="FL" VM="1" Keyword="BeamDosePointSSD" Name="Beam Dose Point SSD"
+(300A,00A0) VERS="4" VR="IS" VM="1" Keyword="NumberOfBrachyApplicationSetups" Name="Number of Brachy Application Setups"
+(300A,00A2) VERS="4" VR="DS" VM="3" Keyword="BrachyApplicationSetupDoseSpecificationPoint" Name="Brachy Application Setup Dose Specification Point"
+(300A,00A4) VERS="4" VR="DS" VM="1" Keyword="BrachyApplicationSetupDose" Name="Brachy Application Setup Dose"
+(300A,00B0) VERS="4" VR="SQ" VM="1" Keyword="BeamSequence" Name="Beam Sequence"
+(300A,00B2) VERS="4" VR="SH" VM="1" Keyword="TreatmentMachineName" Name="Treatment Machine Name "
+(300A,00B3) VERS="4" VR="CS" VM="1" Keyword="PrimaryDosimeterUnit" Name="Primary Dosimeter Unit"
+(300A,00B4) VERS="4" VR="DS" VM="1" Keyword="SourceAxisDistance" Name="Source-Axis Distance"
+(300A,00B6) VERS="4" VR="SQ" VM="1" Keyword="BeamLimitingDeviceSequence" Name="Beam Limiting Device Sequence"
+(300A,00B8) VERS="4" VR="CS" VM="1" Keyword="RTBeamLimitingDeviceType" Name="RT Beam Limiting Device Type"
+(300A,00BA) VERS="4" VR="DS" VM="1" Keyword="SourceToBeamLimitingDeviceDistance" Name="Source to Beam Limiting Device Distance"
+(300A,00BB) VERS="4" VR="FL" VM="1" Keyword="IsocenterToBeamLimitingDeviceDistance" Name="Isocenter to Beam Limiting Device Distance"
+(300A,00BC) VERS="4" VR="IS" VM="1" Keyword="NumberOfLeafJawPairs" Name="Number of Leaf/Jaw Pairs"
+(300A,00BE) VERS="4" VR="DS" VM="3-n" Keyword="LeafPositionBoundaries" Name="Leaf Position Boundaries"
+(300A,00C0) VERS="4" VR="IS" VM="1" Keyword="BeamNumber" Name="Beam Number"
+(300A,00C2) VERS="4" VR="LO" VM="1" Keyword="BeamName" Name="Beam Name"
+(300A,00C3) VERS="4" VR="ST" VM="1" Keyword="BeamDescription" Name="Beam Description"
+(300A,00C4) VERS="4" VR="CS" VM="1" Keyword="BeamType" Name="Beam Type"
+(300A,00C6) VERS="4" VR="CS" VM="1" Keyword="RadiationType" Name="Radiation Type"
+(300A,00C7) VERS="4" VR="CS" VM="1" Keyword="HighDoseTechniqueType" Name="High-Dose Technique Type"
+(300A,00C8) VERS="4" VR="IS" VM="1" Keyword="ReferenceImageNumber" Name="Reference Image Number"
+(300A,00CA) VERS="4" VR="SQ" VM="1" Keyword="PlannedVerificationImageSequence" Name="Planned Verification Image Sequence"
+(300A,00CC) VERS="4" VR="LO" VM="1-n" Keyword="ImagingDeviceSpecificAcquisitionParameters" Name="Imaging Device-Specific Acquisition Parameters"
+(300A,00CE) VERS="4" VR="CS" VM="1" Keyword="TreatmentDeliveryType" Name="Treatment Delivery Type"
+(300A,00D0) VERS="4" VR="IS" VM="1" Keyword="NumberOfWedges" Name="Number of Wedges"
+(300A,00D1) VERS="4" VR="SQ" VM="1" Keyword="WedgeSequence" Name="Wedge Sequence"
+(300A,00D2) VERS="4" VR="IS" VM="1" Keyword="WedgeNumber" Name="Wedge Number"
+(300A,00D3) VERS="4" VR="CS" VM="1" Keyword="WedgeType" Name="Wedge Type"
+(300A,00D4) VERS="4" VR="SH" VM="1" Keyword="WedgeID" Name="Wedge ID"
+(300A,00D5) VERS="4" VR="IS" VM="1" Keyword="WedgeAngle" Name="Wedge Angle"
+(300A,00D6) VERS="4" VR="DS" VM="1" Keyword="WedgeFactor" Name="Wedge Factor"
+(300A,00D7) VERS="4" VR="FL" VM="1" Keyword="TotalWedgeTrayWaterEquivalentThickness" Name="Total Wedge Tray Water-Equivalent Thickness"
+(300A,00D8) VERS="4" VR="DS" VM="1" Keyword="WedgeOrientation" Name="Wedge Orientation"
+(300A,00D9) VERS="4" VR="FL" VM="1" Keyword="IsocenterToWedgeTrayDistance" Name="Isocenter to Wedge Tray Distance"
+(300A,00DA) VERS="4" VR="DS" VM="1" Keyword="SourceToWedgeTrayDistance" Name="Source to Wedge Tray Distance"
+(300A,00DB) VERS="4" VR="FL" VM="1" Keyword="WedgeThinEdgePosition" Name="Wedge Thin Edge Position"
+(300A,00DC) VERS="4" VR="SH" VM="1" Keyword="BolusID" Name="Bolus ID"
+(300A,00DD) VERS="4" VR="ST" VM="1" Keyword="BolusDescription" Name="Bolus Description"
+(300A,00E0) VERS="4" VR="IS" VM="1" Keyword="NumberOfCompensators" Name="Number of Compensators"
+(300A,00E1) VERS="4" VR="SH" VM="1" Keyword="MaterialID" Name="Material ID"
+(300A,00E2) VERS="4" VR="DS" VM="1" Keyword="TotalCompensatorTrayFactor" Name="Total Compensator Tray Factor"
+(300A,00E3) VERS="4" VR="SQ" VM="1" Keyword="CompensatorSequence" Name="Compensator Sequence"
+(300A,00E4) VERS="4" VR="IS" VM="1" Keyword="CompensatorNumber" Name="Compensator Number"
+(300A,00E5) VERS="4" VR="SH" VM="1" Keyword="CompensatorID" Name="Compensator ID"
+(300A,00E6) VERS="4" VR="DS" VM="1" Keyword="SourceToCompensatorTrayDistance" Name="Source to Compensator Tray Distance"
+(300A,00E7) VERS="4" VR="IS" VM="1" Keyword="CompensatorRows" Name="Compensator Rows"
+(300A,00E8) VERS="4" VR="IS" VM="1" Keyword="CompensatorColumns" Name="Compensator Columns"
+(300A,00E9) VERS="4" VR="DS" VM="2" Keyword="CompensatorPixelSpacing" Name="Compensator Pixel Spacing"
+(300A,00EA) VERS="4" VR="DS" VM="2" Keyword="CompensatorPosition" Name="Compensator Position"
+(300A,00EB) VERS="4" VR="DS" VM="1-n" Keyword="CompensatorTransmissionData" Name="Compensator Transmission Data"
+(300A,00EC) VERS="4" VR="DS" VM="1-n" Keyword="CompensatorThicknessData" Name="Compensator Thickness Data"
+(300A,00ED) VERS="4" VR="IS" VM="1" Keyword="NumberOfBoli" Name="Number of Boli"
+(300A,00EE) VERS="4" VR="CS" VM="1" Keyword="CompensatorType" Name="Compensator Type"
+(300A,00F0) VERS="4" VR="IS" VM="1" Keyword="NumberOfBlocks" Name="Number of Blocks"
+(300A,00F2) VERS="4" VR="DS" VM="1" Keyword="TotalBlockTrayFactor" Name="Total Block Tray Factor"
+(300A,00F3) VERS="4" VR="FL" VM="1" Keyword="TotalBlockTrayWaterEquivalentThickness" Name="Total Block Tray Water-Equivalent Thickness"
+(300A,00F4) VERS="4" VR="SQ" VM="1" Keyword="BlockSequence" Name="Block Sequence"
+(300A,00F5) VERS="4" VR="SH" VM="1" Keyword="BlockTrayID" Name="Block Tray ID"
+(300A,00F6) VERS="4" VR="DS" VM="1" Keyword="SourceToBlockTrayDistance" Name="Source to Block Tray Distance"
+(300A,00F7) VERS="4" VR="FL" VM="1" Keyword="IsocenterToBlockTrayDistance" Name="Isocenter to Block Tray Distance"
+(300A,00F8) VERS="4" VR="CS" VM="1" Keyword="BlockType" Name="Block Type"
+(300A,00F9) VERS="4" VR="LO" VM="1" Keyword="AccessoryCode" Name="Accessory Code"
+(300A,00FA) VERS="4" VR="CS" VM="1" Keyword="BlockDivergence" Name="Block Divergence"
+(300A,00FB) VERS="4" VR="CS" VM="1" Keyword="BlockMountingPosition" Name="Block Mounting Position"
+(300A,00FC) VERS="4" VR="IS" VM="1" Keyword="BlockNumber" Name="Block Number"
+(300A,00FE) VERS="4" VR="LO" VM="1" Keyword="BlockName" Name="Block Name"
+(300A,0100) VERS="4" VR="DS" VM="1" Keyword="BlockThickness" Name="Block Thickness"
+(300A,0102) VERS="4" VR="DS" VM="1" Keyword="BlockTransmission" Name="Block Transmission"
+(300A,0104) VERS="4" VR="IS" VM="1" Keyword="BlockNumberOfPoints" Name="Block Number of Points"
+(300A,0106) VERS="4" VR="DS" VM="2-2n" Keyword="BlockData" Name="Block Data"
+(300A,0107) VERS="4" VR="SQ" VM="1" Keyword="ApplicatorSequence" Name="Applicator Sequence"
+(300A,0108) VERS="4" VR="SH" VM="1" Keyword="ApplicatorID" Name="Applicator ID"
+(300A,0109) VERS="4" VR="CS" VM="1" Keyword="ApplicatorType" Name="Applicator Type"
+(300A,010A) VERS="4" VR="LO" VM="1" Keyword="ApplicatorDescription" Name="Applicator Description"
+(300A,010C) VERS="4" VR="DS" VM="1" Keyword="CumulativeDoseReferenceCoefficient" Name="Cumulative Dose Reference Coefficient"
+(300A,010E) VERS="4" VR="DS" VM="1" Keyword="FinalCumulativeMetersetWeight" Name="Final Cumulative Meterset Weight"
+(300A,0110) VERS="4" VR="IS" VM="1" Keyword="NumberOfControlPoints" Name="Number of Control Points"
+(300A,0111) VERS="4" VR="SQ" VM="1" Keyword="ControlPointSequence" Name="Control Point Sequence"
+(300A,0112) VERS="4" VR="IS" VM="1" Keyword="ControlPointIndex" Name="Control Point Index"
+(300A,0114) VERS="4" VR="DS" VM="1" Keyword="NominalBeamEnergy" Name="Nominal Beam Energy"
+(300A,0115) VERS="4" VR="DS" VM="1" Keyword="DoseRateSet" Name="Dose Rate Set"
+(300A,0116) VERS="4" VR="SQ" VM="1" Keyword="WedgePositionSequence" Name="Wedge Position Sequence"
+(300A,0118) VERS="4" VR="CS" VM="1" Keyword="WedgePosition" Name="Wedge Position"
+(300A,011A) VERS="4" VR="SQ" VM="1" Keyword="BeamLimitingDevicePositionSequence" Name="Beam Limiting Device Position Sequence"
+(300A,011C) VERS="4" VR="DS" VM="2-2n" Keyword="LeafJawPositions" Name="Leaf/Jaw Positions"
+(300A,011E) VERS="4" VR="DS" VM="1" Keyword="GantryAngle" Name="Gantry Angle"
+(300A,011F) VERS="4" VR="CS" VM="1" Keyword="GantryRotationDirection" Name="Gantry Rotation Direction"
+(300A,0120) VERS="4" VR="DS" VM="1" Keyword="BeamLimitingDeviceAngle" Name="Beam Limiting Device Angle"
+(300A,0121) VERS="4" VR="CS" VM="1" Keyword="BeamLimitingDeviceRotationDirection" Name="Beam Limiting Device Rotation Direction"
+(300A,0122) VERS="4" VR="DS" VM="1" Keyword="PatientSupportAngle" Name="Patient Support Angle"
+(300A,0123) VERS="4" VR="CS" VM="1" Keyword="PatientSupportRotationDirection" Name="Patient Support Rotation Direction"
+(300A,0124) VERS="4" VR="DS" VM="1" Keyword="TableTopEccentricAxisDistance" Name="Table Top Eccentric Axis Distance"
+(300A,0125) VERS="4" VR="DS" VM="1" Keyword="TableTopEccentricAngle" Name="Table Top Eccentric Angle"
+(300A,0126) VERS="4" VR="CS" VM="1" Keyword="TableTopEccentricRotationDirection" Name="Table Top Eccentric Rotation Direction"
+(300A,0128) VERS="4" VR="DS" VM="1" Keyword="TableTopVerticalPosition" Name="Table Top Vertical Position"
+(300A,0129) VERS="4" VR="DS" VM="1" Keyword="TableTopLongitudinalPosition" Name="Table Top Longitudinal Position"
+(300A,012A) VERS="4" VR="DS" VM="1" Keyword="TableTopLateralPosition" Name="Table Top Lateral Position"
+(300A,012C) VERS="4" VR="DS" VM="3" Keyword="IsocenterPosition" Name="Isocenter Position"
+(300A,012E) VERS="4" VR="DS" VM="3" Keyword="SurfaceEntryPoint" Name="Surface Entry Point"
+(300A,0130) VERS="4" VR="DS" VM="1" Keyword="SourceToSurfaceDistance" Name="Source to Surface Distance"
+(300A,0134) VERS="4" VR="DS" VM="1" Keyword="CumulativeMetersetWeight" Name="Cumulative Meterset Weight"
+(300A,0140) VERS="4" VR="FL" VM="1" Keyword="TableTopPitchAngle" Name="Table Top Pitch Angle"
+(300A,0142) VERS="4" VR="CS" VM="1" Keyword="TableTopPitchRotationDirection" Name="Table Top Pitch Rotation Direction"
+(300A,0144) VERS="4" VR="FL" VM="1" Keyword="TableTopRollAngle" Name="Table Top Roll Angle"
+(300A,0146) VERS="4" VR="CS" VM="1" Keyword="TableTopRollRotationDirection" Name="Table Top Roll Rotation Direction"
+(300A,0148) VERS="4" VR="FL" VM="1" Keyword="HeadFixationAngle" Name="Head Fixation Angle"
+(300A,014A) VERS="4" VR="FL" VM="1" Keyword="GantryPitchAngle" Name="Gantry Pitch Angle"
+(300A,014C) VERS="4" VR="CS" VM="1" Keyword="GantryPitchRotationDirection" Name="Gantry Pitch Rotation Direction"
+(300A,014E) VERS="4" VR="FL" VM="1" Keyword="GantryPitchAngleTolerance" Name="Gantry Pitch Angle Tolerance"
+(300A,0180) VERS="4" VR="SQ" VM="1" Keyword="PatientSetupSequence" Name="Patient Setup Sequence"
+(300A,0182) VERS="4" VR="IS" VM="1" Keyword="PatientSetupNumber" Name="Patient Setup Number"
+(300A,0183) VERS="4" VR="LO" VM="1" Keyword="PatientSetupLabel" Name="Patient Setup Label"
+(300A,0184) VERS="4" VR="LO" VM="1" Keyword="PatientAdditionalPosition" Name="Patient Additional Position"
+(300A,0190) VERS="4" VR="SQ" VM="1" Keyword="FixationDeviceSequence" Name="Fixation Device Sequence"
+(300A,0192) VERS="4" VR="CS" VM="1" Keyword="FixationDeviceType" Name="Fixation Device Type"
+(300A,0194) VERS="4" VR="SH" VM="1" Keyword="FixationDeviceLabel" Name="Fixation Device Label"
+(300A,0196) VERS="4" VR="ST" VM="1" Keyword="FixationDeviceDescription" Name="Fixation Device Description"
+(300A,0198) VERS="4" VR="SH" VM="1" Keyword="FixationDevicePosition" Name="Fixation Device Position"
+(300A,0199) VERS="4" VR="FL" VM="1" Keyword="FixationDevicePitchAngle" Name="Fixation Device Pitch Angle"
+(300A,019A) VERS="4" VR="FL" VM="1" Keyword="FixationDeviceRollAngle" Name="Fixation Device Roll Angle"
+(300A,01A0) VERS="4" VR="SQ" VM="1" Keyword="ShieldingDeviceSequence" Name="Shielding Device Sequence"
+(300A,01A2) VERS="4" VR="CS" VM="1" Keyword="ShieldingDeviceType" Name="Shielding Device Type"
+(300A,01A4) VERS="4" VR="SH" VM="1" Keyword="ShieldingDeviceLabel" Name="Shielding Device Label"
+(300A,01A6) VERS="4" VR="ST" VM="1" Keyword="ShieldingDeviceDescription" Name="Shielding Device Description"
+(300A,01A8) VERS="4" VR="SH" VM="1" Keyword="ShieldingDevicePosition" Name="Shielding Device Position"
+(300A,01B0) VERS="4" VR="CS" VM="1" Keyword="SetupTechnique" Name="Setup Technique"
+(300A,01B2) VERS="4" VR="ST" VM="1" Keyword="SetupTechniqueDescription" Name="Setup Technique Description"
+(300A,01B4) VERS="4" VR="SQ" VM="1" Keyword="SetupDeviceSequence" Name="Setup Device Sequence"
+(300A,01B6) VERS="4" VR="CS" VM="1" Keyword="SetupDeviceType" Name="Setup Device Type"
+(300A,01B8) VERS="4" VR="SH" VM="1" Keyword="SetupDeviceLabel" Name="Setup Device Label"
+(300A,01BA) VERS="4" VR="ST" VM="1" Keyword="SetupDeviceDescription" Name="Setup Device Description"
+(300A,01BC) VERS="4" VR="DS" VM="1" Keyword="SetupDeviceParameter" Name="Setup Device Parameter"
+(300A,01D0) VERS="4" VR="ST" VM="1" Keyword="SetupReferenceDescription" Name="Setup Reference Description"
+(300A,01D2) VERS="4" VR="DS" VM="1" Keyword="TableTopVerticalSetupDisplacement" Name="Table Top Vertical Setup Displacement"
+(300A,01D4) VERS="4" VR="DS" VM="1" Keyword="TableTopLongitudinalSetupDisplacement" Name="Table Top Longitudinal Setup Displacement"
+(300A,01D6) VERS="4" VR="DS" VM="1" Keyword="TableTopLateralSetupDisplacement" Name="Table Top Lateral Setup Displacement"
+(300A,0200) VERS="4" VR="CS" VM="1" Keyword="BrachyTreatmentTechnique" Name="Brachy Treatment Technique"
+(300A,0202) VERS="4" VR="CS" VM="1" Keyword="BrachyTreatmentType" Name="Brachy Treatment Type"
+(300A,0206) VERS="4" VR="SQ" VM="1" Keyword="TreatmentMachineSequence" Name="Treatment Machine Sequence"
+(300A,0210) VERS="4" VR="SQ" VM="1" Keyword="SourceSequence" Name="Source Sequence"
+(300A,0212) VERS="4" VR="IS" VM="1" Keyword="SourceNumber" Name="Source Number"
+(300A,0214) VERS="4" VR="CS" VM="1" Keyword="SourceType" Name="Source Type"
+(300A,0216) VERS="4" VR="LO" VM="1" Keyword="SourceManufacturer" Name="Source Manufacturer"
+(300A,0218) VERS="4" VR="DS" VM="1" Keyword="ActiveSourceDiameter" Name="Active Source Diameter"
+(300A,021A) VERS="4" VR="DS" VM="1" Keyword="ActiveSourceLength" Name="Active Source Length"
+(300A,0222) VERS="4" VR="DS" VM="1" Keyword="SourceEncapsulationNominalThickness" Name="Source Encapsulation Nominal Thickness"
+(300A,0224) VERS="4" VR="DS" VM="1" Keyword="SourceEncapsulationNominalTransmission" Name="Source Encapsulation Nominal Transmission"
+(300A,0226) VERS="4" VR="LO" VM="1" Keyword="SourceIsotopeName" Name="Source Isotope Name"
+(300A,0228) VERS="4" VR="DS" VM="1" Keyword="SourceIsotopeHalfLife" Name="Source Isotope Half Life"
+(300A,0229) VERS="4" VR="CS" VM="1" Keyword="SourceStrengthUnits" Name="Source Strength Units"
+(300A,022A) VERS="4" VR="DS" VM="1" Keyword="ReferenceAirKermaRate" Name="Reference Air Kerma Rate"
+(300A,022B) VERS="4" VR="DS" VM="1" Keyword="SourceStrength" Name="Source Strength"
+(300A,022C) VERS="4" VR="DA" VM="1" Keyword="SourceStrengthReferenceDate" Name="Source Strength Reference Date"
+(300A,022E) VERS="4" VR="TM" VM="1" Keyword="SourceStrengthReferenceTime" Name="Source Strength Reference Time"
+(300A,0230) VERS="4" VR="SQ" VM="1" Keyword="ApplicationSetupSequence" Name="Application Setup Sequence"
+(300A,0232) VERS="4" VR="CS" VM="1" Keyword="ApplicationSetupType" Name="Application Setup Type"
+(300A,0234) VERS="4" VR="IS" VM="1" Keyword="ApplicationSetupNumber" Name="Application Setup Number"
+(300A,0236) VERS="4" VR="LO" VM="1" Keyword="ApplicationSetupName" Name="Application Setup Name"
+(300A,0238) VERS="4" VR="LO" VM="1" Keyword="ApplicationSetupManufacturer" Name="Application Setup Manufacturer"
+(300A,0240) VERS="4" VR="IS" VM="1" Keyword="TemplateNumber" Name="Template Number"
+(300A,0242) VERS="4" VR="SH" VM="1" Keyword="TemplateType" Name="Template Type"
+(300A,0244) VERS="4" VR="LO" VM="1" Keyword="TemplateName" Name="Template Name"
+(300A,0250) VERS="4" VR="DS" VM="1" Keyword="TotalReferenceAirKerma" Name="Total Reference Air Kerma"
+(300A,0260) VERS="4" VR="SQ" VM="1" Keyword="BrachyAccessoryDeviceSequence" Name="Brachy Accessory Device Sequence"
+(300A,0262) VERS="4" VR="IS" VM="1" Keyword="BrachyAccessoryDeviceNumber" Name="Brachy Accessory Device Number"
+(300A,0263) VERS="4" VR="SH" VM="1" Keyword="BrachyAccessoryDeviceID" Name="Brachy Accessory Device ID"
+(300A,0264) VERS="4" VR="CS" VM="1" Keyword="BrachyAccessoryDeviceType" Name="Brachy Accessory Device Type"
+(300A,0266) VERS="4" VR="LO" VM="1" Keyword="BrachyAccessoryDeviceName" Name="Brachy Accessory Device Name"
+(300A,026A) VERS="4" VR="DS" VM="1" Keyword="BrachyAccessoryDeviceNominalThickness" Name="Brachy Accessory Device Nominal Thickness"
+(300A,026C) VERS="4" VR="DS" VM="1" Keyword="BrachyAccessoryDeviceNominalTransmission" Name="Brachy Accessory Device Nominal Transmission"
+(300A,0280) VERS="4" VR="SQ" VM="1" Keyword="ChannelSequence" Name="Channel Sequence"
+(300A,0282) VERS="4" VR="IS" VM="1" Keyword="ChannelNumber" Name="Channel Number"
+(300A,0284) VERS="4" VR="DS" VM="1" Keyword="ChannelLength" Name="Channel Length"
+(300A,0286) VERS="4" VR="DS" VM="1" Keyword="ChannelTotalTime" Name="Channel Total Time"
+(300A,0288) VERS="4" VR="CS" VM="1" Keyword="SourceMovementType" Name="Source Movement Type"
+(300A,028A) VERS="4" VR="IS" VM="1" Keyword="NumberOfPulses" Name="Number of Pulses"
+(300A,028C) VERS="4" VR="DS" VM="1" Keyword="PulseRepetitionInterval" Name="Pulse Repetition Interval"
+(300A,0290) VERS="4" VR="IS" VM="1" Keyword="SourceApplicatorNumber" Name="Source Applicator Number"
+(300A,0291) VERS="4" VR="SH" VM="1" Keyword="SourceApplicatorID" Name="Source Applicator ID"
+(300A,0292) VERS="4" VR="CS" VM="1" Keyword="SourceApplicatorType" Name="Source Applicator Type"
+(300A,0294) VERS="4" VR="LO" VM="1" Keyword="SourceApplicatorName" Name="Source Applicator Name"
+(300A,0296) VERS="4" VR="DS" VM="1" Keyword="SourceApplicatorLength" Name="Source Applicator Length"
+(300A,0298) VERS="4" VR="LO" VM="1" Keyword="SourceApplicatorManufacturer" Name="Source Applicator Manufacturer"
+(300A,029C) VERS="4" VR="DS" VM="1" Keyword="SourceApplicatorWallNominalThickness" Name="Source Applicator Wall Nominal Thickness"
+(300A,029E) VERS="4" VR="DS" VM="1" Keyword="SourceApplicatorWallNominalTransmission" Name="Source Applicator Wall Nominal Transmission"
+(300A,02A0) VERS="4" VR="DS" VM="1" Keyword="SourceApplicatorStepSize" Name="Source Applicator Step Size"
+(300A,02A2) VERS="4" VR="IS" VM="1" Keyword="TransferTubeNumber" Name="Transfer Tube Number"
+(300A,02A4) VERS="4" VR="DS" VM="1" Keyword="TransferTubeLength" Name="Transfer Tube Length"
+(300A,02B0) VERS="4" VR="SQ" VM="1" Keyword="ChannelShieldSequence" Name="Channel Shield Sequence"
+(300A,02B2) VERS="4" VR="IS" VM="1" Keyword="ChannelShieldNumber" Name="Channel Shield Number"
+(300A,02B3) VERS="4" VR="SH" VM="1" Keyword="ChannelShieldID" Name="Channel Shield ID"
+(300A,02B4) VERS="4" VR="LO" VM="1" Keyword="ChannelShieldName" Name="Channel Shield Name"
+(300A,02B8) VERS="4" VR="DS" VM="1" Keyword="ChannelShieldNominalThickness" Name="Channel Shield Nominal Thickness"
+(300A,02BA) VERS="4" VR="DS" VM="1" Keyword="ChannelShieldNominalTransmission" Name="Channel Shield Nominal Transmission"
+(300A,02C8) VERS="4" VR="DS" VM="1" Keyword="FinalCumulativeTimeWeight" Name="Final Cumulative Time Weight"
+(300A,02D0) VERS="4" VR="SQ" VM="1" Keyword="BrachyControlPointSequence" Name="Brachy Control Point Sequence"
+(300A,02D2) VERS="4" VR="DS" VM="1" Keyword="ControlPointRelativePosition" Name="Control Point Relative Position"
+(300A,02D4) VERS="4" VR="DS" VM="3" Keyword="ControlPoint3DPosition" Name="Control Point 3D Position"
+(300A,02D6) VERS="4" VR="DS" VM="1" Keyword="CumulativeTimeWeight" Name="Cumulative Time Weight"
+(300A,02E0) VERS="4" VR="CS" VM="1" Keyword="CompensatorDivergence" Name="Compensator Divergence"
+(300A,02E1) VERS="4" VR="CS" VM="1" Keyword="CompensatorMountingPosition" Name="Compensator Mounting Position"
+(300A,02E2) VERS="4" VR="DS" VM="1-n" Keyword="SourceToCompensatorDistance" Name="Source to Compensator Distance"
+(300A,02E3) VERS="4" VR="FL" VM="1" Keyword="TotalCompensatorTrayWaterEquivalentThickness" Name="Total Compensator Tray Water-Equivalent Thickness"
+(300A,02E4) VERS="4" VR="FL" VM="1" Keyword="IsocenterToCompensatorTrayDistance" Name="Isocenter to Compensator Tray Distance"
+(300A,02E5) VERS="4" VR="FL" VM="1" Keyword="CompensatorColumnOffset" Name="Compensator Column Offset"
+(300A,02E6) VERS="4" VR="FL" VM="1-n" Keyword="IsocenterToCompensatorDistances" Name="Isocenter to Compensator Distances"
+(300A,02E7) VERS="4" VR="FL" VM="1" Keyword="CompensatorRelativeStoppingPowerRatio" Name="Compensator Relative Stopping Power Ratio"
+(300A,02E8) VERS="4" VR="FL" VM="1" Keyword="CompensatorMillingToolDiameter" Name="Compensator Milling Tool Diameter"
+(300A,02EA) VERS="4" VR="SQ" VM="1" Keyword="IonRangeCompensatorSequence" Name="Ion Range Compensator Sequence"
+(300A,02EB) VERS="4" VR="LT" VM="1" Keyword="CompensatorDescription" Name="Compensator Description"
+(300A,0302) VERS="4" VR="IS" VM="1" Keyword="RadiationMassNumber" Name="Radiation Mass Number"
+(300A,0304) VERS="4" VR="IS" VM="1" Keyword="RadiationAtomicNumber" Name="Radiation Atomic Number"
+(300A,0306) VERS="4" VR="SS" VM="1" Keyword="RadiationChargeState" Name="Radiation Charge State"
+(300A,0308) VERS="4" VR="CS" VM="1" Keyword="ScanMode" Name="Scan Mode"
+(300A,030A) VERS="4" VR="FL" VM="2" Keyword="VirtualSourceAxisDistances" Name="Virtual Source-Axis Distances"
+(300A,030C) VERS="4" VR="SQ" VM="1" Keyword="SnoutSequence" Name="Snout Sequence"
+(300A,030D) VERS="4" VR="FL" VM="1" Keyword="SnoutPosition" Name="Snout Position"
+(300A,030F) VERS="4" VR="SH" VM="1" Keyword="SnoutID" Name="Snout ID"
+(300A,0312) VERS="4" VR="IS" VM="1" Keyword="NumberOfRangeShifters" Name="Number of Range Shifters"
+(300A,0314) VERS="4" VR="SQ" VM="1" Keyword="RangeShifterSequence" Name="Range Shifter Sequence"
+(300A,0316) VERS="4" VR="IS" VM="1" Keyword="RangeShifterNumber" Name="Range Shifter Number"
+(300A,0318) VERS="4" VR="SH" VM="1" Keyword="RangeShifterID" Name="Range Shifter ID"
+(300A,0320) VERS="4" VR="CS" VM="1" Keyword="RangeShifterType" Name="Range Shifter Type"
+(300A,0322) VERS="4" VR="LO" VM="1" Keyword="RangeShifterDescription" Name="Range Shifter Description"
+(300A,0330) VERS="4" VR="IS" VM="1" Keyword="NumberOfLateralSpreadingDevices" Name="Number of Lateral Spreading Devices"
+(300A,0332) VERS="4" VR="SQ" VM="1" Keyword="LateralSpreadingDeviceSequence" Name="Lateral Spreading Device Sequence"
+(300A,0334) VERS="4" VR="IS" VM="1" Keyword="LateralSpreadingDeviceNumber" Name="Lateral Spreading Device Number"
+(300A,0336) VERS="4" VR="SH" VM="1" Keyword="LateralSpreadingDeviceID" Name="Lateral Spreading Device ID"
+(300A,0338) VERS="4" VR="CS" VM="1" Keyword="LateralSpreadingDeviceType" Name="Lateral Spreading Device Type"
+(300A,033A) VERS="4" VR="LO" VM="1" Keyword="LateralSpreadingDeviceDescription" Name="Lateral Spreading Device Description"
+(300A,033C) VERS="4" VR="FL" VM="1" Keyword="LateralSpreadingDeviceWaterEquivalentThickness" Name="Lateral Spreading Device Water Equivalent Thickness"
+(300A,0340) VERS="4" VR="IS" VM="1" Keyword="NumberOfRangeModulators" Name="Number of Range Modulators"
+(300A,0342) VERS="4" VR="SQ" VM="1" Keyword="RangeModulatorSequence" Name="Range Modulator Sequence"
+(300A,0344) VERS="4" VR="IS" VM="1" Keyword="RangeModulatorNumber" Name="Range Modulator Number"
+(300A,0346) VERS="4" VR="SH" VM="1" Keyword="RangeModulatorID" Name="Range Modulator ID"
+(300A,0348) VERS="4" VR="CS" VM="1" Keyword="RangeModulatorType" Name="Range Modulator Type"
+(300A,034A) VERS="4" VR="LO" VM="1" Keyword="RangeModulatorDescription" Name="Range Modulator Description"
+(300A,034C) VERS="4" VR="SH" VM="1" Keyword="BeamCurrentModulationID" Name="Beam Current Modulation ID"
+(300A,0350) VERS="4" VR="CS" VM="1" Keyword="PatientSupportType" Name="Patient Support Type"
+(300A,0352) VERS="4" VR="SH" VM="1" Keyword="PatientSupportID" Name="Patient Support ID"
+(300A,0354) VERS="4" VR="LO" VM="1" Keyword="PatientSupportAccessoryCode" Name="Patient Support Accessory Code"
+(300A,0356) VERS="4" VR="FL" VM="1" Keyword="FixationLightAzimuthalAngle" Name="Fixation Light Azimuthal Angle"
+(300A,0358) VERS="4" VR="FL" VM="1" Keyword="FixationLightPolarAngle" Name="Fixation Light Polar Angle"
+(300A,035A) VERS="4" VR="FL" VM="1" Keyword="MetersetRate" Name="Meterset Rate"
+(300A,0360) VERS="4" VR="SQ" VM="1" Keyword="RangeShifterSettingsSequence" Name="Range Shifter Settings Sequence"
+(300A,0362) VERS="4" VR="LO" VM="1" Keyword="RangeShifterSetting" Name="Range Shifter Setting"
+(300A,0364) VERS="4" VR="FL" VM="1" Keyword="IsocenterToRangeShifterDistance" Name="Isocenter to Range Shifter Distance"
+(300A,0366) VERS="4" VR="FL" VM="1" Keyword="RangeShifterWaterEquivalentThickness" Name="Range Shifter Water Equivalent Thickness"
+(300A,0370) VERS="4" VR="SQ" VM="1" Keyword="LateralSpreadingDeviceSettingsSequence" Name="Lateral Spreading Device Settings Sequence"
+(300A,0372) VERS="4" VR="LO" VM="1" Keyword="LateralSpreadingDeviceSetting" Name="Lateral Spreading Device Setting"
+(300A,0374) VERS="4" VR="FL" VM="1" Keyword="IsocenterToLateralSpreadingDeviceDistance" Name="Isocenter to Lateral Spreading Device Distance"
+(300A,0380) VERS="4" VR="SQ" VM="1" Keyword="RangeModulatorSettingsSequence" Name="Range Modulator Settings Sequence"
+(300A,0382) VERS="4" VR="FL" VM="1" Keyword="RangeModulatorGatingStartValue" Name="Range Modulator Gating Start Value"
+(300A,0384) VERS="4" VR="FL" VM="1" Keyword="RangeModulatorGatingStopValue" Name="Range Modulator Gating Stop Value"
+(300A,0386) VERS="4" VR="FL" VM="1" Keyword="RangeModulatorGatingStartWaterEquivalentThickness" Name="Range Modulator Gating Start Water Equivalent Thickness"
+(300A,0388) VERS="4" VR="FL" VM="1" Keyword="RangeModulatorGatingStopWaterEquivalentThickness" Name="Range Modulator Gating Stop Water Equivalent Thickness"
+(300A,038A) VERS="4" VR="FL" VM="1" Keyword="IsocenterToRangeModulatorDistance" Name="Isocenter to Range Modulator Distance"
+(300A,0390) VERS="4" VR="SH" VM="1" Keyword="ScanSpotTuneID" Name="Scan Spot Tune ID"
+(300A,0392) VERS="4" VR="IS" VM="1" Keyword="NumberOfScanSpotPositions" Name="Number of Scan Spot Positions"
+(300A,0394) VERS="4" VR="FL" VM="1-n" Keyword="ScanSpotPositionMap" Name="Scan Spot Position Map"
+(300A,0396) VERS="4" VR="FL" VM="1-n" Keyword="ScanSpotMetersetWeights" Name="Scan Spot Meterset Weights"
+(300A,0398) VERS="4" VR="FL" VM="2" Keyword="ScanningSpotSize" Name="Scanning Spot Size"
+(300A,039A) VERS="4" VR="IS" VM="1" Keyword="NumberOfPaintings" Name="Number of Paintings"
+(300A,03A0) VERS="4" VR="SQ" VM="1" Keyword="IonToleranceTableSequence" Name="Ion Tolerance Table Sequence"
+(300A,03A2) VERS="4" VR="SQ" VM="1" Keyword="IonBeamSequence" Name="Ion Beam Sequence"
+(300A,03A4) VERS="4" VR="SQ" VM="1" Keyword="IonBeamLimitingDeviceSequence" Name="Ion Beam Limiting Device Sequence"
+(300A,03A6) VERS="4" VR="SQ" VM="1" Keyword="IonBlockSequence" Name="Ion Block Sequence"
+(300A,03A8) VERS="4" VR="SQ" VM="1" Keyword="IonControlPointSequence" Name="Ion Control Point Sequence"
+(300A,03AA) VERS="4" VR="SQ" VM="1" Keyword="IonWedgeSequence" Name="Ion Wedge Sequence"
+(300A,03AC) VERS="4" VR="SQ" VM="1" Keyword="IonWedgePositionSequence" Name="Ion Wedge Position Sequence"
+(300A,0401) VERS="4" VR="SQ" VM="1" Keyword="ReferencedSetupImageSequence" Name="Referenced Setup Image Sequence"
+(300A,0402) VERS="4" VR="ST" VM="1" Keyword="SetupImageComment" Name="Setup Image Comment"
+(300A,0410) VERS="4" VR="SQ" VM="1" Keyword="MotionSynchronizationSequence" Name="Motion Synchronization Sequence"
+(300A,0412) VERS="4" VR="FL" VM="3" Keyword="ControlPointOrientation" Name="Control Point Orientation"
+(300A,0420) VERS="4" VR="SQ" VM="1" Keyword="GeneralAccessorySequence" Name="General Accessory Sequence"
+(300A,0421) VERS="4" VR="SH" VM="1" Keyword="GeneralAccessoryID" Name="General Accessory ID"
+(300A,0422) VERS="4" VR="ST" VM="1" Keyword="GeneralAccessoryDescription" Name="General Accessory Description"
+(300A,0423) VERS="4" VR="CS" VM="1" Keyword="GeneralAccessoryType" Name="General Accessory Type"
+(300A,0424) VERS="4" VR="IS" VM="1" Keyword="GeneralAccessoryNumber" Name="General Accessory Number"
+(300A,0431) VERS="4" VR="SQ" VM="1" Keyword="ApplicatorGeometrySequence" Name="Applicator Geometry Sequence"
+(300A,0432) VERS="4" VR="CS" VM="1" Keyword="ApplicatorApertureShape" Name="Applicator Aperture Shape"
+(300A,0433) VERS="4" VR="FL" VM="1" Keyword="ApplicatorOpening" Name="Applicator Opening"
+(300A,0434) VERS="4" VR="FL" VM="1" Keyword="ApplicatorOpeningX" Name="Applicator Opening X"
+(300A,0435) VERS="4" VR="FL" VM="1" Keyword="ApplicatorOpeningY" Name="Applicator Opening Y"
+(300A,0436) VERS="4" VR="FL" VM="1" Keyword="SourceToApplicatorMountingPositionDistance" Name="Source to Applicator Mounting Position Distance"
+(300C,0000) VERS="3" VR="UL" VM="1" Keyword="RTRelationshipGroupLength" Name="RTRelationshipGroupLength"
+(300C,0002) VERS="4" VR="SQ" VM="1" Keyword="ReferencedRTPlanSequence" Name="Referenced RT Plan Sequence"
+(300C,0004) VERS="4" VR="SQ" VM="1" Keyword="ReferencedBeamSequence" Name="Referenced Beam Sequence"
+(300C,0006) VERS="4" VR="IS" VM="1" Keyword="ReferencedBeamNumber" Name="Referenced Beam Number"
+(300C,0007) VERS="4" VR="IS" VM="1" Keyword="ReferencedReferenceImageNumber" Name="Referenced Reference Image Number"
+(300C,0008) VERS="4" VR="DS" VM="1" Keyword="StartCumulativeMetersetWeight" Name="Start Cumulative Meterset Weight"
+(300C,0009) VERS="4" VR="DS" VM="1" Keyword="EndCumulativeMetersetWeight" Name="End Cumulative Meterset Weight"
+(300C,000A) VERS="4" VR="SQ" VM="1" Keyword="ReferencedBrachyApplicationSetupSequence" Name="Referenced Brachy Application Setup Sequence"
+(300C,000C) VERS="4" VR="IS" VM="1" Keyword="ReferencedBrachyApplicationSetupNumber" Name="Referenced Brachy Application Setup Number"
+(300C,000E) VERS="4" VR="IS" VM="1" Keyword="ReferencedSourceNumber" Name="Referenced Source Number"
+(300C,0020) VERS="4" VR="SQ" VM="1" Keyword="ReferencedFractionGroupSequence" Name="Referenced Fraction Group Sequence"
+(300C,0022) VERS="4" VR="IS" VM="1" Keyword="ReferencedFractionGroupNumber" Name="Referenced Fraction Group Number"
+(300C,0040) VERS="4" VR="SQ" VM="1" Keyword="ReferencedVerificationImageSequence" Name="Referenced Verification Image Sequence"
+(300C,0042) VERS="4" VR="SQ" VM="1" Keyword="ReferencedReferenceImageSequence" Name="Referenced Reference Image Sequence"
+(300C,0050) VERS="4" VR="SQ" VM="1" Keyword="ReferencedDoseReferenceSequence" Name="Referenced Dose Reference Sequence"
+(300C,0051) VERS="4" VR="IS" VM="1" Keyword="ReferencedDoseReferenceNumber" Name="Referenced Dose Reference Number"
+(300C,0055) VERS="4" VR="SQ" VM="1" Keyword="BrachyReferencedDoseReferenceSequence" Name="Brachy Referenced Dose Reference Sequence"
+(300C,0060) VERS="4" VR="SQ" VM="1" Keyword="ReferencedStructureSetSequence" Name="Referenced Structure Set Sequence"
+(300C,006A) VERS="4" VR="IS" VM="1" Keyword="ReferencedPatientSetupNumber" Name="Referenced Patient Setup Number"
+(300C,0080) VERS="4" VR="SQ" VM="1" Keyword="ReferencedDoseSequence" Name="Referenced Dose Sequence"
+(300C,00A0) VERS="4" VR="IS" VM="1" Keyword="ReferencedToleranceTableNumber" Name="Referenced Tolerance Table Number"
+(300C,00B0) VERS="4" VR="SQ" VM="1" Keyword="ReferencedBolusSequence" Name="Referenced Bolus Sequence"
+(300C,00C0) VERS="4" VR="IS" VM="1" Keyword="ReferencedWedgeNumber" Name="Referenced Wedge Number"
+(300C,00D0) VERS="4" VR="IS" VM="1" Keyword="ReferencedCompensatorNumber" Name="Referenced Compensator Number"
+(300C,00E0) VERS="4" VR="IS" VM="1" Keyword="ReferencedBlockNumber" Name="Referenced Block Number"
+(300C,00F0) VERS="4" VR="IS" VM="1" Keyword="ReferencedControlPointIndex" Name="Referenced Control Point Index"
+(300C,00F2) VERS="4" VR="SQ" VM="1" Keyword="ReferencedControlPointSequence" Name="Referenced Control Point Sequence"
+(300C,00F4) VERS="4" VR="IS" VM="1" Keyword="ReferencedStartControlPointIndex" Name="Referenced Start Control Point Index"
+(300C,00F6) VERS="4" VR="IS" VM="1" Keyword="ReferencedStopControlPointIndex" Name="Referenced Stop Control Point Index"
+(300C,0100) VERS="4" VR="IS" VM="1" Keyword="ReferencedRangeShifterNumber" Name="Referenced Range Shifter Number"
+(300C,0102) VERS="4" VR="IS" VM="1" Keyword="ReferencedLateralSpreadingDeviceNumber" Name="Referenced Lateral Spreading Device Number"
+(300C,0104) VERS="4" VR="IS" VM="1" Keyword="ReferencedRangeModulatorNumber" Name="Referenced Range Modulator Number"
+(300E,0000) VERS="3" VR="UL" VM="1" Keyword="RTApprovalGroupLength" Name="RTApprovalGroupLength"
+(300E,0002) VERS="4" VR="CS" VM="1" Keyword="ApprovalStatus" Name="Approval Status"
+(300E,0004) VERS="4" VR="DA" VM="1" Keyword="ReviewDate" Name="Review Date"
+(300E,0005) VERS="4" VR="TM" VM="1" Keyword="ReviewTime" Name="Review Time"
+(300E,0008) VERS="4" VR="PN" VM="1" Keyword="ReviewerName" Name="Reviewer Name"
+(4000,0000) VERS="2" VR="UL" VM="1" Keyword="TextGroupLength" Name="Text Group Length"
+(4000,0010) VERS="4RET" VR="LT" VM="1" Keyword="Arbitrary" Name="Arbitrary"
+(4000,4000) VERS="4RET" VR="LT" VM="1" Keyword="TextComments" Name="Text Comments"
+(4008,0000) VERS="3" VR="UL" VM="1" Keyword="ResultsGroupLength" Name="Results Group Length"
+(4008,0040) VERS="4RET" VR="SH" VM="1" Keyword="ResultsID" Name="Results ID"
+(4008,0042) VERS="4RET" VR="LO" VM="1" Keyword="ResultsIDIssuer" Name="Results ID Issuer"
+(4008,0050) VERS="4RET" VR="SQ" VM="1" Keyword="ReferencedInterpretationSequence" Name="Referenced Interpretation Sequence"
+(4008,00FF) VERS="4RET" VR="CS" VM="1" Keyword="ReportProductionStatusTrial" Name="Report Production Status (Trial)"
+(4008,0100) VERS="4RET" VR="DA" VM="1" Keyword="InterpretationRecordedDate" Name="Interpretation Recorded Date"
+(4008,0101) VERS="4RET" VR="TM" VM="1" Keyword="InterpretationRecordedTime" Name="Interpretation Recorded Time"
+(4008,0102) VERS="4RET" VR="PN" VM="1" Keyword="InterpretationRecorder" Name="Interpretation Recorder"
+(4008,0103) VERS="4RET" VR="LO" VM="1" Keyword="ReferenceToRecordedSound" Name="Reference to Recorded Sound"
+(4008,0108) VERS="4RET" VR="DA" VM="1" Keyword="InterpretationTranscriptionDate" Name="Interpretation Transcription Date"
+(4008,0109) VERS="4RET" VR="TM" VM="1" Keyword="InterpretationTranscriptionTime" Name="Interpretation Transcription Time"
+(4008,010A) VERS="4RET" VR="PN" VM="1" Keyword="InterpretationTranscriber" Name="Interpretation Transcriber"
+(4008,010B) VERS="4RET" VR="ST" VM="1" Keyword="InterpretationText" Name="Interpretation Text"
+(4008,010C) VERS="4RET" VR="PN" VM="1" Keyword="InterpretationAuthor" Name="Interpretation Author"
+(4008,0111) VERS="4RET" VR="SQ" VM="1" Keyword="InterpretationApproverSequence" Name="Interpretation Approver Sequence"
+(4008,0112) VERS="4RET" VR="DA" VM="1" Keyword="InterpretationApprovalDate" Name="Interpretation Approval Date"
+(4008,0113) VERS="4RET" VR="TM" VM="1" Keyword="InterpretationApprovalTime" Name="Interpretation Approval Time"
+(4008,0114) VERS="4RET" VR="PN" VM="1" Keyword="PhysicianApprovingInterpretation" Name="Physician Approving Interpretation"
+(4008,0115) VERS="4RET" VR="LT" VM="1" Keyword="InterpretationDiagnosisDescription" Name="Interpretation Diagnosis Description"
+(4008,0117) VERS="4RET" VR="SQ" VM="1" Keyword="InterpretationDiagnosisCodeSequence" Name="Interpretation Diagnosis Code Sequence"
+(4008,0118) VERS="4RET" VR="SQ" VM="1" Keyword="ResultsDistributionListSequence" Name="Results Distribution List Sequence"
+(4008,0119) VERS="4RET" VR="PN" VM="1" Keyword="DistributionName" Name="Distribution Name"
+(4008,011A) VERS="4RET" VR="LO" VM="1" Keyword="DistributionAddress" Name="Distribution Address"
+(4008,0200) VERS="4RET" VR="SH" VM="1" Keyword="InterpretationID" Name="Interpretation ID"
+(4008,0202) VERS="4RET" VR="LO" VM="1" Keyword="InterpretationIDIssuer" Name="Interpretation ID Issuer"
+(4008,0210) VERS="4RET" VR="CS" VM="1" Keyword="InterpretationTypeID" Name="Interpretation Type ID"
+(4008,0212) VERS="4RET" VR="CS" VM="1" Keyword="InterpretationStatusID" Name="Interpretation Status ID"
+(4008,0300) VERS="4RET" VR="ST" VM="1" Keyword="Impressions" Name="Impressions"
+(4008,4000) VERS="4RET" VR="ST" VM="1 " Keyword="ResultsComments" Name="Results Comments"
+(4010,0001) VERS="4" VR="CS" VM="1" Keyword="LowEnergyDetectors" Name="Low Energy Detectors"
+(4010,0002) VERS="4" VR="CS" VM="1" Keyword="HighEnergyDetectors" Name="High Energy Detectors"
+(4010,0004) VERS="4" VR="SQ" VM="1" Keyword="DetectorGeometrySequence" Name="Detector Geometry Sequence"
+(4010,1001) VERS="4" VR="SQ" VM="1" Keyword="ThreatROIVoxelSequence" Name="Threat ROI Voxel Sequence"
+(4010,1004) VERS="4" VR="FL" VM="3" Keyword="ThreatROIBase" Name="Threat ROI Base"
+(4010,1005) VERS="4" VR="FL" VM="3" Keyword="ThreatROIExtents" Name="Threat ROI Extents "
+(4010,1006) VERS="4" VR="OB" VM="1" Keyword="ThreatROIBitmap" Name="Threat ROI Bitmap"
+(4010,1007) VERS="4" VR="SH" VM="1" Keyword="RouteSegmentID" Name="Route Segment ID"
+(4010,1008) VERS="4" VR="CS" VM="1" Keyword="GantryType" Name="Gantry Type"
+(4010,1009) VERS="4" VR="CS" VM="1" Keyword="OOIOwnerType" Name="OOI Owner Type"
+(4010,100A) VERS="4" VR="SQ" VM="1" Keyword="RouteSegmentSequence" Name="Route Segment Sequence"
+(4010,1010) VERS="4" VR="US" VM="1" Keyword="PotentialThreatObjectID" Name="Potential Threat Object ID"
+(4010,1011) VERS="4" VR="SQ" VM="1" Keyword="ThreatSequence" Name="Threat Sequence"
+(4010,1012) VERS="4" VR="CS" VM="1" Keyword="ThreatCategory" Name="Threat Category "
+(4010,1013) VERS="4" VR="LT" VM="1" Keyword="ThreatCategoryDescription" Name="Threat Category Description"
+(4010,1014) VERS="4" VR="CS" VM="1" Keyword="ATDAbilityAssessment" Name="ATD Ability Assessment"
+(4010,1015) VERS="4" VR="CS" VM="1" Keyword="ATDAssessmentFlag" Name="ATD Assessment Flag"
+(4010,1016) VERS="4" VR="FL" VM="1" Keyword="ATDAssessmentProbability" Name="ATD Assessment Probability"
+(4010,1017) VERS="4" VR="FL" VM="1" Keyword="Mass" Name="Mass"
+(4010,1018) VERS="4" VR="FL" VM="1" Keyword="Density" Name="Density"
+(4010,1019) VERS="4" VR="FL" VM="1" Keyword="ZEffective" Name="Z Effective"
+(4010,101A) VERS="4" VR="SH" VM="1" Keyword="BoardingPassID" Name="Boarding Pass ID"
+(4010,101B) VERS="4" VR="FL" VM="3" Keyword="CenterOfMass" Name="Center of Mass"
+(4010,101C) VERS="4" VR="FL" VM="3" Keyword="CenterOfPTO" Name="Center of PTO"
+(4010,101D) VERS="4" VR="FL" VM="6-n" Keyword="BoundingPolygon" Name="Bounding Polygon"
+(4010,101E) VERS="4" VR="SH" VM="1" Keyword="RouteSegmentStartLocationID" Name="Route Segment Start Location ID"
+(4010,101F) VERS="4" VR="SH" VM="1" Keyword="RouteSegmentEndLocationID" Name="Route Segment End Location ID"
+(4010,1020) VERS="4" VR="CS" VM="1" Keyword="RouteSegmentLocationIDType" Name="Route Segment Location ID Type"
+(4010,1021) VERS="4" VR="CS" VM="1-n" Keyword="AbortReason" Name="Abort Reason"
+(4010,1023) VERS="4" VR="FL" VM="1" Keyword="VolumeOfPTO" Name="Volume of PTO"
+(4010,1024) VERS="4" VR="CS" VM="1" Keyword="AbortFlag" Name="Abort Flag"
+(4010,1025) VERS="4" VR="DT" VM="1" Keyword="RouteSegmentStartTime" Name="Route Segment Start Time"
+(4010,1026) VERS="4" VR="DT" VM="1" Keyword="RouteSegmentEndTime" Name="Route Segment End Time"
+(4010,1027) VERS="4" VR="CS" VM="1" Keyword="TDRType" Name="TDR Type"
+(4010,1028) VERS="4" VR="CS" VM="1" Keyword="InternationalRouteSegment" Name="International Route Segment"
+(4010,1029) VERS="4" VR="LO" VM="1-n" Keyword="ThreatDetectionAlgorithmandVersion" Name="Threat Detection Algorithm and Version"
+(4010,102A) VERS="4" VR="SH" VM="1" Keyword="AssignedLocation" Name="Assigned Location "
+(4010,102B) VERS="4" VR="DT" VM="1" Keyword="AlarmDecisionTime" Name="Alarm Decision Time"
+(4010,1031) VERS="4" VR="CS" VM="1" Keyword="AlarmDecision" Name="Alarm Decision"
+(4010,1033) VERS="4" VR="US" VM="1" Keyword="NumberOfTotalObjects" Name="Number of Total Objects"
+(4010,1034) VERS="4" VR="US" VM="1" Keyword="NumberOfAlarmObjects" Name="Number of Alarm Objects"
+(4010,1037) VERS="4" VR="SQ" VM="1" Keyword="PTORepresentationSequence" Name="PTO Representation Sequence"
+(4010,1038) VERS="4" VR="SQ" VM="1" Keyword="ATDAssessmentSequence" Name="ATD Assessment Sequence"
+(4010,1039) VERS="4" VR="CS" VM="1" Keyword="TIPType" Name="TIP Type"
+(4010,103A) VERS="4" VR="CS" VM="1" Keyword="DICOSVersion" Name="DICOS Version"
+(4010,1041) VERS="4" VR="DT" VM="1" Keyword="OOIOwnerCreationTime" Name="OOI Owner Creation Time"
+(4010,1042) VERS="4" VR="CS" VM="1" Keyword="OOIType" Name="OOI Type"
+(4010,1043) VERS="4" VR="FL" VM="3" Keyword="OOISize" Name="OOI Size"
+(4010,1044) VERS="4" VR="CS" VM="1" Keyword="AcquisitionStatus" Name="Acquisition Status"
+(4010,1045) VERS="4" VR="SQ" VM="1" Keyword="BasisMaterialsCodeSequence" Name="Basis Materials Code Sequence"
+(4010,1046) VERS="4" VR="CS" VM="1" Keyword="PhantomType" Name="Phantom Type"
+(4010,1047) VERS="4" VR="SQ" VM="1" Keyword="OOIOwnerSequence" Name="OOI Owner Sequence"
+(4010,1048) VERS="4" VR="CS" VM="1" Keyword="ScanType" Name="Scan Type"
+(4010,1051) VERS="4" VR="LO" VM="1" Keyword="ItineraryID" Name="Itinerary ID"
+(4010,1052) VERS="4" VR="SH" VM="1" Keyword="ItineraryIDType" Name="Itinerary ID Type"
+(4010,1053) VERS="4" VR="LO" VM="1" Keyword="ItineraryIDAssigningAuthority" Name="Itinerary ID Assigning Authority"
+(4010,1054) VERS="4" VR="SH" VM="1" Keyword="RouteID" Name="Route ID"
+(4010,1055) VERS="4" VR="SH" VM="1" Keyword="RouteIDAssigningAuthority" Name="Route ID Assigning Authority"
+(4010,1056) VERS="4" VR="CS" VM="1" Keyword="InboundArrivalType" Name="Inbound Arrival Type"
+(4010,1058) VERS="4" VR="SH" VM="1" Keyword="CarrierID" Name="Carrier ID"
+(4010,1059) VERS="4" VR="CS" VM="1" Keyword="CarrierIDAssigningAuthority" Name="Carrier ID Assigning Authority"
+(4010,1060) VERS="4" VR="FL" VM="3" Keyword="SourceOrientation" Name="Source Orientation"
+(4010,1061) VERS="4" VR="FL" VM="3" Keyword="SourcePosition" Name="Source Position"
+(4010,1062) VERS="4" VR="FL" VM="1" Keyword="BeltHeight" Name="Belt Height"
+(4010,1064) VERS="4" VR="SQ" VM="1" Keyword="AlgorithmRoutingCodeSequence" Name="Algorithm Routing Code Sequence"
+(4010,1067) VERS="4" VR="CS" VM="1" Keyword="TransportClassification" Name="Transport Classification"
+(4010,1068) VERS="4" VR="LT" VM="1" Keyword="OOITypeDescriptor" Name="OOI Type Descriptor"
+(4010,1069) VERS="4" VR="FL" VM="1" Keyword="TotalProcessingTime" Name="Total Processing Time"
+(4010,106C) VERS="4" VR="OB" VM="1" Keyword="DetectorCalibrationData" Name="Detector Calibration Data"
+(4FFE,0001) VERS="4" VR="SQ" VM="1" Keyword="MACParametersSequence" Name="MAC Parameters Sequence"
+(50xx,0000) VERS="3" VR="UL" VM="1" Keyword="CurveGroupLength" Name="Curve Group Length"
+(50xx,0005) VERS="4RET" VR="US" VM="1" Keyword="CurveDimensions" Name="Curve Dimensions "
+(50xx,0010) VERS="4RET" VR="US" VM="1" Keyword="NumberOfPoints" Name="Number of Points "
+(50xx,0020) VERS="4RET" VR="CS" VM="1" Keyword="TypeOfData" Name="Type of Data"
+(50xx,0022) VERS="4RET" VR="LO" VM="1" Keyword="CurveDescription" Name="Curve Description"
+(50xx,0030) VERS="4RET" VR="SH" VM="1-n" Keyword="AxisUnits" Name="Axis Units "
+(50xx,0040) VERS="4RET" VR="SH" VM="1-n" Keyword="AxisLabels" Name="Axis Labels "
+(50xx,0103) VERS="4RET" VR="US" VM="1" Keyword="DataValueRepresentation" Name="Data Value Representation "
+(50xx,0104) VERS="4RET" VR="US" VM="1-n" Keyword="MinimumCoordinateValue" Name="Minimum Coordinate Value "
+(50xx,0105) VERS="4RET" VR="US" VM="1-n" Keyword="MaximumCoordinateValue" Name="Maximum Coordinate Value "
+(50xx,0106) VERS="4RET" VR="SH" VM="1-n" Keyword="CurveRange" Name="Curve Range"
+(50xx,0110) VERS="4RET" VR="US" VM="1-n" Keyword="CurveDataDescriptor" Name="Curve Data Descriptor"
+(50xx,0112) VERS="4RET" VR="US" VM="1-n" Keyword="CoordinateStartValue" Name="Coordinate Start Value"
+(50xx,0114) VERS="4RET" VR="US" VM="1-n" Keyword="CoordinateStepValue" Name="Coordinate Step Value"
+(50xx,1001) VERS="4RET" VR="CS" VM="1" Keyword="CurveActivationLayer" Name="Curve Activation Layer "
+(50xx,2000) VERS="4RET" VR="US" VM="1" Keyword="AudioType" Name="Audio Type"
+(50xx,2002) VERS="4RET" VR="US" VM="1" Keyword="AudioSampleFormat" Name="Audio Sample Format"
+(50xx,2004) VERS="4RET" VR="US" VM="1" Keyword="NumberOfChannels" Name="Number of Channels"
+(50xx,2006) VERS="4RET" VR="UL" VM="1" Keyword="NumberOfSamples" Name="Number of Samples"
+(50xx,2008) VERS="4RET" VR="UL" VM="1" Keyword="SampleRate" Name="Sample Rate"
+(50xx,200A) VERS="4RET" VR="UL" VM="1" Keyword="TotalTime" Name="Total Time"
+(50xx,200C) VERS="4RET" VR="OW/OB" VM="1" Keyword="AudioSampleData" Name="Audio Sample Data"
+(50xx,200E) VERS="4RET" VR="LT" VM="1 " Keyword="AudioComments" Name="Audio Comments"
+(50xx,2500) VERS="4RET" VR="LO" VM="1" Keyword="CurveLabel" Name="Curve Label"
+(50xx,2600) VERS="4RET" VR="SQ" VM="1" Keyword="CurveReferencedOverlaySequence" Name="Curve Referenced Overlay Sequence "
+(50xx,2610) VERS="4RET" VR="US" VM="1" Keyword="CurveReferencedOverlayGroup" Name="Curve Referenced Overlay Group"
+(50xx,3000) VERS="4RET" VR="OW/OB" VM="1" Keyword="CurveData" Name="Curve Data"
+(5200,9229) VERS="4" VR="SQ" VM="1" Keyword="SharedFunctionalGroupsSequence" Name="Shared Functional Groups Sequence"
+(5200,9230) VERS="4" VR="SQ" VM="1" Keyword="PerFrameFunctionalGroupsSequence" Name="Per-frame Functional Groups Sequence"
+(5400,0000) VERS="3" VR="UL" VM="1" Keyword="WaveformGroupLength" Name="WaveformGroupLength"
+(5400,0100) VERS="4" VR="SQ" VM="1" Keyword="WaveformSequence" Name="Waveform Sequence "
+(5400,0110) VERS="4" VR="OB/OW" VM="1" Keyword="ChannelMinimumValue" Name="Channel Minimum Value "
+(5400,0112) VERS="4" VR="OB/OW" VM="1" Keyword="ChannelMaximumValue" Name="Channel Maximum Value "
+(5400,1004) VERS="4" VR="US" VM="1" Keyword="WaveformBitsAllocated" Name="Waveform Bits Allocated"
+(5400,1006) VERS="4" VR="CS" VM="1" Keyword="WaveformSampleInterpretation" Name="Waveform Sample Interpretation"
+(5400,100A) VERS="4" VR="OB/OW" VM="1" Keyword="aveformPaddingValue" Name="Waveform Padding Value"
+(5400,1010) VERS="4" VR="OB/OW" VM="1" Keyword="WaveformData" Name="Waveform Data "
+(5600,0010) VERS="4" VR="OF" VM="1" Keyword="FirstOrderPhaseCorrectionAngle" Name="First Order Phase Correction Angle"
+(5600,0020) VERS="4" VR="OF" VM="1" Keyword="SpectroscopyData" Name="Spectroscopy Data"
+(60xx,0000) VERS="3" VR="UL" VM="1" Keyword="OverlayGroupLength" Name="Overlay Group Length"
+(60xx,0010) VERS="4" VR="US" VM="1" Keyword="OverlayRows" Name="Overlay Rows"
+(60xx,0011) VERS="4" VR="US" VM="1" Keyword="OverlayColumns" Name="Overlay Columns"
+(60xx,0012) VERS="4RET" VR="US" VM="1" Keyword="OverlayPlanes" Name="Overlay Planes"
+(60xx,0015) VERS="4" VR="IS" VM="1" Keyword="NumberOfFramesInOverlay" Name="Number of Frames in Overlay"
+(60xx,0022) VERS="4" VR="LO" VM="1" Keyword="OverlayDescription" Name="Overlay Description"
+(60xx,0040) VERS="4" VR="CS" VM="1" Keyword="OverlayType" Name="Overlay Type"
+(60xx,0045) VERS="4" VR="LO" VM="1" Keyword="OverlaySubtype" Name="Overlay Subtype"
+(60xx,0050) VERS="4" VR="SS" VM="2" Keyword="OverlayOrigin" Name="Overlay Origin"
+(60xx,0051) VERS="4" VR="US" VM="1" Keyword="ImageFrameOrigin" Name="Image Frame Origin"
+(60xx,0052) VERS="4RET" VR="US" VM="1" Keyword="OverlayPlaneOrigin" Name="Overlay Plane Origin"
+(60xx,0060) VERS="4RET" VR="CS" VM="1" Keyword="OverlayCompressionCode" Name="Overlay Compression Code"
+(60xx,0061) VERS="4RET" VR="SH" VM="1" Keyword="OverlayCompressionOriginator" Name="Overlay Compression Originator"
+(60xx,0062) VERS="4RET" VR="SH" VM="1" Keyword="OverlayCompressionLabel" Name="Overlay Compression Label"
+(60xx,0063) VERS="4RET" VR="CS" VM="1" Keyword="OverlayCompressionDescription" Name="Overlay Compression Description"
+(60xx,0066) VERS="4RET" VR="AT" VM="1-n" Keyword="OverlayCompressionStepPointers" Name="Overlay Compression Step Pointers"
+(60xx,0068) VERS="4RET" VR="US" VM="1" Keyword="OverlayRepeatInterval" Name="Overlay Repeat Interval"
+(60xx,0069) VERS="4RET" VR="US" VM="1" Keyword="OverlayBitsGrouped" Name="Overlay Bits Grouped"
+(60xx,0100) VERS="4" VR="US" VM="1" Keyword="OverlayBitsAllocated" Name="Overlay Bits Allocated"
+(60xx,0102) VERS="4" VR="US" VM="1" Keyword="OverlayBitPosition" Name="Overlay Bit Position"
+(60xx,0110) VERS="4RET" VR="CS" VM="1" Keyword="OverlayFormat" Name="Overlay Format"
+(60xx,0200) VERS="4RET" VR="US" VM="1" Keyword="OverlayLocation" Name="Overlay Location"
+(60xx,0800) VERS="4RET" VR="CS" VM="1-n" Keyword="OverlayCodeLabel" Name="Overlay Code Label"
+(60xx,0802) VERS="4RET" VR="US" VM="1" Keyword="OverlayNumberOfTables" Name="Overlay Number of Tables"
+(60xx,0803) VERS="4RET" VR="AT" VM="1-n" Keyword="OverlayCodeTableLocation" Name="Overlay Code Table Location"
+(60xx,0804) VERS="4RET" VR="US" VM="1" Keyword="OverlayBitsForCodeWord" Name="Overlay Bits For Code Word"
+(60xx,1001) VERS="4" VR="CS" VM="1" Keyword="OverlayActivationLayer" Name="Overlay Activation Layer "
+(60xx,1100) VERS="4RET" VR="US" VM="1" Keyword="OverlayDescriptorGray" Name="Overlay Descriptor - Gray"
+(60xx,1101) VERS="4RET" VR="US" VM="1" Keyword="OverlayDescriptorRed" Name="Overlay Descriptor - Red"
+(60xx,1102) VERS="4RET" VR="US" VM="1" Keyword="OverlayDescriptorGreen" Name="Overlay Descriptor - Green"
+(60xx,1103) VERS="4RET" VR="US" VM="1" Keyword="OverlayDescriptorBlue" Name="Overlay Descriptor - Blue"
+(60xx,1200) VERS="4RET" VR="US" VM="1-n" Keyword="OverlaysGray" Name="Overlays - Gray"
+(60xx,1201) VERS="4RET" VR="US" VM="1-n" Keyword="OverlaysRed" Name="Overlays - Red"
+(60xx,1202) VERS="4RET" VR="US" VM="1-n" Keyword="OverlaysGreen" Name="Overlays - Green"
+(60xx,1203) VERS="4RET" VR="US" VM="1-n" Keyword="OverlaysBlue" Name="Overlays - Blue"
+(60xx,1301) VERS="4" VR="IS" VM="1" Keyword="ROIArea" Name="ROI Area"
+(60xx,1302) VERS="4" VR="DS" VM="1" Keyword="ROIMean" Name="ROI Mean"
+(60xx,1303) VERS="4" VR="DS" VM="1" Keyword="ROIStandardDeviation" Name="ROI Standard Deviation"
+(60xx,1500) VERS="4" VR="LO" VM="1" Keyword="OverlayLabel" Name="Overlay Label"
+(60xx,3000) VERS="4" VR="OB/OW" VM="1" Keyword="OverlayData" Name="Overlay Data"
+(60xx,4000) VERS="4RET" VR="LT" VM="1" Keyword="OverlayComments" Name="Overlay Comments"
+(7FDF,0010) VERS="3" VR="OW/OB" VM="1" Keyword="NKI_PixelData" Name="NKI Pixel Data"
+(7FE0,0000) VERS="3" VR="UL" VM="1" Keyword="PixelDataGroupLength" Name="Pixel Data Group Length"
+(7FE0,0010) VERS="4" VR="OW/OB" VM="1" Keyword="PixelData" Name="Pixel Data"
+(7FE0,0020) VERS="4RET" VR="OW" VM="1" Keyword="CoefficientsSDVN" Name="Coefficients SDVN"
+(7FE0,0030) VERS="4RET" VR="OW" VM="1" Keyword="CoefficientsSDHN" Name="Coefficients SDHN"
+(7FE0,0040) VERS="4RET" VR="OW" VM="1" Keyword="CoefficientsSDDN" Name="Coefficients SDDN"
+(7Fxx,0000) VERS="2C" VR="UL" VM="1" Keyword="VariablePixelDataGroupLength" Name="Variable Pixel Data Group Length"
+(7Fxx,0010) VERS="4RET" VR="OW/OB" VM="1" Keyword="VariablePixelData" Name="Variable Pixel Data"
+(7Fxx,0011) VERS="4RET" VR="US" VM="1" Keyword="VariableNextDataGroup" Name="Variable Next Data Group"
+(7Fxx,0020) VERS="4RET" VR="OW" VM="1" Keyword="VariableCoefficientsSDVN" Name="Variable Coefficients SDVN"
+(7Fxx,0030) VERS="4RET" VR="OW" VM="1" Keyword="VariableCoefficientsSDHN" Name="Variable Coefficients SDHN"
+(7Fxx,0040) VERS="4RET" VR="OW" VM="1" Keyword="VariableCoefficientsSDDN" Name="Variable Coefficients SDDN"
+(9999,0100) VERS="CQ" VR="US" VM="1" Keyword="ConquestMaxVRSize" Name="Conquest Maximum VR Size"
+(9999,0200) VERS="CQ" VR="US" VM="1" Keyword="ConquestMaxRowsColumns" Name="Conquest Maximum Rows or Columns"
+(9999,0201) VERS="CQ" VR="US" VM="1" Keyword="ConquestFrame" Name="Conquest Frame"
+(9999,0300) VERS="CQ" VR="LO" VM="1" Keyword="ConquestConsoleText" Name="Conquest Console Text"
+(9999,0400) VERS="CQ" VR="LO" VM="1" Keyword="ConquestConsoleCommand" Name="Conquest Console Command"
+(9999,0500) VERS="CQ" VR="US" VM="1" Keyword="ConquestMaxSlices" Name="Conquest Maximum Slices"
+(9999,0600) VERS="CQ" VR="US" VM="1" Keyword="ConquestMaxNKICompression" Name="Conquest Maximum NKI Compression"
+(9999,0700) VERS="CQ" VR="LO" VM="1" Keyword="ConquestReCompression" Name="Conquest ReCompression"
+(9999,0802) VERS="CQ" VR="US" VM="1" Keyword="ConquestVirtualServerMask" Name="Conquest Virtual Server Mask"
+(9999,0900) VERS="CQ" VR="LO" VM="1" Keyword="ConquestScript" Name="Conquest Script"
+(FFFA,FFFA) VERS="4" VR="SQ" VM="1" Keyword="DigitalSignaturesSequence" Name="Digital Signatures Sequence"
+(FFFC,FFFC) VERS="4" VR="OB" VM="1" Keyword="DataSetTrailingPadding" Name="Data Set Trailing Padding"
+(FFFE,E000) VERS="4" VR="NONE" VM="1" Keyword="Item" Name="Item"
+(FFFE,E00D) VERS="4" VR="NONE" VM="1" Keyword="ItemDelimitationItem" Name="Item Delimitation Item"
+(FFFE,E0DD) VERS="4" VR="NONE" VM="1" Keyword="SequenceDelimitationItem" Name="Sequence Delimitation Item"
diff --git a/dgate.hpp b/dgate.hpp
new file mode 100644
index 0000000..5d64a17
--- /dev/null
+++ b/dgate.hpp
@@ -0,0 +1,294 @@
+#ifndef _DGATE_H_
+# define _DGATE_H_
+
+/*
+MvH 19980705: Added CACHEDevices and JUKEBOXDevices, FindPhysicalDevice
+ljz 19990108: Added LoadImplicitLittleEndianFile and NKI PrivateCompession algorithms
+MvH 19990109: Regen has extra parameter
+ljz 19990317: Changed parameters of LoadImplicitLittleEndianFile
+ljz 19991117: Added parameter FileCompressMode to prototype of nki_private_compress
+ljz 20000629: Added TroubleLogFile and UserLogFile
+mvh 20010415: Added KeepImages flag to RemoveFromPacs: clear from DB only
+ Added SubDir parameter to regen to allow regen of one directory only
+mvh 20010416: Added ChangeUID routine and RegenFile - to allow modification of images
+mvh 20010429: Changed decompressor: now has extra parameter
+mvh 20020529: InitializeTables now has mode parameter (0=normal, 1=simple)
+mvh 20021016: added patid to GetFilename routines
+mvh 20021017: Added NeedPack here
+mvh 20021018: GenerateFileName has NoKill option (for interactive dgate tasks)
+ljz 20030120: Added prototype of FreeDeviceTables
+mvh 20030701: compression parameter for amap
+mvh 20030703: Added prototypes of recompression functions + ArchiveCompression
+mvh 20030706: Optional filename parameter for recompress
+mvh 20030706: Export VRType for implicit little endian support
+mvh 20030921: Added DEVICE_TYPE_MIRROR
+mvh 20040401: Added Changed and ActualMode flags to compress routines
+mvh 20040626: Added study and series UID to getfilename interface
+mvh 20040930: Adapted return type of SetString; added maxlen to BuildSearchString
+mvh 20041013: Added MAXQUERYLENGTH
+mvh 20041029: Added MergeUIDs
+mvh 20041108: Added Syntax input to GenerateFileName
+mvh 20050108: Adapted for linux compile
+mvh 20050109: Added configurable TCPIPTimeOut
+mvh 20050129: Added optional FILE to DumpVR, added CheckFreeStoreOnMIRRORDevice
+mvh 20050401: Added QueryOnModalityWorkList, WorkListTableName, WorkListDB
+mvh 20050404: Added DT_START/ENDSEQUENCE to code sequence in WorkList table
+mvh 20050902: Made space for HL7Tag in DBEntry
+mvh 20051229: Added iDepth to DumpVR
+mvh 20060317: Added called and calling to GenerateFilename
+mvh 20060324: Added StripGroup2 option to recompress
+mvh 20060628: AddToDatabase has JustAdd parameter: skip one unnecessary query
+mvh 20060702: Pass DB to GenerateFilename to avoid zillions of db open and closes
+mvh 20070122: Added MIRRORDevices
+mvh 20070201: Added DebugLevel
+mvh 20070207: Added MakeTableString
+mvh 20080818: DbaseIII check now uses DB flags, not PATHSEP in datasource name
+ Added DT_MSTR
+jf 20090616: Include file stuff
+bcb 20091231: Changed char* to const char* for gcc4.2 warnings
+mvh 20100111: Merged
+mvh 20100123: Added DT_FL and DT_FD
+mvh 20100125: Removed linux warning
+bcb 20100309: Changed SQLLength to unsigned int
+mvh 20100703: Merged
+mvh 20110119: Moved two functions to the correct place
+*/
+
+#define bool BOOL
+#define true TRUE
+#define false FALSE
+
+#ifndef WHEDGE
+# include "dicom.hpp" // DICOM routines
+# include <stdlib.h>
+#ifndef UNIX
+# include <direct.h>
+#else // UNIX
+#include "wintypes.hpp" // windows data types
+#endif // UNIX
+# include "odbci.hpp" // ODBC Interface routines
+# include "dprintf.hpp" // Debug output
+#endif
+
+#ifndef UNIX
+# define PATHSEPCHAR '\\'
+#else
+# define PATHSEPCHAR '/'
+#endif
+
+#define MAXQUERYLENGTH 310000
+
+typedef struct
+ {
+ UINT16 Group;
+ UINT16 Element;
+ char SQLColumn[32];
+ unsigned int SQLLength;
+ int SQLType;
+ int DICOMType;
+ char HL7Tag[32];
+ } DBENTRY;
+
+typedef struct _ACRNemaAddress
+ {
+ char Name[20];
+ char IP[128];
+ char Port[16];
+ char Compress[16];
+ } ACRNemaAddress;
+
+enum
+ {
+ DT_STR =1,
+ DT_DATE,
+ DT_UINT16,
+ DT_UINT32,
+ DT_UI,
+ DT_FL,
+ DT_FD,
+ DT_STARTSEQUENCE,
+ DT_ENDSEQUENCE,
+ DT_MSTR
+ };
+
+extern UINT DebugVRs;
+extern int DebugLevel;
+extern DBENTRY *PatientDB, *StudyDB, *SeriesDB, *ImageDB, *WorkListDB;
+extern char PatientTableName[],
+ StudyTableName[],
+ SeriesTableName[],
+ ImageTableName[],
+ WorkListTableName[];
+extern BYTE Directory [];
+extern BYTE Port [];
+extern BYTE KFACTORFILE [];
+extern BYTE MYACRNEMA [];
+extern char SOPClassFile [];
+extern char OCPipeName[];
+extern char ACPipeName[];
+extern char ServerName[];
+extern char UserLogFile[];
+extern char TroubleLogFile[];
+extern BYTE ACRNEMAMAP[];
+// DataHost added for UNIX version
+// holds network hostname of machine running SQL server
+extern char DataHost[];
+extern char DataSource[];
+extern char UserName[];
+extern char Password[];
+extern int NeedPack;
+extern int TCPIPTimeOut;
+
+extern RTC VRType;
+
+
+BOOL CheckOrMakeTable(Database &);
+BOOL DropTables();
+BOOL MakeSafeString ( VR *, char *);
+BOOL RemoveDuplicates ( Database &, DICOMDataObject *);
+BOOL FixImage(DICOMDataObject *);
+BOOL LoadKFactorFile(char *);
+BOOL InitializeTables (int mode);
+BOOL QueryOnPatient (DICOMDataObject *, Array < DICOMDataObject *> *);
+BOOL QueryOnStudy (DICOMDataObject *, Array < DICOMDataObject *> *);
+BOOL QueryOnSeries (DICOMDataObject *, Array < DICOMDataObject *> *);
+BOOL QueryOnImage (DICOMDataObject *, Array < DICOMDataObject *> *);
+BOOL QueryOnModalityWorkList (DICOMDataObject *, Array < DICOMDataObject *> *);
+char * SetString(VR *vr, char *, int);
+BOOL DumpVR(VR *, FILE * f = NULL, int iDepth = 0);
+BOOL GenerateFileName(DICOMDataObject*, char *Dev, char *Root, char *Filename, BOOL NoKill, int Syntax, char *called, char *calling, Database *db);
+
+DICOMDataObject* LoadDICOMDataObject(char *filename);
+DICOMDataObject* LoadDICOMDataObjectFrame(char *filename);
+DICOMDataObject* LoadImplicitLittleEndianFile(char* filename,
+ unsigned int iVrSizeLimit);
+int nki_private_decompress(short int *dest, signed char *src, int size);
+int nki_private_compress(signed char *dest, short int *src, int npixels, int iMode);
+int get_nki_private_decompressed_length(signed char *src);
+
+BOOL GenUID(char *oString);
+
+BOOL CompressNKIImageFile(char *file, int FileCompressMode, int *ActualMode);
+BOOL CompressJPEGImageFile(char *file, int FileCompressMode, int *ActualMode);
+BOOL DecompressImageFile(char *file, int *Changed);
+BOOL DecompressImage(DICOMDataObject **pDDO, int *Changed);
+BOOL CompressJPEGImage(DICOMDataObject **pDDO, int FileCompressMode, int *ActualMode);
+
+extern char ArchiveCompression[16];
+
+BOOL SaveDICOMDataObject(DICOMDataObject *, char *filename, int FileCompressMode);
+BOOL SaveDICOMDataObjectC10(DICOMDataObject *DDOPtr, char *filename, int FileCompressMode);
+BOOL GetFileName(VR *, char *, char *, BOOL UpdateLRU = TRUE, char *patid=NULL, char *study=NULL, char *series=NULL);
+BOOL GetFileName(VR *, char *, char *, Database &, BOOL UpdateLRU = TRUE, char *patid=NULL, char *study=NULL, char *series=NULL);
+BOOL InitACRNemaAddressArray();
+BOOL CloseACRNemaAddressArray();
+BOOL GetACRNema(char *, char *, char *, char*);
+BOOL RemoveFromWorld(DICOMDataObject *, Database &);
+BOOL RemoveFromPACS(DICOMDataObject *, BOOL KeepImages = FALSE);
+BOOL BuildColumnString(DBENTRY *DBE, char *TableName, VR *vr, char *TempString);
+BOOL BuildSearchString(Database *DB, DBENTRY *DBE, char *TableName, VR *vr, char *Search, char *TempString, int maxlen);
+BOOL SaveToDataBase (Database &DB, DICOMDataObject *, char *filename, const char *Device, BOOL JustAdd);
+BOOL CheckOrMakeTable(Database &);
+BOOL DropTables();
+BOOL MakeSafeString ( VR *, char *);
+BOOL MakeSafeDate ( VR *, char *);
+BOOL RemoveDuplicates ( Database &, DBENTRY *, char *, DICOMDataObject *, BOOL);
+BOOL FixImage(DICOMDataObject *);
+DBENTRY *FindDBE(VR*);
+UINT LastDBE(DBENTRY*);
+BOOL VerifyIsInDBE( VR *vr, DBENTRY *DBE, DBENTRY * &TempDBEPtr );
+UINT DBEIndex(DBENTRY *DBE, VR *vr);
+BOOL DICOM2SQLQuery ( char *s );
+const char *UniqueKey(DBENTRY*);
+const char *UniqueLink(DBENTRY*);
+BOOL UpdateAccessTimes(Database &, char *);
+BOOL ChangeUID(char *OldUID, const char *Type, char *NewUID);
+BOOL MergeUIDs(char *OldUID[], int n, const char *Type, char *NewUID);
+UINT32 SQLRealSize(char *Str, SDWORD Max);
+BOOL Regen();
+BOOL Regen(const char*, int IsCacheOrJukeBox, char *SubDir = NULL);
+BOOL RegenFile(char *filename);
+BOOL AddToTable(
+ Database &DB,
+ DBENTRY *DCMGateDB,
+ char *TableName,
+ DICOMDataObject *DDOPtr,
+ char *ObjectFile,
+ char *DeviceName);
+BOOL MakeTableString ( DBENTRY *DBE, char *s, int mode );
+
+DICOMDataObject *MakeCopy(DICOMDataObject *DO);
+VR *ConstructVRFromSQL (
+ DBENTRY *,
+ UINT16 Group,
+ UINT16 Element,
+ UINT32 Length,
+ char *);
+VR *ConstructAE();
+
+// Type of System
+# define E_WORKGROUP 1
+# define E_PERSONAL 2
+# define E_ENTERPRISE 3
+
+extern UINT Edition;
+extern char EditionText[];
+
+
+// Device related flags
+extern UINT MAGDevices, MOPDevices, CDRDevices, CACHEDevices, JUKEBOXDevices, MIRRORDevices;
+extern UINT MAGDeviceThreshHold;
+
+
+
+# define DEVICE_TYPE_MAG 0x01
+# define DEVICE_TYPE_MOP 0x02
+# define DEVICE_TYPE_CDR 0x04
+# define DEVICE_TYPE_MIRROR 0x08
+# define DEVICE_TYPE_NOKILL 0x100
+
+# define DEVICE_OPTI 0x00
+# define DEVICE_0 0x10
+# define DEVICE_1 0x20
+# define DEVICE_2 0x30
+# define DEVICE_X(xxx) ((xxx+1)<<4)
+
+#ifdef UNIX
+//DUCKHEAD92 BEGIN
+#define stricmp(s1, s2) strcasecmp(s1, s2)
+#define memicmp(s1, s2, n) strncasecmp(s1, s2, n)
+
+/* These next lines are scattered all around the place,
+ should they be WIN32 only? */
+#define O_BINARY 0 /* LINE UNIX ONLY? */
+#define _SH_DENYRW 0x10 /* deny read/write mode */
+#define _SH_DENYWR 0x20 /* deny write mode */
+#define _SH_DENYRD 0x30 /* deny read mode */
+#define _SH_DENYNO 0x40 /* deny none mode */
+#define SH_DENYNO _SH_DENYNO
+#define sopen(a, b, c, d) open(a, b) /* LINE UNIX ONLY? */
+#define WINAPI /* LINE UNIX ONLY */
+#define DeleteCriticalSection(a) pthread_mutex_destroy(a); /* LINE UNIX ONLY */
+void strupr(char *s);
+void strlwr(char *s);
+#define closesocket(xxx) close(xxx) /* LINE UNIX ONLY? */
+#define strnicmp(s1, s2, n) strncasecmp(s1, s2, n)
+//DUCKHEAD92 END
+#endif
+
+BOOL InitializeDeviceTable(char *SCRoot);
+void FreeDeviceTables(void);
+BOOL GetDevice(char *Dev, UINT Flags);
+BOOL GetPhysicalDevice(const char *Dev, char *Name);
+BOOL FindPhysicalDevice(char *Dev, char *Name, char *ObjectFile);
+UINT CheckFreeStoreOnMAGDevice(UINT);
+UINT CheckFreeStoreOnCACHEDevice(UINT);
+UINT CheckFreeStoreOnMIRRORDevice(UINT);
+UINT LargestFreeMAG ();
+UINT MaxMagDevice ();
+
+BOOL ConfigMicroPACS();
+DWORD CurrentTime();
+BOOL ConfigEventNotification ( char *ConfigSection, char *ConfigFile );
+
+#endif
diff --git a/dgatefn.cpp b/dgatefn.cpp
new file mode 100644
index 0000000..d1f117f
--- /dev/null
+++ b/dgatefn.cpp
@@ -0,0 +1,694 @@
+/* MvH 19980326: changed file name generator to ensure correct sorting for avs_rdic */
+/* MvH 19980327: Added FileNameSyntax option in dicom.ini; 0=original, 1=allow sorting */
+/* MvH 19980407: avoid /;<>| in filename; philips: up to 9999 series 999999 slices */
+/* MvH+LJZ 19980409: do not free passed DDOPtr on failure: crashed the lot */
+/* MvH 19980415: Error messages to operatorconsole */
+/* MvH 19980620: Check error flag from GetDevice (out of disk message) */
+/* MvH 19981005: Added FileNameSyntax 2: filename starts with SeriesUID_ */
+/* MvH 19981005: Replaced size%64 by min(size, 63) for correct truncation */
+/* MvH 19981217: FileNameSyntax 3: same as 2 but accept errors */
+/* MvH 19981220: Fixed FileNameSyntax code */
+/* MvH 19990117: FileNameSyntax 4: same as 3 but .dcm extension (forces ch10 format) */
+/* MvH 19990117: Avoid attempts to rewrite image that is not on MAG store (e.g., on CD)*/
+/* MvH 19990315: Do not allow '.' in directory name */
+/* in Syntax 3 directory name is patient ID only (better for ACRVIEW) */
+/* uniqueify more by using time + counter */
+/* MvH 20000127: FileNameSyntax 4 now does not truncate patid, as 3 already did */
+/* Ljz+MvH 20000131: FileNameSyntax 4 has patient ID only as directory name (same as 3)*/
+/* MvH 20000701: Added MaxFileNameLenght option: truncates filename from start */
+/* MvH 20010419: FileNameSyntax 5 on request of Jason Foster - uses patientname as dir */
+/* MvH 20011109: Made MAG name check case insensitive */
+/* MvH 20020416: Made filename counter 4 digits for when writing >100 files/s */
+/* MvH 20020416: Made all instances of time() unsigned */
+/* MvH 20020426: Cannot rewrite image not on MAG store is now a message without *** */
+/* MvH 20020508: The above message will not lead to a fail of GenerateFileName */
+/* MvH 20020802: Added FileNameSyntaxes 6..9; cleaned FileNameSyntax code a bit */
+/* MvH 20020804: Truncate patient ID to 32 chars for mode 6 and 8 (make sure len<255) */
+/* MvH 20021016: Pass indexed patid to GetFilename for speed */
+/* MvH 20021018: GenerateFileName has NoKill option (for interactive dgate tasks) */
+/* MvH 20021223: Added forbidden chars *, ?, " and : (comment from Thomas Buerer) */
+/* ljz 20030401: Overrule '.v2' filenames with '.dcm' when object is not */
+/* ImplicitLittleEndian */
+/* ljz 20030522: Replaced 'static int counter' by 'unsigned int gl_iCounter' */
+/* ljz 20030606: Fixed incremental counter when creating UIDs or generating filenames */
+/* ljz 20030730: Overrule v2 only when not ImplicitLittleEndian, ExplicitLittleEndian */
+/* or ExplicitBigEndian (c.f. 20020401) */
+/* MvH 20030819: Allow longer filenames */
+/* MVH 20030921: Added DEVICE_TYPE_MIRROR TO GetDevice call */
+/* MvH 20040129: Added FileNameSyntax 10 = all files in one directory */
+/* ljz 20040301: Small fix for FileNameSyntax 10 */
+/* mvh 20041108: Added Syntax input to GenerateFileName (overrides ini setting) */
+/* mvh 20050107: Adapted for linux compile */
+/* ljz 20050126: Added FileNameSyntax 11: StudyUID\SeriesUID\SOPUID.dcm */
+/* ljz 20050131: Changes root to 'name' for FileNameSyntax 11 */
+/* mvh 20051210: Clear root output string when image already in database */
+/* kld 20060312: FileNameSyntax 12: similar to 11 but uses Modality_StudyID as dir */
+/* mvh 20060312: Checked it: 12=name_ID\Modality_StudyID\SeriesUID\SOPUID.dcm */
+/* mvh 20060314: Change: 12=name_ID\Modality_StudyID\SeriesID\SOPUID.dcm */
+/* mvh 20060314: new filenamesyntax %name_%id\%modality_%studyid\%seriesid\%sopuid.dcm */
+/* mvh 20060317: Added calledae and callingae to GenerateFilename flexible syntax */
+/* mvh 20060325: imagenum is image number as text, fix imageid, accept all errors */
+/* mvh 20060402: Fix potential problem when patient ID not there */
+/* mvh 20060701: Speeded string handling in new filenamesyntax */
+/* mvh 20060702: Pass DB to GenerateFilename to avoid zillions of db open and closes */
+/* mvh 20070125: Fix %modality; add %studydate and substring (year = %studydate[0,3]) */
+/* mvh 20071027: Extended length of FileNameSyntz parameter to 256 */
+/* mvh 20071027: Stripped spaces of called and calling in flexible filenamesyntax */
+/* mvh 20071030: Small fix in the above */
+/* mvh 20071104: Added %series: 4 digit series number */
+/*
+20090620 jf Include file stuff
+20090926 mvh Added %studydesc and %vxxxx,yyyy etc
+20090927 mvh Added Cleanup ro %vxxxx,yyyy
+20091231 bcb Changed char* to const char* for gcc4.2 warnings
+20100111 mvh Merged; but cast Time to print to (unsigned int)
+20100125 mvh GetPrivateProfileString -> MyGetPrivateProfileString
+20100126 mvh Fixed readout of studydate (typo mix with studydesc)
+20100303 bcb Changed int to unsigned int, commented out unused variables (gcc4.2 Warnings)
+20100703 mvh Merged
+20100828 mvh Update history fix
+20101222 mvh Fixed that ascii codes > 128 where replaced by zero (truncated) in Cleanup
+20110201 mvh Changed prototype of SearchDICOMObject
+20110606 mvh A change of extension when rewriting is now allowed; object is then deleted first
+20120319 mvh Implemented lua: filenamesyntax
+20121208 mvh Added %date to filenamesyntax gives yyyymmdd
+20131013 mvh Default FileNameSyntax set to 4
+*/
+
+#ifndef WHEDGE
+# include "dgate.hpp"
+
+#else
+# include "master.h"
+#endif
+
+#include "gpps.hpp" //DUCKHEAD92
+#include <time.h>
+
+#ifndef UNIX
+#define PATHSEPSTR "\\"
+#define PATHSEPCHAR '\\'
+#else
+#define PATHSEPSTR "/"
+#define PATHSEPCHAR '/'
+//#define memicmp(s1, s2, n) strncasecmp(s1, s2, n)
+#endif
+
+#ifndef RootConfig
+extern char RootConfig[];
+#endif
+#ifndef ConfigFile
+extern char ConfigFile[];
+#endif
+
+unsigned int gl_iFileCounter=0;
+
+static int
+dgatefnmin(int a, int b)
+ {
+ if (a<b)
+ return a;
+ else
+ return b;
+ }
+
+static char FileNameSyntaxString[256];
+
+static
+int
+GetFileNameSyntax(unsigned int *maxfilenamelength)
+ {
+ static int FileNameSyntax=-1;
+ static unsigned int MaxLength = 255;
+ char RootSC[64];
+ char Temp[128];
+
+ if (FileNameSyntax<0)
+ {
+ MyGetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig,
+ (char*) RootSC, 64, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "FileNameSyntax", "4",
+ (char*) FileNameSyntaxString, 256, ConfigFile);
+ FileNameSyntax = atoi(FileNameSyntaxString);
+ if (strchr(FileNameSyntaxString, '%')) FileNameSyntax=999; // configured by string
+ if (memcmp(FileNameSyntaxString, "lua:", 4)==0) FileNameSyntax=998; // lua done by caller (dcm assumed)
+
+ MyGetPrivateProfileString ( RootSC, "MaxFileNameLength", "255",
+ (char*) Temp, 128, ConfigFile);
+ MaxLength = (unsigned int)atoi(Temp);
+ }
+
+ if (maxfilenamelength) *maxfilenamelength = MaxLength;
+ return FileNameSyntax;
+ }
+
+
+/* Cleanup e.g., patient name */
+
+static void Cleanup(char *name)
+ {
+ int Index;
+ unsigned char *Name = (unsigned char *)name;
+
+ Index = 0;
+ while(Name[Index])
+ {
+ switch(Name[Index])
+ {
+ case '/':
+ case '\\':
+ case ';':
+ case '>':
+ case '<':
+ case '|':
+ case ',':
+ case '.':
+ case ' ':
+ case ':':
+ case '?':
+ case '*':
+ case '"':
+ Name[Index] = '_';
+ break;
+ case 13:
+ case 10:
+ Name[Index] = '\0';
+ break;
+
+ }
+ if(Name[Index]<33)
+ {
+ Name[Index] = '\0';
+ break;
+ }
+ ++Index;
+ if(Index>64)
+ {
+ Name[Index] = '\0';
+ break;
+ }
+ }
+
+ while(Name[strlen(name)-1]=='_')
+ Name[strlen(name)-1] = '\0';
+
+ if(!strlen(name))
+ strcpy(name, "unknown");
+ }
+
+#define __SearchDICOMObject
+int SearchDICOMObject(DICOMObject *DDO, const char *desc, char *result, Array < DICOMDataObject * > **A = NULL, DICOMDataObject **O = NULL);
+
+BOOL DeleteImageFile(char *filename, BOOL KeepImages);
+
+// Generate a file name prefix for an IOD
+BOOL
+GenerateFileName(
+ DICOMDataObject *DDOPtr,
+ char *Device,
+ char *Root,
+ char *filename,
+ BOOL NoKill,
+ int Syntax,
+ char *called,
+ char *calling,
+ Database *db)
+ {
+ VR *ImageNumber;
+ VR *ImageID;
+ VR *SeriesNumber;
+ VR *SeriesUID;
+ VR *StudyUID;
+ VR *StudyID;
+ VR *Modality;
+ VR *SOPUID;
+ VR *PatientID;
+ VR *PatientName;
+// VR *TempVR;
+ VR *StudyDate;
+ VR *StudyDesc;
+ unsigned int maxfilenamelength;
+ int iSeries, iImage;//, Index;
+ char Path[1024];//, Path1[1024];
+ char CName[65];
+ char CID[65];
+ char CSeries[65];
+ char CImageNum[65];
+ char CImageID[65];
+ char CSeriesUID[65];
+ char CStudyUID[65];
+ char CStudyID[65];
+ char CModality[65];
+ char CStudyDate[65];
+ char CStudyDesc[65];
+ char CSOPUID[65];
+ char CMod[130];
+ char Called[64];
+ char Calling[64];
+ int AcceptError;
+ int iFileNameSyntax;
+ int i, l, L;
+ char *p, *q;
+
+ // Name syntax >=3 do not use image or series number and can store items without these
+ AcceptError = GetFileNameSyntax(NULL)>=3;
+
+ if (Syntax) iFileNameSyntax = Syntax;
+ else iFileNameSyntax = GetFileNameSyntax(NULL);
+
+ // First, make test if image is already in the database. In which
+ // case we allow the PACS to rewrite it.
+
+ memset((void*)CID, 0, 65);
+ PatientID = DDOPtr->GetVR(0x0010, 0x0020);
+ if(PatientID)
+ {
+ strncpy(CID, (char*) PatientID->Data, dgatefnmin(PatientID->Length,64));
+ if (PatientID->Length)
+ if (CID[PatientID->Length-1]==' ') CID[PatientID->Length-1]=0;
+ }
+
+ if (GetFileName ( DDOPtr->GetVR(0x0008, 0x0018),
+ filename, Device, *db, FALSE, CID))
+ {
+ char dcm[] = ".dcm";
+ char v2[] = ".v2";
+
+ if (memicmp(Device, "MAG", 3) != 0)
+ {
+ OperatorConsole.printf("Cannot rewrite image that is not on MAG store\n");
+ return TRUE;
+ }
+
+ *Root=0;
+
+ // check that the extension is changing; if so delete the original
+ p = strrchr(filename, '.');
+
+ if (iFileNameSyntax==4 || iFileNameSyntax==998 || (iFileNameSyntax>=8 && iFileNameSyntax<=12))
+ q = dcm;
+ else if (iFileNameSyntax!=999)
+ q = v2;
+ else
+ q = strrchr(FileNameSyntaxString, '.');
+
+ if (p && q && strcmp(p, q)!=0)
+ {
+ // changing extension: removed stored image
+ //DeleteImageFile(filename, FALSE);
+ DICOMDataObject DDO;
+ VR *vr;
+
+ vr = DDOPtr->GetVR(0x0008, 0x0018);
+ vr = new VR(0x0008, 0x0018, vr->Length, vr->Data, (BOOL) FALSE );
+ DDO.Push(vr);
+
+ vr = DDOPtr->GetVR(0x0010, 0x0020);
+ vr = new VR(0x0010, 0x0020, vr->Length, vr->Data, (BOOL) FALSE );
+ DDO.Push(vr);
+
+ RemoveFromPACS(&DDO, FALSE);
+ }
+ else
+ return TRUE;
+ }
+
+
+ // return if GetDevice fails (out of disk space ?)
+
+ if (!GetDevice(Device, NoKill ? (DEVICE_TYPE_MAG | DEVICE_TYPE_MIRROR | DEVICE_OPTI | DEVICE_TYPE_NOKILL):(DEVICE_TYPE_MAG | DEVICE_TYPE_MIRROR | DEVICE_OPTI)) )
+ {
+ OperatorConsole.printf("*** Out of disk space\n");
+ return ( FALSE );
+ }
+
+ memset((void*)CID, 0, 65);
+ memset((void*)CName, 0, 65);
+ memset((void*)CSeries, 0, 65);
+ memset((void*)CImageNum, 0, 65);
+ memset((void*)CImageID, 0, 65);
+ memset((void*)CSeriesUID, 0, 65);
+ memset((void*)CStudyUID, 0, 65);
+ memset((void*)CStudyID, 0, 65);
+ memset((void*)CModality, 0, 65);
+ memset((void*)CStudyDate, 0, 65);
+ memset((void*)CStudyDesc, 0, 65);
+ memset((void*)CSOPUID, 0, 65);
+
+ ImageNumber = DDOPtr->GetVR(0x0020, 0x0013);
+ if(!ImageNumber)
+ {
+ OperatorConsole.printf("No image number\n");
+ strcpy(CImageNum, "empty");
+ iImage = 0;
+ //if (!AcceptError) return ( FALSE );
+ }
+ else
+ {
+ strncpy(CImageNum, (char*) ImageNumber->Data, dgatefnmin(ImageNumber->Length,64));
+ iImage = atoi(CImageNum);
+ }
+
+ SeriesNumber = DDOPtr->GetVR(0x0020, 0x0011);
+ if(!SeriesNumber)
+ {
+ OperatorConsole.printf("No Series number\n");
+ strcpy(CSeries, "empty");
+ iSeries = 0;
+ //if (!AcceptError) return ( FALSE );
+ }
+ else
+ {
+ strncpy(CSeries, (char*) SeriesNumber->Data, dgatefnmin(SeriesNumber->Length,64));
+ iSeries = atoi(CSeries);
+ }
+
+ SeriesUID = DDOPtr->GetVR(0x0020, 0x000e);
+ if(!SeriesUID)
+ {
+ OperatorConsole.printf("No Series UID\n");
+ strcpy(CSeriesUID, "empty");
+ //if (!AcceptError) return ( FALSE );
+ }
+ else
+ strncpy(CSeriesUID, (char*) SeriesUID->Data, dgatefnmin(SeriesUID->Length,64));
+
+ StudyID = DDOPtr->GetVR(0x0020, 0x0010);
+ if(!StudyID)
+ {
+ //OperatorConsole.printf("No Study ID\n");
+ strcpy(CStudyID, "empty");
+ //if (!AcceptError) return ( FALSE );
+ }
+ else
+ {
+ strncpy(CStudyID, (char*) StudyID->Data, dgatefnmin(StudyID->Length,64));
+ if (CStudyID[strlen(CStudyID)-1]==' ') CStudyID[strlen(CStudyID)-1]=0;
+ }
+
+ Modality = DDOPtr->GetVR(0x0008, 0x0060);
+ if(!Modality)
+ {
+ //OperatorConsole.printf("No Modality\n");
+ strcpy(CModality, "empty");
+ //if (!AcceptError) return ( FALSE );
+ }
+ else
+ {
+ strncpy(CModality, (char*) Modality->Data, dgatefnmin(Modality->Length,64));
+ if (CModality[strlen(CModality)-1]==' ') CModality[strlen(CModality)-1]=0;
+ }
+
+ StudyDate = DDOPtr->GetVR(0x0008, 0x0020);
+ if(!StudyDate)
+ {
+ //OperatorConsole.printf("No Study Date\n");
+ strcpy(CStudyDate, "empty");
+ //if (!AcceptError) return ( FALSE );
+ }
+ else
+ {
+ strncpy(CStudyDate, (char*) StudyDate->Data, dgatefnmin(StudyDate->Length,64));
+ if (CStudyDate[strlen(CStudyDate)-1]==' ') CStudyDate[strlen(CStudyDate)-1]=0;
+ }
+
+ StudyDesc = DDOPtr->GetVR(0x0008, 0x1030);
+ if(!StudyDesc)
+ {
+ //OperatorConsole.printf("No Study Date\n");
+ strcpy(CStudyDesc, "empty");
+ //if (!AcceptError) return ( FALSE );
+ }
+ else
+ {
+ strncpy(CStudyDesc, (char*) StudyDesc->Data, dgatefnmin(StudyDesc->Length,64));
+ if (CStudyDesc[strlen(CStudyDesc)-1]==' ') CStudyDesc[strlen(CStudyDesc)-1]=0;
+ }
+
+ StudyUID = DDOPtr->GetVR(0x0020, 0x000d);
+ if(!StudyUID)
+ {
+ OperatorConsole.printf("No Study UID\n");
+ strcpy(CStudyUID, "empty");
+ //if (!AcceptError) return ( FALSE );
+ }
+ else
+ strncpy(CStudyUID, (char*) StudyUID->Data, dgatefnmin(StudyUID->Length,64));
+
+ SOPUID = DDOPtr->GetVR(0x0008, 0x0018);
+ if(!SOPUID)
+ {
+ OperatorConsole.printf("No SOP UID\n");
+ strcpy(CSOPUID, "empty");
+ //if (!AcceptError) return ( FALSE );
+ }
+ else
+ strncpy(CSOPUID, (char*) SOPUID->Data, dgatefnmin(SOPUID->Length,64));
+
+ PatientID = DDOPtr->GetVR(0x0010, 0x0020);
+ if(!PatientID)
+ {
+ OperatorConsole.printf("No Patient ID\n");
+ strcpy(CID, "empty");
+ //if (!AcceptError) return(FALSE);
+ }
+ else
+ strncpy(CID, (char*) PatientID->Data, dgatefnmin(PatientID->Length,64));
+
+ PatientName = DDOPtr->GetVR(0x0010, 0x0010);
+ if(!PatientName)
+ {
+ OperatorConsole.printf("No Patient Name\n");
+ strcpy(CName, "empty");
+ //if (!AcceptError) return(FALSE);
+ }
+ else
+ strncpy(CName, (char*) PatientName->Data, dgatefnmin(PatientName->Length,64));
+
+ ImageID = DDOPtr->GetVR(0x0054, 0x0400);
+ if(!ImageID)
+ {
+ //OperatorConsole.printf("No Image ID\n");
+ strcpy(CImageID, "empty");
+ //if (!AcceptError) return ( FALSE );
+ }
+ else
+ {
+ strncpy(CImageID, (char*) ImageID->Data, dgatefnmin(ImageID->Length,64));
+ if (CImageID[strlen(CImageID)-1]==' ') CImageID[strlen(CImageID)-1]=0;
+ }
+
+ /* Cleanup various strings */
+ Cleanup(CName);
+ Cleanup(CID);
+ Cleanup(CStudyID);
+ Cleanup(CModality);
+ Cleanup(CSeries);
+ Cleanup(CImageNum);
+ Cleanup(CImageID);
+ Cleanup(CStudyDesc);
+
+ Called[0]=0;
+ if (called) strcpy(Called, called);
+ while (strlen(Called)>0 && Called[strlen(Called)-1]==' ') Called[strlen(Called)-1] = 0;
+
+ Calling[0]=0;
+ if (calling) strcpy(Calling, calling);
+ while (strlen(Calling)>0 && Calling[strlen(Calling)-1]==' ') Calling[strlen(Calling)-1] = 0;
+
+ /* make directory and filename for a range of FilenameSyntax values */
+ switch (iFileNameSyntax)
+ {
+ case 1:
+ CID [8] = '\0';
+ CName [8] = '\0';
+ strcpy(Root, CName);
+ strcat(Root, "_");
+ strcat(Root, CID);
+ sprintf(filename, "%s%s%04d_%06d_%u%04x.v2", Root, PATHSEPSTR, iSeries, iImage, (unsigned int)time(NULL), (gl_iFileCounter++) & 0xffff);
+ break;
+
+ case 2:
+ CID [8] = '\0';
+ CName [8] = '\0';
+ strcpy(Root, CName);
+ strcat(Root, "_");
+ strcat(Root, CID);
+ sprintf(filename, "%s%s%s_%04d_%06d_%u%04x.v2", Root, PATHSEPSTR, CSeriesUID, iSeries, iImage, (unsigned int)time(NULL), (gl_iFileCounter++) & 0xffff);
+ break;
+
+ case 3:
+ CID [16] = '\0';
+ strcpy(Root, CID);
+ sprintf(filename, "%s%s%s_%04d_%06d_%u%04x.v2", Root, PATHSEPSTR, CSeriesUID, iSeries, iImage, (unsigned int)time(NULL), (gl_iFileCounter++) & 0xffff);
+ break;
+
+ case 4:
+ CID [16] = '\0';
+ strcpy(Root, CID);
+ sprintf(filename, "%s%s%s_%04d_%06d_%u%04x.dcm", Root, PATHSEPSTR, CSeriesUID, iSeries, iImage, (unsigned int)time(NULL), (gl_iFileCounter++) & 0xffff);
+ break;
+
+ case 5:
+ strcpy(Root, CName);
+ sprintf(filename, "%s%s%s_%04d_%06d_%u%04x.v2", Root, PATHSEPSTR, CSeriesUID, iSeries, iImage, (unsigned int)time(NULL), (gl_iFileCounter++) & 0xffff);
+ break;
+
+ case 6:
+ CID [32] = '\0';
+ strcpy(Root, CID);
+ sprintf(filename, "%s%s%s%s%s%s%s.v2", CID, PATHSEPSTR, CStudyUID, PATHSEPSTR, CSeriesUID, PATHSEPSTR, CSOPUID);
+ break;
+
+ case 7:
+ strcpy(Root, CStudyUID);
+ sprintf(filename, "%s%s%s%s%s.v2", CStudyUID, PATHSEPSTR, CSeriesUID, PATHSEPSTR, CSOPUID);
+ break;
+
+ case 8:
+ CID [32] = '\0';
+ strcpy(Root, CID);
+ sprintf(filename, "%s%s%s%s%s%s%s.dcm", CID, PATHSEPSTR, CStudyUID, PATHSEPSTR, CSeriesUID, PATHSEPSTR, CSOPUID);
+ break;
+
+ case 9:
+ strcpy(Root, CStudyUID);
+ sprintf(filename, "%s%s%s%s%s.dcm", CStudyUID, PATHSEPSTR, CSeriesUID, PATHSEPSTR, CSOPUID);
+ break;
+
+ case 10:
+ strcpy(Root, "");
+ sprintf(filename, "Images%s%s.dcm", PATHSEPSTR, CSOPUID);
+ break;
+
+ case 11:
+ strcpy(Root, CName);
+ sprintf(filename, "%s%s%s%s%s%s%s.dcm", Root, PATHSEPSTR, CStudyUID, PATHSEPSTR, CSeriesUID, PATHSEPSTR, CSOPUID);
+ break;
+
+ case 12:
+ strcpy(Root, CName);
+ strcat(Root, "_");
+ strcat(Root, CID);
+ strcpy(CMod, CModality);
+ strcat(CMod, "_");
+ strcat(CMod, CStudyID);
+ sprintf(filename, "%s%s%s%s%s%s%s.dcm", Root, PATHSEPSTR, CMod, PATHSEPSTR, CSeries, PATHSEPSTR, CSOPUID);
+ break;
+
+ case 998: // lua filename done by caller
+ strcpy(filename, FileNameSyntaxString);
+ break;
+
+ case 999: // configured filename: any string with %, e.g., %studydate[0,3]\%name_%id\%sopuid.v2
+ filename[0] = 0;
+ i = 0;
+ L = strlen(FileNameSyntaxString);
+ while (i<L)
+ { if (FileNameSyntaxString[i] == '%')
+ { char *ps = filename + strlen(filename);
+
+ i++;
+ p = FileNameSyntaxString + i;
+ if (memcmp(p, "name" , 4)==0) i+=4, strcat(filename, CName);
+ else if (memcmp(p, "id" , 2)==0) i+=2, strcat(filename, CID);
+ else if (memcmp(p, "modality" , 8)==0) i+=8, strcat(filename, CModality);
+ else if (memcmp(p, "studyid" , 7)==0) i+=7, strcat(filename, CStudyID);
+ else if (memcmp(p, "studyuid" , 8)==0) i+=8, strcat(filename, CStudyUID);
+ else if (memcmp(p, "seriesid" , 8)==0) i+=8, strcat(filename, CSeries);
+ else if (memcmp(p, "seriesuid", 9)==0) i+=9, strcat(filename, CSeriesUID);
+ else if (memcmp(p, "sopuid" , 6)==0) i+=6, strcat(filename, CSOPUID);
+ else if (memcmp(p, "imageid" , 7)==0) i+=7, strcat(filename, CImageID);
+ else if (memcmp(p, "imagenum" , 8)==0) i+=8, strcat(filename, CImageNum);
+ else if (memcmp(p, "image" , 5)==0) i+=5, sprintf(filename+strlen(filename), "%06d", iImage);
+ else if (memcmp(p, "series" , 6)==0) i+=6, sprintf(filename+strlen(filename), "%04d", iSeries);
+ else if (memcmp(p, "time" , 4)==0) i+=4, sprintf(filename+strlen(filename), "%u", (unsigned int)time(NULL));
+ else if (memcmp(p, "date" , 4)==0)
+ { i+=4;
+ time_t rawtime;
+ struct tm * timeinfo;
+ char buffer [80];
+
+ time ( &rawtime );
+ timeinfo = localtime ( &rawtime );
+ strftime (buffer,80,"%Y%m%d", timeinfo);
+ sprintf(filename+strlen(filename), "%s", buffer);
+ }
+ else if (memcmp(p, "counter" , 7)==0) i+=7, sprintf(filename+strlen(filename), "%04x", (gl_iFileCounter++) & 0xffff);
+ else if (memcmp(p, "calledae" , 8)==0) i+=8, strcat(filename, Called);
+ else if (memcmp(p, "callingae", 9)==0) i+=9, strcat(filename, Calling);
+ else if (memcmp(p, "studydate", 9)==0) i+=9, strcat(filename, CStudyDate);
+ else if (memcmp(p, "studydesc", 9)==0) i+=9, strcat(filename, CStudyDesc);
+ else if (memcmp(p, "v" , 1)==0) { i+=1+SearchDICOMObject(DDOPtr, p+1, ps); Cleanup(ps); }
+ else if (memcmp(p, "V" , 1)==0) { i+=1+SearchDICOMObject(DDOPtr, p+1, ps); Cleanup(ps); }
+
+
+ // get substring of variable
+ if (FileNameSyntaxString[i]=='[')
+ { int a=0, b=-1;
+ sscanf(FileNameSyntaxString+i, "[%d,%d]", &a, &b);
+ for (;i<L;i++) if (FileNameSyntaxString[i-1]==']') break;
+ if (a>(signed int)strlen(ps)) a=strlen(ps);
+ if (b>(signed int)strlen(ps)) b=strlen(ps);
+ if (b>=a) {memmove(ps, ps+a, b-a+1); ps[b-a+1]=0;}
+ }
+
+ // unrecognized names are not translated and appear as such in filename - good for debugging
+ }
+ else
+ { l = strlen(filename);
+ filename[l] = FileNameSyntaxString[i++];
+ filename[l+1] = 0;
+ }
+ }
+ break;
+
+ default:
+ CID [8] = '\0';
+ CName [8] = '\0';
+ strcpy(Root, CName);
+ strcat(Root, "_");
+ strcat(Root, CID);
+ sprintf(filename, "%s%s%d_%d_%u.v2", Root, PATHSEPSTR, iSeries, iImage, (unsigned int)time(NULL));
+ break;
+ }
+
+ /* Overrule the FileNameSyntax when 'v2' is desired but the DicomObject is
+ not ImplicitLittleEndian, ExplicitLittleEndian or ExplicitBigEndian.
+ In that case, make 'dcm' files.
+ */
+ if ((iFileNameSyntax != 4) &&
+ (iFileNameSyntax != 8) &&
+ (iFileNameSyntax != 9) &&
+ (iFileNameSyntax != 10) &&
+ (iFileNameSyntax != 11) &&
+ (iFileNameSyntax != 12))
+ {
+ VR* pVR;
+ char s[256];
+
+ pVR = DDOPtr->GetVR(0x0002, 0x0010); // TransferSyntaxUID
+ if (pVR && pVR->Data)
+ {
+ strncpy(s, (char*)pVR->Data, pVR->Length);
+ s[pVR->Length] = 0;
+ if ((strcmp(s, "1.2.840.10008.1.2") != 0) &&
+ (strcmp(s, "1.2.840.10008.1.2.1") != 0) &&
+ (strcmp(s, "1.2.840.10008.1.2.2") != 0))
+ strcpy(strrchr(filename, '.'), ".dcm");
+ }
+ }
+
+ GetFileNameSyntax(&maxfilenamelength);
+ maxfilenamelength += strlen(Root) + 1;
+
+ if (strlen(filename) > maxfilenamelength)
+ {
+ strcpy(Path, filename + strlen(Root) + 1 + strlen(filename) - maxfilenamelength);
+ strcpy(filename + strlen(Root) + 1, Path);
+ }
+
+ return ( TRUE );
+ }
+
diff --git a/dgatesop.lst b/dgatesop.lst
new file mode 100644
index 0000000..69315fb
--- /dev/null
+++ b/dgatesop.lst
@@ -0,0 +1,133 @@
+#
+# DICOM Application / sop / transfer UID list.
+#
+# This list is used by the CheckedPDU_Service ( "filename" ) service
+# class. All incoming associations will be verified against this
+# file.
+#
+# Revision 2: disabled GEMRStorage and GECTStorage
+# Revision 3: extended with new sops and with JPEG transfer syntaxes
+# Revision 4: added Modality Worklist query
+#
+#None none RemoteAE
+#None none LocalAE
+#DICOM 1.2.840.10008.3.1.1.1 application
+Verification 1.2.840.10008.1.1 sop
+StoredPrintStorage 1.2.840.10008.5.1.1.27 sop
+HardcopyGrayscaleImageStorage 1.2.840.10008.5.1.1.29 sop
+HardcopyColorImageStorage 1.2.840.10008.5.1.1.30 sop
+CRStorage 1.2.840.10008.5.1.4.1.1.1 sop
+DXStorageForPresentation 1.2.840.10008.5.1.4.1.1.1.1 sop
+DXStorageForProcessing 1.2.840.10008.5.1.4.1.1.1.1.1 sop
+DMStorageForPresentation 1.2.840.10008.5.1.4.1.1.1.2 sop
+DMStorageForProcessing 1.2.840.10008.5.1.4.1.1.1.2.1 sop
+DOralStorageForPresentation 1.2.840.10008.5.1.4.1.1.1.3 sop
+DOralStorageForProcessing 1.2.840.10008.5.1.4.1.1.1.3.1 sop
+CTStorage 1.2.840.10008.5.1.4.1.1.2 sop
+RetiredUSMultiframeStorage 1.2.840.10008.5.1.4.1.1.3 sop
+USMultiframeStorage 1.2.840.10008.5.1.4.1.1.3.1 sop
+MRStorage 1.2.840.10008.5.1.4.1.1.4 sop
+MRImageStorageEnhanced 1.2.840.10008.5.1.4.1.1.4.1 sop
+MRStorageSpectroscopy 1.2.840.10008.5.1.4.1.1.4.2 sop
+RetiredNMStorage 1.2.840.10008.5.1.4.1.1.5 sop
+RetiredUSStorage 1.2.840.10008.5.1.4.1.1.6 sop
+USStorage 1.2.840.10008.5.1.4.1.1.6.1 sop
+SCStorage 1.2.840.10008.5.1.4.1.1.7 sop
+SCStorageSingleBitMF 1.2.840.10008.5.1.4.1.1.7.1 sop
+SCStorageGrayscaleByteMF 1.2.840.10008.5.1.4.1.1.7.2 sop
+SCStorageGrayscaleWordMF 1.2.840.10008.5.1.4.1.1.7.3 sop
+SCStorageTrueColorMF 1.2.840.10008.5.1.4.1.1.7.4 sop
+StandaloneOverlayStorage 1.2.840.10008.5.1.4.1.1.8 sop
+StandaloneCurveStorage 1.2.840.10008.5.1.4.1.1.9 sop
+#WFStorageTwelveLeadECG 1.2.840.10008.5.1.4.1.1.9.1.1 sop
+#WFStorageGeneralECG 1.2.840.10008.5.1.4.1.1.9.1.2 sop
+#WFStorageAmbulatoryECG 1.2.840.10008.5.1.4.1.1.9.1.3 sop
+#WFStorageHemodynamic 1.2.840.10008.5.1.4.1.1.9.2.1 sop
+#WFStorageCardiacElectrophysiology 1.2.840.10008.5.1.4.1.1.9.3.1 sop
+#WFStorageBasicVoiceAudio 1.2.840.10008.5.1.4.1.1.9.4.1 sop
+StandaloneModalityLUTStorage 1.2.840.10008.5.1.4.1.1.10 sop
+StandaloneVOILUTStorage 1.2.840.10008.5.1.4.1.1.11 sop
+GrayscaleSoftcopyPresentationStateStorage 1.2.840.10008.5.1.4.1.1.11.1 sop
+RetiredXASinglePlaneStorage 1.2.840.10008.5.1.4.1.1.12 sop
+XASinglePlaneStorage 1.2.840.10008.5.1.4.1.1.12.1 sop
+RFStorage 1.2.840.10008.5.1.4.1.1.12.2 sop
+XABiPlaneStorage 1.2.840.10008.5.1.4.1.1.12.3 sop
+NMStorage 1.2.840.10008.5.1.4.1.1.20 sop
+VLImageStorage 1.2.840.10008.5.1.4.1.1.77.1 sop
+VLMultiFrameImageStorage 1.2.840.10008.5.1.4.1.1.77.2 sop
+VLMicroscopicSlideStorage 1.2.840.10008.5.1.4.1.1.77.3 sop
+VLPhotographicStorage 1.2.840.10008.5.1.4.1.1.77.4 sop
+VLEndoscopicImageStorage 1.2.840.10008.5.1.4.1.1.77.1.1 sop
+VLMicroscopicImageStorage 1.2.840.10008.5.1.4.1.1.77.1.2 sop
+VLSlideCoordinatesMicroscopicImageStorage 1.2.840.10008.5.1.4.1.1.77.1.3 sop
+VLPhotographicImageStorage 1.2.840.10008.5.1.4.1.1.77.1.4 sop
+BasicTextSR 1.2.840.10008.5.1.4.1.1.88.11 sop
+EnhancedSR 1.2.840.10008.5.1.4.1.1.88.22 sop
+ComprehensiveSR 1.2.840.10008.5.1.4.1.1.88.33 sop
+MammographyCADSR 1.2.840.10008.5.1.4.1.1.88.50 sop
+KeyObjectSelectionDocument 1.2.840.10008.5.1.4.1.1.88.59 sop
+PETStorage 1.2.840.10008.5.1.4.1.1.128 sop
+StandalonePETCurveStorage 1.2.840.10008.5.1.4.1.1.129 sop
+RTImageStorage 1.2.840.10008.5.1.4.1.1.481.1 sop
+RTDoseStorage 1.2.840.10008.5.1.4.1.1.481.2 sop
+RTStructureStorage 1.2.840.10008.5.1.4.1.1.481.3 sop
+RTTreatmentRecordStorage 1.2.840.10008.5.1.4.1.1.481.4 sop
+RTPlanStorage 1.2.840.10008.5.1.4.1.1.481.5 sop
+RTBrachyTreatmentRecordStorage 1.2.840.10008.5.1.4.1.1.481.6 sop
+RTTreatmentSummaryRecordStorage 1.2.840.10008.5.1.4.1.1.481.7 sop
+#GEMRStorage 1.2.840.113619.4.2 sop
+#GECTStorage 1.2.840.113619.4.3 sop
+GE3DModelObjectStorage 1.2.840.113619.4.26 sop
+GERTPlanStorage 1.2.840.113619.5.249 sop
+GERTPlanStorage2 1.2.840.113619.4.5.249 sop
+GESaturnTDSObjectStorage 1.2.840.113619.5.253 sop
+Philips3DVolumeStorage 1.2.46.670589.5.0.1 sop
+Philips3DObjectStorage 1.2.46.670589.5.0.2 sop
+PhilipsSurfaceStorage 1.2.46.670589.5.0.3 sop
+PhilipsCompositeObjectStorage 1.2.46.670589.5.0.4 sop
+PhilipsMRCardioProfileStorage 1.2.46.670589.5.0.7 sop
+PhilipsMRCardioImageStorage 1.2.46.670589.5.0.8 sop
+PatientRootQuery 1.2.840.10008.5.1.4.1.2.1.1 sop
+PatientRootRetrieve 1.2.840.10008.5.1.4.1.2.1.2 sop
+StudyRootQuery 1.2.840.10008.5.1.4.1.2.2.1 sop
+StudyRootRetrieve 1.2.840.10008.5.1.4.1.2.2.2 sop
+PatientStudyOnlyQuery 1.2.840.10008.5.1.4.1.2.3.1 sop
+PatientStudyOnlyRetrieve 1.2.840.10008.5.1.4.1.2.3.2 sop
+PatientRootRetrieveNKI 1.2.826.0.1.3680043.2.135.1066.5.1.4.1.2.1.2 sop
+StudyRootRetrieveNKI 1.2.826.0.1.3680043.2.135.1066.5.1.4.1.2.2.2 sop
+PatientStudyOnlyRetrieveNKI 1.2.826.0.1.3680043.2.135.1066.5.1.4.1.2.3.2 sop
+BasicGrayscalePrintManagementMeta 1.2.840.10008.5.1.1.9 sop
+BasicColorPrintManagementMeta 1.2.840.10008.5.1.1.18 sop
+BasicFilmSession 1.2.840.10008.5.1.1.1 sop
+BasicFilmBox 1.2.840.10008.5.1.1.2 sop
+BasicGrayscaleImageBox 1.2.840.10008.5.1.1.4 sop
+BasicColorImageBox 1.2.840.10008.5.1.1.4.1 sop
+BasicPrinter 1.2.840.10008.5.1.1.16 sop
+FindModalityWorkList 1.2.840.10008.5.1.4.31 sop
+LittleEndianImplicit 1.2.840.10008.1.2 transfer
+LittleEndianExplicit 1.2.840.10008.1.2.1 transfer
+#BigEndianExplicit 1.2.840.10008.1.2.2 transfer
+JPEGBaseLine1 1.2.840.10008.1.2.4.50 transfer LittleEndianExplicit
+JPEGExtended2and4 1.2.840.10008.1.2.4.51 transfer LittleEndianExplicit
+#JPEGExtended3and5 1.2.840.10008.1.2.4.52 transfer LittleEndianExplicit
+#JPEGSpectralNH6and8 1.2.840.10008.1.2.4.53 transfer LittleEndianExplicit
+#JPEGSpectralNH7and9 1.2.840.10008.1.2.4.54 transfer LittleEndianExplicit
+JPEGFulllNH10and12 1.2.840.10008.1.2.4.55 transfer LittleEndianExplicit
+#JPEGFulllNH11and13 1.2.840.10008.1.2.4.56 transfer LittleEndianExplicit
+JPEGLosslessNH14 1.2.840.10008.1.2.4.57 transfer LittleEndianExplicit
+#JPEGLosslessNH15 1.2.840.10008.1.2.4.58 transfer LittleEndianExplicit
+#JPEGExtended16and18 1.2.840.10008.1.2.4.59 transfer LittleEndianExplicit
+#JPEGExtended17and19 1.2.840.10008.1.2.4.60 transfer LittleEndianExplicit
+#JPEGSpectral20and22 1.2.840.10008.1.2.4.61 transfer LittleEndianExplicit
+#JPEGSpectral21and23 1.2.840.10008.1.2.4.62 transfer LittleEndianExplicit
+#JPEGFull24and26 1.2.840.10008.1.2.4.63 transfer LittleEndianExplicit
+#JPEGFull25and27 1.2.840.10008.1.2.4.64 transfer LittleEndianExplicit
+#JPEGLossless28 1.2.840.10008.1.2.4.65 transfer LittleEndianExplicit
+#JPEGLossless29 1.2.840.10008.1.2.4.66 transfer LittleEndianExplicit
+JPEGLossless 1.2.840.10008.1.2.4.70 transfer LittleEndianExplicit
+#JPEGLS_Lossless 1.2.840.10008.1.2.4.80 transfer LittleEndianExplicit
+#JPEGLS_Lossy 1.2.840.10008.1.2.4.81 transfer LittleEndianExplicit
+#RLELossless 1.2.840.10008.1.2.5 transfer LittleEndianExplicit
+#LittleEndianExplicitDeflated 1.2.840.10008.1.2.1.99 transfer LittleEndianExplicit
+JPEG2000LosslessOnly 1.2.840.10008.1.2.4.90 transfer LittleEndianExplicit
+JPEG2000 1.2.840.10008.1.2.4.91 transfer LittleEndianExplicit
diff --git a/dgatesop.lst.nojpg b/dgatesop.lst.nojpg
new file mode 100644
index 0000000..a5c5c07
--- /dev/null
+++ b/dgatesop.lst.nojpg
@@ -0,0 +1,133 @@
+#
+# DICOM Application / sop / transfer UID list.
+#
+# This list is used by the CheckedPDU_Service ( "filename" ) service
+# class. All incoming associations will be verified against this
+# file.
+#
+# Revision 2: disabled GEMRStorage and GECTStorage
+# Revision 3: extended with new sops and with JPEG transfer syntaxes
+# Revision 4: added Modality Worklist query
+#
+#None none RemoteAE
+#None none LocalAE
+#DICOM 1.2.840.10008.3.1.1.1 application
+Verification 1.2.840.10008.1.1 sop
+StoredPrintStorage 1.2.840.10008.5.1.1.27 sop
+HardcopyGrayscaleImageStorage 1.2.840.10008.5.1.1.29 sop
+HardcopyColorImageStorage 1.2.840.10008.5.1.1.30 sop
+CRStorage 1.2.840.10008.5.1.4.1.1.1 sop
+DXStorageForPresentation 1.2.840.10008.5.1.4.1.1.1.1 sop
+DXStorageForProcessing 1.2.840.10008.5.1.4.1.1.1.1.1 sop
+DMStorageForPresentation 1.2.840.10008.5.1.4.1.1.1.2 sop
+DMStorageForProcessing 1.2.840.10008.5.1.4.1.1.1.2.1 sop
+DOralStorageForPresentation 1.2.840.10008.5.1.4.1.1.1.3 sop
+DOralStorageForProcessing 1.2.840.10008.5.1.4.1.1.1.3.1 sop
+CTStorage 1.2.840.10008.5.1.4.1.1.2 sop
+RetiredUSMultiframeStorage 1.2.840.10008.5.1.4.1.1.3 sop
+USMultiframeStorage 1.2.840.10008.5.1.4.1.1.3.1 sop
+MRStorage 1.2.840.10008.5.1.4.1.1.4 sop
+MRImageStorageEnhanced 1.2.840.10008.5.1.4.1.1.4.1 sop
+MRStorageSpectroscopy 1.2.840.10008.5.1.4.1.1.4.2 sop
+RetiredNMStorage 1.2.840.10008.5.1.4.1.1.5 sop
+RetiredUSStorage 1.2.840.10008.5.1.4.1.1.6 sop
+USStorage 1.2.840.10008.5.1.4.1.1.6.1 sop
+SCStorage 1.2.840.10008.5.1.4.1.1.7 sop
+SCStorageSingleBitMF 1.2.840.10008.5.1.4.1.1.7.1 sop
+SCStorageGrayscaleByteMF 1.2.840.10008.5.1.4.1.1.7.2 sop
+SCStorageGrayscaleWordMF 1.2.840.10008.5.1.4.1.1.7.3 sop
+SCStorageTrueColorMF 1.2.840.10008.5.1.4.1.1.7.4 sop
+StandaloneOverlayStorage 1.2.840.10008.5.1.4.1.1.8 sop
+StandaloneCurveStorage 1.2.840.10008.5.1.4.1.1.9 sop
+#WFStorageTwelveLeadECG 1.2.840.10008.5.1.4.1.1.9.1.1 sop
+#WFStorageGeneralECG 1.2.840.10008.5.1.4.1.1.9.1.2 sop
+#WFStorageAmbulatoryECG 1.2.840.10008.5.1.4.1.1.9.1.3 sop
+#WFStorageHemodynamic 1.2.840.10008.5.1.4.1.1.9.2.1 sop
+#WFStorageCardiacElectrophysiology 1.2.840.10008.5.1.4.1.1.9.3.1 sop
+#WFStorageBasicVoiceAudio 1.2.840.10008.5.1.4.1.1.9.4.1 sop
+StandaloneModalityLUTStorage 1.2.840.10008.5.1.4.1.1.10 sop
+StandaloneVOILUTStorage 1.2.840.10008.5.1.4.1.1.11 sop
+GrayscaleSoftcopyPresentationStateStorage 1.2.840.10008.5.1.4.1.1.11.1 sop
+RetiredXASinglePlaneStorage 1.2.840.10008.5.1.4.1.1.12 sop
+XASinglePlaneStorage 1.2.840.10008.5.1.4.1.1.12.1 sop
+RFStorage 1.2.840.10008.5.1.4.1.1.12.2 sop
+XABiPlaneStorage 1.2.840.10008.5.1.4.1.1.12.3 sop
+NMStorage 1.2.840.10008.5.1.4.1.1.20 sop
+VLImageStorage 1.2.840.10008.5.1.4.1.1.77.1 sop
+VLMultiFrameImageStorage 1.2.840.10008.5.1.4.1.1.77.2 sop
+VLMicroscopicSlideStorage 1.2.840.10008.5.1.4.1.1.77.3 sop
+VLPhotographicStorage 1.2.840.10008.5.1.4.1.1.77.4 sop
+VLEndoscopicImageStorage 1.2.840.10008.5.1.4.1.1.77.1.1 sop
+VLMicroscopicImageStorage 1.2.840.10008.5.1.4.1.1.77.1.2 sop
+VLSlideCoordinatesMicroscopicImageStorage 1.2.840.10008.5.1.4.1.1.77.1.3 sop
+VLPhotographicImageStorage 1.2.840.10008.5.1.4.1.1.77.1.4 sop
+BasicTextSR 1.2.840.10008.5.1.4.1.1.88.11 sop
+EnhancedSR 1.2.840.10008.5.1.4.1.1.88.22 sop
+ComprehensiveSR 1.2.840.10008.5.1.4.1.1.88.33 sop
+MammographyCADSR 1.2.840.10008.5.1.4.1.1.88.50 sop
+KeyObjectSelectionDocument 1.2.840.10008.5.1.4.1.1.88.59 sop
+PETStorage 1.2.840.10008.5.1.4.1.1.128 sop
+StandalonePETCurveStorage 1.2.840.10008.5.1.4.1.1.129 sop
+RTImageStorage 1.2.840.10008.5.1.4.1.1.481.1 sop
+RTDoseStorage 1.2.840.10008.5.1.4.1.1.481.2 sop
+RTStructureStorage 1.2.840.10008.5.1.4.1.1.481.3 sop
+RTTreatmentRecordStorage 1.2.840.10008.5.1.4.1.1.481.4 sop
+RTPlanStorage 1.2.840.10008.5.1.4.1.1.481.5 sop
+RTBrachyTreatmentRecordStorage 1.2.840.10008.5.1.4.1.1.481.6 sop
+RTTreatmentSummaryRecordStorage 1.2.840.10008.5.1.4.1.1.481.7 sop
+#GEMRStorage 1.2.840.113619.4.2 sop
+#GECTStorage 1.2.840.113619.4.3 sop
+GE3DModelObjectStorage 1.2.840.113619.4.26 sop
+GERTPlanStorage 1.2.840.113619.5.249 sop
+GERTPlanStorage2 1.2.840.113619.4.5.249 sop
+GESaturnTDSObjectStorage 1.2.840.113619.5.253 sop
+Philips3DVolumeStorage 1.2.46.670589.5.0.1 sop
+Philips3DObjectStorage 1.2.46.670589.5.0.2 sop
+PhilipsSurfaceStorage 1.2.46.670589.5.0.3 sop
+PhilipsCompositeObjectStorage 1.2.46.670589.5.0.4 sop
+PhilipsMRCardioProfileStorage 1.2.46.670589.5.0.7 sop
+PhilipsMRCardioImageStorage 1.2.46.670589.5.0.8 sop
+PatientRootQuery 1.2.840.10008.5.1.4.1.2.1.1 sop
+PatientRootRetrieve 1.2.840.10008.5.1.4.1.2.1.2 sop
+StudyRootQuery 1.2.840.10008.5.1.4.1.2.2.1 sop
+StudyRootRetrieve 1.2.840.10008.5.1.4.1.2.2.2 sop
+PatientStudyOnlyQuery 1.2.840.10008.5.1.4.1.2.3.1 sop
+PatientStudyOnlyRetrieve 1.2.840.10008.5.1.4.1.2.3.2 sop
+PatientRootRetrieveNKI 1.2.826.0.1.3680043.2.135.1066.5.1.4.1.2.1.2 sop
+StudyRootRetrieveNKI 1.2.826.0.1.3680043.2.135.1066.5.1.4.1.2.2.2 sop
+PatientStudyOnlyRetrieveNKI 1.2.826.0.1.3680043.2.135.1066.5.1.4.1.2.3.2 sop
+BasicGrayscalePrintManagementMeta 1.2.840.10008.5.1.1.9 sop
+BasicColorPrintManagementMeta 1.2.840.10008.5.1.1.18 sop
+BasicFilmSession 1.2.840.10008.5.1.1.1 sop
+BasicFilmBox 1.2.840.10008.5.1.1.2 sop
+BasicGrayscaleImageBox 1.2.840.10008.5.1.1.4 sop
+BasicColorImageBox 1.2.840.10008.5.1.1.4.1 sop
+BasicPrinter 1.2.840.10008.5.1.1.16 sop
+FindModalityWorkList 1.2.840.10008.5.1.4.31 sop
+LittleEndianImplicit 1.2.840.10008.1.2 transfer
+#LittleEndianExplicit 1.2.840.10008.1.2.1 transfer
+#BigEndianExplicit 1.2.840.10008.1.2.2 transfer
+#JPEGBaseLine1 1.2.840.10008.1.2.4.50 transfer LittleEndianExplicit
+#JPEGExtended2and4 1.2.840.10008.1.2.4.51 transfer LittleEndianExplicit
+#JPEGExtended3and5 1.2.840.10008.1.2.4.52 transfer LittleEndianExplicit
+#JPEGSpectralNH6and8 1.2.840.10008.1.2.4.53 transfer LittleEndianExplicit
+#JPEGSpectralNH7and9 1.2.840.10008.1.2.4.54 transfer LittleEndianExplicit
+#JPEGFulllNH10and12 1.2.840.10008.1.2.4.55 transfer LittleEndianExplicit
+#JPEGFulllNH11and13 1.2.840.10008.1.2.4.56 transfer LittleEndianExplicit
+#JPEGLosslessNH14 1.2.840.10008.1.2.4.57 transfer LittleEndianExplicit
+#JPEGLosslessNH15 1.2.840.10008.1.2.4.58 transfer LittleEndianExplicit
+#JPEGExtended16and18 1.2.840.10008.1.2.4.59 transfer LittleEndianExplicit
+#JPEGExtended17and19 1.2.840.10008.1.2.4.60 transfer LittleEndianExplicit
+#JPEGSpectral20and22 1.2.840.10008.1.2.4.61 transfer LittleEndianExplicit
+#JPEGSpectral21and23 1.2.840.10008.1.2.4.62 transfer LittleEndianExplicit
+#JPEGFull24and26 1.2.840.10008.1.2.4.63 transfer LittleEndianExplicit
+#JPEGFull25and27 1.2.840.10008.1.2.4.64 transfer LittleEndianExplicit
+#JPEGLossless28 1.2.840.10008.1.2.4.65 transfer LittleEndianExplicit
+#JPEGLossless29 1.2.840.10008.1.2.4.66 transfer LittleEndianExplicit
+#JPEGLossless 1.2.840.10008.1.2.4.70 transfer LittleEndianExplicit
+#JPEGLS_Lossless 1.2.840.10008.1.2.4.80 transfer LittleEndianExplicit
+#JPEGLS_Lossy 1.2.840.10008.1.2.4.81 transfer LittleEndianExplicit
+#RLELossless 1.2.840.10008.1.2.5 transfer LittleEndianExplicit
+#LittleEndianExplicitDeflated 1.2.840.10008.1.2.1.99 transfer LittleEndianExplicit
+#JPEG2000LosslessOnly 1.2.840.10008.1.2.4.90 transfer LittleEndianExplicit
+#JPEG2000 1.2.840.10008.1.2.4.91 transfer LittleEndianExplicit
diff --git a/dgatesop.lst.withjpg b/dgatesop.lst.withjpg
new file mode 100644
index 0000000..69315fb
--- /dev/null
+++ b/dgatesop.lst.withjpg
@@ -0,0 +1,133 @@
+#
+# DICOM Application / sop / transfer UID list.
+#
+# This list is used by the CheckedPDU_Service ( "filename" ) service
+# class. All incoming associations will be verified against this
+# file.
+#
+# Revision 2: disabled GEMRStorage and GECTStorage
+# Revision 3: extended with new sops and with JPEG transfer syntaxes
+# Revision 4: added Modality Worklist query
+#
+#None none RemoteAE
+#None none LocalAE
+#DICOM 1.2.840.10008.3.1.1.1 application
+Verification 1.2.840.10008.1.1 sop
+StoredPrintStorage 1.2.840.10008.5.1.1.27 sop
+HardcopyGrayscaleImageStorage 1.2.840.10008.5.1.1.29 sop
+HardcopyColorImageStorage 1.2.840.10008.5.1.1.30 sop
+CRStorage 1.2.840.10008.5.1.4.1.1.1 sop
+DXStorageForPresentation 1.2.840.10008.5.1.4.1.1.1.1 sop
+DXStorageForProcessing 1.2.840.10008.5.1.4.1.1.1.1.1 sop
+DMStorageForPresentation 1.2.840.10008.5.1.4.1.1.1.2 sop
+DMStorageForProcessing 1.2.840.10008.5.1.4.1.1.1.2.1 sop
+DOralStorageForPresentation 1.2.840.10008.5.1.4.1.1.1.3 sop
+DOralStorageForProcessing 1.2.840.10008.5.1.4.1.1.1.3.1 sop
+CTStorage 1.2.840.10008.5.1.4.1.1.2 sop
+RetiredUSMultiframeStorage 1.2.840.10008.5.1.4.1.1.3 sop
+USMultiframeStorage 1.2.840.10008.5.1.4.1.1.3.1 sop
+MRStorage 1.2.840.10008.5.1.4.1.1.4 sop
+MRImageStorageEnhanced 1.2.840.10008.5.1.4.1.1.4.1 sop
+MRStorageSpectroscopy 1.2.840.10008.5.1.4.1.1.4.2 sop
+RetiredNMStorage 1.2.840.10008.5.1.4.1.1.5 sop
+RetiredUSStorage 1.2.840.10008.5.1.4.1.1.6 sop
+USStorage 1.2.840.10008.5.1.4.1.1.6.1 sop
+SCStorage 1.2.840.10008.5.1.4.1.1.7 sop
+SCStorageSingleBitMF 1.2.840.10008.5.1.4.1.1.7.1 sop
+SCStorageGrayscaleByteMF 1.2.840.10008.5.1.4.1.1.7.2 sop
+SCStorageGrayscaleWordMF 1.2.840.10008.5.1.4.1.1.7.3 sop
+SCStorageTrueColorMF 1.2.840.10008.5.1.4.1.1.7.4 sop
+StandaloneOverlayStorage 1.2.840.10008.5.1.4.1.1.8 sop
+StandaloneCurveStorage 1.2.840.10008.5.1.4.1.1.9 sop
+#WFStorageTwelveLeadECG 1.2.840.10008.5.1.4.1.1.9.1.1 sop
+#WFStorageGeneralECG 1.2.840.10008.5.1.4.1.1.9.1.2 sop
+#WFStorageAmbulatoryECG 1.2.840.10008.5.1.4.1.1.9.1.3 sop
+#WFStorageHemodynamic 1.2.840.10008.5.1.4.1.1.9.2.1 sop
+#WFStorageCardiacElectrophysiology 1.2.840.10008.5.1.4.1.1.9.3.1 sop
+#WFStorageBasicVoiceAudio 1.2.840.10008.5.1.4.1.1.9.4.1 sop
+StandaloneModalityLUTStorage 1.2.840.10008.5.1.4.1.1.10 sop
+StandaloneVOILUTStorage 1.2.840.10008.5.1.4.1.1.11 sop
+GrayscaleSoftcopyPresentationStateStorage 1.2.840.10008.5.1.4.1.1.11.1 sop
+RetiredXASinglePlaneStorage 1.2.840.10008.5.1.4.1.1.12 sop
+XASinglePlaneStorage 1.2.840.10008.5.1.4.1.1.12.1 sop
+RFStorage 1.2.840.10008.5.1.4.1.1.12.2 sop
+XABiPlaneStorage 1.2.840.10008.5.1.4.1.1.12.3 sop
+NMStorage 1.2.840.10008.5.1.4.1.1.20 sop
+VLImageStorage 1.2.840.10008.5.1.4.1.1.77.1 sop
+VLMultiFrameImageStorage 1.2.840.10008.5.1.4.1.1.77.2 sop
+VLMicroscopicSlideStorage 1.2.840.10008.5.1.4.1.1.77.3 sop
+VLPhotographicStorage 1.2.840.10008.5.1.4.1.1.77.4 sop
+VLEndoscopicImageStorage 1.2.840.10008.5.1.4.1.1.77.1.1 sop
+VLMicroscopicImageStorage 1.2.840.10008.5.1.4.1.1.77.1.2 sop
+VLSlideCoordinatesMicroscopicImageStorage 1.2.840.10008.5.1.4.1.1.77.1.3 sop
+VLPhotographicImageStorage 1.2.840.10008.5.1.4.1.1.77.1.4 sop
+BasicTextSR 1.2.840.10008.5.1.4.1.1.88.11 sop
+EnhancedSR 1.2.840.10008.5.1.4.1.1.88.22 sop
+ComprehensiveSR 1.2.840.10008.5.1.4.1.1.88.33 sop
+MammographyCADSR 1.2.840.10008.5.1.4.1.1.88.50 sop
+KeyObjectSelectionDocument 1.2.840.10008.5.1.4.1.1.88.59 sop
+PETStorage 1.2.840.10008.5.1.4.1.1.128 sop
+StandalonePETCurveStorage 1.2.840.10008.5.1.4.1.1.129 sop
+RTImageStorage 1.2.840.10008.5.1.4.1.1.481.1 sop
+RTDoseStorage 1.2.840.10008.5.1.4.1.1.481.2 sop
+RTStructureStorage 1.2.840.10008.5.1.4.1.1.481.3 sop
+RTTreatmentRecordStorage 1.2.840.10008.5.1.4.1.1.481.4 sop
+RTPlanStorage 1.2.840.10008.5.1.4.1.1.481.5 sop
+RTBrachyTreatmentRecordStorage 1.2.840.10008.5.1.4.1.1.481.6 sop
+RTTreatmentSummaryRecordStorage 1.2.840.10008.5.1.4.1.1.481.7 sop
+#GEMRStorage 1.2.840.113619.4.2 sop
+#GECTStorage 1.2.840.113619.4.3 sop
+GE3DModelObjectStorage 1.2.840.113619.4.26 sop
+GERTPlanStorage 1.2.840.113619.5.249 sop
+GERTPlanStorage2 1.2.840.113619.4.5.249 sop
+GESaturnTDSObjectStorage 1.2.840.113619.5.253 sop
+Philips3DVolumeStorage 1.2.46.670589.5.0.1 sop
+Philips3DObjectStorage 1.2.46.670589.5.0.2 sop
+PhilipsSurfaceStorage 1.2.46.670589.5.0.3 sop
+PhilipsCompositeObjectStorage 1.2.46.670589.5.0.4 sop
+PhilipsMRCardioProfileStorage 1.2.46.670589.5.0.7 sop
+PhilipsMRCardioImageStorage 1.2.46.670589.5.0.8 sop
+PatientRootQuery 1.2.840.10008.5.1.4.1.2.1.1 sop
+PatientRootRetrieve 1.2.840.10008.5.1.4.1.2.1.2 sop
+StudyRootQuery 1.2.840.10008.5.1.4.1.2.2.1 sop
+StudyRootRetrieve 1.2.840.10008.5.1.4.1.2.2.2 sop
+PatientStudyOnlyQuery 1.2.840.10008.5.1.4.1.2.3.1 sop
+PatientStudyOnlyRetrieve 1.2.840.10008.5.1.4.1.2.3.2 sop
+PatientRootRetrieveNKI 1.2.826.0.1.3680043.2.135.1066.5.1.4.1.2.1.2 sop
+StudyRootRetrieveNKI 1.2.826.0.1.3680043.2.135.1066.5.1.4.1.2.2.2 sop
+PatientStudyOnlyRetrieveNKI 1.2.826.0.1.3680043.2.135.1066.5.1.4.1.2.3.2 sop
+BasicGrayscalePrintManagementMeta 1.2.840.10008.5.1.1.9 sop
+BasicColorPrintManagementMeta 1.2.840.10008.5.1.1.18 sop
+BasicFilmSession 1.2.840.10008.5.1.1.1 sop
+BasicFilmBox 1.2.840.10008.5.1.1.2 sop
+BasicGrayscaleImageBox 1.2.840.10008.5.1.1.4 sop
+BasicColorImageBox 1.2.840.10008.5.1.1.4.1 sop
+BasicPrinter 1.2.840.10008.5.1.1.16 sop
+FindModalityWorkList 1.2.840.10008.5.1.4.31 sop
+LittleEndianImplicit 1.2.840.10008.1.2 transfer
+LittleEndianExplicit 1.2.840.10008.1.2.1 transfer
+#BigEndianExplicit 1.2.840.10008.1.2.2 transfer
+JPEGBaseLine1 1.2.840.10008.1.2.4.50 transfer LittleEndianExplicit
+JPEGExtended2and4 1.2.840.10008.1.2.4.51 transfer LittleEndianExplicit
+#JPEGExtended3and5 1.2.840.10008.1.2.4.52 transfer LittleEndianExplicit
+#JPEGSpectralNH6and8 1.2.840.10008.1.2.4.53 transfer LittleEndianExplicit
+#JPEGSpectralNH7and9 1.2.840.10008.1.2.4.54 transfer LittleEndianExplicit
+JPEGFulllNH10and12 1.2.840.10008.1.2.4.55 transfer LittleEndianExplicit
+#JPEGFulllNH11and13 1.2.840.10008.1.2.4.56 transfer LittleEndianExplicit
+JPEGLosslessNH14 1.2.840.10008.1.2.4.57 transfer LittleEndianExplicit
+#JPEGLosslessNH15 1.2.840.10008.1.2.4.58 transfer LittleEndianExplicit
+#JPEGExtended16and18 1.2.840.10008.1.2.4.59 transfer LittleEndianExplicit
+#JPEGExtended17and19 1.2.840.10008.1.2.4.60 transfer LittleEndianExplicit
+#JPEGSpectral20and22 1.2.840.10008.1.2.4.61 transfer LittleEndianExplicit
+#JPEGSpectral21and23 1.2.840.10008.1.2.4.62 transfer LittleEndianExplicit
+#JPEGFull24and26 1.2.840.10008.1.2.4.63 transfer LittleEndianExplicit
+#JPEGFull25and27 1.2.840.10008.1.2.4.64 transfer LittleEndianExplicit
+#JPEGLossless28 1.2.840.10008.1.2.4.65 transfer LittleEndianExplicit
+#JPEGLossless29 1.2.840.10008.1.2.4.66 transfer LittleEndianExplicit
+JPEGLossless 1.2.840.10008.1.2.4.70 transfer LittleEndianExplicit
+#JPEGLS_Lossless 1.2.840.10008.1.2.4.80 transfer LittleEndianExplicit
+#JPEGLS_Lossy 1.2.840.10008.1.2.4.81 transfer LittleEndianExplicit
+#RLELossless 1.2.840.10008.1.2.5 transfer LittleEndianExplicit
+#LittleEndianExplicitDeflated 1.2.840.10008.1.2.1.99 transfer LittleEndianExplicit
+JPEG2000LosslessOnly 1.2.840.10008.1.2.4.90 transfer LittleEndianExplicit
+JPEG2000 1.2.840.10008.1.2.4.91 transfer LittleEndianExplicit
diff --git a/dicom.hpp b/dicom.hpp
new file mode 100644
index 0000000..6437fc9
--- /dev/null
+++ b/dicom.hpp
@@ -0,0 +1,83 @@
+/*
+mvh 20071102: Define SetDicomErrorHandler etc
+mvh 20080203: Added experimental ConfigPadAEWithZeros
+mvh 20090211: Added DCM_ERROR_PARSE
+mvh 20090802: Added DCM_ERROR_DEBUG
+bcb 20091231: Changed char* to const char* for gcc4.2 warnings
+mvh 20100111: Merged
+mvh 20110231: DicomError returns FALSE when handler not installed - to allow some errors to pass
+mvh 20110605: Added DCM_ERROR_ASSOCIATION
+*/
+
+//# define DEBUG_VERSION
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/************************************************************************
+ *
+ * Standard Include for all source files.
+ *
+ ***********************************************************************/
+#ifndef _DICOM_H_
+# define _DICOM_H_
+# include "base.hpp" // C Header Files/Base Data Templates
+# include "endian.hpp" // Endian Nuetral types
+# include "constant.h" // Related constants
+# include "version.h" // Version Related Information
+# include "socket.hpp" // Socket Transport Layer
+# include "deivr.hpp" // DICOMObject/DICOMCMDObject/DICOMDATAObject
+# include "rtc.hpp" // Run-Time-Class support of VR
+# include "aarq.hpp" // A-ASSOCIATE-RQ PDU
+# include "aaac.hpp" // A-ASSOCIATE-AC PDU
+# include "aarj.hpp" // A-ASSOCIATE-RJ/A-RELEASE-RQ/A-RELEASE-RP/A-ABORT-RQ
+# include "pdata.hpp" // P-DATA-TF
+# include "pdu.hpp" // PDU Services
+
+# include "dimsec.hpp" // DIMSE-C Services CEchoRQ/RSP, CStoreRQ/RSP
+ // CFindRQ/RSP, CMoveRQ/RSP
+# include "dimsen.hpp" // DIMSE-N Services
+# include "verify.hpp" // Verification SOP Class
+# include "storage.hpp" // CT Storage, MR Storage, etc.
+# include "qrsop.hpp" // Abstract Q/R Classes
+# include "flpdu.hpp" // Checked PDU_Service Class
+
+#define DCM_ERROR_MEMORY 1
+#define DCM_ERROR_PARSE 2
+#define DCM_ERROR_DEBUG 3
+#define DCM_ERROR_ASSOCIATION 4
+
+typedef void (*DeepErrorCall)(int error,const char *message, int info);
+void SetDicomErrorHandler(DeepErrorCall handler);
+BOOL DicomError(int error,const char *message, int info);
+
+extern BOOL ConfigPadAEWithZeros;
+
+#endif
+
diff --git a/dicom.ini b/dicom.ini
new file mode 100644
index 0000000..f750bee
--- /dev/null
+++ b/dicom.ini
@@ -0,0 +1,86 @@
+# This file contains configuration information for the DICOM server
+# Example Linux version using SqLite
+# Copy this file to dicom.ini to use it
+
+
+
+[sscscp]
+MicroPACS = sscscp
+Edition = Personal
+
+# Network configuration: server name and TCP/IP port#
+MyACRNema = CONQUESTSRV1
+TCPPort = 5678
+
+# Reference to other files: known dicom servers; database layout; sops
+ACRNemaMap = acrnema.map
+kFactorFile = dicom.sql
+SOPClassList = dgatesop.lst
+
+# Host for postgres or mysql only, name, username and password for database
+SQLHost = localhost
+SQLServer = ./data/dbase/conquest.db3
+Username = dontcare
+Password = dontcare
+PostGres = 0
+MySQL = 0
+SQLite = 1
+
+UseEscapeStringConstants = 0
+DoubleBackSlashToDB = 0
+#IndexDBF = 1
+#PackDBF = 0
+#LongQueryDBF = 1000
+
+# Configure database
+TruncateFieldNames = 10
+MaxFieldLength = 254
+MaxFileNameLength = 255
+FixPhilips = 0
+FixKodak = 0
+UIDPrefix = 99999.99999
+EnableReadAheadThread = 1
+PatientQuerySortOrder =
+StudyQuerySortOrder =
+SeriesQuerySortOrder =
+ImageQuerySortOrder =
+EnableComputedFields = 1
+TCPIPTimeOut = 300
+FailHoldOff = 60
+RetryDelay = 100
+QueueSize = 128
+WorkListMode = 0
+WorkListReturnsISO_IR_100 = 1
+DebugLevel = 0
+Prefetcher = 0
+LRUSort =
+AllowTruncate =
+DecompressNon16BitsJpeg = 1
+UseBuiltInJPEG = 1
+IgnoreOutOfMemoryErrors = 0
+PadAEWithZeros = 0
+FileNameSyntax = 3
+
+# Configuration of compression for incoming images and archival
+DroppedFileCompression = un
+IncomingCompression = un
+ArchiveCompression = as
+
+# Names of the database tables
+PatientTableName = DICOMPatients
+StudyTableName = DICOMStudies
+SeriesTableName = DICOMSeries
+ImageTableName = DICOMImages
+DMarkTableName = DICOMAccessUpdates
+RegisteredMOPDeviceTable = RegisteredMOPIDs
+UIDToMOPIDTable = UIDToMOPID
+UIDToCDRIDTable = UIDToCDRID
+
+# Banner and host for debug information
+PACSName = CONQUESTSRV1
+OperatorConsole = 127.0.0.1
+
+# Configuration of disk(s) to store images
+MAGDeviceThreshhold = 0
+MAGDevices = 1
+MAGDevice0 = ./data/
diff --git a/dicom.ini.dbase b/dicom.ini.dbase
new file mode 100644
index 0000000..44ca5d0
--- /dev/null
+++ b/dicom.ini.dbase
@@ -0,0 +1,86 @@
+# This file contains configuration information for the DICOM server
+# Example Linux version using built-in dbaseIII file driver
+# Copy this file to dicom.ini to use it
+
+
+
+[sscscp]
+MicroPACS = sscscp
+Edition = Personal
+
+# Network configuration: server name and TCP/IP port#
+MyACRNema = CONQUESTSRV1
+TCPPort = 5678
+
+# Reference to other files: known dicom servers; database layout; sops
+ACRNemaMap = acrnema.map
+kFactorFile = dicom.sql
+SOPClassList = dgatesop.lst
+
+# Host for postgres or mysql only, name, username and password for database
+SQLHost = localhost
+SQLServer = ./data/dbase/
+Username = conquest
+Password = conquest
+PostGres = 0
+MySQL = 0
+SQLite = 0
+
+UseEscapeStringConstants = 0
+DoubleBackSlashToDB = 0
+IndexDBF = 1
+PackDBF = 0
+LongQueryDBF = 1000
+
+# Configure database
+TruncateFieldNames = 10
+MaxFieldLength = 254
+MaxFileNameLength = 255
+FixPhilips = 0
+FixKodak = 0
+UIDPrefix = 99999.99999
+EnableReadAheadThread = 1
+PatientQuerySortOrder =
+StudyQuerySortOrder =
+SeriesQuerySortOrder =
+ImageQuerySortOrder =
+EnableComputedFields = 1
+TCPIPTimeOut = 300
+FailHoldOff = 60
+RetryDelay = 100
+QueueSize = 128
+WorkListMode = 0
+WorkListReturnsISO_IR_100 = 1
+DebugLevel = 0
+Prefetcher = 0
+LRUSort =
+AllowTruncate =
+DecompressNon16BitsJpeg = 1
+UseBuiltInJPEG = 1
+IgnoreOutOfMemoryErrors = 0
+PadAEWithZeros = 0
+FileNameSyntax = 3
+
+# Configuration of compression for incoming images and archival
+DroppedFileCompression = un
+IncomingCompression = un
+ArchiveCompression = as
+
+# Names of the database tables
+PatientTableName = DICOMPatients
+StudyTableName = DICOMStudies
+SeriesTableName = DICOMSeries
+ImageTableName = DICOMImages
+DMarkTableName = DICOMAccessUpdates
+RegisteredMOPDeviceTable = RegisteredMOPIDs
+UIDToMOPIDTable = UIDToMOPID
+UIDToCDRIDTable = UIDToCDRID
+
+# Banner and host for debug information
+PACSName = CONQUESTSRV1
+OperatorConsole = 127.0.0.1
+
+# Configuration of disk(s) to store images
+MAGDeviceThreshhold = 0
+MAGDevices = 1
+MAGDevice0 = ./data/
diff --git a/dicom.ini.mysql b/dicom.ini.mysql
new file mode 100644
index 0000000..a3f1f55
--- /dev/null
+++ b/dicom.ini.mysql
@@ -0,0 +1,86 @@
+# This file contains configuration information for the DICOM server
+# Example Linux version using MySQL
+# Copy this file to dicom.ini to use it
+
+
+
+[sscscp]
+MicroPACS = sscscp
+Edition = Personal
+
+# Network configuration: server name and TCP/IP port#
+MyACRNema = CONQUESTSRV1
+TCPPort = 5678
+
+# Reference to other files: known dicom servers; database layout; sops
+ACRNemaMap = acrnema.map
+kFactorFile = dicom.sql
+SOPClassList = dgatesop.lst
+
+# Host for postgres or mysql only, name, username and password for database
+SQLHost = localhost
+SQLServer = conquest
+Username = root
+Password = user
+PostGres = 0
+MySQL = 1
+SQLite = 0
+
+UseEscapeStringConstants = 0
+DoubleBackSlashToDB = 1
+#IndexDBF = 1
+#PackDBF = 0
+#LongQueryDBF = 1000
+
+# Configure database
+TruncateFieldNames = 10
+MaxFieldLength = 254
+MaxFileNameLength = 255
+FixPhilips = 0
+FixKodak = 0
+UIDPrefix = 99999.99999
+EnableReadAheadThread = 1
+PatientQuerySortOrder =
+StudyQuerySortOrder =
+SeriesQuerySortOrder =
+ImageQuerySortOrder =
+EnableComputedFields = 1
+TCPIPTimeOut = 300
+FailHoldOff = 60
+RetryDelay = 100
+QueueSize = 128
+WorkListMode = 0
+WorkListReturnsISO_IR_100 = 1
+DebugLevel = 0
+Prefetcher = 0
+LRUSort =
+AllowTruncate =
+DecompressNon16BitsJpeg = 1
+UseBuiltInJPEG = 1
+IgnoreOutOfMemoryErrors = 0
+PadAEWithZeros = 0
+FileNameSyntax = 3
+
+# Configuration of compression for incoming images and archival
+DroppedFileCompression = un
+IncomingCompression = un
+ArchiveCompression = as
+
+# Names of the database tables
+PatientTableName = DICOMPatients
+StudyTableName = DICOMStudies
+SeriesTableName = DICOMSeries
+ImageTableName = DICOMImages
+DMarkTableName = DICOMAccessUpdates
+RegisteredMOPDeviceTable = RegisteredMOPIDs
+UIDToMOPIDTable = UIDToMOPID
+UIDToCDRIDTable = UIDToCDRID
+
+# Banner and host for debug information
+PACSName = CONQUESTSRV1
+OperatorConsole = 127.0.0.1
+
+# Configuration of disk(s) to store images
+MAGDeviceThreshhold = 0
+MAGDevices = 1
+MAGDevice0 = ./data/
diff --git a/dicom.ini.postgres b/dicom.ini.postgres
new file mode 100644
index 0000000..4f5925e
--- /dev/null
+++ b/dicom.ini.postgres
@@ -0,0 +1,86 @@
+# This file contains configuration information for the DICOM server
+# Example Linux version using PostGres user postgres, pw postgres
+# Copy this file to dicom.ini to use it
+# 20051218: Set DoubleBackSlashToDB to 1 (needed for postgres)
+# 20100819: Set UseEscapeStringConstants to 1
+
+[sscscp]
+MicroPACS = sscscp
+Edition = Personal
+
+# Network configuration: server name and TCP/IP port#
+MyACRNema = CONQUESTSRV1
+TCPPort = 5678
+
+# Reference to other files: known dicom servers; database layout; sops
+ACRNemaMap = acrnema.map
+kFactorFile = dicom.sql
+SOPClassList = dgatesop.lst
+
+# Host for postgres or mysql only, name, username and password for database
+SQLHost = localhost
+SQLServer = conquest
+Username = postgres
+Password = postgres
+PostGres = 1
+MySQL = 0
+SQLite = 0
+
+UseEscapeStringConstants = 1
+DoubleBackSlashToDB = 1
+#IndexDBF = 1
+#PackDBF = 0
+#LongQueryDBF = 1000
+
+# Configure database
+TruncateFieldNames = 10
+MaxFieldLength = 254
+MaxFileNameLength = 255
+FixPhilips = 0
+FixKodak = 0
+UIDPrefix = 99999.99999
+EnableReadAheadThread = 1
+PatientQuerySortOrder =
+StudyQuerySortOrder =
+SeriesQuerySortOrder =
+ImageQuerySortOrder =
+EnableComputedFields = 1
+TCPIPTimeOut = 300
+FailHoldOff = 60
+RetryDelay = 100
+QueueSize = 128
+WorkListMode = 0
+WorkListReturnsISO_IR_100 = 1
+DebugLevel = 0
+Prefetcher = 0
+LRUSort =
+AllowTruncate =
+DecompressNon16BitsJpeg = 1
+UseBuiltInJPEG = 1
+IgnoreOutOfMemoryErrors = 0
+PadAEWithZeros = 0
+FileNameSyntax = 3
+
+# Configuration of compression for incoming images and archival
+DroppedFileCompression = un
+IncomingCompression = un
+ArchiveCompression = as
+
+# Names of the database tables
+PatientTableName = DICOMPatients
+StudyTableName = DICOMStudies
+SeriesTableName = DICOMSeries
+ImageTableName = DICOMImages
+DMarkTableName = DICOMAccessUpdates
+RegisteredMOPDeviceTable = RegisteredMOPIDs
+UIDToMOPIDTable = UIDToMOPID
+UIDToCDRIDTable = UIDToCDRID
+
+# Banner and host for debug information
+PACSName = CONQUESTSRV1
+OperatorConsole = 127.0.0.1
+
+# Configuration of disk(s) to store images
+MAGDeviceThreshhold = 0
+MAGDevices = 1
+MAGDevice0 = ./data/
diff --git a/dicom.ini.sqlite b/dicom.ini.sqlite
new file mode 100644
index 0000000..f750bee
--- /dev/null
+++ b/dicom.ini.sqlite
@@ -0,0 +1,86 @@
+# This file contains configuration information for the DICOM server
+# Example Linux version using SqLite
+# Copy this file to dicom.ini to use it
+
+
+
+[sscscp]
+MicroPACS = sscscp
+Edition = Personal
+
+# Network configuration: server name and TCP/IP port#
+MyACRNema = CONQUESTSRV1
+TCPPort = 5678
+
+# Reference to other files: known dicom servers; database layout; sops
+ACRNemaMap = acrnema.map
+kFactorFile = dicom.sql
+SOPClassList = dgatesop.lst
+
+# Host for postgres or mysql only, name, username and password for database
+SQLHost = localhost
+SQLServer = ./data/dbase/conquest.db3
+Username = dontcare
+Password = dontcare
+PostGres = 0
+MySQL = 0
+SQLite = 1
+
+UseEscapeStringConstants = 0
+DoubleBackSlashToDB = 0
+#IndexDBF = 1
+#PackDBF = 0
+#LongQueryDBF = 1000
+
+# Configure database
+TruncateFieldNames = 10
+MaxFieldLength = 254
+MaxFileNameLength = 255
+FixPhilips = 0
+FixKodak = 0
+UIDPrefix = 99999.99999
+EnableReadAheadThread = 1
+PatientQuerySortOrder =
+StudyQuerySortOrder =
+SeriesQuerySortOrder =
+ImageQuerySortOrder =
+EnableComputedFields = 1
+TCPIPTimeOut = 300
+FailHoldOff = 60
+RetryDelay = 100
+QueueSize = 128
+WorkListMode = 0
+WorkListReturnsISO_IR_100 = 1
+DebugLevel = 0
+Prefetcher = 0
+LRUSort =
+AllowTruncate =
+DecompressNon16BitsJpeg = 1
+UseBuiltInJPEG = 1
+IgnoreOutOfMemoryErrors = 0
+PadAEWithZeros = 0
+FileNameSyntax = 3
+
+# Configuration of compression for incoming images and archival
+DroppedFileCompression = un
+IncomingCompression = un
+ArchiveCompression = as
+
+# Names of the database tables
+PatientTableName = DICOMPatients
+StudyTableName = DICOMStudies
+SeriesTableName = DICOMSeries
+ImageTableName = DICOMImages
+DMarkTableName = DICOMAccessUpdates
+RegisteredMOPDeviceTable = RegisteredMOPIDs
+UIDToMOPIDTable = UIDToMOPID
+UIDToCDRIDTable = UIDToCDRID
+
+# Banner and host for debug information
+PACSName = CONQUESTSRV1
+OperatorConsole = 127.0.0.1
+
+# Configuration of disk(s) to store images
+MAGDeviceThreshhold = 0
+MAGDevices = 1
+MAGDevice0 = ./data/
diff --git a/dicom.ini.www b/dicom.ini.www
new file mode 100644
index 0000000..007429e
--- /dev/null
+++ b/dicom.ini.www
@@ -0,0 +1,109 @@
+#
+# This file contains configuration information for the conquest cgi web server;
+# it must be in the same directory as the dgate.exe in the web server script directory.
+# For wamp: dgate.exe runs if it is put in C:\wamp\Apache2\cgi-bin
+# The server home page is then "http://127.0.0.1/cgi-bin/dgate.exe?mode=top"
+# The cgi interface has been tested with wamp5, dgate4.12d, and ie6sp1
+#
+# modified 20070213: default to n4, note about ocx only required on client
+# modified 20080902: webreadonly ON; graphics and viewer configs; sample scripted web pages
+# modified 20101121: Added wadoservers section
+#
+
+[sscscp]
+MicroPACS = sscscp
+
+
+# database layout (copy dicom.sql to the web server script directory or point to the one in your dicom server directory)
+
+kFactorFile = .\dicom.sql
+TruncateFieldNames = 10
+
+
+# default IP address and port of DICOM server (may be non-local, web pages empty if wrong)
+# use version 1.4.14 up, if an older version some feautues will not work
+
+WebServerFor = 127.0.0.1
+TCPPort = 5678
+
+
+# path to script engine: ocx will not download images if wrong - shows as black square with controls
+# for wamp: dgate.exe runs if it is put in C:\wamp\Apache2\cgi-bin
+
+WebScriptAddress = http://127.0.0.1/cgi-bin/dgate.exe
+
+
+# web or local location of ActiveFormProj1.ocx for download (include trailing / or \)
+# the activeX control will not download if wrong or security too high - shows as white square with red x
+# note: it only needs to be registered by the client, not the server!
+# for wamp: the ocx canNOT be in C:\wamp\Apache2\cgi-bin, I put it in c:\wamp\www (above cgi-bin)
+# - the default value is derived from WebScriptAddress
+
+#WebCodeBase = http://127.0.0.1/
+
+
+# if set to 1, the web user cannot edit databases and (in future) other things
+
+#WebReadonly = 1
+
+
+# this is an optional virtual directory used to http: all images from mag0
+# this entry is experimental and unused except for viewer=seriesviewer2
+# in this mode (only) ocx will not download images if wrong - shows as black square with
+# controls - the default value is derived from WebScriptAddress
+
+#WebMAG0Address = http://127.0.0.1/mag0
+
+# excerpt from C:\wamp\Apache2\conf\httpd.conf required for WebMAG0Address (un-# there)
+# or use the wamp traybar menu to create the alias
+
+#Alias /mag0/ "c:/dicomserver/data/"
+#
+#<Directory "c:/dicomserver/data">
+# Options Indexes MultiViews
+# AllowOverride None
+# Order allow,deny
+# Allow from all
+#</Directory>
+
+
+# these settings control size of slice and series viewers, max size of transmitted dicom images
+# (0=original), compression for images sent to the activex (may be un,n1..4,j1,j2), the size of
+# the icons in the image list, the image type used for icons and slice display, and the dgate
+# mode containing the viewer (may be seriesviewer, seriesviewer2, noviewer, serversideviewer,
+# or aiviewer - java code of the latter not included with 1.4.14).
+# note: all items require at least one space left and right of the '=' !
+
+[webdefaults]
+size = 560
+dsize = 0
+compress = n4
+iconsize = 48
+graphic = gif
+viewer = serversideviewer
+
+# enter address (up to not including the ?) of the WADO server for each DICOM AE listed
+# the sample (for AE TESTWADOSRV) comes from the DICOM standard and is not valid
+# the default is the local conquest server (which could use virtualservers as WADO bridge)
+
+[wadoservers]
+TESTWADOSRV = http://www.hospital-stmarco/radiology/wado.php
+
+
+# this creates web page http://xxxxx/cgi-bin/dgate.exe?mode=sample
+
+[sample]
+source = sample.cq
+variable = sample 1
+
+
+# this creates web page http://xxxxx/cgi-bin/dgate.exe?mode=sample2
+# Note: in the header parameter newline is written as \
+
+[sample2]
+variable = sample 2
+line0 = <HEAD><TITLE>Conquest DICOM server - %variable%</TITLE></HEAD>
+line1 = <BODY BGCOLOR='CFDFCF'>
+line2 = <H2>Conquest DICOM server - %variable%</H2>
+line3 = </BODY>
+header= Content-type: text/html\Cache-Control: no-cache\
diff --git a/dicom.sql b/dicom.sql
new file mode 100644
index 0000000..b2ed2bb
--- /dev/null
+++ b/dicom.sql
@@ -0,0 +1,153 @@
+/*
+# DICOM Database layout
+# Example version for all SQL servers (mostly normalized)
+#
+# (File DICOM.SQL)
+# ** DO NOT EDIT THIS FILE UNLESS YOU KNOW WHAT YOU ARE DOING **
+#
+# Version with modality moved to the series level and EchoNumber in image table
+# Revision 3: Patient birthday and sex, bolus agent, correct field lengths
+# Revision 4: Studymodality, Station and Department in study
+# Manufacturer, Model, BodyPart and Protocol in series
+# Acqdate/time, coil, acqnumber, slicelocation and pixel info in images
+# Notes for revision 4:
+# InstitutionalDepartmentName in study (should officially be in series, but eFilm expects it in study)
+# StationName is in study (should officially be in series, but more useful in study)
+# Revision 5: Added patientID in series and images for more efficient querying
+# Revision 6: Added frame of reference UID in series table
+# Revision 7: Added ImageType in image table, StudyModality to 64 chars, AcqDate to SQL_C_DATE
+# Revision 8: Denormalized study table (add patient ID, name, birthdate) to show consistency problems
+# Revision 10: Fixed width of ReceivingCoil: to 16 chars
+# Revision 13: Added ImageID to image database
+# Revision 14: Added WorkList database with HL7 tags
+# Revision 16: Moved Stationname and InstitutionalDepartmentName to series table
+# Revision 17: EchoNumber, ReqProcDescription to 64 characters; StudyModality, EchoNumber, ImageType to DT_MSTR; use Institution instead of InstitutionalDepartmentName
+#
+#
+# 5 databases need to be defined:
+#
+# *Patient*
+# *Study*
+# *Series*
+# *Image*
+# *WorkList*
+#
+#
+# The last defined element of Study is a link back to Patient
+# The last defined element of Series is a link back to Study
+# The last defined element of Image is a link back to Series
+#
+#
+# Format for DICOM databases :
+# { Group, Element, Column Name, Column Length, SQL-Type, DICOM-Type }
+# Format for Worklist database :
+# { Group, Element, Column Name, Column Length, SQL-Type, DICOM-Type, HL7 tag}
+# HL7 tags include SEQ.N, SEQ.N.M, SEQ.N.DATE, SEQ.N.TIME, *AN, *UI
+*/
+
+*Patient*
+{
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR }
+}
+
+*Study*
+{
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0008, 0x0020, "StudyDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0030, "StudyTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0020, 0x0010, "StudyID", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1030, "StudyDescription", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0050, "AccessionNumber", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0090, "ReferPhysician", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x1010, "PatientsAge", 16, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x1030, "PatientsWeight", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0061, "StudyModality", 64, SQL_C_CHAR, DT_MSTR },
+
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR }
+
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR }
+}
+
+*Series*
+{
+ { 0x0020, 0x000e, "SeriesInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0020, 0x0011, "SeriesNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0021, "SeriesDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0031, "SeriesTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0008, 0x103e, "SeriesDescription", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0060, "Modality", 16, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x5100, "PatientPosition", 16, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x0010, "ContrastBolusAgent", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0070, "Manufacturer", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1090, "ModelName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x0015, "BodyPartExamined", 64, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x1030, "ProtocolName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1010, "StationName", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0080, "Institution", 64, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x0052, "FrameOfReferenceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0010, 0x0020, "SeriesPat", 64, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI }
+}
+
+*Image*
+{
+ { 0x0008, 0x0018, "SOPInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0008, 0x0016, "SOPClassUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0020, 0x0013, "ImageNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0023, "ImageDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0033, "ImageTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0018, 0x0086, "EchoNumber", 64, SQL_C_CHAR, DT_MSTR },
+ { 0x0028, 0x0008, "NumberOfFrames", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0022, "AcqDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0032, "AcqTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0018, 0x1250, "ReceivingCoil", 16, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x0012, "AcqNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x1041, "SliceLocation", 16, SQL_C_CHAR, DT_STR },
+ { 0x0028, 0x0002, "SamplesPerPixel", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0004, "PhotoMetricInterpretation", 16, SQL_C_CHAR, DT_STR },
+ { 0x0028, 0x0010, "Rows", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0011, "Colums", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0101, "BitsStored", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0008, 0x0008, "ImageType", 128, SQL_C_CHAR, DT_MSTR },
+ { 0x0054, 0x0400, "ImageID", 16, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0020, "ImagePat", 64, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x000e, "SeriesInstanceUID", 64, SQL_C_CHAR, DT_UI }
+}
+
+*WorkList*
+{
+ { 0x0008, 0x0050, "AccessionNumber", 16, SQL_C_CHAR, DT_STR, "OBR.3" },
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR, "PID.4" },
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR, "PID.5" },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE, "PID.7" },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR, "PID.8" },
+
+ { 0x0010, 0x2000, "MedicalAlerts", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0010, 0x2110, "ContrastAllergies", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI, "---" },
+ { 0x0032, 0x1032, "ReqPhysician", 64, SQL_C_CHAR, DT_STR, "OBR.16" },
+ { 0x0032, 0x1060, "ReqProcDescription", 64, SQL_C_CHAR, DT_STR, "OBR.4.1" },
+
+ { 0x0040, 0x0100, "--------", 0, SQL_C_CHAR, DT_STARTSEQUENCE, "---" },
+ { 0x0008, 0x0060, "Modality", 16, SQL_C_CHAR, DT_STR, "OBR.21" },
+ { 0x0032, 0x1070, "ReqContrastAgent", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0001, "ScheduledAE", 16, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0002, "StartDate", 8, SQL_C_DATE, DT_DATE, "OBR.7.DATE" },
+ { 0x0040, 0x0003, "StartTime", 16, SQL_C_CHAR, DT_TIME, "OBR.7.TIME" },
+ { 0x0040, 0x0006, "PerfPhysician", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0007, "SchedPSDescription", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0009, "SchedPSID", 16, SQL_C_CHAR, DT_STR, "OBR.4" },
+ { 0x0040, 0x0010, "SchedStationName", 16, SQL_C_CHAR, DT_STR, "OBR.24" },
+ { 0x0040, 0x0011, "SchedPSLocation", 16, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0012, "PreMedication", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0400, "SchedPSComments", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0100, "---------", 0, SQL_C_CHAR, DT_ENDSEQUENCE, "---" },
+
+ { 0x0040, 0x1001, "ReqProcID", 16, SQL_C_CHAR, DT_STR, "OBR.4.0" },
+ { 0x0040, 0x1003, "ReqProcPriority", 16, SQL_C_CHAR, DT_STR, "OBR.27 }
+}
diff --git a/dicom.sql.dbase b/dicom.sql.dbase
new file mode 100644
index 0000000..7463602
--- /dev/null
+++ b/dicom.sql.dbase
@@ -0,0 +1,187 @@
+/*
+# DICOM Database layout
+# Example version for built-in DbaseIII driver (denormalized)
+#
+# (File DICOM.SQL)
+# ** DO NOT EDIT THIS FILE UNLESS YOU KNOW WHAT YOU ARE DOING **
+#
+# Version with modality moved to the series level and EchoNumber in image table
+# Revision 3: Patient birthday and sex, bolus agent, correct field lengths
+# Revision 4: Studymodality, Station and Department in study
+# Manufacturer, Model, BodyPart and Protocol in series
+# Acqdate/time, coil, acqnumber, slicelocation and pixel info in images
+# Notes for revision 4:
+# InstitutionalDepartmentName in study (should officially be in series, but eFilm expects it in study)
+# StationName is in study (should officially be in series, but more useful in study)
+# Revision 5: Added patientID in series and images for more efficient querying
+# Revision 6: Added frame of reference UID in series table
+# Revision 7: Added ImageType in image table, StudyModality to 64 chars, AcqDate to SQL_C_DATE
+# Revision 8: Denormalized study table (add patient ID, name, birthdate) to show consistency problems
+# Revision 9: Denormalized series and image table for full query support with built-in DBF driver
+# Revision 10: Fixed width of ReceivingCoil: to 16 chars
+# Revision 11: Added Manufacturer to denormalized image table for built-in DBF driver
+# Revision 12: Removed duplicate STUDYINST field in series for built-in DBF driver
+# Revision 15: Added patient position to denormalized image table for built-in DBF driver
+# Revision 13: Added ImageID to image database
+# Revision 14: Added WorkList database with HL7 tags
+# Revision 16: Moved Stationname and InstitutionalDepartmentName to series table
+# Revision 17: EchoNumber, ReqProcDescription to 64 characters; StudyModality, EchoNumber, ImageType to DT_MSTR; use Institution instead of InstitutionalDepartmentName
+#
+#
+# 5 databases need to be defined:
+#
+# *Patient*
+# *Study*
+# *Series*
+# *Image*
+# *WorkList*
+#
+#
+# The last defined element of Study is a link back to Patient
+# The last defined element of Series is a link back to Study
+# The last defined element of Image is a link back to Series
+#
+#
+# Format for DICOM databases :
+# { Group, Element, Column Name, Column Length, SQL-Type, DICOM-Type }
+# Format for Worklist database :
+# { Group, Element, Column Name, Column Length, SQL-Type, DICOM-Type, HL7 tag}
+# HL7 tags include SEQ.N, SEQ.N.M, SEQ.N.DATE, SEQ.N.TIME, *AN, *UI
+*/
+
+*Patient*
+{
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR }
+}
+
+*Study*
+{
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0008, 0x0020, "StudyDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0030, "StudyTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0020, 0x0010, "StudyID", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1030, "StudyDescription", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0050, "AccessionNumber", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0090, "ReferPhysician", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x1010, "PatientsAge", 16, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x1030, "PatientsWeight", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0061, "StudyModality", 64, SQL_C_CHAR, DT_MSTR },
+
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR }
+
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR }
+}
+
+*Series*
+{
+ { 0x0020, 0x000e, "SeriesInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0020, 0x0011, "SeriesNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0021, "SeriesDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0031, "SeriesTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0008, 0x103e, "SeriesDescription", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0060, "Modality", 16, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x5100, "PatientPosition", 16, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x0010, "ContrastBolusAgent", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0070, "Manufacturer", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1090, "ModelName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x0015, "BodyPartExamined", 64, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x1030, "ProtocolName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1010, "StationName", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0080, "Institution", 64, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x0052, "FrameOfReferenceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0010, 0x0020, "SeriesPat", 64, SQL_C_CHAR, DT_STR },
+
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR }
+
+ { 0x0008, 0x0020, "StudyDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0030, "StudyTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0020, 0x0010, "StudyID", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1030, "StudyDescription", 64, SQL_C_CHAR, DT_STR },
+
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI }
+}
+
+*Image*
+{
+ { 0x0008, 0x0018, "SOPInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0008, 0x0016, "SOPClassUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0020, 0x0013, "ImageNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0023, "ImageDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0033, "ImageTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0018, 0x0086, "EchoNumber", 64, SQL_C_CHAR, DT_MSTR },
+ { 0x0028, 0x0008, "NumberOfFrames", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0022, "AcqDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0032, "AcqTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0018, 0x1250, "ReceivingCoil", 16, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x0012, "AcqNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x1041, "SliceLocation", 16, SQL_C_CHAR, DT_STR },
+ { 0x0028, 0x0002, "SamplesPerPixel", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0004, "PhotoMetricInterpretation", 16, SQL_C_CHAR, DT_STR },
+ { 0x0028, 0x0010, "Rows", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0011, "Colums", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0101, "BitsStored", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0008, 0x0008, "ImageType", 128, SQL_C_CHAR, DT_MSTR },
+ { 0x0054, 0x0400, "ImageID", 16, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0020, "ImagePat", 64, SQL_C_CHAR, DT_STR },
+
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR }
+
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0008, 0x0020, "StudyDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0030, "StudyTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0020, 0x0010, "StudyID", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1030, "StudyDescription", 64, SQL_C_CHAR, DT_STR },
+
+ { 0x0020, 0x0011, "SeriesNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0021, "SeriesDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0031, "SeriesTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0008, 0x103e, "SeriesDescription", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0060, "Modality", 16, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x5100, "PatientPosition", 16, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x0052, "FrameOfReferenceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0008, 0x0070, "Manufacturer", 64, SQL_C_CHAR, DT_STR },
+
+ { 0x0020, 0x000e, "SeriesInstanceUID", 64, SQL_C_CHAR, DT_UI }
+}
+
+*WorkList*
+{
+ { 0x0008, 0x0050, "AccessionNumber", 16, SQL_C_CHAR, DT_STR, "OBR.3" },
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR, "PID.4" },
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR, "PID.5" },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE, "PID.7" },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR, "PID.8" },
+
+ { 0x0010, 0x2000, "MedicalAlerts", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0010, 0x2110, "ContrastAllergies", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI, "---" },
+ { 0x0032, 0x1032, "ReqPhysician", 64, SQL_C_CHAR, DT_STR, "OBR.16" },
+ { 0x0032, 0x1060, "ReqProcDescription", 64, SQL_C_CHAR, DT_STR, "OBR.4.1" },
+
+ { 0x0040, 0x0100, "--------", 0, SQL_C_CHAR, DT_STARTSEQUENCE, "---" },
+ { 0x0008, 0x0060, "Modality", 16, SQL_C_CHAR, DT_STR, "OBR.21" },
+ { 0x0032, 0x1070, "ReqContrastAgent", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0001, "ScheduledAE", 16, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0002, "StartDate", 8, SQL_C_DATE, DT_DATE, "OBR.7.DATE" },
+ { 0x0040, 0x0003, "StartTime", 16, SQL_C_CHAR, DT_TIME, "OBR.7.TIME" },
+ { 0x0040, 0x0006, "PerfPhysician", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0007, "SchedPSDescription", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0009, "SchedPSID", 16, SQL_C_CHAR, DT_STR, "OBR.4" },
+ { 0x0040, 0x0010, "SchedStationName", 16, SQL_C_CHAR, DT_STR, "OBR.24" },
+ { 0x0040, 0x0011, "SchedPSLocation", 16, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0012, "PreMedication", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0400, "SchedPSComments", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0100, "---------", 0, SQL_C_CHAR, DT_ENDSEQUENCE, "---" },
+
+ { 0x0040, 0x1001, "ReqProcID", 16, SQL_C_CHAR, DT_STR, "OBR.4.0" },
+ { 0x0040, 0x1003, "ReqProcPriority", 16, SQL_C_CHAR, DT_STR, "OBR.27 }
+}
diff --git a/dicom.sql.mysql b/dicom.sql.mysql
new file mode 100644
index 0000000..b2ed2bb
--- /dev/null
+++ b/dicom.sql.mysql
@@ -0,0 +1,153 @@
+/*
+# DICOM Database layout
+# Example version for all SQL servers (mostly normalized)
+#
+# (File DICOM.SQL)
+# ** DO NOT EDIT THIS FILE UNLESS YOU KNOW WHAT YOU ARE DOING **
+#
+# Version with modality moved to the series level and EchoNumber in image table
+# Revision 3: Patient birthday and sex, bolus agent, correct field lengths
+# Revision 4: Studymodality, Station and Department in study
+# Manufacturer, Model, BodyPart and Protocol in series
+# Acqdate/time, coil, acqnumber, slicelocation and pixel info in images
+# Notes for revision 4:
+# InstitutionalDepartmentName in study (should officially be in series, but eFilm expects it in study)
+# StationName is in study (should officially be in series, but more useful in study)
+# Revision 5: Added patientID in series and images for more efficient querying
+# Revision 6: Added frame of reference UID in series table
+# Revision 7: Added ImageType in image table, StudyModality to 64 chars, AcqDate to SQL_C_DATE
+# Revision 8: Denormalized study table (add patient ID, name, birthdate) to show consistency problems
+# Revision 10: Fixed width of ReceivingCoil: to 16 chars
+# Revision 13: Added ImageID to image database
+# Revision 14: Added WorkList database with HL7 tags
+# Revision 16: Moved Stationname and InstitutionalDepartmentName to series table
+# Revision 17: EchoNumber, ReqProcDescription to 64 characters; StudyModality, EchoNumber, ImageType to DT_MSTR; use Institution instead of InstitutionalDepartmentName
+#
+#
+# 5 databases need to be defined:
+#
+# *Patient*
+# *Study*
+# *Series*
+# *Image*
+# *WorkList*
+#
+#
+# The last defined element of Study is a link back to Patient
+# The last defined element of Series is a link back to Study
+# The last defined element of Image is a link back to Series
+#
+#
+# Format for DICOM databases :
+# { Group, Element, Column Name, Column Length, SQL-Type, DICOM-Type }
+# Format for Worklist database :
+# { Group, Element, Column Name, Column Length, SQL-Type, DICOM-Type, HL7 tag}
+# HL7 tags include SEQ.N, SEQ.N.M, SEQ.N.DATE, SEQ.N.TIME, *AN, *UI
+*/
+
+*Patient*
+{
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR }
+}
+
+*Study*
+{
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0008, 0x0020, "StudyDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0030, "StudyTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0020, 0x0010, "StudyID", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1030, "StudyDescription", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0050, "AccessionNumber", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0090, "ReferPhysician", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x1010, "PatientsAge", 16, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x1030, "PatientsWeight", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0061, "StudyModality", 64, SQL_C_CHAR, DT_MSTR },
+
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR }
+
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR }
+}
+
+*Series*
+{
+ { 0x0020, 0x000e, "SeriesInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0020, 0x0011, "SeriesNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0021, "SeriesDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0031, "SeriesTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0008, 0x103e, "SeriesDescription", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0060, "Modality", 16, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x5100, "PatientPosition", 16, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x0010, "ContrastBolusAgent", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0070, "Manufacturer", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1090, "ModelName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x0015, "BodyPartExamined", 64, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x1030, "ProtocolName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1010, "StationName", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0080, "Institution", 64, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x0052, "FrameOfReferenceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0010, 0x0020, "SeriesPat", 64, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI }
+}
+
+*Image*
+{
+ { 0x0008, 0x0018, "SOPInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0008, 0x0016, "SOPClassUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0020, 0x0013, "ImageNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0023, "ImageDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0033, "ImageTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0018, 0x0086, "EchoNumber", 64, SQL_C_CHAR, DT_MSTR },
+ { 0x0028, 0x0008, "NumberOfFrames", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0022, "AcqDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0032, "AcqTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0018, 0x1250, "ReceivingCoil", 16, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x0012, "AcqNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x1041, "SliceLocation", 16, SQL_C_CHAR, DT_STR },
+ { 0x0028, 0x0002, "SamplesPerPixel", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0004, "PhotoMetricInterpretation", 16, SQL_C_CHAR, DT_STR },
+ { 0x0028, 0x0010, "Rows", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0011, "Colums", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0101, "BitsStored", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0008, 0x0008, "ImageType", 128, SQL_C_CHAR, DT_MSTR },
+ { 0x0054, 0x0400, "ImageID", 16, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0020, "ImagePat", 64, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x000e, "SeriesInstanceUID", 64, SQL_C_CHAR, DT_UI }
+}
+
+*WorkList*
+{
+ { 0x0008, 0x0050, "AccessionNumber", 16, SQL_C_CHAR, DT_STR, "OBR.3" },
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR, "PID.4" },
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR, "PID.5" },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE, "PID.7" },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR, "PID.8" },
+
+ { 0x0010, 0x2000, "MedicalAlerts", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0010, 0x2110, "ContrastAllergies", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI, "---" },
+ { 0x0032, 0x1032, "ReqPhysician", 64, SQL_C_CHAR, DT_STR, "OBR.16" },
+ { 0x0032, 0x1060, "ReqProcDescription", 64, SQL_C_CHAR, DT_STR, "OBR.4.1" },
+
+ { 0x0040, 0x0100, "--------", 0, SQL_C_CHAR, DT_STARTSEQUENCE, "---" },
+ { 0x0008, 0x0060, "Modality", 16, SQL_C_CHAR, DT_STR, "OBR.21" },
+ { 0x0032, 0x1070, "ReqContrastAgent", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0001, "ScheduledAE", 16, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0002, "StartDate", 8, SQL_C_DATE, DT_DATE, "OBR.7.DATE" },
+ { 0x0040, 0x0003, "StartTime", 16, SQL_C_CHAR, DT_TIME, "OBR.7.TIME" },
+ { 0x0040, 0x0006, "PerfPhysician", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0007, "SchedPSDescription", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0009, "SchedPSID", 16, SQL_C_CHAR, DT_STR, "OBR.4" },
+ { 0x0040, 0x0010, "SchedStationName", 16, SQL_C_CHAR, DT_STR, "OBR.24" },
+ { 0x0040, 0x0011, "SchedPSLocation", 16, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0012, "PreMedication", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0400, "SchedPSComments", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0100, "---------", 0, SQL_C_CHAR, DT_ENDSEQUENCE, "---" },
+
+ { 0x0040, 0x1001, "ReqProcID", 16, SQL_C_CHAR, DT_STR, "OBR.4.0" },
+ { 0x0040, 0x1003, "ReqProcPriority", 16, SQL_C_CHAR, DT_STR, "OBR.27 }
+}
diff --git a/dicom.sql.postgres b/dicom.sql.postgres
new file mode 100644
index 0000000..b2ed2bb
--- /dev/null
+++ b/dicom.sql.postgres
@@ -0,0 +1,153 @@
+/*
+# DICOM Database layout
+# Example version for all SQL servers (mostly normalized)
+#
+# (File DICOM.SQL)
+# ** DO NOT EDIT THIS FILE UNLESS YOU KNOW WHAT YOU ARE DOING **
+#
+# Version with modality moved to the series level and EchoNumber in image table
+# Revision 3: Patient birthday and sex, bolus agent, correct field lengths
+# Revision 4: Studymodality, Station and Department in study
+# Manufacturer, Model, BodyPart and Protocol in series
+# Acqdate/time, coil, acqnumber, slicelocation and pixel info in images
+# Notes for revision 4:
+# InstitutionalDepartmentName in study (should officially be in series, but eFilm expects it in study)
+# StationName is in study (should officially be in series, but more useful in study)
+# Revision 5: Added patientID in series and images for more efficient querying
+# Revision 6: Added frame of reference UID in series table
+# Revision 7: Added ImageType in image table, StudyModality to 64 chars, AcqDate to SQL_C_DATE
+# Revision 8: Denormalized study table (add patient ID, name, birthdate) to show consistency problems
+# Revision 10: Fixed width of ReceivingCoil: to 16 chars
+# Revision 13: Added ImageID to image database
+# Revision 14: Added WorkList database with HL7 tags
+# Revision 16: Moved Stationname and InstitutionalDepartmentName to series table
+# Revision 17: EchoNumber, ReqProcDescription to 64 characters; StudyModality, EchoNumber, ImageType to DT_MSTR; use Institution instead of InstitutionalDepartmentName
+#
+#
+# 5 databases need to be defined:
+#
+# *Patient*
+# *Study*
+# *Series*
+# *Image*
+# *WorkList*
+#
+#
+# The last defined element of Study is a link back to Patient
+# The last defined element of Series is a link back to Study
+# The last defined element of Image is a link back to Series
+#
+#
+# Format for DICOM databases :
+# { Group, Element, Column Name, Column Length, SQL-Type, DICOM-Type }
+# Format for Worklist database :
+# { Group, Element, Column Name, Column Length, SQL-Type, DICOM-Type, HL7 tag}
+# HL7 tags include SEQ.N, SEQ.N.M, SEQ.N.DATE, SEQ.N.TIME, *AN, *UI
+*/
+
+*Patient*
+{
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR }
+}
+
+*Study*
+{
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0008, 0x0020, "StudyDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0030, "StudyTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0020, 0x0010, "StudyID", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1030, "StudyDescription", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0050, "AccessionNumber", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0090, "ReferPhysician", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x1010, "PatientsAge", 16, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x1030, "PatientsWeight", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0061, "StudyModality", 64, SQL_C_CHAR, DT_MSTR },
+
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR }
+
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR }
+}
+
+*Series*
+{
+ { 0x0020, 0x000e, "SeriesInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0020, 0x0011, "SeriesNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0021, "SeriesDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0031, "SeriesTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0008, 0x103e, "SeriesDescription", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0060, "Modality", 16, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x5100, "PatientPosition", 16, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x0010, "ContrastBolusAgent", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0070, "Manufacturer", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1090, "ModelName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x0015, "BodyPartExamined", 64, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x1030, "ProtocolName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1010, "StationName", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0080, "Institution", 64, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x0052, "FrameOfReferenceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0010, 0x0020, "SeriesPat", 64, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI }
+}
+
+*Image*
+{
+ { 0x0008, 0x0018, "SOPInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0008, 0x0016, "SOPClassUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0020, 0x0013, "ImageNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0023, "ImageDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0033, "ImageTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0018, 0x0086, "EchoNumber", 64, SQL_C_CHAR, DT_MSTR },
+ { 0x0028, 0x0008, "NumberOfFrames", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0022, "AcqDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0032, "AcqTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0018, 0x1250, "ReceivingCoil", 16, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x0012, "AcqNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x1041, "SliceLocation", 16, SQL_C_CHAR, DT_STR },
+ { 0x0028, 0x0002, "SamplesPerPixel", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0004, "PhotoMetricInterpretation", 16, SQL_C_CHAR, DT_STR },
+ { 0x0028, 0x0010, "Rows", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0011, "Colums", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0101, "BitsStored", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0008, 0x0008, "ImageType", 128, SQL_C_CHAR, DT_MSTR },
+ { 0x0054, 0x0400, "ImageID", 16, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0020, "ImagePat", 64, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x000e, "SeriesInstanceUID", 64, SQL_C_CHAR, DT_UI }
+}
+
+*WorkList*
+{
+ { 0x0008, 0x0050, "AccessionNumber", 16, SQL_C_CHAR, DT_STR, "OBR.3" },
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR, "PID.4" },
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR, "PID.5" },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE, "PID.7" },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR, "PID.8" },
+
+ { 0x0010, 0x2000, "MedicalAlerts", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0010, 0x2110, "ContrastAllergies", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI, "---" },
+ { 0x0032, 0x1032, "ReqPhysician", 64, SQL_C_CHAR, DT_STR, "OBR.16" },
+ { 0x0032, 0x1060, "ReqProcDescription", 64, SQL_C_CHAR, DT_STR, "OBR.4.1" },
+
+ { 0x0040, 0x0100, "--------", 0, SQL_C_CHAR, DT_STARTSEQUENCE, "---" },
+ { 0x0008, 0x0060, "Modality", 16, SQL_C_CHAR, DT_STR, "OBR.21" },
+ { 0x0032, 0x1070, "ReqContrastAgent", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0001, "ScheduledAE", 16, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0002, "StartDate", 8, SQL_C_DATE, DT_DATE, "OBR.7.DATE" },
+ { 0x0040, 0x0003, "StartTime", 16, SQL_C_CHAR, DT_TIME, "OBR.7.TIME" },
+ { 0x0040, 0x0006, "PerfPhysician", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0007, "SchedPSDescription", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0009, "SchedPSID", 16, SQL_C_CHAR, DT_STR, "OBR.4" },
+ { 0x0040, 0x0010, "SchedStationName", 16, SQL_C_CHAR, DT_STR, "OBR.24" },
+ { 0x0040, 0x0011, "SchedPSLocation", 16, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0012, "PreMedication", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0400, "SchedPSComments", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0100, "---------", 0, SQL_C_CHAR, DT_ENDSEQUENCE, "---" },
+
+ { 0x0040, 0x1001, "ReqProcID", 16, SQL_C_CHAR, DT_STR, "OBR.4.0" },
+ { 0x0040, 0x1003, "ReqProcPriority", 16, SQL_C_CHAR, DT_STR, "OBR.27 }
+}
diff --git a/dicom.sql.sqlite b/dicom.sql.sqlite
new file mode 100644
index 0000000..b2ed2bb
--- /dev/null
+++ b/dicom.sql.sqlite
@@ -0,0 +1,153 @@
+/*
+# DICOM Database layout
+# Example version for all SQL servers (mostly normalized)
+#
+# (File DICOM.SQL)
+# ** DO NOT EDIT THIS FILE UNLESS YOU KNOW WHAT YOU ARE DOING **
+#
+# Version with modality moved to the series level and EchoNumber in image table
+# Revision 3: Patient birthday and sex, bolus agent, correct field lengths
+# Revision 4: Studymodality, Station and Department in study
+# Manufacturer, Model, BodyPart and Protocol in series
+# Acqdate/time, coil, acqnumber, slicelocation and pixel info in images
+# Notes for revision 4:
+# InstitutionalDepartmentName in study (should officially be in series, but eFilm expects it in study)
+# StationName is in study (should officially be in series, but more useful in study)
+# Revision 5: Added patientID in series and images for more efficient querying
+# Revision 6: Added frame of reference UID in series table
+# Revision 7: Added ImageType in image table, StudyModality to 64 chars, AcqDate to SQL_C_DATE
+# Revision 8: Denormalized study table (add patient ID, name, birthdate) to show consistency problems
+# Revision 10: Fixed width of ReceivingCoil: to 16 chars
+# Revision 13: Added ImageID to image database
+# Revision 14: Added WorkList database with HL7 tags
+# Revision 16: Moved Stationname and InstitutionalDepartmentName to series table
+# Revision 17: EchoNumber, ReqProcDescription to 64 characters; StudyModality, EchoNumber, ImageType to DT_MSTR; use Institution instead of InstitutionalDepartmentName
+#
+#
+# 5 databases need to be defined:
+#
+# *Patient*
+# *Study*
+# *Series*
+# *Image*
+# *WorkList*
+#
+#
+# The last defined element of Study is a link back to Patient
+# The last defined element of Series is a link back to Study
+# The last defined element of Image is a link back to Series
+#
+#
+# Format for DICOM databases :
+# { Group, Element, Column Name, Column Length, SQL-Type, DICOM-Type }
+# Format for Worklist database :
+# { Group, Element, Column Name, Column Length, SQL-Type, DICOM-Type, HL7 tag}
+# HL7 tags include SEQ.N, SEQ.N.M, SEQ.N.DATE, SEQ.N.TIME, *AN, *UI
+*/
+
+*Patient*
+{
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR }
+}
+
+*Study*
+{
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0008, 0x0020, "StudyDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0030, "StudyTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0020, 0x0010, "StudyID", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1030, "StudyDescription", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0050, "AccessionNumber", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0090, "ReferPhysician", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x1010, "PatientsAge", 16, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x1030, "PatientsWeight", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0061, "StudyModality", 64, SQL_C_CHAR, DT_MSTR },
+
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR }
+
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR }
+}
+
+*Series*
+{
+ { 0x0020, 0x000e, "SeriesInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0020, 0x0011, "SeriesNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0021, "SeriesDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0031, "SeriesTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0008, 0x103e, "SeriesDescription", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0060, "Modality", 16, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x5100, "PatientPosition", 16, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x0010, "ContrastBolusAgent", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0070, "Manufacturer", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1090, "ModelName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x0015, "BodyPartExamined", 64, SQL_C_CHAR, DT_STR },
+ { 0x0018, 0x1030, "ProtocolName", 64, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x1010, "StationName", 16, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0080, "Institution", 64, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x0052, "FrameOfReferenceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0010, 0x0020, "SeriesPat", 64, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI }
+}
+
+*Image*
+{
+ { 0x0008, 0x0018, "SOPInstanceUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0008, 0x0016, "SOPClassUID", 64, SQL_C_CHAR, DT_UI },
+ { 0x0020, 0x0013, "ImageNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0023, "ImageDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0033, "ImageTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0018, 0x0086, "EchoNumber", 64, SQL_C_CHAR, DT_MSTR },
+ { 0x0028, 0x0008, "NumberOfFrames", 12, SQL_C_CHAR, DT_STR },
+ { 0x0008, 0x0022, "AcqDate", 8, SQL_C_DATE, DT_DATE },
+ { 0x0008, 0x0032, "AcqTime", 16, SQL_C_CHAR, DT_TIME },
+ { 0x0018, 0x1250, "ReceivingCoil", 16, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x0012, "AcqNumber", 12, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x1041, "SliceLocation", 16, SQL_C_CHAR, DT_STR },
+ { 0x0028, 0x0002, "SamplesPerPixel", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0004, "PhotoMetricInterpretation", 16, SQL_C_CHAR, DT_STR },
+ { 0x0028, 0x0010, "Rows", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0011, "Colums", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0028, 0x0101, "BitsStored", 5, SQL_C_CHAR, DT_UINT16 },
+ { 0x0008, 0x0008, "ImageType", 128, SQL_C_CHAR, DT_MSTR },
+ { 0x0054, 0x0400, "ImageID", 16, SQL_C_CHAR, DT_STR },
+ { 0x0010, 0x0020, "ImagePat", 64, SQL_C_CHAR, DT_STR },
+ { 0x0020, 0x000e, "SeriesInstanceUID", 64, SQL_C_CHAR, DT_UI }
+}
+
+*WorkList*
+{
+ { 0x0008, 0x0050, "AccessionNumber", 16, SQL_C_CHAR, DT_STR, "OBR.3" },
+ { 0x0010, 0x0020, "PatientID", 64, SQL_C_CHAR, DT_STR, "PID.4" },
+ { 0x0010, 0x0010, "PatientName", 64, SQL_C_CHAR, DT_STR, "PID.5" },
+ { 0x0010, 0x0030, "PatientBirthDate", 8, SQL_C_DATE, DT_DATE, "PID.7" },
+ { 0x0010, 0x0040, "PatientSex", 16, SQL_C_CHAR, DT_STR, "PID.8" },
+
+ { 0x0010, 0x2000, "MedicalAlerts", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0010, 0x2110, "ContrastAllergies", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0020, 0x000d, "StudyInstanceUID", 64, SQL_C_CHAR, DT_UI, "---" },
+ { 0x0032, 0x1032, "ReqPhysician", 64, SQL_C_CHAR, DT_STR, "OBR.16" },
+ { 0x0032, 0x1060, "ReqProcDescription", 64, SQL_C_CHAR, DT_STR, "OBR.4.1" },
+
+ { 0x0040, 0x0100, "--------", 0, SQL_C_CHAR, DT_STARTSEQUENCE, "---" },
+ { 0x0008, 0x0060, "Modality", 16, SQL_C_CHAR, DT_STR, "OBR.21" },
+ { 0x0032, 0x1070, "ReqContrastAgent", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0001, "ScheduledAE", 16, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0002, "StartDate", 8, SQL_C_DATE, DT_DATE, "OBR.7.DATE" },
+ { 0x0040, 0x0003, "StartTime", 16, SQL_C_CHAR, DT_TIME, "OBR.7.TIME" },
+ { 0x0040, 0x0006, "PerfPhysician", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0007, "SchedPSDescription", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0009, "SchedPSID", 16, SQL_C_CHAR, DT_STR, "OBR.4" },
+ { 0x0040, 0x0010, "SchedStationName", 16, SQL_C_CHAR, DT_STR, "OBR.24" },
+ { 0x0040, 0x0011, "SchedPSLocation", 16, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0012, "PreMedication", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0400, "SchedPSComments", 64, SQL_C_CHAR, DT_STR, "---" },
+ { 0x0040, 0x0100, "---------", 0, SQL_C_CHAR, DT_ENDSEQUENCE, "---" },
+
+ { 0x0040, 0x1001, "ReqProcID", 16, SQL_C_CHAR, DT_STR, "OBR.4.0" },
+ { 0x0040, 0x1003, "ReqProcPriority", 16, SQL_C_CHAR, DT_STR, "OBR.27 }
+}
diff --git a/dimsec.cxx b/dimsec.cxx
new file mode 100644
index 0000000..e88989c
--- /dev/null
+++ b/dimsec.cxx
@@ -0,0 +1,814 @@
+/*
+20030219 ljz Removed MessageID and Priority from the 'write' functions
+ of CStoreRSP, CFindRSP and CMoveRSP
+20030606 ljz Added parameter 'QueryRetrieveLevel' to CFindRSP::Write
+20030811 ljz Do not send DDO in CMoveRSP::Write (DicomEye and OFFIS do not
+ like that).
+20050129 mvh Added Write with extra vr to CEchoRSP
+20051222 mvh Do not add query level if already exists
+20070308 bcb Made changes for big endian
+20070314 mvh Allow send of 0000,1030 (MoveOriginatorAE) and 0000,1031 (MoveOriginatorMessageID)
+ in CStoreRQ
+20070330 mvh Merged bcb's Darwin and Endian stuff
+20080203 mvh Added experimental ConfigPadAEWithZeros
+20080910 bcb Removed big endian changes from here and moved to deivr
+20100309 bcb Added double parentheses (gcc4.2 Warnings)
+20100619 bcb Added UNUSED_ARGUMENT.
+20100717 mvh Merged
+20120624 mvh Delete transfer syntax in data object of outgoing images
+20120628 mvh Undo above change that only affects 'as': would probably break 'as' transfer of jpeg
+*/
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+#ifndef UNUSED_ARGUMENT
+#define UNUSED_ARGUMENT(x) (void)x
+#endif
+
+# include "dicom.hpp"
+
+/************************* C-Echo *******************************/
+
+BOOL CEchoRQ :: Read ( DICOMCommandObject *DCO )
+ {
+ if (!DCO)
+ return ( FALSE );
+
+ if (DCO->GetUINT16(0x0000, 0x0100)!=0x0030)
+ return ( FALSE ); // not a C-Echo-RQ
+
+ return ( TRUE );
+ }
+
+BOOL CEchoRQ :: Write ( PDU_Service *PDU )
+ {
+ DICOMCommandObject DCO;
+ VR *vr;
+ UINT16 Temp;
+ LE_UINT16 leCommand, leDSType, leMessageID;
+ UID uid;
+
+ if (!PDU)
+ return ( FALSE );
+
+ if (!GetUID(uid))
+ return ( FALSE );
+ vr = new VR (0x0000, 0x0002, uid.GetSize(),
+ (void*)uid.GetBuffer(1), FALSE );
+ DCO.Push ( vr );
+
+ leCommand = 0x0030;
+ vr = new VR (0x0000, 0x0100, sizeof(UINT16), &leCommand,
+ FALSE);
+ DCO.Push ( vr );
+
+ leDSType = 0x0101;
+ vr = new VR (0x0000, 0x0800, sizeof(UINT16), &leDSType,
+ FALSE);
+ DCO.Push ( vr );
+
+ Temp = uniq16odd();
+ leMessageID = Temp;
+ vr = new VR (0x0000, 0x0110, sizeof(UINT16), &leMessageID,
+ FALSE);
+ DCO.Push ( vr );
+
+ if (!PDU->Write(&DCO, uid))
+ return ( FALSE );
+
+ return ( TRUE );
+ }
+
+BOOL CEchoRSP :: Read ( DICOMCommandObject *DCO )
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if (DCO->GetUINT16(0x0000, 0x0100)!=0x8030)
+ return ( FALSE );
+
+ return ( TRUE );
+ }
+
+BOOL CEchoRSP :: Write ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ UINT16 ErrorCode, VR *vrextra )
+ {
+ DICOMCommandObject DCOR;
+ LE_UINT16 leCommand, leError;
+ VR *vr;
+ UID uid;
+
+ if ( ! PDU )
+ return ( FALSE );
+ if ( ! DCO )
+ return ( FALSE );
+
+ if (!GetUID(uid))
+ return ( FALSE );
+
+ while (( vr = DCO->Pop() ))
+ {
+ switch (vr->Element)
+ {
+ case 0x0002:
+ case 0x0800:
+ DCOR.Push ( vr );
+ break;
+ case 0x0110:
+ vr->Element = 0x0120;
+ DCOR.Push ( vr );
+ break;
+ default:
+ delete vr;
+ }
+ }
+ leCommand = 0x8030;
+ vr = new VR (0x0000, 0x0100, sizeof(UINT16), &leCommand, FALSE );
+ DCOR.Push ( vr );
+
+ leError = ErrorCode;
+ vr = new VR (0x0000, 0x0900, sizeof(UINT16), &leError, FALSE );
+ DCOR.Push ( vr );
+
+ if (vrextra)
+ DCOR.Push ( vrextra );
+
+ if (!PDU->Write(&DCOR, uid))
+ return ( FALSE );
+
+ return ( TRUE );
+ }
+
+BOOL CEchoRSP :: Write ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ UINT16 ErrorCode )
+ {
+ return ( Write ( PDU, DCO, ErrorCode, NULL ) ); // Write no vrextra
+ }
+
+BOOL CEchoRSP :: Write (PDU_Service *PDU, DICOMCommandObject *DCO)
+ {
+ return ( Write ( PDU, DCO, 0x0000, NULL ) ); // Write Success, no extra
+ }
+
+
+/************************** C-Store ***************************/
+
+BOOL CStoreRQ :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO )
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x0001 )
+ return ( FALSE ); // not C-Store
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ if ( PDU )
+ {
+ if ( DDO )
+ {
+ return ( PDU->Read( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+ // C-Store request, but no data section.. -error
+ return ( FALSE );
+ }
+
+BOOL CStoreRQ :: Read ( DICOMCommandObject *DCO )
+ {
+ return ( Read ( DCO, NULL, NULL ) );
+ }
+
+BOOL CStoreRQ :: Write (
+ PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ VR *MoveMessageID, unsigned char *CallingAE)
+ {
+ DICOMCommandObject DCO;
+ VR *vr;
+ UINT16 Temp;
+ LE_UINT16 leCommand, leDSType, leMessageID, lePriority;
+ UID uid;
+
+ if (!PDU)
+ return ( FALSE );
+
+ if (!GetUID(uid))
+ return ( FALSE );
+ vr = new VR (0x0000, 0x0002, uid.GetSize(),
+ (void*)uid.GetBuffer(1), FALSE );
+ DCO.Push ( vr );
+
+ leCommand = 0x0001;
+ vr = new VR (0x0000, 0x0100, sizeof(UINT16), &leCommand,
+ FALSE);
+ DCO.Push ( vr );
+
+ leDSType = 0x0102;
+ vr = new VR (0x0000, 0x0800, sizeof(UINT16), &leDSType,
+ FALSE);
+ DCO.Push ( vr );
+
+ Temp = uniq16odd();
+ leMessageID = Temp;
+
+ vr = new VR (0x0000, 0x0110, sizeof(UINT16), &leMessageID,
+ FALSE);
+ DCO.Push ( vr );
+
+ lePriority = 0;
+ vr = new VR (0x0000, 0x0700, sizeof(UINT16), &lePriority,
+ FALSE);
+ DCO.Push ( vr );
+
+ vr = DDO->GetVR(0x0008, 0x0018); // Instance
+ if(vr)
+ {
+ VR *vr2;
+
+ vr2 = new VR(0x0000, 0x1000, vr->Length, (BOOL)TRUE);
+ memcpy(vr2->Data, vr->Data, vr->Length);
+ DCO.Push(vr2);
+ }
+
+ if (CallingAE)
+ {
+ VR *vr2;
+ int len = strlen((char *)CallingAE);
+ if (len&1) len++;
+ vr2 = new VR(0x0000, 0x1030, len, (BOOL)TRUE);
+ memcpy(vr2->Data, CallingAE, len);
+ if (((char *)vr2->Data)[len-1]==0) ((char *)vr2->Data)[len-1]=' ';
+ DCO.Push(vr2);
+ }
+
+ if (MoveMessageID)
+ {
+ VR *vr2;
+ vr2 = new VR(0x0000, 0x1031, MoveMessageID->Length, (BOOL)TRUE);
+ memcpy(vr2->Data, MoveMessageID->Data, MoveMessageID->Length);
+ DCO.Push(vr2);
+ }
+
+ if (!PDU->Write(&DCO, uid))
+ return ( FALSE );
+ if ( DDO )
+ {
+// vr = DDO->GetVR(0x0002, 0x0010); // delete tr syntax: mvh 20120624
+// if (vr) DDO->DeleteVR(vr);
+ return ( PDU->Write ( DDO, uid ) );
+ }
+ return ( TRUE );
+ }
+
+BOOL CStoreRSP :: Read ( DICOMCommandObject *DCO )
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if (DCO->GetUINT16(0x0000, 0x0100) != 0x8001)
+ return ( FALSE ); // not a C-Store-RSP
+
+ return ( TRUE );
+ }
+
+BOOL CStoreRSP :: Write (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ UINT16 ErrorCode)
+ {
+ VR *vr;
+ LE_UINT16 leCommand, leMessageID, leRQMessageID, leDSType,
+ leErrorCode, lePriority;
+ DICOMCommandObject DCOR;
+ UID uid;
+
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! DCO )
+ return ( FALSE );
+
+ if (!GetUID(uid))
+ {
+ // Try and grab the uid from the DCO
+ VR *vru = DCO->GetVR(0x0000, 0x0002);
+ if ( ! vru )
+ return ( FALSE );
+ SetUID(uid, vru);
+ }
+
+ lePriority = 0;
+ if(DCO->GetVR(0x0000, 0x0700))
+ lePriority = DCO->GetUINT16( 0x0000, 0x0700 );
+ leErrorCode = ErrorCode;
+ leRQMessageID = DCO->GetUINT16 ( 0x0000, 0x0110 );
+ leMessageID = leRQMessageID;
+ leDSType = 0x0101;
+ leCommand = 0x8001;
+
+ while (( vr = DCO->Pop() ))
+ {
+ switch ( vr->Element )
+ {
+ case 0x0002:
+ DCOR.Push ( vr );
+ break;
+ case 0x0200:
+ vr->Element = 0x0300;
+ DCOR.Push ( vr );
+ break;
+ case 0x0300:
+ vr->Element = 0x0200;
+ DCOR.Push ( vr );
+ break;
+ case 0x1000:
+ DCOR.Push ( vr );
+ break;
+ default:
+ delete vr;
+ }
+ }
+ vr = new VR (0x0000, 0x0100, sizeof(UINT16), &leCommand, FALSE);
+ DCOR.Push ( vr );
+ /* The MessageID in a RSP is now retired */
+// vr = new VR (0x0000, 0x0110, sizeof(UINT16), &leMessageID, FALSE);
+// DCOR.Push ( vr );
+ vr = new VR (0x0000, 0x0120, sizeof(UINT16), &leRQMessageID, FALSE);
+ DCOR.Push ( vr );
+ /* The priority is not used either */
+// vr = new VR (0x0000, 0x0700, sizeof(UINT16), &lePriority, FALSE);
+// DCOR.Push ( vr );
+ vr = new VR (0x0000, 0x0800, sizeof(UINT16), &leDSType, FALSE);
+ DCOR.Push ( vr );
+ vr = new VR (0x0000, 0x0900, sizeof(UINT16), &leErrorCode, FALSE);
+ DCOR.Push ( vr );
+
+ PDU->Write ( &DCOR, uid );
+ return ( TRUE );
+ }
+
+BOOL CStoreRSP :: Write ( PDU_Service *PDU, DICOMCommandObject *DCO)
+ {
+ return ( Write ( PDU, DCO, 0x0000 ) );
+ }
+
+/************************** C-Find ***************************/
+
+BOOL CFindRQ :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO )
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x0020 )
+ return ( FALSE ); // not C-Find
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ if ( PDU )
+ {
+ if ( DDO )
+ {
+ return ( PDU->Read( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+ // C-Find request, but no data section.. -error
+ return ( FALSE );
+ }
+
+BOOL CFindRQ :: Read ( DICOMCommandObject *DCO )
+ {
+ return ( Read ( DCO, NULL, NULL ) );
+ }
+
+BOOL CFindRQ :: Write (
+ PDU_Service *PDU,
+ DICOMDataObject *DDO)
+ {
+ DICOMCommandObject DCO;
+ VR *vr;
+ UINT16 Temp;
+ LE_UINT16 leCommand, leDSType, leMessageID, lePriority;
+ UID uid;
+
+ if (!PDU)
+ return ( FALSE );
+
+ if (!GetUID(uid))
+ return ( FALSE );
+ vr = new VR (0x0000, 0x0002, uid.GetSize(),
+ (void*)uid.GetBuffer(1), FALSE );
+ DCO.Push ( vr );
+
+ leCommand = 0x0020;
+ vr = new VR (0x0000, 0x0100, sizeof(UINT16), &leCommand,
+ FALSE);
+ DCO.Push ( vr );
+
+ leDSType = 0x0102;
+ vr = new VR (0x0000, 0x0800, sizeof(UINT16), &leDSType,
+ FALSE);
+ DCO.Push ( vr );
+
+ Temp = uniq16odd();
+ leMessageID = Temp;
+
+ vr = new VR (0x0000, 0x0110, sizeof(UINT16), &leMessageID,
+ FALSE);
+ DCO.Push ( vr );
+
+ lePriority = 0;
+ vr = new VR (0x0000, 0x0700, sizeof(UINT16), &lePriority,
+ FALSE);
+ DCO.Push ( vr );
+
+ if (!PDU->Write(&DCO, uid))
+ return ( FALSE );
+ if ( DDO )
+ return ( PDU->Write ( DDO, uid ) );
+ return ( TRUE );
+ }
+
+BOOL CFindRSP :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO )
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if (DCO->GetUINT16(0x0000, 0x0100) != 0x8020)
+ return ( FALSE ); // not a C-Find-RSP
+
+ if (DDO)
+ {
+ if (DCO->GetUINT16(0x0000, 0x0800) != 0x0101)
+ {
+ return ( PDU->Read ( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+
+BOOL CFindRSP :: Read ( DICOMCommandObject *DCO )
+ {
+ return ( Read ( DCO, NULL, NULL ) );
+ }
+
+BOOL CFindRSP :: Write (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ UINT16 ErrorCode,
+ DICOMDataObject *DDO,
+ char* QueryRetrieveLevel)
+ {
+ VR *vr, *vr2;
+ LE_UINT16 leCommand, leMessageID, leRQMessageID, leDSType,
+ leErrorCode, lePriority;
+ DICOMCommandObject DCOR;
+ UID uid;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! DCO )
+ return ( FALSE );
+
+ if (!GetUID(uid))
+ return ( FALSE );
+
+ lePriority = 0;
+ if(DCO->GetVR(0x0000, 0x0700))
+ lePriority = DCO->GetUINT16( 0x0000, 0x0700 );
+ leErrorCode = ErrorCode;
+ leRQMessageID = DCO->GetUINT16 ( 0x0000, 0x0110 );
+ leMessageID = leRQMessageID;
+ if(DDO)
+ leDSType = 0x0102;
+ else
+ leDSType = 0x0101;
+ leCommand = 0x8020;
+
+ // Rather than destory the original command object, just make
+ // copies of the elements we need.
+
+ if((vr = DCO->GetVR ( 0x0000, 0x0002 ) ))
+ {
+ vr2 = new VR ( 0x0000, 0x0002, vr->Length, TRUE );
+ memcpy(vr2->Data, vr->Data, (int)vr->Length);
+ DCOR.Push ( vr2 );
+ }
+ if((vr = DCO->GetVR ( 0x0000, 0x0300 ) ))
+ {
+ vr2 = new VR ( 0x0000, 0x0300, vr->Length, TRUE );
+ memcpy(vr2->Data, vr->Data, (int)vr->Length);
+ DCOR.Push ( vr2 );
+ }
+ if((vr = DCO->GetVR ( 0x0000, 0x0200 ) ))
+ {
+ vr2 = new VR ( 0x0000, 0x0200, vr->Length, TRUE );
+ memcpy(vr2->Data, vr->Data, (int)vr->Length);
+ DCOR.Push ( vr2 );
+ }
+ vr = new VR (0x0000, 0x0100, sizeof(UINT16), &leCommand, FALSE);
+ DCOR.Push ( vr );
+ /* The MessageID in a RSP is now retired */
+// vr = new VR (0x0000, 0x0110, sizeof(UINT16), &leMessageID, FALSE);
+// DCOR.Push ( vr );
+ vr = new VR (0x0000, 0x0120, sizeof(UINT16), &leRQMessageID, FALSE);
+ DCOR.Push ( vr );
+ /* The priority is not used either */
+// vr = new VR (0x0000, 0x0700, sizeof(UINT16), &lePriority, FALSE);
+// DCOR.Push ( vr );
+ vr = new VR (0x0000, 0x0800, sizeof(UINT16), &leDSType, FALSE);
+ DCOR.Push ( vr );
+ vr = new VR (0x0000, 0x0900, sizeof(UINT16), &leErrorCode, FALSE);
+ DCOR.Push ( vr );
+
+ PDU->Write ( &DCOR, uid );
+ if(DDO)
+ {
+ if (!DDO->GetVR(0x0008, 0x0052))
+ {
+ // Also send the required Quey/Retrieve level
+ int iLength;
+ iLength = strlen(QueryRetrieveLevel);
+ if (iLength & 0x01)
+ iLength++;
+ vr2 = new VR(0x0008, 0x0052, iLength, TRUE );
+ memcpy(vr2->Data, QueryRetrieveLevel, iLength);
+ DDO->Push(vr2);
+ }
+ PDU->Write ( DDO, uid );
+ }
+ return ( TRUE );
+ }
+
+BOOL CFindRSP :: Write (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ DICOMDataObject *DDO,
+ char* QueryRetrieveLevel)
+ {
+ if ( DDO )
+ return ( Write ( PDU, DCO, 0xff00, DDO, QueryRetrieveLevel) );
+
+ return ( Write ( PDU, DCO, 0x0000, NULL, QueryRetrieveLevel) );
+ }
+
+/************************** C-Move ***************************/
+
+BOOL CMoveRQ :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO )
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x0021 )
+ return ( FALSE ); // not C-Move
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ if ( PDU )
+ {
+ if ( DDO )
+ {
+ return ( PDU->Read( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+ // C-Move request, but no data section.. -error
+ return ( FALSE );
+ }
+
+BOOL CMoveRQ :: Read ( DICOMCommandObject *DCO )
+ {
+ return ( Read ( DCO, NULL, NULL ) );
+ }
+
+BOOL CMoveRQ :: Write (
+ PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ BYTE *Where)
+ {
+ DICOMCommandObject DCO;
+ VR *vr;
+ UINT16 Temp;
+ LE_UINT16 leCommand, leDSType, leMessageID, lePriority;
+ BYTE WhereACRNema [ 17 ];
+ UID uid;
+
+ if (!PDU)
+ return ( FALSE );
+
+ if (!Where )
+ return ( FALSE );
+
+ if (!GetUID(uid))
+ return ( FALSE );
+ vr = new VR (0x0000, 0x0002, uid.GetSize(),
+ (void*)uid.GetBuffer(1), FALSE );
+ DCO.Push ( vr );
+
+ leCommand = 0x0021;
+ vr = new VR (0x0000, 0x0100, sizeof(UINT16), &leCommand,
+ FALSE);
+ DCO.Push ( vr );
+
+ leDSType = 0x0102;
+ vr = new VR (0x0000, 0x0800, sizeof(UINT16), &leDSType,
+ FALSE);
+ DCO.Push ( vr );
+
+ Temp = uniq16odd();
+ leMessageID = Temp;
+
+ vr = new VR (0x0000, 0x0110, sizeof(UINT16), &leMessageID,
+ FALSE);
+ DCO.Push ( vr );
+
+ lePriority = 0;
+ vr = new VR (0x0000, 0x0700, sizeof(UINT16), &lePriority,
+ FALSE);
+ DCO.Push ( vr );
+
+ strcpy((char*) WhereACRNema, " ");
+ if (ConfigPadAEWithZeros) memset((char*) WhereACRNema, 0, 16);
+ memcpy( (void*) &WhereACRNema[0],
+ (void*) Where,
+ strlen((char*) Where) );
+ vr = new VR (0x0000, 0x0600, 16, (void*) &WhereACRNema[0],
+ FALSE);
+ DCO.Push ( vr );
+
+ if (!PDU->Write(&DCO, uid))
+ return ( FALSE );
+ if ( DDO )
+ return ( PDU->Write ( DDO, uid ) );
+ return ( TRUE );
+ }
+
+BOOL CMoveRSP :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO )
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if (DCO->GetUINT16(0x0000, 0x0100) != 0x8021)
+ return ( FALSE ); // not a C-Move-RSP
+
+ if (DDO)
+ {
+ if (DCO->GetUINT16(0x0000, 0x0800) != 0x0101)
+ {
+ if ( PDU )
+ return ( PDU->Read ( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+
+BOOL CMoveRSP :: Read ( DICOMCommandObject *DCO )
+ {
+ return ( Read ( DCO, NULL, NULL ) );
+ }
+
+BOOL CMoveRSP :: Write (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ UINT16 ErrorCode,
+ UINT16 NumberRemaining,
+ UINT16 NumberComplete,
+ UINT16 NumberFailed,
+ UINT16 NumberWarning,
+ DICOMDataObject *DDO)
+ {
+ VR *vr, *vr2;
+ LE_UINT16 leCommand, leMessageID, leRQMessageID, leDSType,
+ leErrorCode, lePriority;
+ LE_UINT16 leNumberRemaining, leNumberComplete,
+ leNumberFailed, leNumberWarning;
+ DICOMCommandObject DCOR;
+ UID uid;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! DCO )
+ return ( FALSE );
+
+ if (!GetUID(uid))
+ return ( FALSE );
+
+ lePriority = 0;
+ if(DCO->GetVR(0x0000, 0x0700))
+ lePriority = DCO->GetUINT16( 0x0000, 0x0700 );
+ leNumberRemaining = NumberRemaining;
+ leNumberComplete = NumberComplete;
+ leNumberFailed = NumberFailed;
+ leNumberWarning = NumberWarning;
+ leErrorCode = ErrorCode;
+ leRQMessageID = DCO->GetUINT16 ( 0x0000, 0x0110 );
+ leMessageID = leRQMessageID;
+ UNUSED_ARGUMENT(DDO);
+// if(DDO) // ljz 20030811: do not send DDO
+// leDSType = 0x0102;
+// else
+ leDSType = 0x0101;
+ leCommand = 0x8021;
+
+ if((vr = DCO->GetVR ( 0x0000, 0x0002 ) ))
+ {
+ vr2 = new VR ( 0x0000, 0x0002, vr->Length, TRUE );
+ memcpy(vr2->Data, vr->Data, (int)vr->Length);
+ DCOR.Push ( vr2 );
+ }
+ if((vr = DCO->GetVR ( 0x0000, 0x0300 ) ))
+ {
+ vr2 = new VR ( 0x0000, 0x0300, vr->Length, TRUE );
+ memcpy(vr2->Data, vr->Data, (int)vr->Length);
+ DCOR.Push ( vr2 );
+ }
+ if((vr = DCO->GetVR ( 0x0000, 0x0200 ) ))
+ {
+ vr2 = new VR ( 0x0000, 0x0200, vr->Length, TRUE );
+ memcpy(vr2->Data, vr->Data, (int)vr->Length);
+ DCOR.Push ( vr2 );
+ }
+
+ vr = new VR (0x0000, 0x0100, sizeof(UINT16), &leCommand, FALSE);
+ DCOR.Push ( vr );
+ /* The MessageID in a RSP is now retired */
+// vr = new VR (0x0000, 0x0110, sizeof(UINT16), &leMessageID, FALSE);
+// DCOR.Push ( vr );
+ vr = new VR (0x0000, 0x0120, sizeof(UINT16), &leRQMessageID, FALSE);
+ DCOR.Push ( vr );
+ /* The priority is not used either */
+// vr = new VR (0x0000, 0x0700, sizeof(UINT16), &lePriority, FALSE);
+// DCOR.Push ( vr );
+ vr = new VR (0x0000, 0x0800, sizeof(UINT16), &leDSType, FALSE);
+ DCOR.Push ( vr );
+ vr = new VR (0x0000, 0x0900, sizeof(UINT16), &leErrorCode, FALSE);
+ DCOR.Push ( vr );
+ vr = new VR (0x0000, 0x1020, sizeof(UINT16), &leNumberRemaining,
+ FALSE);
+ DCOR.Push ( vr );
+ vr = new VR (0x0000, 0x1021, sizeof(UINT16), &leNumberComplete,
+ FALSE);
+ DCOR.Push ( vr );
+ vr = new VR (0x0000, 0x1022, sizeof(UINT16), &leNumberFailed,
+ FALSE);
+ DCOR.Push ( vr );
+ vr = new VR (0x0000, 0x1023, sizeof(UINT16), &leNumberWarning,
+ FALSE);
+ DCOR.Push ( vr );
+
+ PDU->Write ( &DCOR, uid );
+// if(DDO) // ljz 20030811: do not send DDO
+// PDU->Write ( DDO, uid );
+ return ( TRUE );
+ }
+
+
diff --git a/dimsec.hpp b/dimsec.hpp
new file mode 100644
index 0000000..9af141d
--- /dev/null
+++ b/dimsec.hpp
@@ -0,0 +1,159 @@
+/*
+20030606 ljz Added parameter 'QueryRetrieveLevel' to CFindRSP::Write
+20050129 mvh Added Write with extra vr to CEchoRSP
+20070314 mvh Allow send of 0000,1030 (MoveOriginatorAE) and 0000,1031 (MoveOriginatorMessageID)
+ in CStoreRQ
+20100619 bcb Added virtual destructors (gcc4.0 Warnings)
+20100717 bcb Merged
+ */
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+
+class CEchoRQ
+ {
+ public:
+ BOOL Read ( DICOMCommandObject * );
+ BOOL Write ( PDU_Service * );
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~CEchoRQ() {};
+#endif
+ };
+
+class CEchoRSP
+ {
+ public:
+ BOOL Read ( DICOMCommandObject * );
+ BOOL Write ( PDU_Service *, DICOMCommandObject *, UINT16, VR * );
+ BOOL Write ( PDU_Service *, DICOMCommandObject *, UINT16 );
+ BOOL Write ( PDU_Service *, DICOMCommandObject * );
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~CEchoRSP() {};
+#endif
+ };
+
+class CStoreRQ
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *,
+ DICOMDataObject * );
+ BOOL Read ( DICOMCommandObject * );
+ BOOL Write ( PDU_Service * , DICOMDataObject *, VR *MoveMessageID = NULL, unsigned char *CallingAE = NULL);
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~CStoreRQ() {};
+#endif
+ };
+
+class CStoreRSP
+ {
+ public:
+ BOOL Read ( DICOMCommandObject * );
+ BOOL Write ( PDU_Service * , DICOMCommandObject *, UINT16 );
+ BOOL Write ( PDU_Service *, DICOMCommandObject * );
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~CStoreRSP() {};
+#endif
+ };
+
+class CFindRQ
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *,
+ DICOMDataObject * );
+ BOOL Read ( DICOMCommandObject * );
+ BOOL Write ( PDU_Service * , DICOMDataObject *);
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~CFindRQ() {};
+#endif
+ };
+
+class CFindRSP
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *,
+ DICOMDataObject * );
+ BOOL Read ( DICOMCommandObject * );
+ BOOL Write ( PDU_Service *,
+ DICOMCommandObject *,
+ UINT16,
+ DICOMDataObject *,
+ char* QueryRetrieveLevel);
+ BOOL Write ( PDU_Service *,
+ DICOMCommandObject *,
+ DICOMDataObject *,
+ char* QueryRetrieveLevel);
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~CFindRSP() {};
+#endif
+ };
+
+class CMoveRQ
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *,
+ DICOMDataObject * );
+ BOOL Read ( DICOMCommandObject * );
+ BOOL Write ( PDU_Service * , DICOMDataObject *, BYTE *);
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~CMoveRQ() {};
+#endif
+ };
+
+class CMoveRSP
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *,
+ DICOMDataObject * );
+ BOOL Read ( DICOMCommandObject * );
+ BOOL Write ( PDU_Service *,
+ DICOMCommandObject *,
+ UINT16,
+ UINT16,
+ UINT16,
+ UINT16,
+ UINT16,
+ DICOMDataObject *);
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~CMoveRSP() {};
+#endif
+ };
+
diff --git a/dimsen.cxx b/dimsen.cxx
new file mode 100644
index 0000000..b1e49e3
--- /dev/null
+++ b/dimsen.cxx
@@ -0,0 +1,1306 @@
+/* 19990415 ljz Removed static on TranslateUIDToVR */
+/* 20020822 mvh Use instead of DIMSEN.CPP */
+/* 20071118 mvh Removed faulty overloaded 'NGetRQ::Write' */
+/* 20080905 bcb Removed (void*) cast for deivr change */
+/* 20100309 bcb Added double parentheses (gcc4.2 Warnings) */
+/* 20100619 bcb Added UNUSED(x) */
+/* 20100717 mvh Merged */
+
+# include "dicom.hpp"
+
+#ifndef UNUSED_ARGUMENT
+#define UNUSED_ARGUMENT(x) (void)x
+#endif
+
+static VR *CopyVR ( VR * );
+static VR *BuildATVR ( DICOMObject *, UINT16, UINT16 );
+static BOOL DecomposeATVR ( VR *, DICOMObject * );
+
+BOOL
+NEventReportRQ :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO )
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x0100 )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ if ( PDU )
+ {
+ if ( DDO )
+ {
+ return ( PDU->Read( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+
+ return ( TRUE );
+ }
+
+BOOL
+NEventReportRQ :: Write (
+ PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ UID *AffectedSOPInstanceUID,
+ UINT16 EventID)
+ {
+ UID SOPClassUID;
+ LE_UINT16 Command, MessageID, DataSetType, EventTypeID;
+ VR *vr;
+ DICOMCommandObject DCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ Command = 0x0100;
+ MessageID = uniq16odd();
+ if ( DDO )
+ DataSetType = 0x0102;
+ else
+ DataSetType = 0x0101;
+
+ EventTypeID = EventID;
+ if ( ! GetUID ( SOPClassUID ) )
+ {
+ return ( FALSE );
+ }
+
+ vr = TranslateUIDToVR ( &SOPClassUID, 0x0000, 0x0002 );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0100, sizeof(UINT16), &Command, (BOOL) FALSE );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0110, sizeof(UINT16), &MessageID, (BOOL) FALSE );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0800, sizeof(UINT16), &DataSetType, (BOOL) FALSE );
+ DCO.Push(vr);
+
+ if ( AffectedSOPInstanceUID )
+ {
+ vr = TranslateUIDToVR ( AffectedSOPInstanceUID, 0x0000, 0x1000 );
+ DCO.Push ( vr );
+ }
+
+ vr = new VR ( 0x0000, 0x1002, sizeof(UINT16), &EventTypeID, (BOOL) FALSE );
+ DCO.Push ( vr );
+
+ if ( ! PDU->Write ( &DCO, SOPClassUID ) )
+ return ( FALSE );
+
+ if ( DDO )
+ {
+ if ( ! PDU->Write ( DDO, SOPClassUID ) )
+ return ( FALSE );
+ }
+ return ( TRUE );
+ }
+
+
+BOOL
+NEventReportRQ :: Write (
+ PDU_Service *PDU,
+ UID *AffectedSOPInstanceUID,
+ UINT16 EventID )
+ {
+ return ( Write ( PDU, NULL, AffectedSOPInstanceUID, EventID) );
+ }
+
+
+BOOL
+NEventReportRSP :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO)
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x8100 )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ if ( PDU )
+ {
+ if ( DDO )
+ {
+ return ( PDU->Read( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+
+ return ( TRUE );
+ }
+
+
+BOOL
+NEventReportRSP :: Write (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ UID *AffectedSOPInstanceUID,
+ UINT16 Status,
+ UINT16 EventID,
+ DICOMDataObject *DDO)
+ {
+ UID SOPClassUID;
+ LE_UINT16 Command, MessageID, DataSetType, EventTypeID, StatusField;
+ VR *vr;
+ DICOMCommandObject rDCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! DCO )
+ return ( FALSE );
+
+ Command = 0x8100;
+ MessageID = DCO->GetUINT16 ( 0x0000, 0x0110 );
+
+ if ( DDO )
+ DataSetType = 0x0102;
+ else
+ DataSetType = 0x0101;
+
+ EventTypeID = EventID;
+ StatusField = Status;
+
+ if ( ! GetUID ( SOPClassUID ) )
+ {
+ return ( FALSE );
+ }
+
+ vr = TranslateUIDToVR ( &SOPClassUID, 0x0000, 0x0002 );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0100, sizeof(UINT16), &Command, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0120, sizeof(UINT16), &MessageID, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0800, sizeof(UINT16), &DataSetType, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0900, sizeof(UINT16), &StatusField, (BOOL) FALSE );
+ rDCO.Push(vr);
+
+ if ( AffectedSOPInstanceUID )
+ {
+ vr = TranslateUIDToVR ( AffectedSOPInstanceUID, 0x0000, 0x1000 );
+ rDCO.Push ( vr );
+ }
+ else
+ {
+ // Check to see if we can snag it from the command object
+ vr = DCO->GetVR(0x0000, 0x1000);
+ if ( vr )
+ {
+ // Copy it
+ vr = CopyVR ( vr );
+ rDCO.Push( vr );
+ }
+ }
+
+ vr = new VR ( 0x0000, 0x1002, sizeof(UINT16), &EventTypeID, (BOOL) FALSE );
+ rDCO.Push ( vr );
+
+ if ( ! PDU->Write ( &rDCO, SOPClassUID ) )
+ return ( FALSE );
+
+ if ( DDO )
+ {
+ if ( ! PDU->Write ( DDO, SOPClassUID ) )
+ return ( FALSE );
+ }
+ return ( TRUE );
+ }
+
+BOOL
+NEventReportRSP :: Write (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ UID *AffectedSOPInstanceUID,
+ UINT16 EventID,
+ DICOMDataObject *DDO)
+ {
+ return ( Write ( PDU, DCO, AffectedSOPInstanceUID, 0x0000, EventID, DDO ) );
+ }
+
+/*********************** N-GET-RQ ****************************/
+
+BOOL
+NGetRQ :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO)
+ {
+ UNUSED_ARGUMENT(DDO);
+ UNUSED_ARGUMENT(PDU);
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x0110 )
+ return ( FALSE );
+
+ DecomposeATVR(DCO->GetVR(0x0000, 0x1005), DDO);
+
+ return ( TRUE );
+ }
+
+BOOL
+NGetRQ :: Write (
+ PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ UID *RequestedSOPInstanceUID)
+ {
+ UID SOPClassUID;
+ LE_UINT16 Command, MessageID, DataSetType;
+ VR *vr;
+ DICOMCommandObject DCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ Command = 0x0110;
+ MessageID = uniq16odd();
+ DataSetType = 0x0101;
+
+ if ( ! GetUID ( SOPClassUID ) )
+ {
+ return ( FALSE );
+ }
+
+ vr = TranslateUIDToVR ( &SOPClassUID, 0x0000, 0x0003 ); // Note Affected SOP Class UID
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0100, sizeof(UINT16), &Command, (BOOL) FALSE );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0110, sizeof(UINT16), &MessageID, (BOOL) FALSE );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0800, sizeof(UINT16), &DataSetType, (BOOL) FALSE );
+ DCO.Push(vr);
+
+ if ( RequestedSOPInstanceUID )
+ {
+ vr = TranslateUIDToVR ( RequestedSOPInstanceUID, 0x0000, 0x1001 );
+ DCO.Push ( vr );
+ }
+
+ vr = BuildATVR(DDO, 0x0000, 0x1005);
+ DCO.Push(vr);
+
+ if ( ! PDU->Write ( &DCO, SOPClassUID ) )
+ return ( FALSE );
+
+ return ( TRUE );
+ }
+
+//BOOL
+//NGetRQ :: Write (
+// PDU_Service *PDU,
+// UID *RequestedSOPInstanceUID)
+// {
+// return ( Write ( PDU, RequestedSOPInstanceUID) );
+// }
+
+BOOL
+NGetRSP :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO)
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x8110 )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ if ( PDU )
+ {
+ if ( DDO )
+ {
+ return ( PDU->Read( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+
+ return ( TRUE );
+ }
+
+BOOL
+NGetRSP :: Write (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ UID *AffectedSOPInstanceUID,
+ UINT16 Status,
+ DICOMDataObject *DDO)
+ {
+ UID SOPClassUID;
+ LE_UINT16 Command, MessageID, DataSetType, StatusField;
+ VR *vr;
+ DICOMCommandObject rDCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! DCO )
+ return ( FALSE );
+
+ Command = 0x8110;
+ MessageID = DCO->GetUINT16 ( 0x0000, 0x0110 );
+
+ if ( DDO )
+ DataSetType = 0x0102;
+ else
+ DataSetType = 0x0101;
+
+ StatusField = Status;
+
+ if ( ! GetUID ( SOPClassUID ) )
+ {
+ return ( FALSE );
+ }
+
+ vr = TranslateUIDToVR ( &SOPClassUID, 0x0000, 0x0002 );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0100, sizeof(UINT16), &Command, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0120, sizeof(UINT16), &MessageID, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0800, sizeof(UINT16), &DataSetType, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0900, sizeof(UINT16), &StatusField, (BOOL) FALSE );
+ rDCO.Push(vr);
+
+ if ( AffectedSOPInstanceUID )
+ {
+ vr = TranslateUIDToVR ( AffectedSOPInstanceUID, 0x0000, 0x1000 );
+ rDCO.Push ( vr );
+ }
+ else
+ {
+ // Check to see if we can snag it from the command object
+ vr = DCO->GetVR(0x0000, 0x1000);
+ if ( vr )
+ {
+ // Copy it
+ vr = CopyVR ( vr );
+ rDCO.Push( vr );
+ }
+ }
+
+
+ if ( ! PDU->Write ( &rDCO, SOPClassUID ) )
+ return ( FALSE );
+
+ if ( DDO )
+ {
+ if ( ! PDU->Write ( DDO, SOPClassUID ) )
+ return ( FALSE );
+ }
+ return ( TRUE );
+ }
+
+/**************************** N-SET-RQ *********************************/
+
+BOOL
+NSetRQ :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO)
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x0120 )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ if ( PDU )
+ {
+ if ( DDO )
+ {
+ return ( PDU->Read( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+
+ return ( TRUE );
+ }
+
+BOOL
+NSetRQ :: Write (
+ PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ UID *RequestedSOPInstanceUID )
+ {
+ UID SOPClassUID;
+ LE_UINT16 Command, MessageID, DataSetType;
+ VR *vr;
+ DICOMCommandObject DCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ Command = 0x0120;
+ MessageID = uniq16odd();
+
+// if ( DDO )
+ DataSetType = 0x0102;
+// else
+// DataSetType = 0x0101;
+
+ if ( ! GetUID ( SOPClassUID ) )
+ {
+ return ( FALSE );
+ }
+
+ vr = TranslateUIDToVR ( &SOPClassUID, 0x0000, 0x0003 );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0100, sizeof(UINT16), &Command, (BOOL) FALSE );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0110, sizeof(UINT16), &MessageID, (BOOL) FALSE );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0800, sizeof(UINT16), &DataSetType, (BOOL) FALSE );
+ DCO.Push(vr);
+
+ if ( RequestedSOPInstanceUID )
+ {
+ vr = TranslateUIDToVR ( RequestedSOPInstanceUID, 0x0000, 0x1001 );
+ DCO.Push ( vr );
+ }
+
+ if ( ! PDU->Write ( &DCO, SOPClassUID ) )
+ return ( FALSE );
+
+ if ( DDO )
+ {
+ if ( ! PDU->Write ( DDO, SOPClassUID ) )
+ return ( FALSE );
+ }
+ return ( TRUE );
+ }
+
+BOOL
+NSetRQ :: Write (
+ PDU_Service *PDU,
+ UID *RequestedSOPInstanceUID )
+ {
+ return ( Write ( PDU, NULL, RequestedSOPInstanceUID ) );
+ }
+
+BOOL
+NSetRSP :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO)
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x8120 )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ if ( PDU )
+ {
+ if ( DDO )
+ {
+ return ( PDU->Read( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+
+ return ( TRUE );
+ }
+
+BOOL
+NSetRSP :: Write (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ UID *AffectedSOPInstanceUID,
+ UINT16 Status,
+ DICOMDataObject *DDO)
+ {
+ UID SOPClassUID;
+ LE_UINT16 Command, MessageID, DataSetType, StatusField;
+ VR *vr;
+ DICOMCommandObject rDCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! DCO )
+ return ( FALSE );
+
+ Command = 0x8120;
+ MessageID = DCO->GetUINT16 ( 0x0000, 0x0110 );
+
+ if ( DDO )
+ DataSetType = 0x0102;
+ else
+ DataSetType = 0x0101;
+
+ StatusField = Status;
+
+ if ( ! GetUID ( SOPClassUID ) )
+ {
+ return ( FALSE );
+ }
+
+ vr = TranslateUIDToVR ( &SOPClassUID, 0x0000, 0x0002 );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0100, sizeof(UINT16), &Command, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0120, sizeof(UINT16), &MessageID, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0800, sizeof(UINT16), &DataSetType, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0900, sizeof(UINT16), &StatusField, (BOOL) FALSE );
+ rDCO.Push(vr);
+
+ if ( AffectedSOPInstanceUID )
+ {
+ vr = TranslateUIDToVR ( AffectedSOPInstanceUID, 0x0000, 0x1000 );
+ rDCO.Push ( vr );
+ }
+ else
+ {
+ // Check to see if we can snag it from the command object
+ vr = DCO->GetVR(0x0000, 0x1000);
+ if ( vr )
+ {
+ // Copy it
+ vr = CopyVR ( vr );
+ rDCO.Push( vr );
+ }
+ }
+
+
+ if ( ! PDU->Write ( &rDCO, SOPClassUID ) )
+ return ( FALSE );
+
+ if ( DDO )
+ {
+ if ( ! PDU->Write ( DDO, SOPClassUID ) )
+ return ( FALSE );
+ }
+ return ( TRUE );
+ }
+
+/***************************** N-ACTION *******************************/
+
+BOOL
+NActionRQ :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO)
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x0130 )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ if ( PDU )
+ {
+ if ( DDO )
+ {
+ return ( PDU->Read( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+
+ return ( TRUE );
+ }
+
+BOOL
+NActionRQ :: Write (
+ PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ UID *RequestedSOPInstanceUID,
+ UINT16 ActionTypeID)
+ {
+ UID SOPClassUID;
+ LE_UINT16 Command, MessageID, DataSetType, ActionID;
+ VR *vr;
+ DICOMCommandObject DCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ Command = 0x0130;
+ MessageID = uniq16odd();
+ if ( DDO )
+ DataSetType = 0x0102;
+ else
+ DataSetType = 0x0101;
+
+ ActionID = ActionTypeID;
+ if ( ! GetUID ( SOPClassUID ) )
+ {
+ return ( FALSE );
+ }
+
+ vr = TranslateUIDToVR ( &SOPClassUID, 0x0000, 0x0003 );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0100, sizeof(UINT16), &Command, (BOOL) FALSE );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0110, sizeof(UINT16), &MessageID, (BOOL) FALSE );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0800, sizeof(UINT16), &DataSetType, (BOOL) FALSE );
+ DCO.Push(vr);
+
+ if ( RequestedSOPInstanceUID )
+ {
+ vr = TranslateUIDToVR ( RequestedSOPInstanceUID, 0x0000, 0x1001 );
+ DCO.Push ( vr );
+ }
+
+ vr = new VR ( 0x0000, 0x1008, sizeof(UINT16), &ActionID, (BOOL) FALSE );
+ DCO.Push ( vr );
+
+ if ( ! PDU->Write ( &DCO, SOPClassUID ) )
+ return ( FALSE );
+
+ if ( DDO )
+ {
+ if ( ! PDU->Write ( DDO, SOPClassUID ) )
+ return ( FALSE );
+ }
+ return ( TRUE );
+ }
+
+BOOL
+NActionRQ :: Write (
+ PDU_Service *PDU,
+ UID *RequestedSOPInstanceUID,
+ UINT16 ActionTypeID)
+ {
+
+ return ( Write ( PDU, NULL, RequestedSOPInstanceUID, ActionTypeID ) );
+ }
+
+
+BOOL
+NActionRSP :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO)
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x8130 )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ if ( PDU )
+ {
+ if ( DDO )
+ {
+ return ( PDU->Read( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+
+ return ( TRUE );
+ }
+
+BOOL
+NActionRSP :: Write (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ UID *AffectedSOPInstanceUID,
+ UINT16 ActionTypeID,
+ UINT16 Status,
+ DICOMDataObject *DDO)
+ {
+ UID SOPClassUID;
+ LE_UINT16 Command, MessageID, DataSetType, ActionID, StatusField;
+ VR *vr;
+ DICOMCommandObject rDCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! DCO )
+ return ( FALSE );
+
+ Command = 0x8130;
+ MessageID = DCO->GetUINT16 ( 0x0000, 0x0110 );
+
+ if ( DDO )
+ DataSetType = 0x0102;
+ else
+ DataSetType = 0x0101;
+
+ ActionID = ActionTypeID;
+ StatusField = Status;
+
+ if ( ! GetUID ( SOPClassUID ) )
+ {
+ return ( FALSE );
+ }
+
+ vr = TranslateUIDToVR ( &SOPClassUID, 0x0000, 0x0002 );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0100, sizeof(UINT16), &Command, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0120, sizeof(UINT16), &MessageID, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0800, sizeof(UINT16), &DataSetType, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0900, sizeof(UINT16), &StatusField, (BOOL) FALSE );
+ rDCO.Push(vr);
+
+ if ( AffectedSOPInstanceUID )
+ {
+ vr = TranslateUIDToVR ( AffectedSOPInstanceUID, 0x0000, 0x1000 );
+ rDCO.Push ( vr );
+ }
+ else
+ {
+ // Check to see if we can snag it from the command object
+ vr = DCO->GetVR(0x0000, 0x1000);
+ if ( vr )
+ {
+ // Copy it
+ vr = CopyVR ( vr );
+ rDCO.Push( vr );
+ }
+ }
+
+ vr = new VR ( 0x0000, 0x1008, sizeof(UINT16), &ActionID, (BOOL) FALSE );
+ rDCO.Push ( vr );
+
+ if ( ! PDU->Write ( &rDCO, SOPClassUID ) )
+ return ( FALSE );
+
+ if ( DDO )
+ {
+ if ( ! PDU->Write ( DDO, SOPClassUID ) )
+ return ( FALSE );
+ }
+ return ( TRUE );
+ }
+
+/************************* N-CREATE **********************************/
+BOOL
+NCreateRQ :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO)
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x0140 )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ if ( PDU )
+ {
+ if ( DDO )
+ {
+ return ( PDU->Read( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+
+ return ( TRUE );
+ }
+
+BOOL
+NCreateRQ :: Write (
+ PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ UID *AffectedSOPInstanceUID )
+ {
+ UID SOPClassUID;
+ LE_UINT16 Command, MessageID, DataSetType;
+ VR *vr;
+ DICOMCommandObject DCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ Command = 0x0140;
+ MessageID = uniq16odd();
+// if ( DDO )
+ DataSetType = 0x0102;
+// else
+// DataSetType = 0x0101;
+
+ if ( ! GetUID ( SOPClassUID ) )
+ {
+ return ( FALSE );
+ }
+
+ vr = TranslateUIDToVR ( &SOPClassUID, 0x0000, 0x0002 );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0100, sizeof(UINT16), &Command, (BOOL) FALSE );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0110, sizeof(UINT16), &MessageID, (BOOL) FALSE );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0800, sizeof(UINT16), &DataSetType, (BOOL) FALSE );
+ DCO.Push(vr);
+
+ if ( AffectedSOPInstanceUID )
+ {
+ vr = TranslateUIDToVR ( AffectedSOPInstanceUID, 0x0000, 0x1000 );
+ DCO.Push ( vr );
+ }
+
+
+ if ( ! PDU->Write ( &DCO, SOPClassUID ) )
+ return ( FALSE );
+
+ if ( DDO )
+ {
+ if ( ! PDU->Write ( DDO, SOPClassUID ) )
+ return ( FALSE );
+ }
+ return ( TRUE );
+ }
+
+BOOL
+NCreateRQ :: Write (
+ PDU_Service *PDU,
+ UID *AffectedSOPInstanceUID )
+ {
+
+ return ( Write ( PDU, NULL, AffectedSOPInstanceUID ) );
+ }
+
+
+BOOL
+NCreateRSP :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU,
+ DICOMDataObject *DDO )
+ {
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x8140 )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ if ( PDU )
+ {
+ if ( DDO )
+ {
+ return ( PDU->Read( DDO ) );
+ }
+ }
+ return ( TRUE );
+ }
+
+ return ( TRUE );
+ }
+
+BOOL
+NCreateRSP :: Write (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ UID *AffectedSOPInstanceUID,
+ UINT16 Status,
+ DICOMDataObject *DDO)
+ {
+ UID SOPClassUID;
+ LE_UINT16 Command, MessageID, DataSetType, StatusField;
+ VR *vr;
+ DICOMCommandObject rDCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! DCO )
+ return ( FALSE );
+
+ Command = 0x8140;
+ MessageID = DCO->GetUINT16 ( 0x0000, 0x0110 );
+
+ if ( DDO )
+ DataSetType = 0x0102;
+ else
+ DataSetType = 0x0101;
+
+ StatusField = Status;
+
+ if ( ! GetUID ( SOPClassUID ) )
+ {
+ return ( FALSE );
+ }
+
+ vr = TranslateUIDToVR ( &SOPClassUID, 0x0000, 0x0002 );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0100, sizeof(UINT16), &Command, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0120, sizeof(UINT16), &MessageID, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0800, sizeof(UINT16), &DataSetType, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0900, sizeof(UINT16), &StatusField, (BOOL) FALSE );
+ rDCO.Push(vr);
+
+ if ( AffectedSOPInstanceUID )
+ {
+ vr = TranslateUIDToVR ( AffectedSOPInstanceUID, 0x0000, 0x1000 );
+ rDCO.Push ( vr );
+ }
+ else
+ {
+ // Check to see if we can snag it from the command object
+ vr = DCO->GetVR(0x0000, 0x1000);
+ if ( vr )
+ {
+ // Copy it
+ vr = CopyVR ( vr );
+ rDCO.Push( vr );
+ }
+ }
+
+ if ( ! PDU->Write ( &rDCO, SOPClassUID ) )
+ return ( FALSE );
+
+ if ( DDO )
+ {
+ if ( ! PDU->Write ( DDO, SOPClassUID ) )
+ return ( FALSE );
+ }
+ return ( TRUE );
+ }
+
+/************************ N-DELETE **************************/
+
+BOOL
+NDeleteRQ :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU)
+ {
+ UNUSED_ARGUMENT(PDU);
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x0150 )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ return ( TRUE );
+ }
+
+ return ( TRUE );
+ }
+
+BOOL
+NDeleteRQ :: Write (
+ PDU_Service *PDU,
+ UID *RequestedSOPInstanceUID )
+ {
+ UID SOPClassUID;
+ LE_UINT16 Command, MessageID, DataSetType;
+ VR *vr;
+ DICOMCommandObject DCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ Command = 0x0150;
+ MessageID = uniq16odd();
+ DataSetType = 0x0101;
+
+ if ( ! GetUID ( SOPClassUID ) )
+ {
+ return ( FALSE );
+ }
+
+ vr = TranslateUIDToVR ( &SOPClassUID, 0x0000, 0x0003 );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0100, sizeof(UINT16), &Command, (BOOL) FALSE );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0110, sizeof(UINT16), &MessageID, (BOOL) FALSE );
+ DCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0800, sizeof(UINT16), &DataSetType, (BOOL) FALSE );
+ DCO.Push(vr);
+
+ if ( RequestedSOPInstanceUID )
+ {
+ vr = TranslateUIDToVR ( RequestedSOPInstanceUID, 0x0000, 0x1001 );
+ DCO.Push ( vr );
+ }
+
+
+ if ( ! PDU->Write ( &DCO, SOPClassUID ) )
+ return ( FALSE );
+
+ return ( TRUE );
+ }
+
+
+
+BOOL
+NDeleteRSP :: Read (
+ DICOMCommandObject *DCO,
+ PDU_Service *PDU)
+ {
+ UNUSED_ARGUMENT(PDU);
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0100) != 0x8150 )
+ return ( FALSE );
+
+ if ( DCO->GetUINT16(0x0000, 0x0800) != 0x0101 )
+ {
+ return ( TRUE );
+ }
+
+ return ( TRUE );
+ }
+
+BOOL
+NDeleteRSP :: Write (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ UID *AffectedSOPInstanceUID,
+ UINT16 Status)
+ {
+ UID SOPClassUID;
+ LE_UINT16 Command, MessageID, DataSetType, StatusField;
+ VR *vr;
+ DICOMCommandObject rDCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! DCO )
+ return ( FALSE );
+
+ Command = 0x8150;
+ MessageID = DCO->GetUINT16 ( 0x0000, 0x0110 );
+
+ DataSetType = 0x0101;
+
+
+ StatusField = Status;
+
+ if ( ! GetUID ( SOPClassUID ) )
+ {
+ return ( FALSE );
+ }
+
+ vr = TranslateUIDToVR ( &SOPClassUID, 0x0000, 0x0002 );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0100, sizeof(UINT16), &Command, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0120, sizeof(UINT16), &MessageID, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0800, sizeof(UINT16), &DataSetType, (BOOL) FALSE );
+ rDCO.Push(vr);
+ vr = new VR ( 0x0000, 0x0900, sizeof(UINT16), &StatusField, (BOOL) FALSE );
+ rDCO.Push(vr);
+
+ if ( AffectedSOPInstanceUID )
+ {
+ vr = TranslateUIDToVR ( AffectedSOPInstanceUID, 0x0000, 0x1000 );
+ rDCO.Push ( vr );
+ }
+ else
+ {
+ // Check to see if we can snag it from the command object
+ vr = DCO->GetVR(0x0000, 0x1000);
+ if ( vr )
+ {
+ // Copy it
+ vr = CopyVR ( vr );
+ rDCO.Push( vr );
+ }
+ }
+
+
+ if ( ! PDU->Write ( &rDCO, SOPClassUID ) )
+ return ( FALSE );
+
+ return ( TRUE );
+ }
+
+
+// Convert UID structures to a VR structure
+//
+// Notes: very lenienant about encoding. Makes a good effort to encode
+// correctly VR UI type even if UID isn't perfect
+
+VR *
+TranslateUIDToVR (
+ UID *Uid,
+ UINT16 Group,
+ UINT16 Element )
+ {
+ UINT32 Length;
+ VR *vr;
+ char *s;
+
+ if ( ! Uid )
+ {
+ return ( new VR (Group, Element, 0, (BOOL) FALSE ) );
+ }
+ Length = Uid->GetSize ();
+
+ if(Length & 0x01)
+ ++Length;
+
+ vr = new VR ( Group, Element, Length, (BOOL) TRUE );
+
+ if ( ! vr )
+ return ( NULL );
+
+ memset ( (void*)vr->Data, 0, Length);
+ memcpy ( (void*)vr->Data, (void*)Uid->GetBuffer(1), Uid->GetSize() );
+
+ Length = Uid->GetSize () ;
+
+ s = (char*)vr->Data;
+ while ( Length )
+ {
+ if(s[Length-1] == ' ' )
+ s[Length-1] = '\0';
+ else
+ break;
+ --Length;
+ }
+ if ( Length & 0x01 )
+ ++Length;
+
+ vr->Length = Length;
+ return ( vr );
+ }
+
+static VR *
+CopyVR (
+ VR *vr )
+ {
+ VR *nvr;
+
+ if ( ! vr )
+ return ( NULL );
+
+ if(vr->Length)
+ {
+ nvr = new VR ( vr->Group, vr->Element, vr->Length, (BOOL) TRUE );
+ memcpy ( (void*)nvr->Data, (void*)vr->Data, vr->Length);
+ }
+ else
+ nvr = new VR ( vr->Group, vr->Element, 0, (BOOL) FALSE );
+
+ return ( nvr );
+ }
+
+
+static VR *
+BuildATVR (
+ DICOMObject *DO,
+ UINT16 Group,
+ UINT16 Element)
+ {
+ VR *vr, *tvr;
+ DICOMObject TDO;
+ UINT Count;
+ LE_UINT16 dGroup, dElement;
+ BYTE *Data;
+
+ if ( ! DO )
+ return ( new VR ( Group, Element, 0, (BOOL) FALSE ) );
+
+ Count = 0;
+
+
+ while (( tvr = DO->Pop () ))
+ {
+ if ( tvr->Element != 0x0000 )
+ ++Count;
+ TDO.Push(tvr);
+ }
+
+ vr = new VR ( Group, Element, (UINT32) Count * (sizeof(UINT16) * 2), (BOOL) TRUE );
+
+ Data = (BYTE*)vr->Data;
+
+ Count = 0;
+ while (( tvr = TDO.Pop () ))
+ {
+ if ( tvr->Element == 0x0000 )
+ {
+ delete tvr;
+ continue;
+ }
+
+ dGroup = tvr->Group;
+ dElement = tvr->Element;
+
+ memcpy ( (void*) &Data[Count], (void*) &dGroup, sizeof(UINT16) );
+ Count += sizeof(UINT16);
+ memcpy ( (void*) &Data[Count], (void*) &dElement, sizeof(UINT16) );
+ Count += sizeof(UINT16);
+ DO->Push(tvr);
+ }
+
+ return ( vr );
+ }
+
+
+static BOOL
+DecomposeATVR (
+ VR *vr,
+ DICOMObject *DO )
+ {
+ VR *tvr;
+ DICOMObject TDO;
+ UINT Count;
+ LE_UINT16 dGroup, dElement;
+ BYTE *Data;
+
+ if ( ! vr )
+ return ( FALSE );
+
+ if ( ! vr->Data )
+ return ( FALSE );
+
+ if ( ! vr->Length )
+ return ( FALSE );
+
+ Count = 0;
+ Data = (BYTE*)vr->Data;
+
+ while ( Count < vr->Length )
+ {
+ memcpy ( (void*) &dGroup, (void*) &Data[Count], sizeof(UINT16) );
+ Count += sizeof(UINT16);
+ memcpy ( (void*) &dElement, (void*) &Data[Count], sizeof(UINT16) );
+ Count += sizeof(UINT16);
+ tvr = new VR ( dGroup, dElement, 0, (BOOL) FALSE );
+ DO->Push(tvr);
+ }
+
+ return ( TRUE );
+ }
+
+
diff --git a/dimsen.hpp b/dimsen.hpp
new file mode 100644
index 0000000..1a6387a
--- /dev/null
+++ b/dimsen.hpp
@@ -0,0 +1,236 @@
+/* 20020822 mvh Cleanup layout */
+/* 20100619 bcb Added virtual destructors */
+/* 20100717 mvh Merged */
+
+#ifndef _DIMSEN_HPP
+# define _DIMSEN_HPP
+
+# define N_EVENT_REPORT_RQ 0x0100
+# define N_EVENT_REPORT_RSP 0x8100
+# define N_GET_RQ 0x0110
+# define N_GET_RSP 0x8110
+# define N_SET_RQ 0x0120
+# define N_SET_RSP 0x8120
+# define N_ACTION_RQ 0x0130
+# define N_ACTION_RSP 0x8130
+# define N_CREATE_RQ 0x0140
+# define N_CREATE_RSP 0x8140
+# define N_DELETE_RQ 0x0150
+# define N_DELETE_RSP 0x8150
+
+VR *TranslateUIDToVR ( UID *, UINT16, UINT16 );
+
+class NEventReportRQ
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *PDU=NULL,
+ DICOMDataObject *DDO=NULL );
+ BOOL Write ( PDU_Service *,
+ DICOMDataObject *DDO,
+ UID *AffectedSOPInstanceUID,
+ UINT16 EventID);
+ BOOL Write ( PDU_Service *PDU,
+ UID *AffectedSOPInstanceUID,
+ UINT16 EventID);
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~NEventReportRQ() {};
+#endif
+ };
+
+class NEventReportRSP
+ {
+ public:
+
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *PDU = NULL,
+ DICOMDataObject *DDO = NULL );
+ BOOL Write ( PDU_Service *,
+ DICOMCommandObject *,
+ UID *AffectedSOPInstanceUID,
+ UINT16 Status,
+ UINT16 EventID,
+ DICOMDataObject *DDO = NULL);
+ BOOL Write ( PDU_Service *,
+ DICOMCommandObject *,
+ UID *AffectedSOPInstanceUID,
+ UINT16 EventID,
+ DICOMDataObject *DDO = NULL);
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~NEventReportRSP() {};
+#endif
+ };
+
+class NGetRQ
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *PDU = NULL,
+ DICOMDataObject *DDO = NULL);
+ BOOL Write ( PDU_Service *,
+ DICOMDataObject *DDO,
+ UID *RequestedSOPInstanceUID);
+ BOOL Write ( PDU_Service *PDU,
+ UID *RequestedSOPInstnaceUID );
+
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~NGetRQ() {};
+#endif
+ };
+
+class NGetRSP
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *PDU = NULL,
+ DICOMDataObject *DDO = NULL);
+ BOOL Write ( PDU_Service *PDU,
+ DICOMCommandObject *,
+ UID *AffectedSOPInstanceUID,
+ UINT16 Status = 0,
+ DICOMDataObject *DDO = NULL);
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~NGetRSP() {};
+#endif
+ };
+
+class NSetRQ
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *PDU = NULL,
+ DICOMDataObject *DDO = NULL );
+ BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ UID *RequestedSOPInstanceUID );
+ BOOL Write ( PDU_Service *PDU,
+ UID *RequestedSOPInstnaceUID );
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~NSetRQ() {};
+#endif
+ };
+
+class NSetRSP
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *PDU = NULL,
+ DICOMDataObject *DDO = NULL );
+ BOOL Write ( PDU_Service *PDU,
+ DICOMCommandObject *,
+ UID *AffectedSOPInstanceUID,
+ UINT16 Status = 0,
+ DICOMDataObject *DDO = NULL);
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~NSetRSP() {};
+#endif
+ };
+
+class NActionRQ
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *PDU=NULL,
+ DICOMDataObject *DDO=NULL );
+ BOOL Write ( PDU_Service *,
+ DICOMDataObject *,
+ UID *RequestedSOPInstanceUID,
+ UINT16 ActionTypeID);
+ BOOL Write ( PDU_Service *,
+ UID *RequestedSOPInstanceUID,
+ UINT16 ActionTypeID);
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~NActionRQ() {};
+#endif
+ };
+
+class NActionRSP
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *PDU = NULL,
+ DICOMDataObject *DDO = NULL );
+ BOOL Write ( PDU_Service *PDU,
+ DICOMCommandObject *,
+ UID *AffectedSOPInstanceUID,
+ UINT16 ActionTypeID,
+ UINT16 Status = 0,
+ DICOMDataObject *DDO = NULL);
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~NActionRSP() {};
+#endif
+ };
+
+
+class NCreateRQ
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *PDU = NULL,
+ DICOMDataObject *DDO = NULL );
+ BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ UID *AffectedSOPInstanceUID );
+ BOOL Write ( PDU_Service *PDU,
+ UID *AffectedSOPInstanceUID );
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~NCreateRQ() {};
+#endif
+ };
+
+class NCreateRSP
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *PDU = NULL,
+ DICOMDataObject *DDO = NULL );
+ BOOL Write ( PDU_Service *PDU,
+ DICOMCommandObject *,
+ UID *AffectedSOPInstanceUID,
+ UINT16 Status = 0,
+ DICOMDataObject *DDO = NULL);
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~NCreateRSP() {};
+#endif
+ };
+
+class NDeleteRQ
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *PDU = NULL);
+ BOOL Write ( PDU_Service *PDU,
+ UID *RequestedSOPInstanceUID );
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~NDeleteRQ() {};
+#endif
+ };
+
+class NDeleteRSP
+ {
+ public:
+ BOOL Read ( DICOMCommandObject *,
+ PDU_Service *PDU = NULL);
+ BOOL Write ( PDU_Service *PDU,
+ DICOMCommandObject *,
+ UID *AffectedSOPInstanceUID,
+ UINT16 Status = 0);
+ virtual BOOL GetUID ( UID & ) = 0;
+#ifdef __GNUC__
+ virtual ~NDeleteRSP() {};
+#endif
+ };
+
+#endif
+
diff --git a/dprintf.cpp b/dprintf.cpp
new file mode 100644
index 0000000..ddf1094
--- /dev/null
+++ b/dprintf.cpp
@@ -0,0 +1,344 @@
+/*
+20000211 ljz Removed MajorEvent and MinorEvent instances of 'Debug'.
+ Cosmetics. Added UserLog and TroubleLog.
+ Added timestamp option.
+ Added CriticalSection when printing to file or stdout.
+20011110 mvh Post release 1.3.10: keep log files closed while working
+20021027 mvh Avoid crash when logfile cannot be opened
+20041003 mvh Note: max 1200 chars (use %.1000s to print long strings)
+20060618 mvh Define _SH_DENYNO if needed
+20070105 mvh Added timestamp for linux users (thanks, Mark Pearson)
+20070406 mvh Use reentrant ctime_r and localtime_r when available
+20070408 mvh Protected entire .printf() with global critical section
+20070712 mvh Closed/opened critical section where recursive call to printf
+ Would hang linux version with sqlite
+20071120 mvh Use fputs instead of fprintf at end: otherwise % removed
+20080821 mvh Fix for Solaris SUNwspro compiler
+20090620 jf Include file stuff
+20091231 bcb Changed char* to const char* for gcc4.2 warnings
+20100111 mvh Merged
+20100125 mvh Removed linux warning
+20100309 bcb Removed Windows only variable from unix build.
+20100619 bcb Added #ifndefs made Port a local lPort (gcc4.0 Warnings)
+20100717 mvh Merged
+20100816 mvh removed (a) from #ifndef EnterCriticalSection(a) etc
+*/
+
+# include <stdio.h>
+# include <stdarg.h>
+
+#ifndef UNIX
+# include <time.h>
+# include <windows.h>
+# include <share.h>
+#else
+# include "wintypes.hpp"
+# include "npipe.hpp"
+#endif
+# include "dicom.hpp"
+# include "dprintf.hpp"
+
+#ifdef UNIX
+# include <pthread.h> //DUCKHEAD92
+#endif
+
+#ifndef _SH_DENYNO
+#define _SH_DENYNO SH_DENYNO
+#endif
+
+extern char ServerName[];
+
+#ifndef WIN32
+# include <unistd.h>
+# include <dirent.h>
+#ifndef EnterCriticalSection
+# define EnterCriticalSection(a) pthread_mutex_lock(a)
+#endif
+#ifndef LeaveCriticalSection
+# define LeaveCriticalSection(a) pthread_mutex_unlock(a)
+#endif
+#ifndef CRITICAL_SECTION
+# define CRITICAL_SECTION pthread_mutex_t
+#endif
+#ifndef InitializeCriticalSection
+# define InitializeCriticalSection(a) pthread_mutex_init(a, NULL);
+#endif
+#ifndef DeleteCriticalSection
+# define DeleteCriticalSection(a) pthread_mutex_destroy(a);
+#endif
+#endif
+
+static CRITICAL_SECTION CriticalFile;
+static int CriticalFileExists=0;
+
+/* Constructor and Destructor */
+
+Debug::Debug()
+#ifdef __GNUC__ //Faster with member initialization.
+:BDebug(0),Debugfp(NULL),CloseOnOff(0), UseMessagePipe(0), UseUDP(0),
+bAddTimeStamps(0), SocketUDP(), DescribeSource(FALSE)
+#endif
+{
+ if (!CriticalFileExists)
+ { CriticalFileExists=1;
+ InitializeCriticalSection(&CriticalFile);
+ }
+#ifndef __GNUC__
+ BDebug = 0;
+ Debugfp = NULL;
+ CloseOnOff = 0;
+ UseMessagePipe = 0;
+ UseUDP = 0;
+ bAddTimeStamps = 0;
+#endif
+}
+
+Debug::~Debug()
+{
+ Off();
+}
+
+/* Several overloaded Debug 'ON' functions */
+
+void Debug::On()
+{
+ Off();
+ if (!CriticalFileExists)
+ { CriticalFileExists=1;
+ InitializeCriticalSection(&CriticalFile);
+ }
+ Debugfp = stdout;
+ BDebug = 1 ;
+ CloseOnOff = 0;
+ UseMessagePipe = 0;
+}
+
+void Debug::On(FILE* fp)
+{
+ Off();
+ if(!fp) return;
+
+ if (!CriticalFileExists)
+ { CriticalFileExists=1;
+ InitializeCriticalSection(&CriticalFile);
+ }
+
+ Debugfp = fp;
+ BDebug = 1;
+ CloseOnOff = 0;
+ UseMessagePipe = 0;
+}
+
+void Debug::On(char* filename)
+{
+ Off();
+ if(!filename) return;
+
+ if (!CriticalFileExists)
+ { CriticalFileExists=1;
+ InitializeCriticalSection(&CriticalFile);
+ }
+
+//#ifndef UNIX
+// Debugfp = _fsopen(filename, "a", _SH_DENYNO);
+//#else
+// Debugfp = fopen(filename, "a");
+//#endif
+// if(!Debugfp)
+// return;
+
+ Debugfp = NULL;
+ strcpy(FilePipeName, filename);
+ BDebug = 3;
+ CloseOnOff = 0;
+ UseMessagePipe = 0;
+}
+
+void Debug::OnMsgPipe(char* MsgPipe)
+{
+ Off();
+ if (!CriticalFileExists)
+ { CriticalFileExists=1;
+ InitializeCriticalSection(&CriticalFile);
+ }
+ BDebug = 1;
+ UseMessagePipe = 1;
+ CloseOnOff = 0;
+ DescribeSource = TRUE;
+ strcpy(FilePipeName, MsgPipe);
+}
+
+void Debug::OnMsgPipe(char* MsgPipe, BOOL DSource)
+{
+ Off();
+ if (!CriticalFileExists)
+ { CriticalFileExists=1;
+ InitializeCriticalSection(&CriticalFile);
+ }
+ BDebug = 1;
+ UseMessagePipe = 1;
+ CloseOnOff = 0;
+ DescribeSource = DSource;
+ strcpy(FilePipeName, MsgPipe);
+}
+
+void Debug::OnUDP(char* Host, const char* lPort)
+{
+ Off();
+ if (!CriticalFileExists)
+ { CriticalFileExists=1;
+ InitializeCriticalSection(&CriticalFile);
+ }
+ if(!SocketUDP.BindUDPClient(Host, lPort))
+ { printf("FAILED TO BIND UDP CLIENT\n");
+ return;
+ }
+ UseUDP = 1;
+ BDebug = 1;
+ CloseOnOff = 0;
+ DescribeSource = TRUE;
+}
+
+
+/* One Debug 'OFF' function */
+
+void Debug::Off()
+{
+ if(!BDebug)
+ return;
+// DeleteCriticalSection(&CriticalFile);
+ BDebug = 0;
+ if(CloseOnOff && Debugfp != NULL)
+ fclose(Debugfp);
+ CloseOnOff = 0;
+ UseMessagePipe = 0;
+ UseUDP = 0;
+}
+
+
+/* Finally the PRINT function */
+
+#ifndef localtime_r
+#define localtime_r(a, b) memcpy(b, localtime(a), sizeof(struct tm))
+#endif
+
+int Debug::printf(const char *fmt, ...)
+{
+ int rc = 0;
+ va_list vargs;
+ char s[1250];
+ time_t Time;
+#ifndef UNIX
+ struct tm LocalTime;
+#endif
+ int iLength;
+
+ /* Debug::On() must be called first */
+ if(!BDebug)
+ return rc;
+
+ EnterCriticalSection(&CriticalFile);
+
+ if(DescribeSource)
+ sprintf(s, "[%s] ", ServerName);
+ else
+ s[0] = 0;
+
+#ifndef UNIX
+ if (bAddTimeStamps)
+ {
+ time(&Time); /* Get time as long integer. */
+ localtime_r(&Time, &LocalTime); /* Convert to local time. */
+ sprintf(s + strlen(s), "%04d%02d%02d %02d:%02d:%02d ",
+ LocalTime.tm_year + 1900,
+ LocalTime.tm_mon + 1,
+ LocalTime.tm_mday,
+ LocalTime.tm_hour,
+ LocalTime.tm_min,
+ LocalTime.tm_sec);
+ }
+#else
+ if (bAddTimeStamps)
+ { char TimeString[128], buf[64];
+ Time = time(NULL);
+#ifdef SOLARIS
+ strcpy(TimeString, ctime_r(&Time, buf, 64));
+#else
+ strcpy(TimeString, ctime_r(&Time, buf));
+#endif
+ TimeString[strlen(TimeString)-1] = '\0';
+ strcat(s, TimeString);
+ strcat(s, " ");
+ }
+#endif
+
+ iLength = strlen(s);
+ va_start(vargs, fmt);
+ vsprintf(s + iLength, fmt, vargs);
+ va_end(vargs);
+
+ LeaveCriticalSection(&CriticalFile);
+
+ if ((strstr(s + iLength, "***")) && (this != &TroubleLog))
+ TroubleLog.printf("%s", s + iLength);
+
+ EnterCriticalSection(&CriticalFile);
+
+ if(!UseMessagePipe)
+ { if(!UseUDP)
+ { if (BDebug==3)
+ { // append to a file that is opened/closed everytime
+#ifndef UNIX
+ Debugfp = _fsopen(FilePipeName, "a", _SH_DENYNO);
+#else
+ Debugfp = fopen(FilePipeName, "a");
+#endif
+ if (Debugfp)
+ { rc = fputs(s, Debugfp);
+ fclose(Debugfp);
+ }
+ }
+
+ else if(Debugfp)
+ { // Output to a file that remains open or stdout
+ rc = fputs(s, Debugfp);
+ fflush(Debugfp);
+ }
+ }
+ else
+ { // Output to a UDP PORT
+ rc = 1;
+ SocketUDP.SendBinary((BYTE*)s,(UINT)strlen(s));
+ }
+ }
+ else
+ { // Output to a named pipe
+#ifndef UNIX
+ if(WaitNamedPipe(FilePipeName, 1))
+ { rc = 1;
+ CallNamedPipe(FilePipeName, s, strlen(s)+1, NULL, 0, NULL, NMPWAIT_NOWAIT);
+ }
+#else
+ NamedPipe aMessagePipe(FilePipeName);
+ aMessagePipe.Connect();
+ if(aMessagePipe.Write((unsigned char*)s, strlen(s)+1) == strlen(s) + 1)
+ rc = 1;
+ aMessagePipe.Disconnect();
+#endif
+ }
+
+ LeaveCriticalSection(&CriticalFile);
+ return rc;
+}
+
+
+/* Global instances of the logging functionality */
+
+Debug SystemDebug;
+Debug OperatorConsole;
+Debug AccessUpdate;
+//Debug MajorEvent;
+//Debug MinorEvent;
+Debug UserLog;
+Debug TroubleLog;
+
diff --git a/dprintf.hpp b/dprintf.hpp
new file mode 100644
index 0000000..8e9d3d7
--- /dev/null
+++ b/dprintf.hpp
@@ -0,0 +1,57 @@
+#ifndef _DPRINTF_H_
+# define _DPRINTF_H_
+
+/*
+20000211 ljz Removed MajorEvent and MinorEvent instances of 'Debug'
+ Added UserLog and TroubleLog
+ Added bAddTimeStamps member
+20011110 mvh Replaced MessagePipeName by FilePipeName
+ Blocked out critical section
+20091231 bcb Changed char* to const char* for gcc4.2 warnings
+20100111 mvh Merged
+20100619 bcb Fix gcc4.0 warnings and prevented coping of clases with pointers.
+20100717 mvh Merged
+*/
+
+class Debug
+{
+private:
+ int BDebug;
+ FILE* Debugfp;
+// CRITICAL_SECTION CriticalFile;
+ int CloseOnOff;
+ int UseMessagePipe;
+ char FilePipeName[256];
+ int UseUDP;
+ char bAddTimeStamps;
+public:
+ Socket SocketUDP;
+public:
+ Debug();
+ ~Debug();
+ BOOL DescribeSource;
+ void AddTimeStamps(char YesOrNo) {bAddTimeStamps = YesOrNo;};
+ void On(FILE *);
+ void On();
+ void On(char *filename);
+ void OnMsgPipe(char *MsgPipeName);
+ void OnMsgPipe(char *MsgPipeName, BOOL);
+ void OnUDP(char *Host, const char *IP);
+ void Off();
+ int printf(const char *, ...);
+#ifdef __GNUC__
+private:// This will prevent it from being copied (it has pointers)
+ Debug(const Debug&);
+ Debug & operator = (const Debug &D);
+#endif
+};
+
+extern Debug SystemDebug;
+extern Debug OperatorConsole;
+extern Debug AccessUpdate;
+//extern Debug MajorEvent;
+//extern Debug MinorEvent;
+extern Debug UserLog;
+extern Debug TroubleLog;
+
+#endif
diff --git a/endian.cpd b/endian.cpd
new file mode 100644
index 0000000..ac050a9
--- /dev/null
+++ b/endian.cpd
@@ -0,0 +1,103 @@
+/* mvh 20001106 removed unneeded (and sometimes uncompilable) XE_UINTX::XE_UINTX (int x) */
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+// Template file. Never compiler directly
+
+XE_UINTX & XE_UINTX :: operator = (UINTX &x)
+ {
+ Data = SwitchEndian (x);
+ return (*this);
+ }
+
+XE_UINTX & XE_UINTX :: operator = (const XE_UINTX &x)
+ {
+ Data = x.Data;
+ return (*this);
+ }
+
+XE_UINTX & XE_UINTX :: operator = (const int &x)
+ {
+ UINTX Temp = (UINTX) x;
+ Data = SwitchEndian (Temp);
+ return (*this);
+ }
+
+XE_UINTX * XE_UINTX :: operator & ()
+ {
+ return ( (XE_UINTX*)&Data );
+ }
+
+XE_UINTX :: operator UINTX ()
+ {
+ return (SwitchEndian (Data) );
+ }
+
+XE_UINTX :: XE_UINTX ()
+ {
+ Data = 0;
+ }
+
+XE_UINTX :: XE_UINTX (XE_UINTX &x)
+ {
+ Data = x.Data;
+ }
+
+XE_UINTX :: XE_UINTX (UINT16 x)
+ {
+ UINTX Temp = (UINTX) x;
+ Data = SwitchEndian ( Temp );
+ }
+
+XE_UINTX :: XE_UINTX (UINT32 x)
+ {
+ UINTX Temp = (UINTX) x;
+ Data = SwitchEndian ( Temp );
+ }
+
+XE_UINTX :: XE_UINTX (INT16 x)
+ {
+ UINTX Temp = (UINTX) x;
+ Data = SwitchEndian ( Temp );
+ }
+
+XE_UINTX :: XE_UINTX (INT32 x)
+ {
+ UINTX Temp = (UINTX) x;
+ Data = SwitchEndian ( Temp );
+ }
+
+//XE_UINTX :: XE_UINTX (int x)
+// {
+// UINTX Temp = (UINTX) x;
+// Data = SwitchEndian ( Temp );
+// }
+
+
diff --git a/endian.cxx b/endian.cxx
new file mode 100644
index 0000000..7534f79
--- /dev/null
+++ b/endian.cxx
@@ -0,0 +1,121 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/* 20070330 mvh Merged bcb stuff */
+/* 20070726 bcb Removed some duplicates from endian.hpp */
+/* 20130508 lsp Removed unused XE_UINTX and include "endian.cpd"
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+# include "dicom.hpp"
+
+UINT16 SwitchEndian(UINT16 x)
+ {
+ return ( ((x >> 8) & 0x00ff) | ((x << 8) & 0xff00) );
+ }
+
+UINT32 SwitchEndian(UINT32 x)
+ {
+ return ( ((UINT32) SwitchEndian ((UINT16) (x >> 16))) |
+ ((UINT32) (SwitchEndian ((UINT16) (x & 0x0000ffff)) << 16) ));
+ }
+
+INT16 SwitchEndian(INT16 x)
+ {
+ return ((INT16) SwitchEndian((UINT16) x) );
+ }
+
+INT32 SwitchEndian(INT32 x)
+ {
+ return ((INT32) SwitchEndian((UINT32) x) );
+ }
+
+# ifndef BSD // done in endian.hpp
+
+# if NATIVE_ENDIAN == LITTLE_ENDIAN
+
+# define LE_UINT16 UINT16
+# define LE_UINT32 UINT32
+# define LE_INT16 INT16
+# define LE_INT32 INT32
+
+//# define XE_UINTX BE_UINT16
+# define UINTX UINT16
+//# include "endian.cpd"
+//#undef XE_UINTX
+#undef UINTX
+//# define XE_UINTX BE_UINT32
+# define UINTX UINT32
+//# include "endian.cpd"
+//#undef XE_UINTX
+#undef UINTX
+//# define XE_UINTX BE_INT16
+# define UINTX INT16
+//# include "endian.cpd"
+//#undef XE_UINTX
+#undef UINTX
+//# define XE_UINTX BE_INT32
+# define UINTX INT32
+//# include "endian.cpd"
+
+//#undef XE_UINTX
+#undef UINTX
+
+#else
+# define BE_UINT16 UINT16
+# define BE_UINT32 UINT32
+# define BE_INT16 INT16
+# define BE_INT32 INT32
+
+//# define XE_UINTX LE_UINT16
+# define UINTX UINT16
+//# include "endian.cpd"
+//#undef XE_UINTX
+#undef UINTX
+//# define XE_UINTX LE_UINT32
+# define UINTX UINT32
+//# include "endian.cpd"
+//#undef XE_UINTX
+#undef UINTX
+//# define XE_UINTX LE_INT16
+# define UINTX INT16
+//# include "endian.cpd"
+//#undef XE_UINTX
+#undef UINTX
+//# define XE_UINTX LE_INT32
+# define UINTX INT32
+//# include "endian.cpd"
+
+//#undef XE_UINTX
+#undef UINTX
+
+#endif
+#endif //BSD
+
+
+
+
diff --git a/endian.hpd b/endian.hpd
new file mode 100644
index 0000000..cf37e57
--- /dev/null
+++ b/endian.hpd
@@ -0,0 +1,53 @@
+/* mvh 20001106 removed unneeded (and sometimes uncompilable) XE_UINTX::XE_UINTX (int x) */
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+// Template file. Never include directly. Include endian.hpp instead
+
+class XE_UINTX
+ {
+ public:
+ UINTX Data;
+
+ XE_UINTX & operator = (UINTX &);
+ XE_UINTX & operator = (const XE_UINTX &);
+ XE_UINTX & operator = (const int &);
+ XE_UINTX * operator & ();
+ operator UINTX ();
+ XE_UINTX ();
+ XE_UINTX (XE_UINTX &);
+ XE_UINTX (UINT16);
+ XE_UINTX (UINT32);
+ XE_UINTX (INT16);
+ XE_UINTX (INT32);
+// XE_UINTX (int);
+ };
+
+
diff --git a/endian.hpp b/endian.hpp
new file mode 100644
index 0000000..a6e724d
--- /dev/null
+++ b/endian.hpp
@@ -0,0 +1,107 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/*
+20090215 mvh Started an update history
+*/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+// Architectually Neutral Endian types.
+//
+// Note these are not done with C++ templates. This is a design choice.
+UINT16 SwitchEndian(UINT16 x);
+UINT32 SwitchEndian(UINT32 x);
+INT16 SwitchEndian(INT16 x);
+INT32 SwitchEndian(INT32 x);
+
+# ifdef BSD // Swap durring file reads and writes
+# define LE_UINT16 UINT16
+# define LE_UINT32 UINT32
+# define LE_INT16 INT16
+# define LE_INT32 INT32
+# else //Do the original stuff
+# if NATIVE_ENDIAN == LITTLE_ENDIAN
+
+# define LE_UINT16 UINT16
+# define LE_UINT32 UINT32
+# define LE_INT16 INT16
+# define LE_INT32 INT32
+
+# define XE_UINTX BE_UINT16
+# define UINTX UINT16
+# include "endian.hpd"
+#undef XE_UINTX
+#undef UINTX
+# define XE_UINTX BE_UINT32
+# define UINTX UINT32
+# include "endian.hpd"
+#undef XE_UINTX
+#undef UINTX
+# define XE_UINTX BE_INT16
+# define UINTX INT16
+# include "endian.hpd"
+#undef XE_UINTX
+#undef UINTX
+# define XE_UINTX BE_INT32
+# define UINTX INT32
+# include "endian.hpd"
+
+#undef XE_UINTX
+#undef UINTX
+
+#else
+# define BE_UINT16 UINT16
+# define BE_UINT32 UINT32
+# define BE_INT16 INT16
+# define BE_INT32 INT32
+
+# define XE_UINTX LE_UINT16
+# define UINTX UINT16
+# include "endian.hpd"
+#undef XE_UINTX
+#undef UINTX
+# define XE_UINTX LE_UINT32
+# define UINTX UINT32
+# include "endian.hpd"
+#undef XE_UINTX
+#undef UINTX
+# define XE_UINTX LE_INT16
+# define UINTX INT16
+# include "endian.hpd"
+#undef XE_UINTX
+#undef UINTX
+# define XE_UINTX LE_INT32
+# define UINTX INT32
+# include "endian.hpd"
+
+#undef XE_UINTX
+#undef UINTX
+
+#endif
+#endif //BSD
+
diff --git a/farray.thh b/farray.thh
new file mode 100644
index 0000000..1a5f45a
--- /dev/null
+++ b/farray.thh
@@ -0,0 +1,259 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/*20100309 bcb Changed INT to unsigned UINT.(gcc4.2 Warnings)
+ 20100621 bcb Added no-copy to classes
+ 20100707 mvh Merged
+*/
+
+/************************************************************************
+ *
+ * Sorted / Fixed, Fast-Access Array.
+ *
+ ************************************************************************/
+
+template <class KEYTYPE, class DATATYPE>
+class FixedArray
+ {
+ public:
+ UINT ArraySize;
+ UINT Top;
+ KEYTYPE *KeyTable;
+ DATATYPE *DataTable;
+
+ FixedArray (UINT, BOOL);
+ ~FixedArray ();
+ BOOL Sort();
+ DATATYPE & Add(KEYTYPE &, DATATYPE &);
+ DATATYPE & Add(DATATYPE &);
+ INT IndexOf(KEYTYPE &);
+ DATATYPE & Get(INT Index)
+ { return(DataTable[Index]); };
+ BOOL RemoveAt(INT);
+ DATATYPE & operator [] (INT Index)
+ { return(Get(Index)); };
+ UINT GetSize()
+ { return ( Top ); };
+ UINT GetAllocationSize()
+ { return ( ArraySize ); };
+#ifdef __GNUC__
+ private:// This will prevent it from being copied (it has pointers)
+ FixedArray(const FixedArray&);
+ const FixedArray<KEYTYPE,DATATYPE> & operator = (const FixedArray<KEYTYPE,DATATYPE>&);
+#endif
+ };
+
+template <class KEYTYPE, class DATATYPE>
+class FixedArrayElement
+ {
+ public:
+ KEYTYPE Key;
+ DATATYPE Data;
+ UINT operator > (FixedArrayElement &FAE)
+ { return ( Key > FAE.Key ); };
+ UINT operator < (FixedArrayElement &FAE)
+ { return ( Key < FAE.Key ); };
+ UINT operator == (FixedArrayElement &FAE)
+ { return ( Key == FAE.Key ); };
+ };
+
+template <class KEYTYPE, class DATATYPE>
+ FixedArray<KEYTYPE, DATATYPE> :: FixedArray (
+ UINT aSize,
+ BOOL UseKeys)
+#ifdef __GNUC__// The GCC way
+:ArraySize(aSize), Top(0),KeyTable(NULL),DataTable(new DATATYPE [ aSize ])
+ {
+ if ( UseKeys )
+ KeyTable = new KEYTYPE [ aSize ];
+ }
+#else
+ {
+ ArraySize = aSize;
+ Top = 0;
+ if ( UseKeys )
+ KeyTable = new KEYTYPE [ aSize ];
+ else
+ KeyTable = NULL;
+ DataTable = new DATATYPE [ aSize ];
+ }
+#endif
+
+template <class KEYTYPE, class DATATYPE>
+ FixedArray<KEYTYPE, DATATYPE> :: ~FixedArray ()
+ {
+ if ( KeyTable )
+ delete KeyTable;
+ if ( DataTable )
+ delete DataTable;
+ }
+
+template <class KEYTYPE, class DATATYPE>
+BOOL FixedArray<KEYTYPE, DATATYPE> :: Sort()
+ {
+ UINT Index;
+ FixedArrayElement < KEYTYPE, DATATYPE > FAE;
+ PQueue< FixedArrayElement<KEYTYPE, DATATYPE> > PQFAE;
+
+ if ( ! KeyTable )
+ return ( FALSE ); // Not a sortable array
+
+ Index = 0;
+ while ( Index < Top )
+ {
+ FAE.Key = KeyTable [ Index ];
+ FAE.Data = DataTable [ Index ];
+ PQFAE.Push(FAE);
+ ++Index;
+ }
+ Index = 0;
+ while ( Index < Top )
+ {
+ FAE = PQFAE.Pop ();
+ KeyTable [ Index ] = FAE.Key;
+ DataTable [ Index ] = FAE.Data;
+ ++Index;
+ }
+ return ( TRUE );
+ }
+
+template <class KEYTYPE, class DATATYPE>
+DATATYPE & FixedArray<KEYTYPE, DATATYPE> :: Add(
+ KEYTYPE &Key,
+ DATATYPE &Data)
+ {
+ if (Top < ArraySize)
+ {
+ if ( KeyTable )
+ KeyTable [ Top ] = Key;
+ if ( DataTable )
+ DataTable [ Top ] = Data;
+ ++Top;
+ }
+ return ( DataTable [ Top-1 ] );
+ }
+
+template <class KEYTYPE, class DATATYPE>
+DATATYPE & FixedArray<KEYTYPE, DATATYPE> :: Add(
+ DATATYPE &Data)
+ {
+ if ( Top < ArraySize )
+ {
+ if ( DataTable )
+ DataTable [ Top ] = Data;
+ ++Top;
+ }
+ return ( DataTable [ Top-1 ] );
+ }
+
+template <class KEYTYPE, class DATATYPE>
+INT FixedArray<KEYTYPE, DATATYPE> :: IndexOf(
+ KEYTYPE &Key)
+ {
+ UINT Index = (Top / 2);
+ INT Shift = (Top / 2 - 1);
+
+ if (!KeyTable)
+ return ( -1 );
+
+ if ( ! Top )
+ return ( -1 );
+
+ while ( KeyTable [ Index ] != Key )
+ {
+ if ( KeyTable [ Index ] > Key )
+ Index -= Shift;
+ else
+ Index += Shift;
+
+ if ( Index >= Top )
+ { Index = Top - 1; break; };
+ if ( Index <= 0 )
+ { Index = 0; break; };
+ if ( Shift == 0 )
+ { break; }
+ Shift = Shift / 2;
+ }
+ if ( KeyTable [ Index ] == Key )
+ return ( Index );
+
+ if ( KeyTable [ Index ] < Key )
+ {
+ while ( Index < Top )
+ {
+ if ( KeyTable [ Index ] == Key )
+ return ( Index );
+ if ( KeyTable [ Index ] > Key )
+ return ( -1 );
+ ++Index;
+ }
+ return ( -1 );
+ }
+ else
+ {
+ while ( Index >= 0 )
+ {
+ if ( KeyTable [ Index ] == Key )
+ return ( Index );
+ if ( KeyTable [ Index ] < Key )
+ return ( -1 );
+ --Index;
+ }
+ return ( -1 );
+ }
+ return ( -1 );
+ }
+
+
+template <class KEYTYPE, class DATATYPE>
+BOOL FixedArray<KEYTYPE, DATATYPE> :: RemoveAt(
+ INT Index)
+ {
+ if ( Index >= Top )
+ return ( FALSE );
+
+ if ( DataTable )
+ {
+ if ( (Index + 1) != Top )
+ memcpy( (void*)&DataTable [ Index ],
+ (void*)&DataTable [ Index + 1],
+ sizeof ( DATATYPE ) * Top - Index - 1);
+ }
+ if ( KeyTable )
+ {
+ if ( (Index + 1) != Top )
+ memcpy( (void*)&KeyTable [ Index ],
+ (void*)&KeyTable [ Index + 1],
+ sizeof ( KEYTYPE ) * Top - Index - 1);
+ }
+ --Top;
+ return ( TRUE );
+ }
+
+
diff --git a/filepdu.cxx b/filepdu.cxx
new file mode 100644
index 0000000..dbc1320
--- /dev/null
+++ b/filepdu.cxx
@@ -0,0 +1,356 @@
+/*
+20000420 ljz Fix in MakeChapter10: type of AffectedSOPClassUID and
+ RequestedSOPClassUID
+20030205 ljz Fixed FileMetaInformationVersion for big-endian machines
+20030424 ljz Put the correct TransferSyntaxUID in chapter10 files
+20041108 mvh Fix strdup memory access problem (found using $c drop file test mode)
+20051229 mvh Fixed LEAK of 68 bytes when 0002,0010 not defined
+20060618 mvh Added definition of _SH_DENYNO
+20090211 mvh Check result of Dynamic_ParseRawVRIntoDCM
+20091231 bcb Changed char* to const char* for gcc4.2 warnings
+20100111 mvh Merged
+20100309 bcb Added double parentheses (gcc4.2 Warnings)
+20100309 bcb Cast multichar as UINT16, commented out unused variables (gcc4.2 Warnings)
+20100706 bcb Fixed TransferSyntax in SaveDICOMDataObject(ACRNEMA_VR_DUMP) for testcompress.
+20100726 mvh Merged
+20100823 mvh Merged small comment fix
+20130508 lsp Fixed problem in SaveDicomDataObject() indicated by Klocwork
+*/
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+# include "dicom.hpp"
+# include <stdlib.h>
+
+#ifndef _SH_DENYNO
+#define _SH_DENYNO SH_DENYNO
+#endif
+
+// Disk File I/O for PDU_Service Class
+
+BOOL
+FileBuffer :: OpenForRead ( char *filename )
+ {
+#ifndef WINDOWS
+ fp = fopen(filename, "rb");
+#else
+ // Open Shared mode for Windows. Unix will allow sharing by default
+ fp = _fsopen(filename, "rb", _SH_DENYWR);
+#endif
+ if( fp )
+ return ( TRUE );
+ return ( FALSE );
+ }
+
+BOOL
+FileBuffer :: OpenForWrite ( char *filename )
+ {
+ fp = fopen(filename, "wb");
+ if ( fp )
+ return ( TRUE );
+ return ( FALSE );
+ }
+
+BOOL
+FileBuffer :: Close ()
+ {
+ fclose(fp);
+ return ( TRUE );
+ }
+
+BOOL
+FileBuffer :: SendBinary ( BYTE *Data, UINT Length )
+ {
+ fwrite((char*)Data, 1, Length, fp);
+ return ( TRUE );
+ }
+
+INT
+FileBuffer :: ReadBinary ( BYTE *Data, UINT Length )
+ {
+ INT Ret;
+
+ //fprintf(stderr, "ReadBinary(Data, %d) : ", Length);
+ if(feof(fp))
+ {
+ //fprintf(stderr, " -1\n");
+ return ( -1 );
+ }
+ Ret = (INT)fread((char*)Data, 1, Length, fp);
+ //fprintf(stderr, " %d\n", Ret);
+ return ( Ret );
+ }
+
+DICOMDataObject *
+PDU_Service :: LoadDICOMDataObject (
+ char *filename )
+ {
+ FileBuffer IOBuffer;
+ FILE *fp;
+ char s[256];
+ DICOMDataObject *DDO;
+ UINT Mode;
+ UINT CheckOffset;
+
+ fp = fopen(filename, "rb");
+ if(!fp)
+ return ( NULL );
+ fseek(fp, 128, SEEK_SET);
+ fread(s, 1, 4, fp);
+ s[4] = '\0';
+ if(strcmp(s, "DICM"))
+ {
+ CheckOffset = 0;
+ fseek(fp, 0, SEEK_SET);
+ }
+ else
+ CheckOffset = 128+4;
+
+ fread(s,1,6,fp);
+ if(s[5]>10)
+ Mode = TSA_EXPLICIT_LITTLE_ENDIAN;
+ else
+ Mode = TSA_IMPLICIT_LITTLE_ENDIAN;
+ fseek(fp, CheckOffset, SEEK_SET);
+
+ IOBuffer.fp = fp;
+
+ while(IOBuffer.Buffer :: Fill(50000))
+ ; // still reading from disk
+
+ DDO = new DICOMDataObject;
+
+ if (!Dynamic_ParseRawVRIntoDCM(IOBuffer, DDO, Mode))
+ {
+ delete DDO;
+ DDO = NULL;
+ }
+
+ IOBuffer.Close();
+ return ( DDO );
+ }
+
+
+# define _LittleEndianUID "1.2.840.10008.1.2"
+//# define _ImplementationUID "none yet"
+//# define _ImplementationVersion "0.1AlphaUCDMC "
+//# define _SourceApplicationAE "none "
+
+BOOL
+PDU_Service :: MakeChapter10 (DICOMDataObject *DDOPtr,const char* pszTransferSyntaxUID)
+ {
+ VR *vr, *vr1;
+// UINT16 tuint16;
+// VR *TempVR;
+// char s[140];
+ char _ImplementationUID[128];
+ char _ImplementationVersion[128];
+ char _SourceApplicationAE[32];
+ ImplementationVersion IV;
+ ImplementationClass IC;
+ DICOMDataObject DDOTemp;
+
+ GetImplementationClass(IC);
+ GetImplementationVersion(IV);
+ strcpy(_ImplementationUID, (char*)IC.ImplementationName.GetBuffer(1));
+ strcpy(_ImplementationVersion, (char*)IV.Version.GetBuffer(1));
+ strcpy(_SourceApplicationAE, (char*)AAssociateRQ::CallingApTitle);
+ if (_SourceApplicationAE[0] == ' ')
+ strcpy(_SourceApplicationAE, "UCDMC_TOOLKIT ");
+
+ // Strip away the existing Part 10 header..
+ while((vr = DDOPtr->Pop()))
+ {
+ if(vr->Group!=0x0002)
+ DDOTemp.Push(vr);
+ else
+ delete vr;
+ }
+ while((vr = DDOTemp.Pop()))
+ DDOPtr->Push(vr);
+
+ vr = DDOPtr->GetVR(0x0002, 0x0001); // always null
+ if(!vr)
+ {
+ // This does not contain the C10 Header yet, so we need to
+ // constuct it
+ vr = new VR(0x0002, 0x0001, 0x0002, TRUE);
+ /* The FileMetaInformationVersion */
+// tuint16 = 0x0100;
+// memcpy(vr->Data, (void*)&tuint16, 2);
+ /* First byte should be 0, second should be 1
+ Thanx to William Peterson [wfpeterson at kinetixresources.com]
+ */
+ ((char*)vr->Data)[0] = 0;
+ ((char*)vr->Data)[1] = 1;
+ vr->TypeCode = 'OB';
+ DDOPtr->Push(vr);
+ vr = DDOPtr->GetVR(0x0008, 0x0016);
+ if(vr)
+ {
+ vr1 = new VR(0x0002, 0x0002, vr->Length, TRUE);
+ memcpy(vr1->Data, vr->Data, vr->Length);
+ /* Fix: vr changed to vr1.
+ Thanx to Gunter Zeilinger & Michael Hofer [M_Hofer at gmx.net]
+ */
+ vr1->TypeCode = 'UI';
+ DDOPtr->Push(vr1);
+ }
+ vr = DDOPtr->GetVR(0x0008, 0x0018);
+ if(vr)
+ {
+ vr1 = new VR(0x0002, 0x0003, vr->Length, TRUE);
+ memcpy(vr1->Data, vr->Data, vr->Length);
+ /* Fix: vr changed to vr1.
+ Thanx to Gunter Zeilinger & Michael Hofer [M_Hofer at gmx.net]
+ */
+ vr1->TypeCode = 'UI';
+ DDOPtr->Push(vr1);
+ }
+// vr = new VR(0x0002, 0x0010, strlen(_LittleEndianUID), TRUE);
+ vr = new VR(0x0002, 0x0010, strlen(pszTransferSyntaxUID), TRUE);
+ memset(vr->Data, 0, vr->Length);
+// memcpy(vr->Data, (void*)_LittleEndianUID, strlen(_LittleEndianUID));
+ memcpy(vr->Data, (void*)pszTransferSyntaxUID, strlen(pszTransferSyntaxUID));
+ vr->TypeCode = 'UI';
+ DDOPtr->Push(vr);
+ vr = new VR(0x0002, 0x0012, strlen(_ImplementationUID), TRUE);
+ memset(vr->Data, 0, vr->Length);
+ memcpy(vr->Data, (void*)_ImplementationUID, strlen(_ImplementationUID));
+ vr->TypeCode = 'UI';
+ DDOPtr->Push(vr);
+ vr = new VR(0x0002, 0x0013, strlen(_ImplementationVersion), TRUE);
+ memset(vr->Data, 0, vr->Length);
+ memcpy(vr->Data, (void*)_ImplementationVersion, strlen(_ImplementationVersion));
+ vr->TypeCode = 'SH';
+ DDOPtr->Push(vr);
+ /* Following VR is type 3 (not obligatory), and the lib does not know
+ what AE has received the image. The code above where AAssociateRQ is
+ used to retrieve the AE does not work: this PDU is not the same as
+ the PDU that has receiced the image...
+ */
+/*
+ vr = new VR(0x0002, 0x0016, strlen(_SourceApplicationAE), TRUE);
+ memset(vr->Data, 0, vr->Length);
+ memcpy(vr->Data, (void*)_SourceApplicationAE, strlen(_SourceApplicationAE));
+ vr->TypeCode = 'AE';
+ DDOPtr->Push(vr);
+*/
+ }
+ return ( TRUE );
+ }
+
+
+BOOL
+PDU_Service :: SaveDICOMDataObject (
+ char *filename,
+ UINT Format,
+ DICOMDataObject *DDO )
+ {
+ FileBuffer IOBuffer;
+ FILE *fp;
+ char s[264];
+ char TransferSyntaxUID[256];
+ UID uid;
+ VR* pVR;
+
+ switch ( Format )
+ {
+ case ACRNEMA_VR_DUMP:
+ fp = fopen(filename, "wb");
+ if(!fp)
+ return ( FALSE );
+// Fix the TransferSyntax if there and wrong. bcb 20100706
+// This makes test compression work and does no harm on a correct file!
+ pVR = DDO->GetVR(0x0002, 0x0010);
+ if (pVR && pVR->Length && pVR->Length != 18)// Implicit always 18.
+ {
+ pVR->ReAlloc(18);
+ memcpy((char*)pVR->Data,"1.2.840.10008.1.2\0", 18);
+ }
+ ImplicitLittleEndian_ParseDCMIntoRawVR(DDO, IOBuffer);
+ IOBuffer.fp = fp;
+ IOBuffer.Buffer::Flush();
+ IOBuffer.Close();
+ return ( TRUE );
+ case DICOM_CHAPTER_10_IMPLICIT:
+ fp = fopen(filename, "wb");
+ if(!fp)
+ return ( FALSE );
+
+ MakeChapter10(DDO);
+ ImplicitLittleEndian_ParseDCMIntoRawVR(DDO, IOBuffer);
+ memset((void*)s, 0, 256);
+ strcpy(&s[128], "DICM");
+ fwrite(s, 1, 128 + 4, fp);
+ IOBuffer.fp = fp;
+ IOBuffer.Buffer::Flush();
+ IOBuffer.Close();
+ return ( TRUE );
+ case DICOM_CHAPTER_10_EXPLICIT:
+
+ fp = fopen(filename, "wb");
+ if(!fp)
+ return ( FALSE );
+
+ /* See what TransferSyntax was used */
+ pVR = DDO->GetVR(0x0002, 0x0010);
+ if (pVR && pVR->Data && (((char*)pVR->Data)[0] != 0))
+ { memset(TransferSyntaxUID, 0, 256);
+ memcpy(TransferSyntaxUID, (char*)pVR->Data, pVR->Length);
+ }
+ else
+ { /* When undefined, use implicit little endian */
+ char *p=GetTransferSyntaxUID(TSA_IMPLICIT_LITTLE_ENDIAN);
+ if (p)
+ { strcpy(TransferSyntaxUID, p);
+ free(p); // mvh 20051230: LEAK
+ }
+ else
+ { fclose(fp);
+ return FALSE;
+ }
+ }
+ MakeChapter10(DDO, TransferSyntaxUID);
+
+ Dynamic_ParseDCMIntoRawVR(DDO, IOBuffer, TSA_EXPLICIT_LITTLE_ENDIAN);
+
+ memset((void*)s, 0, 256);
+ strcpy(&s[128], "DICM");
+ fwrite(s, 1, 128 + 4, fp);
+ IOBuffer.fp = fp;
+ IOBuffer.Buffer::Flush();
+ IOBuffer.Close();
+ return ( TRUE );
+
+ }
+ return ( FALSE );
+ }
+
diff --git a/flpdu.cxx b/flpdu.cxx
new file mode 100644
index 0000000..0af7b5e
--- /dev/null
+++ b/flpdu.cxx
@@ -0,0 +1,1027 @@
+/*
+20050130 mvh Allocate 1 item longer lists to allow configuration from GUI
+20050213 mvh Fix to allow windows created file as input under linux
+20060618 mvh Added definition of _SH_DENYNO
+20090802 mvh Added DCM_ERROR_DEBUG statement to debug failed connect
+20100309 bcb Commented out unused variable (gcc4.2 Warnings)
+20100619 bcb Fix gcc4 warnings and improve speed
+20100717 mvh Merged
+*/
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+# include "dicom.hpp"
+#ifdef MAC
+extern "C" int stricmp(char *, char *);
+#endif
+#ifndef stricmp
+#ifndef WINDOWS
+#ifndef MAC
+# define stricmp strcasecmp
+#endif
+#endif
+#endif
+#ifdef WINDOWS
+# include <stdlib.h>
+#endif
+
+#ifndef _SH_DENYNO
+#define _SH_DENYNO SH_DENYNO
+#endif
+
+static BOOL
+__is_whitespace(char ch)
+{
+ switch ( ch )
+ {
+ case ' ':
+ case '\t':
+ case '\n':
+ return ( TRUE );
+ }
+ return ( FALSE );
+}
+
+# define is_whitespace(xxx) __is_whitespace(xxx)
+
+CheckedPDU_Service :: CheckedPDU_Service ( char *filename )
+#ifndef __GNUC__ // Old way
+ {
+ InitializeFrom ( filename );
+ }
+#else //Newer and a little gcc faster way.
+:SOPUIDListCount(0),
+TransferUIDListCount(0),
+ApplicationUIDListCount(0),
+RemoteAEListCount(0),
+LocalAEListCount(0),
+SOPUIDList(NULL),
+SOPUIDListNames(NULL),
+TransferUIDList(NULL),
+TransferUIDListNames(NULL),
+ApplicationUIDList(NULL),
+ApplicationUIDListNames(NULL),
+RemoteAEList(NULL),
+RemoteAEListNames(NULL),
+LocalAEList(NULL),
+LocalAEListNames(NULL)
+{ //Initialize it here, no need for an extra call
+ FILE *fp;
+ UINT Index, ArgIndex;
+ UINT SOPUIDListIndex = 0,
+ TransferUIDListIndex = 0,
+ ApplicationUIDListIndex = 0,
+ RemoteAEListIndex = 0,
+ LocalAEListIndex = 0;
+ char s[256];
+ char Arg1[64];
+ char Arg2[64];
+ char Arg3[64];
+ // char Arg4[64];
+
+ if ( ! filename )
+ return;
+
+#ifndef WINDOWS
+ fp = fopen ( filename, "r" );
+#else
+ fp = _fsopen ( filename, "r", _SH_DENYWR );
+#endif
+ if ( ! fp )
+ return;
+
+ fgets ( s, 255, fp );
+ while ( ! feof ( fp ) )
+ {
+ if ( s [ 0 ] == '#' )
+ {
+ fgets( s, 255, fp );
+ continue;
+ }
+ Index = 0;
+ ArgIndex = 0;
+ while ( is_whitespace(s[Index]) )
+ {
+ if ( ! s[Index] )
+ break;
+ ++Index;
+ }
+ if ( ! s[Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ while ( !is_whitespace(s[Index]) )
+ {
+ Arg1[ArgIndex] = s[Index];
+ if(!s[Index])
+ break;
+ ++Index;
+ ++ArgIndex;
+ }
+ Arg1[ArgIndex] = '\0';
+ if ( !s [Index] )
+ {
+ // garbled line
+ fgets ( s, 255, fp );
+ continue;
+ }
+ ArgIndex = 0;
+ while ( is_whitespace(s[Index]) )
+ {
+ if ( ! s[Index] )
+ break;
+ ++Index;
+ }
+ if ( ! s[Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ while ( !is_whitespace(s[Index]) )
+ {
+ Arg2[ArgIndex] = s[Index];
+ if(!s[Index])
+ break;
+ ++Index;
+ ++ArgIndex;
+ }
+ Arg2[ArgIndex] = '\0';
+ if ( !s [Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ ArgIndex = 0;
+ while ( is_whitespace(s[Index]) )
+ {
+ if ( ! s[Index] )
+ break;
+ ++Index;
+ }
+ if ( ! s[Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ while ( !is_whitespace(s[Index]) && s[Index]!=10 && s[Index]!=13)
+ {
+ Arg3[ArgIndex] = s[Index];
+ if(!s[Index])
+ break;
+ ++Index;
+ ++ArgIndex;
+ }
+ Arg3[ArgIndex] = '\0';
+
+ if(!stricmp(Arg3, "RemoteAE"))
+ ++RemoteAEListCount;
+ if(!stricmp(Arg3, "LocalAE"))
+ ++LocalAEListCount;
+ if(!stricmp(Arg3, "sop"))
+ ++SOPUIDListCount;
+ if(!stricmp(Arg3, "abstract"))
+ ++SOPUIDListCount;
+ if(!stricmp(Arg3, "transfer"))
+ ++TransferUIDListCount;
+ if(!stricmp(Arg3, "Application"))
+ ++ApplicationUIDListCount;
+
+ // should detect garbled / unrecognized lines
+
+ fgets ( s, 255, fp );
+ }
+ //fclose ( fp );
+
+ if ( SOPUIDListCount || TRUE )
+ {
+ SOPUIDList = new char *[SOPUIDListCount+1];
+ SOPUIDListNames = new char *[SOPUIDListCount+1];
+ }
+ if ( TransferUIDListCount || TRUE )
+ {
+ TransferUIDList = new char *[TransferUIDListCount+1];
+ TransferUIDListNames = new char *[TransferUIDListCount+1];
+ }
+ if ( ApplicationUIDListCount || TRUE)
+ {
+ ApplicationUIDList = new char *[ApplicationUIDListCount+1];
+ ApplicationUIDListNames = new char *[ApplicationUIDListCount+1];
+ }
+ if ( RemoteAEListCount || TRUE)
+ {
+ RemoteAEList = new char *[RemoteAEListCount+1];
+ RemoteAEListNames = new char *[RemoteAEListCount+1];
+ }
+ if ( LocalAEListCount || TRUE)
+ {
+ LocalAEList = new char *[LocalAEListCount+1];
+ LocalAEListNames = new char *[LocalAEListCount+1];
+ }
+
+ Index = 0;
+ while ( Index < SOPUIDListCount )
+ {
+ SOPUIDList [ Index ] = NULL;
+ SOPUIDListNames [ Index ] = NULL;
+ ++Index;
+ }
+ Index = 0;
+ while ( Index < TransferUIDListCount )
+ {
+ TransferUIDList [ Index ] = NULL;
+ TransferUIDListNames [ Index ] = NULL;
+ ++Index;
+ }
+ Index = 0;
+ while ( Index < ApplicationUIDListCount )
+ {
+ ApplicationUIDList [ Index ] = NULL;
+ ApplicationUIDListNames [ Index ] = NULL;
+ ++Index;
+ }
+ Index = 0;
+ while ( Index < RemoteAEListCount )
+ {
+ RemoteAEList [ Index ] = NULL;
+ RemoteAEListNames [ Index ] = NULL;
+ ++Index;
+ }
+ Index = 0;
+ while ( Index < LocalAEListCount )
+ {
+ LocalAEList [ Index ] = NULL;
+ LocalAEListNames [ Index] = NULL;
+ ++Index;
+ }
+
+ fseek(fp, 0, SEEK_SET);
+ // fp = fopen ( filename, "r" );
+ // if ( ! fp )
+ // return ( FALSE );
+
+ fgets ( s, 255, fp );
+ while ( ! feof ( fp ) )
+ {
+ if ( s [ 0 ] == '#' )
+ {
+ fgets( s, 255, fp );
+ continue;
+ }
+ Index = 0;
+ ArgIndex = 0;
+ while ( is_whitespace(s[Index]) )
+ {
+ if ( ! s[Index] )
+ break;
+ ++Index;
+ }
+ if ( ! s[Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ while ( !is_whitespace(s[Index]) )
+ {
+ Arg1[ArgIndex] = s[Index];
+ if(!s[Index])
+ break;
+ ++Index;
+ ++ArgIndex;
+ }
+ Arg1[ArgIndex] = '\0';
+ if ( !s [Index] )
+ {
+ // garbled line
+ fgets ( s, 255, fp );
+ continue;
+ }
+ ArgIndex = 0;
+ while ( is_whitespace(s[Index]) )
+ {
+ if ( ! s[Index] )
+ break;
+ ++Index;
+ }
+ if ( ! s[Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ while ( !is_whitespace(s[Index]) )
+ {
+ Arg2[ArgIndex] = s[Index];
+ if(!s[Index])
+ break;
+ ++Index;
+ ++ArgIndex;
+ }
+ Arg2[ArgIndex] = '\0';
+ if ( !s [Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ ArgIndex = 0;
+ while ( is_whitespace(s[Index]) )
+ {
+ if ( ! s[Index] )
+ break;
+ ++Index;
+ }
+ if ( ! s[Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ while ( !is_whitespace(s[Index]) && s[Index]!=10 && s[Index]!=13)
+ {
+ Arg3[ArgIndex] = s[Index];
+ if(!s[Index])
+ break;
+ ++Index;
+ ++ArgIndex;
+ }
+ Arg3[ArgIndex] = '\0';
+ if(!stricmp(Arg3, "RemoteAE"))
+ {
+ RemoteAEList [ RemoteAEListIndex ] =
+ new char [ strlen ( Arg2 ) + 1 ];
+ RemoteAEListNames [ RemoteAEListIndex ] =
+ new char [ strlen ( Arg1 ) + 1 ];
+ strcpy ( RemoteAEList [ RemoteAEListIndex ], Arg2 );
+ strcpy ( RemoteAEListNames [ RemoteAEListIndex ], Arg1 );
+ ++RemoteAEListIndex;
+ }
+ if(!stricmp(Arg3, "LocalAE"))
+ {
+ LocalAEList [ LocalAEListIndex ] =
+ new char [ strlen ( Arg2 ) + 1 ];
+ LocalAEListNames [ LocalAEListIndex ] =
+ new char [ strlen ( Arg1 ) + 1 ];
+ strcpy ( LocalAEList [ LocalAEListIndex ], Arg2 );
+ strcpy ( LocalAEListNames [ LocalAEListIndex ], Arg1 );
+ ++LocalAEListIndex;
+ }
+ if(!stricmp(Arg3, "sop"))
+ {
+ SOPUIDList [ SOPUIDListIndex ] =
+ new char [ strlen ( Arg2 ) + 1 ];
+ SOPUIDListNames [ SOPUIDListIndex ] =
+ new char [ strlen ( Arg1 ) + 1 ];
+ strcpy ( SOPUIDList [ SOPUIDListIndex ], Arg2 );
+ strcpy ( SOPUIDListNames [ SOPUIDListIndex ], Arg1 );
+ ++SOPUIDListIndex;
+ }
+ if(!stricmp(Arg3, "abstract"))
+ {
+ SOPUIDList [ SOPUIDListIndex ] =
+ new char [ strlen ( Arg2 ) + 1 ];
+ SOPUIDListNames [ SOPUIDListIndex ] =
+ new char [ strlen ( Arg1 ) + 1 ];
+ strcpy ( SOPUIDList [ SOPUIDListIndex ], Arg2 );
+ strcpy ( SOPUIDListNames [ SOPUIDListIndex ], Arg1 );
+ ++SOPUIDListIndex;
+ }
+ if(!stricmp(Arg3, "transfer"))
+ {
+ TransferUIDList [ TransferUIDListIndex ] =
+ new char [ strlen ( Arg2 ) + 1 ];
+ TransferUIDListNames [ TransferUIDListIndex ] =
+ new char [ strlen ( Arg1 ) + 1 ];
+ strcpy ( TransferUIDList [ TransferUIDListIndex ], Arg2 );
+ strcpy ( TransferUIDListNames [ TransferUIDListIndex ], Arg1 );
+ ++TransferUIDListIndex;
+ }
+ if(!stricmp(Arg3, "Application"))
+ {
+ ApplicationUIDList [ ApplicationUIDListIndex ] =
+ new char [ strlen ( Arg2 ) + 1 ];
+ ApplicationUIDListNames [ ApplicationUIDListIndex ] =
+ new char [ strlen ( Arg1 ) + 1 ];
+ strcpy ( ApplicationUIDList [ ApplicationUIDListIndex ], Arg2 );
+ strcpy ( ApplicationUIDListNames [ ApplicationUIDListIndex ], Arg1 );
+ ++ApplicationUIDListIndex;
+ }
+
+ // should detect garbled / unrecognized lines
+
+ fgets ( s, 255, fp );
+ }
+ fclose ( fp );
+
+ return;
+}
+#endif
+
+CheckedPDU_Service :: ~CheckedPDU_Service ()
+ {
+ ReleaseMemory ( );
+ }
+
+BOOL
+CheckedPDU_Service :: ReleaseMemory ()
+ {
+ UINT Index;
+
+ if ( SOPUIDList )
+ {
+ Index = 0;
+ while ( Index < SOPUIDListCount )
+ {
+ delete SOPUIDList [ Index ] ;
+ delete SOPUIDListNames [ Index ] ;
+ ++Index;
+ }
+ delete SOPUIDList;
+ delete SOPUIDListNames;
+ SOPUIDList = NULL;
+ SOPUIDListNames = NULL;
+ SOPUIDListCount = 0;
+ }
+
+ if ( TransferUIDList )
+ {
+ Index = 0;
+ while ( Index < TransferUIDListCount )
+ {
+ delete TransferUIDList [ Index ] ;
+ delete TransferUIDListNames [ Index ] ;
+ ++Index;
+ }
+ delete TransferUIDList;
+ delete TransferUIDListNames;
+ TransferUIDList = NULL;
+ TransferUIDListNames = NULL;
+ TransferUIDListCount = 0;
+ }
+
+ if ( ApplicationUIDList )
+ {
+ Index = 0;
+ while ( Index < ApplicationUIDListCount )
+ {
+ delete ApplicationUIDList [ Index ] ;
+ delete ApplicationUIDListNames [ Index ] ;
+ ++Index;
+ }
+ delete ApplicationUIDList;
+ delete ApplicationUIDListNames;
+ ApplicationUIDList = NULL;
+ ApplicationUIDListNames = NULL;
+ ApplicationUIDListCount = 0;
+ }
+ if ( RemoteAEList )
+ {
+ Index = 0;
+ while ( Index < RemoteAEListCount )
+ {
+ delete RemoteAEList [ Index ] ;
+ delete RemoteAEListNames [ Index ] ;
+ ++Index;
+ }
+ delete RemoteAEList;
+ delete RemoteAEListNames;
+ RemoteAEList = NULL;
+ RemoteAEListNames = NULL;
+ RemoteAEListCount = 0;
+ }
+ if ( LocalAEList )
+ {
+ Index = 0;
+ while ( Index < LocalAEListCount )
+ {
+ delete LocalAEList [ Index ] ;
+ delete LocalAEListNames [ Index ] ;
+ ++Index;
+ }
+ delete LocalAEList;
+ delete LocalAEListNames;
+ LocalAEList = NULL;
+ LocalAEListNames = NULL;
+ LocalAEListCount = 0;
+ }
+ return ( TRUE );
+ }
+
+#ifndef __GNUC__ // Old way, now done above in constructor.
+BOOL
+CheckedPDU_Service :: InitializeFrom (char *filename)
+ {
+ FILE *fp;
+ UINT Index, ArgIndex;
+ UINT SOPUIDListIndex = 0,
+ TransferUIDListIndex = 0,
+ ApplicationUIDListIndex = 0,
+ RemoteAEListIndex = 0,
+ LocalAEListIndex = 0;
+ char s[256];
+ char Arg1[64];
+ char Arg2[64];
+ char Arg3[64];
+// char Arg4[64];
+
+ SOPUIDListCount = 0;
+ TransferUIDListCount = 0;
+ ApplicationUIDListCount = 0;
+ RemoteAEListCount = 0;
+ LocalAEListCount = 0;
+ SOPUIDList = NULL;
+ TransferUIDList = NULL;
+ ApplicationUIDList = NULL;
+ RemoteAEList = NULL;
+ LocalAEList = NULL;
+
+ if ( ! filename )
+ return ( FALSE );
+
+#ifndef WINDOWS
+ fp = fopen ( filename, "r" );
+#else
+ fp = _fsopen ( filename, "r", _SH_DENYWR );
+#endif
+ if ( ! fp )
+ return ( FALSE );
+
+ fgets ( s, 255, fp );
+ while ( ! feof ( fp ) )
+ {
+ if ( s [ 0 ] == '#' )
+ {
+ fgets( s, 255, fp );
+ continue;
+ }
+ Index = 0;
+ ArgIndex = 0;
+ while ( is_whitespace(s[Index]) )
+ {
+ if ( ! s[Index] )
+ break;
+ ++Index;
+ }
+ if ( ! s[Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ while ( !is_whitespace(s[Index]) )
+ {
+ Arg1[ArgIndex] = s[Index];
+ if(!s[Index])
+ break;
+ ++Index;
+ ++ArgIndex;
+ }
+ Arg1[ArgIndex] = '\0';
+ if ( !s [Index] )
+ {
+ // garbled line
+ fgets ( s, 255, fp );
+ continue;
+ }
+ ArgIndex = 0;
+ while ( is_whitespace(s[Index]) )
+ {
+ if ( ! s[Index] )
+ break;
+ ++Index;
+ }
+ if ( ! s[Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ while ( !is_whitespace(s[Index]) )
+ {
+ Arg2[ArgIndex] = s[Index];
+ if(!s[Index])
+ break;
+ ++Index;
+ ++ArgIndex;
+ }
+ Arg2[ArgIndex] = '\0';
+ if ( !s [Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ ArgIndex = 0;
+ while ( is_whitespace(s[Index]) )
+ {
+ if ( ! s[Index] )
+ break;
+ ++Index;
+ }
+ if ( ! s[Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ while ( !is_whitespace(s[Index]) && s[Index]!=10 && s[Index]!=13)
+ {
+ Arg3[ArgIndex] = s[Index];
+ if(!s[Index])
+ break;
+ ++Index;
+ ++ArgIndex;
+ }
+ Arg3[ArgIndex] = '\0';
+
+ if(!stricmp(Arg3, "RemoteAE"))
+ ++RemoteAEListCount;
+ if(!stricmp(Arg3, "LocalAE"))
+ ++LocalAEListCount;
+ if(!stricmp(Arg3, "sop"))
+ ++SOPUIDListCount;
+ if(!stricmp(Arg3, "abstract"))
+ ++SOPUIDListCount;
+ if(!stricmp(Arg3, "transfer"))
+ ++TransferUIDListCount;
+ if(!stricmp(Arg3, "Application"))
+ ++ApplicationUIDListCount;
+
+ // should detect garbled / unrecognized lines
+
+ fgets ( s, 255, fp );
+ }
+ //fclose ( fp );
+
+ if ( SOPUIDListCount || TRUE )
+ {
+ SOPUIDList = new char *[SOPUIDListCount+1];
+ SOPUIDListNames = new char *[SOPUIDListCount+1];
+ }
+ if ( TransferUIDListCount || TRUE )
+ {
+ TransferUIDList = new char *[TransferUIDListCount+1];
+ TransferUIDListNames = new char *[TransferUIDListCount+1];
+ }
+ if ( ApplicationUIDListCount || TRUE)
+ {
+ ApplicationUIDList = new char *[ApplicationUIDListCount+1];
+ ApplicationUIDListNames = new char *[ApplicationUIDListCount+1];
+ }
+ if ( RemoteAEListCount || TRUE)
+ {
+ RemoteAEList = new char *[RemoteAEListCount+1];
+ RemoteAEListNames = new char *[RemoteAEListCount+1];
+ }
+ if ( LocalAEListCount || TRUE)
+ {
+ LocalAEList = new char *[LocalAEListCount+1];
+ LocalAEListNames = new char *[LocalAEListCount+1];
+ }
+
+ Index = 0;
+ while ( Index < SOPUIDListCount )
+ {
+ SOPUIDList [ Index ] = NULL;
+ SOPUIDListNames [ Index ] = NULL;
+ ++Index;
+ }
+ Index = 0;
+ while ( Index < TransferUIDListCount )
+ {
+ TransferUIDList [ Index ] = NULL;
+ TransferUIDListNames [ Index ] = NULL;
+ ++Index;
+ }
+ Index = 0;
+ while ( Index < ApplicationUIDListCount )
+ {
+ ApplicationUIDList [ Index ] = NULL;
+ ApplicationUIDListNames [ Index ] = NULL;
+ ++Index;
+ }
+ Index = 0;
+ while ( Index < RemoteAEListCount )
+ {
+ RemoteAEList [ Index ] = NULL;
+ RemoteAEListNames [ Index ] = NULL;
+ ++Index;
+ }
+ Index = 0;
+ while ( Index < LocalAEListCount )
+ {
+ LocalAEList [ Index ] = NULL;
+ LocalAEListNames [ Index] = NULL;
+ ++Index;
+ }
+
+ fseek(fp, 0, SEEK_SET);
+// fp = fopen ( filename, "r" );
+// if ( ! fp )
+// return ( FALSE );
+
+ fgets ( s, 255, fp );
+ while ( ! feof ( fp ) )
+ {
+ if ( s [ 0 ] == '#' )
+ {
+ fgets( s, 255, fp );
+ continue;
+ }
+ Index = 0;
+ ArgIndex = 0;
+ while ( is_whitespace(s[Index]) )
+ {
+ if ( ! s[Index] )
+ break;
+ ++Index;
+ }
+ if ( ! s[Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ while ( !is_whitespace(s[Index]) )
+ {
+ Arg1[ArgIndex] = s[Index];
+ if(!s[Index])
+ break;
+ ++Index;
+ ++ArgIndex;
+ }
+ Arg1[ArgIndex] = '\0';
+ if ( !s [Index] )
+ {
+ // garbled line
+ fgets ( s, 255, fp );
+ continue;
+ }
+ ArgIndex = 0;
+ while ( is_whitespace(s[Index]) )
+ {
+ if ( ! s[Index] )
+ break;
+ ++Index;
+ }
+ if ( ! s[Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ while ( !is_whitespace(s[Index]) )
+ {
+ Arg2[ArgIndex] = s[Index];
+ if(!s[Index])
+ break;
+ ++Index;
+ ++ArgIndex;
+ }
+ Arg2[ArgIndex] = '\0';
+ if ( !s [Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ ArgIndex = 0;
+ while ( is_whitespace(s[Index]) )
+ {
+ if ( ! s[Index] )
+ break;
+ ++Index;
+ }
+ if ( ! s[Index] )
+ {
+ fgets ( s, 255, fp );
+ continue;
+ }
+ while ( !is_whitespace(s[Index]) && s[Index]!=10 && s[Index]!=13)
+ {
+ Arg3[ArgIndex] = s[Index];
+ if(!s[Index])
+ break;
+ ++Index;
+ ++ArgIndex;
+ }
+ Arg3[ArgIndex] = '\0';
+ if(!stricmp(Arg3, "RemoteAE"))
+ {
+ RemoteAEList [ RemoteAEListIndex ] =
+ new char [ strlen ( Arg2 ) + 1 ];
+ RemoteAEListNames [ RemoteAEListIndex ] =
+ new char [ strlen ( Arg1 ) + 1 ];
+ strcpy ( RemoteAEList [ RemoteAEListIndex ], Arg2 );
+ strcpy ( RemoteAEListNames [ RemoteAEListIndex ], Arg1 );
+ ++RemoteAEListIndex;
+ }
+ if(!stricmp(Arg3, "LocalAE"))
+ {
+ LocalAEList [ LocalAEListIndex ] =
+ new char [ strlen ( Arg2 ) + 1 ];
+ LocalAEListNames [ LocalAEListIndex ] =
+ new char [ strlen ( Arg1 ) + 1 ];
+ strcpy ( LocalAEList [ LocalAEListIndex ], Arg2 );
+ strcpy ( LocalAEListNames [ LocalAEListIndex ], Arg1 );
+ ++LocalAEListIndex;
+ }
+ if(!stricmp(Arg3, "sop"))
+ {
+ SOPUIDList [ SOPUIDListIndex ] =
+ new char [ strlen ( Arg2 ) + 1 ];
+ SOPUIDListNames [ SOPUIDListIndex ] =
+ new char [ strlen ( Arg1 ) + 1 ];
+ strcpy ( SOPUIDList [ SOPUIDListIndex ], Arg2 );
+ strcpy ( SOPUIDListNames [ SOPUIDListIndex ], Arg1 );
+ ++SOPUIDListIndex;
+ }
+ if(!stricmp(Arg3, "abstract"))
+ {
+ SOPUIDList [ SOPUIDListIndex ] =
+ new char [ strlen ( Arg2 ) + 1 ];
+ SOPUIDListNames [ SOPUIDListIndex ] =
+ new char [ strlen ( Arg1 ) + 1 ];
+ strcpy ( SOPUIDList [ SOPUIDListIndex ], Arg2 );
+ strcpy ( SOPUIDListNames [ SOPUIDListIndex ], Arg1 );
+ ++SOPUIDListIndex;
+ }
+ if(!stricmp(Arg3, "transfer"))
+ {
+ TransferUIDList [ TransferUIDListIndex ] =
+ new char [ strlen ( Arg2 ) + 1 ];
+ TransferUIDListNames [ TransferUIDListIndex ] =
+ new char [ strlen ( Arg1 ) + 1 ];
+ strcpy ( TransferUIDList [ TransferUIDListIndex ], Arg2 );
+ strcpy ( TransferUIDListNames [ TransferUIDListIndex ], Arg1 );
+ ++TransferUIDListIndex;
+ }
+ if(!stricmp(Arg3, "Application"))
+ {
+ ApplicationUIDList [ ApplicationUIDListIndex ] =
+ new char [ strlen ( Arg2 ) + 1 ];
+ ApplicationUIDListNames [ ApplicationUIDListIndex ] =
+ new char [ strlen ( Arg1 ) + 1 ];
+ strcpy ( ApplicationUIDList [ ApplicationUIDListIndex ], Arg2 );
+ strcpy ( ApplicationUIDListNames [ ApplicationUIDListIndex ], Arg1 );
+ ++ApplicationUIDListIndex;
+ }
+
+ // should detect garbled / unrecognized lines
+
+ fgets ( s, 255, fp );
+ }
+ fclose ( fp );
+
+ return ( TRUE );
+ }
+#endif
+
+BOOL
+CheckedPDU_Service :: CanYouHandleTransferSyntax (
+ TransferSyntax &TrnSyntax)
+ {
+ UINT Index;
+
+ if ( ! TransferUIDListCount )
+ return ( TRUE );
+
+ Index = 0;
+ while ( Index < TransferUIDListCount )
+ {
+
+char test[1000];
+sprintf(test, "Testing transfer: '%s' against list #%d = '%s'", (char*) TrnSyntax.TransferSyntaxName.GetBuffer(1), Index,
+(char *) UID ( TransferUIDList [ Index ]).GetBuffer(1));
+DicomError(DCM_ERROR_DEBUG, test, 0);
+
+ if ( UID ( TransferUIDList [ Index ] ) ==
+ TrnSyntax.TransferSyntaxName)
+ return ( TRUE );
+ ++Index;
+ }
+ return ( FALSE );
+ }
+
+BOOL
+CheckedPDU_Service :: ShouldIAcceptRemoteApTitle (
+ BYTE *ApTitle)
+ {
+ UINT Index;
+ char s[64];
+
+ if ( ! RemoteAEListCount )
+ return ( TRUE );
+
+ memset((void*)s, 0, 32);
+ memcpy((void*)s, (void*)ApTitle, 16);
+ Index = 0;
+ while(s[Index])
+ {
+ if(__is_whitespace(s[Index]))
+ {
+ s[Index] = '\0';
+ break;
+ }
+ ++Index;
+ }
+ Index = 0;
+ while ( Index < RemoteAEListCount )
+ {
+ if ( !strcmp(RemoteAEList [ Index ], s))
+ return ( TRUE );
+ ++Index;
+ }
+ return ( FALSE );
+ }
+
+
+BOOL
+CheckedPDU_Service :: ShouldIAcceptLocalApTitle (
+ BYTE *ApTitle)
+ {
+ UINT Index;
+ char s[64];
+
+ if ( ! LocalAEListCount )
+ return ( TRUE );
+
+ memset((void*)s, 0, 32);
+ memcpy((void*)s, (void*)ApTitle, 16);
+ Index = 0;
+ while(s[Index])
+ {
+ if(__is_whitespace(s[Index]))
+ {
+ s[Index] = '\0';
+ break;
+ }
+ ++Index;
+ }
+ Index = 0;
+ while ( Index < LocalAEListCount )
+ {
+ if ( !strcmp(LocalAEList [ Index ], s))
+ return ( TRUE );
+ ++Index;
+ }
+ return ( FALSE );
+ }
+
+BOOL
+CheckedPDU_Service :: ShouldIAcceptApplicationContext (
+ ApplicationContext &AppContext)
+ {
+ UINT Index;
+
+ if ( ! ApplicationUIDListCount )
+ return ( TRUE );
+
+ Index = 0;
+ while ( Index < ApplicationUIDListCount )
+ {
+ if ( UID ( ApplicationUIDList [ Index ] ) ==
+ AppContext.ApplicationContextName)
+ return ( TRUE );
+ ++Index;
+ }
+ return ( FALSE );
+ }
+
+BOOL
+CheckedPDU_Service :: ShouldIAcceptAbstractSyntax (
+ AbstractSyntax &AbsSyntax)
+ {
+ UINT Index;
+
+ if ( ! SOPUIDListCount )
+ return ( TRUE );
+
+ Index = 0;
+ while ( Index < SOPUIDListCount )
+ {
+ if ( UID ( SOPUIDList [ Index ] ) ==
+ AbsSyntax.AbstractSyntaxName)
+ return ( TRUE );
+ ++Index;
+ }
+ return ( FALSE );
+ }
+
diff --git a/flpdu.hpp b/flpdu.hpp
new file mode 100644
index 0000000..a434f8d
--- /dev/null
+++ b/flpdu.hpp
@@ -0,0 +1,78 @@
+/*
+20050129 mvh Made tables public
+20080819 mvh Made CanYouHandleTransferSyntax public
+20100619 bcb Added no-copy to the CheckedPDU_Service class.
+20100713 mvh Merged
+20110118 mvh Added unchecked CheckedPDU_Service () using NULL default
+*/
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/***********************************************************************
+ *
+ * Cheked (Verified) PDU_Service Class.
+ *
+ ***********************************************************************/
+
+
+class CheckedPDU_Service :
+ public PDU_Service
+ {
+ BOOL ShouldIAcceptRemoteApTitle(BYTE *);
+ BOOL ShouldIAcceptLocalApTitle(BYTE *);
+ BOOL ShouldIAcceptApplicationContext(ApplicationContext &);
+ BOOL ShouldIAcceptAbstractSyntax(AbstractSyntax &);
+ public:
+ BOOL CanYouHandleTransferSyntax(TransferSyntax &);
+ UINT SOPUIDListCount;
+ UINT TransferUIDListCount;
+ UINT ApplicationUIDListCount;
+ UINT RemoteAEListCount;
+ UINT LocalAEListCount;
+ char **SOPUIDList;
+ char **SOPUIDListNames;
+ char **TransferUIDList;
+ char **TransferUIDListNames;
+ char **ApplicationUIDList;
+ char **ApplicationUIDListNames;
+ char **RemoteAEList;
+ char **RemoteAEListNames;
+ char **LocalAEList;
+ char **LocalAEListNames;
+ CheckedPDU_Service (char *filename = NULL);
+ ~CheckedPDU_Service ();
+ BOOL InitializeFrom ( char *filename );
+ BOOL ReleaseMemory ();
+#ifdef __GNUC__
+ private:// This will prevent it from being copied (it has pointers)
+ CheckedPDU_Service(const CheckedPDU_Service&);
+ const CheckedPDU_Service & operator = (const CheckedPDU_Service&);
+#endif
+ };
+
diff --git a/gpps.cpp b/gpps.cpp
new file mode 100644
index 0000000..8638b26
--- /dev/null
+++ b/gpps.cpp
@@ -0,0 +1,362 @@
+// GetPrivateProfileString() -- approximate implementation of
+// Windows NT System Services version of GetPrivateProfileString()
+// probably doesn't handle the NULL key for section name or value key
+// correctly also, doesn't provide Microsoft backwards compatability
+// wrt TAB characters in the value string -- Microsoft terminates value
+// at the first TAB, but I couldn't discover what the behavior should
+// be regarding TABS in quoted strings so, I treat tabs like any other
+// characters -- NO comments following value string separated by a TAB
+// are allowed (that is an anachronism anyway)
+
+// 20040111 mvh Fixes: defaults now work, allow DOS type files, case insensitive
+// 20070330 mvh Change by Mark Pearson: also allow tabs instead of spaces around =
+// 20090620 jf Include file stuff
+// 20091231 bcb Changed char* to const char* and added blank[]="" for gcc4.2 warnings
+// 20100111 mvh Merged
+// 20100124 mvh Fix: blank item (e.g., password = ) returned default not empty
+// 20100124 mvh Added cache for ini items: accelerates server with cached disk data 7x!!!!
+// 20100124 mvh ini file is tested for newer version every second
+// 20100309 bcb Added double parentheses (gcc4.2 Warnings)
+// 20100703 mvh Merged
+// 20110320 mvh Removal of trailing blanks in value also removed one character after blank
+// 20110331 mvh Added FlushPrivateProfileStringCache
+// 20110407 mvh Extended FlushPrivateProfileStringCache to reset timestamp
+// Fixed that was reading beyond current section
+
+int gpps=0, gppstime=0;
+
+#include <stdio.h>
+#ifdef UNIX
+#include <unistd.h>
+#endif
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <string.h>
+#include <time.h>
+#include "gpps.hpp"
+#include "dicom.hpp"
+
+#ifndef WIN32
+#define stricmp(s1, s2) strcasecmp(s1, s2) //DUCKHEAD92
+#endif
+
+#define NINICACHE 1000
+
+char IniCache[NINICACHE][64];
+char IniSections[NINICACHE][64];
+char IniValues[NINICACHE][1024];
+int IniCheckSums[NINICACHE];
+CRITICAL_SECTION IniCritical;
+int IniTop=0, IniBottom=0;
+time_t IniTm=0, lasttime=0;
+
+int into_IniCache(const char *section, const char *in, char *value)
+ {
+ int i, sum, r;
+
+ const char *p = in;
+ sum = 0;
+ while(*p) sum+=*p++;
+ p = section;
+ while(*p) sum+=*p++;
+
+ if (IniTop==0 && IniBottom==0)
+ InitializeCriticalSection(&IniCritical);
+
+ EnterCriticalSection(&IniCritical);
+
+ /* clear cache if it is empty */
+ if (IniTop==0 && IniBottom==0)
+ for (i=0; i<NINICACHE; i++)
+ IniCache[i][0]=0;
+
+ if ((IniTop+1)%NINICACHE == IniBottom)
+ IniBottom = (IniBottom+1)%NINICACHE; // delete oldest entry
+
+ strcpy(IniCache[IniTop], in);
+ strcpy(IniSections[IniTop], section);
+ strcpy(IniValues[IniTop], value);
+ IniCheckSums[IniTop] = sum;
+ r = IniTop;
+
+ IniTop = (IniTop+1)%NINICACHE;
+
+ LeaveCriticalSection(&IniCritical);
+
+ return r;
+ }
+
+int isin_IniCache(const char *section, const char *in, char *file)
+ {
+ int i, sum;
+ const char *p = in;
+ struct stat statbuf;
+
+ if (IniTop==0 && IniBottom==0) return -1;
+
+ sum = 0;
+ while(*p) sum+=*p++;
+ p = section;
+ while(*p) sum+=*p++;
+
+ EnterCriticalSection(&IniCritical);
+
+ // retest for changed ini file once per second
+ if (lasttime!=time(NULL))
+ {
+ lasttime = time(NULL);
+ if (stat(file, &statbuf) != -1)
+ if (statbuf.st_mtime != IniTm)
+ {
+ IniTop=0;
+ IniBottom=0;
+ IniTm = statbuf.st_mtime;
+ lasttime = time(NULL);
+ LeaveCriticalSection(&IniCritical);
+ return -1;
+ }
+ }
+
+ for (i=IniTop; i!=IniBottom; i=(i==0 ? NINICACHE-1 : i-1))
+ {
+ if (IniCheckSums[i] == sum)
+ if (strcmp(IniCache[i], in)==0 && strcmp(IniSections[i], section)==0)
+ {
+ LeaveCriticalSection(&IniCritical);
+ return i;
+ }
+ }
+
+ LeaveCriticalSection(&IniCritical);
+ return -1;
+ }
+
+DWORD
+MyGetPrivateProfileString(const char *theSection, // section name
+ const char *theKey, // search key name
+ const char *theDefault, // default value if not found
+ char *theReturnBuffer, // return valuse stored here
+ size_t theReturnBufferLength, // byte length of return buffer
+ char *theIniFileName) // pathname of ini file to search
+{
+ int i, t = time(NULL);
+ gpps++;
+
+ // try to find it in the cache
+ if ((i = isin_IniCache(theSection, theKey, theIniFileName))>=0)
+ { strcpy(theReturnBuffer, IniValues[i]);
+ gppstime += time(NULL)-t;
+ return strlen(theReturnBuffer);
+ }
+
+ FILE *aFile = theIniFileName ? fopen(theIniFileName, "r") : NULL;
+ size_t aLength = (theDefault == NULL) ? 0 : strlen(theDefault);
+ BOOL matched = FALSE;
+
+ if(theReturnBufferLength == 0 || theReturnBuffer == NULL)
+ {
+ if(aFile)
+ {
+ fclose(aFile);
+ }
+ return 0;
+ }
+
+ if(aFile == NULL)
+ {
+ // no ini file specified, return the default
+
+ ++aLength; // room for NULL char
+ aLength = theReturnBufferLength < aLength ?
+ theReturnBufferLength : aLength;
+ strncpy(theReturnBuffer, theDefault, aLength);
+ theReturnBuffer[aLength - 1] = '\0';
+ return aLength - 1;
+ }
+
+ char aLine[2048];
+ char *aValue;
+ char *aString;
+ char blank[] = "";
+ size_t aLineLength;
+ size_t aReturnLength = 0;
+ BOOL aSectionFound = FALSE;
+
+ while(fgets(aLine, sizeof(aLine), aFile) != NULL)
+ {
+ aLineLength = strlen(aLine);
+ // strip final '\n'
+ if(aLineLength > 0 && aLine[aLineLength - 1] == '\n')
+ {
+ aLine[aLineLength - 1] = '\0';
+ aLineLength--;
+ }
+ // strip final '\r'
+ if(aLineLength > 0 && aLine[aLineLength - 1] == '\r')
+ {
+ aLine[aLineLength - 1] = '\0';
+ aLineLength--;
+ }
+ switch(*aLine)
+ {
+ case ' ': // blank line
+ case ';': // comment line
+ continue;
+ break;
+
+ case '[': // section marker
+
+ if((aString = strchr(aLine, ']')))
+ {
+ *aString = '\0';
+
+ // accept as matched if NULL key or exact match
+
+ if(!theSection || !stricmp(aLine + 1, theSection))
+ {
+ aSectionFound = TRUE;
+ }
+ else if (theSection && stricmp(aLine + 1, theSection))
+ {
+ aSectionFound = FALSE;
+ }
+ }
+
+ break;
+
+ default:
+
+ // try to match value keys if in proper section
+
+ if(aSectionFound)
+ {
+ // try to match requested key
+
+ if((aString = aValue = strchr(aLine, '=')))
+ {
+ *aValue = '\0';
+ ++aValue;
+
+ // strip leading blanks in value field
+
+ while((*aValue == ' ' || *aValue == '\t') && aValue < aLine + sizeof(aLine))
+ {
+ *aValue++ = '\0';
+ }
+ if(aValue >= aLine + sizeof(aLine))
+ {
+ aValue = blank;
+ }
+ }
+ else
+ {
+ aValue = blank;
+ }
+
+ // strip trailing blanks from key
+
+ if(aString)
+ {
+ while(--aString >= aLine && (*aString == ' ' || *aString == '\t'))
+ {
+ *aString = '\0';
+ }
+ }
+
+ // see if key is matched
+
+ if(theKey == NULL || !stricmp(theKey, aLine))
+ {
+ // matched -- first, terminate value part
+ matched = TRUE;
+ aLineLength = strlen(aValue);
+
+ // remove trailing blanks from aValue if any
+
+ aString = aValue + aLineLength;
+
+ while(--aString > aValue && (*aString == ' ' || *aString == '\t'))
+ {
+ *aString = '\0';
+ --aLineLength;
+ }
+
+ // unquote value if quoted
+
+ if(aLineLength >= 2 && aValue[0] == '"' &&
+ aValue[aLineLength - 1] == '"')
+ {
+ // string quoted with double quotes
+
+ aValue[aLineLength - 1] = '\0';
+ ++aValue;
+ aLineLength -= 2;
+ }
+ else
+ {
+ // single quotes allowed also...
+
+ if(aLineLength >= 2 && aValue[0] == '\'' &&
+ aValue[aLineLength - 1] == '\'')
+ {
+ aValue[aLineLength - 1] = '\0';
+ ++aValue;
+ aLineLength -= 2;
+ }
+ }
+
+ // compute maximum length copyable
+
+ aLineLength = (aLineLength <
+ theReturnBufferLength - aReturnLength) ? aLineLength :
+ theReturnBufferLength - aReturnLength;
+
+ // do the copy to return buffer
+
+ if(aLineLength>=0)
+ {
+ strncpy(&theReturnBuffer[aReturnLength],
+ aValue, aLineLength);
+ aReturnLength += aLineLength;
+ if(aReturnLength < theReturnBufferLength)
+ {
+ theReturnBuffer[aReturnLength] = '\0';
+ ++aReturnLength;
+
+ }
+ }
+ }
+ }
+
+ break;
+ }
+ }
+
+ if(aFile)
+ {
+ fclose(aFile);
+ }
+
+ if (aReturnLength==0 && !matched)
+ {
+ ++aLength; // room for NULL char
+ aLength = theReturnBufferLength < aLength ?
+ theReturnBufferLength : aLength;
+ strncpy(theReturnBuffer, theDefault, aLength);
+ theReturnBuffer[aLength - 1] = '\0';
+ // store into cache
+ into_IniCache(theSection, theKey, theReturnBuffer);
+ gppstime += time(NULL)-t;
+ return aLength - 1;
+ }
+
+ // store into cache
+ into_IniCache(theSection, theKey, theReturnBuffer);
+ gppstime += time(NULL)-t;
+ return aReturnLength > 0 ? aReturnLength - 1 : 0;
+}
+
+void FlushPrivateProfileStringCache(void)
+{ lasttime = 0;
+ IniTm = 0;
+}
diff --git a/gpps.hpp b/gpps.hpp
new file mode 100644
index 0000000..4151bca
--- /dev/null
+++ b/gpps.hpp
@@ -0,0 +1,27 @@
+//20091231 bcb Changed char* to const char* for gcc4.2 warnings
+//20100111 mvh Merged
+//20100124 mvh Renamed to MyGetPrivateProfileString used for windows and linux
+//20110331 mvh Added FlushPrivateProfileStringCache
+
+// MyGetPrivateProfileString: much faster version than GetPrivateProfileString
+
+#ifndef GPPS_HPP
+#define GPPS_HPP
+#ifdef UNIX
+#include <sys/types.h>
+#include "wintypes.hpp"
+#else
+#include "windows.h"
+#endif
+
+DWORD
+MyGetPrivateProfileString(const char *theSection, // section name
+ const char *theKey, // search key name
+ const char *theDefault, // default value if not found
+ char *theReturnBuffer, // return valuse stored here
+ size_t theBufferLength, // byte length of return buffer
+ char *theIniFileName); // pathname of ini file to search
+
+void FlushPrivateProfileStringCache(void);
+
+#endif
diff --git a/jasper-1.900.1-6ct/COPYRIGHT b/jasper-1.900.1-6ct/COPYRIGHT
new file mode 100644
index 0000000..db023aa
--- /dev/null
+++ b/jasper-1.900.1-6ct/COPYRIGHT
@@ -0,0 +1,2 @@
+The copyright information for the JasPer software accompanies the software
+license, and can be found in the file named "LICENSE".
diff --git a/jasper-1.900.1-6ct/ChangeLog b/jasper-1.900.1-6ct/ChangeLog
new file mode 100644
index 0000000..e69de29
diff --git a/jasper-1.900.1-6ct/INSTALL b/jasper-1.900.1-6ct/INSTALL
new file mode 100644
index 0000000..857e21a
--- /dev/null
+++ b/jasper-1.900.1-6ct/INSTALL
@@ -0,0 +1,3 @@
+Detailed instructions on how to build and install the JasPer software
+can be found in the JasPer Software Reference Manual which is located
+in the doc directory. (See the section titled "Building the Software".)
diff --git a/jasper-1.900.1-6ct/LICENSE b/jasper-1.900.1-6ct/LICENSE
new file mode 100644
index 0000000..f817ef4
--- /dev/null
+++ b/jasper-1.900.1-6ct/LICENSE
@@ -0,0 +1,51 @@
+JasPer License Version 2.0
+
+Copyright (c) 2001-2006 Michael David Adams
+Copyright (c) 1999-2000 Image Power, Inc.
+Copyright (c) 1999-2000 The University of British Columbia
+
+All rights reserved.
+
+Permission is hereby granted, free of charge, to any person (the
+"User") obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge,
+publish, distribute, and/or sell copies of the Software, and to permit
+persons to whom the Software is furnished to do so, subject to the
+following conditions:
+
+1. The above copyright notices and this permission notice (which
+includes the disclaimer below) shall be included in all copies or
+substantial portions of the Software.
+
+2. The name of a copyright holder shall not be used to endorse or
+promote products derived from the Software without specific prior
+written permission.
+
+THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+"AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+
diff --git a/jasper-1.900.1-6ct/Makefile.am b/jasper-1.900.1-6ct/Makefile.am
new file mode 100644
index 0000000..344987b
--- /dev/null
+++ b/jasper-1.900.1-6ct/Makefile.am
@@ -0,0 +1,91 @@
+# Copyright (c) 2001-2003 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+AUTOMAKE_OPTIONS = foreign dist-zip dist-tarZ
+
+EXTRA_DIST = README INSTALL COPYRIGHT LICENSE NEWS ChangeLog data doc \
+ jasper.spec.in jasper.spec acaux
+
+# Note: We need to put the derived file "jasper.spec" in the distribution
+# in order to facilitate RPM building.
+
+SUBDIRS = src
+
+rpm: dist
+ for i in BUILD RPMS SRPMS SOURCES SPECS; do \
+ j=$$PWD/RPMTOP/$$i; \
+ if ! -d $$j; then \
+ mkdir -p $$j || exit 1; \
+ fi \
+ done
+ rpmbuild --rmsource --define "_topdir $$PWD/RPMTOP" \
+ -ta $(PACKAGE)-$(JAS_VERSION).tar.gz
+ rm -rf $$PWD/RPMTOP/BUILD/$(PACKAGE)-$(JAS_VERSION)
+
+# We need to ensure that any Subversion directories in the extra directories
+# are removed before the distribution archive is made.
+dist-hook:
+ for i in $(EXTRA_DIST); do \
+ if test -d $$i; then \
+ j=`find $(distdir)/$$i -name .svn`; \
+ if test -n "$$j"; then \
+ rm -rf $$j; \
+ fi; \
+ fi; \
+ done
+
diff --git a/jasper-1.900.1-6ct/Makefile.in b/jasper-1.900.1-6ct/Makefile.in
new file mode 100644
index 0000000..a3e560d
--- /dev/null
+++ b/jasper-1.900.1-6ct/Makefile.in
@@ -0,0 +1,711 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2003 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = .
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+DIST_COMMON = README $(am__configure_deps) $(srcdir)/Makefile.am \
+ $(srcdir)/Makefile.in $(srcdir)/jasper.spec.in \
+ $(top_srcdir)/configure ChangeLog INSTALL NEWS \
+ acaux/config.guess acaux/config.sub acaux/depcomp \
+ acaux/install-sh acaux/ltmain.sh acaux/missing \
+ acaux/mkinstalldirs
+subdir = .
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \
+ configure.lineno configure.status.lineno
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES = jasper.spec
+SOURCES =
+DIST_SOURCES =
+RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
+ html-recursive info-recursive install-data-recursive \
+ install-exec-recursive install-info-recursive \
+ install-recursive installcheck-recursive installdirs-recursive \
+ pdf-recursive ps-recursive uninstall-info-recursive \
+ uninstall-recursive
+ETAGS = etags
+CTAGS = ctags
+DIST_SUBDIRS = $(SUBDIRS)
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+distdir = $(PACKAGE)-$(VERSION)
+top_distdir = $(distdir)
+am__remove_distdir = \
+ { test ! -d $(distdir) \
+ || { find $(distdir) -type d ! -perm -200 -exec chmod u+w {} ';' \
+ && rm -fr $(distdir); }; }
+DIST_ARCHIVES = $(distdir).tar.gz $(distdir).tar.Z $(distdir).zip
+GZIP_ENV = --best
+distuninstallcheck_listfiles = find . -type f -print
+distcleancheck_listfiles = find . -type f -print
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+AUTOMAKE_OPTIONS = foreign dist-zip dist-tarZ
+EXTRA_DIST = README INSTALL COPYRIGHT LICENSE NEWS ChangeLog data doc \
+ jasper.spec.in jasper.spec acaux
+
+
+# Note: We need to put the derived file "jasper.spec" in the distribution
+# in order to facilitate RPM building.
+SUBDIRS = src
+all: all-recursive
+
+.SUFFIXES:
+am--refresh:
+ @:
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ echo ' cd $(srcdir) && $(AUTOMAKE) --foreign '; \
+ cd $(srcdir) && $(AUTOMAKE) --foreign \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ echo ' $(SHELL) ./config.status'; \
+ $(SHELL) ./config.status;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ $(SHELL) ./config.status --recheck
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(srcdir) && $(AUTOCONF)
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS)
+jasper.spec: $(top_builddir)/config.status $(srcdir)/jasper.spec.in
+ cd $(top_builddir) && $(SHELL) ./config.status $@
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+
+# This directory's subdirectories are mostly independent; you can cd
+# into them and run `make' without going through this Makefile.
+# To change the values of `make' variables: instead of editing Makefiles,
+# (1) if the variable is set in `config.status', edit `config.status'
+# (which will cause the Makefiles to be regenerated when you run `make');
+# (2) otherwise, pass the desired values on the `make' command line.
+$(RECURSIVE_TARGETS):
+ @failcom='exit 1'; \
+ for f in x $$MAKEFLAGS; do \
+ case $$f in \
+ *=* | --[!k]*);; \
+ *k*) failcom='fail=yes';; \
+ esac; \
+ done; \
+ dot_seen=no; \
+ target=`echo $@ | sed s/-recursive//`; \
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ echo "Making $$target in $$subdir"; \
+ if test "$$subdir" = "."; then \
+ dot_seen=yes; \
+ local_target="$$target-am"; \
+ else \
+ local_target="$$target"; \
+ fi; \
+ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+ || eval $$failcom; \
+ done; \
+ if test "$$dot_seen" = "no"; then \
+ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
+ fi; test -z "$$fail"
+
+mostlyclean-recursive clean-recursive distclean-recursive \
+maintainer-clean-recursive:
+ @failcom='exit 1'; \
+ for f in x $$MAKEFLAGS; do \
+ case $$f in \
+ *=* | --[!k]*);; \
+ *k*) failcom='fail=yes';; \
+ esac; \
+ done; \
+ dot_seen=no; \
+ case "$@" in \
+ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
+ *) list='$(SUBDIRS)' ;; \
+ esac; \
+ rev=''; for subdir in $$list; do \
+ if test "$$subdir" = "."; then :; else \
+ rev="$$subdir $$rev"; \
+ fi; \
+ done; \
+ rev="$$rev ."; \
+ target=`echo $@ | sed s/-recursive//`; \
+ for subdir in $$rev; do \
+ echo "Making $$target in $$subdir"; \
+ if test "$$subdir" = "."; then \
+ local_target="$$target-am"; \
+ else \
+ local_target="$$target"; \
+ fi; \
+ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+ || eval $$failcom; \
+ done && test -z "$$fail"
+tags-recursive:
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
+ done
+ctags-recursive:
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
+ done
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
+ include_option=--etags-include; \
+ empty_fix=.; \
+ else \
+ include_option=--include; \
+ empty_fix=; \
+ fi; \
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ if test "$$subdir" = .; then :; else \
+ test ! -f $$subdir/TAGS || \
+ tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \
+ fi; \
+ done; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ $(am__remove_distdir)
+ mkdir $(distdir)
+ $(mkdir_p) $(distdir)/. $(distdir)/acaux
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+ list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
+ if test "$$subdir" = .; then :; else \
+ test -d "$(distdir)/$$subdir" \
+ || $(mkdir_p) "$(distdir)/$$subdir" \
+ || exit 1; \
+ distdir=`$(am__cd) $(distdir) && pwd`; \
+ top_distdir=`$(am__cd) $(top_distdir) && pwd`; \
+ (cd $$subdir && \
+ $(MAKE) $(AM_MAKEFLAGS) \
+ top_distdir="$$top_distdir" \
+ distdir="$$distdir/$$subdir" \
+ distdir) \
+ || exit 1; \
+ fi; \
+ done
+ $(MAKE) $(AM_MAKEFLAGS) \
+ top_distdir="$(top_distdir)" distdir="$(distdir)" \
+ dist-hook
+ -find $(distdir) -type d ! -perm -777 -exec chmod a+rwx {} \; -o \
+ ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \
+ ! -type d ! -perm -400 -exec chmod a+r {} \; -o \
+ ! -type d ! -perm -444 -exec $(SHELL) $(install_sh) -c -m a+r {} {} \; \
+ || chmod -R a+r $(distdir)
+dist-gzip: distdir
+ tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz
+ $(am__remove_distdir)
+
+dist-bzip2: distdir
+ tardir=$(distdir) && $(am__tar) | bzip2 -9 -c >$(distdir).tar.bz2
+ $(am__remove_distdir)
+dist-tarZ: distdir
+ tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z
+ $(am__remove_distdir)
+
+dist-shar: distdir
+ shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz
+ $(am__remove_distdir)
+dist-zip: distdir
+ -rm -f $(distdir).zip
+ zip -rq $(distdir).zip $(distdir)
+ $(am__remove_distdir)
+
+dist dist-all: distdir
+ tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz
+ tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z
+ -rm -f $(distdir).zip
+ zip -rq $(distdir).zip $(distdir)
+ $(am__remove_distdir)
+
+# This target untars the dist file and tries a VPATH configuration. Then
+# it guarantees that the distribution is self-contained by making another
+# tarfile.
+distcheck: dist
+ case '$(DIST_ARCHIVES)' in \
+ *.tar.gz*) \
+ GZIP=$(GZIP_ENV) gunzip -c $(distdir).tar.gz | $(am__untar) ;;\
+ *.tar.bz2*) \
+ bunzip2 -c $(distdir).tar.bz2 | $(am__untar) ;;\
+ *.tar.Z*) \
+ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\
+ *.shar.gz*) \
+ GZIP=$(GZIP_ENV) gunzip -c $(distdir).shar.gz | unshar ;;\
+ *.zip*) \
+ unzip $(distdir).zip ;;\
+ esac
+ chmod -R a-w $(distdir); chmod a+w $(distdir)
+ mkdir $(distdir)/_build
+ mkdir $(distdir)/_inst
+ chmod a-w $(distdir)
+ dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \
+ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \
+ && cd $(distdir)/_build \
+ && ../configure --srcdir=.. --prefix="$$dc_install_base" \
+ $(DISTCHECK_CONFIGURE_FLAGS) \
+ && $(MAKE) $(AM_MAKEFLAGS) \
+ && $(MAKE) $(AM_MAKEFLAGS) dvi \
+ && $(MAKE) $(AM_MAKEFLAGS) check \
+ && $(MAKE) $(AM_MAKEFLAGS) install \
+ && $(MAKE) $(AM_MAKEFLAGS) installcheck \
+ && $(MAKE) $(AM_MAKEFLAGS) uninstall \
+ && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \
+ distuninstallcheck \
+ && chmod -R a-w "$$dc_install_base" \
+ && ({ \
+ (cd ../.. && umask 077 && mkdir "$$dc_destdir") \
+ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \
+ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \
+ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \
+ distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \
+ } || { rm -rf "$$dc_destdir"; exit 1; }) \
+ && rm -rf "$$dc_destdir" \
+ && $(MAKE) $(AM_MAKEFLAGS) dist \
+ && rm -rf $(DIST_ARCHIVES) \
+ && $(MAKE) $(AM_MAKEFLAGS) distcleancheck
+ $(am__remove_distdir)
+ @(echo "$(distdir) archives ready for distribution: "; \
+ list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \
+ sed -e '1{h;s/./=/g;p;x;}' -e '$${p;x;}'
+distuninstallcheck:
+ @cd $(distuninstallcheck_dir) \
+ && test `$(distuninstallcheck_listfiles) | wc -l` -le 1 \
+ || { echo "ERROR: files left after uninstall:" ; \
+ if test -n "$(DESTDIR)"; then \
+ echo " (check DESTDIR support)"; \
+ fi ; \
+ $(distuninstallcheck_listfiles) ; \
+ exit 1; } >&2
+distcleancheck: distclean
+ @if test '$(srcdir)' = . ; then \
+ echo "ERROR: distcleancheck can only run from a VPATH build" ; \
+ exit 1 ; \
+ fi
+ @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \
+ || { echo "ERROR: files left in build directory after distclean:" ; \
+ $(distcleancheck_listfiles) ; \
+ exit 1; } >&2
+check-am: all-am
+check: check-recursive
+all-am: Makefile
+installdirs: installdirs-recursive
+installdirs-am:
+install: install-recursive
+install-exec: install-exec-recursive
+install-data: install-data-recursive
+uninstall: uninstall-recursive
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-recursive
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-recursive
+
+clean-am: clean-generic clean-libtool mostlyclean-am
+
+distclean: distclean-recursive
+ -rm -f $(am__CONFIG_DISTCLEAN_FILES)
+ -rm -f Makefile
+distclean-am: clean-am distclean-generic distclean-libtool \
+ distclean-tags
+
+dvi: dvi-recursive
+
+dvi-am:
+
+html: html-recursive
+
+info: info-recursive
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-recursive
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-recursive
+ -rm -f $(am__CONFIG_DISTCLEAN_FILES)
+ -rm -rf $(top_srcdir)/autom4te.cache
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-recursive
+
+mostlyclean-am: mostlyclean-generic mostlyclean-libtool
+
+pdf: pdf-recursive
+
+pdf-am:
+
+ps: ps-recursive
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+uninstall-info: uninstall-info-recursive
+
+.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am am--refresh check \
+ check-am clean clean-generic clean-libtool clean-recursive \
+ ctags ctags-recursive dist dist-all dist-bzip2 dist-gzip \
+ dist-hook dist-shar dist-tarZ dist-zip distcheck distclean \
+ distclean-generic distclean-libtool distclean-recursive \
+ distclean-tags distcleancheck distdir distuninstallcheck dvi \
+ dvi-am html html-am info info-am install install-am \
+ install-data install-data-am install-exec install-exec-am \
+ install-info install-info-am install-man install-strip \
+ installcheck installcheck-am installdirs installdirs-am \
+ maintainer-clean maintainer-clean-generic \
+ maintainer-clean-recursive mostlyclean mostlyclean-generic \
+ mostlyclean-libtool mostlyclean-recursive pdf pdf-am ps ps-am \
+ tags tags-recursive uninstall uninstall-am uninstall-info-am
+
+
+rpm: dist
+ for i in BUILD RPMS SRPMS SOURCES SPECS; do \
+ j=$$PWD/RPMTOP/$$i; \
+ if ! -d $$j; then \
+ mkdir -p $$j || exit 1; \
+ fi \
+ done
+ rpmbuild --rmsource --define "_topdir $$PWD/RPMTOP" \
+ -ta $(PACKAGE)-$(JAS_VERSION).tar.gz
+ rm -rf $$PWD/RPMTOP/BUILD/$(PACKAGE)-$(JAS_VERSION)
+
+# We need to ensure that any Subversion directories in the extra directories
+# are removed before the distribution archive is made.
+dist-hook:
+ for i in $(EXTRA_DIST); do \
+ if test -d $$i; then \
+ j=`find $(distdir)/$$i -name .svn`; \
+ if test -n "$$j"; then \
+ rm -rf $$j; \
+ fi; \
+ fi; \
+ done
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/NEWS b/jasper-1.900.1-6ct/NEWS
new file mode 100644
index 0000000..25e1fa9
--- /dev/null
+++ b/jasper-1.900.1-6ct/NEWS
@@ -0,0 +1,19 @@
+Dear JasPer Users:
+
+I am pleased to announce the availability of JasPer version 1.900.1.
+
+This release fixes some build problems as well as
+a multiply-defined symbol problem in jpc_qmfb.h.
+
+The new JasPer release is available from the JasPer Project Home Page
+(i.e., http://www.ece.uvic.ca/~mdadams/jasper) and the JPEG web site
+(i.e., http://www.jpeg.org/software).
+
+Regards,
+Michael
+
+---
+Michael Adams, Assistant Professor
+Dept. of Elec. and Comp. Engineering, University of Victoria
+P.O. Box 3055 STN CSC, Victoria, BC, V8W 3P6, CANADA
+E-mail: mdadams at ece.uvic.ca, Web: www.ece.uvic.ca/~mdadams
diff --git a/jasper-1.900.1-6ct/README b/jasper-1.900.1-6ct/README
new file mode 100644
index 0000000..88fd2f1
--- /dev/null
+++ b/jasper-1.900.1-6ct/README
@@ -0,0 +1,22 @@
+JasPer Readme
+*************
+
+This is the source code distribution for JasPer. JasPer is a collection
+of software (i.e., a library and application programs) for the coding
+and manipulation of images. This software can handle image data in a
+variety of formats. One such format supported by JasPer is the JPEG-2000
+format defined in ISO/IEC 15444-1.
+
+The complete licensing terms for the JasPer software can be found in
+the file named "LICENSE" in the top level directory of this software
+distribution. Any use of this software contrary to the terms of the
+license is strictly prohibited. The changes made to the software
+since the last release are described in the file "NEWS". Detailed
+documentation on the JasPer software can be found in the JasPer Software
+Reference Manual. This manual is located in the "doc" directory, and
+includes useful information such as: 1) how to build, install, and use
+the software, 2) how to submit report bugs, and 3) where to find
+additional information about the software.
+
+Enjoy! :)
+
diff --git a/jasper-1.900.1-6ct/acaux/config.guess b/jasper-1.900.1-6ct/acaux/config.guess
new file mode 100644
index 0000000..2fc3acc
--- /dev/null
+++ b/jasper-1.900.1-6ct/acaux/config.guess
@@ -0,0 +1,1411 @@
+#! /bin/sh
+# Attempt to guess a canonical system name.
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+# 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
+
+timestamp='2003-06-17'
+
+# This file 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 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, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# Originally written by Per Bothner <per at bothner.com>.
+# Please send patches to <config-patches at gnu.org>. Submit a context
+# diff and a properly formatted ChangeLog entry.
+#
+# This script attempts to guess a canonical system name similar to
+# config.sub. If it succeeds, it prints the system name on stdout, and
+# exits with 0. Otherwise, it exits with 1.
+#
+# The plan is that this can be called by configure scripts if you
+# don't specify an explicit build system type.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION]
+
+Output the configuration name of the system \`$me' is run on.
+
+Operation modes:
+ -h, --help print this help, then exit
+ -t, --time-stamp print date of last modification, then exit
+ -v, --version print version number, then exit
+
+Report bugs and patches to <config-patches at gnu.org>."
+
+version="\
+GNU config.guess ($timestamp)
+
+Originally written by Per Bothner.
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
+Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions. There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+ case $1 in
+ --time-stamp | --time* | -t )
+ echo "$timestamp" ; exit 0 ;;
+ --version | -v )
+ echo "$version" ; exit 0 ;;
+ --help | --h* | -h )
+ echo "$usage"; exit 0 ;;
+ -- ) # Stop option processing
+ shift; break ;;
+ - ) # Use stdin as input.
+ break ;;
+ -* )
+ echo "$me: invalid option $1$help" >&2
+ exit 1 ;;
+ * )
+ break ;;
+ esac
+done
+
+if test $# != 0; then
+ echo "$me: too many arguments$help" >&2
+ exit 1
+fi
+
+trap 'exit 1' 1 2 15
+
+# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
+# compiler to aid in system detection is discouraged as it requires
+# temporary files to be created and, as you can see below, it is a
+# headache to deal with in a portable fashion.
+
+# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
+# use `HOST_CC' if defined, but it is deprecated.
+
+# Portable tmp directory creation inspired by the Autoconf team.
+
+set_cc_for_build='
+trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
+trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
+: ${TMPDIR=/tmp} ;
+ { tmp=`(umask 077 && mktemp -d -q "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
+ { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
+ { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
+ { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
+dummy=$tmp/dummy ;
+tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
+case $CC_FOR_BUILD,$HOST_CC,$CC in
+ ,,) echo "int x;" > $dummy.c ;
+ for c in cc gcc c89 c99 ; do
+ if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
+ CC_FOR_BUILD="$c"; break ;
+ fi ;
+ done ;
+ if test x"$CC_FOR_BUILD" = x ; then
+ CC_FOR_BUILD=no_compiler_found ;
+ fi
+ ;;
+ ,,*) CC_FOR_BUILD=$CC ;;
+ ,*,*) CC_FOR_BUILD=$HOST_CC ;;
+esac ;'
+
+# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
+# (ghazi at noc.rutgers.edu 1994-08-24)
+if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
+ PATH=$PATH:/.attbin ; export PATH
+fi
+
+UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
+UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
+UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown
+UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
+
+## for Red Hat Linux
+if test -f /etc/redhat-release ; then
+ VENDOR=redhat ;
+else
+ VENDOR= ;
+fi
+
+# Note: order is significant - the case branches are not exclusive.
+
+case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
+ *:NetBSD:*:*)
+ # NetBSD (nbsd) targets should (where applicable) match one or
+ # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*,
+ # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently
+ # switched to ELF, *-*-netbsd* would select the old
+ # object file format. This provides both forward
+ # compatibility and a consistent mechanism for selecting the
+ # object file format.
+ #
+ # Note: NetBSD doesn't particularly care about the vendor
+ # portion of the name. We always set it to "unknown".
+ sysctl="sysctl -n hw.machine_arch"
+ UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
+ /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
+ case "${UNAME_MACHINE_ARCH}" in
+ armeb) machine=armeb-unknown ;;
+ arm*) machine=arm-unknown ;;
+ sh3el) machine=shl-unknown ;;
+ sh3eb) machine=sh-unknown ;;
+ *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
+ esac
+ # The Operating System including object format, if it has switched
+ # to ELF recently, or will in the future.
+ case "${UNAME_MACHINE_ARCH}" in
+ arm*|i386|m68k|ns32k|sh3*|sparc|vax)
+ eval $set_cc_for_build
+ if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
+ | grep __ELF__ >/dev/null
+ then
+ # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
+ # Return netbsd for either. FIX?
+ os=netbsd
+ else
+ os=netbsdelf
+ fi
+ ;;
+ *)
+ os=netbsd
+ ;;
+ esac
+ # The OS release
+ # Debian GNU/NetBSD machines have a different userland, and
+ # thus, need a distinct triplet. However, they do not need
+ # kernel version information, so it can be replaced with a
+ # suitable tag, in the style of linux-gnu.
+ case "${UNAME_VERSION}" in
+ Debian*)
+ release='-gnu'
+ ;;
+ *)
+ release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+ ;;
+ esac
+ # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
+ # contains redundant information, the shorter form:
+ # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
+ echo "${machine}-${os}${release}"
+ exit 0 ;;
+ amiga:OpenBSD:*:*)
+ echo m68k-unknown-openbsd${UNAME_RELEASE}
+ exit 0 ;;
+ arc:OpenBSD:*:*)
+ echo mipsel-unknown-openbsd${UNAME_RELEASE}
+ exit 0 ;;
+ hp300:OpenBSD:*:*)
+ echo m68k-unknown-openbsd${UNAME_RELEASE}
+ exit 0 ;;
+ mac68k:OpenBSD:*:*)
+ echo m68k-unknown-openbsd${UNAME_RELEASE}
+ exit 0 ;;
+ macppc:OpenBSD:*:*)
+ echo powerpc-unknown-openbsd${UNAME_RELEASE}
+ exit 0 ;;
+ mvme68k:OpenBSD:*:*)
+ echo m68k-unknown-openbsd${UNAME_RELEASE}
+ exit 0 ;;
+ mvme88k:OpenBSD:*:*)
+ echo m88k-unknown-openbsd${UNAME_RELEASE}
+ exit 0 ;;
+ mvmeppc:OpenBSD:*:*)
+ echo powerpc-unknown-openbsd${UNAME_RELEASE}
+ exit 0 ;;
+ pmax:OpenBSD:*:*)
+ echo mipsel-unknown-openbsd${UNAME_RELEASE}
+ exit 0 ;;
+ sgi:OpenBSD:*:*)
+ echo mipseb-unknown-openbsd${UNAME_RELEASE}
+ exit 0 ;;
+ sun3:OpenBSD:*:*)
+ echo m68k-unknown-openbsd${UNAME_RELEASE}
+ exit 0 ;;
+ wgrisc:OpenBSD:*:*)
+ echo mipsel-unknown-openbsd${UNAME_RELEASE}
+ exit 0 ;;
+ *:OpenBSD:*:*)
+ echo ${UNAME_MACHINE}-unknown-openbsd${UNAME_RELEASE}
+ exit 0 ;;
+ alpha:OSF1:*:*)
+ if test $UNAME_RELEASE = "V4.0"; then
+ UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
+ fi
+ # According to Compaq, /usr/sbin/psrinfo has been available on
+ # OSF/1 and Tru64 systems produced since 1995. I hope that
+ # covers most systems running today. This code pipes the CPU
+ # types through head -n 1, so we only detect the type of CPU 0.
+ ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1`
+ case "$ALPHA_CPU_TYPE" in
+ "EV4 (21064)")
+ UNAME_MACHINE="alpha" ;;
+ "EV4.5 (21064)")
+ UNAME_MACHINE="alpha" ;;
+ "LCA4 (21066/21068)")
+ UNAME_MACHINE="alpha" ;;
+ "EV5 (21164)")
+ UNAME_MACHINE="alphaev5" ;;
+ "EV5.6 (21164A)")
+ UNAME_MACHINE="alphaev56" ;;
+ "EV5.6 (21164PC)")
+ UNAME_MACHINE="alphapca56" ;;
+ "EV5.7 (21164PC)")
+ UNAME_MACHINE="alphapca57" ;;
+ "EV6 (21264)")
+ UNAME_MACHINE="alphaev6" ;;
+ "EV6.7 (21264A)")
+ UNAME_MACHINE="alphaev67" ;;
+ "EV6.8CB (21264C)")
+ UNAME_MACHINE="alphaev68" ;;
+ "EV6.8AL (21264B)")
+ UNAME_MACHINE="alphaev68" ;;
+ "EV6.8CX (21264D)")
+ UNAME_MACHINE="alphaev68" ;;
+ "EV6.9A (21264/EV69A)")
+ UNAME_MACHINE="alphaev69" ;;
+ "EV7 (21364)")
+ UNAME_MACHINE="alphaev7" ;;
+ "EV7.9 (21364A)")
+ UNAME_MACHINE="alphaev79" ;;
+ esac
+ # A Vn.n version is a released version.
+ # A Tn.n version is a released field test version.
+ # A Xn.n version is an unreleased experimental baselevel.
+ # 1.2 uses "1.2" for uname -r.
+ echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[VTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+ exit 0 ;;
+ Alpha*:OpenVMS:*:*)
+ echo alpha-hp-vms
+ exit 0 ;;
+ Alpha\ *:Windows_NT*:*)
+ # How do we know it's Interix rather than the generic POSIX subsystem?
+ # Should we change UNAME_MACHINE based on the output of uname instead
+ # of the specific Alpha model?
+ echo alpha-pc-interix
+ exit 0 ;;
+ 21064:Windows_NT:50:3)
+ echo alpha-dec-winnt3.5
+ exit 0 ;;
+ Amiga*:UNIX_System_V:4.0:*)
+ echo m68k-unknown-sysv4
+ exit 0;;
+ *:[Aa]miga[Oo][Ss]:*:*)
+ echo ${UNAME_MACHINE}-unknown-amigaos
+ exit 0 ;;
+ *:[Mm]orph[Oo][Ss]:*:*)
+ echo ${UNAME_MACHINE}-unknown-morphos
+ exit 0 ;;
+ *:OS/390:*:*)
+ echo i370-ibm-openedition
+ exit 0 ;;
+ arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
+ echo arm-acorn-riscix${UNAME_RELEASE}
+ exit 0;;
+ SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
+ echo hppa1.1-hitachi-hiuxmpp
+ exit 0;;
+ Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
+ # akee at wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
+ if test "`(/bin/universe) 2>/dev/null`" = att ; then
+ echo pyramid-pyramid-sysv3
+ else
+ echo pyramid-pyramid-bsd
+ fi
+ exit 0 ;;
+ NILE*:*:*:dcosx)
+ echo pyramid-pyramid-svr4
+ exit 0 ;;
+ DRS?6000:unix:4.0:6*)
+ echo sparc-icl-nx6
+ exit 0 ;;
+ DRS?6000:UNIX_SV:4.2*:7*)
+ case `/usr/bin/uname -p` in
+ sparc) echo sparc-icl-nx7 && exit 0 ;;
+ esac ;;
+ sun4H:SunOS:5.*:*)
+ echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit 0 ;;
+ sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
+ echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit 0 ;;
+ i86pc:SunOS:5.*:*)
+ echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit 0 ;;
+ sun4*:SunOS:6*:*)
+ # According to config.sub, this is the proper way to canonicalize
+ # SunOS6. Hard to guess exactly what SunOS6 will be like, but
+ # it's likely to be more like Solaris than SunOS4.
+ echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit 0 ;;
+ sun4*:SunOS:*:*)
+ case "`/usr/bin/arch -k`" in
+ Series*|S4*)
+ UNAME_RELEASE=`uname -v`
+ ;;
+ esac
+ # Japanese Language versions have a version number like `4.1.3-JL'.
+ echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
+ exit 0 ;;
+ sun3*:SunOS:*:*)
+ echo m68k-sun-sunos${UNAME_RELEASE}
+ exit 0 ;;
+ sun*:*:4.2BSD:*)
+ UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
+ test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
+ case "`/bin/arch`" in
+ sun3)
+ echo m68k-sun-sunos${UNAME_RELEASE}
+ ;;
+ sun4)
+ echo sparc-sun-sunos${UNAME_RELEASE}
+ ;;
+ esac
+ exit 0 ;;
+ aushp:SunOS:*:*)
+ echo sparc-auspex-sunos${UNAME_RELEASE}
+ exit 0 ;;
+ # The situation for MiNT is a little confusing. The machine name
+ # can be virtually everything (everything which is not
+ # "atarist" or "atariste" at least should have a processor
+ # > m68000). The system name ranges from "MiNT" over "FreeMiNT"
+ # to the lowercase version "mint" (or "freemint"). Finally
+ # the system name "TOS" denotes a system which is actually not
+ # MiNT. But MiNT is downward compatible to TOS, so this should
+ # be no problem.
+ atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
+ echo m68k-atari-mint${UNAME_RELEASE}
+ exit 0 ;;
+ atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
+ echo m68k-atari-mint${UNAME_RELEASE}
+ exit 0 ;;
+ *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
+ echo m68k-atari-mint${UNAME_RELEASE}
+ exit 0 ;;
+ milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
+ echo m68k-milan-mint${UNAME_RELEASE}
+ exit 0 ;;
+ hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
+ echo m68k-hades-mint${UNAME_RELEASE}
+ exit 0 ;;
+ *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
+ echo m68k-unknown-mint${UNAME_RELEASE}
+ exit 0 ;;
+ powerpc:machten:*:*)
+ echo powerpc-apple-machten${UNAME_RELEASE}
+ exit 0 ;;
+ RISC*:Mach:*:*)
+ echo mips-dec-mach_bsd4.3
+ exit 0 ;;
+ RISC*:ULTRIX:*:*)
+ echo mips-dec-ultrix${UNAME_RELEASE}
+ exit 0 ;;
+ VAX*:ULTRIX*:*:*)
+ echo vax-dec-ultrix${UNAME_RELEASE}
+ exit 0 ;;
+ 2020:CLIX:*:* | 2430:CLIX:*:*)
+ echo clipper-intergraph-clix${UNAME_RELEASE}
+ exit 0 ;;
+ mips:*:*:UMIPS | mips:*:*:RISCos)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+#ifdef __cplusplus
+#include <stdio.h> /* for printf() prototype */
+ int main (int argc, char *argv[]) {
+#else
+ int main (argc, argv) int argc; char *argv[]; {
+#endif
+ #if defined (host_mips) && defined (MIPSEB)
+ #if defined (SYSTYPE_SYSV)
+ printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
+ #endif
+ #if defined (SYSTYPE_SVR4)
+ printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
+ #endif
+ #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
+ printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
+ #endif
+ #endif
+ exit (-1);
+ }
+EOF
+ $CC_FOR_BUILD -o $dummy $dummy.c \
+ && $dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \
+ && exit 0
+ echo mips-mips-riscos${UNAME_RELEASE}
+ exit 0 ;;
+ Motorola:PowerMAX_OS:*:*)
+ echo powerpc-motorola-powermax
+ exit 0 ;;
+ Motorola:*:4.3:PL8-*)
+ echo powerpc-harris-powermax
+ exit 0 ;;
+ Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
+ echo powerpc-harris-powermax
+ exit 0 ;;
+ Night_Hawk:Power_UNIX:*:*)
+ echo powerpc-harris-powerunix
+ exit 0 ;;
+ m88k:CX/UX:7*:*)
+ echo m88k-harris-cxux7
+ exit 0 ;;
+ m88k:*:4*:R4*)
+ echo m88k-motorola-sysv4
+ exit 0 ;;
+ m88k:*:3*:R3*)
+ echo m88k-motorola-sysv3
+ exit 0 ;;
+ AViiON:dgux:*:*)
+ # DG/UX returns AViiON for all architectures
+ UNAME_PROCESSOR=`/usr/bin/uname -p`
+ if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
+ then
+ if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
+ [ ${TARGET_BINARY_INTERFACE}x = x ]
+ then
+ echo m88k-dg-dgux${UNAME_RELEASE}
+ else
+ echo m88k-dg-dguxbcs${UNAME_RELEASE}
+ fi
+ else
+ echo i586-dg-dgux${UNAME_RELEASE}
+ fi
+ exit 0 ;;
+ M88*:DolphinOS:*:*) # DolphinOS (SVR3)
+ echo m88k-dolphin-sysv3
+ exit 0 ;;
+ M88*:*:R3*:*)
+ # Delta 88k system running SVR3
+ echo m88k-motorola-sysv3
+ exit 0 ;;
+ XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
+ echo m88k-tektronix-sysv3
+ exit 0 ;;
+ Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
+ echo m68k-tektronix-bsd
+ exit 0 ;;
+ *:IRIX*:*:*)
+ echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
+ exit 0 ;;
+ ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
+ echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id
+ exit 0 ;; # Note that: echo "'`uname -s`'" gives 'AIX '
+ i*86:AIX:*:*)
+ echo i386-ibm-aix
+ exit 0 ;;
+ ia64:AIX:*:*)
+ if [ -x /usr/bin/oslevel ] ; then
+ IBM_REV=`/usr/bin/oslevel`
+ else
+ IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+ fi
+ echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
+ exit 0 ;;
+ *:AIX:2:3)
+ if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #include <sys/systemcfg.h>
+
+ main()
+ {
+ if (!__power_pc())
+ exit(1);
+ puts("powerpc-ibm-aix3.2.5");
+ exit(0);
+ }
+EOF
+ $CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0
+ echo rs6000-ibm-aix3.2.5
+ elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
+ echo rs6000-ibm-aix3.2.4
+ else
+ echo rs6000-ibm-aix3.2
+ fi
+ exit 0 ;;
+ *:AIX:*:[45])
+ IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
+ if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
+ IBM_ARCH=rs6000
+ else
+ IBM_ARCH=powerpc
+ fi
+ if [ -x /usr/bin/oslevel ] ; then
+ IBM_REV=`/usr/bin/oslevel`
+ else
+ IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+ fi
+ echo ${IBM_ARCH}-ibm-aix${IBM_REV}
+ exit 0 ;;
+ *:AIX:*:*)
+ echo rs6000-ibm-aix
+ exit 0 ;;
+ ibmrt:4.4BSD:*|romp-ibm:BSD:*)
+ echo romp-ibm-bsd4.4
+ exit 0 ;;
+ ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and
+ echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to
+ exit 0 ;; # report: romp-ibm BSD 4.3
+ *:BOSX:*:*)
+ echo rs6000-bull-bosx
+ exit 0 ;;
+ DPX/2?00:B.O.S.:*:*)
+ echo m68k-bull-sysv3
+ exit 0 ;;
+ 9000/[34]??:4.3bsd:1.*:*)
+ echo m68k-hp-bsd
+ exit 0 ;;
+ hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
+ echo m68k-hp-bsd4.4
+ exit 0 ;;
+ 9000/[34678]??:HP-UX:*:*)
+ HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+ case "${UNAME_MACHINE}" in
+ 9000/31? ) HP_ARCH=m68000 ;;
+ 9000/[34]?? ) HP_ARCH=m68k ;;
+ 9000/[678][0-9][0-9])
+ if [ -x /usr/bin/getconf ]; then
+ sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
+ sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
+ case "${sc_cpu_version}" in
+ 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
+ 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+ 532) # CPU_PA_RISC2_0
+ case "${sc_kernel_bits}" in
+ 32) HP_ARCH="hppa2.0n" ;;
+ 64) HP_ARCH="hppa2.0w" ;;
+ '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20
+ esac ;;
+ esac
+ fi
+ if [ "${HP_ARCH}" = "" ]; then
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+
+ #define _HPUX_SOURCE
+ #include <stdlib.h>
+ #include <unistd.h>
+
+ int main ()
+ {
+ #if defined(_SC_KERNEL_BITS)
+ long bits = sysconf(_SC_KERNEL_BITS);
+ #endif
+ long cpu = sysconf (_SC_CPU_VERSION);
+
+ switch (cpu)
+ {
+ case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
+ case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
+ case CPU_PA_RISC2_0:
+ #if defined(_SC_KERNEL_BITS)
+ switch (bits)
+ {
+ case 64: puts ("hppa2.0w"); break;
+ case 32: puts ("hppa2.0n"); break;
+ default: puts ("hppa2.0"); break;
+ } break;
+ #else /* !defined(_SC_KERNEL_BITS) */
+ puts ("hppa2.0"); break;
+ #endif
+ default: puts ("hppa1.0"); break;
+ }
+ exit (0);
+ }
+EOF
+ (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
+ test -z "$HP_ARCH" && HP_ARCH=hppa
+ fi ;;
+ esac
+ if [ ${HP_ARCH} = "hppa2.0w" ]
+ then
+ # avoid double evaluation of $set_cc_for_build
+ test -n "$CC_FOR_BUILD" || eval $set_cc_for_build
+ if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E -) | grep __LP64__ >/dev/null
+ then
+ HP_ARCH="hppa2.0w"
+ else
+ HP_ARCH="hppa64"
+ fi
+ fi
+ echo ${HP_ARCH}-hp-hpux${HPUX_REV}
+ exit 0 ;;
+ ia64:HP-UX:*:*)
+ HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+ echo ia64-hp-hpux${HPUX_REV}
+ exit 0 ;;
+ 3050*:HI-UX:*:*)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #include <unistd.h>
+ int
+ main ()
+ {
+ long cpu = sysconf (_SC_CPU_VERSION);
+ /* The order matters, because CPU_IS_HP_MC68K erroneously returns
+ true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct
+ results, however. */
+ if (CPU_IS_PA_RISC (cpu))
+ {
+ switch (cpu)
+ {
+ case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
+ case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
+ case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
+ default: puts ("hppa-hitachi-hiuxwe2"); break;
+ }
+ }
+ else if (CPU_IS_HP_MC68K (cpu))
+ puts ("m68k-hitachi-hiuxwe2");
+ else puts ("unknown-hitachi-hiuxwe2");
+ exit (0);
+ }
+EOF
+ $CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0
+ echo unknown-hitachi-hiuxwe2
+ exit 0 ;;
+ 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
+ echo hppa1.1-hp-bsd
+ exit 0 ;;
+ 9000/8??:4.3bsd:*:*)
+ echo hppa1.0-hp-bsd
+ exit 0 ;;
+ *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
+ echo hppa1.0-hp-mpeix
+ exit 0 ;;
+ hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
+ echo hppa1.1-hp-osf
+ exit 0 ;;
+ hp8??:OSF1:*:*)
+ echo hppa1.0-hp-osf
+ exit 0 ;;
+ i*86:OSF1:*:*)
+ if [ -x /usr/sbin/sysversion ] ; then
+ echo ${UNAME_MACHINE}-unknown-osf1mk
+ else
+ echo ${UNAME_MACHINE}-unknown-osf1
+ fi
+ exit 0 ;;
+ parisc*:Lites*:*:*)
+ echo hppa1.1-hp-lites
+ exit 0 ;;
+ C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
+ echo c1-convex-bsd
+ exit 0 ;;
+ C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
+ if getsysinfo -f scalar_acc
+ then echo c32-convex-bsd
+ else echo c2-convex-bsd
+ fi
+ exit 0 ;;
+ C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
+ echo c34-convex-bsd
+ exit 0 ;;
+ C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
+ echo c38-convex-bsd
+ exit 0 ;;
+ C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
+ echo c4-convex-bsd
+ exit 0 ;;
+ CRAY*Y-MP:*:*:*)
+ echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit 0 ;;
+ CRAY*[A-Z]90:*:*:*)
+ echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
+ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
+ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
+ -e 's/\.[^.]*$/.X/'
+ exit 0 ;;
+ CRAY*TS:*:*:*)
+ echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit 0 ;;
+ CRAY*T3E:*:*:*)
+ echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit 0 ;;
+ CRAY*SV1:*:*:*)
+ echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit 0 ;;
+ *:UNICOS/mp:*:*)
+ echo nv1-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit 0 ;;
+ F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
+ FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+ FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+ FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
+ echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+ exit 0 ;;
+ i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
+ echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
+ exit 0 ;;
+ sparc*:BSD/OS:*:*)
+ echo sparc-unknown-bsdi${UNAME_RELEASE}
+ exit 0 ;;
+ *:BSD/OS:*:*)
+ echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
+ exit 0 ;;
+ *:FreeBSD:*:*|*:GNU/FreeBSD:*:*)
+ # Determine whether the default compiler uses glibc.
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #include <features.h>
+ #if __GLIBC__ >= 2
+ LIBC=gnu
+ #else
+ LIBC=
+ #endif
+EOF
+ eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=`
+ echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`${LIBC:+-$LIBC}
+ exit 0 ;;
+ i*:CYGWIN*:*)
+ echo ${UNAME_MACHINE}-pc-cygwin
+ exit 0 ;;
+ i*:MINGW*:*)
+ echo ${UNAME_MACHINE}-pc-mingw32
+ exit 0 ;;
+ i*:PW*:*)
+ echo ${UNAME_MACHINE}-pc-pw32
+ exit 0 ;;
+ x86:Interix*:[34]*)
+ echo i586-pc-interix${UNAME_RELEASE}|sed -e 's/\..*//'
+ exit 0 ;;
+ [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
+ echo i${UNAME_MACHINE}-pc-mks
+ exit 0 ;;
+ i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
+ # How do we know it's Interix rather than the generic POSIX subsystem?
+ # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
+ # UNAME_MACHINE based on the output of uname instead of i386?
+ echo i586-pc-interix
+ exit 0 ;;
+ i*:UWIN*:*)
+ echo ${UNAME_MACHINE}-pc-uwin
+ exit 0 ;;
+ p*:CYGWIN*:*)
+ echo powerpcle-unknown-cygwin
+ exit 0 ;;
+ prep*:SunOS:5.*:*)
+ echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit 0 ;;
+ *:GNU:*:*)
+ echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
+ exit 0 ;;
+ i*86:Minix:*:*)
+ echo ${UNAME_MACHINE}-pc-minix
+ exit 0 ;;
+ arm*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit 0 ;;
+ cris:Linux:*:*)
+ echo cris-axis-linux-gnu
+ exit 0 ;;
+ ia64:Linux:*:*)
+ echo ${UNAME_MACHINE}-${VENDOR:-unknown}-linux-gnu
+ exit 0 ;;
+ m68*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit 0 ;;
+ mips:Linux:*:*)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #undef CPU
+ #undef mips
+ #undef mipsel
+ #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+ CPU=mipsel
+ #else
+ #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+ CPU=mips
+ #else
+ CPU=
+ #endif
+ #endif
+EOF
+ eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=`
+ test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0
+ ;;
+ mips64:Linux:*:*)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #undef CPU
+ #undef mips64
+ #undef mips64el
+ #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+ CPU=mips64el
+ #else
+ #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+ CPU=mips64
+ #else
+ CPU=
+ #endif
+ #endif
+EOF
+ eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=`
+ test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0
+ ;;
+ ppc:Linux:*:*)
+ echo powerpc-${VENDOR:-unknown}-linux-gnu
+ exit 0 ;;
+ ppc64:Linux:*:*)
+ echo powerpc64-${VENDOR:-unknown}-linux-gnu
+ exit 0 ;;
+ alpha:Linux:*:*)
+ case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
+ EV5) UNAME_MACHINE=alphaev5 ;;
+ EV56) UNAME_MACHINE=alphaev56 ;;
+ PCA56) UNAME_MACHINE=alphapca56 ;;
+ PCA57) UNAME_MACHINE=alphapca56 ;;
+ EV6) UNAME_MACHINE=alphaev6 ;;
+ EV67) UNAME_MACHINE=alphaev67 ;;
+ EV68*) UNAME_MACHINE=alphaev68 ;;
+ esac
+ objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null
+ if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
+ echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
+ exit 0 ;;
+ parisc:Linux:*:* | hppa:Linux:*:*)
+ # Look for CPU level
+ case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
+ PA7*) echo hppa1.1-unknown-linux-gnu ;;
+ PA8*) echo hppa2.0-unknown-linux-gnu ;;
+ *) echo hppa-unknown-linux-gnu ;;
+ esac
+ exit 0 ;;
+ parisc64:Linux:*:* | hppa64:Linux:*:*)
+ echo hppa64-unknown-linux-gnu
+ exit 0 ;;
+ s390:Linux:*:* | s390x:Linux:*:*)
+ echo ${UNAME_MACHINE}-${VENDOR:-ibm}-linux-gnu
+ exit 0 ;;
+ sh64*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit 0 ;;
+ sh*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit 0 ;;
+ sparc:Linux:*:* | sparc64:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit 0 ;;
+ x86_64:Linux:*:*)
+ echo x86_64-${VENDOR:-unknown}-linux-gnu
+ exit 0 ;;
+ i*86:Linux:*:*)
+ # The BFD linker knows what the default object file format is, so
+ # first see if it will tell us. cd to the root directory to prevent
+ # problems with other programs or directories called `ld' in the path.
+ # Set LC_ALL=C to ensure ld outputs messages in English.
+ ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \
+ | sed -ne '/supported targets:/!d
+ s/[ ][ ]*/ /g
+ s/.*supported targets: *//
+ s/ .*//
+ p'`
+ case "$ld_supported_targets" in
+ elf32-i386)
+ TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu"
+ ;;
+ a.out-i386-linux)
+ echo "${UNAME_MACHINE}-pc-linux-gnuaout"
+ exit 0 ;;
+ coff-i386)
+ echo "${UNAME_MACHINE}-pc-linux-gnucoff"
+ exit 0 ;;
+ "")
+ # Either a pre-BFD a.out linker (linux-gnuoldld) or
+ # one that does not give us useful --help.
+ echo "${UNAME_MACHINE}-pc-linux-gnuoldld"
+ exit 0 ;;
+ esac
+ # Determine whether the default compiler is a.out or elf
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #include <features.h>
+ #ifdef __ELF__
+ # ifdef __GLIBC__
+ # if __GLIBC__ >= 2
+ LIBC=gnu
+ # else
+ LIBC=gnulibc1
+ # endif
+ # else
+ LIBC=gnulibc1
+ # endif
+ #else
+ #ifdef __INTEL_COMPILER
+ LIBC=gnu
+ #else
+ LIBC=gnuaout
+ #endif
+ #endif
+EOF
+ eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=`
+ test x"${LIBC}" != x && echo "${UNAME_MACHINE}-${VENDOR:-pc}-linux-${LIBC}" && exit 0
+ test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0
+ ;;
+ i*86:DYNIX/ptx:4*:*)
+ # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
+ # earlier versions are messed up and put the nodename in both
+ # sysname and nodename.
+ echo i386-sequent-sysv4
+ exit 0 ;;
+ i*86:UNIX_SV:4.2MP:2.*)
+ # Unixware is an offshoot of SVR4, but it has its own version
+ # number series starting with 2...
+ # I am not positive that other SVR4 systems won't match this,
+ # I just have to hope. -- rms.
+ # Use sysv4.2uw... so that sysv4* matches it.
+ echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
+ exit 0 ;;
+ i*86:OS/2:*:*)
+ # If we were able to find `uname', then EMX Unix compatibility
+ # is probably installed.
+ echo ${UNAME_MACHINE}-pc-os2-emx
+ exit 0 ;;
+ i*86:XTS-300:*:STOP)
+ echo ${UNAME_MACHINE}-unknown-stop
+ exit 0 ;;
+ i*86:atheos:*:*)
+ echo ${UNAME_MACHINE}-unknown-atheos
+ exit 0 ;;
+ i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
+ echo i386-unknown-lynxos${UNAME_RELEASE}
+ exit 0 ;;
+ i*86:*DOS:*:*)
+ echo ${UNAME_MACHINE}-pc-msdosdjgpp
+ exit 0 ;;
+ i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
+ UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
+ if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
+ echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
+ else
+ echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
+ fi
+ exit 0 ;;
+ i*86:*:5:[78]*)
+ case `/bin/uname -X | grep "^Machine"` in
+ *486*) UNAME_MACHINE=i486 ;;
+ *Pentium) UNAME_MACHINE=i586 ;;
+ *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
+ esac
+ echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
+ exit 0 ;;
+ i*86:*:3.2:*)
+ if test -f /usr/options/cb.name; then
+ UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
+ echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
+ elif /bin/uname -X 2>/dev/null >/dev/null ; then
+ UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
+ (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
+ (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
+ && UNAME_MACHINE=i586
+ (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
+ && UNAME_MACHINE=i686
+ (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
+ && UNAME_MACHINE=i686
+ echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
+ else
+ echo ${UNAME_MACHINE}-pc-sysv32
+ fi
+ exit 0 ;;
+ pc:*:*:*)
+ # Left here for compatibility:
+ # uname -m prints for DJGPP always 'pc', but it prints nothing about
+ # the processor, so we play safe by assuming i386.
+ echo i386-pc-msdosdjgpp
+ exit 0 ;;
+ Intel:Mach:3*:*)
+ echo i386-pc-mach3
+ exit 0 ;;
+ paragon:*:*:*)
+ echo i860-intel-osf1
+ exit 0 ;;
+ i860:*:4.*:*) # i860-SVR4
+ if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
+ echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
+ else # Add other i860-SVR4 vendors below as they are discovered.
+ echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4
+ fi
+ exit 0 ;;
+ mini*:CTIX:SYS*5:*)
+ # "miniframe"
+ echo m68010-convergent-sysv
+ exit 0 ;;
+ mc68k:UNIX:SYSTEM5:3.51m)
+ echo m68k-convergent-sysv
+ exit 0 ;;
+ M680?0:D-NIX:5.3:*)
+ echo m68k-diab-dnix
+ exit 0 ;;
+ M68*:*:R3V[567]*:*)
+ test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;;
+ 3[34]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0)
+ OS_REL=''
+ test -r /etc/.relid \
+ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+ /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+ && echo i486-ncr-sysv4.3${OS_REL} && exit 0
+ /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+ && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;;
+ 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
+ /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+ && echo i486-ncr-sysv4 && exit 0 ;;
+ m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
+ echo m68k-unknown-lynxos${UNAME_RELEASE}
+ exit 0 ;;
+ mc68030:UNIX_System_V:4.*:*)
+ echo m68k-atari-sysv4
+ exit 0 ;;
+ TSUNAMI:LynxOS:2.*:*)
+ echo sparc-unknown-lynxos${UNAME_RELEASE}
+ exit 0 ;;
+ rs6000:LynxOS:2.*:*)
+ echo rs6000-unknown-lynxos${UNAME_RELEASE}
+ exit 0 ;;
+ PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*)
+ echo powerpc-unknown-lynxos${UNAME_RELEASE}
+ exit 0 ;;
+ SM[BE]S:UNIX_SV:*:*)
+ echo mips-dde-sysv${UNAME_RELEASE}
+ exit 0 ;;
+ RM*:ReliantUNIX-*:*:*)
+ echo mips-sni-sysv4
+ exit 0 ;;
+ RM*:SINIX-*:*:*)
+ echo mips-sni-sysv4
+ exit 0 ;;
+ *:SINIX-*:*:*)
+ if uname -p 2>/dev/null >/dev/null ; then
+ UNAME_MACHINE=`(uname -p) 2>/dev/null`
+ echo ${UNAME_MACHINE}-sni-sysv4
+ else
+ echo ns32k-sni-sysv
+ fi
+ exit 0 ;;
+ PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
+ # says <Richard.M.Bartel at ccMail.Census.GOV>
+ echo i586-unisys-sysv4
+ exit 0 ;;
+ *:UNIX_System_V:4*:FTX*)
+ # From Gerald Hewes <hewes at openmarket.com>.
+ # How about differentiating between stratus architectures? -djm
+ echo hppa1.1-stratus-sysv4
+ exit 0 ;;
+ *:*:*:FTX*)
+ # From seanf at swdc.stratus.com.
+ echo i860-stratus-sysv4
+ exit 0 ;;
+ *:VOS:*:*)
+ # From Paul.Green at stratus.com.
+ echo hppa1.1-stratus-vos
+ exit 0 ;;
+ mc68*:A/UX:*:*)
+ echo m68k-apple-aux${UNAME_RELEASE}
+ exit 0 ;;
+ news*:NEWS-OS:6*:*)
+ echo mips-sony-newsos6
+ exit 0 ;;
+ R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
+ if [ -d /usr/nec ]; then
+ echo mips-nec-sysv${UNAME_RELEASE}
+ else
+ echo mips-unknown-sysv${UNAME_RELEASE}
+ fi
+ exit 0 ;;
+ BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only.
+ echo powerpc-be-beos
+ exit 0 ;;
+ BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only.
+ echo powerpc-apple-beos
+ exit 0 ;;
+ BePC:BeOS:*:*) # BeOS running on Intel PC compatible.
+ echo i586-pc-beos
+ exit 0 ;;
+ SX-4:SUPER-UX:*:*)
+ echo sx4-nec-superux${UNAME_RELEASE}
+ exit 0 ;;
+ SX-5:SUPER-UX:*:*)
+ echo sx5-nec-superux${UNAME_RELEASE}
+ exit 0 ;;
+ SX-6:SUPER-UX:*:*)
+ echo sx6-nec-superux${UNAME_RELEASE}
+ exit 0 ;;
+ Power*:Rhapsody:*:*)
+ echo powerpc-apple-rhapsody${UNAME_RELEASE}
+ exit 0 ;;
+ *:Rhapsody:*:*)
+ echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
+ exit 0 ;;
+ *:Darwin:*:*)
+ case `uname -p` in
+ *86) UNAME_PROCESSOR=i686 ;;
+ powerpc) UNAME_PROCESSOR=powerpc ;;
+ esac
+ echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
+ exit 0 ;;
+ *:procnto*:*:* | *:QNX:[0123456789]*:*)
+ UNAME_PROCESSOR=`uname -p`
+ if test "$UNAME_PROCESSOR" = "x86"; then
+ UNAME_PROCESSOR=i386
+ UNAME_MACHINE=pc
+ fi
+ echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
+ exit 0 ;;
+ *:QNX:*:4*)
+ echo i386-pc-qnx
+ exit 0 ;;
+ NSR-[DGKLNPTVW]:NONSTOP_KERNEL:*:*)
+ echo nsr-tandem-nsk${UNAME_RELEASE}
+ exit 0 ;;
+ *:NonStop-UX:*:*)
+ echo mips-compaq-nonstopux
+ exit 0 ;;
+ BS2000:POSIX*:*:*)
+ echo bs2000-siemens-sysv
+ exit 0 ;;
+ DS/*:UNIX_System_V:*:*)
+ echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
+ exit 0 ;;
+ *:Plan9:*:*)
+ # "uname -m" is not consistent, so use $cputype instead. 386
+ # is converted to i386 for consistency with other x86
+ # operating systems.
+ if test "$cputype" = "386"; then
+ UNAME_MACHINE=i386
+ else
+ UNAME_MACHINE="$cputype"
+ fi
+ echo ${UNAME_MACHINE}-unknown-plan9
+ exit 0 ;;
+ *:TOPS-10:*:*)
+ echo pdp10-unknown-tops10
+ exit 0 ;;
+ *:TENEX:*:*)
+ echo pdp10-unknown-tenex
+ exit 0 ;;
+ KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
+ echo pdp10-dec-tops20
+ exit 0 ;;
+ XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
+ echo pdp10-xkl-tops20
+ exit 0 ;;
+ *:TOPS-20:*:*)
+ echo pdp10-unknown-tops20
+ exit 0 ;;
+ *:ITS:*:*)
+ echo pdp10-unknown-its
+ exit 0 ;;
+ SEI:*:*:SEIUX)
+ echo mips-sei-seiux${UNAME_RELEASE}
+ exit 0 ;;
+esac
+
+#echo '(No uname command or uname output not recognized.)' 1>&2
+#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2
+
+eval $set_cc_for_build
+cat >$dummy.c <<EOF
+#ifdef _SEQUENT_
+# include <sys/types.h>
+# include <sys/utsname.h>
+#endif
+main ()
+{
+#if defined (sony)
+#if defined (MIPSEB)
+ /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed,
+ I don't know.... */
+ printf ("mips-sony-bsd\n"); exit (0);
+#else
+#include <sys/param.h>
+ printf ("m68k-sony-newsos%s\n",
+#ifdef NEWSOS4
+ "4"
+#else
+ ""
+#endif
+ ); exit (0);
+#endif
+#endif
+
+#if defined (__arm) && defined (__acorn) && defined (__unix)
+ printf ("arm-acorn-riscix"); exit (0);
+#endif
+
+#if defined (hp300) && !defined (hpux)
+ printf ("m68k-hp-bsd\n"); exit (0);
+#endif
+
+#if defined (NeXT)
+#if !defined (__ARCHITECTURE__)
+#define __ARCHITECTURE__ "m68k"
+#endif
+ int version;
+ version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
+ if (version < 4)
+ printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
+ else
+ printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
+ exit (0);
+#endif
+
+#if defined (MULTIMAX) || defined (n16)
+#if defined (UMAXV)
+ printf ("ns32k-encore-sysv\n"); exit (0);
+#else
+#if defined (CMU)
+ printf ("ns32k-encore-mach\n"); exit (0);
+#else
+ printf ("ns32k-encore-bsd\n"); exit (0);
+#endif
+#endif
+#endif
+
+#if defined (__386BSD__)
+ printf ("i386-pc-bsd\n"); exit (0);
+#endif
+
+#if defined (sequent)
+#if defined (i386)
+ printf ("i386-sequent-dynix\n"); exit (0);
+#endif
+#if defined (ns32000)
+ printf ("ns32k-sequent-dynix\n"); exit (0);
+#endif
+#endif
+
+#if defined (_SEQUENT_)
+ struct utsname un;
+
+ uname(&un);
+
+ if (strncmp(un.version, "V2", 2) == 0) {
+ printf ("i386-sequent-ptx2\n"); exit (0);
+ }
+ if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
+ printf ("i386-sequent-ptx1\n"); exit (0);
+ }
+ printf ("i386-sequent-ptx\n"); exit (0);
+
+#endif
+
+#if defined (vax)
+# if !defined (ultrix)
+# include <sys/param.h>
+# if defined (BSD)
+# if BSD == 43
+ printf ("vax-dec-bsd4.3\n"); exit (0);
+# else
+# if BSD == 199006
+ printf ("vax-dec-bsd4.3reno\n"); exit (0);
+# else
+ printf ("vax-dec-bsd\n"); exit (0);
+# endif
+# endif
+# else
+ printf ("vax-dec-bsd\n"); exit (0);
+# endif
+# else
+ printf ("vax-dec-ultrix\n"); exit (0);
+# endif
+#endif
+
+#if defined (alliant) && defined (i860)
+ printf ("i860-alliant-bsd\n"); exit (0);
+#endif
+
+ exit (1);
+}
+EOF
+
+$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && $dummy && exit 0
+
+# Apollos put the system type in the environment.
+
+test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; }
+
+# Convex versions that predate uname can use getsysinfo(1)
+
+if [ -x /usr/convex/getsysinfo ]
+then
+ case `getsysinfo -f cpu_type` in
+ c1*)
+ echo c1-convex-bsd
+ exit 0 ;;
+ c2*)
+ if getsysinfo -f scalar_acc
+ then echo c32-convex-bsd
+ else echo c2-convex-bsd
+ fi
+ exit 0 ;;
+ c34*)
+ echo c34-convex-bsd
+ exit 0 ;;
+ c38*)
+ echo c38-convex-bsd
+ exit 0 ;;
+ c4*)
+ echo c4-convex-bsd
+ exit 0 ;;
+ esac
+fi
+
+cat >&2 <<EOF
+$0: unable to guess system type
+
+This script, last modified $timestamp, has failed to recognize
+the operating system you are using. It is advised that you
+download the most up to date version of the config scripts from
+
+ ftp://ftp.gnu.org/pub/gnu/config/
+
+If the version you run ($0) is already up to date, please
+send the following data and any information you think might be
+pertinent to <config-patches at gnu.org> in order to provide the needed
+information to handle your system.
+
+config.guess timestamp = $timestamp
+
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
+/bin/uname -X = `(/bin/uname -X) 2>/dev/null`
+
+hostinfo = `(hostinfo) 2>/dev/null`
+/bin/universe = `(/bin/universe) 2>/dev/null`
+/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null`
+/bin/arch = `(/bin/arch) 2>/dev/null`
+/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
+
+UNAME_MACHINE = ${UNAME_MACHINE}
+UNAME_RELEASE = ${UNAME_RELEASE}
+UNAME_SYSTEM = ${UNAME_SYSTEM}
+UNAME_VERSION = ${UNAME_VERSION}
+EOF
+
+exit 1
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/jasper-1.900.1-6ct/acaux/config.sub b/jasper-1.900.1-6ct/acaux/config.sub
new file mode 100644
index 0000000..6b2ff9f
--- /dev/null
+++ b/jasper-1.900.1-6ct/acaux/config.sub
@@ -0,0 +1,1500 @@
+#! /bin/sh
+# Configuration validation subroutine script.
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+# 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
+
+timestamp='2003-06-18'
+
+# This file is (in principle) common to ALL GNU software.
+# The presence of a machine in this file suggests that SOME GNU software
+# can handle that machine. It does not imply ALL GNU software can.
+#
+# This file 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
+# 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, Inc., 59 Temple Place - Suite 330,
+# Boston, MA 02111-1307, USA.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# Please send patches to <config-patches at gnu.org>. Submit a context
+# diff and a properly formatted ChangeLog entry.
+#
+# Configuration subroutine to validate and canonicalize a configuration type.
+# Supply the specified configuration type as an argument.
+# If it is invalid, we print an error message on stderr and exit with code 1.
+# Otherwise, we print the canonical config type on stdout and succeed.
+
+# This file is supposed to be the same for all GNU packages
+# and recognize all the CPU types, system types and aliases
+# that are meaningful with *any* GNU software.
+# Each package is responsible for reporting which valid configurations
+# it does not support. The user should be able to distinguish
+# a failure to support a valid configuration from a meaningless
+# configuration.
+
+# The goal of this file is to map all the various variations of a given
+# machine specification into a single specification in the form:
+# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
+# or in some cases, the newer four-part form:
+# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
+# It is wrong to echo any other type of specification.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION] CPU-MFR-OPSYS
+ $0 [OPTION] ALIAS
+
+Canonicalize a configuration name.
+
+Operation modes:
+ -h, --help print this help, then exit
+ -t, --time-stamp print date of last modification, then exit
+ -v, --version print version number, then exit
+
+Report bugs and patches to <config-patches at gnu.org>."
+
+version="\
+GNU config.sub ($timestamp)
+
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
+Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions. There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+ case $1 in
+ --time-stamp | --time* | -t )
+ echo "$timestamp" ; exit 0 ;;
+ --version | -v )
+ echo "$version" ; exit 0 ;;
+ --help | --h* | -h )
+ echo "$usage"; exit 0 ;;
+ -- ) # Stop option processing
+ shift; break ;;
+ - ) # Use stdin as input.
+ break ;;
+ -* )
+ echo "$me: invalid option $1$help"
+ exit 1 ;;
+
+ *local*)
+ # First pass through any local machine types.
+ echo $1
+ exit 0;;
+
+ * )
+ break ;;
+ esac
+done
+
+case $# in
+ 0) echo "$me: missing argument$help" >&2
+ exit 1;;
+ 1) ;;
+ *) echo "$me: too many arguments$help" >&2
+ exit 1;;
+esac
+
+# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
+# Here we must recognize all the valid KERNEL-OS combinations.
+maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
+case $maybe_os in
+ nto-qnx* | linux-gnu* | freebsd*-gnu* | netbsd*-gnu* | storm-chaos* | os2-emx* | rtmk-nova*)
+ os=-$maybe_os
+ basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
+ ;;
+ *)
+ basic_machine=`echo $1 | sed 's/-[^-]*$//'`
+ if [ $basic_machine != $1 ]
+ then os=`echo $1 | sed 's/.*-/-/'`
+ else os=; fi
+ ;;
+esac
+
+### Let's recognize common machines as not being operating systems so
+### that things like config.sub decstation-3100 work. We also
+### recognize some manufacturers as not being operating systems, so we
+### can provide default operating systems below.
+case $os in
+ -sun*os*)
+ # Prevent following clause from handling this invalid input.
+ ;;
+ -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
+ -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
+ -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
+ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
+ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
+ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
+ -apple | -axis)
+ os=
+ basic_machine=$1
+ ;;
+ -sim | -cisco | -oki | -wec | -winbond)
+ os=
+ basic_machine=$1
+ ;;
+ -scout)
+ ;;
+ -wrs)
+ os=-vxworks
+ basic_machine=$1
+ ;;
+ -chorusos*)
+ os=-chorusos
+ basic_machine=$1
+ ;;
+ -chorusrdb)
+ os=-chorusrdb
+ basic_machine=$1
+ ;;
+ -hiux*)
+ os=-hiuxwe2
+ ;;
+ -sco5)
+ os=-sco3.2v5
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco4)
+ os=-sco3.2v4
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco3.2.[4-9]*)
+ os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco3.2v[4-9]*)
+ # Don't forget version if it is 3.2v4 or newer.
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco*)
+ os=-sco3.2v2
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -udk*)
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -isc)
+ os=-isc2.2
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -clix*)
+ basic_machine=clipper-intergraph
+ ;;
+ -isc*)
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -lynx*)
+ os=-lynxos
+ ;;
+ -ptx*)
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
+ ;;
+ -windowsnt*)
+ os=`echo $os | sed -e 's/windowsnt/winnt/'`
+ ;;
+ -psos*)
+ os=-psos
+ ;;
+ -mint | -mint[0-9]*)
+ basic_machine=m68k-atari
+ os=-mint
+ ;;
+esac
+
+# Decode aliases for certain CPU-COMPANY combinations.
+case $basic_machine in
+ # Recognize the basic CPU types without company name.
+ # Some are omitted here because they have special meanings below.
+ 1750a | 580 \
+ | a29k \
+ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
+ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
+ | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \
+ | c4x | clipper \
+ | d10v | d30v | dlx | dsp16xx \
+ | fr30 | frv \
+ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
+ | i370 | i860 | i960 | ia64 \
+ | ip2k \
+ | m32r | m68000 | m68k | m88k | mcore \
+ | mips | mipsbe | mipseb | mipsel | mipsle \
+ | mips16 \
+ | mips64 | mips64el \
+ | mips64vr | mips64vrel \
+ | mips64orion | mips64orionel \
+ | mips64vr4100 | mips64vr4100el \
+ | mips64vr4300 | mips64vr4300el \
+ | mips64vr5000 | mips64vr5000el \
+ | mipsisa32 | mipsisa32el \
+ | mipsisa32r2 | mipsisa32r2el \
+ | mipsisa64 | mipsisa64el \
+ | mipsisa64sb1 | mipsisa64sb1el \
+ | mipsisa64sr71k | mipsisa64sr71kel \
+ | mipstx39 | mipstx39el \
+ | mn10200 | mn10300 \
+ | msp430 \
+ | ns16k | ns32k \
+ | openrisc | or32 \
+ | pdp10 | pdp11 | pj | pjl \
+ | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
+ | pyramid \
+ | s390 | s390x \
+ | sh | sh[1234] | sh[23]e | sh[34]eb | shbe | shle | sh[1234]le | sh3ele \
+ | sh64 | sh64le \
+ | sparc | sparc64 | sparc86x | sparclet | sparclite | sparcv8 | sparcv9 | sparcv9b \
+ | strongarm \
+ | tahoe | thumb | tic4x | tic80 | tron \
+ | v850 | v850e \
+ | we32k \
+ | x86 | xscale | xstormy16 | xtensa \
+ | z8k)
+ basic_machine=$basic_machine-unknown
+ ;;
+ m6811 | m68hc11 | m6812 | m68hc12)
+ # Motorola 68HC11/12.
+ basic_machine=$basic_machine-unknown
+ os=-none
+ ;;
+ m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
+ ;;
+
+ # We use `pc' rather than `unknown'
+ # because (1) that's what they normally are, and
+ # (2) the word "unknown" tends to confuse beginning users.
+ i*86 | x86_64)
+ basic_machine=$basic_machine-pc
+ ;;
+ # Object if more than one company name word.
+ *-*-*)
+ echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+ exit 1
+ ;;
+ # Recognize the basic CPU types with company name.
+ 580-* \
+ | a29k-* \
+ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
+ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
+ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
+ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \
+ | avr-* \
+ | bs2000-* \
+ | c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \
+ | clipper-* | cydra-* \
+ | d10v-* | d30v-* | dlx-* \
+ | elxsi-* \
+ | f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \
+ | h8300-* | h8500-* \
+ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
+ | i*86-* | i860-* | i960-* | ia64-* \
+ | ip2k-* \
+ | m32r-* \
+ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
+ | m88110-* | m88k-* | mcore-* \
+ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
+ | mips16-* \
+ | mips64-* | mips64el-* \
+ | mips64vr-* | mips64vrel-* \
+ | mips64orion-* | mips64orionel-* \
+ | mips64vr4100-* | mips64vr4100el-* \
+ | mips64vr4300-* | mips64vr4300el-* \
+ | mips64vr5000-* | mips64vr5000el-* \
+ | mipsisa32-* | mipsisa32el-* \
+ | mipsisa32r2-* | mipsisa32r2el-* \
+ | mipsisa64-* | mipsisa64el-* \
+ | mipsisa64sb1-* | mipsisa64sb1el-* \
+ | mipsisa64sr71k-* | mipsisa64sr71kel-* \
+ | mipstx39-* | mipstx39el-* \
+ | msp430-* \
+ | none-* | np1-* | nv1-* | ns16k-* | ns32k-* \
+ | orion-* \
+ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
+ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
+ | pyramid-* \
+ | romp-* | rs6000-* \
+ | s390-* | s390x-* \
+ | sh-* | sh[1234]-* | sh[23]e-* | sh[34]eb-* | shbe-* \
+ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
+ | sparc-* | sparc64-* | sparc86x-* | sparclet-* | sparclite-* \
+ | sparcv8-* | sparcv9-* | sparcv9b-* | strongarm-* | sv1-* | sx?-* \
+ | tahoe-* | thumb-* \
+ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
+ | tron-* \
+ | v850-* | v850e-* | vax-* \
+ | we32k-* \
+ | x86-* | x86_64-* | xps100-* | xscale-* | xstormy16-* \
+ | xtensa-* \
+ | ymp-* \
+ | z8k-*)
+ ;;
+ # Recognize the various machine names and aliases which stand
+ # for a CPU type and a company and sometimes even an OS.
+ 386bsd)
+ basic_machine=i386-unknown
+ os=-bsd
+ ;;
+ 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
+ basic_machine=m68000-att
+ ;;
+ 3b*)
+ basic_machine=we32k-att
+ ;;
+ a29khif)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ adobe68k)
+ basic_machine=m68010-adobe
+ os=-scout
+ ;;
+ alliant | fx80)
+ basic_machine=fx80-alliant
+ ;;
+ altos | altos3068)
+ basic_machine=m68k-altos
+ ;;
+ am29k)
+ basic_machine=a29k-none
+ os=-bsd
+ ;;
+ amd64)
+ basic_machine=x86_64-pc
+ ;;
+ amdahl)
+ basic_machine=580-amdahl
+ os=-sysv
+ ;;
+ amiga | amiga-*)
+ basic_machine=m68k-unknown
+ ;;
+ amigaos | amigados)
+ basic_machine=m68k-unknown
+ os=-amigaos
+ ;;
+ amigaunix | amix)
+ basic_machine=m68k-unknown
+ os=-sysv4
+ ;;
+ apollo68)
+ basic_machine=m68k-apollo
+ os=-sysv
+ ;;
+ apollo68bsd)
+ basic_machine=m68k-apollo
+ os=-bsd
+ ;;
+ aux)
+ basic_machine=m68k-apple
+ os=-aux
+ ;;
+ balance)
+ basic_machine=ns32k-sequent
+ os=-dynix
+ ;;
+ c90)
+ basic_machine=c90-cray
+ os=-unicos
+ ;;
+ convex-c1)
+ basic_machine=c1-convex
+ os=-bsd
+ ;;
+ convex-c2)
+ basic_machine=c2-convex
+ os=-bsd
+ ;;
+ convex-c32)
+ basic_machine=c32-convex
+ os=-bsd
+ ;;
+ convex-c34)
+ basic_machine=c34-convex
+ os=-bsd
+ ;;
+ convex-c38)
+ basic_machine=c38-convex
+ os=-bsd
+ ;;
+ cray | j90)
+ basic_machine=j90-cray
+ os=-unicos
+ ;;
+ crds | unos)
+ basic_machine=m68k-crds
+ ;;
+ cris | cris-* | etrax*)
+ basic_machine=cris-axis
+ ;;
+ da30 | da30-*)
+ basic_machine=m68k-da30
+ ;;
+ decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
+ basic_machine=mips-dec
+ ;;
+ decsystem10* | dec10*)
+ basic_machine=pdp10-dec
+ os=-tops10
+ ;;
+ decsystem20* | dec20*)
+ basic_machine=pdp10-dec
+ os=-tops20
+ ;;
+ delta | 3300 | motorola-3300 | motorola-delta \
+ | 3300-motorola | delta-motorola)
+ basic_machine=m68k-motorola
+ ;;
+ delta88)
+ basic_machine=m88k-motorola
+ os=-sysv3
+ ;;
+ dpx20 | dpx20-*)
+ basic_machine=rs6000-bull
+ os=-bosx
+ ;;
+ dpx2* | dpx2*-bull)
+ basic_machine=m68k-bull
+ os=-sysv3
+ ;;
+ ebmon29k)
+ basic_machine=a29k-amd
+ os=-ebmon
+ ;;
+ elxsi)
+ basic_machine=elxsi-elxsi
+ os=-bsd
+ ;;
+ encore | umax | mmax)
+ basic_machine=ns32k-encore
+ ;;
+ es1800 | OSE68k | ose68k | ose | OSE)
+ basic_machine=m68k-ericsson
+ os=-ose
+ ;;
+ fx2800)
+ basic_machine=i860-alliant
+ ;;
+ genix)
+ basic_machine=ns32k-ns
+ ;;
+ gmicro)
+ basic_machine=tron-gmicro
+ os=-sysv
+ ;;
+ go32)
+ basic_machine=i386-pc
+ os=-go32
+ ;;
+ h3050r* | hiux*)
+ basic_machine=hppa1.1-hitachi
+ os=-hiuxwe2
+ ;;
+ h8300hms)
+ basic_machine=h8300-hitachi
+ os=-hms
+ ;;
+ h8300xray)
+ basic_machine=h8300-hitachi
+ os=-xray
+ ;;
+ h8500hms)
+ basic_machine=h8500-hitachi
+ os=-hms
+ ;;
+ harris)
+ basic_machine=m88k-harris
+ os=-sysv3
+ ;;
+ hp300-*)
+ basic_machine=m68k-hp
+ ;;
+ hp300bsd)
+ basic_machine=m68k-hp
+ os=-bsd
+ ;;
+ hp300hpux)
+ basic_machine=m68k-hp
+ os=-hpux
+ ;;
+ hp3k9[0-9][0-9] | hp9[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hp9k2[0-9][0-9] | hp9k31[0-9])
+ basic_machine=m68000-hp
+ ;;
+ hp9k3[2-9][0-9])
+ basic_machine=m68k-hp
+ ;;
+ hp9k6[0-9][0-9] | hp6[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hp9k7[0-79][0-9] | hp7[0-79][0-9])
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k78[0-9] | hp78[0-9])
+ # FIXME: really hppa2.0-hp
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
+ # FIXME: really hppa2.0-hp
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[0-9][13679] | hp8[0-9][13679])
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[0-9][0-9] | hp8[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hppa-next)
+ os=-nextstep3
+ ;;
+ hppaosf)
+ basic_machine=hppa1.1-hp
+ os=-osf
+ ;;
+ hppro)
+ basic_machine=hppa1.1-hp
+ os=-proelf
+ ;;
+ i370-ibm* | ibm*)
+ basic_machine=i370-ibm
+ ;;
+# I'm not sure what "Sysv32" means. Should this be sysv3.2?
+ i*86v32)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-sysv32
+ ;;
+ i*86v4*)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-sysv4
+ ;;
+ i*86v)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-sysv
+ ;;
+ i*86sol2)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-solaris2
+ ;;
+ i386mach)
+ basic_machine=i386-mach
+ os=-mach
+ ;;
+ i386-vsta | vsta)
+ basic_machine=i386-unknown
+ os=-vsta
+ ;;
+ iris | iris4d)
+ basic_machine=mips-sgi
+ case $os in
+ -irix*)
+ ;;
+ *)
+ os=-irix4
+ ;;
+ esac
+ ;;
+ isi68 | isi)
+ basic_machine=m68k-isi
+ os=-sysv
+ ;;
+ m88k-omron*)
+ basic_machine=m88k-omron
+ ;;
+ magnum | m3230)
+ basic_machine=mips-mips
+ os=-sysv
+ ;;
+ merlin)
+ basic_machine=ns32k-utek
+ os=-sysv
+ ;;
+ mingw32)
+ basic_machine=i386-pc
+ os=-mingw32
+ ;;
+ miniframe)
+ basic_machine=m68000-convergent
+ ;;
+ *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
+ basic_machine=m68k-atari
+ os=-mint
+ ;;
+ mips3*-*)
+ basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
+ ;;
+ mips3*)
+ basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
+ ;;
+ mmix*)
+ basic_machine=mmix-knuth
+ os=-mmixware
+ ;;
+ monitor)
+ basic_machine=m68k-rom68k
+ os=-coff
+ ;;
+ morphos)
+ basic_machine=powerpc-unknown
+ os=-morphos
+ ;;
+ msdos)
+ basic_machine=i386-pc
+ os=-msdos
+ ;;
+ mvs)
+ basic_machine=i370-ibm
+ os=-mvs
+ ;;
+ ncr3000)
+ basic_machine=i486-ncr
+ os=-sysv4
+ ;;
+ netbsd386)
+ basic_machine=i386-unknown
+ os=-netbsd
+ ;;
+ netwinder)
+ basic_machine=armv4l-rebel
+ os=-linux
+ ;;
+ news | news700 | news800 | news900)
+ basic_machine=m68k-sony
+ os=-newsos
+ ;;
+ news1000)
+ basic_machine=m68030-sony
+ os=-newsos
+ ;;
+ news-3600 | risc-news)
+ basic_machine=mips-sony
+ os=-newsos
+ ;;
+ necv70)
+ basic_machine=v70-nec
+ os=-sysv
+ ;;
+ next | m*-next )
+ basic_machine=m68k-next
+ case $os in
+ -nextstep* )
+ ;;
+ -ns2*)
+ os=-nextstep2
+ ;;
+ *)
+ os=-nextstep3
+ ;;
+ esac
+ ;;
+ nh3000)
+ basic_machine=m68k-harris
+ os=-cxux
+ ;;
+ nh[45]000)
+ basic_machine=m88k-harris
+ os=-cxux
+ ;;
+ nindy960)
+ basic_machine=i960-intel
+ os=-nindy
+ ;;
+ mon960)
+ basic_machine=i960-intel
+ os=-mon960
+ ;;
+ nonstopux)
+ basic_machine=mips-compaq
+ os=-nonstopux
+ ;;
+ np1)
+ basic_machine=np1-gould
+ ;;
+ nv1)
+ basic_machine=nv1-cray
+ os=-unicosmp
+ ;;
+ nsr-tandem)
+ basic_machine=nsr-tandem
+ ;;
+ op50n-* | op60c-*)
+ basic_machine=hppa1.1-oki
+ os=-proelf
+ ;;
+ or32 | or32-*)
+ basic_machine=or32-unknown
+ os=-coff
+ ;;
+ OSE68000 | ose68000)
+ basic_machine=m68000-ericsson
+ os=-ose
+ ;;
+ os68k)
+ basic_machine=m68k-none
+ os=-os68k
+ ;;
+ pa-hitachi)
+ basic_machine=hppa1.1-hitachi
+ os=-hiuxwe2
+ ;;
+ paragon)
+ basic_machine=i860-intel
+ os=-osf
+ ;;
+ pbd)
+ basic_machine=sparc-tti
+ ;;
+ pbb)
+ basic_machine=m68k-tti
+ ;;
+ pc532 | pc532-*)
+ basic_machine=ns32k-pc532
+ ;;
+ pentium | p5 | k5 | k6 | nexgen | viac3)
+ basic_machine=i586-pc
+ ;;
+ pentiumpro | p6 | 6x86 | athlon | athlon_*)
+ basic_machine=i686-pc
+ ;;
+ pentiumii | pentium2 | pentiumiii | pentium3)
+ basic_machine=i686-pc
+ ;;
+ pentium4)
+ basic_machine=i786-pc
+ ;;
+ pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
+ basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentiumpro-* | p6-* | 6x86-* | athlon-*)
+ basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
+ basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentium4-*)
+ basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pn)
+ basic_machine=pn-gould
+ ;;
+ power) basic_machine=power-ibm
+ ;;
+ ppc) basic_machine=powerpc-unknown
+ ;;
+ ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ppcle | powerpclittle | ppc-le | powerpc-little)
+ basic_machine=powerpcle-unknown
+ ;;
+ ppcle-* | powerpclittle-*)
+ basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ppc64) basic_machine=powerpc64-unknown
+ ;;
+ ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ppc64le | powerpc64little | ppc64-le | powerpc64-little)
+ basic_machine=powerpc64le-unknown
+ ;;
+ ppc64le-* | powerpc64little-*)
+ basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ps2)
+ basic_machine=i386-ibm
+ ;;
+ pw32)
+ basic_machine=i586-unknown
+ os=-pw32
+ ;;
+ rom68k)
+ basic_machine=m68k-rom68k
+ os=-coff
+ ;;
+ rm[46]00)
+ basic_machine=mips-siemens
+ ;;
+ rtpc | rtpc-*)
+ basic_machine=romp-ibm
+ ;;
+ sa29200)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ sb1)
+ basic_machine=mipsisa64sb1-unknown
+ ;;
+ sb1el)
+ basic_machine=mipsisa64sb1el-unknown
+ ;;
+ sei)
+ basic_machine=mips-sei
+ os=-seiux
+ ;;
+ sequent)
+ basic_machine=i386-sequent
+ ;;
+ sh)
+ basic_machine=sh-hitachi
+ os=-hms
+ ;;
+ sh64)
+ basic_machine=sh64-unknown
+ ;;
+ sparclite-wrs | simso-wrs)
+ basic_machine=sparclite-wrs
+ os=-vxworks
+ ;;
+ sps7)
+ basic_machine=m68k-bull
+ os=-sysv2
+ ;;
+ spur)
+ basic_machine=spur-unknown
+ ;;
+ st2000)
+ basic_machine=m68k-tandem
+ ;;
+ stratus)
+ basic_machine=i860-stratus
+ os=-sysv4
+ ;;
+ sun2)
+ basic_machine=m68000-sun
+ ;;
+ sun2os3)
+ basic_machine=m68000-sun
+ os=-sunos3
+ ;;
+ sun2os4)
+ basic_machine=m68000-sun
+ os=-sunos4
+ ;;
+ sun3os3)
+ basic_machine=m68k-sun
+ os=-sunos3
+ ;;
+ sun3os4)
+ basic_machine=m68k-sun
+ os=-sunos4
+ ;;
+ sun4os3)
+ basic_machine=sparc-sun
+ os=-sunos3
+ ;;
+ sun4os4)
+ basic_machine=sparc-sun
+ os=-sunos4
+ ;;
+ sun4sol2)
+ basic_machine=sparc-sun
+ os=-solaris2
+ ;;
+ sun3 | sun3-*)
+ basic_machine=m68k-sun
+ ;;
+ sun4)
+ basic_machine=sparc-sun
+ ;;
+ sun386 | sun386i | roadrunner)
+ basic_machine=i386-sun
+ ;;
+ sv1)
+ basic_machine=sv1-cray
+ os=-unicos
+ ;;
+ symmetry)
+ basic_machine=i386-sequent
+ os=-dynix
+ ;;
+ t3e)
+ basic_machine=alphaev5-cray
+ os=-unicos
+ ;;
+ t90)
+ basic_machine=t90-cray
+ os=-unicos
+ ;;
+ tic54x | c54x*)
+ basic_machine=tic54x-unknown
+ os=-coff
+ ;;
+ tic55x | c55x*)
+ basic_machine=tic55x-unknown
+ os=-coff
+ ;;
+ tic6x | c6x*)
+ basic_machine=tic6x-unknown
+ os=-coff
+ ;;
+ tx39)
+ basic_machine=mipstx39-unknown
+ ;;
+ tx39el)
+ basic_machine=mipstx39el-unknown
+ ;;
+ toad1)
+ basic_machine=pdp10-xkl
+ os=-tops20
+ ;;
+ tower | tower-32)
+ basic_machine=m68k-ncr
+ ;;
+ udi29k)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ ultra3)
+ basic_machine=a29k-nyu
+ os=-sym1
+ ;;
+ v810 | necv810)
+ basic_machine=v810-nec
+ os=-none
+ ;;
+ vaxv)
+ basic_machine=vax-dec
+ os=-sysv
+ ;;
+ vms)
+ basic_machine=vax-dec
+ os=-vms
+ ;;
+ vpp*|vx|vx-*)
+ basic_machine=f301-fujitsu
+ ;;
+ vxworks960)
+ basic_machine=i960-wrs
+ os=-vxworks
+ ;;
+ vxworks68)
+ basic_machine=m68k-wrs
+ os=-vxworks
+ ;;
+ vxworks29k)
+ basic_machine=a29k-wrs
+ os=-vxworks
+ ;;
+ w65*)
+ basic_machine=w65-wdc
+ os=-none
+ ;;
+ w89k-*)
+ basic_machine=hppa1.1-winbond
+ os=-proelf
+ ;;
+ xps | xps100)
+ basic_machine=xps100-honeywell
+ ;;
+ ymp)
+ basic_machine=ymp-cray
+ os=-unicos
+ ;;
+ z8k-*-coff)
+ basic_machine=z8k-unknown
+ os=-sim
+ ;;
+ none)
+ basic_machine=none-none
+ os=-none
+ ;;
+
+# Here we handle the default manufacturer of certain CPU types. It is in
+# some cases the only manufacturer, in others, it is the most popular.
+ w89k)
+ basic_machine=hppa1.1-winbond
+ ;;
+ op50n)
+ basic_machine=hppa1.1-oki
+ ;;
+ op60c)
+ basic_machine=hppa1.1-oki
+ ;;
+ romp)
+ basic_machine=romp-ibm
+ ;;
+ rs6000)
+ basic_machine=rs6000-ibm
+ ;;
+ vax)
+ basic_machine=vax-dec
+ ;;
+ pdp10)
+ # there are many clones, so DEC is not a safe bet
+ basic_machine=pdp10-unknown
+ ;;
+ pdp11)
+ basic_machine=pdp11-dec
+ ;;
+ we32k)
+ basic_machine=we32k-att
+ ;;
+ sh3 | sh4 | sh[34]eb | sh[1234]le | sh[23]ele)
+ basic_machine=sh-unknown
+ ;;
+ sh64)
+ basic_machine=sh64-unknown
+ ;;
+ sparc | sparcv8 | sparcv9 | sparcv9b)
+ basic_machine=sparc-sun
+ ;;
+ cydra)
+ basic_machine=cydra-cydrome
+ ;;
+ orion)
+ basic_machine=orion-highlevel
+ ;;
+ orion105)
+ basic_machine=clipper-highlevel
+ ;;
+ mac | mpw | mac-mpw)
+ basic_machine=m68k-apple
+ ;;
+ pmac | pmac-mpw)
+ basic_machine=powerpc-apple
+ ;;
+ *-unknown)
+ # Make sure to match an already-canonicalized machine name.
+ ;;
+ *)
+ echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+ exit 1
+ ;;
+esac
+
+# Here we canonicalize certain aliases for manufacturers.
+case $basic_machine in
+ *-digital*)
+ basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
+ ;;
+ *-commodore*)
+ basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
+ ;;
+ *)
+ ;;
+esac
+
+# Decode manufacturer-specific aliases for certain operating systems.
+
+if [ x"$os" != x"" ]
+then
+case $os in
+ # First match some system type aliases
+ # that might get confused with valid system types.
+ # -solaris* is a basic system type, with this one exception.
+ -solaris1 | -solaris1.*)
+ os=`echo $os | sed -e 's|solaris1|sunos4|'`
+ ;;
+ -solaris)
+ os=-solaris2
+ ;;
+ -svr4*)
+ os=-sysv4
+ ;;
+ -unixware*)
+ os=-sysv4.2uw
+ ;;
+ -gnu/linux*)
+ os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
+ ;;
+ # First accept the basic system types.
+ # The portable systems comes first.
+ # Each alternative MUST END IN A *, to match a version number.
+ # -sysv* is not here because it comes later, after sysvr4.
+ -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
+ | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\
+ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \
+ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
+ | -aos* \
+ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
+ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
+ | -hiux* | -386bsd* | -netbsd* | -openbsd* | -freebsd* | -riscix* \
+ | -lynxos* | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
+ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
+ | -chorusos* | -chorusrdb* \
+ | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
+ | -mingw32* | -linux-gnu* | -uxpv* | -beos* | -mpeix* | -udk* \
+ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
+ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
+ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
+ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
+ | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
+ | -powermax* | -dnix* | -nx6 | -nx7 | -sei*)
+ # Remember, each alternative MUST END IN *, to match a version number.
+ ;;
+ -qnx*)
+ case $basic_machine in
+ x86-* | i*86-*)
+ ;;
+ *)
+ os=-nto$os
+ ;;
+ esac
+ ;;
+ -nto-qnx*)
+ ;;
+ -nto*)
+ os=`echo $os | sed -e 's|nto|nto-qnx|'`
+ ;;
+ -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
+ | -windows* | -osx | -abug | -netware* | -os9* | -beos* \
+ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
+ ;;
+ -mac*)
+ os=`echo $os | sed -e 's|mac|macos|'`
+ ;;
+ -linux*)
+ os=`echo $os | sed -e 's|linux|linux-gnu|'`
+ ;;
+ -sunos5*)
+ os=`echo $os | sed -e 's|sunos5|solaris2|'`
+ ;;
+ -sunos6*)
+ os=`echo $os | sed -e 's|sunos6|solaris3|'`
+ ;;
+ -opened*)
+ os=-openedition
+ ;;
+ -wince*)
+ os=-wince
+ ;;
+ -osfrose*)
+ os=-osfrose
+ ;;
+ -osf*)
+ os=-osf
+ ;;
+ -utek*)
+ os=-bsd
+ ;;
+ -dynix*)
+ os=-bsd
+ ;;
+ -acis*)
+ os=-aos
+ ;;
+ -atheos*)
+ os=-atheos
+ ;;
+ -386bsd)
+ os=-bsd
+ ;;
+ -ctix* | -uts*)
+ os=-sysv
+ ;;
+ -nova*)
+ os=-rtmk-nova
+ ;;
+ -ns2 )
+ os=-nextstep2
+ ;;
+ -nsk*)
+ os=-nsk
+ ;;
+ # Preserve the version number of sinix5.
+ -sinix5.*)
+ os=`echo $os | sed -e 's|sinix|sysv|'`
+ ;;
+ -sinix*)
+ os=-sysv4
+ ;;
+ -triton*)
+ os=-sysv3
+ ;;
+ -oss*)
+ os=-sysv3
+ ;;
+ -svr4)
+ os=-sysv4
+ ;;
+ -svr3)
+ os=-sysv3
+ ;;
+ -sysvr4)
+ os=-sysv4
+ ;;
+ # This must come after -sysvr4.
+ -sysv*)
+ ;;
+ -ose*)
+ os=-ose
+ ;;
+ -es1800*)
+ os=-ose
+ ;;
+ -xenix)
+ os=-xenix
+ ;;
+ -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+ os=-mint
+ ;;
+ -aros*)
+ os=-aros
+ ;;
+ -kaos*)
+ os=-kaos
+ ;;
+ -none)
+ ;;
+ *)
+ # Get rid of the `-' at the beginning of $os.
+ os=`echo $os | sed 's/[^-]*-//'`
+ echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
+ exit 1
+ ;;
+esac
+else
+
+# Here we handle the default operating systems that come with various machines.
+# The value should be what the vendor currently ships out the door with their
+# machine or put another way, the most popular os provided with the machine.
+
+# Note that if you're going to try to match "-MANUFACTURER" here (say,
+# "-sun"), then you have to tell the case statement up towards the top
+# that MANUFACTURER isn't an operating system. Otherwise, code above
+# will signal an error saying that MANUFACTURER isn't an operating
+# system, and we'll never get to this point.
+
+case $basic_machine in
+ *-acorn)
+ os=-riscix1.2
+ ;;
+ arm*-rebel)
+ os=-linux
+ ;;
+ arm*-semi)
+ os=-aout
+ ;;
+ c4x-* | tic4x-*)
+ os=-coff
+ ;;
+ # This must come before the *-dec entry.
+ pdp10-*)
+ os=-tops20
+ ;;
+ pdp11-*)
+ os=-none
+ ;;
+ *-dec | vax-*)
+ os=-ultrix4.2
+ ;;
+ m68*-apollo)
+ os=-domain
+ ;;
+ i386-sun)
+ os=-sunos4.0.2
+ ;;
+ m68000-sun)
+ os=-sunos3
+ # This also exists in the configure program, but was not the
+ # default.
+ # os=-sunos4
+ ;;
+ m68*-cisco)
+ os=-aout
+ ;;
+ mips*-cisco)
+ os=-elf
+ ;;
+ mips*-*)
+ os=-elf
+ ;;
+ or32-*)
+ os=-coff
+ ;;
+ *-tti) # must be before sparc entry or we get the wrong os.
+ os=-sysv3
+ ;;
+ sparc-* | *-sun)
+ os=-sunos4.1.1
+ ;;
+ *-be)
+ os=-beos
+ ;;
+ *-ibm)
+ os=-aix
+ ;;
+ *-wec)
+ os=-proelf
+ ;;
+ *-winbond)
+ os=-proelf
+ ;;
+ *-oki)
+ os=-proelf
+ ;;
+ *-hp)
+ os=-hpux
+ ;;
+ *-hitachi)
+ os=-hiux
+ ;;
+ i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
+ os=-sysv
+ ;;
+ *-cbm)
+ os=-amigaos
+ ;;
+ *-dg)
+ os=-dgux
+ ;;
+ *-dolphin)
+ os=-sysv3
+ ;;
+ m68k-ccur)
+ os=-rtu
+ ;;
+ m88k-omron*)
+ os=-luna
+ ;;
+ *-next )
+ os=-nextstep
+ ;;
+ *-sequent)
+ os=-ptx
+ ;;
+ *-crds)
+ os=-unos
+ ;;
+ *-ns)
+ os=-genix
+ ;;
+ i370-*)
+ os=-mvs
+ ;;
+ *-next)
+ os=-nextstep3
+ ;;
+ *-gould)
+ os=-sysv
+ ;;
+ *-highlevel)
+ os=-bsd
+ ;;
+ *-encore)
+ os=-bsd
+ ;;
+ *-sgi)
+ os=-irix
+ ;;
+ *-siemens)
+ os=-sysv4
+ ;;
+ *-masscomp)
+ os=-rtu
+ ;;
+ f30[01]-fujitsu | f700-fujitsu)
+ os=-uxpv
+ ;;
+ *-rom68k)
+ os=-coff
+ ;;
+ *-*bug)
+ os=-coff
+ ;;
+ *-apple)
+ os=-macos
+ ;;
+ *-atari*)
+ os=-mint
+ ;;
+ *)
+ os=-none
+ ;;
+esac
+fi
+
+# Here we handle the case where we know the os, and the CPU type, but not the
+# manufacturer. We pick the logical manufacturer.
+vendor=unknown
+case $basic_machine in
+ *-unknown)
+ case $os in
+ -riscix*)
+ vendor=acorn
+ ;;
+ -sunos*)
+ vendor=sun
+ ;;
+ -aix*)
+ vendor=ibm
+ ;;
+ -beos*)
+ vendor=be
+ ;;
+ -hpux*)
+ vendor=hp
+ ;;
+ -mpeix*)
+ vendor=hp
+ ;;
+ -hiux*)
+ vendor=hitachi
+ ;;
+ -unos*)
+ vendor=crds
+ ;;
+ -dgux*)
+ vendor=dg
+ ;;
+ -luna*)
+ vendor=omron
+ ;;
+ -genix*)
+ vendor=ns
+ ;;
+ -mvs* | -opened*)
+ vendor=ibm
+ ;;
+ -ptx*)
+ vendor=sequent
+ ;;
+ -vxsim* | -vxworks* | -windiss*)
+ vendor=wrs
+ ;;
+ -aux*)
+ vendor=apple
+ ;;
+ -hms*)
+ vendor=hitachi
+ ;;
+ -mpw* | -macos*)
+ vendor=apple
+ ;;
+ -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+ vendor=atari
+ ;;
+ -vos*)
+ vendor=stratus
+ ;;
+ esac
+ basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
+ ;;
+esac
+
+echo $basic_machine$os
+exit 0
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/jasper-1.900.1-6ct/acaux/depcomp b/jasper-1.900.1-6ct/acaux/depcomp
new file mode 100644
index 0000000..807b991
--- /dev/null
+++ b/jasper-1.900.1-6ct/acaux/depcomp
@@ -0,0 +1,423 @@
+#! /bin/sh
+
+# depcomp - compile a program generating dependencies as side-effects
+# Copyright 1999, 2000 Free Software Foundation, Inc.
+
+# 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, 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, Inc., 59 Temple Place - Suite 330, Boston, MA
+# 02111-1307, USA.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# Originally written by Alexandre Oliva <oliva at dcc.unicamp.br>.
+
+if test -z "$depmode" || test -z "$source" || test -z "$object"; then
+ echo "depcomp: Variables source, object and depmode must be set" 1>&2
+ exit 1
+fi
+# `libtool' can also be set to `yes' or `no'.
+
+if test -z "$depfile"; then
+ base=`echo "$object" | sed -e 's,^.*/,,' -e 's,\.\([^.]*\)$,.P\1,'`
+ dir=`echo "$object" | sed 's,/.*$,/,'`
+ if test "$dir" = "$object"; then
+ dir=
+ fi
+ # FIXME: should be _deps on DOS.
+ depfile="$dir.deps/$base"
+fi
+
+tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
+
+rm -f "$tmpdepfile"
+
+# Some modes work just like other modes, but use different flags. We
+# parameterize here, but still list the modes in the big case below,
+# to make depend.m4 easier to write. Note that we *cannot* use a case
+# here, because this file can only contain one case statement.
+if test "$depmode" = hp; then
+ # HP compiler uses -M and no extra arg.
+ gccflag=-M
+ depmode=gcc
+fi
+
+if test "$depmode" = dashXmstdout; then
+ # This is just like dashmstdout with a different argument.
+ dashmflag=-xM
+ depmode=dashmstdout
+fi
+
+case "$depmode" in
+gcc3)
+## gcc 3 implements dependency tracking that does exactly what
+## we want. Yay! Note: for some reason libtool 1.4 doesn't like
+## it if -MD -MP comes after the -MF stuff. Hmm.
+ "$@" -MT "$object" -MD -MP -MF "$tmpdepfile"
+ stat=$?
+ if test $stat -eq 0; then :
+ else
+ rm -f "$tmpdepfile"
+ exit $stat
+ fi
+ mv "$tmpdepfile" "$depfile"
+ ;;
+
+gcc)
+## There are various ways to get dependency output from gcc. Here's
+## why we pick this rather obscure method:
+## - Don't want to use -MD because we'd like the dependencies to end
+## up in a subdir. Having to rename by hand is ugly.
+## (We might end up doing this anyway to support other compilers.)
+## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like
+## -MM, not -M (despite what the docs say).
+## - Using -M directly means running the compiler twice (even worse
+## than renaming).
+ if test -z "$gccflag"; then
+ gccflag=-MD,
+ fi
+ "$@" -Wp,"$gccflag$tmpdepfile"
+ stat=$?
+ if test $stat -eq 0; then :
+ else
+ rm -f "$tmpdepfile"
+ exit $stat
+ fi
+ rm -f "$depfile"
+ echo "$object : \\" > "$depfile"
+ alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
+## The second -e expression handles DOS-style file names with drive letters.
+ sed -e 's/^[^:]*: / /' \
+ -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile"
+## This next piece of magic avoids the `deleted header file' problem.
+## The problem is that when a header file which appears in a .P file
+## is deleted, the dependency causes make to die (because there is
+## typically no way to rebuild the header). We avoid this by adding
+## dummy dependencies for each header file. Too bad gcc doesn't do
+## this for us directly.
+ tr ' ' '
+' < "$tmpdepfile" |
+## Some versions of gcc put a space before the `:'. On the theory
+## that the space means something, we add a space to the output as
+## well.
+## Some versions of the HPUX 10.20 sed can't process this invocation
+## correctly. Breaking it into two sed invocations is a workaround.
+ sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
+ rm -f "$tmpdepfile"
+ ;;
+
+hp)
+ # This case exists only to let depend.m4 do its work. It works by
+ # looking at the text of this script. This case will never be run,
+ # since it is checked for above.
+ exit 1
+ ;;
+
+sgi)
+ if test "$libtool" = yes; then
+ "$@" "-Wp,-MDupdate,$tmpdepfile"
+ else
+ "$@" -MDupdate "$tmpdepfile"
+ fi
+ stat=$?
+ if test $stat -eq 0; then :
+ else
+ rm -f "$tmpdepfile"
+ exit $stat
+ fi
+ rm -f "$depfile"
+
+ if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files
+ echo "$object : \\" > "$depfile"
+
+ # Clip off the initial element (the dependent). Don't try to be
+ # clever and replace this with sed code, as IRIX sed won't handle
+ # lines with more than a fixed number of characters (4096 in
+ # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines;
+ # the IRIX cc adds comments like `#:fec' to the end of the
+ # dependency line.
+ tr ' ' '
+' < "$tmpdepfile" \
+ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \
+ tr '
+' ' ' >> $depfile
+ echo >> $depfile
+
+ # The second pass generates a dummy entry for each header file.
+ tr ' ' '
+' < "$tmpdepfile" \
+ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
+ >> $depfile
+ else
+ # The sourcefile does not contain any dependencies, so just
+ # store a dummy comment line, to avoid errors with the Makefile
+ # "include basename.Plo" scheme.
+ echo "#dummy" > "$depfile"
+ fi
+ rm -f "$tmpdepfile"
+ ;;
+
+aix)
+ # The C for AIX Compiler uses -M and outputs the dependencies
+ # in a .u file. This file always lives in the current directory.
+ # Also, the AIX compiler puts `$object:' at the start of each line;
+ # $object doesn't have directory information.
+ stripped=`echo "$object" | sed -e 's,^.*/,,' -e 's/\(.*\)\..*$/\1/'`
+ tmpdepfile="$stripped.u"
+ outname="$stripped.o"
+ if test "$libtool" = yes; then
+ "$@" -Wc,-M
+ else
+ "$@" -M
+ fi
+
+ stat=$?
+ if test $stat -eq 0; then :
+ else
+ rm -f "$tmpdepfile"
+ exit $stat
+ fi
+
+ if test -f "$tmpdepfile"; then
+ # Each line is of the form `foo.o: dependent.h'.
+ # Do two passes, one to just change these to
+ # `$object: dependent.h' and one to simply `dependent.h:'.
+ sed -e "s,^$outname:,$object :," < "$tmpdepfile" > "$depfile"
+ sed -e "s,^$outname: \(.*\)$,\1:," < "$tmpdepfile" >> "$depfile"
+ else
+ # The sourcefile does not contain any dependencies, so just
+ # store a dummy comment line, to avoid errors with the Makefile
+ # "include basename.Plo" scheme.
+ echo "#dummy" > "$depfile"
+ fi
+ rm -f "$tmpdepfile"
+ ;;
+
+tru64)
+ # The Tru64 compiler uses -MD to generate dependencies as a side
+ # effect. `cc -MD -o foo.o ...' puts the dependencies into `foo.o.d'.
+ # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put
+ # dependencies in `foo.d' instead, so we check for that too.
+ # Subdirectories are respected.
+ dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
+ test "x$dir" = "x$object" && dir=
+ base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
+
+ if test "$libtool" = yes; then
+ tmpdepfile1="$dir.libs/$base.lo.d"
+ tmpdepfile2="$dir.libs/$base.d"
+ "$@" -Wc,-MD
+ else
+ tmpdepfile1="$dir$base.o.d"
+ tmpdepfile2="$dir$base.d"
+ "$@" -MD
+ fi
+
+ stat=$?
+ if test $stat -eq 0; then :
+ else
+ rm -f "$tmpdepfile1" "$tmpdepfile2"
+ exit $stat
+ fi
+
+ if test -f "$tmpdepfile1"; then
+ tmpdepfile="$tmpdepfile1"
+ else
+ tmpdepfile="$tmpdepfile2"
+ fi
+ if test -f "$tmpdepfile"; then
+ sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile"
+ # That's a space and a tab in the [].
+ sed -e 's,^.*\.[a-z]*:[ ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
+ else
+ echo "#dummy" > "$depfile"
+ fi
+ rm -f "$tmpdepfile"
+ ;;
+
+#nosideeffect)
+ # This comment above is used by automake to tell side-effect
+ # dependency tracking mechanisms from slower ones.
+
+dashmstdout)
+ # Important note: in order to support this mode, a compiler *must*
+ # always write the proprocessed file to stdout, regardless of -o.
+ "$@" || exit $?
+
+ # Remove the call to Libtool.
+ if test "$libtool" = yes; then
+ while test $1 != '--mode=compile'; do
+ shift
+ done
+ shift
+ fi
+
+ # Remove `-o $object'. We will use -o /dev/null later,
+ # however we can't do the remplacement now because
+ # `-o $object' might simply not be used
+ IFS=" "
+ for arg
+ do
+ case $arg in
+ -o)
+ shift
+ ;;
+ $object)
+ shift
+ ;;
+ *)
+ set fnord "$@" "$arg"
+ shift # fnord
+ shift # $arg
+ ;;
+ esac
+ done
+
+ test -z "$dashmflag" && dashmflag=-M
+ "$@" -o /dev/null $dashmflag | sed 's:^[^:]*\:[ ]*:'"$object"'\: :' > "$tmpdepfile"
+ rm -f "$depfile"
+ cat < "$tmpdepfile" > "$depfile"
+ tr ' ' '
+' < "$tmpdepfile" | \
+## Some versions of the HPUX 10.20 sed can't process this invocation
+## correctly. Breaking it into two sed invocations is a workaround.
+ sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
+ rm -f "$tmpdepfile"
+ ;;
+
+dashXmstdout)
+ # This case only exists to satisfy depend.m4. It is never actually
+ # run, as this mode is specially recognized in the preamble.
+ exit 1
+ ;;
+
+makedepend)
+ "$@" || exit $?
+ # X makedepend
+ shift
+ cleared=no
+ for arg in "$@"; do
+ case $cleared in
+ no)
+ set ""; shift
+ cleared=yes ;;
+ esac
+ case "$arg" in
+ -D*|-I*)
+ set fnord "$@" "$arg"; shift ;;
+ -*)
+ ;;
+ *)
+ set fnord "$@" "$arg"; shift ;;
+ esac
+ done
+ obj_suffix="`echo $object | sed 's/^.*\././'`"
+ touch "$tmpdepfile"
+ ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@"
+ rm -f "$depfile"
+ cat < "$tmpdepfile" > "$depfile"
+ sed '1,2d' "$tmpdepfile" | tr ' ' '
+' | \
+## Some versions of the HPUX 10.20 sed can't process this invocation
+## correctly. Breaking it into two sed invocations is a workaround.
+ sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
+ rm -f "$tmpdepfile" "$tmpdepfile".bak
+ ;;
+
+cpp)
+ # Important note: in order to support this mode, a compiler *must*
+ # always write the proprocessed file to stdout.
+ "$@" || exit $?
+
+ # Remove the call to Libtool.
+ if test "$libtool" = yes; then
+ while test $1 != '--mode=compile'; do
+ shift
+ done
+ shift
+ fi
+
+ # Remove `-o $object'.
+ IFS=" "
+ for arg
+ do
+ case $arg in
+ -o)
+ shift
+ ;;
+ $object)
+ shift
+ ;;
+ *)
+ set fnord "$@" "$arg"
+ shift # fnord
+ shift # $arg
+ ;;
+ esac
+ done
+
+ "$@" -E |
+ sed -n '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' |
+ sed '$ s: \\$::' > "$tmpdepfile"
+ rm -f "$depfile"
+ echo "$object : \\" > "$depfile"
+ cat < "$tmpdepfile" >> "$depfile"
+ sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile"
+ rm -f "$tmpdepfile"
+ ;;
+
+msvisualcpp)
+ # Important note: in order to support this mode, a compiler *must*
+ # always write the proprocessed file to stdout, regardless of -o,
+ # because we must use -o when running libtool.
+ "$@" || exit $?
+ IFS=" "
+ for arg
+ do
+ case "$arg" in
+ "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI")
+ set fnord "$@"
+ shift
+ shift
+ ;;
+ *)
+ set fnord "$@" "$arg"
+ shift
+ shift
+ ;;
+ esac
+ done
+ "$@" -E |
+ sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::echo "`cygpath -u \\"\1\\"`":p' | sort | uniq > "$tmpdepfile"
+ rm -f "$depfile"
+ echo "$object : \\" > "$depfile"
+ . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s:: \1 \\:p' >> "$depfile"
+ echo " " >> "$depfile"
+ . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::\1\::p' >> "$depfile"
+ rm -f "$tmpdepfile"
+ ;;
+
+none)
+ exec "$@"
+ ;;
+
+*)
+ echo "Unknown depmode $depmode" 1>&2
+ exit 1
+ ;;
+esac
+
+exit 0
diff --git a/jasper-1.900.1-6ct/acaux/install-sh b/jasper-1.900.1-6ct/acaux/install-sh
new file mode 100644
index 0000000..11870f1
--- /dev/null
+++ b/jasper-1.900.1-6ct/acaux/install-sh
@@ -0,0 +1,251 @@
+#!/bin/sh
+#
+# install - install a program, script, or datafile
+# This comes from X11R5 (mit/util/scripts/install.sh).
+#
+# Copyright 1991 by the Massachusetts Institute of Technology
+#
+# Permission to use, copy, modify, distribute, and sell this software and its
+# documentation for any purpose is hereby granted without fee, provided that
+# the above copyright notice appear in all copies and that both that
+# copyright notice and this permission notice appear in supporting
+# documentation, and that the name of M.I.T. not be used in advertising or
+# publicity pertaining to distribution of the software without specific,
+# written prior permission. M.I.T. makes no representations about the
+# suitability of this software for any purpose. It is provided "as is"
+# without express or implied warranty.
+#
+# Calling this script install-sh is preferred over install.sh, to prevent
+# `make' implicit rules from creating a file called install from it
+# when there is no Makefile.
+#
+# This script is compatible with the BSD install script, but was written
+# from scratch. It can only install one file at a time, a restriction
+# shared with many OS's install programs.
+
+
+# set DOITPROG to echo to test this script
+
+# Don't use :- since 4.3BSD and earlier shells don't like it.
+doit="${DOITPROG-}"
+
+
+# put in absolute paths if you don't have them in your path; or use env. vars.
+
+mvprog="${MVPROG-mv}"
+cpprog="${CPPROG-cp}"
+chmodprog="${CHMODPROG-chmod}"
+chownprog="${CHOWNPROG-chown}"
+chgrpprog="${CHGRPPROG-chgrp}"
+stripprog="${STRIPPROG-strip}"
+rmprog="${RMPROG-rm}"
+mkdirprog="${MKDIRPROG-mkdir}"
+
+transformbasename=""
+transform_arg=""
+instcmd="$mvprog"
+chmodcmd="$chmodprog 0755"
+chowncmd=""
+chgrpcmd=""
+stripcmd=""
+rmcmd="$rmprog -f"
+mvcmd="$mvprog"
+src=""
+dst=""
+dir_arg=""
+
+while [ x"$1" != x ]; do
+ case $1 in
+ -c) instcmd="$cpprog"
+ shift
+ continue;;
+
+ -d) dir_arg=true
+ shift
+ continue;;
+
+ -m) chmodcmd="$chmodprog $2"
+ shift
+ shift
+ continue;;
+
+ -o) chowncmd="$chownprog $2"
+ shift
+ shift
+ continue;;
+
+ -g) chgrpcmd="$chgrpprog $2"
+ shift
+ shift
+ continue;;
+
+ -s) stripcmd="$stripprog"
+ shift
+ continue;;
+
+ -t=*) transformarg=`echo $1 | sed 's/-t=//'`
+ shift
+ continue;;
+
+ -b=*) transformbasename=`echo $1 | sed 's/-b=//'`
+ shift
+ continue;;
+
+ *) if [ x"$src" = x ]
+ then
+ src=$1
+ else
+ # this colon is to work around a 386BSD /bin/sh bug
+ :
+ dst=$1
+ fi
+ shift
+ continue;;
+ esac
+done
+
+if [ x"$src" = x ]
+then
+ echo "install: no input file specified"
+ exit 1
+else
+ :
+fi
+
+if [ x"$dir_arg" != x ]; then
+ dst=$src
+ src=""
+
+ if [ -d $dst ]; then
+ instcmd=:
+ chmodcmd=""
+ else
+ instcmd=$mkdirprog
+ fi
+else
+
+# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
+# might cause directories to be created, which would be especially bad
+# if $src (and thus $dsttmp) contains '*'.
+
+ if [ -f "$src" ] || [ -d "$src" ]
+ then
+ :
+ else
+ echo "install: $src does not exist"
+ exit 1
+ fi
+
+ if [ x"$dst" = x ]
+ then
+ echo "install: no destination specified"
+ exit 1
+ else
+ :
+ fi
+
+# If destination is a directory, append the input filename; if your system
+# does not like double slashes in filenames, you may need to add some logic
+
+ if [ -d $dst ]
+ then
+ dst="$dst"/`basename $src`
+ else
+ :
+ fi
+fi
+
+## this sed command emulates the dirname command
+dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
+
+# Make sure that the destination directory exists.
+# this part is taken from Noah Friedman's mkinstalldirs script
+
+# Skip lots of stat calls in the usual case.
+if [ ! -d "$dstdir" ]; then
+defaultIFS='
+ '
+IFS="${IFS-${defaultIFS}}"
+
+oIFS="${IFS}"
+# Some sh's can't handle IFS=/ for some reason.
+IFS='%'
+set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'`
+IFS="${oIFS}"
+
+pathcomp=''
+
+while [ $# -ne 0 ] ; do
+ pathcomp="${pathcomp}${1}"
+ shift
+
+ if [ ! -d "${pathcomp}" ] ;
+ then
+ $mkdirprog "${pathcomp}"
+ else
+ :
+ fi
+
+ pathcomp="${pathcomp}/"
+done
+fi
+
+if [ x"$dir_arg" != x ]
+then
+ $doit $instcmd $dst &&
+
+ if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else : ; fi &&
+ if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else : ; fi &&
+ if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else : ; fi &&
+ if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else : ; fi
+else
+
+# If we're going to rename the final executable, determine the name now.
+
+ if [ x"$transformarg" = x ]
+ then
+ dstfile=`basename $dst`
+ else
+ dstfile=`basename $dst $transformbasename |
+ sed $transformarg`$transformbasename
+ fi
+
+# don't allow the sed command to completely eliminate the filename
+
+ if [ x"$dstfile" = x ]
+ then
+ dstfile=`basename $dst`
+ else
+ :
+ fi
+
+# Make a temp file name in the proper directory.
+
+ dsttmp=$dstdir/#inst.$$#
+
+# Move or copy the file name to the temp name
+
+ $doit $instcmd $src $dsttmp &&
+
+ trap "rm -f ${dsttmp}" 0 &&
+
+# and set any options; do chmod last to preserve setuid bits
+
+# If any of these fail, we abort the whole thing. If we want to
+# ignore errors from any of these, just make sure not to ignore
+# errors from the above "$doit $instcmd $src $dsttmp" command.
+
+ if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else :;fi &&
+ if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else :;fi &&
+ if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else :;fi &&
+ if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else :;fi &&
+
+# Now rename the file to the real destination.
+
+ $doit $rmcmd -f $dstdir/$dstfile &&
+ $doit $mvcmd $dsttmp $dstdir/$dstfile
+
+fi &&
+
+
+exit 0
diff --git a/jasper-1.900.1-6ct/acaux/ltmain.sh b/jasper-1.900.1-6ct/acaux/ltmain.sh
new file mode 100644
index 0000000..0223495
--- /dev/null
+++ b/jasper-1.900.1-6ct/acaux/ltmain.sh
@@ -0,0 +1,6911 @@
+# ltmain.sh - Provide generalized library-building support services.
+# NOTE: Changing this file will not affect anything until you rerun configure.
+#
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005
+# Free Software Foundation, Inc.
+# Originally by Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
+#
+# 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 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, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+basename="s,^.*/,,g"
+
+# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
+# is ksh but when the shell is invoked as "sh" and the current value of
+# the _XPG environment variable is not equal to 1 (one), the special
+# positional parameter $0, within a function call, is the name of the
+# function.
+progpath="$0"
+
+# The name of this program:
+progname=`echo "$progpath" | $SED $basename`
+modename="$progname"
+
+# Global variables:
+EXIT_SUCCESS=0
+EXIT_FAILURE=1
+
+PROGRAM=ltmain.sh
+PACKAGE=libtool
+VERSION=1.5.22
+TIMESTAMP=" (1.1220.2.365 2005/12/18 22:14:06)"
+
+# Be Bourne compatible (taken from Autoconf:_AS_BOURNE_COMPATIBLE).
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+ emulate sh
+ NULLCMD=:
+ # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+ # is contrary to our usage. Disable this feature.
+ alias -g '${1+"$@"}'='"$@"'
+ setopt NO_GLOB_SUBST
+else
+ case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
+fi
+
+# Check that we have a working $echo.
+if test "X$1" = X--no-reexec; then
+ # Discard the --no-reexec flag, and continue.
+ shift
+elif test "X$1" = X--fallback-echo; then
+ # Avoid inline document here, it may be left over
+ :
+elif test "X`($echo '\t') 2>/dev/null`" = 'X\t'; then
+ # Yippee, $echo works!
+ :
+else
+ # Restart under the correct shell, and then maybe $echo will work.
+ exec $SHELL "$progpath" --no-reexec ${1+"$@"}
+fi
+
+if test "X$1" = X--fallback-echo; then
+ # used as fallback echo
+ shift
+ cat <<EOF
+$*
+EOF
+ exit $EXIT_SUCCESS
+fi
+
+default_mode=
+help="Try \`$progname --help' for more information."
+magic="%%%MAGIC variable%%%"
+mkdir="mkdir"
+mv="mv -f"
+rm="rm -f"
+
+# Sed substitution that helps us do robust quoting. It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed="${SED}"' -e 1s/^X//'
+sed_quote_subst='s/\([\\`\\"$\\\\]\)/\\\1/g'
+# test EBCDIC or ASCII
+case `echo X|tr X '\101'` in
+ A) # ASCII based system
+ # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
+ SP2NL='tr \040 \012'
+ NL2SP='tr \015\012 \040\040'
+ ;;
+ *) # EBCDIC based system
+ SP2NL='tr \100 \n'
+ NL2SP='tr \r\n \100\100'
+ ;;
+esac
+
+# NLS nuisances.
+# Only set LANG and LC_ALL to C if already set.
+# These must not be set unconditionally because not all systems understand
+# e.g. LANG=C (notably SCO).
+# We save the old values to restore during execute mode.
+for lt_var in LANG LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
+do
+ eval "if test \"\${$lt_var+set}\" = set; then
+ save_$lt_var=\$$lt_var
+ $lt_var=C
+ export $lt_var
+ fi"
+done
+
+# Make sure IFS has a sensible default
+lt_nl='
+'
+IFS=" $lt_nl"
+
+if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
+ $echo "$modename: not configured to build any kind of library" 1>&2
+ $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2
+ exit $EXIT_FAILURE
+fi
+
+# Global variables.
+mode=$default_mode
+nonopt=
+prev=
+prevopt=
+run=
+show="$echo"
+show_help=
+execute_dlfiles=
+duplicate_deps=no
+preserve_args=
+lo2o="s/\\.lo\$/.${objext}/"
+o2lo="s/\\.${objext}\$/.lo/"
+extracted_archives=
+extracted_serial=0
+
+#####################################
+# Shell function definitions:
+# This seems to be the best place for them
+
+# func_mktempdir [string]
+# Make a temporary directory that won't clash with other running
+# libtool processes, and avoids race conditions if possible. If
+# given, STRING is the basename for that directory.
+func_mktempdir ()
+{
+ my_template="${TMPDIR-/tmp}/${1-$progname}"
+
+ if test "$run" = ":"; then
+ # Return a directory name, but don't create it in dry-run mode
+ my_tmpdir="${my_template}-$$"
+ else
+
+ # If mktemp works, use that first and foremost
+ my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null`
+
+ if test ! -d "$my_tmpdir"; then
+ # Failing that, at least try and use $RANDOM to avoid a race
+ my_tmpdir="${my_template}-${RANDOM-0}$$"
+
+ save_mktempdir_umask=`umask`
+ umask 0077
+ $mkdir "$my_tmpdir"
+ umask $save_mktempdir_umask
+ fi
+
+ # If we're not in dry-run mode, bomb out on failure
+ test -d "$my_tmpdir" || {
+ $echo "cannot create temporary directory \`$my_tmpdir'" 1>&2
+ exit $EXIT_FAILURE
+ }
+ fi
+
+ $echo "X$my_tmpdir" | $Xsed
+}
+
+
+# func_win32_libid arg
+# return the library type of file 'arg'
+#
+# Need a lot of goo to handle *both* DLLs and import libs
+# Has to be a shell function in order to 'eat' the argument
+# that is supplied when $file_magic_command is called.
+func_win32_libid ()
+{
+ win32_libid_type="unknown"
+ win32_fileres=`file -L $1 2>/dev/null`
+ case $win32_fileres in
+ *ar\ archive\ import\ library*) # definitely import
+ win32_libid_type="x86 archive import"
+ ;;
+ *ar\ archive*) # could be an import, or static
+ if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | \
+ $EGREP -e 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then
+ win32_nmres=`eval $NM -f posix -A $1 | \
+ $SED -n -e '1,100{/ I /{s,.*,import,;p;q;};}'`
+ case $win32_nmres in
+ import*) win32_libid_type="x86 archive import";;
+ *) win32_libid_type="x86 archive static";;
+ esac
+ fi
+ ;;
+ *DLL*)
+ win32_libid_type="x86 DLL"
+ ;;
+ *executable*) # but shell scripts are "executable" too...
+ case $win32_fileres in
+ *MS\ Windows\ PE\ Intel*)
+ win32_libid_type="x86 DLL"
+ ;;
+ esac
+ ;;
+ esac
+ $echo $win32_libid_type
+}
+
+
+# func_infer_tag arg
+# Infer tagged configuration to use if any are available and
+# if one wasn't chosen via the "--tag" command line option.
+# Only attempt this if the compiler in the base compile
+# command doesn't match the default compiler.
+# arg is usually of the form 'gcc ...'
+func_infer_tag ()
+{
+ if test -n "$available_tags" && test -z "$tagname"; then
+ CC_quoted=
+ for arg in $CC; do
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ CC_quoted="$CC_quoted $arg"
+ done
+ case $@ in
+ # Blanks in the command may have been stripped by the calling shell,
+ # but not from the CC environment variable when configure was run.
+ " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) ;;
+ # Blanks at the start of $base_compile will cause this to fail
+ # if we don't check for them as well.
+ *)
+ for z in $available_tags; do
+ if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then
+ # Evaluate the configuration.
+ eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`"
+ CC_quoted=
+ for arg in $CC; do
+ # Double-quote args containing other shell metacharacters.
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ CC_quoted="$CC_quoted $arg"
+ done
+ case "$@ " in
+ " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*)
+ # The compiler in the base compile command matches
+ # the one in the tagged configuration.
+ # Assume this is the tagged configuration we want.
+ tagname=$z
+ break
+ ;;
+ esac
+ fi
+ done
+ # If $tagname still isn't set, then no tagged configuration
+ # was found and let the user know that the "--tag" command
+ # line option must be used.
+ if test -z "$tagname"; then
+ $echo "$modename: unable to infer tagged configuration"
+ $echo "$modename: specify a tag with \`--tag'" 1>&2
+ exit $EXIT_FAILURE
+# else
+# $echo "$modename: using $tagname tagged configuration"
+ fi
+ ;;
+ esac
+ fi
+}
+
+
+# func_extract_an_archive dir oldlib
+func_extract_an_archive ()
+{
+ f_ex_an_ar_dir="$1"; shift
+ f_ex_an_ar_oldlib="$1"
+
+ $show "(cd $f_ex_an_ar_dir && $AR x $f_ex_an_ar_oldlib)"
+ $run eval "(cd \$f_ex_an_ar_dir && $AR x \$f_ex_an_ar_oldlib)" || exit $?
+ if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
+ :
+ else
+ $echo "$modename: ERROR: object name conflicts: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" 1>&2
+ exit $EXIT_FAILURE
+ fi
+}
+
+# func_extract_archives gentop oldlib ...
+func_extract_archives ()
+{
+ my_gentop="$1"; shift
+ my_oldlibs=${1+"$@"}
+ my_oldobjs=""
+ my_xlib=""
+ my_xabs=""
+ my_xdir=""
+ my_status=""
+
+ $show "${rm}r $my_gentop"
+ $run ${rm}r "$my_gentop"
+ $show "$mkdir $my_gentop"
+ $run $mkdir "$my_gentop"
+ my_status=$?
+ if test "$my_status" -ne 0 && test ! -d "$my_gentop"; then
+ exit $my_status
+ fi
+
+ for my_xlib in $my_oldlibs; do
+ # Extract the objects.
+ case $my_xlib in
+ [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;;
+ *) my_xabs=`pwd`"/$my_xlib" ;;
+ esac
+ my_xlib=`$echo "X$my_xlib" | $Xsed -e 's%^.*/%%'`
+ my_xlib_u=$my_xlib
+ while :; do
+ case " $extracted_archives " in
+ *" $my_xlib_u "*)
+ extracted_serial=`expr $extracted_serial + 1`
+ my_xlib_u=lt$extracted_serial-$my_xlib ;;
+ *) break ;;
+ esac
+ done
+ extracted_archives="$extracted_archives $my_xlib_u"
+ my_xdir="$my_gentop/$my_xlib_u"
+
+ $show "${rm}r $my_xdir"
+ $run ${rm}r "$my_xdir"
+ $show "$mkdir $my_xdir"
+ $run $mkdir "$my_xdir"
+ exit_status=$?
+ if test "$exit_status" -ne 0 && test ! -d "$my_xdir"; then
+ exit $exit_status
+ fi
+ case $host in
+ *-darwin*)
+ $show "Extracting $my_xabs"
+ # Do not bother doing anything if just a dry run
+ if test -z "$run"; then
+ darwin_orig_dir=`pwd`
+ cd $my_xdir || exit $?
+ darwin_archive=$my_xabs
+ darwin_curdir=`pwd`
+ darwin_base_archive=`$echo "X$darwin_archive" | $Xsed -e 's%^.*/%%'`
+ darwin_arches=`lipo -info "$darwin_archive" 2>/dev/null | $EGREP Architectures 2>/dev/null`
+ if test -n "$darwin_arches"; then
+ darwin_arches=`echo "$darwin_arches" | $SED -e 's/.*are://'`
+ darwin_arch=
+ $show "$darwin_base_archive has multiple architectures $darwin_arches"
+ for darwin_arch in $darwin_arches ; do
+ mkdir -p "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+ lipo -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}"
+ cd "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+ func_extract_an_archive "`pwd`" "${darwin_base_archive}"
+ cd "$darwin_curdir"
+ $rm "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}"
+ done # $darwin_arches
+ ## Okay now we have a bunch of thin objects, gotta fatten them up :)
+ darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print| xargs basename | sort -u | $NL2SP`
+ darwin_file=
+ darwin_files=
+ for darwin_file in $darwin_filelist; do
+ darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP`
+ lipo -create -output "$darwin_file" $darwin_files
+ done # $darwin_filelist
+ ${rm}r unfat-$$
+ cd "$darwin_orig_dir"
+ else
+ cd "$darwin_orig_dir"
+ func_extract_an_archive "$my_xdir" "$my_xabs"
+ fi # $darwin_arches
+ fi # $run
+ ;;
+ *)
+ func_extract_an_archive "$my_xdir" "$my_xabs"
+ ;;
+ esac
+ my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP`
+ done
+ func_extract_archives_result="$my_oldobjs"
+}
+# End of Shell function definitions
+#####################################
+
+# Darwin sucks
+eval std_shrext=\"$shrext_cmds\"
+
+disable_libs=no
+
+# Parse our command line options once, thoroughly.
+while test "$#" -gt 0
+do
+ arg="$1"
+ shift
+
+ case $arg in
+ -*=*) optarg=`$echo "X$arg" | $Xsed -e 's/[-_a-zA-Z0-9]*=//'` ;;
+ *) optarg= ;;
+ esac
+
+ # If the previous option needs an argument, assign it.
+ if test -n "$prev"; then
+ case $prev in
+ execute_dlfiles)
+ execute_dlfiles="$execute_dlfiles $arg"
+ ;;
+ tag)
+ tagname="$arg"
+ preserve_args="${preserve_args}=$arg"
+
+ # Check whether tagname contains only valid characters
+ case $tagname in
+ *[!-_A-Za-z0-9,/]*)
+ $echo "$progname: invalid tag name: $tagname" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ case $tagname in
+ CC)
+ # Don't test for the "default" C tag, as we know, it's there, but
+ # not specially marked.
+ ;;
+ *)
+ if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "$progpath" > /dev/null; then
+ taglist="$taglist $tagname"
+ # Evaluate the configuration.
+ eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$tagname'$/,/^# ### END LIBTOOL TAG CONFIG: '$tagname'$/p' < $progpath`"
+ else
+ $echo "$progname: ignoring unknown tag $tagname" 1>&2
+ fi
+ ;;
+ esac
+ ;;
+ *)
+ eval "$prev=\$arg"
+ ;;
+ esac
+
+ prev=
+ prevopt=
+ continue
+ fi
+
+ # Have we seen a non-optional argument yet?
+ case $arg in
+ --help)
+ show_help=yes
+ ;;
+
+ --version)
+ $echo "$PROGRAM (GNU $PACKAGE) $VERSION$TIMESTAMP"
+ $echo
+ $echo "Copyright (C) 2005 Free Software Foundation, Inc."
+ $echo "This is free software; see the source for copying conditions. There is NO"
+ $echo "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+ exit $?
+ ;;
+
+ --config)
+ ${SED} -e '1,/^# ### BEGIN LIBTOOL CONFIG/d' -e '/^# ### END LIBTOOL CONFIG/,$d' $progpath
+ # Now print the configurations for the tags.
+ for tagname in $taglist; do
+ ${SED} -n -e "/^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$/,/^# ### END LIBTOOL TAG CONFIG: $tagname$/p" < "$progpath"
+ done
+ exit $?
+ ;;
+
+ --debug)
+ $echo "$progname: enabling shell trace mode"
+ set -x
+ preserve_args="$preserve_args $arg"
+ ;;
+
+ --dry-run | -n)
+ run=:
+ ;;
+
+ --features)
+ $echo "host: $host"
+ if test "$build_libtool_libs" = yes; then
+ $echo "enable shared libraries"
+ else
+ $echo "disable shared libraries"
+ fi
+ if test "$build_old_libs" = yes; then
+ $echo "enable static libraries"
+ else
+ $echo "disable static libraries"
+ fi
+ exit $?
+ ;;
+
+ --finish) mode="finish" ;;
+
+ --mode) prevopt="--mode" prev=mode ;;
+ --mode=*) mode="$optarg" ;;
+
+ --preserve-dup-deps) duplicate_deps="yes" ;;
+
+ --quiet | --silent)
+ show=:
+ preserve_args="$preserve_args $arg"
+ ;;
+
+ --tag)
+ prevopt="--tag"
+ prev=tag
+ preserve_args="$preserve_args --tag"
+ ;;
+ --tag=*)
+ set tag "$optarg" ${1+"$@"}
+ shift
+ prev=tag
+ preserve_args="$preserve_args --tag"
+ ;;
+
+ -dlopen)
+ prevopt="-dlopen"
+ prev=execute_dlfiles
+ ;;
+
+ -*)
+ $echo "$modename: unrecognized option \`$arg'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+
+ *)
+ nonopt="$arg"
+ break
+ ;;
+ esac
+done
+
+if test -n "$prevopt"; then
+ $echo "$modename: option \`$prevopt' requires an argument" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+fi
+
+case $disable_libs in
+no)
+ ;;
+shared)
+ build_libtool_libs=no
+ build_old_libs=yes
+ ;;
+static)
+ build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`
+ ;;
+esac
+
+# If this variable is set in any of the actions, the command in it
+# will be execed at the end. This prevents here-documents from being
+# left over by shells.
+exec_cmd=
+
+if test -z "$show_help"; then
+
+ # Infer the operation mode.
+ if test -z "$mode"; then
+ $echo "*** Warning: inferring the mode of operation is deprecated." 1>&2
+ $echo "*** Future versions of Libtool will require --mode=MODE be specified." 1>&2
+ case $nonopt in
+ *cc | cc* | *++ | gcc* | *-gcc* | g++* | xlc*)
+ mode=link
+ for arg
+ do
+ case $arg in
+ -c)
+ mode=compile
+ break
+ ;;
+ esac
+ done
+ ;;
+ *db | *dbx | *strace | *truss)
+ mode=execute
+ ;;
+ *install*|cp|mv)
+ mode=install
+ ;;
+ *rm)
+ mode=uninstall
+ ;;
+ *)
+ # If we have no mode, but dlfiles were specified, then do execute mode.
+ test -n "$execute_dlfiles" && mode=execute
+
+ # Just use the default operation mode.
+ if test -z "$mode"; then
+ if test -n "$nonopt"; then
+ $echo "$modename: warning: cannot infer operation mode from \`$nonopt'" 1>&2
+ else
+ $echo "$modename: warning: cannot infer operation mode without MODE-ARGS" 1>&2
+ fi
+ fi
+ ;;
+ esac
+ fi
+
+ # Only execute mode is allowed to have -dlopen flags.
+ if test -n "$execute_dlfiles" && test "$mode" != execute; then
+ $echo "$modename: unrecognized option \`-dlopen'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Change the help message to a mode-specific one.
+ generic_help="$help"
+ help="Try \`$modename --help --mode=$mode' for more information."
+
+ # These modes are in order of execution frequency so that they run quickly.
+ case $mode in
+ # libtool compile mode
+ compile)
+ modename="$modename: compile"
+ # Get the compilation command and the source file.
+ base_compile=
+ srcfile="$nonopt" # always keep a non-empty value in "srcfile"
+ suppress_opt=yes
+ suppress_output=
+ arg_mode=normal
+ libobj=
+ later=
+
+ for arg
+ do
+ case $arg_mode in
+ arg )
+ # do not "continue". Instead, add this to base_compile
+ lastarg="$arg"
+ arg_mode=normal
+ ;;
+
+ target )
+ libobj="$arg"
+ arg_mode=normal
+ continue
+ ;;
+
+ normal )
+ # Accept any command-line options.
+ case $arg in
+ -o)
+ if test -n "$libobj" ; then
+ $echo "$modename: you cannot specify \`-o' more than once" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ arg_mode=target
+ continue
+ ;;
+
+ -static | -prefer-pic | -prefer-non-pic)
+ later="$later $arg"
+ continue
+ ;;
+
+ -no-suppress)
+ suppress_opt=no
+ continue
+ ;;
+
+ -Xcompiler)
+ arg_mode=arg # the next one goes into the "base_compile" arg list
+ continue # The current "srcfile" will either be retained or
+ ;; # replaced later. I would guess that would be a bug.
+
+ -Wc,*)
+ args=`$echo "X$arg" | $Xsed -e "s/^-Wc,//"`
+ lastarg=
+ save_ifs="$IFS"; IFS=','
+ for arg in $args; do
+ IFS="$save_ifs"
+
+ # Double-quote args containing other shell metacharacters.
+ # Many Bourne shells cannot handle close brackets correctly
+ # in scan sets, so we specify it separately.
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ lastarg="$lastarg $arg"
+ done
+ IFS="$save_ifs"
+ lastarg=`$echo "X$lastarg" | $Xsed -e "s/^ //"`
+
+ # Add the arguments to base_compile.
+ base_compile="$base_compile $lastarg"
+ continue
+ ;;
+
+ * )
+ # Accept the current argument as the source file.
+ # The previous "srcfile" becomes the current argument.
+ #
+ lastarg="$srcfile"
+ srcfile="$arg"
+ ;;
+ esac # case $arg
+ ;;
+ esac # case $arg_mode
+
+ # Aesthetically quote the previous argument.
+ lastarg=`$echo "X$lastarg" | $Xsed -e "$sed_quote_subst"`
+
+ case $lastarg in
+ # Double-quote args containing other shell metacharacters.
+ # Many Bourne shells cannot handle close brackets correctly
+ # in scan sets, and some SunOS ksh mistreat backslash-escaping
+ # in scan sets (worked around with variable expansion),
+ # and furthermore cannot handle '|' '&' '(' ')' in scan sets
+ # at all, so we specify them separately.
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ lastarg="\"$lastarg\""
+ ;;
+ esac
+
+ base_compile="$base_compile $lastarg"
+ done # for arg
+
+ case $arg_mode in
+ arg)
+ $echo "$modename: you must specify an argument for -Xcompile"
+ exit $EXIT_FAILURE
+ ;;
+ target)
+ $echo "$modename: you must specify a target with \`-o'" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ *)
+ # Get the name of the library object.
+ [ -z "$libobj" ] && libobj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%'`
+ ;;
+ esac
+
+ # Recognize several different file suffixes.
+ # If the user specifies -o file.o, it is replaced with file.lo
+ xform='[cCFSifmso]'
+ case $libobj in
+ *.ada) xform=ada ;;
+ *.adb) xform=adb ;;
+ *.ads) xform=ads ;;
+ *.asm) xform=asm ;;
+ *.c++) xform=c++ ;;
+ *.cc) xform=cc ;;
+ *.ii) xform=ii ;;
+ *.class) xform=class ;;
+ *.cpp) xform=cpp ;;
+ *.cxx) xform=cxx ;;
+ *.f90) xform=f90 ;;
+ *.for) xform=for ;;
+ *.java) xform=java ;;
+ *.obj) xform=obj ;;
+ esac
+
+ libobj=`$echo "X$libobj" | $Xsed -e "s/\.$xform$/.lo/"`
+
+ case $libobj in
+ *.lo) obj=`$echo "X$libobj" | $Xsed -e "$lo2o"` ;;
+ *)
+ $echo "$modename: cannot determine name of library object from \`$libobj'" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ func_infer_tag $base_compile
+
+ for arg in $later; do
+ case $arg in
+ -static)
+ build_old_libs=yes
+ continue
+ ;;
+
+ -prefer-pic)
+ pic_mode=yes
+ continue
+ ;;
+
+ -prefer-non-pic)
+ pic_mode=no
+ continue
+ ;;
+ esac
+ done
+
+ qlibobj=`$echo "X$libobj" | $Xsed -e "$sed_quote_subst"`
+ case $qlibobj in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ qlibobj="\"$qlibobj\"" ;;
+ esac
+ test "X$libobj" != "X$qlibobj" \
+ && $echo "X$libobj" | grep '[]~#^*{};<>?"'"'"' &()|`$[]' \
+ && $echo "$modename: libobj name \`$libobj' may not contain shell special characters."
+ objname=`$echo "X$obj" | $Xsed -e 's%^.*/%%'`
+ xdir=`$echo "X$obj" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$obj"; then
+ xdir=
+ else
+ xdir=$xdir/
+ fi
+ lobj=${xdir}$objdir/$objname
+
+ if test -z "$base_compile"; then
+ $echo "$modename: you must specify a compilation command" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Delete any leftover library objects.
+ if test "$build_old_libs" = yes; then
+ removelist="$obj $lobj $libobj ${libobj}T"
+ else
+ removelist="$lobj $libobj ${libobj}T"
+ fi
+
+ $run $rm $removelist
+ trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15
+
+ # On Cygwin there's no "real" PIC flag so we must build both object types
+ case $host_os in
+ cygwin* | mingw* | pw32* | os2*)
+ pic_mode=default
+ ;;
+ esac
+ if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then
+ # non-PIC code in shared libraries is not supported
+ pic_mode=default
+ fi
+
+ # Calculate the filename of the output object if compiler does
+ # not support -o with -c
+ if test "$compiler_c_o" = no; then
+ output_obj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext}
+ lockfile="$output_obj.lock"
+ removelist="$removelist $output_obj $lockfile"
+ trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15
+ else
+ output_obj=
+ need_locks=no
+ lockfile=
+ fi
+
+ # Lock this critical section if it is needed
+ # We use this script file to make the link, it avoids creating a new file
+ if test "$need_locks" = yes; then
+ until $run ln "$progpath" "$lockfile" 2>/dev/null; do
+ $show "Waiting for $lockfile to be removed"
+ sleep 2
+ done
+ elif test "$need_locks" = warn; then
+ if test -f "$lockfile"; then
+ $echo "\
+*** ERROR, $lockfile exists and contains:
+`cat $lockfile 2>/dev/null`
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together. If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+ $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+ $echo "$srcfile" > "$lockfile"
+ fi
+
+ if test -n "$fix_srcfile_path"; then
+ eval srcfile=\"$fix_srcfile_path\"
+ fi
+ qsrcfile=`$echo "X$srcfile" | $Xsed -e "$sed_quote_subst"`
+ case $qsrcfile in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ qsrcfile="\"$qsrcfile\"" ;;
+ esac
+
+ $run $rm "$libobj" "${libobj}T"
+
+ # Create a libtool object file (analogous to a ".la" file),
+ # but don't create it if we're doing a dry run.
+ test -z "$run" && cat > ${libobj}T <<EOF
+# $libobj - a libtool object file
+# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# Name of the PIC object.
+EOF
+
+ # Only build a PIC object if we are building libtool libraries.
+ if test "$build_libtool_libs" = yes; then
+ # Without this assignment, base_compile gets emptied.
+ fbsd_hideous_sh_bug=$base_compile
+
+ if test "$pic_mode" != no; then
+ command="$base_compile $qsrcfile $pic_flag"
+ else
+ # Don't build PIC code
+ command="$base_compile $qsrcfile"
+ fi
+
+ if test ! -d "${xdir}$objdir"; then
+ $show "$mkdir ${xdir}$objdir"
+ $run $mkdir ${xdir}$objdir
+ exit_status=$?
+ if test "$exit_status" -ne 0 && test ! -d "${xdir}$objdir"; then
+ exit $exit_status
+ fi
+ fi
+
+ if test -z "$output_obj"; then
+ # Place PIC objects in $objdir
+ command="$command -o $lobj"
+ fi
+
+ $run $rm "$lobj" "$output_obj"
+
+ $show "$command"
+ if $run eval "$command"; then :
+ else
+ test -n "$output_obj" && $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+
+ if test "$need_locks" = warn &&
+ test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
+ $echo "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together. If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+ $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+
+ # Just move the object if needed, then go on to compile the next one
+ if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then
+ $show "$mv $output_obj $lobj"
+ if $run $mv $output_obj $lobj; then :
+ else
+ error=$?
+ $run $rm $removelist
+ exit $error
+ fi
+ fi
+
+ # Append the name of the PIC object to the libtool object file.
+ test -z "$run" && cat >> ${libobj}T <<EOF
+pic_object='$objdir/$objname'
+
+EOF
+
+ # Allow error messages only from the first compilation.
+ if test "$suppress_opt" = yes; then
+ suppress_output=' >/dev/null 2>&1'
+ fi
+ else
+ # No PIC object so indicate it doesn't exist in the libtool
+ # object file.
+ test -z "$run" && cat >> ${libobj}T <<EOF
+pic_object=none
+
+EOF
+ fi
+
+ # Only build a position-dependent object if we build old libraries.
+ if test "$build_old_libs" = yes; then
+ if test "$pic_mode" != yes; then
+ # Don't build PIC code
+ command="$base_compile $qsrcfile"
+ else
+ command="$base_compile $qsrcfile $pic_flag"
+ fi
+ if test "$compiler_c_o" = yes; then
+ command="$command -o $obj"
+ fi
+
+ # Suppress compiler output if we already did a PIC compilation.
+ command="$command$suppress_output"
+ $run $rm "$obj" "$output_obj"
+ $show "$command"
+ if $run eval "$command"; then :
+ else
+ $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+
+ if test "$need_locks" = warn &&
+ test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
+ $echo "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together. If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+ $run $rm $removelist
+ exit $EXIT_FAILURE
+ fi
+
+ # Just move the object if needed
+ if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then
+ $show "$mv $output_obj $obj"
+ if $run $mv $output_obj $obj; then :
+ else
+ error=$?
+ $run $rm $removelist
+ exit $error
+ fi
+ fi
+
+ # Append the name of the non-PIC object the libtool object file.
+ # Only append if the libtool object file exists.
+ test -z "$run" && cat >> ${libobj}T <<EOF
+# Name of the non-PIC object.
+non_pic_object='$objname'
+
+EOF
+ else
+ # Append the name of the non-PIC object the libtool object file.
+ # Only append if the libtool object file exists.
+ test -z "$run" && cat >> ${libobj}T <<EOF
+# Name of the non-PIC object.
+non_pic_object=none
+
+EOF
+ fi
+
+ $run $mv "${libobj}T" "${libobj}"
+
+ # Unlock the critical section if it was locked
+ if test "$need_locks" != no; then
+ $run $rm "$lockfile"
+ fi
+
+ exit $EXIT_SUCCESS
+ ;;
+
+ # libtool link mode
+ link | relink)
+ modename="$modename: link"
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+ # It is impossible to link a dll without this setting, and
+ # we shouldn't force the makefile maintainer to figure out
+ # which system we are compiling for in order to pass an extra
+ # flag for every libtool invocation.
+ # allow_undefined=no
+
+ # FIXME: Unfortunately, there are problems with the above when trying
+ # to make a dll which has undefined symbols, in which case not
+ # even a static library is built. For now, we need to specify
+ # -no-undefined on the libtool link line when we can be certain
+ # that all symbols are satisfied, otherwise we get a static library.
+ allow_undefined=yes
+ ;;
+ *)
+ allow_undefined=yes
+ ;;
+ esac
+ libtool_args="$nonopt"
+ base_compile="$nonopt $@"
+ compile_command="$nonopt"
+ finalize_command="$nonopt"
+
+ compile_rpath=
+ finalize_rpath=
+ compile_shlibpath=
+ finalize_shlibpath=
+ convenience=
+ old_convenience=
+ deplibs=
+ old_deplibs=
+ compiler_flags=
+ linker_flags=
+ dllsearchpath=
+ lib_search_path=`pwd`
+ inst_prefix_dir=
+
+ avoid_version=no
+ dlfiles=
+ dlprefiles=
+ dlself=no
+ export_dynamic=no
+ export_symbols=
+ export_symbols_regex=
+ generated=
+ libobjs=
+ ltlibs=
+ module=no
+ no_install=no
+ objs=
+ non_pic_objects=
+ notinst_path= # paths that contain not-installed libtool libraries
+ precious_files_regex=
+ prefer_static_libs=no
+ preload=no
+ prev=
+ prevarg=
+ release=
+ rpath=
+ xrpath=
+ perm_rpath=
+ temp_rpath=
+ thread_safe=no
+ vinfo=
+ vinfo_number=no
+
+ func_infer_tag $base_compile
+
+ # We need to know -static, to get the right output filenames.
+ for arg
+ do
+ case $arg in
+ -all-static | -static | -static-libtool-libs)
+ case $arg in
+ -all-static)
+ if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then
+ $echo "$modename: warning: complete static linking is impossible in this configuration" 1>&2
+ fi
+ if test -n "$link_static_flag"; then
+ dlopen_self=$dlopen_self_static
+ fi
+ prefer_static_libs=yes
+ ;;
+ -static)
+ if test -z "$pic_flag" && test -n "$link_static_flag"; then
+ dlopen_self=$dlopen_self_static
+ fi
+ prefer_static_libs=built
+ ;;
+ -static-libtool-libs)
+ if test -z "$pic_flag" && test -n "$link_static_flag"; then
+ dlopen_self=$dlopen_self_static
+ fi
+ prefer_static_libs=yes
+ ;;
+ esac
+ build_libtool_libs=no
+ build_old_libs=yes
+ break
+ ;;
+ esac
+ done
+
+ # See if our shared archives depend on static archives.
+ test -n "$old_archive_from_new_cmds" && build_old_libs=yes
+
+ # Go through the arguments, transforming them on the way.
+ while test "$#" -gt 0; do
+ arg="$1"
+ shift
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ qarg=\"`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`\" ### testsuite: skip nested quoting test
+ ;;
+ *) qarg=$arg ;;
+ esac
+ libtool_args="$libtool_args $qarg"
+
+ # If the previous option needs an argument, assign it.
+ if test -n "$prev"; then
+ case $prev in
+ output)
+ compile_command="$compile_command @OUTPUT@"
+ finalize_command="$finalize_command @OUTPUT@"
+ ;;
+ esac
+
+ case $prev in
+ dlfiles|dlprefiles)
+ if test "$preload" = no; then
+ # Add the symbol object into the linking commands.
+ compile_command="$compile_command @SYMFILE@"
+ finalize_command="$finalize_command @SYMFILE@"
+ preload=yes
+ fi
+ case $arg in
+ *.la | *.lo) ;; # We handle these cases below.
+ force)
+ if test "$dlself" = no; then
+ dlself=needless
+ export_dynamic=yes
+ fi
+ prev=
+ continue
+ ;;
+ self)
+ if test "$prev" = dlprefiles; then
+ dlself=yes
+ elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then
+ dlself=yes
+ else
+ dlself=needless
+ export_dynamic=yes
+ fi
+ prev=
+ continue
+ ;;
+ *)
+ if test "$prev" = dlfiles; then
+ dlfiles="$dlfiles $arg"
+ else
+ dlprefiles="$dlprefiles $arg"
+ fi
+ prev=
+ continue
+ ;;
+ esac
+ ;;
+ expsyms)
+ export_symbols="$arg"
+ if test ! -f "$arg"; then
+ $echo "$modename: symbol file \`$arg' does not exist"
+ exit $EXIT_FAILURE
+ fi
+ prev=
+ continue
+ ;;
+ expsyms_regex)
+ export_symbols_regex="$arg"
+ prev=
+ continue
+ ;;
+ inst_prefix)
+ inst_prefix_dir="$arg"
+ prev=
+ continue
+ ;;
+ precious_regex)
+ precious_files_regex="$arg"
+ prev=
+ continue
+ ;;
+ release)
+ release="-$arg"
+ prev=
+ continue
+ ;;
+ objectlist)
+ if test -f "$arg"; then
+ save_arg=$arg
+ moreargs=
+ for fil in `cat $save_arg`
+ do
+# moreargs="$moreargs $fil"
+ arg=$fil
+ # A libtool-controlled object.
+
+ # Check to see that this really is a libtool object.
+ if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ pic_object=
+ non_pic_object=
+
+ # Read the .lo file
+ # If there is no directory component, then add one.
+ case $arg in
+ */* | *\\*) . $arg ;;
+ *) . ./$arg ;;
+ esac
+
+ if test -z "$pic_object" || \
+ test -z "$non_pic_object" ||
+ test "$pic_object" = none && \
+ test "$non_pic_object" = none; then
+ $echo "$modename: cannot find name of object for \`$arg'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Extract subdirectory from the argument.
+ xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$arg"; then
+ xdir=
+ else
+ xdir="$xdir/"
+ fi
+
+ if test "$pic_object" != none; then
+ # Prepend the subdirectory the object is found in.
+ pic_object="$xdir$pic_object"
+
+ if test "$prev" = dlfiles; then
+ if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+ dlfiles="$dlfiles $pic_object"
+ prev=
+ continue
+ else
+ # If libtool objects are unsupported, then we need to preload.
+ prev=dlprefiles
+ fi
+ fi
+
+ # CHECK ME: I think I busted this. -Ossama
+ if test "$prev" = dlprefiles; then
+ # Preload the old-style object.
+ dlprefiles="$dlprefiles $pic_object"
+ prev=
+ fi
+
+ # A PIC object.
+ libobjs="$libobjs $pic_object"
+ arg="$pic_object"
+ fi
+
+ # Non-PIC object.
+ if test "$non_pic_object" != none; then
+ # Prepend the subdirectory the object is found in.
+ non_pic_object="$xdir$non_pic_object"
+
+ # A standard non-PIC object
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ if test -z "$pic_object" || test "$pic_object" = none ; then
+ arg="$non_pic_object"
+ fi
+ else
+ # If the PIC object exists, use it instead.
+ # $xdir was prepended to $pic_object above.
+ non_pic_object="$pic_object"
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ fi
+ else
+ # Only an error if not doing a dry-run.
+ if test -z "$run"; then
+ $echo "$modename: \`$arg' is not a valid libtool object" 1>&2
+ exit $EXIT_FAILURE
+ else
+ # Dry-run case.
+
+ # Extract subdirectory from the argument.
+ xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$arg"; then
+ xdir=
+ else
+ xdir="$xdir/"
+ fi
+
+ pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"`
+ non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"`
+ libobjs="$libobjs $pic_object"
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ fi
+ fi
+ done
+ else
+ $echo "$modename: link input file \`$save_arg' does not exist"
+ exit $EXIT_FAILURE
+ fi
+ arg=$save_arg
+ prev=
+ continue
+ ;;
+ rpath | xrpath)
+ # We need an absolute path.
+ case $arg in
+ [\\/]* | [A-Za-z]:[\\/]*) ;;
+ *)
+ $echo "$modename: only absolute run-paths are allowed" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ if test "$prev" = rpath; then
+ case "$rpath " in
+ *" $arg "*) ;;
+ *) rpath="$rpath $arg" ;;
+ esac
+ else
+ case "$xrpath " in
+ *" $arg "*) ;;
+ *) xrpath="$xrpath $arg" ;;
+ esac
+ fi
+ prev=
+ continue
+ ;;
+ xcompiler)
+ compiler_flags="$compiler_flags $qarg"
+ prev=
+ compile_command="$compile_command $qarg"
+ finalize_command="$finalize_command $qarg"
+ continue
+ ;;
+ xlinker)
+ linker_flags="$linker_flags $qarg"
+ compiler_flags="$compiler_flags $wl$qarg"
+ prev=
+ compile_command="$compile_command $wl$qarg"
+ finalize_command="$finalize_command $wl$qarg"
+ continue
+ ;;
+ xcclinker)
+ linker_flags="$linker_flags $qarg"
+ compiler_flags="$compiler_flags $qarg"
+ prev=
+ compile_command="$compile_command $qarg"
+ finalize_command="$finalize_command $qarg"
+ continue
+ ;;
+ shrext)
+ shrext_cmds="$arg"
+ prev=
+ continue
+ ;;
+ darwin_framework|darwin_framework_skip)
+ test "$prev" = "darwin_framework" && compiler_flags="$compiler_flags $arg"
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ prev=
+ continue
+ ;;
+ *)
+ eval "$prev=\"\$arg\""
+ prev=
+ continue
+ ;;
+ esac
+ fi # test -n "$prev"
+
+ prevarg="$arg"
+
+ case $arg in
+ -all-static)
+ if test -n "$link_static_flag"; then
+ compile_command="$compile_command $link_static_flag"
+ finalize_command="$finalize_command $link_static_flag"
+ fi
+ continue
+ ;;
+
+ -allow-undefined)
+ # FIXME: remove this flag sometime in the future.
+ $echo "$modename: \`-allow-undefined' is deprecated because it is the default" 1>&2
+ continue
+ ;;
+
+ -avoid-version)
+ avoid_version=yes
+ continue
+ ;;
+
+ -dlopen)
+ prev=dlfiles
+ continue
+ ;;
+
+ -dlpreopen)
+ prev=dlprefiles
+ continue
+ ;;
+
+ -export-dynamic)
+ export_dynamic=yes
+ continue
+ ;;
+
+ -export-symbols | -export-symbols-regex)
+ if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
+ $echo "$modename: more than one -exported-symbols argument is not allowed"
+ exit $EXIT_FAILURE
+ fi
+ if test "X$arg" = "X-export-symbols"; then
+ prev=expsyms
+ else
+ prev=expsyms_regex
+ fi
+ continue
+ ;;
+
+ -framework|-arch|-isysroot)
+ case " $CC " in
+ *" ${arg} ${1} "* | *" ${arg} ${1} "*)
+ prev=darwin_framework_skip ;;
+ *) compiler_flags="$compiler_flags $arg"
+ prev=darwin_framework ;;
+ esac
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ continue
+ ;;
+
+ -inst-prefix-dir)
+ prev=inst_prefix
+ continue
+ ;;
+
+ # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*
+ # so, if we see these flags be careful not to treat them like -L
+ -L[A-Z][A-Z]*:*)
+ case $with_gcc/$host in
+ no/*-*-irix* | /*-*-irix*)
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ ;;
+ esac
+ continue
+ ;;
+
+ -L*)
+ dir=`$echo "X$arg" | $Xsed -e 's/^-L//'`
+ # We need an absolute path.
+ case $dir in
+ [\\/]* | [A-Za-z]:[\\/]*) ;;
+ *)
+ absdir=`cd "$dir" && pwd`
+ if test -z "$absdir"; then
+ $echo "$modename: cannot determine absolute directory name of \`$dir'" 1>&2
+ absdir="$dir"
+ notinst_path="$notinst_path $dir"
+ fi
+ dir="$absdir"
+ ;;
+ esac
+ case "$deplibs " in
+ *" -L$dir "*) ;;
+ *)
+ deplibs="$deplibs -L$dir"
+ lib_search_path="$lib_search_path $dir"
+ ;;
+ esac
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+ testbindir=`$echo "X$dir" | $Xsed -e 's*/lib$*/bin*'`
+ case :$dllsearchpath: in
+ *":$dir:"*) ;;
+ *) dllsearchpath="$dllsearchpath:$dir";;
+ esac
+ case :$dllsearchpath: in
+ *":$testbindir:"*) ;;
+ *) dllsearchpath="$dllsearchpath:$testbindir";;
+ esac
+ ;;
+ esac
+ continue
+ ;;
+
+ -l*)
+ if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos*)
+ # These systems don't actually have a C or math library (as such)
+ continue
+ ;;
+ *-*-os2*)
+ # These systems don't actually have a C library (as such)
+ test "X$arg" = "X-lc" && continue
+ ;;
+ *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+ # Do not include libc due to us having libc/libc_r.
+ test "X$arg" = "X-lc" && continue
+ ;;
+ *-*-rhapsody* | *-*-darwin1.[012])
+ # Rhapsody C and math libraries are in the System framework
+ deplibs="$deplibs -framework System"
+ continue
+ ;;
+ *-*-sco3.2v5* | *-*-sco5v6*)
+ # Causes problems with __ctype
+ test "X$arg" = "X-lc" && continue
+ ;;
+ *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+ # Compiler inserts libc in the correct place for threads to work
+ test "X$arg" = "X-lc" && continue
+ ;;
+ esac
+ elif test "X$arg" = "X-lc_r"; then
+ case $host in
+ *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+ # Do not include libc_r directly, use -pthread flag.
+ continue
+ ;;
+ esac
+ fi
+ deplibs="$deplibs $arg"
+ continue
+ ;;
+
+ # Tru64 UNIX uses -model [arg] to determine the layout of C++
+ # classes, name mangling, and exception handling.
+ -model)
+ compile_command="$compile_command $arg"
+ compiler_flags="$compiler_flags $arg"
+ finalize_command="$finalize_command $arg"
+ prev=xcompiler
+ continue
+ ;;
+
+ -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe)
+ compiler_flags="$compiler_flags $arg"
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ continue
+ ;;
+
+ -module)
+ module=yes
+ continue
+ ;;
+
+ # -64, -mips[0-9] enable 64-bit mode on the SGI compiler
+ # -r[0-9][0-9]* specifies the processor on the SGI compiler
+ # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler
+ # +DA*, +DD* enable 64-bit mode on the HP compiler
+ # -q* pass through compiler args for the IBM compiler
+ # -m* pass through architecture-specific compiler args for GCC
+ # -m*, -t[45]*, -txscale* pass through architecture-specific
+ # compiler args for GCC
+ # -pg pass through profiling flag for GCC
+ # @file GCC response files
+ -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*|-pg| \
+ -t[45]*|-txscale*|@*)
+
+ # Unknown arguments in both finalize_command and compile_command need
+ # to be aesthetically quoted because they are evaled later.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ compiler_flags="$compiler_flags $arg"
+ continue
+ ;;
+
+ -shrext)
+ prev=shrext
+ continue
+ ;;
+
+ -no-fast-install)
+ fast_install=no
+ continue
+ ;;
+
+ -no-install)
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+ # The PATH hackery in wrapper scripts is required on Windows
+ # in order for the loader to find any dlls it needs.
+ $echo "$modename: warning: \`-no-install' is ignored for $host" 1>&2
+ $echo "$modename: warning: assuming \`-no-fast-install' instead" 1>&2
+ fast_install=no
+ ;;
+ *) no_install=yes ;;
+ esac
+ continue
+ ;;
+
+ -no-undefined)
+ allow_undefined=no
+ continue
+ ;;
+
+ -objectlist)
+ prev=objectlist
+ continue
+ ;;
+
+ -o) prev=output ;;
+
+ -precious-files-regex)
+ prev=precious_regex
+ continue
+ ;;
+
+ -release)
+ prev=release
+ continue
+ ;;
+
+ -rpath)
+ prev=rpath
+ continue
+ ;;
+
+ -R)
+ prev=xrpath
+ continue
+ ;;
+
+ -R*)
+ dir=`$echo "X$arg" | $Xsed -e 's/^-R//'`
+ # We need an absolute path.
+ case $dir in
+ [\\/]* | [A-Za-z]:[\\/]*) ;;
+ *)
+ $echo "$modename: only absolute run-paths are allowed" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ case "$xrpath " in
+ *" $dir "*) ;;
+ *) xrpath="$xrpath $dir" ;;
+ esac
+ continue
+ ;;
+
+ -static | -static-libtool-libs)
+ # The effects of -static are defined in a previous loop.
+ # We used to do the same as -all-static on platforms that
+ # didn't have a PIC flag, but the assumption that the effects
+ # would be equivalent was wrong. It would break on at least
+ # Digital Unix and AIX.
+ continue
+ ;;
+
+ -thread-safe)
+ thread_safe=yes
+ continue
+ ;;
+
+ -version-info)
+ prev=vinfo
+ continue
+ ;;
+ -version-number)
+ prev=vinfo
+ vinfo_number=yes
+ continue
+ ;;
+
+ -Wc,*)
+ args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wc,//'`
+ arg=
+ save_ifs="$IFS"; IFS=','
+ for flag in $args; do
+ IFS="$save_ifs"
+ case $flag in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ flag="\"$flag\""
+ ;;
+ esac
+ arg="$arg $wl$flag"
+ compiler_flags="$compiler_flags $flag"
+ done
+ IFS="$save_ifs"
+ arg=`$echo "X$arg" | $Xsed -e "s/^ //"`
+ ;;
+
+ -Wl,*)
+ args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wl,//'`
+ arg=
+ save_ifs="$IFS"; IFS=','
+ for flag in $args; do
+ IFS="$save_ifs"
+ case $flag in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ flag="\"$flag\""
+ ;;
+ esac
+ arg="$arg $wl$flag"
+ compiler_flags="$compiler_flags $wl$flag"
+ linker_flags="$linker_flags $flag"
+ done
+ IFS="$save_ifs"
+ arg=`$echo "X$arg" | $Xsed -e "s/^ //"`
+ ;;
+
+ -Xcompiler)
+ prev=xcompiler
+ continue
+ ;;
+
+ -Xlinker)
+ prev=xlinker
+ continue
+ ;;
+
+ -XCClinker)
+ prev=xcclinker
+ continue
+ ;;
+
+ # Some other compiler flag.
+ -* | +*)
+ # Unknown arguments in both finalize_command and compile_command need
+ # to be aesthetically quoted because they are evaled later.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ ;;
+
+ *.$objext)
+ # A standard object.
+ objs="$objs $arg"
+ ;;
+
+ *.lo)
+ # A libtool-controlled object.
+
+ # Check to see that this really is a libtool object.
+ if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ pic_object=
+ non_pic_object=
+
+ # Read the .lo file
+ # If there is no directory component, then add one.
+ case $arg in
+ */* | *\\*) . $arg ;;
+ *) . ./$arg ;;
+ esac
+
+ if test -z "$pic_object" || \
+ test -z "$non_pic_object" ||
+ test "$pic_object" = none && \
+ test "$non_pic_object" = none; then
+ $echo "$modename: cannot find name of object for \`$arg'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Extract subdirectory from the argument.
+ xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$arg"; then
+ xdir=
+ else
+ xdir="$xdir/"
+ fi
+
+ if test "$pic_object" != none; then
+ # Prepend the subdirectory the object is found in.
+ pic_object="$xdir$pic_object"
+
+ if test "$prev" = dlfiles; then
+ if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+ dlfiles="$dlfiles $pic_object"
+ prev=
+ continue
+ else
+ # If libtool objects are unsupported, then we need to preload.
+ prev=dlprefiles
+ fi
+ fi
+
+ # CHECK ME: I think I busted this. -Ossama
+ if test "$prev" = dlprefiles; then
+ # Preload the old-style object.
+ dlprefiles="$dlprefiles $pic_object"
+ prev=
+ fi
+
+ # A PIC object.
+ libobjs="$libobjs $pic_object"
+ arg="$pic_object"
+ fi
+
+ # Non-PIC object.
+ if test "$non_pic_object" != none; then
+ # Prepend the subdirectory the object is found in.
+ non_pic_object="$xdir$non_pic_object"
+
+ # A standard non-PIC object
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ if test -z "$pic_object" || test "$pic_object" = none ; then
+ arg="$non_pic_object"
+ fi
+ else
+ # If the PIC object exists, use it instead.
+ # $xdir was prepended to $pic_object above.
+ non_pic_object="$pic_object"
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ fi
+ else
+ # Only an error if not doing a dry-run.
+ if test -z "$run"; then
+ $echo "$modename: \`$arg' is not a valid libtool object" 1>&2
+ exit $EXIT_FAILURE
+ else
+ # Dry-run case.
+
+ # Extract subdirectory from the argument.
+ xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$xdir" = "X$arg"; then
+ xdir=
+ else
+ xdir="$xdir/"
+ fi
+
+ pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"`
+ non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"`
+ libobjs="$libobjs $pic_object"
+ non_pic_objects="$non_pic_objects $non_pic_object"
+ fi
+ fi
+ ;;
+
+ *.$libext)
+ # An archive.
+ deplibs="$deplibs $arg"
+ old_deplibs="$old_deplibs $arg"
+ continue
+ ;;
+
+ *.la)
+ # A libtool-controlled library.
+
+ if test "$prev" = dlfiles; then
+ # This library was specified with -dlopen.
+ dlfiles="$dlfiles $arg"
+ prev=
+ elif test "$prev" = dlprefiles; then
+ # The library was specified with -dlpreopen.
+ dlprefiles="$dlprefiles $arg"
+ prev=
+ else
+ deplibs="$deplibs $arg"
+ fi
+ continue
+ ;;
+
+ # Some other compiler argument.
+ *)
+ # Unknown arguments in both finalize_command and compile_command need
+ # to be aesthetically quoted because they are evaled later.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ ;;
+ esac # arg
+
+ # Now actually substitute the argument into the commands.
+ if test -n "$arg"; then
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ fi
+ done # argument parsing loop
+
+ if test -n "$prev"; then
+ $echo "$modename: the \`$prevarg' option requires an argument" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then
+ eval arg=\"$export_dynamic_flag_spec\"
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ fi
+
+ oldlibs=
+ # calculate the name of the file, without its directory
+ outputname=`$echo "X$output" | $Xsed -e 's%^.*/%%'`
+ libobjs_save="$libobjs"
+
+ if test -n "$shlibpath_var"; then
+ # get the directories listed in $shlibpath_var
+ eval shlib_search_path=\`\$echo \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\`
+ else
+ shlib_search_path=
+ fi
+ eval sys_lib_search_path=\"$sys_lib_search_path_spec\"
+ eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\"
+
+ output_objdir=`$echo "X$output" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$output_objdir" = "X$output"; then
+ output_objdir="$objdir"
+ else
+ output_objdir="$output_objdir/$objdir"
+ fi
+ # Create the object directory.
+ if test ! -d "$output_objdir"; then
+ $show "$mkdir $output_objdir"
+ $run $mkdir $output_objdir
+ exit_status=$?
+ if test "$exit_status" -ne 0 && test ! -d "$output_objdir"; then
+ exit $exit_status
+ fi
+ fi
+
+ # Determine the type of output
+ case $output in
+ "")
+ $echo "$modename: you must specify an output file" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ *.$libext) linkmode=oldlib ;;
+ *.lo | *.$objext) linkmode=obj ;;
+ *.la) linkmode=lib ;;
+ *) linkmode=prog ;; # Anything else should be a program.
+ esac
+
+ case $host in
+ *cygwin* | *mingw* | *pw32*)
+ # don't eliminate duplications in $postdeps and $predeps
+ duplicate_compiler_generated_deps=yes
+ ;;
+ *)
+ duplicate_compiler_generated_deps=$duplicate_deps
+ ;;
+ esac
+ specialdeplibs=
+
+ libs=
+ # Find all interdependent deplibs by searching for libraries
+ # that are linked more than once (e.g. -la -lb -la)
+ for deplib in $deplibs; do
+ if test "X$duplicate_deps" = "Xyes" ; then
+ case "$libs " in
+ *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+ esac
+ fi
+ libs="$libs $deplib"
+ done
+
+ if test "$linkmode" = lib; then
+ libs="$predeps $libs $compiler_lib_search_path $postdeps"
+
+ # Compute libraries that are listed more than once in $predeps
+ # $postdeps and mark them as special (i.e., whose duplicates are
+ # not to be eliminated).
+ pre_post_deps=
+ if test "X$duplicate_compiler_generated_deps" = "Xyes" ; then
+ for pre_post_dep in $predeps $postdeps; do
+ case "$pre_post_deps " in
+ *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;;
+ esac
+ pre_post_deps="$pre_post_deps $pre_post_dep"
+ done
+ fi
+ pre_post_deps=
+ fi
+
+ deplibs=
+ newdependency_libs=
+ newlib_search_path=
+ need_relink=no # whether we're linking any uninstalled libtool libraries
+ notinst_deplibs= # not-installed libtool libraries
+ case $linkmode in
+ lib)
+ passes="conv link"
+ for file in $dlfiles $dlprefiles; do
+ case $file in
+ *.la) ;;
+ *)
+ $echo "$modename: libraries can \`-dlopen' only libtool libraries: $file" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ done
+ ;;
+ prog)
+ compile_deplibs=
+ finalize_deplibs=
+ alldeplibs=no
+ newdlfiles=
+ newdlprefiles=
+ passes="conv scan dlopen dlpreopen link"
+ ;;
+ *) passes="conv"
+ ;;
+ esac
+ for pass in $passes; do
+ if test "$linkmode,$pass" = "lib,link" ||
+ test "$linkmode,$pass" = "prog,scan"; then
+ libs="$deplibs"
+ deplibs=
+ fi
+ if test "$linkmode" = prog; then
+ case $pass in
+ dlopen) libs="$dlfiles" ;;
+ dlpreopen) libs="$dlprefiles" ;;
+ link) libs="$deplibs %DEPLIBS% $dependency_libs" ;;
+ esac
+ fi
+ if test "$pass" = dlopen; then
+ # Collect dlpreopened libraries
+ save_deplibs="$deplibs"
+ deplibs=
+ fi
+ for deplib in $libs; do
+ lib=
+ found=no
+ case $deplib in
+ -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe)
+ if test "$linkmode,$pass" = "prog,link"; then
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ else
+ compiler_flags="$compiler_flags $deplib"
+ fi
+ continue
+ ;;
+ -l*)
+ if test "$linkmode" != lib && test "$linkmode" != prog; then
+ $echo "$modename: warning: \`-l' is ignored for archives/objects" 1>&2
+ continue
+ fi
+ name=`$echo "X$deplib" | $Xsed -e 's/^-l//'`
+ for searchdir in $newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path; do
+ for search_ext in .la $std_shrext .so .a; do
+ # Search the libtool library
+ lib="$searchdir/lib${name}${search_ext}"
+ if test -f "$lib"; then
+ if test "$search_ext" = ".la"; then
+ found=yes
+ else
+ found=no
+ fi
+ break 2
+ fi
+ done
+ done
+ if test "$found" != yes; then
+ # deplib doesn't seem to be a libtool library
+ if test "$linkmode,$pass" = "prog,link"; then
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ else
+ deplibs="$deplib $deplibs"
+ test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
+ fi
+ continue
+ else # deplib is a libtool library
+ # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,
+ # We need to do some special things here, and not later.
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $deplib "*)
+ if (${SED} -e '2q' $lib |
+ grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ library_names=
+ old_library=
+ case $lib in
+ */* | *\\*) . $lib ;;
+ *) . ./$lib ;;
+ esac
+ for l in $old_library $library_names; do
+ ll="$l"
+ done
+ if test "X$ll" = "X$old_library" ; then # only static version available
+ found=no
+ ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$ladir" = "X$lib" && ladir="."
+ lib=$ladir/$old_library
+ if test "$linkmode,$pass" = "prog,link"; then
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ else
+ deplibs="$deplib $deplibs"
+ test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
+ fi
+ continue
+ fi
+ fi
+ ;;
+ *) ;;
+ esac
+ fi
+ fi
+ ;; # -l
+ -L*)
+ case $linkmode in
+ lib)
+ deplibs="$deplib $deplibs"
+ test "$pass" = conv && continue
+ newdependency_libs="$deplib $newdependency_libs"
+ newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`
+ ;;
+ prog)
+ if test "$pass" = conv; then
+ deplibs="$deplib $deplibs"
+ continue
+ fi
+ if test "$pass" = scan; then
+ deplibs="$deplib $deplibs"
+ else
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ fi
+ newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`
+ ;;
+ *)
+ $echo "$modename: warning: \`-L' is ignored for archives/objects" 1>&2
+ ;;
+ esac # linkmode
+ continue
+ ;; # -L
+ -R*)
+ if test "$pass" = link; then
+ dir=`$echo "X$deplib" | $Xsed -e 's/^-R//'`
+ # Make sure the xrpath contains only unique directories.
+ case "$xrpath " in
+ *" $dir "*) ;;
+ *) xrpath="$xrpath $dir" ;;
+ esac
+ fi
+ deplibs="$deplib $deplibs"
+ continue
+ ;;
+ *.la) lib="$deplib" ;;
+ *.$libext)
+ if test "$pass" = conv; then
+ deplibs="$deplib $deplibs"
+ continue
+ fi
+ case $linkmode in
+ lib)
+ valid_a_lib=no
+ case $deplibs_check_method in
+ match_pattern*)
+ set dummy $deplibs_check_method
+ match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
+ if eval $echo \"$deplib\" 2>/dev/null \
+ | $SED 10q \
+ | $EGREP "$match_pattern_regex" > /dev/null; then
+ valid_a_lib=yes
+ fi
+ ;;
+ pass_all)
+ valid_a_lib=yes
+ ;;
+ esac
+ if test "$valid_a_lib" != yes; then
+ $echo
+ $echo "*** Warning: Trying to link with static lib archive $deplib."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have"
+ $echo "*** because the file extensions .$libext of this argument makes me believe"
+ $echo "*** that it is just a static archive that I should not used here."
+ else
+ $echo
+ $echo "*** Warning: Linking the shared library $output against the"
+ $echo "*** static library $deplib is not portable!"
+ deplibs="$deplib $deplibs"
+ fi
+ continue
+ ;;
+ prog)
+ if test "$pass" != link; then
+ deplibs="$deplib $deplibs"
+ else
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ fi
+ continue
+ ;;
+ esac # linkmode
+ ;; # *.$libext
+ *.lo | *.$objext)
+ if test "$pass" = conv; then
+ deplibs="$deplib $deplibs"
+ elif test "$linkmode" = prog; then
+ if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then
+ # If there is no dlopen support or we're linking statically,
+ # we need to preload.
+ newdlprefiles="$newdlprefiles $deplib"
+ compile_deplibs="$deplib $compile_deplibs"
+ finalize_deplibs="$deplib $finalize_deplibs"
+ else
+ newdlfiles="$newdlfiles $deplib"
+ fi
+ fi
+ continue
+ ;;
+ %DEPLIBS%)
+ alldeplibs=yes
+ continue
+ ;;
+ esac # case $deplib
+ if test "$found" = yes || test -f "$lib"; then :
+ else
+ $echo "$modename: cannot find the library \`$lib' or unhandled argument \`$deplib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Check to see that this really is a libtool archive.
+ if (${SED} -e '2q' $lib | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then :
+ else
+ $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$ladir" = "X$lib" && ladir="."
+
+ dlname=
+ dlopen=
+ dlpreopen=
+ libdir=
+ library_names=
+ old_library=
+ # If the library was installed with an old release of libtool,
+ # it will not redefine variables installed, or shouldnotlink
+ installed=yes
+ shouldnotlink=no
+ avoidtemprpath=
+
+
+ # Read the .la file
+ case $lib in
+ */* | *\\*) . $lib ;;
+ *) . ./$lib ;;
+ esac
+
+ if test "$linkmode,$pass" = "lib,link" ||
+ test "$linkmode,$pass" = "prog,scan" ||
+ { test "$linkmode" != prog && test "$linkmode" != lib; }; then
+ test -n "$dlopen" && dlfiles="$dlfiles $dlopen"
+ test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen"
+ fi
+
+ if test "$pass" = conv; then
+ # Only check for convenience libraries
+ deplibs="$lib $deplibs"
+ if test -z "$libdir"; then
+ if test -z "$old_library"; then
+ $echo "$modename: cannot find name of link library for \`$lib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ # It is a libtool convenience library, so add in its objects.
+ convenience="$convenience $ladir/$objdir/$old_library"
+ old_convenience="$old_convenience $ladir/$objdir/$old_library"
+ tmp_libs=
+ for deplib in $dependency_libs; do
+ deplibs="$deplib $deplibs"
+ if test "X$duplicate_deps" = "Xyes" ; then
+ case "$tmp_libs " in
+ *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+ esac
+ fi
+ tmp_libs="$tmp_libs $deplib"
+ done
+ elif test "$linkmode" != prog && test "$linkmode" != lib; then
+ $echo "$modename: \`$lib' is not a convenience library" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ continue
+ fi # $pass = conv
+
+
+ # Get the name of the library we link against.
+ linklib=
+ for l in $old_library $library_names; do
+ linklib="$l"
+ done
+ if test -z "$linklib"; then
+ $echo "$modename: cannot find name of link library for \`$lib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # This library was specified with -dlopen.
+ if test "$pass" = dlopen; then
+ if test -z "$libdir"; then
+ $echo "$modename: cannot -dlopen a convenience library: \`$lib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ if test -z "$dlname" ||
+ test "$dlopen_support" != yes ||
+ test "$build_libtool_libs" = no; then
+ # If there is no dlname, no dlopen support or we're linking
+ # statically, we need to preload. We also need to preload any
+ # dependent libraries so libltdl's deplib preloader doesn't
+ # bomb out in the load deplibs phase.
+ dlprefiles="$dlprefiles $lib $dependency_libs"
+ else
+ newdlfiles="$newdlfiles $lib"
+ fi
+ continue
+ fi # $pass = dlopen
+
+ # We need an absolute path.
+ case $ladir in
+ [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;;
+ *)
+ abs_ladir=`cd "$ladir" && pwd`
+ if test -z "$abs_ladir"; then
+ $echo "$modename: warning: cannot determine absolute directory name of \`$ladir'" 1>&2
+ $echo "$modename: passing it literally to the linker, although it might fail" 1>&2
+ abs_ladir="$ladir"
+ fi
+ ;;
+ esac
+ laname=`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
+
+ # Find the relevant object directory and library name.
+ if test "X$installed" = Xyes; then
+ if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+ $echo "$modename: warning: library \`$lib' was moved." 1>&2
+ dir="$ladir"
+ absdir="$abs_ladir"
+ libdir="$abs_ladir"
+ else
+ dir="$libdir"
+ absdir="$libdir"
+ fi
+ test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
+ else
+ if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then
+ dir="$ladir"
+ absdir="$abs_ladir"
+ # Remove this search path later
+ notinst_path="$notinst_path $abs_ladir"
+ else
+ dir="$ladir/$objdir"
+ absdir="$abs_ladir/$objdir"
+ # Remove this search path later
+ notinst_path="$notinst_path $abs_ladir"
+ fi
+ fi # $installed = yes
+ name=`$echo "X$laname" | $Xsed -e 's/\.la$//' -e 's/^lib//'`
+
+ # This library was specified with -dlpreopen.
+ if test "$pass" = dlpreopen; then
+ if test -z "$libdir"; then
+ $echo "$modename: cannot -dlpreopen a convenience library: \`$lib'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ # Prefer using a static library (so that no silly _DYNAMIC symbols
+ # are required to link).
+ if test -n "$old_library"; then
+ newdlprefiles="$newdlprefiles $dir/$old_library"
+ # Otherwise, use the dlname, so that lt_dlopen finds it.
+ elif test -n "$dlname"; then
+ newdlprefiles="$newdlprefiles $dir/$dlname"
+ else
+ newdlprefiles="$newdlprefiles $dir/$linklib"
+ fi
+ fi # $pass = dlpreopen
+
+ if test -z "$libdir"; then
+ # Link the convenience library
+ if test "$linkmode" = lib; then
+ deplibs="$dir/$old_library $deplibs"
+ elif test "$linkmode,$pass" = "prog,link"; then
+ compile_deplibs="$dir/$old_library $compile_deplibs"
+ finalize_deplibs="$dir/$old_library $finalize_deplibs"
+ else
+ deplibs="$lib $deplibs" # used for prog,scan pass
+ fi
+ continue
+ fi
+
+
+ if test "$linkmode" = prog && test "$pass" != link; then
+ newlib_search_path="$newlib_search_path $ladir"
+ deplibs="$lib $deplibs"
+
+ linkalldeplibs=no
+ if test "$link_all_deplibs" != no || test -z "$library_names" ||
+ test "$build_libtool_libs" = no; then
+ linkalldeplibs=yes
+ fi
+
+ tmp_libs=
+ for deplib in $dependency_libs; do
+ case $deplib in
+ -L*) newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`;; ### testsuite: skip nested quoting test
+ esac
+ # Need to link against all dependency_libs?
+ if test "$linkalldeplibs" = yes; then
+ deplibs="$deplib $deplibs"
+ else
+ # Need to hardcode shared library paths
+ # or/and link against static libraries
+ newdependency_libs="$deplib $newdependency_libs"
+ fi
+ if test "X$duplicate_deps" = "Xyes" ; then
+ case "$tmp_libs " in
+ *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+ esac
+ fi
+ tmp_libs="$tmp_libs $deplib"
+ done # for deplib
+ continue
+ fi # $linkmode = prog...
+
+ if test "$linkmode,$pass" = "prog,link"; then
+ if test -n "$library_names" &&
+ { { test "$prefer_static_libs" = no ||
+ test "$prefer_static_libs,$installed" = "built,yes"; } ||
+ test -z "$old_library"; }; then
+ # We need to hardcode the library path
+ if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then
+ # Make sure the rpath contains only unique directories.
+ case "$temp_rpath " in
+ *" $dir "*) ;;
+ *" $absdir "*) ;;
+ *) temp_rpath="$temp_rpath $absdir" ;;
+ esac
+ fi
+
+ # Hardcode the library path.
+ # Skip directories that are in the system default run-time
+ # search path.
+ case " $sys_lib_dlsearch_path " in
+ *" $absdir "*) ;;
+ *)
+ case "$compile_rpath " in
+ *" $absdir "*) ;;
+ *) compile_rpath="$compile_rpath $absdir"
+ esac
+ ;;
+ esac
+ case " $sys_lib_dlsearch_path " in
+ *" $libdir "*) ;;
+ *)
+ case "$finalize_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_rpath="$finalize_rpath $libdir"
+ esac
+ ;;
+ esac
+ fi # $linkmode,$pass = prog,link...
+
+ if test "$alldeplibs" = yes &&
+ { test "$deplibs_check_method" = pass_all ||
+ { test "$build_libtool_libs" = yes &&
+ test -n "$library_names"; }; }; then
+ # We only need to search for static libraries
+ continue
+ fi
+ fi
+
+ link_static=no # Whether the deplib will be linked statically
+ use_static_libs=$prefer_static_libs
+ if test "$use_static_libs" = built && test "$installed" = yes ; then
+ use_static_libs=no
+ fi
+ if test -n "$library_names" &&
+ { test "$use_static_libs" = no || test -z "$old_library"; }; then
+ if test "$installed" = no; then
+ notinst_deplibs="$notinst_deplibs $lib"
+ need_relink=yes
+ fi
+ # This is a shared library
+
+ # Warn about portability, can't link against -module's on
+ # some systems (darwin)
+ if test "$shouldnotlink" = yes && test "$pass" = link ; then
+ $echo
+ if test "$linkmode" = prog; then
+ $echo "*** Warning: Linking the executable $output against the loadable module"
+ else
+ $echo "*** Warning: Linking the shared library $output against the loadable module"
+ fi
+ $echo "*** $linklib is not portable!"
+ fi
+ if test "$linkmode" = lib &&
+ test "$hardcode_into_libs" = yes; then
+ # Hardcode the library path.
+ # Skip directories that are in the system default run-time
+ # search path.
+ case " $sys_lib_dlsearch_path " in
+ *" $absdir "*) ;;
+ *)
+ case "$compile_rpath " in
+ *" $absdir "*) ;;
+ *) compile_rpath="$compile_rpath $absdir"
+ esac
+ ;;
+ esac
+ case " $sys_lib_dlsearch_path " in
+ *" $libdir "*) ;;
+ *)
+ case "$finalize_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_rpath="$finalize_rpath $libdir"
+ esac
+ ;;
+ esac
+ fi
+
+ if test -n "$old_archive_from_expsyms_cmds"; then
+ # figure out the soname
+ set dummy $library_names
+ realname="$2"
+ shift; shift
+ libname=`eval \\$echo \"$libname_spec\"`
+ # use dlname if we got it. it's perfectly good, no?
+ if test -n "$dlname"; then
+ soname="$dlname"
+ elif test -n "$soname_spec"; then
+ # bleh windows
+ case $host in
+ *cygwin* | mingw*)
+ major=`expr $current - $age`
+ versuffix="-$major"
+ ;;
+ esac
+ eval soname=\"$soname_spec\"
+ else
+ soname="$realname"
+ fi
+
+ # Make a new name for the extract_expsyms_cmds to use
+ soroot="$soname"
+ soname=`$echo $soroot | ${SED} -e 's/^.*\///'`
+ newlib="libimp-`$echo $soname | ${SED} 's/^lib//;s/\.dll$//'`.a"
+
+ # If the library has no export list, then create one now
+ if test -f "$output_objdir/$soname-def"; then :
+ else
+ $show "extracting exported symbol list from \`$soname'"
+ save_ifs="$IFS"; IFS='~'
+ cmds=$extract_expsyms_cmds
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ fi
+
+ # Create $newlib
+ if test -f "$output_objdir/$newlib"; then :; else
+ $show "generating import library for \`$soname'"
+ save_ifs="$IFS"; IFS='~'
+ cmds=$old_archive_from_expsyms_cmds
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ fi
+ # make sure the library variables are pointing to the new library
+ dir=$output_objdir
+ linklib=$newlib
+ fi # test -n "$old_archive_from_expsyms_cmds"
+
+ if test "$linkmode" = prog || test "$mode" != relink; then
+ add_shlibpath=
+ add_dir=
+ add=
+ lib_linked=yes
+ case $hardcode_action in
+ immediate | unsupported)
+ if test "$hardcode_direct" = no; then
+ add="$dir/$linklib"
+ case $host in
+ *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;;
+ *-*-sysv4*uw2*) add_dir="-L$dir" ;;
+ *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \
+ *-*-unixware7*) add_dir="-L$dir" ;;
+ *-*-darwin* )
+ # if the lib is a module then we can not link against
+ # it, someone is ignoring the new warnings I added
+ if /usr/bin/file -L $add 2> /dev/null |
+ $EGREP ": [^:]* bundle" >/dev/null ; then
+ $echo "** Warning, lib $linklib is a module, not a shared library"
+ if test -z "$old_library" ; then
+ $echo
+ $echo "** And there doesn't seem to be a static archive available"
+ $echo "** The link will probably fail, sorry"
+ else
+ add="$dir/$old_library"
+ fi
+ fi
+ esac
+ elif test "$hardcode_minus_L" = no; then
+ case $host in
+ *-*-sunos*) add_shlibpath="$dir" ;;
+ esac
+ add_dir="-L$dir"
+ add="-l$name"
+ elif test "$hardcode_shlibpath_var" = no; then
+ add_shlibpath="$dir"
+ add="-l$name"
+ else
+ lib_linked=no
+ fi
+ ;;
+ relink)
+ if test "$hardcode_direct" = yes; then
+ add="$dir/$linklib"
+ elif test "$hardcode_minus_L" = yes; then
+ add_dir="-L$dir"
+ # Try looking first in the location we're being installed to.
+ if test -n "$inst_prefix_dir"; then
+ case $libdir in
+ [\\/]*)
+ add_dir="$add_dir -L$inst_prefix_dir$libdir"
+ ;;
+ esac
+ fi
+ add="-l$name"
+ elif test "$hardcode_shlibpath_var" = yes; then
+ add_shlibpath="$dir"
+ add="-l$name"
+ else
+ lib_linked=no
+ fi
+ ;;
+ *) lib_linked=no ;;
+ esac
+
+ if test "$lib_linked" != yes; then
+ $echo "$modename: configuration error: unsupported hardcode properties"
+ exit $EXIT_FAILURE
+ fi
+
+ if test -n "$add_shlibpath"; then
+ case :$compile_shlibpath: in
+ *":$add_shlibpath:"*) ;;
+ *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;;
+ esac
+ fi
+ if test "$linkmode" = prog; then
+ test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs"
+ test -n "$add" && compile_deplibs="$add $compile_deplibs"
+ else
+ test -n "$add_dir" && deplibs="$add_dir $deplibs"
+ test -n "$add" && deplibs="$add $deplibs"
+ if test "$hardcode_direct" != yes && \
+ test "$hardcode_minus_L" != yes && \
+ test "$hardcode_shlibpath_var" = yes; then
+ case :$finalize_shlibpath: in
+ *":$libdir:"*) ;;
+ *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
+ esac
+ fi
+ fi
+ fi
+
+ if test "$linkmode" = prog || test "$mode" = relink; then
+ add_shlibpath=
+ add_dir=
+ add=
+ # Finalize command for both is simple: just hardcode it.
+ if test "$hardcode_direct" = yes; then
+ add="$libdir/$linklib"
+ elif test "$hardcode_minus_L" = yes; then
+ add_dir="-L$libdir"
+ add="-l$name"
+ elif test "$hardcode_shlibpath_var" = yes; then
+ case :$finalize_shlibpath: in
+ *":$libdir:"*) ;;
+ *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;;
+ esac
+ add="-l$name"
+ elif test "$hardcode_automatic" = yes; then
+ if test -n "$inst_prefix_dir" &&
+ test -f "$inst_prefix_dir$libdir/$linklib" ; then
+ add="$inst_prefix_dir$libdir/$linklib"
+ else
+ add="$libdir/$linklib"
+ fi
+ else
+ # We cannot seem to hardcode it, guess we'll fake it.
+ add_dir="-L$libdir"
+ # Try looking first in the location we're being installed to.
+ if test -n "$inst_prefix_dir"; then
+ case $libdir in
+ [\\/]*)
+ add_dir="$add_dir -L$inst_prefix_dir$libdir"
+ ;;
+ esac
+ fi
+ add="-l$name"
+ fi
+
+ if test "$linkmode" = prog; then
+ test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs"
+ test -n "$add" && finalize_deplibs="$add $finalize_deplibs"
+ else
+ test -n "$add_dir" && deplibs="$add_dir $deplibs"
+ test -n "$add" && deplibs="$add $deplibs"
+ fi
+ fi
+ elif test "$linkmode" = prog; then
+ # Here we assume that one of hardcode_direct or hardcode_minus_L
+ # is not unsupported. This is valid on all known static and
+ # shared platforms.
+ if test "$hardcode_direct" != unsupported; then
+ test -n "$old_library" && linklib="$old_library"
+ compile_deplibs="$dir/$linklib $compile_deplibs"
+ finalize_deplibs="$dir/$linklib $finalize_deplibs"
+ else
+ compile_deplibs="-l$name -L$dir $compile_deplibs"
+ finalize_deplibs="-l$name -L$dir $finalize_deplibs"
+ fi
+ elif test "$build_libtool_libs" = yes; then
+ # Not a shared library
+ if test "$deplibs_check_method" != pass_all; then
+ # We're trying link a shared library against a static one
+ # but the system doesn't support it.
+
+ # Just print a warning and add the library to dependency_libs so
+ # that the program can be linked against the static library.
+ $echo
+ $echo "*** Warning: This system can not link to static lib archive $lib."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have."
+ if test "$module" = yes; then
+ $echo "*** But as you try to build a module library, libtool will still create "
+ $echo "*** a static module, that should work as long as the dlopening application"
+ $echo "*** is linked with the -dlopen flag to resolve symbols at runtime."
+ if test -z "$global_symbol_pipe"; then
+ $echo
+ $echo "*** However, this would only work if libtool was able to extract symbol"
+ $echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+ $echo "*** not find such a program. So, this module is probably useless."
+ $echo "*** \`nm' from GNU binutils and a full rebuild may help."
+ fi
+ if test "$build_old_libs" = no; then
+ build_libtool_libs=module
+ build_old_libs=yes
+ else
+ build_libtool_libs=no
+ fi
+ fi
+ else
+ deplibs="$dir/$old_library $deplibs"
+ link_static=yes
+ fi
+ fi # link shared/static library?
+
+ if test "$linkmode" = lib; then
+ if test -n "$dependency_libs" &&
+ { test "$hardcode_into_libs" != yes ||
+ test "$build_old_libs" = yes ||
+ test "$link_static" = yes; }; then
+ # Extract -R from dependency_libs
+ temp_deplibs=
+ for libdir in $dependency_libs; do
+ case $libdir in
+ -R*) temp_xrpath=`$echo "X$libdir" | $Xsed -e 's/^-R//'`
+ case " $xrpath " in
+ *" $temp_xrpath "*) ;;
+ *) xrpath="$xrpath $temp_xrpath";;
+ esac;;
+ *) temp_deplibs="$temp_deplibs $libdir";;
+ esac
+ done
+ dependency_libs="$temp_deplibs"
+ fi
+
+ newlib_search_path="$newlib_search_path $absdir"
+ # Link against this library
+ test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs"
+ # ... and its dependency_libs
+ tmp_libs=
+ for deplib in $dependency_libs; do
+ newdependency_libs="$deplib $newdependency_libs"
+ if test "X$duplicate_deps" = "Xyes" ; then
+ case "$tmp_libs " in
+ *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;;
+ esac
+ fi
+ tmp_libs="$tmp_libs $deplib"
+ done
+
+ if test "$link_all_deplibs" != no; then
+ # Add the search paths of all dependency libraries
+ for deplib in $dependency_libs; do
+ case $deplib in
+ -L*) path="$deplib" ;;
+ *.la)
+ dir=`$echo "X$deplib" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$dir" = "X$deplib" && dir="."
+ # We need an absolute path.
+ case $dir in
+ [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;;
+ *)
+ absdir=`cd "$dir" && pwd`
+ if test -z "$absdir"; then
+ $echo "$modename: warning: cannot determine absolute directory name of \`$dir'" 1>&2
+ absdir="$dir"
+ fi
+ ;;
+ esac
+ if grep "^installed=no" $deplib > /dev/null; then
+ path="$absdir/$objdir"
+ else
+ eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
+ if test -z "$libdir"; then
+ $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ if test "$absdir" != "$libdir"; then
+ $echo "$modename: warning: \`$deplib' seems to be moved" 1>&2
+ fi
+ path="$absdir"
+ fi
+ depdepl=
+ case $host in
+ *-*-darwin*)
+ # we do not want to link against static libs,
+ # but need to link against shared
+ eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib`
+ if test -n "$deplibrary_names" ; then
+ for tmp in $deplibrary_names ; do
+ depdepl=$tmp
+ done
+ if test -f "$path/$depdepl" ; then
+ depdepl="$path/$depdepl"
+ fi
+ # do not add paths which are already there
+ case " $newlib_search_path " in
+ *" $path "*) ;;
+ *) newlib_search_path="$newlib_search_path $path";;
+ esac
+ fi
+ path=""
+ ;;
+ *)
+ path="-L$path"
+ ;;
+ esac
+ ;;
+ -l*)
+ case $host in
+ *-*-darwin*)
+ # Again, we only want to link against shared libraries
+ eval tmp_libs=`$echo "X$deplib" | $Xsed -e "s,^\-l,,"`
+ for tmp in $newlib_search_path ; do
+ if test -f "$tmp/lib$tmp_libs.dylib" ; then
+ eval depdepl="$tmp/lib$tmp_libs.dylib"
+ break
+ fi
+ done
+ path=""
+ ;;
+ *) continue ;;
+ esac
+ ;;
+ *) continue ;;
+ esac
+ case " $deplibs " in
+ *" $path "*) ;;
+ *) deplibs="$path $deplibs" ;;
+ esac
+ case " $deplibs " in
+ *" $depdepl "*) ;;
+ *) deplibs="$depdepl $deplibs" ;;
+ esac
+ done
+ fi # link_all_deplibs != no
+ fi # linkmode = lib
+ done # for deplib in $libs
+ dependency_libs="$newdependency_libs"
+ if test "$pass" = dlpreopen; then
+ # Link the dlpreopened libraries before other libraries
+ for deplib in $save_deplibs; do
+ deplibs="$deplib $deplibs"
+ done
+ fi
+ if test "$pass" != dlopen; then
+ if test "$pass" != conv; then
+ # Make sure lib_search_path contains only unique directories.
+ lib_search_path=
+ for dir in $newlib_search_path; do
+ case "$lib_search_path " in
+ *" $dir "*) ;;
+ *) lib_search_path="$lib_search_path $dir" ;;
+ esac
+ done
+ newlib_search_path=
+ fi
+
+ if test "$linkmode,$pass" != "prog,link"; then
+ vars="deplibs"
+ else
+ vars="compile_deplibs finalize_deplibs"
+ fi
+ for var in $vars dependency_libs; do
+ # Add libraries to $var in reverse order
+ eval tmp_libs=\"\$$var\"
+ new_libs=
+ for deplib in $tmp_libs; do
+ # FIXME: Pedantically, this is the right thing to do, so
+ # that some nasty dependency loop isn't accidentally
+ # broken:
+ #new_libs="$deplib $new_libs"
+ # Pragmatically, this seems to cause very few problems in
+ # practice:
+ case $deplib in
+ -L*) new_libs="$deplib $new_libs" ;;
+ -R*) ;;
+ *)
+ # And here is the reason: when a library appears more
+ # than once as an explicit dependence of a library, or
+ # is implicitly linked in more than once by the
+ # compiler, it is considered special, and multiple
+ # occurrences thereof are not removed. Compare this
+ # with having the same library being listed as a
+ # dependency of multiple other libraries: in this case,
+ # we know (pedantically, we assume) the library does not
+ # need to be listed more than once, so we keep only the
+ # last copy. This is not always right, but it is rare
+ # enough that we require users that really mean to play
+ # such unportable linking tricks to link the library
+ # using -Wl,-lname, so that libtool does not consider it
+ # for duplicate removal.
+ case " $specialdeplibs " in
+ *" $deplib "*) new_libs="$deplib $new_libs" ;;
+ *)
+ case " $new_libs " in
+ *" $deplib "*) ;;
+ *) new_libs="$deplib $new_libs" ;;
+ esac
+ ;;
+ esac
+ ;;
+ esac
+ done
+ tmp_libs=
+ for deplib in $new_libs; do
+ case $deplib in
+ -L*)
+ case " $tmp_libs " in
+ *" $deplib "*) ;;
+ *) tmp_libs="$tmp_libs $deplib" ;;
+ esac
+ ;;
+ *) tmp_libs="$tmp_libs $deplib" ;;
+ esac
+ done
+ eval $var=\"$tmp_libs\"
+ done # for var
+ fi
+ # Last step: remove runtime libs from dependency_libs
+ # (they stay in deplibs)
+ tmp_libs=
+ for i in $dependency_libs ; do
+ case " $predeps $postdeps $compiler_lib_search_path " in
+ *" $i "*)
+ i=""
+ ;;
+ esac
+ if test -n "$i" ; then
+ tmp_libs="$tmp_libs $i"
+ fi
+ done
+ dependency_libs=$tmp_libs
+ done # for pass
+ if test "$linkmode" = prog; then
+ dlfiles="$newdlfiles"
+ dlprefiles="$newdlprefiles"
+ fi
+
+ case $linkmode in
+ oldlib)
+ if test -n "$deplibs"; then
+ $echo "$modename: warning: \`-l' and \`-L' are ignored for archives" 1>&2
+ fi
+
+ if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+ $echo "$modename: warning: \`-dlopen' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$rpath"; then
+ $echo "$modename: warning: \`-rpath' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$xrpath"; then
+ $echo "$modename: warning: \`-R' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info/-version-number' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored for archives" 1>&2
+ fi
+
+ if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
+ $echo "$modename: warning: \`-export-symbols' is ignored for archives" 1>&2
+ fi
+
+ # Now set the variables for building old libraries.
+ build_libtool_libs=no
+ oldlibs="$output"
+ objs="$objs$old_deplibs"
+ ;;
+
+ lib)
+ # Make sure we only generate libraries of the form `libNAME.la'.
+ case $outputname in
+ lib*)
+ name=`$echo "X$outputname" | $Xsed -e 's/\.la$//' -e 's/^lib//'`
+ eval shared_ext=\"$shrext_cmds\"
+ eval libname=\"$libname_spec\"
+ ;;
+ *)
+ if test "$module" = no; then
+ $echo "$modename: libtool library \`$output' must begin with \`lib'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ if test "$need_lib_prefix" != no; then
+ # Add the "lib" prefix for modules if required
+ name=`$echo "X$outputname" | $Xsed -e 's/\.la$//'`
+ eval shared_ext=\"$shrext_cmds\"
+ eval libname=\"$libname_spec\"
+ else
+ libname=`$echo "X$outputname" | $Xsed -e 's/\.la$//'`
+ fi
+ ;;
+ esac
+
+ if test -n "$objs"; then
+ if test "$deplibs_check_method" != pass_all; then
+ $echo "$modename: cannot build libtool library \`$output' from non-libtool objects on this host:$objs" 2>&1
+ exit $EXIT_FAILURE
+ else
+ $echo
+ $echo "*** Warning: Linking the shared library $output against the non-libtool"
+ $echo "*** objects $objs is not portable!"
+ libobjs="$libobjs $objs"
+ fi
+ fi
+
+ if test "$dlself" != no; then
+ $echo "$modename: warning: \`-dlopen self' is ignored for libtool libraries" 1>&2
+ fi
+
+ set dummy $rpath
+ if test "$#" -gt 2; then
+ $echo "$modename: warning: ignoring multiple \`-rpath's for a libtool library" 1>&2
+ fi
+ install_libdir="$2"
+
+ oldlibs=
+ if test -z "$rpath"; then
+ if test "$build_libtool_libs" = yes; then
+ # Building a libtool convenience library.
+ # Some compilers have problems with a `.al' extension so
+ # convenience libraries should have the same extension an
+ # archive normally would.
+ oldlibs="$output_objdir/$libname.$libext $oldlibs"
+ build_libtool_libs=convenience
+ build_old_libs=yes
+ fi
+
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info/-version-number' is ignored for convenience libraries" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored for convenience libraries" 1>&2
+ fi
+ else
+
+ # Parse the version information argument.
+ save_ifs="$IFS"; IFS=':'
+ set dummy $vinfo 0 0 0
+ IFS="$save_ifs"
+
+ if test -n "$8"; then
+ $echo "$modename: too many parameters to \`-version-info'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # convert absolute version numbers to libtool ages
+ # this retains compatibility with .la files and attempts
+ # to make the code below a bit more comprehensible
+
+ case $vinfo_number in
+ yes)
+ number_major="$2"
+ number_minor="$3"
+ number_revision="$4"
+ #
+ # There are really only two kinds -- those that
+ # use the current revision as the major version
+ # and those that subtract age and use age as
+ # a minor version. But, then there is irix
+ # which has an extra 1 added just for fun
+ #
+ case $version_type in
+ darwin|linux|osf|windows|none)
+ current=`expr $number_major + $number_minor`
+ age="$number_minor"
+ revision="$number_revision"
+ ;;
+ freebsd-aout|freebsd-elf|sunos)
+ current="$number_major"
+ revision="$number_minor"
+ age="0"
+ ;;
+ irix|nonstopux)
+ current=`expr $number_major + $number_minor - 1`
+ age="$number_minor"
+ revision="$number_minor"
+ ;;
+ esac
+ ;;
+ no)
+ current="$2"
+ revision="$3"
+ age="$4"
+ ;;
+ esac
+
+ # Check that each of the things are valid numbers.
+ case $current in
+ 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+ *)
+ $echo "$modename: CURRENT \`$current' must be a nonnegative integer" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ case $revision in
+ 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+ *)
+ $echo "$modename: REVISION \`$revision' must be a nonnegative integer" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ case $age in
+ 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
+ *)
+ $echo "$modename: AGE \`$age' must be a nonnegative integer" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ if test "$age" -gt "$current"; then
+ $echo "$modename: AGE \`$age' is greater than the current interface number \`$current'" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Calculate the version variables.
+ major=
+ versuffix=
+ verstring=
+ case $version_type in
+ none) ;;
+
+ darwin)
+ # Like Linux, but with the current version available in
+ # verstring for coding it into the library header
+ major=.`expr $current - $age`
+ versuffix="$major.$age.$revision"
+ # Darwin ld doesn't like 0 for these options...
+ minor_current=`expr $current + 1`
+ verstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision"
+ ;;
+
+ freebsd-aout)
+ major=".$current"
+ versuffix=".$current.$revision";
+ ;;
+
+ freebsd-elf)
+ major=".$current"
+ versuffix=".$current";
+ ;;
+
+ irix | nonstopux)
+ major=`expr $current - $age + 1`
+
+ case $version_type in
+ nonstopux) verstring_prefix=nonstopux ;;
+ *) verstring_prefix=sgi ;;
+ esac
+ verstring="$verstring_prefix$major.$revision"
+
+ # Add in all the interfaces that we are compatible with.
+ loop=$revision
+ while test "$loop" -ne 0; do
+ iface=`expr $revision - $loop`
+ loop=`expr $loop - 1`
+ verstring="$verstring_prefix$major.$iface:$verstring"
+ done
+
+ # Before this point, $major must not contain `.'.
+ major=.$major
+ versuffix="$major.$revision"
+ ;;
+
+ linux)
+ major=.`expr $current - $age`
+ versuffix="$major.$age.$revision"
+ ;;
+
+ osf)
+ major=.`expr $current - $age`
+ versuffix=".$current.$age.$revision"
+ verstring="$current.$age.$revision"
+
+ # Add in all the interfaces that we are compatible with.
+ loop=$age
+ while test "$loop" -ne 0; do
+ iface=`expr $current - $loop`
+ loop=`expr $loop - 1`
+ verstring="$verstring:${iface}.0"
+ done
+
+ # Make executables depend on our current version.
+ verstring="$verstring:${current}.0"
+ ;;
+
+ sunos)
+ major=".$current"
+ versuffix=".$current.$revision"
+ ;;
+
+ windows)
+ # Use '-' rather than '.', since we only want one
+ # extension on DOS 8.3 filesystems.
+ major=`expr $current - $age`
+ versuffix="-$major"
+ ;;
+
+ *)
+ $echo "$modename: unknown library version type \`$version_type'" 1>&2
+ $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ # Clear the version info if we defaulted, and they specified a release.
+ if test -z "$vinfo" && test -n "$release"; then
+ major=
+ case $version_type in
+ darwin)
+ # we can't check for "0.0" in archive_cmds due to quoting
+ # problems, so we reset it completely
+ verstring=
+ ;;
+ *)
+ verstring="0.0"
+ ;;
+ esac
+ if test "$need_version" = no; then
+ versuffix=
+ else
+ versuffix=".0.0"
+ fi
+ fi
+
+ # Remove version info from name if versioning should be avoided
+ if test "$avoid_version" = yes && test "$need_version" = no; then
+ major=
+ versuffix=
+ verstring=""
+ fi
+
+ # Check to see if the archive will have undefined symbols.
+ if test "$allow_undefined" = yes; then
+ if test "$allow_undefined_flag" = unsupported; then
+ $echo "$modename: warning: undefined symbols not allowed in $host shared libraries" 1>&2
+ build_libtool_libs=no
+ build_old_libs=yes
+ fi
+ else
+ # Don't allow undefined symbols.
+ allow_undefined_flag="$no_undefined_flag"
+ fi
+ fi
+
+ if test "$mode" != relink; then
+ # Remove our outputs, but don't remove object files since they
+ # may have been created when compiling PIC objects.
+ removelist=
+ tempremovelist=`$echo "$output_objdir/*"`
+ for p in $tempremovelist; do
+ case $p in
+ *.$objext)
+ ;;
+ $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*)
+ if test "X$precious_files_regex" != "X"; then
+ if echo $p | $EGREP -e "$precious_files_regex" >/dev/null 2>&1
+ then
+ continue
+ fi
+ fi
+ removelist="$removelist $p"
+ ;;
+ *) ;;
+ esac
+ done
+ if test -n "$removelist"; then
+ $show "${rm}r $removelist"
+ $run ${rm}r $removelist
+ fi
+ fi
+
+ # Now set the variables for building old libraries.
+ if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then
+ oldlibs="$oldlibs $output_objdir/$libname.$libext"
+
+ # Transform .lo files to .o files.
+ oldobjs="$objs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP`
+ fi
+
+ # Eliminate all temporary directories.
+# for path in $notinst_path; do
+# lib_search_path=`$echo "$lib_search_path " | ${SED} -e "s% $path % %g"`
+# deplibs=`$echo "$deplibs " | ${SED} -e "s% -L$path % %g"`
+# dependency_libs=`$echo "$dependency_libs " | ${SED} -e "s% -L$path % %g"`
+# done
+
+ if test -n "$xrpath"; then
+ # If the user specified any rpath flags, then add them.
+ temp_xrpath=
+ for libdir in $xrpath; do
+ temp_xrpath="$temp_xrpath -R$libdir"
+ case "$finalize_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_rpath="$finalize_rpath $libdir" ;;
+ esac
+ done
+ if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then
+ dependency_libs="$temp_xrpath $dependency_libs"
+ fi
+ fi
+
+ # Make sure dlfiles contains only unique files that won't be dlpreopened
+ old_dlfiles="$dlfiles"
+ dlfiles=
+ for lib in $old_dlfiles; do
+ case " $dlprefiles $dlfiles " in
+ *" $lib "*) ;;
+ *) dlfiles="$dlfiles $lib" ;;
+ esac
+ done
+
+ # Make sure dlprefiles contains only unique files
+ old_dlprefiles="$dlprefiles"
+ dlprefiles=
+ for lib in $old_dlprefiles; do
+ case "$dlprefiles " in
+ *" $lib "*) ;;
+ *) dlprefiles="$dlprefiles $lib" ;;
+ esac
+ done
+
+ if test "$build_libtool_libs" = yes; then
+ if test -n "$rpath"; then
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos*)
+ # these systems don't actually have a c library (as such)!
+ ;;
+ *-*-rhapsody* | *-*-darwin1.[012])
+ # Rhapsody C library is in the System framework
+ deplibs="$deplibs -framework System"
+ ;;
+ *-*-netbsd*)
+ # Don't link with libc until the a.out ld.so is fixed.
+ ;;
+ *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+ # Do not include libc due to us having libc/libc_r.
+ ;;
+ *-*-sco3.2v5* | *-*-sco5v6*)
+ # Causes problems with __ctype
+ ;;
+ *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
+ # Compiler inserts libc in the correct place for threads to work
+ ;;
+ *)
+ # Add libc to deplibs on all other systems if necessary.
+ if test "$build_libtool_need_lc" = "yes"; then
+ deplibs="$deplibs -lc"
+ fi
+ ;;
+ esac
+ fi
+
+ # Transform deplibs into only deplibs that can be linked in shared.
+ name_save=$name
+ libname_save=$libname
+ release_save=$release
+ versuffix_save=$versuffix
+ major_save=$major
+ # I'm not sure if I'm treating the release correctly. I think
+ # release should show up in the -l (ie -lgmp5) so we don't want to
+ # add it in twice. Is that correct?
+ release=""
+ versuffix=""
+ major=""
+ newdeplibs=
+ droppeddeps=no
+ case $deplibs_check_method in
+ pass_all)
+ # Don't check for shared/static. Everything works.
+ # This might be a little naive. We might want to check
+ # whether the library exists or not. But this is on
+ # osf3 & osf4 and I'm not really sure... Just
+ # implementing what was already the behavior.
+ newdeplibs=$deplibs
+ ;;
+ test_compile)
+ # This code stresses the "libraries are programs" paradigm to its
+ # limits. Maybe even breaks it. We compile a program, linking it
+ # against the deplibs as a proxy for the library. Then we can check
+ # whether they linked in statically or dynamically with ldd.
+ $rm conftest.c
+ cat > conftest.c <<EOF
+ int main() { return 0; }
+EOF
+ $rm conftest
+ if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then
+ ldd_output=`ldd conftest`
+ for i in $deplibs; do
+ name=`expr $i : '-l\(.*\)'`
+ # If $name is empty we are operating on a -L argument.
+ if test "$name" != "" && test "$name" != "0"; then
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $i "*)
+ newdeplibs="$newdeplibs $i"
+ i=""
+ ;;
+ esac
+ fi
+ if test -n "$i" ; then
+ libname=`eval \\$echo \"$libname_spec\"`
+ deplib_matches=`eval \\$echo \"$library_names_spec\"`
+ set dummy $deplib_matches
+ deplib_match=$2
+ if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+ newdeplibs="$newdeplibs $i"
+ else
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning: dynamic linker does not accept needed library $i."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which I believe you do not have"
+ $echo "*** because a test_compile did reveal that the linker did not use it for"
+ $echo "*** its dynamic dependency list that programs get resolved with at runtime."
+ fi
+ fi
+ else
+ newdeplibs="$newdeplibs $i"
+ fi
+ done
+ else
+ # Error occurred in the first compile. Let's try to salvage
+ # the situation: Compile a separate program for each library.
+ for i in $deplibs; do
+ name=`expr $i : '-l\(.*\)'`
+ # If $name is empty we are operating on a -L argument.
+ if test "$name" != "" && test "$name" != "0"; then
+ $rm conftest
+ if $LTCC $LTCFLAGS -o conftest conftest.c $i; then
+ ldd_output=`ldd conftest`
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $i "*)
+ newdeplibs="$newdeplibs $i"
+ i=""
+ ;;
+ esac
+ fi
+ if test -n "$i" ; then
+ libname=`eval \\$echo \"$libname_spec\"`
+ deplib_matches=`eval \\$echo \"$library_names_spec\"`
+ set dummy $deplib_matches
+ deplib_match=$2
+ if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+ newdeplibs="$newdeplibs $i"
+ else
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning: dynamic linker does not accept needed library $i."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have"
+ $echo "*** because a test_compile did reveal that the linker did not use this one"
+ $echo "*** as a dynamic dependency that programs can get resolved with at runtime."
+ fi
+ fi
+ else
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning! Library $i is needed by this library but I was not able to"
+ $echo "*** make it link in! You will probably need to install it or some"
+ $echo "*** library that it depends on before this library will be fully"
+ $echo "*** functional. Installing it before continuing would be even better."
+ fi
+ else
+ newdeplibs="$newdeplibs $i"
+ fi
+ done
+ fi
+ ;;
+ file_magic*)
+ set dummy $deplibs_check_method
+ file_magic_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
+ for a_deplib in $deplibs; do
+ name=`expr $a_deplib : '-l\(.*\)'`
+ # If $name is empty we are operating on a -L argument.
+ if test "$name" != "" && test "$name" != "0"; then
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $a_deplib "*)
+ newdeplibs="$newdeplibs $a_deplib"
+ a_deplib=""
+ ;;
+ esac
+ fi
+ if test -n "$a_deplib" ; then
+ libname=`eval \\$echo \"$libname_spec\"`
+ for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
+ potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
+ for potent_lib in $potential_libs; do
+ # Follow soft links.
+ if ls -lLd "$potent_lib" 2>/dev/null \
+ | grep " -> " >/dev/null; then
+ continue
+ fi
+ # The statement above tries to avoid entering an
+ # endless loop below, in case of cyclic links.
+ # We might still enter an endless loop, since a link
+ # loop can be closed while we follow links,
+ # but so what?
+ potlib="$potent_lib"
+ while test -h "$potlib" 2>/dev/null; do
+ potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'`
+ case $potliblink in
+ [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";;
+ *) potlib=`$echo "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";;
+ esac
+ done
+ if eval $file_magic_cmd \"\$potlib\" 2>/dev/null \
+ | ${SED} 10q \
+ | $EGREP "$file_magic_regex" > /dev/null; then
+ newdeplibs="$newdeplibs $a_deplib"
+ a_deplib=""
+ break 2
+ fi
+ done
+ done
+ fi
+ if test -n "$a_deplib" ; then
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning: linker path does not have real file for library $a_deplib."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have"
+ $echo "*** because I did check the linker path looking for a file starting"
+ if test -z "$potlib" ; then
+ $echo "*** with $libname but no candidates were found. (...for file magic test)"
+ else
+ $echo "*** with $libname and none of the candidates passed a file format test"
+ $echo "*** using a file magic. Last file checked: $potlib"
+ fi
+ fi
+ else
+ # Add a -L argument.
+ newdeplibs="$newdeplibs $a_deplib"
+ fi
+ done # Gone through all deplibs.
+ ;;
+ match_pattern*)
+ set dummy $deplibs_check_method
+ match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"`
+ for a_deplib in $deplibs; do
+ name=`expr $a_deplib : '-l\(.*\)'`
+ # If $name is empty we are operating on a -L argument.
+ if test -n "$name" && test "$name" != "0"; then
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ case " $predeps $postdeps " in
+ *" $a_deplib "*)
+ newdeplibs="$newdeplibs $a_deplib"
+ a_deplib=""
+ ;;
+ esac
+ fi
+ if test -n "$a_deplib" ; then
+ libname=`eval \\$echo \"$libname_spec\"`
+ for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
+ potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
+ for potent_lib in $potential_libs; do
+ potlib="$potent_lib" # see symlink-check above in file_magic test
+ if eval $echo \"$potent_lib\" 2>/dev/null \
+ | ${SED} 10q \
+ | $EGREP "$match_pattern_regex" > /dev/null; then
+ newdeplibs="$newdeplibs $a_deplib"
+ a_deplib=""
+ break 2
+ fi
+ done
+ done
+ fi
+ if test -n "$a_deplib" ; then
+ droppeddeps=yes
+ $echo
+ $echo "*** Warning: linker path does not have real file for library $a_deplib."
+ $echo "*** I have the capability to make that library automatically link in when"
+ $echo "*** you link to this library. But I can only do this if you have a"
+ $echo "*** shared version of the library, which you do not appear to have"
+ $echo "*** because I did check the linker path looking for a file starting"
+ if test -z "$potlib" ; then
+ $echo "*** with $libname but no candidates were found. (...for regex pattern test)"
+ else
+ $echo "*** with $libname and none of the candidates passed a file format test"
+ $echo "*** using a regex pattern. Last file checked: $potlib"
+ fi
+ fi
+ else
+ # Add a -L argument.
+ newdeplibs="$newdeplibs $a_deplib"
+ fi
+ done # Gone through all deplibs.
+ ;;
+ none | unknown | *)
+ newdeplibs=""
+ tmp_deplibs=`$echo "X $deplibs" | $Xsed -e 's/ -lc$//' \
+ -e 's/ -[LR][^ ]*//g'`
+ if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+ for i in $predeps $postdeps ; do
+ # can't use Xsed below, because $i might contain '/'
+ tmp_deplibs=`$echo "X $tmp_deplibs" | ${SED} -e "1s,^X,," -e "s,$i,,"`
+ done
+ fi
+ if $echo "X $tmp_deplibs" | $Xsed -e 's/[ ]//g' \
+ | grep . >/dev/null; then
+ $echo
+ if test "X$deplibs_check_method" = "Xnone"; then
+ $echo "*** Warning: inter-library dependencies are not supported in this platform."
+ else
+ $echo "*** Warning: inter-library dependencies are not known to be supported."
+ fi
+ $echo "*** All declared inter-library dependencies are being dropped."
+ droppeddeps=yes
+ fi
+ ;;
+ esac
+ versuffix=$versuffix_save
+ major=$major_save
+ release=$release_save
+ libname=$libname_save
+ name=$name_save
+
+ case $host in
+ *-*-rhapsody* | *-*-darwin1.[012])
+ # On Rhapsody replace the C library is the System framework
+ newdeplibs=`$echo "X $newdeplibs" | $Xsed -e 's/ -lc / -framework System /'`
+ ;;
+ esac
+
+ if test "$droppeddeps" = yes; then
+ if test "$module" = yes; then
+ $echo
+ $echo "*** Warning: libtool could not satisfy all declared inter-library"
+ $echo "*** dependencies of module $libname. Therefore, libtool will create"
+ $echo "*** a static module, that should work as long as the dlopening"
+ $echo "*** application is linked with the -dlopen flag."
+ if test -z "$global_symbol_pipe"; then
+ $echo
+ $echo "*** However, this would only work if libtool was able to extract symbol"
+ $echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+ $echo "*** not find such a program. So, this module is probably useless."
+ $echo "*** \`nm' from GNU binutils and a full rebuild may help."
+ fi
+ if test "$build_old_libs" = no; then
+ oldlibs="$output_objdir/$libname.$libext"
+ build_libtool_libs=module
+ build_old_libs=yes
+ else
+ build_libtool_libs=no
+ fi
+ else
+ $echo "*** The inter-library dependencies that have been dropped here will be"
+ $echo "*** automatically added whenever a program is linked with this library"
+ $echo "*** or is declared to -dlopen it."
+
+ if test "$allow_undefined" = no; then
+ $echo
+ $echo "*** Since this library must not contain undefined symbols,"
+ $echo "*** because either the platform does not support them or"
+ $echo "*** it was explicitly requested with -no-undefined,"
+ $echo "*** libtool will only create a static version of it."
+ if test "$build_old_libs" = no; then
+ oldlibs="$output_objdir/$libname.$libext"
+ build_libtool_libs=module
+ build_old_libs=yes
+ else
+ build_libtool_libs=no
+ fi
+ fi
+ fi
+ fi
+ # Done checking deplibs!
+ deplibs=$newdeplibs
+ fi
+
+
+ # move library search paths that coincide with paths to not yet
+ # installed libraries to the beginning of the library search list
+ new_libs=
+ for path in $notinst_path; do
+ case " $new_libs " in
+ *" -L$path/$objdir "*) ;;
+ *)
+ case " $deplibs " in
+ *" -L$path/$objdir "*)
+ new_libs="$new_libs -L$path/$objdir" ;;
+ esac
+ ;;
+ esac
+ done
+ for deplib in $deplibs; do
+ case $deplib in
+ -L*)
+ case " $new_libs " in
+ *" $deplib "*) ;;
+ *) new_libs="$new_libs $deplib" ;;
+ esac
+ ;;
+ *) new_libs="$new_libs $deplib" ;;
+ esac
+ done
+ deplibs="$new_libs"
+
+
+ # All the library-specific variables (install_libdir is set above).
+ library_names=
+ old_library=
+ dlname=
+
+ # Test again, we may have decided not to build it any more
+ if test "$build_libtool_libs" = yes; then
+ if test "$hardcode_into_libs" = yes; then
+ # Hardcode the library paths
+ hardcode_libdirs=
+ dep_rpath=
+ rpath="$finalize_rpath"
+ test "$mode" != relink && rpath="$compile_rpath$rpath"
+ for libdir in $rpath; do
+ if test -n "$hardcode_libdir_flag_spec"; then
+ if test -n "$hardcode_libdir_separator"; then
+ if test -z "$hardcode_libdirs"; then
+ hardcode_libdirs="$libdir"
+ else
+ # Just accumulate the unique libdirs.
+ case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+ *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+ ;;
+ *)
+ hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+ ;;
+ esac
+ fi
+ else
+ eval flag=\"$hardcode_libdir_flag_spec\"
+ dep_rpath="$dep_rpath $flag"
+ fi
+ elif test -n "$runpath_var"; then
+ case "$perm_rpath " in
+ *" $libdir "*) ;;
+ *) perm_rpath="$perm_rpath $libdir" ;;
+ esac
+ fi
+ done
+ # Substitute the hardcoded libdirs into the rpath.
+ if test -n "$hardcode_libdir_separator" &&
+ test -n "$hardcode_libdirs"; then
+ libdir="$hardcode_libdirs"
+ if test -n "$hardcode_libdir_flag_spec_ld"; then
+ eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\"
+ else
+ eval dep_rpath=\"$hardcode_libdir_flag_spec\"
+ fi
+ fi
+ if test -n "$runpath_var" && test -n "$perm_rpath"; then
+ # We should set the runpath_var.
+ rpath=
+ for dir in $perm_rpath; do
+ rpath="$rpath$dir:"
+ done
+ eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var"
+ fi
+ test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs"
+ fi
+
+ shlibpath="$finalize_shlibpath"
+ test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
+ if test -n "$shlibpath"; then
+ eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var"
+ fi
+
+ # Get the real and link names of the library.
+ eval shared_ext=\"$shrext_cmds\"
+ eval library_names=\"$library_names_spec\"
+ set dummy $library_names
+ realname="$2"
+ shift; shift
+
+ if test -n "$soname_spec"; then
+ eval soname=\"$soname_spec\"
+ else
+ soname="$realname"
+ fi
+ if test -z "$dlname"; then
+ dlname=$soname
+ fi
+
+ lib="$output_objdir/$realname"
+ linknames=
+ for link
+ do
+ linknames="$linknames $link"
+ done
+
+ # Use standard objects if they are pic
+ test -z "$pic_flag" && libobjs=`$echo "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+
+ # Prepare the list of exported symbols
+ if test -z "$export_symbols"; then
+ if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then
+ $show "generating symbol list for \`$libname.la'"
+ export_symbols="$output_objdir/$libname.exp"
+ $run $rm $export_symbols
+ cmds=$export_symbols_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ if len=`expr "X$cmd" : ".*"` &&
+ test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ skipped_export=false
+ else
+ # The command line is too long to execute in one step.
+ $show "using reloadable object file for export list..."
+ skipped_export=:
+ # Break out early, otherwise skipped_export may be
+ # set to false by a later but shorter cmd.
+ break
+ fi
+ done
+ IFS="$save_ifs"
+ if test -n "$export_symbols_regex"; then
+ $show "$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\""
+ $run eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
+ $show "$mv \"${export_symbols}T\" \"$export_symbols\""
+ $run eval '$mv "${export_symbols}T" "$export_symbols"'
+ fi
+ fi
+ fi
+
+ if test -n "$export_symbols" && test -n "$include_expsyms"; then
+ $run eval '$echo "X$include_expsyms" | $SP2NL >> "$export_symbols"'
+ fi
+
+ tmp_deplibs=
+ for test_deplib in $deplibs; do
+ case " $convenience " in
+ *" $test_deplib "*) ;;
+ *)
+ tmp_deplibs="$tmp_deplibs $test_deplib"
+ ;;
+ esac
+ done
+ deplibs="$tmp_deplibs"
+
+ if test -n "$convenience"; then
+ if test -n "$whole_archive_flag_spec"; then
+ save_libobjs=$libobjs
+ eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
+ else
+ gentop="$output_objdir/${outputname}x"
+ generated="$generated $gentop"
+
+ func_extract_archives $gentop $convenience
+ libobjs="$libobjs $func_extract_archives_result"
+ fi
+ fi
+
+ if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then
+ eval flag=\"$thread_safe_flag_spec\"
+ linker_flags="$linker_flags $flag"
+ fi
+
+ # Make a backup of the uninstalled library when relinking
+ if test "$mode" = relink; then
+ $run eval '(cd $output_objdir && $rm ${realname}U && $mv $realname ${realname}U)' || exit $?
+ fi
+
+ # Do each of the archive commands.
+ if test "$module" = yes && test -n "$module_cmds" ; then
+ if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
+ eval test_cmds=\"$module_expsym_cmds\"
+ cmds=$module_expsym_cmds
+ else
+ eval test_cmds=\"$module_cmds\"
+ cmds=$module_cmds
+ fi
+ else
+ if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+ eval test_cmds=\"$archive_expsym_cmds\"
+ cmds=$archive_expsym_cmds
+ else
+ eval test_cmds=\"$archive_cmds\"
+ cmds=$archive_cmds
+ fi
+ fi
+
+ if test "X$skipped_export" != "X:" &&
+ len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
+ test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+ :
+ else
+ # The command line is too long to link in one step, link piecewise.
+ $echo "creating reloadable object files..."
+
+ # Save the value of $output and $libobjs because we want to
+ # use them later. If we have whole_archive_flag_spec, we
+ # want to use save_libobjs as it was before
+ # whole_archive_flag_spec was expanded, because we can't
+ # assume the linker understands whole_archive_flag_spec.
+ # This may have to be revisited, in case too many
+ # convenience libraries get linked in and end up exceeding
+ # the spec.
+ if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then
+ save_libobjs=$libobjs
+ fi
+ save_output=$output
+ output_la=`$echo "X$output" | $Xsed -e "$basename"`
+
+ # Clear the reloadable object creation command queue and
+ # initialize k to one.
+ test_cmds=
+ concat_cmds=
+ objlist=
+ delfiles=
+ last_robj=
+ k=1
+ output=$output_objdir/$output_la-${k}.$objext
+ # Loop over the list of objects to be linked.
+ for obj in $save_libobjs
+ do
+ eval test_cmds=\"$reload_cmds $objlist $last_robj\"
+ if test "X$objlist" = X ||
+ { len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
+ test "$len" -le "$max_cmd_len"; }; then
+ objlist="$objlist $obj"
+ else
+ # The command $test_cmds is almost too long, add a
+ # command to the queue.
+ if test "$k" -eq 1 ; then
+ # The first file doesn't have a previous command to add.
+ eval concat_cmds=\"$reload_cmds $objlist $last_robj\"
+ else
+ # All subsequent reloadable object files will link in
+ # the last one created.
+ eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj\"
+ fi
+ last_robj=$output_objdir/$output_la-${k}.$objext
+ k=`expr $k + 1`
+ output=$output_objdir/$output_la-${k}.$objext
+ objlist=$obj
+ len=1
+ fi
+ done
+ # Handle the remaining objects by creating one last
+ # reloadable object file. All subsequent reloadable object
+ # files will link in the last one created.
+ test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+ eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\"
+
+ if ${skipped_export-false}; then
+ $show "generating symbol list for \`$libname.la'"
+ export_symbols="$output_objdir/$libname.exp"
+ $run $rm $export_symbols
+ libobjs=$output
+ # Append the command to create the export file.
+ eval concat_cmds=\"\$concat_cmds~$export_symbols_cmds\"
+ fi
+
+ # Set up a command to remove the reloadable object files
+ # after they are used.
+ i=0
+ while test "$i" -lt "$k"
+ do
+ i=`expr $i + 1`
+ delfiles="$delfiles $output_objdir/$output_la-${i}.$objext"
+ done
+
+ $echo "creating a temporary reloadable object file: $output"
+
+ # Loop through the commands generated above and execute them.
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $concat_cmds; do
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+
+ libobjs=$output
+ # Restore the value of output.
+ output=$save_output
+
+ if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then
+ eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
+ fi
+ # Expand the library linking commands again to reset the
+ # value of $libobjs for piecewise linking.
+
+ # Do each of the archive commands.
+ if test "$module" = yes && test -n "$module_cmds" ; then
+ if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
+ cmds=$module_expsym_cmds
+ else
+ cmds=$module_cmds
+ fi
+ else
+ if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+ cmds=$archive_expsym_cmds
+ else
+ cmds=$archive_cmds
+ fi
+ fi
+
+ # Append the command to remove the reloadable object files
+ # to the just-reset $cmds.
+ eval cmds=\"\$cmds~\$rm $delfiles\"
+ fi
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || {
+ lt_exit=$?
+
+ # Restore the uninstalled library and exit
+ if test "$mode" = relink; then
+ $run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname}U $realname)'
+ fi
+
+ exit $lt_exit
+ }
+ done
+ IFS="$save_ifs"
+
+ # Restore the uninstalled library and exit
+ if test "$mode" = relink; then
+ $run eval '(cd $output_objdir && $rm ${realname}T && $mv $realname ${realname}T && $mv "$realname"U $realname)' || exit $?
+
+ if test -n "$convenience"; then
+ if test -z "$whole_archive_flag_spec"; then
+ $show "${rm}r $gentop"
+ $run ${rm}r "$gentop"
+ fi
+ fi
+
+ exit $EXIT_SUCCESS
+ fi
+
+ # Create links to the real library.
+ for linkname in $linknames; do
+ if test "$realname" != "$linkname"; then
+ $show "(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)"
+ $run eval '(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)' || exit $?
+ fi
+ done
+
+ # If -module or -export-dynamic was specified, set the dlname.
+ if test "$module" = yes || test "$export_dynamic" = yes; then
+ # On all known operating systems, these are identical.
+ dlname="$soname"
+ fi
+ fi
+ ;;
+
+ obj)
+ if test -n "$deplibs"; then
+ $echo "$modename: warning: \`-l' and \`-L' are ignored for objects" 1>&2
+ fi
+
+ if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+ $echo "$modename: warning: \`-dlopen' is ignored for objects" 1>&2
+ fi
+
+ if test -n "$rpath"; then
+ $echo "$modename: warning: \`-rpath' is ignored for objects" 1>&2
+ fi
+
+ if test -n "$xrpath"; then
+ $echo "$modename: warning: \`-R' is ignored for objects" 1>&2
+ fi
+
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info' is ignored for objects" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored for objects" 1>&2
+ fi
+
+ case $output in
+ *.lo)
+ if test -n "$objs$old_deplibs"; then
+ $echo "$modename: cannot build library object \`$output' from non-libtool objects" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ libobj="$output"
+ obj=`$echo "X$output" | $Xsed -e "$lo2o"`
+ ;;
+ *)
+ libobj=
+ obj="$output"
+ ;;
+ esac
+
+ # Delete the old objects.
+ $run $rm $obj $libobj
+
+ # Objects from convenience libraries. This assumes
+ # single-version convenience libraries. Whenever we create
+ # different ones for PIC/non-PIC, this we'll have to duplicate
+ # the extraction.
+ reload_conv_objs=
+ gentop=
+ # reload_cmds runs $LD directly, so let us get rid of
+ # -Wl from whole_archive_flag_spec and hope we can get by with
+ # turning comma into space..
+ wl=
+
+ if test -n "$convenience"; then
+ if test -n "$whole_archive_flag_spec"; then
+ eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\"
+ reload_conv_objs=$reload_objs\ `$echo "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'`
+ else
+ gentop="$output_objdir/${obj}x"
+ generated="$generated $gentop"
+
+ func_extract_archives $gentop $convenience
+ reload_conv_objs="$reload_objs $func_extract_archives_result"
+ fi
+ fi
+
+ # Create the old-style object.
+ reload_objs="$objs$old_deplibs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
+
+ output="$obj"
+ cmds=$reload_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+
+ # Exit if we aren't doing a library object file.
+ if test -z "$libobj"; then
+ if test -n "$gentop"; then
+ $show "${rm}r $gentop"
+ $run ${rm}r $gentop
+ fi
+
+ exit $EXIT_SUCCESS
+ fi
+
+ if test "$build_libtool_libs" != yes; then
+ if test -n "$gentop"; then
+ $show "${rm}r $gentop"
+ $run ${rm}r $gentop
+ fi
+
+ # Create an invalid libtool object if no PIC, so that we don't
+ # accidentally link it into a program.
+ # $show "echo timestamp > $libobj"
+ # $run eval "echo timestamp > $libobj" || exit $?
+ exit $EXIT_SUCCESS
+ fi
+
+ if test -n "$pic_flag" || test "$pic_mode" != default; then
+ # Only do commands if we really have different PIC objects.
+ reload_objs="$libobjs $reload_conv_objs"
+ output="$libobj"
+ cmds=$reload_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ fi
+
+ if test -n "$gentop"; then
+ $show "${rm}r $gentop"
+ $run ${rm}r $gentop
+ fi
+
+ exit $EXIT_SUCCESS
+ ;;
+
+ prog)
+ case $host in
+ *cygwin*) output=`$echo $output | ${SED} -e 's,.exe$,,;s,$,.exe,'` ;;
+ esac
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info' is ignored for programs" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored for programs" 1>&2
+ fi
+
+ if test "$preload" = yes; then
+ if test "$dlopen_support" = unknown && test "$dlopen_self" = unknown &&
+ test "$dlopen_self_static" = unknown; then
+ $echo "$modename: warning: \`AC_LIBTOOL_DLOPEN' not used. Assuming no dlopen support."
+ fi
+ fi
+
+ case $host in
+ *-*-rhapsody* | *-*-darwin1.[012])
+ # On Rhapsody replace the C library is the System framework
+ compile_deplibs=`$echo "X $compile_deplibs" | $Xsed -e 's/ -lc / -framework System /'`
+ finalize_deplibs=`$echo "X $finalize_deplibs" | $Xsed -e 's/ -lc / -framework System /'`
+ ;;
+ esac
+
+ case $host in
+ *darwin*)
+ # Don't allow lazy linking, it breaks C++ global constructors
+ if test "$tagname" = CXX ; then
+ compile_command="$compile_command ${wl}-bind_at_load"
+ finalize_command="$finalize_command ${wl}-bind_at_load"
+ fi
+ ;;
+ esac
+
+
+ # move library search paths that coincide with paths to not yet
+ # installed libraries to the beginning of the library search list
+ new_libs=
+ for path in $notinst_path; do
+ case " $new_libs " in
+ *" -L$path/$objdir "*) ;;
+ *)
+ case " $compile_deplibs " in
+ *" -L$path/$objdir "*)
+ new_libs="$new_libs -L$path/$objdir" ;;
+ esac
+ ;;
+ esac
+ done
+ for deplib in $compile_deplibs; do
+ case $deplib in
+ -L*)
+ case " $new_libs " in
+ *" $deplib "*) ;;
+ *) new_libs="$new_libs $deplib" ;;
+ esac
+ ;;
+ *) new_libs="$new_libs $deplib" ;;
+ esac
+ done
+ compile_deplibs="$new_libs"
+
+
+ compile_command="$compile_command $compile_deplibs"
+ finalize_command="$finalize_command $finalize_deplibs"
+
+ if test -n "$rpath$xrpath"; then
+ # If the user specified any rpath flags, then add them.
+ for libdir in $rpath $xrpath; do
+ # This is the magic to use -rpath.
+ case "$finalize_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_rpath="$finalize_rpath $libdir" ;;
+ esac
+ done
+ fi
+
+ # Now hardcode the library paths
+ rpath=
+ hardcode_libdirs=
+ for libdir in $compile_rpath $finalize_rpath; do
+ if test -n "$hardcode_libdir_flag_spec"; then
+ if test -n "$hardcode_libdir_separator"; then
+ if test -z "$hardcode_libdirs"; then
+ hardcode_libdirs="$libdir"
+ else
+ # Just accumulate the unique libdirs.
+ case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+ *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+ ;;
+ *)
+ hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+ ;;
+ esac
+ fi
+ else
+ eval flag=\"$hardcode_libdir_flag_spec\"
+ rpath="$rpath $flag"
+ fi
+ elif test -n "$runpath_var"; then
+ case "$perm_rpath " in
+ *" $libdir "*) ;;
+ *) perm_rpath="$perm_rpath $libdir" ;;
+ esac
+ fi
+ case $host in
+ *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+ testbindir=`$echo "X$libdir" | $Xsed -e 's*/lib$*/bin*'`
+ case :$dllsearchpath: in
+ *":$libdir:"*) ;;
+ *) dllsearchpath="$dllsearchpath:$libdir";;
+ esac
+ case :$dllsearchpath: in
+ *":$testbindir:"*) ;;
+ *) dllsearchpath="$dllsearchpath:$testbindir";;
+ esac
+ ;;
+ esac
+ done
+ # Substitute the hardcoded libdirs into the rpath.
+ if test -n "$hardcode_libdir_separator" &&
+ test -n "$hardcode_libdirs"; then
+ libdir="$hardcode_libdirs"
+ eval rpath=\" $hardcode_libdir_flag_spec\"
+ fi
+ compile_rpath="$rpath"
+
+ rpath=
+ hardcode_libdirs=
+ for libdir in $finalize_rpath; do
+ if test -n "$hardcode_libdir_flag_spec"; then
+ if test -n "$hardcode_libdir_separator"; then
+ if test -z "$hardcode_libdirs"; then
+ hardcode_libdirs="$libdir"
+ else
+ # Just accumulate the unique libdirs.
+ case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
+ *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+ ;;
+ *)
+ hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+ ;;
+ esac
+ fi
+ else
+ eval flag=\"$hardcode_libdir_flag_spec\"
+ rpath="$rpath $flag"
+ fi
+ elif test -n "$runpath_var"; then
+ case "$finalize_perm_rpath " in
+ *" $libdir "*) ;;
+ *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;;
+ esac
+ fi
+ done
+ # Substitute the hardcoded libdirs into the rpath.
+ if test -n "$hardcode_libdir_separator" &&
+ test -n "$hardcode_libdirs"; then
+ libdir="$hardcode_libdirs"
+ eval rpath=\" $hardcode_libdir_flag_spec\"
+ fi
+ finalize_rpath="$rpath"
+
+ if test -n "$libobjs" && test "$build_old_libs" = yes; then
+ # Transform all the library objects into standard objects.
+ compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+ finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+ fi
+
+ dlsyms=
+ if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+ if test -n "$NM" && test -n "$global_symbol_pipe"; then
+ dlsyms="${outputname}S.c"
+ else
+ $echo "$modename: not configured to extract global symbols from dlpreopened files" 1>&2
+ fi
+ fi
+
+ if test -n "$dlsyms"; then
+ case $dlsyms in
+ "") ;;
+ *.c)
+ # Discover the nlist of each of the dlfiles.
+ nlist="$output_objdir/${outputname}.nm"
+
+ $show "$rm $nlist ${nlist}S ${nlist}T"
+ $run $rm "$nlist" "${nlist}S" "${nlist}T"
+
+ # Parse the name list into a source file.
+ $show "creating $output_objdir/$dlsyms"
+
+ test -z "$run" && $echo > "$output_objdir/$dlsyms" "\
+/* $dlsyms - symbol resolution table for \`$outputname' dlsym emulation. */
+/* Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP */
+
+#ifdef __cplusplus
+extern \"C\" {
+#endif
+
+/* Prevent the only kind of declaration conflicts we can make. */
+#define lt_preloaded_symbols some_other_symbol
+
+/* External symbol declarations for the compiler. */\
+"
+
+ if test "$dlself" = yes; then
+ $show "generating symbol list for \`$output'"
+
+ test -z "$run" && $echo ': @PROGRAM@ ' > "$nlist"
+
+ # Add our own program objects to the symbol list.
+ progfiles=`$echo "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP`
+ for arg in $progfiles; do
+ $show "extracting global C symbols from \`$arg'"
+ $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'"
+ done
+
+ if test -n "$exclude_expsyms"; then
+ $run eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T'
+ $run eval '$mv "$nlist"T "$nlist"'
+ fi
+
+ if test -n "$export_symbols_regex"; then
+ $run eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T'
+ $run eval '$mv "$nlist"T "$nlist"'
+ fi
+
+ # Prepare the list of exported symbols
+ if test -z "$export_symbols"; then
+ export_symbols="$output_objdir/$outputname.exp"
+ $run $rm $export_symbols
+ $run eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
+ case $host in
+ *cygwin* | *mingw* )
+ $run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+ $run eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"'
+ ;;
+ esac
+ else
+ $run eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"'
+ $run eval 'grep -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T'
+ $run eval 'mv "$nlist"T "$nlist"'
+ case $host in
+ *cygwin* | *mingw* )
+ $run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+ $run eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
+ ;;
+ esac
+ fi
+ fi
+
+ for arg in $dlprefiles; do
+ $show "extracting global C symbols from \`$arg'"
+ name=`$echo "$arg" | ${SED} -e 's%^.*/%%'`
+ $run eval '$echo ": $name " >> "$nlist"'
+ $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'"
+ done
+
+ if test -z "$run"; then
+ # Make sure we have at least an empty file.
+ test -f "$nlist" || : > "$nlist"
+
+ if test -n "$exclude_expsyms"; then
+ $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T
+ $mv "$nlist"T "$nlist"
+ fi
+
+ # Try sorting and uniquifying the output.
+ if grep -v "^: " < "$nlist" |
+ if sort -k 3 </dev/null >/dev/null 2>&1; then
+ sort -k 3
+ else
+ sort +2
+ fi |
+ uniq > "$nlist"S; then
+ :
+ else
+ grep -v "^: " < "$nlist" > "$nlist"S
+ fi
+
+ if test -f "$nlist"S; then
+ eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$dlsyms"'
+ else
+ $echo '/* NONE */' >> "$output_objdir/$dlsyms"
+ fi
+
+ $echo >> "$output_objdir/$dlsyms" "\
+
+#undef lt_preloaded_symbols
+
+#if defined (__STDC__) && __STDC__
+# define lt_ptr void *
+#else
+# define lt_ptr char *
+# define const
+#endif
+
+/* The mapping between symbol names and symbols. */
+"
+
+ case $host in
+ *cygwin* | *mingw* )
+ $echo >> "$output_objdir/$dlsyms" "\
+/* DATA imports from DLLs on WIN32 can't be const, because
+ runtime relocations are performed -- see ld's documentation
+ on pseudo-relocs */
+struct {
+"
+ ;;
+ * )
+ $echo >> "$output_objdir/$dlsyms" "\
+const struct {
+"
+ ;;
+ esac
+
+
+ $echo >> "$output_objdir/$dlsyms" "\
+ const char *name;
+ lt_ptr address;
+}
+lt_preloaded_symbols[] =
+{\
+"
+
+ eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$dlsyms"
+
+ $echo >> "$output_objdir/$dlsyms" "\
+ {0, (lt_ptr) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+ return lt_preloaded_symbols;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif\
+"
+ fi
+
+ pic_flag_for_symtable=
+ case $host in
+ # compiling the symbol table file with pic_flag works around
+ # a FreeBSD bug that causes programs to crash when -lm is
+ # linked before any other PIC object. But we must not use
+ # pic_flag when linking with -static. The problem exists in
+ # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.
+ *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
+ case "$compile_command " in
+ *" -static "*) ;;
+ *) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND";;
+ esac;;
+ *-*-hpux*)
+ case "$compile_command " in
+ *" -static "*) ;;
+ *) pic_flag_for_symtable=" $pic_flag";;
+ esac
+ esac
+
+ # Now compile the dynamic symbol file.
+ $show "(cd $output_objdir && $LTCC $LTCFLAGS -c$no_builtin_flag$pic_flag_for_symtable \"$dlsyms\")"
+ $run eval '(cd $output_objdir && $LTCC $LTCFLAGS -c$no_builtin_flag$pic_flag_for_symtable "$dlsyms")' || exit $?
+
+ # Clean up the generated files.
+ $show "$rm $output_objdir/$dlsyms $nlist ${nlist}S ${nlist}T"
+ $run $rm "$output_objdir/$dlsyms" "$nlist" "${nlist}S" "${nlist}T"
+
+ # Transform the symbol file into the correct name.
+ case $host in
+ *cygwin* | *mingw* )
+ if test -f "$output_objdir/${outputname}.def" ; then
+ compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%" | $NL2SP`
+ finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%" | $NL2SP`
+ else
+ compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP`
+ finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP`
+ fi
+ ;;
+ * )
+ compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP`
+ finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP`
+ ;;
+ esac
+ ;;
+ *)
+ $echo "$modename: unknown suffix for \`$dlsyms'" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ else
+ # We keep going just in case the user didn't refer to
+ # lt_preloaded_symbols. The linker will fail if global_symbol_pipe
+ # really was required.
+
+ # Nullify the symbol file.
+ compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s% @SYMFILE@%%" | $NL2SP`
+ finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s% @SYMFILE@%%" | $NL2SP`
+ fi
+
+ if test "$need_relink" = no || test "$build_libtool_libs" != yes; then
+ # Replace the output file specification.
+ compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e 's%@OUTPUT@%'"$output"'%g' | $NL2SP`
+ link_command="$compile_command$compile_rpath"
+
+ # We have no uninstalled library dependencies, so finalize right now.
+ $show "$link_command"
+ $run eval "$link_command"
+ exit_status=$?
+
+ # Delete the generated files.
+ if test -n "$dlsyms"; then
+ $show "$rm $output_objdir/${outputname}S.${objext}"
+ $run $rm "$output_objdir/${outputname}S.${objext}"
+ fi
+
+ exit $exit_status
+ fi
+
+ if test -n "$shlibpath_var"; then
+ # We should set the shlibpath_var
+ rpath=
+ for dir in $temp_rpath; do
+ case $dir in
+ [\\/]* | [A-Za-z]:[\\/]*)
+ # Absolute path.
+ rpath="$rpath$dir:"
+ ;;
+ *)
+ # Relative path: add a thisdir entry.
+ rpath="$rpath\$thisdir/$dir:"
+ ;;
+ esac
+ done
+ temp_rpath="$rpath"
+ fi
+
+ if test -n "$compile_shlibpath$finalize_shlibpath"; then
+ compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command"
+ fi
+ if test -n "$finalize_shlibpath"; then
+ finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command"
+ fi
+
+ compile_var=
+ finalize_var=
+ if test -n "$runpath_var"; then
+ if test -n "$perm_rpath"; then
+ # We should set the runpath_var.
+ rpath=
+ for dir in $perm_rpath; do
+ rpath="$rpath$dir:"
+ done
+ compile_var="$runpath_var=\"$rpath\$$runpath_var\" "
+ fi
+ if test -n "$finalize_perm_rpath"; then
+ # We should set the runpath_var.
+ rpath=
+ for dir in $finalize_perm_rpath; do
+ rpath="$rpath$dir:"
+ done
+ finalize_var="$runpath_var=\"$rpath\$$runpath_var\" "
+ fi
+ fi
+
+ if test "$no_install" = yes; then
+ # We don't need to create a wrapper script.
+ link_command="$compile_var$compile_command$compile_rpath"
+ # Replace the output file specification.
+ link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'`
+ # Delete the old output file.
+ $run $rm $output
+ # Link the executable and exit
+ $show "$link_command"
+ $run eval "$link_command" || exit $?
+ exit $EXIT_SUCCESS
+ fi
+
+ if test "$hardcode_action" = relink; then
+ # Fast installation is not supported
+ link_command="$compile_var$compile_command$compile_rpath"
+ relink_command="$finalize_var$finalize_command$finalize_rpath"
+
+ $echo "$modename: warning: this platform does not like uninstalled shared libraries" 1>&2
+ $echo "$modename: \`$output' will be relinked during installation" 1>&2
+ else
+ if test "$fast_install" != no; then
+ link_command="$finalize_var$compile_command$finalize_rpath"
+ if test "$fast_install" = yes; then
+ relink_command=`$echo "X$compile_var$compile_command$compile_rpath" | $SP2NL | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g' | $NL2SP`
+ else
+ # fast_install is set to needless
+ relink_command=
+ fi
+ else
+ link_command="$compile_var$compile_command$compile_rpath"
+ relink_command="$finalize_var$finalize_command$finalize_rpath"
+ fi
+ fi
+
+ # Replace the output file specification.
+ link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`
+
+ # Delete the old output files.
+ $run $rm $output $output_objdir/$outputname $output_objdir/lt-$outputname
+
+ $show "$link_command"
+ $run eval "$link_command" || exit $?
+
+ # Now create the wrapper script.
+ $show "creating $output"
+
+ # Quote the relink command for shipping.
+ if test -n "$relink_command"; then
+ # Preserve any variables that may affect compiler behavior
+ for var in $variables_saved_for_relink; do
+ if eval test -z \"\${$var+set}\"; then
+ relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command"
+ elif eval var_value=\$$var; test -z "$var_value"; then
+ relink_command="$var=; export $var; $relink_command"
+ else
+ var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"`
+ relink_command="$var=\"$var_value\"; export $var; $relink_command"
+ fi
+ done
+ relink_command="(cd `pwd`; $relink_command)"
+ relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e "$sed_quote_subst" | $NL2SP`
+ fi
+
+ # Quote $echo for shipping.
+ if test "X$echo" = "X$SHELL $progpath --fallback-echo"; then
+ case $progpath in
+ [\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";;
+ *) qecho="$SHELL `pwd`/$progpath --fallback-echo";;
+ esac
+ qecho=`$echo "X$qecho" | $Xsed -e "$sed_quote_subst"`
+ else
+ qecho=`$echo "X$echo" | $Xsed -e "$sed_quote_subst"`
+ fi
+
+ # Only actually do things if our run command is non-null.
+ if test -z "$run"; then
+ # win32 will think the script is a binary if it has
+ # a .exe suffix, so we strip it off here.
+ case $output in
+ *.exe) output=`$echo $output|${SED} 's,.exe$,,'` ;;
+ esac
+ # test for cygwin because mv fails w/o .exe extensions
+ case $host in
+ *cygwin*)
+ exeext=.exe
+ outputname=`$echo $outputname|${SED} 's,.exe$,,'` ;;
+ *) exeext= ;;
+ esac
+ case $host in
+ *cygwin* | *mingw* )
+ output_name=`basename $output`
+ output_path=`dirname $output`
+ cwrappersource="$output_path/$objdir/lt-$output_name.c"
+ cwrapper="$output_path/$output_name.exe"
+ $rm $cwrappersource $cwrapper
+ trap "$rm $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15
+
+ cat > $cwrappersource <<EOF
+
+/* $cwrappersource - temporary wrapper executable for $objdir/$outputname
+ Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
+
+ The $output program cannot be directly executed until all the libtool
+ libraries that it depends on are installed.
+
+ This wrapper executable should never be moved out of the build directory.
+ If it is, it will not operate correctly.
+
+ Currently, it simply execs the wrapper *script* "/bin/sh $output",
+ but could eventually absorb all of the scripts functionality and
+ exec $objdir/$outputname directly.
+*/
+EOF
+ cat >> $cwrappersource<<"EOF"
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <malloc.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+#include <sys/stat.h>
+
+#if defined(PATH_MAX)
+# define LT_PATHMAX PATH_MAX
+#elif defined(MAXPATHLEN)
+# define LT_PATHMAX MAXPATHLEN
+#else
+# define LT_PATHMAX 1024
+#endif
+
+#ifndef DIR_SEPARATOR
+# define DIR_SEPARATOR '/'
+# define PATH_SEPARATOR ':'
+#endif
+
+#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \
+ defined (__OS2__)
+# define HAVE_DOS_BASED_FILE_SYSTEM
+# ifndef DIR_SEPARATOR_2
+# define DIR_SEPARATOR_2 '\\'
+# endif
+# ifndef PATH_SEPARATOR_2
+# define PATH_SEPARATOR_2 ';'
+# endif
+#endif
+
+#ifndef DIR_SEPARATOR_2
+# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
+#else /* DIR_SEPARATOR_2 */
+# define IS_DIR_SEPARATOR(ch) \
+ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
+#endif /* DIR_SEPARATOR_2 */
+
+#ifndef PATH_SEPARATOR_2
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)
+#else /* PATH_SEPARATOR_2 */
+# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)
+#endif /* PATH_SEPARATOR_2 */
+
+#define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type)))
+#define XFREE(stale) do { \
+ if (stale) { free ((void *) stale); stale = 0; } \
+} while (0)
+
+/* -DDEBUG is fairly common in CFLAGS. */
+#undef DEBUG
+#if defined DEBUGWRAPPER
+# define DEBUG(format, ...) fprintf(stderr, format, __VA_ARGS__)
+#else
+# define DEBUG(format, ...)
+#endif
+
+const char *program_name = NULL;
+
+void * xmalloc (size_t num);
+char * xstrdup (const char *string);
+const char * base_name (const char *name);
+char * find_executable(const char *wrapper);
+int check_executable(const char *path);
+char * strendzap(char *str, const char *pat);
+void lt_fatal (const char *message, ...);
+
+int
+main (int argc, char *argv[])
+{
+ char **newargz;
+ int i;
+
+ program_name = (char *) xstrdup (base_name (argv[0]));
+ DEBUG("(main) argv[0] : %s\n",argv[0]);
+ DEBUG("(main) program_name : %s\n",program_name);
+ newargz = XMALLOC(char *, argc+2);
+EOF
+
+ cat >> $cwrappersource <<EOF
+ newargz[0] = (char *) xstrdup("$SHELL");
+EOF
+
+ cat >> $cwrappersource <<"EOF"
+ newargz[1] = find_executable(argv[0]);
+ if (newargz[1] == NULL)
+ lt_fatal("Couldn't find %s", argv[0]);
+ DEBUG("(main) found exe at : %s\n",newargz[1]);
+ /* we know the script has the same name, without the .exe */
+ /* so make sure newargz[1] doesn't end in .exe */
+ strendzap(newargz[1],".exe");
+ for (i = 1; i < argc; i++)
+ newargz[i+1] = xstrdup(argv[i]);
+ newargz[argc+1] = NULL;
+
+ for (i=0; i<argc+1; i++)
+ {
+ DEBUG("(main) newargz[%d] : %s\n",i,newargz[i]);
+ ;
+ }
+
+EOF
+
+ case $host_os in
+ mingw*)
+ cat >> $cwrappersource <<EOF
+ execv("$SHELL",(char const **)newargz);
+EOF
+ ;;
+ *)
+ cat >> $cwrappersource <<EOF
+ execv("$SHELL",newargz);
+EOF
+ ;;
+ esac
+
+ cat >> $cwrappersource <<"EOF"
+ return 127;
+}
+
+void *
+xmalloc (size_t num)
+{
+ void * p = (void *) malloc (num);
+ if (!p)
+ lt_fatal ("Memory exhausted");
+
+ return p;
+}
+
+char *
+xstrdup (const char *string)
+{
+ return string ? strcpy ((char *) xmalloc (strlen (string) + 1), string) : NULL
+;
+}
+
+const char *
+base_name (const char *name)
+{
+ const char *base;
+
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+ /* Skip over the disk name in MSDOS pathnames. */
+ if (isalpha ((unsigned char)name[0]) && name[1] == ':')
+ name += 2;
+#endif
+
+ for (base = name; *name; name++)
+ if (IS_DIR_SEPARATOR (*name))
+ base = name + 1;
+ return base;
+}
+
+int
+check_executable(const char * path)
+{
+ struct stat st;
+
+ DEBUG("(check_executable) : %s\n", path ? (*path ? path : "EMPTY!") : "NULL!");
+ if ((!path) || (!*path))
+ return 0;
+
+ if ((stat (path, &st) >= 0) &&
+ (
+ /* MinGW & native WIN32 do not support S_IXOTH or S_IXGRP */
+#if defined (S_IXOTH)
+ ((st.st_mode & S_IXOTH) == S_IXOTH) ||
+#endif
+#if defined (S_IXGRP)
+ ((st.st_mode & S_IXGRP) == S_IXGRP) ||
+#endif
+ ((st.st_mode & S_IXUSR) == S_IXUSR))
+ )
+ return 1;
+ else
+ return 0;
+}
+
+/* Searches for the full path of the wrapper. Returns
+ newly allocated full path name if found, NULL otherwise */
+char *
+find_executable (const char* wrapper)
+{
+ int has_slash = 0;
+ const char* p;
+ const char* p_next;
+ /* static buffer for getcwd */
+ char tmp[LT_PATHMAX + 1];
+ int tmp_len;
+ char* concat_name;
+
+ DEBUG("(find_executable) : %s\n", wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!");
+
+ if ((wrapper == NULL) || (*wrapper == '\0'))
+ return NULL;
+
+ /* Absolute path? */
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+ if (isalpha ((unsigned char)wrapper[0]) && wrapper[1] == ':')
+ {
+ concat_name = xstrdup (wrapper);
+ if (check_executable(concat_name))
+ return concat_name;
+ XFREE(concat_name);
+ }
+ else
+ {
+#endif
+ if (IS_DIR_SEPARATOR (wrapper[0]))
+ {
+ concat_name = xstrdup (wrapper);
+ if (check_executable(concat_name))
+ return concat_name;
+ XFREE(concat_name);
+ }
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+ }
+#endif
+
+ for (p = wrapper; *p; p++)
+ if (*p == '/')
+ {
+ has_slash = 1;
+ break;
+ }
+ if (!has_slash)
+ {
+ /* no slashes; search PATH */
+ const char* path = getenv ("PATH");
+ if (path != NULL)
+ {
+ for (p = path; *p; p = p_next)
+ {
+ const char* q;
+ size_t p_len;
+ for (q = p; *q; q++)
+ if (IS_PATH_SEPARATOR(*q))
+ break;
+ p_len = q - p;
+ p_next = (*q == '\0' ? q : q + 1);
+ if (p_len == 0)
+ {
+ /* empty path: current directory */
+ if (getcwd (tmp, LT_PATHMAX) == NULL)
+ lt_fatal ("getcwd failed");
+ tmp_len = strlen(tmp);
+ concat_name = XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1);
+ memcpy (concat_name, tmp, tmp_len);
+ concat_name[tmp_len] = '/';
+ strcpy (concat_name + tmp_len + 1, wrapper);
+ }
+ else
+ {
+ concat_name = XMALLOC(char, p_len + 1 + strlen(wrapper) + 1);
+ memcpy (concat_name, p, p_len);
+ concat_name[p_len] = '/';
+ strcpy (concat_name + p_len + 1, wrapper);
+ }
+ if (check_executable(concat_name))
+ return concat_name;
+ XFREE(concat_name);
+ }
+ }
+ /* not found in PATH; assume curdir */
+ }
+ /* Relative path | not found in path: prepend cwd */
+ if (getcwd (tmp, LT_PATHMAX) == NULL)
+ lt_fatal ("getcwd failed");
+ tmp_len = strlen(tmp);
+ concat_name = XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1);
+ memcpy (concat_name, tmp, tmp_len);
+ concat_name[tmp_len] = '/';
+ strcpy (concat_name + tmp_len + 1, wrapper);
+
+ if (check_executable(concat_name))
+ return concat_name;
+ XFREE(concat_name);
+ return NULL;
+}
+
+char *
+strendzap(char *str, const char *pat)
+{
+ size_t len, patlen;
+
+ assert(str != NULL);
+ assert(pat != NULL);
+
+ len = strlen(str);
+ patlen = strlen(pat);
+
+ if (patlen <= len)
+ {
+ str += len - patlen;
+ if (strcmp(str, pat) == 0)
+ *str = '\0';
+ }
+ return str;
+}
+
+static void
+lt_error_core (int exit_status, const char * mode,
+ const char * message, va_list ap)
+{
+ fprintf (stderr, "%s: %s: ", program_name, mode);
+ vfprintf (stderr, message, ap);
+ fprintf (stderr, ".\n");
+
+ if (exit_status >= 0)
+ exit (exit_status);
+}
+
+void
+lt_fatal (const char *message, ...)
+{
+ va_list ap;
+ va_start (ap, message);
+ lt_error_core (EXIT_FAILURE, "FATAL", message, ap);
+ va_end (ap);
+}
+EOF
+ # we should really use a build-platform specific compiler
+ # here, but OTOH, the wrappers (shell script and this C one)
+ # are only useful if you want to execute the "real" binary.
+ # Since the "real" binary is built for $host, then this
+ # wrapper might as well be built for $host, too.
+ $run $LTCC $LTCFLAGS -s -o $cwrapper $cwrappersource
+ ;;
+ esac
+ $rm $output
+ trap "$rm $output; exit $EXIT_FAILURE" 1 2 15
+
+ $echo > $output "\
+#! $SHELL
+
+# $output - temporary wrapper script for $objdir/$outputname
+# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
+#
+# The $output program cannot be directly executed until all the libtool
+# libraries that it depends on are installed.
+#
+# This wrapper script should never be moved out of the build directory.
+# If it is, it will not operate correctly.
+
+# Sed substitution that helps us do robust quoting. It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed='${SED} -e 1s/^X//'
+sed_quote_subst='$sed_quote_subst'
+
+# Be Bourne compatible (taken from Autoconf:_AS_BOURNE_COMPATIBLE).
+if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
+ emulate sh
+ NULLCMD=:
+ # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
+ # is contrary to our usage. Disable this feature.
+ alias -g '\${1+\"\$@\"}'='\"\$@\"'
+ setopt NO_GLOB_SUBST
+else
+ case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
+fi
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+relink_command=\"$relink_command\"
+
+# This environment variable determines our operation mode.
+if test \"\$libtool_install_magic\" = \"$magic\"; then
+ # install mode needs the following variable:
+ notinst_deplibs='$notinst_deplibs'
+else
+ # When we are sourced in execute mode, \$file and \$echo are already set.
+ if test \"\$libtool_execute_magic\" != \"$magic\"; then
+ echo=\"$qecho\"
+ file=\"\$0\"
+ # Make sure echo works.
+ if test \"X\$1\" = X--no-reexec; then
+ # Discard the --no-reexec flag, and continue.
+ shift
+ elif test \"X\`(\$echo '\t') 2>/dev/null\`\" = 'X\t'; then
+ # Yippee, \$echo works!
+ :
+ else
+ # Restart under the correct shell, and then maybe \$echo will work.
+ exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"}
+ fi
+ fi\
+"
+ $echo >> $output "\
+
+ # Find the directory that this script lives in.
+ thisdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\`
+ test \"x\$thisdir\" = \"x\$file\" && thisdir=.
+
+ # Follow symbolic links until we get to the real thisdir.
+ file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\`
+ while test -n \"\$file\"; do
+ destdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\`
+
+ # If there was a directory component, then change thisdir.
+ if test \"x\$destdir\" != \"x\$file\"; then
+ case \"\$destdir\" in
+ [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
+ *) thisdir=\"\$thisdir/\$destdir\" ;;
+ esac
+ fi
+
+ file=\`\$echo \"X\$file\" | \$Xsed -e 's%^.*/%%'\`
+ file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\`
+ done
+
+ # Try to get the absolute directory name.
+ absdir=\`cd \"\$thisdir\" && pwd\`
+ test -n \"\$absdir\" && thisdir=\"\$absdir\"
+"
+
+ if test "$fast_install" = yes; then
+ $echo >> $output "\
+ program=lt-'$outputname'$exeext
+ progdir=\"\$thisdir/$objdir\"
+
+ if test ! -f \"\$progdir/\$program\" || \\
+ { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
+ test \"X\$file\" != \"X\$progdir/\$program\"; }; then
+
+ file=\"\$\$-\$program\"
+
+ if test ! -d \"\$progdir\"; then
+ $mkdir \"\$progdir\"
+ else
+ $rm \"\$progdir/\$file\"
+ fi"
+
+ $echo >> $output "\
+
+ # relink executable if necessary
+ if test -n \"\$relink_command\"; then
+ if relink_command_output=\`eval \$relink_command 2>&1\`; then :
+ else
+ $echo \"\$relink_command_output\" >&2
+ $rm \"\$progdir/\$file\"
+ exit $EXIT_FAILURE
+ fi
+ fi
+
+ $mv \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
+ { $rm \"\$progdir/\$program\";
+ $mv \"\$progdir/\$file\" \"\$progdir/\$program\"; }
+ $rm \"\$progdir/\$file\"
+ fi"
+ else
+ $echo >> $output "\
+ program='$outputname'
+ progdir=\"\$thisdir/$objdir\"
+"
+ fi
+
+ $echo >> $output "\
+
+ if test -f \"\$progdir/\$program\"; then"
+
+ # Export our shlibpath_var if we have one.
+ if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+ $echo >> $output "\
+ # Add our own library path to $shlibpath_var
+ $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
+
+ # Some systems cannot cope with colon-terminated $shlibpath_var
+ # The second colon is a workaround for a bug in BeOS R4 sed
+ $shlibpath_var=\`\$echo \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\`
+
+ export $shlibpath_var
+"
+ fi
+
+ # fixup the dll searchpath if we need to.
+ if test -n "$dllsearchpath"; then
+ $echo >> $output "\
+ # Add the dll search path components to the executable PATH
+ PATH=$dllsearchpath:\$PATH
+"
+ fi
+
+ $echo >> $output "\
+ if test \"\$libtool_execute_magic\" != \"$magic\"; then
+ # Run the actual program with our arguments.
+"
+ case $host in
+ # Backslashes separate directories on plain windows
+ *-*-mingw | *-*-os2*)
+ $echo >> $output "\
+ exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
+"
+ ;;
+
+ *)
+ $echo >> $output "\
+ exec \"\$progdir/\$program\" \${1+\"\$@\"}
+"
+ ;;
+ esac
+ $echo >> $output "\
+ \$echo \"\$0: cannot exec \$program \$*\"
+ exit $EXIT_FAILURE
+ fi
+ else
+ # The program doesn't exist.
+ \$echo \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
+ \$echo \"This script is just a wrapper for \$program.\" 1>&2
+ $echo \"See the $PACKAGE documentation for more information.\" 1>&2
+ exit $EXIT_FAILURE
+ fi
+fi\
+"
+ chmod +x $output
+ fi
+ exit $EXIT_SUCCESS
+ ;;
+ esac
+
+ # See if we need to build an old-fashioned archive.
+ for oldlib in $oldlibs; do
+
+ if test "$build_libtool_libs" = convenience; then
+ oldobjs="$libobjs_save"
+ addlibs="$convenience"
+ build_libtool_libs=no
+ else
+ if test "$build_libtool_libs" = module; then
+ oldobjs="$libobjs_save"
+ build_libtool_libs=no
+ else
+ oldobjs="$old_deplibs $non_pic_objects"
+ fi
+ addlibs="$old_convenience"
+ fi
+
+ if test -n "$addlibs"; then
+ gentop="$output_objdir/${outputname}x"
+ generated="$generated $gentop"
+
+ func_extract_archives $gentop $addlibs
+ oldobjs="$oldobjs $func_extract_archives_result"
+ fi
+
+ # Do each command in the archive commands.
+ if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then
+ cmds=$old_archive_from_new_cmds
+ else
+ # POSIX demands no paths to be encoded in archives. We have
+ # to avoid creating archives with duplicate basenames if we
+ # might have to extract them afterwards, e.g., when creating a
+ # static archive out of a convenience library, or when linking
+ # the entirety of a libtool archive into another (currently
+ # not supported by libtool).
+ if (for obj in $oldobjs
+ do
+ $echo "X$obj" | $Xsed -e 's%^.*/%%'
+ done | sort | sort -uc >/dev/null 2>&1); then
+ :
+ else
+ $echo "copying selected object files to avoid basename conflicts..."
+
+ if test -z "$gentop"; then
+ gentop="$output_objdir/${outputname}x"
+ generated="$generated $gentop"
+
+ $show "${rm}r $gentop"
+ $run ${rm}r "$gentop"
+ $show "$mkdir $gentop"
+ $run $mkdir "$gentop"
+ exit_status=$?
+ if test "$exit_status" -ne 0 && test ! -d "$gentop"; then
+ exit $exit_status
+ fi
+ fi
+
+ save_oldobjs=$oldobjs
+ oldobjs=
+ counter=1
+ for obj in $save_oldobjs
+ do
+ objbase=`$echo "X$obj" | $Xsed -e 's%^.*/%%'`
+ case " $oldobjs " in
+ " ") oldobjs=$obj ;;
+ *[\ /]"$objbase "*)
+ while :; do
+ # Make sure we don't pick an alternate name that also
+ # overlaps.
+ newobj=lt$counter-$objbase
+ counter=`expr $counter + 1`
+ case " $oldobjs " in
+ *[\ /]"$newobj "*) ;;
+ *) if test ! -f "$gentop/$newobj"; then break; fi ;;
+ esac
+ done
+ $show "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
+ $run ln "$obj" "$gentop/$newobj" ||
+ $run cp "$obj" "$gentop/$newobj"
+ oldobjs="$oldobjs $gentop/$newobj"
+ ;;
+ *) oldobjs="$oldobjs $obj" ;;
+ esac
+ done
+ fi
+
+ eval cmds=\"$old_archive_cmds\"
+
+ if len=`expr "X$cmds" : ".*"` &&
+ test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+ cmds=$old_archive_cmds
+ else
+ # the command line is too long to link in one step, link in parts
+ $echo "using piecewise archive linking..."
+ save_RANLIB=$RANLIB
+ RANLIB=:
+ objlist=
+ concat_cmds=
+ save_oldobjs=$oldobjs
+
+ # Is there a better way of finding the last object in the list?
+ for obj in $save_oldobjs
+ do
+ last_oldobj=$obj
+ done
+ for obj in $save_oldobjs
+ do
+ oldobjs="$objlist $obj"
+ objlist="$objlist $obj"
+ eval test_cmds=\"$old_archive_cmds\"
+ if len=`expr "X$test_cmds" : ".*" 2>/dev/null` &&
+ test "$len" -le "$max_cmd_len"; then
+ :
+ else
+ # the above command should be used before it gets too long
+ oldobjs=$objlist
+ if test "$obj" = "$last_oldobj" ; then
+ RANLIB=$save_RANLIB
+ fi
+ test -z "$concat_cmds" || concat_cmds=$concat_cmds~
+ eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\"
+ objlist=
+ fi
+ done
+ RANLIB=$save_RANLIB
+ oldobjs=$objlist
+ if test "X$oldobjs" = "X" ; then
+ eval cmds=\"\$concat_cmds\"
+ else
+ eval cmds=\"\$concat_cmds~\$old_archive_cmds\"
+ fi
+ fi
+ fi
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ eval cmd=\"$cmd\"
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ done
+
+ if test -n "$generated"; then
+ $show "${rm}r$generated"
+ $run ${rm}r$generated
+ fi
+
+ # Now create the libtool archive.
+ case $output in
+ *.la)
+ old_library=
+ test "$build_old_libs" = yes && old_library="$libname.$libext"
+ $show "creating $output"
+
+ # Preserve any variables that may affect compiler behavior
+ for var in $variables_saved_for_relink; do
+ if eval test -z \"\${$var+set}\"; then
+ relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command"
+ elif eval var_value=\$$var; test -z "$var_value"; then
+ relink_command="$var=; export $var; $relink_command"
+ else
+ var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"`
+ relink_command="$var=\"$var_value\"; export $var; $relink_command"
+ fi
+ done
+ # Quote the link command for shipping.
+ relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)"
+ relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e "$sed_quote_subst" | $NL2SP`
+ if test "$hardcode_automatic" = yes ; then
+ relink_command=
+ fi
+
+
+ # Only create the output if not a dry run.
+ if test -z "$run"; then
+ for installed in no yes; do
+ if test "$installed" = yes; then
+ if test -z "$install_libdir"; then
+ break
+ fi
+ output="$output_objdir/$outputname"i
+ # Replace all uninstalled libtool libraries with the installed ones
+ newdependency_libs=
+ for deplib in $dependency_libs; do
+ case $deplib in
+ *.la)
+ name=`$echo "X$deplib" | $Xsed -e 's%^.*/%%'`
+ eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
+ if test -z "$libdir"; then
+ $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ newdependency_libs="$newdependency_libs $libdir/$name"
+ ;;
+ *) newdependency_libs="$newdependency_libs $deplib" ;;
+ esac
+ done
+ dependency_libs="$newdependency_libs"
+ newdlfiles=
+ for lib in $dlfiles; do
+ name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
+ eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+ if test -z "$libdir"; then
+ $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ newdlfiles="$newdlfiles $libdir/$name"
+ done
+ dlfiles="$newdlfiles"
+ newdlprefiles=
+ for lib in $dlprefiles; do
+ name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
+ eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+ if test -z "$libdir"; then
+ $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ newdlprefiles="$newdlprefiles $libdir/$name"
+ done
+ dlprefiles="$newdlprefiles"
+ else
+ newdlfiles=
+ for lib in $dlfiles; do
+ case $lib in
+ [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+ *) abs=`pwd`"/$lib" ;;
+ esac
+ newdlfiles="$newdlfiles $abs"
+ done
+ dlfiles="$newdlfiles"
+ newdlprefiles=
+ for lib in $dlprefiles; do
+ case $lib in
+ [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+ *) abs=`pwd`"/$lib" ;;
+ esac
+ newdlprefiles="$newdlprefiles $abs"
+ done
+ dlprefiles="$newdlprefiles"
+ fi
+ $rm $output
+ # place dlname in correct position for cygwin
+ tdlname=$dlname
+ case $host,$output,$installed,$module,$dlname in
+ *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;;
+ esac
+ $echo > $output "\
+# $outputname - a libtool library file
+# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# The name that we can dlopen(3).
+dlname='$tdlname'
+
+# Names of this library.
+library_names='$library_names'
+
+# The name of the static archive.
+old_library='$old_library'
+
+# Libraries that this one depends upon.
+dependency_libs='$dependency_libs'
+
+# Version information for $libname.
+current=$current
+age=$age
+revision=$revision
+
+# Is this an already installed library?
+installed=$installed
+
+# Should we warn about portability when linking against -modules?
+shouldnotlink=$module
+
+# Files to dlopen/dlpreopen
+dlopen='$dlfiles'
+dlpreopen='$dlprefiles'
+
+# Directory that this library needs to be installed in:
+libdir='$install_libdir'"
+ if test "$installed" = no && test "$need_relink" = yes; then
+ $echo >> $output "\
+relink_command=\"$relink_command\""
+ fi
+ done
+ fi
+
+ # Do a symbolic link so that the libtool archive can be found in
+ # LD_LIBRARY_PATH before the program is installed.
+ $show "(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)"
+ $run eval '(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)' || exit $?
+ ;;
+ esac
+ exit $EXIT_SUCCESS
+ ;;
+
+ # libtool install mode
+ install)
+ modename="$modename: install"
+
+ # There may be an optional sh(1) argument at the beginning of
+ # install_prog (especially on Windows NT).
+ if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh ||
+ # Allow the use of GNU shtool's install command.
+ $echo "X$nonopt" | grep shtool > /dev/null; then
+ # Aesthetically quote it.
+ arg=`$echo "X$nonopt" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ install_prog="$arg "
+ arg="$1"
+ shift
+ else
+ install_prog=
+ arg=$nonopt
+ fi
+
+ # The real first argument should be the name of the installation program.
+ # Aesthetically quote it.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ install_prog="$install_prog$arg"
+
+ # We need to accept at least all the BSD install flags.
+ dest=
+ files=
+ opts=
+ prev=
+ install_type=
+ isdir=no
+ stripme=
+ for arg
+ do
+ if test -n "$dest"; then
+ files="$files $dest"
+ dest=$arg
+ continue
+ fi
+
+ case $arg in
+ -d) isdir=yes ;;
+ -f)
+ case " $install_prog " in
+ *[\\\ /]cp\ *) ;;
+ *) prev=$arg ;;
+ esac
+ ;;
+ -g | -m | -o) prev=$arg ;;
+ -s)
+ stripme=" -s"
+ continue
+ ;;
+ -*)
+ ;;
+ *)
+ # If the previous option needed an argument, then skip it.
+ if test -n "$prev"; then
+ prev=
+ else
+ dest=$arg
+ continue
+ fi
+ ;;
+ esac
+
+ # Aesthetically quote the argument.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case $arg in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"")
+ arg="\"$arg\""
+ ;;
+ esac
+ install_prog="$install_prog $arg"
+ done
+
+ if test -z "$install_prog"; then
+ $echo "$modename: you must specify an install program" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ if test -n "$prev"; then
+ $echo "$modename: the \`$prev' option requires an argument" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ if test -z "$files"; then
+ if test -z "$dest"; then
+ $echo "$modename: no file or destination specified" 1>&2
+ else
+ $echo "$modename: you must specify a destination" 1>&2
+ fi
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Strip any trailing slash from the destination.
+ dest=`$echo "X$dest" | $Xsed -e 's%/$%%'`
+
+ # Check to see that the destination is a directory.
+ test -d "$dest" && isdir=yes
+ if test "$isdir" = yes; then
+ destdir="$dest"
+ destname=
+ else
+ destdir=`$echo "X$dest" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$destdir" = "X$dest" && destdir=.
+ destname=`$echo "X$dest" | $Xsed -e 's%^.*/%%'`
+
+ # Not a directory, so check to see that there is only one file specified.
+ set dummy $files
+ if test "$#" -gt 2; then
+ $echo "$modename: \`$dest' is not a directory" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ fi
+ case $destdir in
+ [\\/]* | [A-Za-z]:[\\/]*) ;;
+ *)
+ for file in $files; do
+ case $file in
+ *.lo) ;;
+ *)
+ $echo "$modename: \`$destdir' must be an absolute directory name" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+ done
+ ;;
+ esac
+
+ # This variable tells wrapper scripts just to set variables rather
+ # than running their programs.
+ libtool_install_magic="$magic"
+
+ staticlibs=
+ future_libdirs=
+ current_libdirs=
+ for file in $files; do
+
+ # Do each installation.
+ case $file in
+ *.$libext)
+ # Do the static libraries later.
+ staticlibs="$staticlibs $file"
+ ;;
+
+ *.la)
+ # Check to see that this really is a libtool archive.
+ if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then :
+ else
+ $echo "$modename: \`$file' is not a valid libtool archive" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ library_names=
+ old_library=
+ relink_command=
+ # If there is no directory component, then add one.
+ case $file in
+ */* | *\\*) . $file ;;
+ *) . ./$file ;;
+ esac
+
+ # Add the libdir to current_libdirs if it is the destination.
+ if test "X$destdir" = "X$libdir"; then
+ case "$current_libdirs " in
+ *" $libdir "*) ;;
+ *) current_libdirs="$current_libdirs $libdir" ;;
+ esac
+ else
+ # Note the libdir as a future libdir.
+ case "$future_libdirs " in
+ *" $libdir "*) ;;
+ *) future_libdirs="$future_libdirs $libdir" ;;
+ esac
+ fi
+
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`/
+ test "X$dir" = "X$file/" && dir=
+ dir="$dir$objdir"
+
+ if test -n "$relink_command"; then
+ # Determine the prefix the user has applied to our future dir.
+ inst_prefix_dir=`$echo "$destdir" | $SED "s%$libdir\$%%"`
+
+ # Don't allow the user to place us outside of our expected
+ # location b/c this prevents finding dependent libraries that
+ # are installed to the same prefix.
+ # At present, this check doesn't affect windows .dll's that
+ # are installed into $libdir/../bin (currently, that works fine)
+ # but it's something to keep an eye on.
+ if test "$inst_prefix_dir" = "$destdir"; then
+ $echo "$modename: error: cannot install \`$file' to a directory not ending in $libdir" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ if test -n "$inst_prefix_dir"; then
+ # Stick the inst_prefix_dir data into the link command.
+ relink_command=`$echo "$relink_command" | $SP2NL | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%" | $NL2SP`
+ else
+ relink_command=`$echo "$relink_command" | $SP2NL | $SED "s%@inst_prefix_dir@%%" | $NL2SP`
+ fi
+
+ $echo "$modename: warning: relinking \`$file'" 1>&2
+ $show "$relink_command"
+ if $run eval "$relink_command"; then :
+ else
+ $echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ fi
+
+ # See the names of the shared library.
+ set dummy $library_names
+ if test -n "$2"; then
+ realname="$2"
+ shift
+ shift
+
+ srcname="$realname"
+ test -n "$relink_command" && srcname="$realname"T
+
+ # Install the shared library and build the symlinks.
+ $show "$install_prog $dir/$srcname $destdir/$realname"
+ $run eval "$install_prog $dir/$srcname $destdir/$realname" || exit $?
+ if test -n "$stripme" && test -n "$striplib"; then
+ $show "$striplib $destdir/$realname"
+ $run eval "$striplib $destdir/$realname" || exit $?
+ fi
+
+ if test "$#" -gt 0; then
+ # Delete the old symlinks, and create new ones.
+ # Try `ln -sf' first, because the `ln' binary might depend on
+ # the symlink we replace! Solaris /bin/ln does not understand -f,
+ # so we also need to try rm && ln -s.
+ for linkname
+ do
+ if test "$linkname" != "$realname"; then
+ $show "(cd $destdir && { $LN_S -f $realname $linkname || { $rm $linkname && $LN_S $realname $linkname; }; })"
+ $run eval "(cd $destdir && { $LN_S -f $realname $linkname || { $rm $linkname && $LN_S $realname $linkname; }; })"
+ fi
+ done
+ fi
+
+ # Do each command in the postinstall commands.
+ lib="$destdir/$realname"
+ cmds=$postinstall_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || {
+ lt_exit=$?
+
+ # Restore the uninstalled library and exit
+ if test "$mode" = relink; then
+ $run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname}U $realname)'
+ fi
+
+ exit $lt_exit
+ }
+ done
+ IFS="$save_ifs"
+ fi
+
+ # Install the pseudo-library for information purposes.
+ name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ instname="$dir/$name"i
+ $show "$install_prog $instname $destdir/$name"
+ $run eval "$install_prog $instname $destdir/$name" || exit $?
+
+ # Maybe install the static library, too.
+ test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library"
+ ;;
+
+ *.lo)
+ # Install (i.e. copy) a libtool object.
+
+ # Figure out destination file name, if it wasn't already specified.
+ if test -n "$destname"; then
+ destfile="$destdir/$destname"
+ else
+ destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ destfile="$destdir/$destfile"
+ fi
+
+ # Deduce the name of the destination old-style object file.
+ case $destfile in
+ *.lo)
+ staticdest=`$echo "X$destfile" | $Xsed -e "$lo2o"`
+ ;;
+ *.$objext)
+ staticdest="$destfile"
+ destfile=
+ ;;
+ *)
+ $echo "$modename: cannot copy a libtool object to \`$destfile'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ # Install the libtool object if requested.
+ if test -n "$destfile"; then
+ $show "$install_prog $file $destfile"
+ $run eval "$install_prog $file $destfile" || exit $?
+ fi
+
+ # Install the old object if enabled.
+ if test "$build_old_libs" = yes; then
+ # Deduce the name of the old-style object file.
+ staticobj=`$echo "X$file" | $Xsed -e "$lo2o"`
+
+ $show "$install_prog $staticobj $staticdest"
+ $run eval "$install_prog \$staticobj \$staticdest" || exit $?
+ fi
+ exit $EXIT_SUCCESS
+ ;;
+
+ *)
+ # Figure out destination file name, if it wasn't already specified.
+ if test -n "$destname"; then
+ destfile="$destdir/$destname"
+ else
+ destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ destfile="$destdir/$destfile"
+ fi
+
+ # If the file is missing, and there is a .exe on the end, strip it
+ # because it is most likely a libtool script we actually want to
+ # install
+ stripped_ext=""
+ case $file in
+ *.exe)
+ if test ! -f "$file"; then
+ file=`$echo $file|${SED} 's,.exe$,,'`
+ stripped_ext=".exe"
+ fi
+ ;;
+ esac
+
+ # Do a test to see if this is really a libtool program.
+ case $host in
+ *cygwin*|*mingw*)
+ wrapper=`$echo $file | ${SED} -e 's,.exe$,,'`
+ ;;
+ *)
+ wrapper=$file
+ ;;
+ esac
+ if (${SED} -e '4q' $wrapper | grep "^# Generated by .*$PACKAGE")>/dev/null 2>&1; then
+ notinst_deplibs=
+ relink_command=
+
+ # Note that it is not necessary on cygwin/mingw to append a dot to
+ # foo even if both foo and FILE.exe exist: automatic-append-.exe
+ # behavior happens only for exec(3), not for open(2)! Also, sourcing
+ # `FILE.' does not work on cygwin managed mounts.
+ #
+ # If there is no directory component, then add one.
+ case $wrapper in
+ */* | *\\*) . ${wrapper} ;;
+ *) . ./${wrapper} ;;
+ esac
+
+ # Check the variables that should have been set.
+ if test -z "$notinst_deplibs"; then
+ $echo "$modename: invalid libtool wrapper script \`$wrapper'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ finalize=yes
+ for lib in $notinst_deplibs; do
+ # Check to see that each library is installed.
+ libdir=
+ if test -f "$lib"; then
+ # If there is no directory component, then add one.
+ case $lib in
+ */* | *\\*) . $lib ;;
+ *) . ./$lib ;;
+ esac
+ fi
+ libfile="$libdir/"`$echo "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test
+ if test -n "$libdir" && test ! -f "$libfile"; then
+ $echo "$modename: warning: \`$lib' has not been installed in \`$libdir'" 1>&2
+ finalize=no
+ fi
+ done
+
+ relink_command=
+ # Note that it is not necessary on cygwin/mingw to append a dot to
+ # foo even if both foo and FILE.exe exist: automatic-append-.exe
+ # behavior happens only for exec(3), not for open(2)! Also, sourcing
+ # `FILE.' does not work on cygwin managed mounts.
+ #
+ # If there is no directory component, then add one.
+ case $wrapper in
+ */* | *\\*) . ${wrapper} ;;
+ *) . ./${wrapper} ;;
+ esac
+
+ outputname=
+ if test "$fast_install" = no && test -n "$relink_command"; then
+ if test "$finalize" = yes && test -z "$run"; then
+ tmpdir=`func_mktempdir`
+ file=`$echo "X$file$stripped_ext" | $Xsed -e 's%^.*/%%'`
+ outputname="$tmpdir/$file"
+ # Replace the output file specification.
+ relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g' | $NL2SP`
+
+ $show "$relink_command"
+ if $run eval "$relink_command"; then :
+ else
+ $echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2
+ ${rm}r "$tmpdir"
+ continue
+ fi
+ file="$outputname"
+ else
+ $echo "$modename: warning: cannot relink \`$file'" 1>&2
+ fi
+ else
+ # Install the binary that we compiled earlier.
+ file=`$echo "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"`
+ fi
+ fi
+
+ # remove .exe since cygwin /usr/bin/install will append another
+ # one anyway
+ case $install_prog,$host in
+ */usr/bin/install*,*cygwin*)
+ case $file:$destfile in
+ *.exe:*.exe)
+ # this is ok
+ ;;
+ *.exe:*)
+ destfile=$destfile.exe
+ ;;
+ *:*.exe)
+ destfile=`$echo $destfile | ${SED} -e 's,.exe$,,'`
+ ;;
+ esac
+ ;;
+ esac
+ $show "$install_prog$stripme $file $destfile"
+ $run eval "$install_prog\$stripme \$file \$destfile" || exit $?
+ test -n "$outputname" && ${rm}r "$tmpdir"
+ ;;
+ esac
+ done
+
+ for file in $staticlibs; do
+ name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+
+ # Set up the ranlib parameters.
+ oldlib="$destdir/$name"
+
+ $show "$install_prog $file $oldlib"
+ $run eval "$install_prog \$file \$oldlib" || exit $?
+
+ if test -n "$stripme" && test -n "$old_striplib"; then
+ $show "$old_striplib $oldlib"
+ $run eval "$old_striplib $oldlib" || exit $?
+ fi
+
+ # Do each command in the postinstall commands.
+ cmds=$old_postinstall_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ done
+
+ if test -n "$future_libdirs"; then
+ $echo "$modename: warning: remember to run \`$progname --finish$future_libdirs'" 1>&2
+ fi
+
+ if test -n "$current_libdirs"; then
+ # Maybe just do a dry run.
+ test -n "$run" && current_libdirs=" -n$current_libdirs"
+ exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs'
+ else
+ exit $EXIT_SUCCESS
+ fi
+ ;;
+
+ # libtool finish mode
+ finish)
+ modename="$modename: finish"
+ libdirs="$nonopt"
+ admincmds=
+
+ if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+ for dir
+ do
+ libdirs="$libdirs $dir"
+ done
+
+ for libdir in $libdirs; do
+ if test -n "$finish_cmds"; then
+ # Do each command in the finish commands.
+ cmds=$finish_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd" || admincmds="$admincmds
+ $cmd"
+ done
+ IFS="$save_ifs"
+ fi
+ if test -n "$finish_eval"; then
+ # Do the single finish_eval.
+ eval cmds=\"$finish_eval\"
+ $run eval "$cmds" || admincmds="$admincmds
+ $cmds"
+ fi
+ done
+ fi
+
+ # Exit here if they wanted silent mode.
+ test "$show" = : && exit $EXIT_SUCCESS
+
+ $echo "X----------------------------------------------------------------------" | $Xsed
+ $echo "Libraries have been installed in:"
+ for libdir in $libdirs; do
+ $echo " $libdir"
+ done
+ $echo
+ $echo "If you ever happen to want to link against installed libraries"
+ $echo "in a given directory, LIBDIR, you must either use libtool, and"
+ $echo "specify the full pathname of the library, or use the \`-LLIBDIR'"
+ $echo "flag during linking and do at least one of the following:"
+ if test -n "$shlibpath_var"; then
+ $echo " - add LIBDIR to the \`$shlibpath_var' environment variable"
+ $echo " during execution"
+ fi
+ if test -n "$runpath_var"; then
+ $echo " - add LIBDIR to the \`$runpath_var' environment variable"
+ $echo " during linking"
+ fi
+ if test -n "$hardcode_libdir_flag_spec"; then
+ libdir=LIBDIR
+ eval flag=\"$hardcode_libdir_flag_spec\"
+
+ $echo " - use the \`$flag' linker flag"
+ fi
+ if test -n "$admincmds"; then
+ $echo " - have your system administrator run these commands:$admincmds"
+ fi
+ if test -f /etc/ld.so.conf; then
+ $echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
+ fi
+ $echo
+ $echo "See any operating system documentation about shared libraries for"
+ $echo "more information, such as the ld(1) and ld.so(8) manual pages."
+ $echo "X----------------------------------------------------------------------" | $Xsed
+ exit $EXIT_SUCCESS
+ ;;
+
+ # libtool execute mode
+ execute)
+ modename="$modename: execute"
+
+ # The first argument is the command name.
+ cmd="$nonopt"
+ if test -z "$cmd"; then
+ $echo "$modename: you must specify a COMMAND" 1>&2
+ $echo "$help"
+ exit $EXIT_FAILURE
+ fi
+
+ # Handle -dlopen flags immediately.
+ for file in $execute_dlfiles; do
+ if test ! -f "$file"; then
+ $echo "$modename: \`$file' is not a file" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ dir=
+ case $file in
+ *.la)
+ # Check to see that this really is a libtool archive.
+ if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then :
+ else
+ $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ # Read the libtool library.
+ dlname=
+ library_names=
+
+ # If there is no directory component, then add one.
+ case $file in
+ */* | *\\*) . $file ;;
+ *) . ./$file ;;
+ esac
+
+ # Skip this library if it cannot be dlopened.
+ if test -z "$dlname"; then
+ # Warn if it was a shared library.
+ test -n "$library_names" && $echo "$modename: warning: \`$file' was not linked with \`-export-dynamic'"
+ continue
+ fi
+
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$dir" = "X$file" && dir=.
+
+ if test -f "$dir/$objdir/$dlname"; then
+ dir="$dir/$objdir"
+ else
+ $echo "$modename: cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" 1>&2
+ exit $EXIT_FAILURE
+ fi
+ ;;
+
+ *.lo)
+ # Just add the directory containing the .lo file.
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$dir" = "X$file" && dir=.
+ ;;
+
+ *)
+ $echo "$modename: warning \`-dlopen' is ignored for non-libtool libraries and objects" 1>&2
+ continue
+ ;;
+ esac
+
+ # Get the absolute pathname.
+ absdir=`cd "$dir" && pwd`
+ test -n "$absdir" && dir="$absdir"
+
+ # Now add the directory to shlibpath_var.
+ if eval "test -z \"\$$shlibpath_var\""; then
+ eval "$shlibpath_var=\"\$dir\""
+ else
+ eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\""
+ fi
+ done
+
+ # This variable tells wrapper scripts just to set shlibpath_var
+ # rather than running their programs.
+ libtool_execute_magic="$magic"
+
+ # Check if any of the arguments is a wrapper script.
+ args=
+ for file
+ do
+ case $file in
+ -*) ;;
+ *)
+ # Do a test to see if this is really a libtool program.
+ if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ # If there is no directory component, then add one.
+ case $file in
+ */* | *\\*) . $file ;;
+ *) . ./$file ;;
+ esac
+
+ # Transform arg to wrapped name.
+ file="$progdir/$program"
+ fi
+ ;;
+ esac
+ # Quote arguments (to preserve shell metacharacters).
+ file=`$echo "X$file" | $Xsed -e "$sed_quote_subst"`
+ args="$args \"$file\""
+ done
+
+ if test -z "$run"; then
+ if test -n "$shlibpath_var"; then
+ # Export the shlibpath_var.
+ eval "export $shlibpath_var"
+ fi
+
+ # Restore saved environment variables
+ for lt_var in LANG LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
+ do
+ eval "if test \"\${save_$lt_var+set}\" = set; then
+ $lt_var=\$save_$lt_var; export $lt_var
+ else
+ $lt_unset $lt_var
+ fi"
+ done
+
+
+ # Now prepare to actually exec the command.
+ exec_cmd="\$cmd$args"
+ else
+ # Display what would be done.
+ if test -n "$shlibpath_var"; then
+ eval "\$echo \"\$shlibpath_var=\$$shlibpath_var\""
+ $echo "export $shlibpath_var"
+ fi
+ $echo "$cmd$args"
+ exit $EXIT_SUCCESS
+ fi
+ ;;
+
+ # libtool clean and uninstall mode
+ clean | uninstall)
+ modename="$modename: $mode"
+ rm="$nonopt"
+ files=
+ rmforce=
+ exit_status=0
+
+ # This variable tells wrapper scripts just to set variables rather
+ # than running their programs.
+ libtool_install_magic="$magic"
+
+ for arg
+ do
+ case $arg in
+ -f) rm="$rm $arg"; rmforce=yes ;;
+ -*) rm="$rm $arg" ;;
+ *) files="$files $arg" ;;
+ esac
+ done
+
+ if test -z "$rm"; then
+ $echo "$modename: you must specify an RM program" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+
+ rmdirs=
+
+ origobjdir="$objdir"
+ for file in $files; do
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$dir" = "X$file"; then
+ dir=.
+ objdir="$origobjdir"
+ else
+ objdir="$dir/$origobjdir"
+ fi
+ name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ test "$mode" = uninstall && objdir="$dir"
+
+ # Remember objdir for removal later, being careful to avoid duplicates
+ if test "$mode" = clean; then
+ case " $rmdirs " in
+ *" $objdir "*) ;;
+ *) rmdirs="$rmdirs $objdir" ;;
+ esac
+ fi
+
+ # Don't error if the file doesn't exist and rm -f was used.
+ if (test -L "$file") >/dev/null 2>&1 \
+ || (test -h "$file") >/dev/null 2>&1 \
+ || test -f "$file"; then
+ :
+ elif test -d "$file"; then
+ exit_status=1
+ continue
+ elif test "$rmforce" = yes; then
+ continue
+ fi
+
+ rmfiles="$file"
+
+ case $name in
+ *.la)
+ # Possibly a libtool archive, so verify it.
+ if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ . $dir/$name
+
+ # Delete the libtool libraries and symlinks.
+ for n in $library_names; do
+ rmfiles="$rmfiles $objdir/$n"
+ done
+ test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library"
+
+ case "$mode" in
+ clean)
+ case " $library_names " in
+ # " " in the beginning catches empty $dlname
+ *" $dlname "*) ;;
+ *) rmfiles="$rmfiles $objdir/$dlname" ;;
+ esac
+ test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i"
+ ;;
+ uninstall)
+ if test -n "$library_names"; then
+ # Do each command in the postuninstall commands.
+ cmds=$postuninstall_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd"
+ if test "$?" -ne 0 && test "$rmforce" != yes; then
+ exit_status=1
+ fi
+ done
+ IFS="$save_ifs"
+ fi
+
+ if test -n "$old_library"; then
+ # Do each command in the old_postuninstall commands.
+ cmds=$old_postuninstall_cmds
+ save_ifs="$IFS"; IFS='~'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ eval cmd=\"$cmd\"
+ $show "$cmd"
+ $run eval "$cmd"
+ if test "$?" -ne 0 && test "$rmforce" != yes; then
+ exit_status=1
+ fi
+ done
+ IFS="$save_ifs"
+ fi
+ # FIXME: should reinstall the best remaining shared library.
+ ;;
+ esac
+ fi
+ ;;
+
+ *.lo)
+ # Possibly a libtool object, so verify it.
+ if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+
+ # Read the .lo file
+ . $dir/$name
+
+ # Add PIC object to the list of files to remove.
+ if test -n "$pic_object" \
+ && test "$pic_object" != none; then
+ rmfiles="$rmfiles $dir/$pic_object"
+ fi
+
+ # Add non-PIC object to the list of files to remove.
+ if test -n "$non_pic_object" \
+ && test "$non_pic_object" != none; then
+ rmfiles="$rmfiles $dir/$non_pic_object"
+ fi
+ fi
+ ;;
+
+ *)
+ if test "$mode" = clean ; then
+ noexename=$name
+ case $file in
+ *.exe)
+ file=`$echo $file|${SED} 's,.exe$,,'`
+ noexename=`$echo $name|${SED} 's,.exe$,,'`
+ # $file with .exe has already been added to rmfiles,
+ # add $file without .exe
+ rmfiles="$rmfiles $file"
+ ;;
+ esac
+ # Do a test to see if this is a libtool program.
+ if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then
+ relink_command=
+ . $dir/$noexename
+
+ # note $name still contains .exe if it was in $file originally
+ # as does the version of $file that was added into $rmfiles
+ rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}"
+ if test "$fast_install" = yes && test -n "$relink_command"; then
+ rmfiles="$rmfiles $objdir/lt-$name"
+ fi
+ if test "X$noexename" != "X$name" ; then
+ rmfiles="$rmfiles $objdir/lt-${noexename}.c"
+ fi
+ fi
+ fi
+ ;;
+ esac
+ $show "$rm $rmfiles"
+ $run $rm $rmfiles || exit_status=1
+ done
+ objdir="$origobjdir"
+
+ # Try to remove the ${objdir}s in the directories where we deleted files
+ for dir in $rmdirs; do
+ if test -d "$dir"; then
+ $show "rmdir $dir"
+ $run rmdir $dir >/dev/null 2>&1
+ fi
+ done
+
+ exit $exit_status
+ ;;
+
+ "")
+ $echo "$modename: you must specify a MODE" 1>&2
+ $echo "$generic_help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+ esac
+
+ if test -z "$exec_cmd"; then
+ $echo "$modename: invalid operation mode \`$mode'" 1>&2
+ $echo "$generic_help" 1>&2
+ exit $EXIT_FAILURE
+ fi
+fi # test -z "$show_help"
+
+if test -n "$exec_cmd"; then
+ eval exec $exec_cmd
+ exit $EXIT_FAILURE
+fi
+
+# We need to display help for each of the modes.
+case $mode in
+"") $echo \
+"Usage: $modename [OPTION]... [MODE-ARG]...
+
+Provide generalized library-building support services.
+
+ --config show all configuration variables
+ --debug enable verbose shell tracing
+-n, --dry-run display commands without modifying any files
+ --features display basic configuration information and exit
+ --finish same as \`--mode=finish'
+ --help display this help message and exit
+ --mode=MODE use operation mode MODE [default=inferred from MODE-ARGS]
+ --quiet same as \`--silent'
+ --silent don't print informational messages
+ --tag=TAG use configuration variables from tag TAG
+ --version print version information
+
+MODE must be one of the following:
+
+ clean remove files from the build directory
+ compile compile a source file into a libtool object
+ execute automatically set library path, then run a program
+ finish complete the installation of libtool libraries
+ install install libraries or executables
+ link create a library or an executable
+ uninstall remove libraries from an installed directory
+
+MODE-ARGS vary depending on the MODE. Try \`$modename --help --mode=MODE' for
+a more detailed description of MODE.
+
+Report bugs to <bug-libtool at gnu.org>."
+ exit $EXIT_SUCCESS
+ ;;
+
+clean)
+ $echo \
+"Usage: $modename [OPTION]... --mode=clean RM [RM-OPTION]... FILE...
+
+Remove files from the build directory.
+
+RM is the name of the program to use to delete files associated with each FILE
+(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed
+to RM.
+
+If FILE is a libtool library, object or program, all the files associated
+with it are deleted. Otherwise, only FILE itself is deleted using RM."
+ ;;
+
+compile)
+ $echo \
+"Usage: $modename [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE
+
+Compile a source file into a libtool library object.
+
+This mode accepts the following additional options:
+
+ -o OUTPUT-FILE set the output file name to OUTPUT-FILE
+ -prefer-pic try to building PIC objects only
+ -prefer-non-pic try to building non-PIC objects only
+ -static always build a \`.o' file suitable for static linking
+
+COMPILE-COMMAND is a command to be used in creating a \`standard' object file
+from the given SOURCEFILE.
+
+The output file name is determined by removing the directory component from
+SOURCEFILE, then substituting the C source code suffix \`.c' with the
+library object suffix, \`.lo'."
+ ;;
+
+execute)
+ $echo \
+"Usage: $modename [OPTION]... --mode=execute COMMAND [ARGS]...
+
+Automatically set library path, then run a program.
+
+This mode accepts the following additional options:
+
+ -dlopen FILE add the directory containing FILE to the library path
+
+This mode sets the library path environment variable according to \`-dlopen'
+flags.
+
+If any of the ARGS are libtool executable wrappers, then they are translated
+into their corresponding uninstalled binary, and any of their required library
+directories are added to the library path.
+
+Then, COMMAND is executed, with ARGS as arguments."
+ ;;
+
+finish)
+ $echo \
+"Usage: $modename [OPTION]... --mode=finish [LIBDIR]...
+
+Complete the installation of libtool libraries.
+
+Each LIBDIR is a directory that contains libtool libraries.
+
+The commands that this mode executes may require superuser privileges. Use
+the \`--dry-run' option if you just want to see what would be executed."
+ ;;
+
+install)
+ $echo \
+"Usage: $modename [OPTION]... --mode=install INSTALL-COMMAND...
+
+Install executables or libraries.
+
+INSTALL-COMMAND is the installation command. The first component should be
+either the \`install' or \`cp' program.
+
+The rest of the components are interpreted as arguments to that command (only
+BSD-compatible install options are recognized)."
+ ;;
+
+link)
+ $echo \
+"Usage: $modename [OPTION]... --mode=link LINK-COMMAND...
+
+Link object files or libraries together to form another library, or to
+create an executable program.
+
+LINK-COMMAND is a command using the C compiler that you would use to create
+a program from several object files.
+
+The following components of LINK-COMMAND are treated specially:
+
+ -all-static do not do any dynamic linking at all
+ -avoid-version do not add a version suffix if possible
+ -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime
+ -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols
+ -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3)
+ -export-symbols SYMFILE
+ try to export only the symbols listed in SYMFILE
+ -export-symbols-regex REGEX
+ try to export only the symbols matching REGEX
+ -LLIBDIR search LIBDIR for required installed libraries
+ -lNAME OUTPUT-FILE requires the installed library libNAME
+ -module build a library that can dlopened
+ -no-fast-install disable the fast-install mode
+ -no-install link a not-installable executable
+ -no-undefined declare that a library does not refer to external symbols
+ -o OUTPUT-FILE create OUTPUT-FILE from the specified objects
+ -objectlist FILE Use a list of object files found in FILE to specify objects
+ -precious-files-regex REGEX
+ don't remove output files matching REGEX
+ -release RELEASE specify package release information
+ -rpath LIBDIR the created library will eventually be installed in LIBDIR
+ -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries
+ -static do not do any dynamic linking of uninstalled libtool libraries
+ -static-libtool-libs
+ do not do any dynamic linking of libtool libraries
+ -version-info CURRENT[:REVISION[:AGE]]
+ specify library version info [each variable defaults to 0]
+
+All other options (arguments beginning with \`-') are ignored.
+
+Every other argument is treated as a filename. Files ending in \`.la' are
+treated as uninstalled libtool libraries, other files are standard or library
+object files.
+
+If the OUTPUT-FILE ends in \`.la', then a libtool library is created,
+only library objects (\`.lo' files) may be specified, and \`-rpath' is
+required, except when creating a convenience library.
+
+If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created
+using \`ar' and \`ranlib', or on Windows using \`lib'.
+
+If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file
+is created, otherwise an executable program is created."
+ ;;
+
+uninstall)
+ $echo \
+"Usage: $modename [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...
+
+Remove libraries from an installation directory.
+
+RM is the name of the program to use to delete files associated with each FILE
+(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed
+to RM.
+
+If FILE is a libtool library, all the files associated with it are deleted.
+Otherwise, only FILE itself is deleted using RM."
+ ;;
+
+*)
+ $echo "$modename: invalid operation mode \`$mode'" 1>&2
+ $echo "$help" 1>&2
+ exit $EXIT_FAILURE
+ ;;
+esac
+
+$echo
+$echo "Try \`$modename --help' for more information about other modes."
+
+exit $?
+
+# The TAGs below are defined such that we never get into a situation
+# in which we disable both kinds of libraries. Given conflicting
+# choices, we go for a static library, that is the most portable,
+# since we can't tell whether shared libraries were disabled because
+# the user asked for that or because the platform doesn't support
+# them. This is particularly important on AIX, because we don't
+# support having both static and shared libraries enabled at the same
+# time on that platform, so we default to a shared-only configuration.
+# If a disable-shared tag is given, we'll fallback to a static-only
+# configuration. But we'll never go from static-only to shared-only.
+
+# ### BEGIN LIBTOOL TAG CONFIG: disable-shared
+disable_libs=shared
+# ### END LIBTOOL TAG CONFIG: disable-shared
+
+# ### BEGIN LIBTOOL TAG CONFIG: disable-static
+disable_libs=static
+# ### END LIBTOOL TAG CONFIG: disable-static
+
+# Local Variables:
+# mode:shell-script
+# sh-indentation:2
+# End:
diff --git a/jasper-1.900.1-6ct/acaux/missing b/jasper-1.900.1-6ct/acaux/missing
new file mode 100644
index 0000000..6a37006
--- /dev/null
+++ b/jasper-1.900.1-6ct/acaux/missing
@@ -0,0 +1,336 @@
+#! /bin/sh
+# Common stub for a few missing GNU programs while installing.
+# Copyright (C) 1996, 1997, 1999, 2000, 2002 Free Software Foundation, Inc.
+# Originally by Fran,cois Pinard <pinard at iro.umontreal.ca>, 1996.
+
+# 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, 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, Inc., 59 Temple Place - Suite 330, Boston, MA
+# 02111-1307, USA.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+if test $# -eq 0; then
+ echo 1>&2 "Try \`$0 --help' for more information"
+ exit 1
+fi
+
+run=:
+
+# In the cases where this matters, `missing' is being run in the
+# srcdir already.
+if test -f configure.ac; then
+ configure_ac=configure.ac
+else
+ configure_ac=configure.in
+fi
+
+case "$1" in
+--run)
+ # Try to run requested program, and just exit if it succeeds.
+ run=
+ shift
+ "$@" && exit 0
+ ;;
+esac
+
+# If it does not exist, or fails to run (possibly an outdated version),
+# try to emulate it.
+case "$1" in
+
+ -h|--h|--he|--hel|--help)
+ echo "\
+$0 [OPTION]... PROGRAM [ARGUMENT]...
+
+Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an
+error status if there is no known handling for PROGRAM.
+
+Options:
+ -h, --help display this help and exit
+ -v, --version output version information and exit
+ --run try to run the given command, and emulate it if it fails
+
+Supported PROGRAM values:
+ aclocal touch file \`aclocal.m4'
+ autoconf touch file \`configure'
+ autoheader touch file \`config.h.in'
+ automake touch all \`Makefile.in' files
+ bison create \`y.tab.[ch]', if possible, from existing .[ch]
+ flex create \`lex.yy.c', if possible, from existing .c
+ help2man touch the output file
+ lex create \`lex.yy.c', if possible, from existing .c
+ makeinfo touch the output file
+ tar try tar, gnutar, gtar, then tar without non-portable flags
+ yacc create \`y.tab.[ch]', if possible, from existing .[ch]"
+ ;;
+
+ -v|--v|--ve|--ver|--vers|--versi|--versio|--version)
+ echo "missing 0.4 - GNU automake"
+ ;;
+
+ -*)
+ echo 1>&2 "$0: Unknown \`$1' option"
+ echo 1>&2 "Try \`$0 --help' for more information"
+ exit 1
+ ;;
+
+ aclocal*)
+ if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+ # We have it, but it failed.
+ exit 1
+ fi
+
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified \`acinclude.m4' or \`${configure_ac}'. You might want
+ to install the \`Automake' and \`Perl' packages. Grab them from
+ any GNU archive site."
+ touch aclocal.m4
+ ;;
+
+ autoconf)
+ if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+ # We have it, but it failed.
+ exit 1
+ fi
+
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified \`${configure_ac}'. You might want to install the
+ \`Autoconf' and \`GNU m4' packages. Grab them from any GNU
+ archive site."
+ touch configure
+ ;;
+
+ autoheader)
+ if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+ # We have it, but it failed.
+ exit 1
+ fi
+
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified \`acconfig.h' or \`${configure_ac}'. You might want
+ to install the \`Autoconf' and \`GNU m4' packages. Grab them
+ from any GNU archive site."
+ files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}`
+ test -z "$files" && files="config.h"
+ touch_files=
+ for f in $files; do
+ case "$f" in
+ *:*) touch_files="$touch_files "`echo "$f" |
+ sed -e 's/^[^:]*://' -e 's/:.*//'`;;
+ *) touch_files="$touch_files $f.in";;
+ esac
+ done
+ touch $touch_files
+ ;;
+
+ automake*)
+ if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+ # We have it, but it failed.
+ exit 1
+ fi
+
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'.
+ You might want to install the \`Automake' and \`Perl' packages.
+ Grab them from any GNU archive site."
+ find . -type f -name Makefile.am -print |
+ sed 's/\.am$/.in/' |
+ while read f; do touch "$f"; done
+ ;;
+
+ autom4te)
+ if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+ # We have it, but it failed.
+ exit 1
+ fi
+
+ echo 1>&2 "\
+WARNING: \`$1' is needed, and you do not seem to have it handy on your
+ system. You might have modified some files without having the
+ proper tools for further handling them.
+ You can get \`$1Help2man' as part of \`Autoconf' from any GNU
+ archive site."
+
+ file=`echo "$*" | sed -n 's/.*--output[ =]*\([^ ]*\).*/\1/p'`
+ test -z "$file" && file=`echo "$*" | sed -n 's/.*-o[ ]*\([^ ]*\).*/\1/p'`
+ if test -f "$file"; then
+ touch $file
+ else
+ test -z "$file" || exec >$file
+ echo "#! /bin/sh"
+ echo "# Created by GNU Automake missing as a replacement of"
+ echo "# $ $@"
+ echo "exit 0"
+ chmod +x $file
+ exit 1
+ fi
+ ;;
+
+ bison|yacc)
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified a \`.y' file. You may need the \`Bison' package
+ in order for those modifications to take effect. You can get
+ \`Bison' from any GNU archive site."
+ rm -f y.tab.c y.tab.h
+ if [ $# -ne 1 ]; then
+ eval LASTARG="\${$#}"
+ case "$LASTARG" in
+ *.y)
+ SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'`
+ if [ -f "$SRCFILE" ]; then
+ cp "$SRCFILE" y.tab.c
+ fi
+ SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'`
+ if [ -f "$SRCFILE" ]; then
+ cp "$SRCFILE" y.tab.h
+ fi
+ ;;
+ esac
+ fi
+ if [ ! -f y.tab.h ]; then
+ echo >y.tab.h
+ fi
+ if [ ! -f y.tab.c ]; then
+ echo 'main() { return 0; }' >y.tab.c
+ fi
+ ;;
+
+ lex|flex)
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified a \`.l' file. You may need the \`Flex' package
+ in order for those modifications to take effect. You can get
+ \`Flex' from any GNU archive site."
+ rm -f lex.yy.c
+ if [ $# -ne 1 ]; then
+ eval LASTARG="\${$#}"
+ case "$LASTARG" in
+ *.l)
+ SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'`
+ if [ -f "$SRCFILE" ]; then
+ cp "$SRCFILE" lex.yy.c
+ fi
+ ;;
+ esac
+ fi
+ if [ ! -f lex.yy.c ]; then
+ echo 'main() { return 0; }' >lex.yy.c
+ fi
+ ;;
+
+ help2man)
+ if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+ # We have it, but it failed.
+ exit 1
+ fi
+
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified a dependency of a manual page. You may need the
+ \`Help2man' package in order for those modifications to take
+ effect. You can get \`Help2man' from any GNU archive site."
+
+ file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'`
+ if test -z "$file"; then
+ file=`echo "$*" | sed -n 's/.*--output=\([^ ]*\).*/\1/p'`
+ fi
+ if [ -f "$file" ]; then
+ touch $file
+ else
+ test -z "$file" || exec >$file
+ echo ".ab help2man is required to generate this page"
+ exit 1
+ fi
+ ;;
+
+ makeinfo)
+ if test -z "$run" && (makeinfo --version) > /dev/null 2>&1; then
+ # We have makeinfo, but it failed.
+ exit 1
+ fi
+
+ echo 1>&2 "\
+WARNING: \`$1' is missing on your system. You should only need it if
+ you modified a \`.texi' or \`.texinfo' file, or any other file
+ indirectly affecting the aspect of the manual. The spurious
+ call might also be the consequence of using a buggy \`make' (AIX,
+ DU, IRIX). You might want to install the \`Texinfo' package or
+ the \`GNU make' package. Grab either from any GNU archive site."
+ file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'`
+ if test -z "$file"; then
+ file=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'`
+ file=`sed -n '/^@setfilename/ { s/.* \([^ ]*\) *$/\1/; p; q; }' $file`
+ fi
+ touch $file
+ ;;
+
+ tar)
+ shift
+ if test -n "$run"; then
+ echo 1>&2 "ERROR: \`tar' requires --run"
+ exit 1
+ fi
+
+ # We have already tried tar in the generic part.
+ # Look for gnutar/gtar before invocation to avoid ugly error
+ # messages.
+ if (gnutar --version > /dev/null 2>&1); then
+ gnutar "$@" && exit 0
+ fi
+ if (gtar --version > /dev/null 2>&1); then
+ gtar "$@" && exit 0
+ fi
+ firstarg="$1"
+ if shift; then
+ case "$firstarg" in
+ *o*)
+ firstarg=`echo "$firstarg" | sed s/o//`
+ tar "$firstarg" "$@" && exit 0
+ ;;
+ esac
+ case "$firstarg" in
+ *h*)
+ firstarg=`echo "$firstarg" | sed s/h//`
+ tar "$firstarg" "$@" && exit 0
+ ;;
+ esac
+ fi
+
+ echo 1>&2 "\
+WARNING: I can't seem to be able to run \`tar' with the given arguments.
+ You may want to install GNU tar or Free paxutils, or check the
+ command line arguments."
+ exit 1
+ ;;
+
+ *)
+ echo 1>&2 "\
+WARNING: \`$1' is needed, and you do not seem to have it handy on your
+ system. You might have modified some files without having the
+ proper tools for further handling them. Check the \`README' file,
+ it often tells you about the needed prerequirements for installing
+ this package. You may also peek at any GNU archive site, in case
+ some other package would contain this missing \`$1' program."
+ exit 1
+ ;;
+esac
+
+exit 0
diff --git a/jasper-1.900.1-6ct/acaux/mkinstalldirs b/jasper-1.900.1-6ct/acaux/mkinstalldirs
new file mode 100644
index 0000000..8ab885e
--- /dev/null
+++ b/jasper-1.900.1-6ct/acaux/mkinstalldirs
@@ -0,0 +1,99 @@
+#! /bin/sh
+# mkinstalldirs --- make directory hierarchy
+# Author: Noah Friedman <friedman at prep.ai.mit.edu>
+# Created: 1993-05-16
+# Public domain
+
+errstatus=0
+dirmode=""
+
+usage="\
+Usage: mkinstalldirs [-h] [--help] [-m mode] dir ..."
+
+# process command line arguments
+while test $# -gt 0 ; do
+ case "${1}" in
+ -h | --help | --h* ) # -h for help
+ echo "${usage}" 1>&2; exit 0 ;;
+ -m ) # -m PERM arg
+ shift
+ test $# -eq 0 && { echo "${usage}" 1>&2; exit 1; }
+ dirmode="${1}"
+ shift ;;
+ -- ) shift; break ;; # stop option processing
+ -* ) echo "${usage}" 1>&2; exit 1 ;; # unknown option
+ * ) break ;; # first non-opt arg
+ esac
+done
+
+for file
+do
+ if test -d "$file"; then
+ shift
+ else
+ break
+ fi
+done
+
+case $# in
+0) exit 0 ;;
+esac
+
+case $dirmode in
+'')
+ if mkdir -p -- . 2>/dev/null; then
+ echo "mkdir -p -- $*"
+ exec mkdir -p -- "$@"
+ fi ;;
+*)
+ if mkdir -m "$dirmode" -p -- . 2>/dev/null; then
+ echo "mkdir -m $dirmode -p -- $*"
+ exec mkdir -m "$dirmode" -p -- "$@"
+ fi ;;
+esac
+
+for file
+do
+ set fnord `echo ":$file" | sed -ne 's/^:\//#/;s/^://;s/\// /g;s/^#/\//;p'`
+ shift
+
+ pathcomp=
+ for d
+ do
+ pathcomp="$pathcomp$d"
+ case "$pathcomp" in
+ -* ) pathcomp=./$pathcomp ;;
+ esac
+
+ if test ! -d "$pathcomp"; then
+ echo "mkdir $pathcomp"
+
+ mkdir "$pathcomp" || lasterr=$?
+
+ if test ! -d "$pathcomp"; then
+ errstatus=$lasterr
+ else
+ if test ! -z "$dirmode"; then
+ echo "chmod $dirmode $pathcomp"
+
+ lasterr=""
+ chmod "$dirmode" "$pathcomp" || lasterr=$?
+
+ if test ! -z "$lasterr"; then
+ errstatus=$lasterr
+ fi
+ fi
+ fi
+ fi
+
+ pathcomp="$pathcomp/"
+ done
+done
+
+exit $errstatus
+
+# Local Variables:
+# mode: shell-script
+# sh-indentation: 3
+# End:
+# mkinstalldirs ends here
diff --git a/jasper-1.900.1-6ct/aclocal.m4 b/jasper-1.900.1-6ct/aclocal.m4
new file mode 100644
index 0000000..b9e32cf
--- /dev/null
+++ b/jasper-1.900.1-6ct/aclocal.m4
@@ -0,0 +1,7249 @@
+# generated automatically by aclocal 1.9.6 -*- Autoconf -*-
+
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
+# 2005 Free Software Foundation, Inc.
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
+
+# serial 48 AC_PROG_LIBTOOL
+
+
+# AC_PROVIDE_IFELSE(MACRO-NAME, IF-PROVIDED, IF-NOT-PROVIDED)
+# -----------------------------------------------------------
+# If this macro is not defined by Autoconf, define it here.
+m4_ifdef([AC_PROVIDE_IFELSE],
+ [],
+ [m4_define([AC_PROVIDE_IFELSE],
+ [m4_ifdef([AC_PROVIDE_$1],
+ [$2], [$3])])])
+
+
+# AC_PROG_LIBTOOL
+# ---------------
+AC_DEFUN([AC_PROG_LIBTOOL],
+[AC_REQUIRE([_AC_PROG_LIBTOOL])dnl
+dnl If AC_PROG_CXX has already been expanded, run AC_LIBTOOL_CXX
+dnl immediately, otherwise, hook it in at the end of AC_PROG_CXX.
+ AC_PROVIDE_IFELSE([AC_PROG_CXX],
+ [AC_LIBTOOL_CXX],
+ [define([AC_PROG_CXX], defn([AC_PROG_CXX])[AC_LIBTOOL_CXX
+ ])])
+dnl And a similar setup for Fortran 77 support
+ AC_PROVIDE_IFELSE([AC_PROG_F77],
+ [AC_LIBTOOL_F77],
+ [define([AC_PROG_F77], defn([AC_PROG_F77])[AC_LIBTOOL_F77
+])])
+
+dnl Quote A][M_PROG_GCJ so that aclocal doesn't bring it in needlessly.
+dnl If either AC_PROG_GCJ or A][M_PROG_GCJ have already been expanded, run
+dnl AC_LIBTOOL_GCJ immediately, otherwise, hook it in at the end of both.
+ AC_PROVIDE_IFELSE([AC_PROG_GCJ],
+ [AC_LIBTOOL_GCJ],
+ [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],
+ [AC_LIBTOOL_GCJ],
+ [AC_PROVIDE_IFELSE([LT_AC_PROG_GCJ],
+ [AC_LIBTOOL_GCJ],
+ [ifdef([AC_PROG_GCJ],
+ [define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[AC_LIBTOOL_GCJ])])
+ ifdef([A][M_PROG_GCJ],
+ [define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[AC_LIBTOOL_GCJ])])
+ ifdef([LT_AC_PROG_GCJ],
+ [define([LT_AC_PROG_GCJ],
+ defn([LT_AC_PROG_GCJ])[AC_LIBTOOL_GCJ])])])])
+])])# AC_PROG_LIBTOOL
+
+
+# _AC_PROG_LIBTOOL
+# ----------------
+AC_DEFUN([_AC_PROG_LIBTOOL],
+[AC_REQUIRE([AC_LIBTOOL_SETUP])dnl
+AC_BEFORE([$0],[AC_LIBTOOL_CXX])dnl
+AC_BEFORE([$0],[AC_LIBTOOL_F77])dnl
+AC_BEFORE([$0],[AC_LIBTOOL_GCJ])dnl
+
+# This can be used to rebuild libtool when needed
+LIBTOOL_DEPS="$ac_aux_dir/ltmain.sh"
+
+# Always use our own libtool.
+LIBTOOL='$(SHELL) $(top_builddir)/libtool'
+AC_SUBST(LIBTOOL)dnl
+
+# Prevent multiple expansion
+define([AC_PROG_LIBTOOL], [])
+])# _AC_PROG_LIBTOOL
+
+
+# AC_LIBTOOL_SETUP
+# ----------------
+AC_DEFUN([AC_LIBTOOL_SETUP],
+[AC_PREREQ(2.50)dnl
+AC_REQUIRE([AC_ENABLE_SHARED])dnl
+AC_REQUIRE([AC_ENABLE_STATIC])dnl
+AC_REQUIRE([AC_ENABLE_FAST_INSTALL])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_PROG_LD])dnl
+AC_REQUIRE([AC_PROG_LD_RELOAD_FLAG])dnl
+AC_REQUIRE([AC_PROG_NM])dnl
+
+AC_REQUIRE([AC_PROG_LN_S])dnl
+AC_REQUIRE([AC_DEPLIBS_CHECK_METHOD])dnl
+# Autoconf 2.13's AC_OBJEXT and AC_EXEEXT macros only works for C compilers!
+AC_REQUIRE([AC_OBJEXT])dnl
+AC_REQUIRE([AC_EXEEXT])dnl
+dnl
+
+AC_LIBTOOL_SYS_MAX_CMD_LEN
+AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE
+AC_LIBTOOL_OBJDIR
+
+AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl
+_LT_AC_PROG_ECHO_BACKSLASH
+
+case $host_os in
+aix3*)
+ # AIX sometimes has problems with the GCC collect2 program. For some
+ # reason, if we set the COLLECT_NAMES environment variable, the problems
+ # vanish in a puff of smoke.
+ if test "X${COLLECT_NAMES+set}" != Xset; then
+ COLLECT_NAMES=
+ export COLLECT_NAMES
+ fi
+ ;;
+esac
+
+# Sed substitution that helps us do robust quoting. It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed='sed -e 1s/^X//'
+[sed_quote_subst='s/\([\\"\\`$\\\\]\)/\\\1/g']
+
+# Same as above, but do not quote variable references.
+[double_quote_subst='s/\([\\"\\`\\\\]\)/\\\1/g']
+
+# Sed substitution to delay expansion of an escaped shell variable in a
+# double_quote_subst'ed string.
+delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
+
+# Sed substitution to avoid accidental globbing in evaled expressions
+no_glob_subst='s/\*/\\\*/g'
+
+# Constants:
+rm="rm -f"
+
+# Global variables:
+default_ofile=libtool
+can_build_shared=yes
+
+# All known linkers require a `.a' archive for static linking (except MSVC,
+# which needs '.lib').
+libext=a
+ltmain="$ac_aux_dir/ltmain.sh"
+ofile="$default_ofile"
+with_gnu_ld="$lt_cv_prog_gnu_ld"
+
+AC_CHECK_TOOL(AR, ar, false)
+AC_CHECK_TOOL(RANLIB, ranlib, :)
+AC_CHECK_TOOL(STRIP, strip, :)
+
+old_CC="$CC"
+old_CFLAGS="$CFLAGS"
+
+# Set sane defaults for various variables
+test -z "$AR" && AR=ar
+test -z "$AR_FLAGS" && AR_FLAGS=cru
+test -z "$AS" && AS=as
+test -z "$CC" && CC=cc
+test -z "$LTCC" && LTCC=$CC
+test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+test -z "$LD" && LD=ld
+test -z "$LN_S" && LN_S="ln -s"
+test -z "$MAGIC_CMD" && MAGIC_CMD=file
+test -z "$NM" && NM=nm
+test -z "$SED" && SED=sed
+test -z "$OBJDUMP" && OBJDUMP=objdump
+test -z "$RANLIB" && RANLIB=:
+test -z "$STRIP" && STRIP=:
+test -z "$ac_objext" && ac_objext=o
+
+# Determine commands to create old-style static archives.
+old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs'
+old_postinstall_cmds='chmod 644 $oldlib'
+old_postuninstall_cmds=
+
+if test -n "$RANLIB"; then
+ case $host_os in
+ openbsd*)
+ old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib"
+ ;;
+ *)
+ old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib"
+ ;;
+ esac
+ old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib"
+fi
+
+_LT_CC_BASENAME([$compiler])
+
+# Only perform the check for file, if the check method requires it
+case $deplibs_check_method in
+file_magic*)
+ if test "$file_magic_cmd" = '$MAGIC_CMD'; then
+ AC_PATH_MAGIC
+ fi
+ ;;
+esac
+
+AC_PROVIDE_IFELSE([AC_LIBTOOL_DLOPEN], enable_dlopen=yes, enable_dlopen=no)
+AC_PROVIDE_IFELSE([AC_LIBTOOL_WIN32_DLL],
+enable_win32_dll=yes, enable_win32_dll=no)
+
+AC_ARG_ENABLE([libtool-lock],
+ [AC_HELP_STRING([--disable-libtool-lock],
+ [avoid locking (might break parallel builds)])])
+test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
+
+AC_ARG_WITH([pic],
+ [AC_HELP_STRING([--with-pic],
+ [try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
+ [pic_mode="$withval"],
+ [pic_mode=default])
+test -z "$pic_mode" && pic_mode=default
+
+# Use C for the default configuration in the libtool script
+tagname=
+AC_LIBTOOL_LANG_C_CONFIG
+_LT_AC_TAGCONFIG
+])# AC_LIBTOOL_SETUP
+
+
+# _LT_AC_SYS_COMPILER
+# -------------------
+AC_DEFUN([_LT_AC_SYS_COMPILER],
+[AC_REQUIRE([AC_PROG_CC])dnl
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+])# _LT_AC_SYS_COMPILER
+
+
+# _LT_CC_BASENAME(CC)
+# -------------------
+# Calculate cc_basename. Skip known compiler wrappers and cross-prefix.
+AC_DEFUN([_LT_CC_BASENAME],
+[for cc_temp in $1""; do
+ case $cc_temp in
+ compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
+ distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
+ \-*) ;;
+ *) break;;
+ esac
+done
+cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+])
+
+
+# _LT_COMPILER_BOILERPLATE
+# ------------------------
+# Check for compiler boilerplate output or warnings with
+# the simple compiler test code.
+AC_DEFUN([_LT_COMPILER_BOILERPLATE],
+[ac_outfile=conftest.$ac_objext
+printf "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$rm conftest*
+])# _LT_COMPILER_BOILERPLATE
+
+
+# _LT_LINKER_BOILERPLATE
+# ----------------------
+# Check for linker boilerplate output or warnings with
+# the simple link test code.
+AC_DEFUN([_LT_LINKER_BOILERPLATE],
+[ac_outfile=conftest.$ac_objext
+printf "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$rm conftest*
+])# _LT_LINKER_BOILERPLATE
+
+
+# _LT_AC_SYS_LIBPATH_AIX
+# ----------------------
+# Links a minimal program and checks the executable
+# for the system default hardcoded library path. In most cases,
+# this is /usr/lib:/lib, but when the MPI compilers are used
+# the location of the communication and MPI libs are included too.
+# If we don't find anything, use the default library path according
+# to the aix ld manual.
+AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX],
+[AC_LINK_IFELSE(AC_LANG_PROGRAM,[
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`; fi],[])
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+])# _LT_AC_SYS_LIBPATH_AIX
+
+
+# _LT_AC_SHELL_INIT(ARG)
+# ----------------------
+AC_DEFUN([_LT_AC_SHELL_INIT],
+[ifdef([AC_DIVERSION_NOTICE],
+ [AC_DIVERT_PUSH(AC_DIVERSION_NOTICE)],
+ [AC_DIVERT_PUSH(NOTICE)])
+$1
+AC_DIVERT_POP
+])# _LT_AC_SHELL_INIT
+
+
+# _LT_AC_PROG_ECHO_BACKSLASH
+# --------------------------
+# Add some code to the start of the generated configure script which
+# will find an echo command which doesn't interpret backslashes.
+AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH],
+[_LT_AC_SHELL_INIT([
+# Check that we are running under the correct shell.
+SHELL=${CONFIG_SHELL-/bin/sh}
+
+case X$ECHO in
+X*--fallback-echo)
+ # Remove one level of quotation (which was required for Make).
+ ECHO=`echo "$ECHO" | sed 's,\\\\\[$]\\[$]0,'[$]0','`
+ ;;
+esac
+
+echo=${ECHO-echo}
+if test "X[$]1" = X--no-reexec; then
+ # Discard the --no-reexec flag, and continue.
+ shift
+elif test "X[$]1" = X--fallback-echo; then
+ # Avoid inline document here, it may be left over
+ :
+elif test "X`($echo '\t') 2>/dev/null`" = 'X\t' ; then
+ # Yippee, $echo works!
+ :
+else
+ # Restart under the correct shell.
+ exec $SHELL "[$]0" --no-reexec ${1+"[$]@"}
+fi
+
+if test "X[$]1" = X--fallback-echo; then
+ # used as fallback echo
+ shift
+ cat <<EOF
+[$]*
+EOF
+ exit 0
+fi
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+if test -z "$ECHO"; then
+if test "X${echo_test_string+set}" != Xset; then
+# find a string as large as possible, as long as the shell can cope with it
+ for cmd in 'sed 50q "[$]0"' 'sed 20q "[$]0"' 'sed 10q "[$]0"' 'sed 2q "[$]0"' 'echo test'; do
+ # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ...
+ if (echo_test_string=`eval $cmd`) 2>/dev/null &&
+ echo_test_string=`eval $cmd` &&
+ (test "X$echo_test_string" = "X$echo_test_string") 2>/dev/null
+ then
+ break
+ fi
+ done
+fi
+
+if test "X`($echo '\t') 2>/dev/null`" = 'X\t' &&
+ echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ :
+else
+ # The Solaris, AIX, and Digital Unix default echo programs unquote
+ # backslashes. This makes it impossible to quote backslashes using
+ # echo "$something" | sed 's/\\/\\\\/g'
+ #
+ # So, first we look for a working echo in the user's PATH.
+
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+ for dir in $PATH /usr/ucb; do
+ IFS="$lt_save_ifs"
+ if (test -f $dir/echo || test -f $dir/echo$ac_exeext) &&
+ test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' &&
+ echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ echo="$dir/echo"
+ break
+ fi
+ done
+ IFS="$lt_save_ifs"
+
+ if test "X$echo" = Xecho; then
+ # We didn't find a better echo, so look for alternatives.
+ if test "X`(print -r '\t') 2>/dev/null`" = 'X\t' &&
+ echo_testing_string=`(print -r "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ # This shell has a builtin print -r that does the trick.
+ echo='print -r'
+ elif (test -f /bin/ksh || test -f /bin/ksh$ac_exeext) &&
+ test "X$CONFIG_SHELL" != X/bin/ksh; then
+ # If we have ksh, try running configure again with it.
+ ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh}
+ export ORIGINAL_CONFIG_SHELL
+ CONFIG_SHELL=/bin/ksh
+ export CONFIG_SHELL
+ exec $CONFIG_SHELL "[$]0" --no-reexec ${1+"[$]@"}
+ else
+ # Try using printf.
+ echo='printf %s\n'
+ if test "X`($echo '\t') 2>/dev/null`" = 'X\t' &&
+ echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ # Cool, printf works
+ :
+ elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` &&
+ test "X$echo_testing_string" = 'X\t' &&
+ echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL
+ export CONFIG_SHELL
+ SHELL="$CONFIG_SHELL"
+ export SHELL
+ echo="$CONFIG_SHELL [$]0 --fallback-echo"
+ elif echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` &&
+ test "X$echo_testing_string" = 'X\t' &&
+ echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ echo="$CONFIG_SHELL [$]0 --fallback-echo"
+ else
+ # maybe with a smaller string...
+ prev=:
+
+ for cmd in 'echo test' 'sed 2q "[$]0"' 'sed 10q "[$]0"' 'sed 20q "[$]0"' 'sed 50q "[$]0"'; do
+ if (test "X$echo_test_string" = "X`eval $cmd`") 2>/dev/null
+ then
+ break
+ fi
+ prev="$cmd"
+ done
+
+ if test "$prev" != 'sed 50q "[$]0"'; then
+ echo_test_string=`eval $prev`
+ export echo_test_string
+ exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "[$]0" ${1+"[$]@"}
+ else
+ # Oops. We lost completely, so just stick with echo.
+ echo=echo
+ fi
+ fi
+ fi
+ fi
+fi
+fi
+
+# Copy echo and quote the copy suitably for passing to libtool from
+# the Makefile, instead of quoting the original, which is used later.
+ECHO=$echo
+if test "X$ECHO" = "X$CONFIG_SHELL [$]0 --fallback-echo"; then
+ ECHO="$CONFIG_SHELL \\\$\[$]0 --fallback-echo"
+fi
+
+AC_SUBST(ECHO)
+])])# _LT_AC_PROG_ECHO_BACKSLASH
+
+
+# _LT_AC_LOCK
+# -----------
+AC_DEFUN([_LT_AC_LOCK],
+[AC_ARG_ENABLE([libtool-lock],
+ [AC_HELP_STRING([--disable-libtool-lock],
+ [avoid locking (might break parallel builds)])])
+test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
+
+# Some flags need to be propagated to the compiler or linker for good
+# libtool support.
+case $host in
+ia64-*-hpux*)
+ # Find out which ABI we are using.
+ echo 'int i;' > conftest.$ac_ext
+ if AC_TRY_EVAL(ac_compile); then
+ case `/usr/bin/file conftest.$ac_objext` in
+ *ELF-32*)
+ HPUX_IA64_MODE="32"
+ ;;
+ *ELF-64*)
+ HPUX_IA64_MODE="64"
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+*-*-irix6*)
+ # Find out which ABI we are using.
+ echo '[#]line __oline__ "configure"' > conftest.$ac_ext
+ if AC_TRY_EVAL(ac_compile); then
+ if test "$lt_cv_prog_gnu_ld" = yes; then
+ case `/usr/bin/file conftest.$ac_objext` in
+ *32-bit*)
+ LD="${LD-ld} -melf32bsmip"
+ ;;
+ *N32*)
+ LD="${LD-ld} -melf32bmipn32"
+ ;;
+ *64-bit*)
+ LD="${LD-ld} -melf64bmip"
+ ;;
+ esac
+ else
+ case `/usr/bin/file conftest.$ac_objext` in
+ *32-bit*)
+ LD="${LD-ld} -32"
+ ;;
+ *N32*)
+ LD="${LD-ld} -n32"
+ ;;
+ *64-bit*)
+ LD="${LD-ld} -64"
+ ;;
+ esac
+ fi
+ fi
+ rm -rf conftest*
+ ;;
+
+x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*|s390*-*linux*|sparc*-*linux*)
+ # Find out which ABI we are using.
+ echo 'int i;' > conftest.$ac_ext
+ if AC_TRY_EVAL(ac_compile); then
+ case `/usr/bin/file conftest.o` in
+ *32-bit*)
+ case $host in
+ x86_64-*linux*)
+ LD="${LD-ld} -m elf_i386"
+ ;;
+ ppc64-*linux*|powerpc64-*linux*)
+ LD="${LD-ld} -m elf32ppclinux"
+ ;;
+ s390x-*linux*)
+ LD="${LD-ld} -m elf_s390"
+ ;;
+ sparc64-*linux*)
+ LD="${LD-ld} -m elf32_sparc"
+ ;;
+ esac
+ ;;
+ *64-bit*)
+ case $host in
+ x86_64-*linux*)
+ LD="${LD-ld} -m elf_x86_64"
+ ;;
+ ppc*-*linux*|powerpc*-*linux*)
+ LD="${LD-ld} -m elf64ppc"
+ ;;
+ s390*-*linux*)
+ LD="${LD-ld} -m elf64_s390"
+ ;;
+ sparc*-*linux*)
+ LD="${LD-ld} -m elf64_sparc"
+ ;;
+ esac
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+
+*-*-sco3.2v5*)
+ # On SCO OpenServer 5, we need -belf to get full-featured binaries.
+ SAVE_CFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS -belf"
+ AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf,
+ [AC_LANG_PUSH(C)
+ AC_TRY_LINK([],[],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no])
+ AC_LANG_POP])
+ if test x"$lt_cv_cc_needs_belf" != x"yes"; then
+ # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
+ CFLAGS="$SAVE_CFLAGS"
+ fi
+ ;;
+sparc*-*solaris*)
+ # Find out which ABI we are using.
+ echo 'int i;' > conftest.$ac_ext
+ if AC_TRY_EVAL(ac_compile); then
+ case `/usr/bin/file conftest.o` in
+ *64-bit*)
+ case $lt_cv_prog_gnu_ld in
+ yes*) LD="${LD-ld} -m elf64_sparc" ;;
+ *) LD="${LD-ld} -64" ;;
+ esac
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+
+AC_PROVIDE_IFELSE([AC_LIBTOOL_WIN32_DLL],
+[*-*-cygwin* | *-*-mingw* | *-*-pw32*)
+ AC_CHECK_TOOL(DLLTOOL, dlltool, false)
+ AC_CHECK_TOOL(AS, as, false)
+ AC_CHECK_TOOL(OBJDUMP, objdump, false)
+ ;;
+ ])
+esac
+
+need_locks="$enable_libtool_lock"
+
+])# _LT_AC_LOCK
+
+
+# AC_LIBTOOL_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+# [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE])
+# ----------------------------------------------------------------
+# Check whether the given compiler option works
+AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION],
+[AC_REQUIRE([LT_AC_PROG_SED])
+AC_CACHE_CHECK([$1], [$2],
+ [$2=no
+ ifelse([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4])
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+ lt_compiler_flag="$3"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ # The option is referenced via a variable to avoid confusing sed.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+ (eval "$lt_compile" 2>conftest.err)
+ ac_status=$?
+ cat conftest.err >&AS_MESSAGE_LOG_FD
+ echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+ if (exit $ac_status) && test -s "$ac_outfile"; then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings other than the usual output.
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+ $2=yes
+ fi
+ fi
+ $rm conftest*
+])
+
+if test x"[$]$2" = xyes; then
+ ifelse([$5], , :, [$5])
+else
+ ifelse([$6], , :, [$6])
+fi
+])# AC_LIBTOOL_COMPILER_OPTION
+
+
+# AC_LIBTOOL_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+# [ACTION-SUCCESS], [ACTION-FAILURE])
+# ------------------------------------------------------------
+# Check whether the given compiler option works
+AC_DEFUN([AC_LIBTOOL_LINKER_OPTION],
+[AC_CACHE_CHECK([$1], [$2],
+ [$2=no
+ save_LDFLAGS="$LDFLAGS"
+ LDFLAGS="$LDFLAGS $3"
+ printf "$lt_simple_link_test_code" > conftest.$ac_ext
+ if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+ # The linker can only warn and ignore the option if not recognized
+ # So say no if there are warnings
+ if test -s conftest.err; then
+ # Append any errors to the config.log.
+ cat conftest.err 1>&AS_MESSAGE_LOG_FD
+ $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if diff conftest.exp conftest.er2 >/dev/null; then
+ $2=yes
+ fi
+ else
+ $2=yes
+ fi
+ fi
+ $rm conftest*
+ LDFLAGS="$save_LDFLAGS"
+])
+
+if test x"[$]$2" = xyes; then
+ ifelse([$4], , :, [$4])
+else
+ ifelse([$5], , :, [$5])
+fi
+])# AC_LIBTOOL_LINKER_OPTION
+
+
+# AC_LIBTOOL_SYS_MAX_CMD_LEN
+# --------------------------
+AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN],
+[# find the maximum length of command line arguments
+AC_MSG_CHECKING([the maximum length of command line arguments])
+AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
+ i=0
+ teststring="ABCD"
+
+ case $build_os in
+ msdosdjgpp*)
+ # On DJGPP, this test can blow up pretty badly due to problems in libc
+ # (any single argument exceeding 2000 bytes causes a buffer overrun
+ # during glob expansion). Even if it were fixed, the result of this
+ # check would be larger than it should be.
+ lt_cv_sys_max_cmd_len=12288; # 12K is about right
+ ;;
+
+ gnu*)
+ # Under GNU Hurd, this test is not required because there is
+ # no limit to the length of command line arguments.
+ # Libtool will interpret -1 as no limit whatsoever
+ lt_cv_sys_max_cmd_len=-1;
+ ;;
+
+ cygwin* | mingw*)
+ # On Win9x/ME, this test blows up -- it succeeds, but takes
+ # about 5 minutes as the teststring grows exponentially.
+ # Worse, since 9x/ME are not pre-emptively multitasking,
+ # you end up with a "frozen" computer, even though with patience
+ # the test eventually succeeds (with a max line length of 256k).
+ # Instead, let's just punt: use the minimum linelength reported by
+ # all of the supported platforms: 8192 (on NT/2K/XP).
+ lt_cv_sys_max_cmd_len=8192;
+ ;;
+
+ amigaos*)
+ # On AmigaOS with pdksh, this test takes hours, literally.
+ # So we just punt and use a minimum line length of 8192.
+ lt_cv_sys_max_cmd_len=8192;
+ ;;
+
+ netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
+ # This has been around since 386BSD, at least. Likely further.
+ if test -x /sbin/sysctl; then
+ lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
+ elif test -x /usr/sbin/sysctl; then
+ lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
+ else
+ lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs
+ fi
+ # And add a safety zone
+ lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+ lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+ ;;
+
+ interix*)
+ # We know the value 262144 and hardcode it with a safety zone (like BSD)
+ lt_cv_sys_max_cmd_len=196608
+ ;;
+
+ osf*)
+ # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
+ # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
+ # nice to cause kernel panics so lets avoid the loop below.
+ # First set a reasonable default.
+ lt_cv_sys_max_cmd_len=16384
+ #
+ if test -x /sbin/sysconfig; then
+ case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
+ *1*) lt_cv_sys_max_cmd_len=-1 ;;
+ esac
+ fi
+ ;;
+ sco3.2v5*)
+ lt_cv_sys_max_cmd_len=102400
+ ;;
+ sysv5* | sco5v6* | sysv4.2uw2*)
+ kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
+ if test -n "$kargmax"; then
+ lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[ ]]//'`
+ else
+ lt_cv_sys_max_cmd_len=32768
+ fi
+ ;;
+ *)
+ # If test is not a shell built-in, we'll probably end up computing a
+ # maximum length that is only half of the actual maximum length, but
+ # we can't tell.
+ SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
+ while (test "X"`$SHELL [$]0 --fallback-echo "X$teststring" 2>/dev/null` \
+ = "XX$teststring") >/dev/null 2>&1 &&
+ new_result=`expr "X$teststring" : ".*" 2>&1` &&
+ lt_cv_sys_max_cmd_len=$new_result &&
+ test $i != 17 # 1/2 MB should be enough
+ do
+ i=`expr $i + 1`
+ teststring=$teststring$teststring
+ done
+ teststring=
+ # Add a significant safety factor because C++ compilers can tack on massive
+ # amounts of additional arguments before passing them to the linker.
+ # It appears as though 1/2 is a usable value.
+ lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
+ ;;
+ esac
+])
+if test -n $lt_cv_sys_max_cmd_len ; then
+ AC_MSG_RESULT($lt_cv_sys_max_cmd_len)
+else
+ AC_MSG_RESULT(none)
+fi
+])# AC_LIBTOOL_SYS_MAX_CMD_LEN
+
+
+# _LT_AC_CHECK_DLFCN
+# ------------------
+AC_DEFUN([_LT_AC_CHECK_DLFCN],
+[AC_CHECK_HEADERS(dlfcn.h)dnl
+])# _LT_AC_CHECK_DLFCN
+
+
+# _LT_AC_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE,
+# ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING)
+# ---------------------------------------------------------------------
+AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF],
+[AC_REQUIRE([_LT_AC_CHECK_DLFCN])dnl
+if test "$cross_compiling" = yes; then :
+ [$4]
+else
+ lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+ lt_status=$lt_dlunknown
+ cat > conftest.$ac_ext <<EOF
+[#line __oline__ "configure"
+#include "confdefs.h"
+
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef RTLD_GLOBAL
+# define LT_DLGLOBAL RTLD_GLOBAL
+#else
+# ifdef DL_GLOBAL
+# define LT_DLGLOBAL DL_GLOBAL
+# else
+# define LT_DLGLOBAL 0
+# endif
+#endif
+
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+ find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+# ifdef RTLD_LAZY
+# define LT_DLLAZY_OR_NOW RTLD_LAZY
+# else
+# ifdef DL_LAZY
+# define LT_DLLAZY_OR_NOW DL_LAZY
+# else
+# ifdef RTLD_NOW
+# define LT_DLLAZY_OR_NOW RTLD_NOW
+# else
+# ifdef DL_NOW
+# define LT_DLLAZY_OR_NOW DL_NOW
+# else
+# define LT_DLLAZY_OR_NOW 0
+# endif
+# endif
+# endif
+# endif
+#endif
+
+#ifdef __cplusplus
+extern "C" void exit (int);
+#endif
+
+void fnord() { int i=42;}
+int main ()
+{
+ void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+ int status = $lt_dlunknown;
+
+ if (self)
+ {
+ if (dlsym (self,"fnord")) status = $lt_dlno_uscore;
+ else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
+ /* dlclose (self); */
+ }
+ else
+ puts (dlerror ());
+
+ exit (status);
+}]
+EOF
+ if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
+ (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
+ lt_status=$?
+ case x$lt_status in
+ x$lt_dlno_uscore) $1 ;;
+ x$lt_dlneed_uscore) $2 ;;
+ x$lt_dlunknown|x*) $3 ;;
+ esac
+ else :
+ # compilation failed
+ $3
+ fi
+fi
+rm -fr conftest*
+])# _LT_AC_TRY_DLOPEN_SELF
+
+
+# AC_LIBTOOL_DLOPEN_SELF
+# ----------------------
+AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF],
+[AC_REQUIRE([_LT_AC_CHECK_DLFCN])dnl
+if test "x$enable_dlopen" != xyes; then
+ enable_dlopen=unknown
+ enable_dlopen_self=unknown
+ enable_dlopen_self_static=unknown
+else
+ lt_cv_dlopen=no
+ lt_cv_dlopen_libs=
+
+ case $host_os in
+ beos*)
+ lt_cv_dlopen="load_add_on"
+ lt_cv_dlopen_libs=
+ lt_cv_dlopen_self=yes
+ ;;
+
+ mingw* | pw32*)
+ lt_cv_dlopen="LoadLibrary"
+ lt_cv_dlopen_libs=
+ ;;
+
+ cygwin*)
+ lt_cv_dlopen="dlopen"
+ lt_cv_dlopen_libs=
+ ;;
+
+ darwin*)
+ # if libdl is installed we need to link against it
+ AC_CHECK_LIB([dl], [dlopen],
+ [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[
+ lt_cv_dlopen="dyld"
+ lt_cv_dlopen_libs=
+ lt_cv_dlopen_self=yes
+ ])
+ ;;
+
+ *)
+ AC_CHECK_FUNC([shl_load],
+ [lt_cv_dlopen="shl_load"],
+ [AC_CHECK_LIB([dld], [shl_load],
+ [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-dld"],
+ [AC_CHECK_FUNC([dlopen],
+ [lt_cv_dlopen="dlopen"],
+ [AC_CHECK_LIB([dl], [dlopen],
+ [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],
+ [AC_CHECK_LIB([svld], [dlopen],
+ [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"],
+ [AC_CHECK_LIB([dld], [dld_link],
+ [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-dld"])
+ ])
+ ])
+ ])
+ ])
+ ])
+ ;;
+ esac
+
+ if test "x$lt_cv_dlopen" != xno; then
+ enable_dlopen=yes
+ else
+ enable_dlopen=no
+ fi
+
+ case $lt_cv_dlopen in
+ dlopen)
+ save_CPPFLAGS="$CPPFLAGS"
+ test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
+
+ save_LDFLAGS="$LDFLAGS"
+ wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
+
+ save_LIBS="$LIBS"
+ LIBS="$lt_cv_dlopen_libs $LIBS"
+
+ AC_CACHE_CHECK([whether a program can dlopen itself],
+ lt_cv_dlopen_self, [dnl
+ _LT_AC_TRY_DLOPEN_SELF(
+ lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes,
+ lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross)
+ ])
+
+ if test "x$lt_cv_dlopen_self" = xyes; then
+ wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
+ AC_CACHE_CHECK([whether a statically linked program can dlopen itself],
+ lt_cv_dlopen_self_static, [dnl
+ _LT_AC_TRY_DLOPEN_SELF(
+ lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes,
+ lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross)
+ ])
+ fi
+
+ CPPFLAGS="$save_CPPFLAGS"
+ LDFLAGS="$save_LDFLAGS"
+ LIBS="$save_LIBS"
+ ;;
+ esac
+
+ case $lt_cv_dlopen_self in
+ yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
+ *) enable_dlopen_self=unknown ;;
+ esac
+
+ case $lt_cv_dlopen_self_static in
+ yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
+ *) enable_dlopen_self_static=unknown ;;
+ esac
+fi
+])# AC_LIBTOOL_DLOPEN_SELF
+
+
+# AC_LIBTOOL_PROG_CC_C_O([TAGNAME])
+# ---------------------------------
+# Check to see if options -c and -o are simultaneously supported by compiler
+AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O],
+[AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl
+AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext],
+ [_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)],
+ [_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no
+ $rm -r conftest 2>/dev/null
+ mkdir conftest
+ cd conftest
+ mkdir out
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+ lt_compiler_flag="-o out/conftest2.$ac_objext"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+ (eval "$lt_compile" 2>out/conftest.err)
+ ac_status=$?
+ cat out/conftest.err >&AS_MESSAGE_LOG_FD
+ echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+ if (exit $ac_status) && test -s out/conftest2.$ac_objext
+ then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
+ $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+ if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+ _LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+ fi
+ fi
+ chmod u+w . 2>&AS_MESSAGE_LOG_FD
+ $rm conftest*
+ # SGI C++ compiler will create directory out/ii_files/ for
+ # template instantiation
+ test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files
+ $rm out/* && rmdir out
+ cd ..
+ rmdir conftest
+ $rm conftest*
+])
+])# AC_LIBTOOL_PROG_CC_C_O
+
+
+# AC_LIBTOOL_SYS_HARD_LINK_LOCKS([TAGNAME])
+# -----------------------------------------
+# Check to see if we can do hard links to lock some files if needed
+AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS],
+[AC_REQUIRE([_LT_AC_LOCK])dnl
+
+hard_links="nottested"
+if test "$_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then
+ # do not overwrite the value of need_locks provided by the user
+ AC_MSG_CHECKING([if we can lock with hard links])
+ hard_links=yes
+ $rm conftest*
+ ln conftest.a conftest.b 2>/dev/null && hard_links=no
+ touch conftest.a
+ ln conftest.a conftest.b 2>&5 || hard_links=no
+ ln conftest.a conftest.b 2>/dev/null && hard_links=no
+ AC_MSG_RESULT([$hard_links])
+ if test "$hard_links" = no; then
+ AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe])
+ need_locks=warn
+ fi
+else
+ need_locks=no
+fi
+])# AC_LIBTOOL_SYS_HARD_LINK_LOCKS
+
+
+# AC_LIBTOOL_OBJDIR
+# -----------------
+AC_DEFUN([AC_LIBTOOL_OBJDIR],
+[AC_CACHE_CHECK([for objdir], [lt_cv_objdir],
+[rm -f .libs 2>/dev/null
+mkdir .libs 2>/dev/null
+if test -d .libs; then
+ lt_cv_objdir=.libs
+else
+ # MS-DOS does not allow filenames that begin with a dot.
+ lt_cv_objdir=_libs
+fi
+rmdir .libs 2>/dev/null])
+objdir=$lt_cv_objdir
+])# AC_LIBTOOL_OBJDIR
+
+
+# AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH([TAGNAME])
+# ----------------------------------------------
+# Check hardcoding attributes.
+AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH],
+[AC_MSG_CHECKING([how to hardcode library paths into programs])
+_LT_AC_TAGVAR(hardcode_action, $1)=
+if test -n "$_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)" || \
+ test -n "$_LT_AC_TAGVAR(runpath_var, $1)" || \
+ test "X$_LT_AC_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then
+
+ # We can hardcode non-existant directories.
+ if test "$_LT_AC_TAGVAR(hardcode_direct, $1)" != no &&
+ # If the only mechanism to avoid hardcoding is shlibpath_var, we
+ # have to relink, otherwise we might link with an installed library
+ # when we should be linking with a yet-to-be-installed one
+ ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)" != no &&
+ test "$_LT_AC_TAGVAR(hardcode_minus_L, $1)" != no; then
+ # Linking always hardcodes the temporary library directory.
+ _LT_AC_TAGVAR(hardcode_action, $1)=relink
+ else
+ # We can link without hardcoding, and we can hardcode nonexisting dirs.
+ _LT_AC_TAGVAR(hardcode_action, $1)=immediate
+ fi
+else
+ # We cannot hardcode anything, or else we can only hardcode existing
+ # directories.
+ _LT_AC_TAGVAR(hardcode_action, $1)=unsupported
+fi
+AC_MSG_RESULT([$_LT_AC_TAGVAR(hardcode_action, $1)])
+
+if test "$_LT_AC_TAGVAR(hardcode_action, $1)" = relink; then
+ # Fast installation is not supported
+ enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+ test "$enable_shared" = no; then
+ # Fast installation is not necessary
+ enable_fast_install=needless
+fi
+])# AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH
+
+
+# AC_LIBTOOL_SYS_LIB_STRIP
+# ------------------------
+AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP],
+[striplib=
+old_striplib=
+AC_MSG_CHECKING([whether stripping libraries is possible])
+if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then
+ test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
+ test -z "$striplib" && striplib="$STRIP --strip-unneeded"
+ AC_MSG_RESULT([yes])
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+ case $host_os in
+ darwin*)
+ if test -n "$STRIP" ; then
+ striplib="$STRIP -x"
+ AC_MSG_RESULT([yes])
+ else
+ AC_MSG_RESULT([no])
+fi
+ ;;
+ *)
+ AC_MSG_RESULT([no])
+ ;;
+ esac
+fi
+])# AC_LIBTOOL_SYS_LIB_STRIP
+
+
+# AC_LIBTOOL_SYS_DYNAMIC_LINKER
+# -----------------------------
+# PORTME Fill in your ld.so characteristics
+AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER],
+[AC_MSG_CHECKING([dynamic linker characteristics])
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
+ # if the path contains ";" then we assume it to be the separator
+ # otherwise default to the standard path separator (i.e. ":") - it is
+ # assumed that no part of a normal pathname contains ";" but that should
+ # okay in the real world where ";" in dirpaths is itself problematic.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+else
+ sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+ shlibpath_var=LIBPATH
+
+ # AIX 3 has no versioning support, so we append a major version to the name.
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+
+aix4* | aix5*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ hardcode_into_libs=yes
+ if test "$host_cpu" = ia64; then
+ # AIX 5 supports IA64
+ library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ else
+ # With GCC up to 2.95.x, collect2 would create an import file
+ # for dependence libraries. The import file would start with
+ # the line `#! .'. This would cause the generated library to
+ # depend on `.', always an invalid library. This was fixed in
+ # development snapshots of GCC prior to 3.0.
+ case $host_os in
+ aix4 | aix4.[[01]] | aix4.[[01]].*)
+ if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+ echo ' yes '
+ echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
+ :
+ else
+ can_build_shared=no
+ fi
+ ;;
+ esac
+ # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+ # soname into executable. Probably we can add versioning support to
+ # collect2, so additional links can be useful in future.
+ if test "$aix_use_runtimelinking" = yes; then
+ # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+ # instead of lib<name>.a to let people know that these are not
+ # typical AIX shared libraries.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ else
+ # We preserve .a as extension for shared libraries through AIX4.2
+ # and later when we are not doing run time linking.
+ library_names_spec='${libname}${release}.a $libname.a'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ fi
+ shlibpath_var=LIBPATH
+ fi
+ ;;
+
+amigaos*)
+ library_names_spec='$libname.ixlibrary $libname.a'
+ # Create ${libname}_ixlibrary.a entries in /sys/libs.
+ finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+ ;;
+
+beos*)
+ library_names_spec='${libname}${shared_ext}'
+ dynamic_linker="$host_os ld.so"
+ shlibpath_var=LIBRARY_PATH
+ ;;
+
+bsdi[[45]]*)
+ version_type=linux
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+ sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+ # the default ld.so.conf also contains /usr/contrib/lib and
+ # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+ # libtool to hard-code these into programs
+ ;;
+
+cygwin* | mingw* | pw32*)
+ version_type=windows
+ shrext_cmds=".dll"
+ need_version=no
+ need_lib_prefix=no
+
+ case $GCC,$host_os in
+ yes,cygwin* | yes,mingw* | yes,pw32*)
+ library_names_spec='$libname.dll.a'
+ # DLL is installed to $(libdir)/../bin by postinstall_cmds
+ postinstall_cmds='base_file=`basename \${file}`~
+ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~
+ dldir=$destdir/`dirname \$dlpath`~
+ test -d \$dldir || mkdir -p \$dldir~
+ $install_prog $dir/$dlname \$dldir/$dlname~
+ chmod a+x \$dldir/$dlname'
+ postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+ dlpath=$dir/\$dldll~
+ $rm \$dlpath'
+ shlibpath_overrides_runpath=yes
+
+ case $host_os in
+ cygwin*)
+ # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+ soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib"
+ ;;
+ mingw*)
+ # MinGW DLLs use traditional 'lib' prefix
+ soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | [grep ';[c-zC-Z]:/' >/dev/null]; then
+ # It is most probably a Windows format PATH printed by
+ # mingw gcc, but we are running on Cygwin. Gcc prints its search
+ # path with ; separators, and with drive letters. We can handle the
+ # drive letters (cygwin fileutils understands them), so leave them,
+ # especially as we might pass files found there to a mingw objdump,
+ # which wouldn't understand a cygwinified path. Ahh.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+ ;;
+ pw32*)
+ # pw32 DLLs use 'pw' prefix rather than 'lib'
+ library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+ ;;
+ esac
+ ;;
+
+ *)
+ library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib'
+ ;;
+ esac
+ dynamic_linker='Win32 ld.exe'
+ # FIXME: first we should search . and the directory the executable is in
+ shlibpath_var=PATH
+ ;;
+
+darwin* | rhapsody*)
+ dynamic_linker="$host_os dyld"
+ version_type=darwin
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+ soname_spec='${libname}${release}${major}$shared_ext'
+ shlibpath_overrides_runpath=yes
+ shlibpath_var=DYLD_LIBRARY_PATH
+ shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+ # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
+ if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
+ else
+ sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib'
+ fi
+ sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+ ;;
+
+dgux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+freebsd1*)
+ dynamic_linker=no
+ ;;
+
+kfreebsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+freebsd* | dragonfly*)
+ # DragonFly does not have aout. When/if they implement a new
+ # versioning mechanism, adjust this.
+ if test -x /usr/bin/objformat; then
+ objformat=`/usr/bin/objformat`
+ else
+ case $host_os in
+ freebsd[[123]]*) objformat=aout ;;
+ *) objformat=elf ;;
+ esac
+ fi
+ version_type=freebsd-$objformat
+ case $version_type in
+ freebsd-elf*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ need_version=no
+ need_lib_prefix=no
+ ;;
+ freebsd-*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+ need_version=yes
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_os in
+ freebsd2*)
+ shlibpath_overrides_runpath=yes
+ ;;
+ freebsd3.[[01]]* | freebsdelf3.[[01]]*)
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \
+ freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1)
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+ freebsd*) # from 4.6 on
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ esac
+ ;;
+
+gnu*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ ;;
+
+hpux9* | hpux10* | hpux11*)
+ # Give a soname corresponding to the major version so that dld.sl refuses to
+ # link against other versions.
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ case $host_cpu in
+ ia64*)
+ shrext_cmds='.so'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.so"
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ if test "X$HPUX_IA64_MODE" = X32; then
+ sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+ else
+ sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+ fi
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ hppa*64*)
+ shrext_cmds='.sl'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ *)
+ shrext_cmds='.sl'
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=SHLIB_PATH
+ shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+ esac
+ # HP-UX runs *really* slowly unless shared libraries are mode 555.
+ postinstall_cmds='chmod 555 $lib'
+ ;;
+
+interix3*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+
+irix5* | irix6* | nonstopux*)
+ case $host_os in
+ nonstopux*) version_type=nonstopux ;;
+ *)
+ if test "$lt_cv_prog_gnu_ld" = yes; then
+ version_type=linux
+ else
+ version_type=irix
+ fi ;;
+ esac
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+ case $host_os in
+ irix5* | nonstopux*)
+ libsuff= shlibsuff=
+ ;;
+ *)
+ case $LD in # libtool.m4 will add one of these switches to LD
+ *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+ libsuff= shlibsuff= libmagic=32-bit;;
+ *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+ libsuff=32 shlibsuff=N32 libmagic=N32;;
+ *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+ libsuff=64 shlibsuff=64 libmagic=64-bit;;
+ *) libsuff= shlibsuff= libmagic=never-match;;
+ esac
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+ sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+ hardcode_into_libs=yes
+ ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+ dynamic_linker=no
+ ;;
+
+# This must be Linux ELF.
+linux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ # This implies no fast_install, which is unacceptable.
+ # Some rework will be needed to allow for fast_install
+ # before this can be enabled.
+ hardcode_into_libs=yes
+
+ # find out which ABI we are using
+ libsuff=
+ case "$host_cpu" in
+ x86_64*|s390x*|powerpc64*)
+ echo '[#]line __oline__ "configure"' > conftest.$ac_ext
+ if AC_TRY_EVAL(ac_compile); then
+ case `/usr/bin/file conftest.$ac_objext` in
+ *64-bit*)
+ libsuff=64
+ sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}"
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+ esac
+
+ # Append ld.so.conf contents to the search path
+ if test -f /etc/ld.so.conf; then
+ lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+ sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra"
+ fi
+
+ # We used to test for /lib/ld.so.1 and disable shared libraries on
+ # powerpc, because MkLinux only supported shared libraries with the
+ # GNU dynamic linker. Since this was broken with cross compilers,
+ # most powerpc-linux boxes support dynamic linking these days and
+ # people can always --disable-shared, the test was removed, and we
+ # assume the GNU/Linux dynamic linker is in use.
+ dynamic_linker='GNU/Linux ld.so'
+ ;;
+
+knetbsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+netbsd*)
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ dynamic_linker='NetBSD (a.out) ld.so'
+ else
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='NetBSD ld.elf_so'
+ fi
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+
+newsos6)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+nto-qnx*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+openbsd*)
+ version_type=sunos
+ sys_lib_dlsearch_path_spec="/usr/lib"
+ need_lib_prefix=no
+ # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+ case $host_os in
+ openbsd3.3 | openbsd3.3.*) need_version=yes ;;
+ *) need_version=no ;;
+ esac
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ case $host_os in
+ openbsd2.[[89]] | openbsd2.[[89]].*)
+ shlibpath_overrides_runpath=no
+ ;;
+ *)
+ shlibpath_overrides_runpath=yes
+ ;;
+ esac
+ else
+ shlibpath_overrides_runpath=yes
+ fi
+ ;;
+
+os2*)
+ libname_spec='$name'
+ shrext_cmds=".dll"
+ need_lib_prefix=no
+ library_names_spec='$libname${shared_ext} $libname.a'
+ dynamic_linker='OS/2 ld.exe'
+ shlibpath_var=LIBPATH
+ ;;
+
+osf3* | osf4* | osf5*)
+ version_type=osf
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+ sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+ ;;
+
+solaris*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ # ldd complains unless libraries are executable
+ postinstall_cmds='chmod +x $lib'
+ ;;
+
+sunos4*)
+ version_type=sunos
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ if test "$with_gnu_ld" = yes; then
+ need_lib_prefix=no
+ fi
+ need_version=yes
+ ;;
+
+sysv4 | sysv4.3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_vendor in
+ sni)
+ shlibpath_overrides_runpath=no
+ need_lib_prefix=no
+ export_dynamic_flag_spec='${wl}-Blargedynsym'
+ runpath_var=LD_RUN_PATH
+ ;;
+ siemens)
+ need_lib_prefix=no
+ ;;
+ motorola)
+ need_lib_prefix=no
+ need_version=no
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+ ;;
+ esac
+ ;;
+
+sysv4*MP*)
+ if test -d /usr/nec ;then
+ version_type=linux
+ library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+ soname_spec='$libname${shared_ext}.$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ fi
+ ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+ version_type=freebsd-elf
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ if test "$with_gnu_ld" = yes; then
+ sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+ shlibpath_overrides_runpath=no
+ else
+ sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+ shlibpath_overrides_runpath=yes
+ case $host_os in
+ sco3.2v5*)
+ sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+ ;;
+ esac
+ fi
+ sys_lib_dlsearch_path_spec='/usr/lib'
+ ;;
+
+uts4*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+*)
+ dynamic_linker=no
+ ;;
+esac
+AC_MSG_RESULT([$dynamic_linker])
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+ variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+])# AC_LIBTOOL_SYS_DYNAMIC_LINKER
+
+
+# _LT_AC_TAGCONFIG
+# ----------------
+AC_DEFUN([_LT_AC_TAGCONFIG],
+[AC_ARG_WITH([tags],
+ [AC_HELP_STRING([--with-tags@<:@=TAGS@:>@],
+ [include additional configurations @<:@automatic@:>@])],
+ [tagnames="$withval"])
+
+if test -f "$ltmain" && test -n "$tagnames"; then
+ if test ! -f "${ofile}"; then
+ AC_MSG_WARN([output file `$ofile' does not exist])
+ fi
+
+ if test -z "$LTCC"; then
+ eval "`$SHELL ${ofile} --config | grep '^LTCC='`"
+ if test -z "$LTCC"; then
+ AC_MSG_WARN([output file `$ofile' does not look like a libtool script])
+ else
+ AC_MSG_WARN([using `LTCC=$LTCC', extracted from `$ofile'])
+ fi
+ fi
+ if test -z "$LTCFLAGS"; then
+ eval "`$SHELL ${ofile} --config | grep '^LTCFLAGS='`"
+ fi
+
+ # Extract list of available tagged configurations in $ofile.
+ # Note that this assumes the entire list is on one line.
+ available_tags=`grep "^available_tags=" "${ofile}" | $SED -e 's/available_tags=\(.*$\)/\1/' -e 's/\"//g'`
+
+ lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+ for tagname in $tagnames; do
+ IFS="$lt_save_ifs"
+ # Check whether tagname contains only valid characters
+ case `$echo "X$tagname" | $Xsed -e 's:[[-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,/]]::g'` in
+ "") ;;
+ *) AC_MSG_ERROR([invalid tag name: $tagname])
+ ;;
+ esac
+
+ if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "${ofile}" > /dev/null
+ then
+ AC_MSG_ERROR([tag name \"$tagname\" already exists])
+ fi
+
+ # Update the list of available tags.
+ if test -n "$tagname"; then
+ echo appending configuration tag \"$tagname\" to $ofile
+
+ case $tagname in
+ CXX)
+ if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
+ ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
+ (test "X$CXX" != "Xg++"))) ; then
+ AC_LIBTOOL_LANG_CXX_CONFIG
+ else
+ tagname=""
+ fi
+ ;;
+
+ F77)
+ if test -n "$F77" && test "X$F77" != "Xno"; then
+ AC_LIBTOOL_LANG_F77_CONFIG
+ else
+ tagname=""
+ fi
+ ;;
+
+ GCJ)
+ if test -n "$GCJ" && test "X$GCJ" != "Xno"; then
+ AC_LIBTOOL_LANG_GCJ_CONFIG
+ else
+ tagname=""
+ fi
+ ;;
+
+ RC)
+ AC_LIBTOOL_LANG_RC_CONFIG
+ ;;
+
+ *)
+ AC_MSG_ERROR([Unsupported tag name: $tagname])
+ ;;
+ esac
+
+ # Append the new tag name to the list of available tags.
+ if test -n "$tagname" ; then
+ available_tags="$available_tags $tagname"
+ fi
+ fi
+ done
+ IFS="$lt_save_ifs"
+
+ # Now substitute the updated list of available tags.
+ if eval "sed -e 's/^available_tags=.*\$/available_tags=\"$available_tags\"/' \"$ofile\" > \"${ofile}T\""; then
+ mv "${ofile}T" "$ofile"
+ chmod +x "$ofile"
+ else
+ rm -f "${ofile}T"
+ AC_MSG_ERROR([unable to update list of available tagged configurations.])
+ fi
+fi
+])# _LT_AC_TAGCONFIG
+
+
+# AC_LIBTOOL_DLOPEN
+# -----------------
+# enable checks for dlopen support
+AC_DEFUN([AC_LIBTOOL_DLOPEN],
+ [AC_BEFORE([$0],[AC_LIBTOOL_SETUP])
+])# AC_LIBTOOL_DLOPEN
+
+
+# AC_LIBTOOL_WIN32_DLL
+# --------------------
+# declare package support for building win32 DLLs
+AC_DEFUN([AC_LIBTOOL_WIN32_DLL],
+[AC_BEFORE([$0], [AC_LIBTOOL_SETUP])
+])# AC_LIBTOOL_WIN32_DLL
+
+
+# AC_ENABLE_SHARED([DEFAULT])
+# ---------------------------
+# implement the --enable-shared flag
+# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'.
+AC_DEFUN([AC_ENABLE_SHARED],
+[define([AC_ENABLE_SHARED_DEFAULT], ifelse($1, no, no, yes))dnl
+AC_ARG_ENABLE([shared],
+ [AC_HELP_STRING([--enable-shared@<:@=PKGS@:>@],
+ [build shared libraries @<:@default=]AC_ENABLE_SHARED_DEFAULT[@:>@])],
+ [p=${PACKAGE-default}
+ case $enableval in
+ yes) enable_shared=yes ;;
+ no) enable_shared=no ;;
+ *)
+ enable_shared=no
+ # Look at the argument we got. We use all the common list separators.
+ lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+ for pkg in $enableval; do
+ IFS="$lt_save_ifs"
+ if test "X$pkg" = "X$p"; then
+ enable_shared=yes
+ fi
+ done
+ IFS="$lt_save_ifs"
+ ;;
+ esac],
+ [enable_shared=]AC_ENABLE_SHARED_DEFAULT)
+])# AC_ENABLE_SHARED
+
+
+# AC_DISABLE_SHARED
+# -----------------
+# set the default shared flag to --disable-shared
+AC_DEFUN([AC_DISABLE_SHARED],
+[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
+AC_ENABLE_SHARED(no)
+])# AC_DISABLE_SHARED
+
+
+# AC_ENABLE_STATIC([DEFAULT])
+# ---------------------------
+# implement the --enable-static flag
+# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'.
+AC_DEFUN([AC_ENABLE_STATIC],
+[define([AC_ENABLE_STATIC_DEFAULT], ifelse($1, no, no, yes))dnl
+AC_ARG_ENABLE([static],
+ [AC_HELP_STRING([--enable-static@<:@=PKGS@:>@],
+ [build static libraries @<:@default=]AC_ENABLE_STATIC_DEFAULT[@:>@])],
+ [p=${PACKAGE-default}
+ case $enableval in
+ yes) enable_static=yes ;;
+ no) enable_static=no ;;
+ *)
+ enable_static=no
+ # Look at the argument we got. We use all the common list separators.
+ lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+ for pkg in $enableval; do
+ IFS="$lt_save_ifs"
+ if test "X$pkg" = "X$p"; then
+ enable_static=yes
+ fi
+ done
+ IFS="$lt_save_ifs"
+ ;;
+ esac],
+ [enable_static=]AC_ENABLE_STATIC_DEFAULT)
+])# AC_ENABLE_STATIC
+
+
+# AC_DISABLE_STATIC
+# -----------------
+# set the default static flag to --disable-static
+AC_DEFUN([AC_DISABLE_STATIC],
+[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
+AC_ENABLE_STATIC(no)
+])# AC_DISABLE_STATIC
+
+
+# AC_ENABLE_FAST_INSTALL([DEFAULT])
+# ---------------------------------
+# implement the --enable-fast-install flag
+# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'.
+AC_DEFUN([AC_ENABLE_FAST_INSTALL],
+[define([AC_ENABLE_FAST_INSTALL_DEFAULT], ifelse($1, no, no, yes))dnl
+AC_ARG_ENABLE([fast-install],
+ [AC_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@],
+ [optimize for fast installation @<:@default=]AC_ENABLE_FAST_INSTALL_DEFAULT[@:>@])],
+ [p=${PACKAGE-default}
+ case $enableval in
+ yes) enable_fast_install=yes ;;
+ no) enable_fast_install=no ;;
+ *)
+ enable_fast_install=no
+ # Look at the argument we got. We use all the common list separators.
+ lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+ for pkg in $enableval; do
+ IFS="$lt_save_ifs"
+ if test "X$pkg" = "X$p"; then
+ enable_fast_install=yes
+ fi
+ done
+ IFS="$lt_save_ifs"
+ ;;
+ esac],
+ [enable_fast_install=]AC_ENABLE_FAST_INSTALL_DEFAULT)
+])# AC_ENABLE_FAST_INSTALL
+
+
+# AC_DISABLE_FAST_INSTALL
+# -----------------------
+# set the default to --disable-fast-install
+AC_DEFUN([AC_DISABLE_FAST_INSTALL],
+[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
+AC_ENABLE_FAST_INSTALL(no)
+])# AC_DISABLE_FAST_INSTALL
+
+
+# AC_LIBTOOL_PICMODE([MODE])
+# --------------------------
+# implement the --with-pic flag
+# MODE is either `yes' or `no'. If omitted, it defaults to `both'.
+AC_DEFUN([AC_LIBTOOL_PICMODE],
+[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
+pic_mode=ifelse($#,1,$1,default)
+])# AC_LIBTOOL_PICMODE
+
+
+# AC_PROG_EGREP
+# -------------
+# This is predefined starting with Autoconf 2.54, so this conditional
+# definition can be removed once we require Autoconf 2.54 or later.
+m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP],
+[AC_CACHE_CHECK([for egrep], [ac_cv_prog_egrep],
+ [if echo a | (grep -E '(a|b)') >/dev/null 2>&1
+ then ac_cv_prog_egrep='grep -E'
+ else ac_cv_prog_egrep='egrep'
+ fi])
+ EGREP=$ac_cv_prog_egrep
+ AC_SUBST([EGREP])
+])])
+
+
+# AC_PATH_TOOL_PREFIX
+# -------------------
+# find a file program which can recognise shared library
+AC_DEFUN([AC_PATH_TOOL_PREFIX],
+[AC_REQUIRE([AC_PROG_EGREP])dnl
+AC_MSG_CHECKING([for $1])
+AC_CACHE_VAL(lt_cv_path_MAGIC_CMD,
+[case $MAGIC_CMD in
+[[\\/*] | ?:[\\/]*])
+ lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+ ;;
+*)
+ lt_save_MAGIC_CMD="$MAGIC_CMD"
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+dnl $ac_dummy forces splitting on constant user-supplied paths.
+dnl POSIX.2 word splitting is done only on the output of word expansions,
+dnl not every word. This closes a longstanding sh security hole.
+ ac_dummy="ifelse([$2], , $PATH, [$2])"
+ for ac_dir in $ac_dummy; do
+ IFS="$lt_save_ifs"
+ test -z "$ac_dir" && ac_dir=.
+ if test -f $ac_dir/$1; then
+ lt_cv_path_MAGIC_CMD="$ac_dir/$1"
+ if test -n "$file_magic_test_file"; then
+ case $deplibs_check_method in
+ "file_magic "*)
+ file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+ MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+ if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
+ $EGREP "$file_magic_regex" > /dev/null; then
+ :
+ else
+ cat <<EOF 1>&2
+
+*** Warning: the command libtool uses to detect shared libraries,
+*** $file_magic_cmd, produces output that libtool cannot recognize.
+*** The result is that libtool may fail to recognize shared libraries
+*** as such. This will affect the creation of libtool libraries that
+*** depend on shared libraries, but programs linked with such libtool
+*** libraries will work regardless of this problem. Nevertheless, you
+*** may want to report the problem to your system manager and/or to
+*** bug-libtool at gnu.org
+
+EOF
+ fi ;;
+ esac
+ fi
+ break
+ fi
+ done
+ IFS="$lt_save_ifs"
+ MAGIC_CMD="$lt_save_MAGIC_CMD"
+ ;;
+esac])
+MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+if test -n "$MAGIC_CMD"; then
+ AC_MSG_RESULT($MAGIC_CMD)
+else
+ AC_MSG_RESULT(no)
+fi
+])# AC_PATH_TOOL_PREFIX
+
+
+# AC_PATH_MAGIC
+# -------------
+# find a file program which can recognise a shared library
+AC_DEFUN([AC_PATH_MAGIC],
+[AC_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH)
+if test -z "$lt_cv_path_MAGIC_CMD"; then
+ if test -n "$ac_tool_prefix"; then
+ AC_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH)
+ else
+ MAGIC_CMD=:
+ fi
+fi
+])# AC_PATH_MAGIC
+
+
+# AC_PROG_LD
+# ----------
+# find the pathname to the GNU or non-GNU linker
+AC_DEFUN([AC_PROG_LD],
+[AC_ARG_WITH([gnu-ld],
+ [AC_HELP_STRING([--with-gnu-ld],
+ [assume the C compiler uses GNU ld @<:@default=no@:>@])],
+ [test "$withval" = no || with_gnu_ld=yes],
+ [with_gnu_ld=no])
+AC_REQUIRE([LT_AC_PROG_SED])dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+ac_prog=ld
+if test "$GCC" = yes; then
+ # Check if gcc -print-prog-name=ld gives a path.
+ AC_MSG_CHECKING([for ld used by $CC])
+ case $host in
+ *-*-mingw*)
+ # gcc leaves a trailing carriage return which upsets mingw
+ ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+ *)
+ ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+ esac
+ case $ac_prog in
+ # Accept absolute paths.
+ [[\\/]]* | ?:[[\\/]]*)
+ re_direlt='/[[^/]][[^/]]*/\.\./'
+ # Canonicalize the pathname of ld
+ ac_prog=`echo $ac_prog| $SED 's%\\\\%/%g'`
+ while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do
+ ac_prog=`echo $ac_prog| $SED "s%$re_direlt%/%"`
+ done
+ test -z "$LD" && LD="$ac_prog"
+ ;;
+ "")
+ # If it fails, then pretend we aren't using GCC.
+ ac_prog=ld
+ ;;
+ *)
+ # If it is relative, then search for the first ld in PATH.
+ with_gnu_ld=unknown
+ ;;
+ esac
+elif test "$with_gnu_ld" = yes; then
+ AC_MSG_CHECKING([for GNU ld])
+else
+ AC_MSG_CHECKING([for non-GNU ld])
+fi
+AC_CACHE_VAL(lt_cv_path_LD,
+[if test -z "$LD"; then
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+ for ac_dir in $PATH; do
+ IFS="$lt_save_ifs"
+ test -z "$ac_dir" && ac_dir=.
+ if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+ lt_cv_path_LD="$ac_dir/$ac_prog"
+ # Check to see if the program is GNU ld. I'd rather use --version,
+ # but apparently some variants of GNU ld only accept -v.
+ # Break only if it was the GNU/non-GNU ld that we prefer.
+ case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
+ *GNU* | *'with BFD'*)
+ test "$with_gnu_ld" != no && break
+ ;;
+ *)
+ test "$with_gnu_ld" != yes && break
+ ;;
+ esac
+ fi
+ done
+ IFS="$lt_save_ifs"
+else
+ lt_cv_path_LD="$LD" # Let the user override the test with a path.
+fi])
+LD="$lt_cv_path_LD"
+if test -n "$LD"; then
+ AC_MSG_RESULT($LD)
+else
+ AC_MSG_RESULT(no)
+fi
+test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
+AC_PROG_LD_GNU
+])# AC_PROG_LD
+
+
+# AC_PROG_LD_GNU
+# --------------
+AC_DEFUN([AC_PROG_LD_GNU],
+[AC_REQUIRE([AC_PROG_EGREP])dnl
+AC_CACHE_CHECK([if the linker ($LD) is GNU ld], lt_cv_prog_gnu_ld,
+[# I'd rather use --version here, but apparently some GNU lds only accept -v.
+case `$LD -v 2>&1 </dev/null` in
+*GNU* | *'with BFD'*)
+ lt_cv_prog_gnu_ld=yes
+ ;;
+*)
+ lt_cv_prog_gnu_ld=no
+ ;;
+esac])
+with_gnu_ld=$lt_cv_prog_gnu_ld
+])# AC_PROG_LD_GNU
+
+
+# AC_PROG_LD_RELOAD_FLAG
+# ----------------------
+# find reload flag for linker
+# -- PORTME Some linkers may need a different reload flag.
+AC_DEFUN([AC_PROG_LD_RELOAD_FLAG],
+[AC_CACHE_CHECK([for $LD option to reload object files],
+ lt_cv_ld_reload_flag,
+ [lt_cv_ld_reload_flag='-r'])
+reload_flag=$lt_cv_ld_reload_flag
+case $reload_flag in
+"" | " "*) ;;
+*) reload_flag=" $reload_flag" ;;
+esac
+reload_cmds='$LD$reload_flag -o $output$reload_objs'
+case $host_os in
+ darwin*)
+ if test "$GCC" = yes; then
+ reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
+ else
+ reload_cmds='$LD$reload_flag -o $output$reload_objs'
+ fi
+ ;;
+esac
+])# AC_PROG_LD_RELOAD_FLAG
+
+
+# AC_DEPLIBS_CHECK_METHOD
+# -----------------------
+# how to check for library dependencies
+# -- PORTME fill in with the dynamic library characteristics
+AC_DEFUN([AC_DEPLIBS_CHECK_METHOD],
+[AC_CACHE_CHECK([how to recognise dependent libraries],
+lt_cv_deplibs_check_method,
+[lt_cv_file_magic_cmd='$MAGIC_CMD'
+lt_cv_file_magic_test_file=
+lt_cv_deplibs_check_method='unknown'
+# Need to set the preceding variable on all platforms that support
+# interlibrary dependencies.
+# 'none' -- dependencies not supported.
+# `unknown' -- same as none, but documents that we really don't know.
+# 'pass_all' -- all dependencies passed with no checks.
+# 'test_compile' -- check by making test program.
+# 'file_magic [[regex]]' -- check by looking for files in library path
+# which responds to the $file_magic_cmd with a given extended regex.
+# If you have `file' or equivalent on your system and you're not sure
+# whether `pass_all' will *always* work, you probably want this one.
+
+case $host_os in
+aix4* | aix5*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+beos*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+bsdi[[45]]*)
+ lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)'
+ lt_cv_file_magic_cmd='/usr/bin/file -L'
+ lt_cv_file_magic_test_file=/shlib/libc.so
+ ;;
+
+cygwin*)
+ # func_win32_libid is a shell function defined in ltmain.sh
+ lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+ lt_cv_file_magic_cmd='func_win32_libid'
+ ;;
+
+mingw* | pw32*)
+ # Base MSYS/MinGW do not provide the 'file' command needed by
+ # func_win32_libid shell function, so use a weaker test based on 'objdump'.
+ lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?'
+ lt_cv_file_magic_cmd='$OBJDUMP -f'
+ ;;
+
+darwin* | rhapsody*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+freebsd* | kfreebsd*-gnu | dragonfly*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then
+ case $host_cpu in
+ i*86 )
+ # Not sure whether the presence of OpenBSD here was a mistake.
+ # Let's accept both of them until this is cleared up.
+ lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library'
+ lt_cv_file_magic_cmd=/usr/bin/file
+ lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
+ ;;
+ esac
+ else
+ lt_cv_deplibs_check_method=pass_all
+ fi
+ ;;
+
+gnu*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+hpux10.20* | hpux11*)
+ lt_cv_file_magic_cmd=/usr/bin/file
+ case $host_cpu in
+ ia64*)
+ lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64'
+ lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
+ ;;
+ hppa*64*)
+ [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]']
+ lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
+ ;;
+ *)
+ lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]].[[0-9]]) shared library'
+ lt_cv_file_magic_test_file=/usr/lib/libc.sl
+ ;;
+ esac
+ ;;
+
+interix3*)
+ # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
+ lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$'
+ ;;
+
+irix5* | irix6* | nonstopux*)
+ case $LD in
+ *-32|*"-32 ") libmagic=32-bit;;
+ *-n32|*"-n32 ") libmagic=N32;;
+ *-64|*"-64 ") libmagic=64-bit;;
+ *) libmagic=never-match;;
+ esac
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+# This must be Linux ELF.
+linux*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then
+ lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+ else
+ lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$'
+ fi
+ ;;
+
+newos6*)
+ lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)'
+ lt_cv_file_magic_cmd=/usr/bin/file
+ lt_cv_file_magic_test_file=/usr/lib/libnls.so
+ ;;
+
+nto-qnx*)
+ lt_cv_deplibs_check_method=unknown
+ ;;
+
+openbsd*)
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$'
+ else
+ lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+ fi
+ ;;
+
+osf3* | osf4* | osf5*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+solaris*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+sysv4 | sysv4.3*)
+ case $host_vendor in
+ motorola)
+ lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]'
+ lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
+ ;;
+ ncr)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+ sequent)
+ lt_cv_file_magic_cmd='/bin/file'
+ lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )'
+ ;;
+ sni)
+ lt_cv_file_magic_cmd='/bin/file'
+ lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib"
+ lt_cv_file_magic_test_file=/lib/libc.so
+ ;;
+ siemens)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+ pc)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+ esac
+ ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+esac
+])
+file_magic_cmd=$lt_cv_file_magic_cmd
+deplibs_check_method=$lt_cv_deplibs_check_method
+test -z "$deplibs_check_method" && deplibs_check_method=unknown
+])# AC_DEPLIBS_CHECK_METHOD
+
+
+# AC_PROG_NM
+# ----------
+# find the pathname to a BSD-compatible name lister
+AC_DEFUN([AC_PROG_NM],
+[AC_CACHE_CHECK([for BSD-compatible nm], lt_cv_path_NM,
+[if test -n "$NM"; then
+ # Let the user override the test.
+ lt_cv_path_NM="$NM"
+else
+ lt_nm_to_check="${ac_tool_prefix}nm"
+ if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
+ lt_nm_to_check="$lt_nm_to_check nm"
+ fi
+ for lt_tmp_nm in $lt_nm_to_check; do
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+ for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
+ IFS="$lt_save_ifs"
+ test -z "$ac_dir" && ac_dir=.
+ tmp_nm="$ac_dir/$lt_tmp_nm"
+ if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+ # Check to see if the nm accepts a BSD-compat flag.
+ # Adding the `sed 1q' prevents false positives on HP-UX, which says:
+ # nm: unknown option "B" ignored
+ # Tru64's nm complains that /dev/null is an invalid object file
+ case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
+ */dev/null* | *'Invalid file or object type'*)
+ lt_cv_path_NM="$tmp_nm -B"
+ break
+ ;;
+ *)
+ case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
+ */dev/null*)
+ lt_cv_path_NM="$tmp_nm -p"
+ break
+ ;;
+ *)
+ lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
+ continue # so that we can try to find one that supports BSD flags
+ ;;
+ esac
+ ;;
+ esac
+ fi
+ done
+ IFS="$lt_save_ifs"
+ done
+ test -z "$lt_cv_path_NM" && lt_cv_path_NM=nm
+fi])
+NM="$lt_cv_path_NM"
+])# AC_PROG_NM
+
+
+# AC_CHECK_LIBM
+# -------------
+# check for math library
+AC_DEFUN([AC_CHECK_LIBM],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+LIBM=
+case $host in
+*-*-beos* | *-*-cygwin* | *-*-pw32* | *-*-darwin*)
+ # These system don't have libm, or don't need it
+ ;;
+*-ncr-sysv4.3*)
+ AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw")
+ AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm")
+ ;;
+*)
+ AC_CHECK_LIB(m, cos, LIBM="-lm")
+ ;;
+esac
+])# AC_CHECK_LIBM
+
+
+# AC_LIBLTDL_CONVENIENCE([DIRECTORY])
+# -----------------------------------
+# sets LIBLTDL to the link flags for the libltdl convenience library and
+# LTDLINCL to the include flags for the libltdl header and adds
+# --enable-ltdl-convenience to the configure arguments. Note that
+# AC_CONFIG_SUBDIRS is not called here. If DIRECTORY is not provided,
+# it is assumed to be `libltdl'. LIBLTDL will be prefixed with
+# '${top_builddir}/' and LTDLINCL will be prefixed with '${top_srcdir}/'
+# (note the single quotes!). If your package is not flat and you're not
+# using automake, define top_builddir and top_srcdir appropriately in
+# the Makefiles.
+AC_DEFUN([AC_LIBLTDL_CONVENIENCE],
+[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
+ case $enable_ltdl_convenience in
+ no) AC_MSG_ERROR([this package needs a convenience libltdl]) ;;
+ "") enable_ltdl_convenience=yes
+ ac_configure_args="$ac_configure_args --enable-ltdl-convenience" ;;
+ esac
+ LIBLTDL='${top_builddir}/'ifelse($#,1,[$1],['libltdl'])/libltdlc.la
+ LTDLINCL='-I${top_srcdir}/'ifelse($#,1,[$1],['libltdl'])
+ # For backwards non-gettext consistent compatibility...
+ INCLTDL="$LTDLINCL"
+])# AC_LIBLTDL_CONVENIENCE
+
+
+# AC_LIBLTDL_INSTALLABLE([DIRECTORY])
+# -----------------------------------
+# sets LIBLTDL to the link flags for the libltdl installable library and
+# LTDLINCL to the include flags for the libltdl header and adds
+# --enable-ltdl-install to the configure arguments. Note that
+# AC_CONFIG_SUBDIRS is not called here. If DIRECTORY is not provided,
+# and an installed libltdl is not found, it is assumed to be `libltdl'.
+# LIBLTDL will be prefixed with '${top_builddir}/'# and LTDLINCL with
+# '${top_srcdir}/' (note the single quotes!). If your package is not
+# flat and you're not using automake, define top_builddir and top_srcdir
+# appropriately in the Makefiles.
+# In the future, this macro may have to be called after AC_PROG_LIBTOOL.
+AC_DEFUN([AC_LIBLTDL_INSTALLABLE],
+[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
+ AC_CHECK_LIB(ltdl, lt_dlinit,
+ [test x"$enable_ltdl_install" != xyes && enable_ltdl_install=no],
+ [if test x"$enable_ltdl_install" = xno; then
+ AC_MSG_WARN([libltdl not installed, but installation disabled])
+ else
+ enable_ltdl_install=yes
+ fi
+ ])
+ if test x"$enable_ltdl_install" = x"yes"; then
+ ac_configure_args="$ac_configure_args --enable-ltdl-install"
+ LIBLTDL='${top_builddir}/'ifelse($#,1,[$1],['libltdl'])/libltdl.la
+ LTDLINCL='-I${top_srcdir}/'ifelse($#,1,[$1],['libltdl'])
+ else
+ ac_configure_args="$ac_configure_args --enable-ltdl-install=no"
+ LIBLTDL="-lltdl"
+ LTDLINCL=
+ fi
+ # For backwards non-gettext consistent compatibility...
+ INCLTDL="$LTDLINCL"
+])# AC_LIBLTDL_INSTALLABLE
+
+
+# AC_LIBTOOL_CXX
+# --------------
+# enable support for C++ libraries
+AC_DEFUN([AC_LIBTOOL_CXX],
+[AC_REQUIRE([_LT_AC_LANG_CXX])
+])# AC_LIBTOOL_CXX
+
+
+# _LT_AC_LANG_CXX
+# ---------------
+AC_DEFUN([_LT_AC_LANG_CXX],
+[AC_REQUIRE([AC_PROG_CXX])
+AC_REQUIRE([_LT_AC_PROG_CXXCPP])
+_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}CXX])
+])# _LT_AC_LANG_CXX
+
+# _LT_AC_PROG_CXXCPP
+# ------------------
+AC_DEFUN([_LT_AC_PROG_CXXCPP],
+[
+AC_REQUIRE([AC_PROG_CXX])
+if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
+ ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
+ (test "X$CXX" != "Xg++"))) ; then
+ AC_PROG_CXXCPP
+fi
+])# _LT_AC_PROG_CXXCPP
+
+# AC_LIBTOOL_F77
+# --------------
+# enable support for Fortran 77 libraries
+AC_DEFUN([AC_LIBTOOL_F77],
+[AC_REQUIRE([_LT_AC_LANG_F77])
+])# AC_LIBTOOL_F77
+
+
+# _LT_AC_LANG_F77
+# ---------------
+AC_DEFUN([_LT_AC_LANG_F77],
+[AC_REQUIRE([AC_PROG_F77])
+_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}F77])
+])# _LT_AC_LANG_F77
+
+
+# AC_LIBTOOL_GCJ
+# --------------
+# enable support for GCJ libraries
+AC_DEFUN([AC_LIBTOOL_GCJ],
+[AC_REQUIRE([_LT_AC_LANG_GCJ])
+])# AC_LIBTOOL_GCJ
+
+
+# _LT_AC_LANG_GCJ
+# ---------------
+AC_DEFUN([_LT_AC_LANG_GCJ],
+[AC_PROVIDE_IFELSE([AC_PROG_GCJ],[],
+ [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],[],
+ [AC_PROVIDE_IFELSE([LT_AC_PROG_GCJ],[],
+ [ifdef([AC_PROG_GCJ],[AC_REQUIRE([AC_PROG_GCJ])],
+ [ifdef([A][M_PROG_GCJ],[AC_REQUIRE([A][M_PROG_GCJ])],
+ [AC_REQUIRE([A][C_PROG_GCJ_OR_A][M_PROG_GCJ])])])])])])
+_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}GCJ])
+])# _LT_AC_LANG_GCJ
+
+
+# AC_LIBTOOL_RC
+# -------------
+# enable support for Windows resource files
+AC_DEFUN([AC_LIBTOOL_RC],
+[AC_REQUIRE([LT_AC_PROG_RC])
+_LT_AC_SHELL_INIT([tagnames=${tagnames+${tagnames},}RC])
+])# AC_LIBTOOL_RC
+
+
+# AC_LIBTOOL_LANG_C_CONFIG
+# ------------------------
+# Ensure that the configuration vars for the C compiler are
+# suitably defined. Those variables are subsequently used by
+# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
+AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG], [_LT_AC_LANG_C_CONFIG])
+AC_DEFUN([_LT_AC_LANG_C_CONFIG],
+[lt_save_CC="$CC"
+AC_LANG_PUSH(C)
+
+# Source file extension for C test sources.
+ac_ext=c
+
+# Object file extension for compiled C test sources.
+objext=o
+_LT_AC_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="int some_variable = 0;\n"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='int main(){return(0);}\n'
+
+_LT_AC_SYS_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+AC_LIBTOOL_PROG_COMPILER_NO_RTTI($1)
+AC_LIBTOOL_PROG_COMPILER_PIC($1)
+AC_LIBTOOL_PROG_CC_C_O($1)
+AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1)
+AC_LIBTOOL_PROG_LD_SHLIBS($1)
+AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
+AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
+AC_LIBTOOL_SYS_LIB_STRIP
+AC_LIBTOOL_DLOPEN_SELF
+
+# Report which library types will actually be built
+AC_MSG_CHECKING([if libtool supports shared libraries])
+AC_MSG_RESULT([$can_build_shared])
+
+AC_MSG_CHECKING([whether to build shared libraries])
+test "$can_build_shared" = "no" && enable_shared=no
+
+# On AIX, shared libraries and static libraries use the same namespace, and
+# are all built from PIC.
+case $host_os in
+aix3*)
+ test "$enable_shared" = yes && enable_static=no
+ if test -n "$RANLIB"; then
+ archive_cmds="$archive_cmds~\$RANLIB \$lib"
+ postinstall_cmds='$RANLIB $lib'
+ fi
+ ;;
+
+aix4* | aix5*)
+ if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+ test "$enable_shared" = yes && enable_static=no
+ fi
+ ;;
+esac
+AC_MSG_RESULT([$enable_shared])
+
+AC_MSG_CHECKING([whether to build static libraries])
+# Make sure either enable_shared or enable_static is yes.
+test "$enable_shared" = yes || enable_static=yes
+AC_MSG_RESULT([$enable_static])
+
+AC_LIBTOOL_CONFIG($1)
+
+AC_LANG_POP
+CC="$lt_save_CC"
+])# AC_LIBTOOL_LANG_C_CONFIG
+
+
+# AC_LIBTOOL_LANG_CXX_CONFIG
+# --------------------------
+# Ensure that the configuration vars for the C compiler are
+# suitably defined. Those variables are subsequently used by
+# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
+AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG], [_LT_AC_LANG_CXX_CONFIG(CXX)])
+AC_DEFUN([_LT_AC_LANG_CXX_CONFIG],
+[AC_LANG_PUSH(C++)
+AC_REQUIRE([AC_PROG_CXX])
+AC_REQUIRE([_LT_AC_PROG_CXXCPP])
+
+_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_AC_TAGVAR(allow_undefined_flag, $1)=
+_LT_AC_TAGVAR(always_export_symbols, $1)=no
+_LT_AC_TAGVAR(archive_expsym_cmds, $1)=
+_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_AC_TAGVAR(hardcode_direct, $1)=no
+_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_AC_TAGVAR(hardcode_minus_L, $1)=no
+_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+_LT_AC_TAGVAR(hardcode_automatic, $1)=no
+_LT_AC_TAGVAR(module_cmds, $1)=
+_LT_AC_TAGVAR(module_expsym_cmds, $1)=
+_LT_AC_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_AC_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_AC_TAGVAR(no_undefined_flag, $1)=
+_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Dependencies to place before and after the object being linked:
+_LT_AC_TAGVAR(predep_objects, $1)=
+_LT_AC_TAGVAR(postdep_objects, $1)=
+_LT_AC_TAGVAR(predeps, $1)=
+_LT_AC_TAGVAR(postdeps, $1)=
+_LT_AC_TAGVAR(compiler_lib_search_path, $1)=
+
+# Source file extension for C++ test sources.
+ac_ext=cpp
+
+# Object file extension for compiled C++ test sources.
+objext=o
+_LT_AC_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="int some_variable = 0;\n"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }\n'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_AC_SYS_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC=$CC
+lt_save_LD=$LD
+lt_save_GCC=$GCC
+GCC=$GXX
+lt_save_with_gnu_ld=$with_gnu_ld
+lt_save_path_LD=$lt_cv_path_LD
+if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
+ lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
+else
+ $as_unset lt_cv_prog_gnu_ld
+fi
+if test -n "${lt_cv_path_LDCXX+set}"; then
+ lt_cv_path_LD=$lt_cv_path_LDCXX
+else
+ $as_unset lt_cv_path_LD
+fi
+test -z "${LDCXX+set}" || LD=$LDCXX
+CC=${CXX-"c++"}
+compiler=$CC
+_LT_AC_TAGVAR(compiler, $1)=$CC
+_LT_CC_BASENAME([$compiler])
+
+# We don't want -fno-exception wen compiling C++ code, so set the
+# no_builtin_flag separately
+if test "$GXX" = yes; then
+ _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
+else
+ _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+fi
+
+if test "$GXX" = yes; then
+ # Set up default GNU C++ configuration
+
+ AC_PROG_LD
+
+ # Check if GNU C++ uses GNU ld as the underlying linker, since the
+ # archiving commands below assume that GNU ld is being used.
+ if test "$with_gnu_ld" = yes; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+ # If archive_cmds runs LD, not CC, wlarc should be empty
+ # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
+ # investigate it a little bit more. (MM)
+ wlarc='${wl}'
+
+ # ancient GNU ld didn't support --whole-archive et. al.
+ if eval "`$CC -print-prog-name=ld` --help 2>&1" | \
+ grep 'no-whole-archive' > /dev/null; then
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+ else
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+ fi
+ else
+ with_gnu_ld=no
+ wlarc=
+
+ # A generic and very simple default shared library creation
+ # command for GNU C++ for the case where it uses the native
+ # linker, instead of GNU ld. If possible, this setting should
+ # overridden to take advantage of the native linker features on
+ # the platform it is being used on.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+ fi
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"'
+
+else
+ GXX=no
+ with_gnu_ld=no
+ wlarc=
+fi
+
+# PORTME: fill in a description of your system's C++ link characteristics
+AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+_LT_AC_TAGVAR(ld_shlibs, $1)=yes
+case $host_os in
+ aix3*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ aix4* | aix5*)
+ if test "$host_cpu" = ia64; then
+ # On IA64, the linker does run time linking by default, so we don't
+ # have to do anything special.
+ aix_use_runtimelinking=no
+ exp_sym_flag='-Bexport'
+ no_entry_flag=""
+ else
+ aix_use_runtimelinking=no
+
+ # Test if we are trying to use run time linking or normal
+ # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+ # need to do runtime linking.
+ case $host_os in aix4.[[23]]|aix4.[[23]].*|aix5*)
+ for ld_flag in $LDFLAGS; do
+ case $ld_flag in
+ *-brtl*)
+ aix_use_runtimelinking=yes
+ break
+ ;;
+ esac
+ done
+ ;;
+ esac
+
+ exp_sym_flag='-bexport'
+ no_entry_flag='-bnoentry'
+ fi
+
+ # When large executables or shared objects are built, AIX ld can
+ # have problems creating the table of contents. If linking a library
+ # or program results in "error TOC overflow" add -mminimal-toc to
+ # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not
+ # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+ _LT_AC_TAGVAR(archive_cmds, $1)=''
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':'
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+
+ if test "$GXX" = yes; then
+ case $host_os in aix4.[[012]]|aix4.[[012]].*)
+ # We only want to do this on AIX 4.2 and lower, the check
+ # below for broken collect2 doesn't work under 4.3+
+ collect2name=`${CC} -print-prog-name=collect2`
+ if test -f "$collect2name" && \
+ strings "$collect2name" | grep resolve_lib_name >/dev/null
+ then
+ # We have reworked collect2
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ else
+ # We have old collect2
+ _LT_AC_TAGVAR(hardcode_direct, $1)=unsupported
+ # It fails to find uninstalled libraries when the uninstalled
+ # path is not listed in the libpath. Setting hardcode_minus_L
+ # to unsupported forces relinking
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=
+ fi
+ ;;
+ esac
+ shared_flag='-shared'
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag="$shared_flag "'${wl}-G'
+ fi
+ else
+ # not using gcc
+ if test "$host_cpu" = ia64; then
+ # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+ # chokes on -Wl,-G. The following line is correct:
+ shared_flag='-G'
+ else
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag='${wl}-G'
+ else
+ shared_flag='${wl}-bM:SRE'
+ fi
+ fi
+ fi
+
+ # It seems that -bexpall does not export symbols beginning with
+ # underscore (_), so it is better to generate a list of symbols to export.
+ _LT_AC_TAGVAR(always_export_symbols, $1)=yes
+ if test "$aix_use_runtimelinking" = yes; then
+ # Warning - without using the other runtime loading flags (-brtl),
+ # -berok will link without error, but may produce a broken library.
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='-berok'
+ # Determine the default libpath from the value encoded in an empty executable.
+ _LT_AC_SYS_LIBPATH_AIX
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+ else
+ if test "$host_cpu" = ia64; then
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+ else
+ # Determine the default libpath from the value encoded in an empty executable.
+ _LT_AC_SYS_LIBPATH_AIX
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+ # Warning - without using the other run time loading flags,
+ # -berok will link without error, but may produce a broken library.
+ _LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+ # Exported symbols can be pulled into shared objects from archives
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes
+ # This is similar to how AIX traditionally builds its shared libraries.
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+ fi
+ fi
+ ;;
+
+ beos*)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+ # support --undefined. This deserves some investigation. FIXME
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+
+ chorus*)
+ case $cc_basename in
+ *)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ ;;
+
+ cygwin* | mingw* | pw32*)
+ # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+ # as there is no search path for DLLs.
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ _LT_AC_TAGVAR(always_export_symbols, $1)=no
+ _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+
+ if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ # If the export-symbols file already is a .def file (1st line
+ # is EXPORTS), use it as is; otherwise, prepend...
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+ cp $export_symbols $output_objdir/$soname.def;
+ else
+ echo EXPORTS > $output_objdir/$soname.def;
+ cat $export_symbols >> $output_objdir/$soname.def;
+ fi~
+ $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ darwin* | rhapsody*)
+ case $host_os in
+ rhapsody* | darwin1.[[012]])
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}suppress'
+ ;;
+ *) # Darwin 1.3 on
+ if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ else
+ case ${MACOSX_DEPLOYMENT_TARGET} in
+ 10.[[012]])
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ ;;
+ 10.*)
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}dynamic_lookup'
+ ;;
+ esac
+ fi
+ ;;
+ esac
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_automatic, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=''
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+
+ if test "$GXX" = yes ; then
+ lt_int_apple_cc_single_mod=no
+ output_verbose_link_cmd='echo'
+ if $CC -dumpspecs 2>&1 | $EGREP 'single_module' >/dev/null ; then
+ lt_int_apple_cc_single_mod=yes
+ fi
+ if test "X$lt_int_apple_cc_single_mod" = Xyes ; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -r -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
+ fi
+ _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ if test "X$lt_int_apple_cc_single_mod" = Xyes ; then
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ else
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -r -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ fi
+ _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ else
+ case $cc_basename in
+ xlc*)
+ output_verbose_link_cmd='echo'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
+ _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ ;;
+ *)
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ fi
+ ;;
+
+ dgux*)
+ case $cc_basename in
+ ec++*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ ghcx*)
+ # Green Hills C++ Compiler
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ ;;
+ freebsd[[12]]*)
+ # C++ shared libraries reported to be fairly broken before switch to ELF
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ freebsd-elf*)
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ ;;
+ freebsd* | kfreebsd*-gnu | dragonfly*)
+ # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
+ # conventions
+ _LT_AC_TAGVAR(ld_shlibs, $1)=yes
+ ;;
+ gnu*)
+ ;;
+ hpux9*)
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+ # but as the default
+ # location of the library.
+
+ case $cc_basename in
+ CC*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ aCC*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "[[-]]L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ *)
+ if test "$GXX" = yes; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$CC -shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ else
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ esac
+ ;;
+ hpux10*|hpux11*)
+ if test $with_gnu_ld = no; then
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ case $host_cpu in
+ hppa*64*|ia64*)
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir'
+ ;;
+ *)
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ ;;
+ esac
+ fi
+ case $host_cpu in
+ hppa*64*|ia64*)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+ *)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+ # but as the default
+ # location of the library.
+ ;;
+ esac
+
+ case $cc_basename in
+ CC*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ aCC*)
+ case $host_cpu in
+ hppa*64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ ia64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ esac
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ *)
+ if test "$GXX" = yes; then
+ if test $with_gnu_ld = no; then
+ case $host_cpu in
+ hppa*64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ ia64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ esac
+ fi
+ else
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ esac
+ ;;
+ interix3*)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+ # Instead, shared libraries are loaded at an image base (0x10000000 by
+ # default) and relocated if they conflict, which is a slow very memory
+ # consuming and fragmenting process. To avoid this, we pick a random,
+ # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+ # time. Moving up from 0x10000000 also allows more sbrk(2) space.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ ;;
+ irix5* | irix6*)
+ case $cc_basename in
+ CC*)
+ # SGI C++
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+
+ # Archives containing C++ object files must be created using
+ # "CC -ar", where "CC" is the IRIX C++ compiler. This is
+ # necessary to make sure instantiated templates are included
+ # in the archive.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs'
+ ;;
+ *)
+ if test "$GXX" = yes; then
+ if test "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` -o $lib'
+ fi
+ fi
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+ ;;
+ esac
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ ;;
+ linux*)
+ case $cc_basename in
+ KCC*)
+ # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+ # KCC will only create a shared library if the output file
+ # ends with ".so" (or ".sl" for HP-UX), so rename the library
+ # to its proper name (with version) after linking.
+ _LT_AC_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | grep "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath,$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+ # Archives containing C++ object files must be created using
+ # "CC -Bstatic", where "CC" is the KAI C++ compiler.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
+ ;;
+ icpc*)
+ # Intel C++
+ with_gnu_ld=yes
+ # version 8.0 and above of icpc choke on multiply defined symbols
+ # if we add $predep_objects and $postdep_objects, however 7.1 and
+ # earlier do not add the objects themselves.
+ case `$CC -V 2>&1` in
+ *"Version 7."*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ ;;
+ *) # Version 8.0 or newer
+ tmp_idyn=
+ case $host_cpu in
+ ia64*) tmp_idyn=' -i_dynamic';;
+ esac
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ ;;
+ esac
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+ ;;
+ pgCC*)
+ # Portland Group C++ compiler
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+ ;;
+ cxx*)
+ # Compaq C++
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
+
+ runpath_var=LD_RUN_PATH
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ esac
+ ;;
+ lynxos*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ m88k*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ mvs*)
+ case $cc_basename in
+ cxx*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ ;;
+ netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags'
+ wlarc=
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ fi
+ # Workaround some broken pre-1.5 toolchains
+ output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
+ ;;
+ openbsd2*)
+ # C++ shared libraries are fairly broken
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ openbsd*)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+ fi
+ output_verbose_link_cmd='echo'
+ ;;
+ osf3*)
+ case $cc_basename in
+ KCC*)
+ # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+ # KCC will only create a shared library if the output file
+ # ends with ".so" (or ".sl" for HP-UX), so rename the library
+ # to its proper name (with version) after linking.
+ _LT_AC_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Archives containing C++ object files must be created using
+ # "CC -Bstatic", where "CC" is the KAI C++ compiler.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
+
+ ;;
+ RCC*)
+ # Rational C++ 2.4.1
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ cxx*)
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && echo ${wl}-set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ *)
+ if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"'
+
+ else
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ esac
+ ;;
+ osf4* | osf5*)
+ case $cc_basename in
+ KCC*)
+ # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+ # KCC will only create a shared library if the output file
+ # ends with ".so" (or ".sl" for HP-UX), so rename the library
+ # to its proper name (with version) after linking.
+ _LT_AC_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Archives containing C++ object files must be created using
+ # the KAI C++ compiler.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs'
+ ;;
+ RCC*)
+ # Rational C++ 2.4.1
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ cxx*)
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
+ echo "-hidden">> $lib.exp~
+ $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname -Wl,-input -Wl,$lib.exp `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~
+ $rm $lib.exp'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ *)
+ if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"'
+
+ else
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ esac
+ ;;
+ psos*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ sunos4*)
+ case $cc_basename in
+ CC*)
+ # Sun C++ 4.x
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ lcc*)
+ # Lucid
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ ;;
+ solaris*)
+ case $cc_basename in
+ CC*)
+ # Sun C++ 4.2, 5.x and Centerline C++
+ _LT_AC_TAGVAR(archive_cmds_need_lc,$1)=yes
+ _LT_AC_TAGVAR(no_undefined_flag, $1)=' -zdefs'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ case $host_os in
+ solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+ *)
+ # The C++ compiler is used as linker so we must use $wl
+ # flag to pass the commands to the underlying system
+ # linker. We must also pass each convience library through
+ # to the system linker between allextract/defaultextract.
+ # The C++ compiler will combine linker options so we
+ # cannot just pass the convience library names through
+ # without $wl.
+ # Supported since Solaris 2.6 (maybe 2.5.1?)
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract'
+ ;;
+ esac
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+
+ output_verbose_link_cmd='echo'
+
+ # Archives containing C++ object files must be created using
+ # "CC -xar", where "CC" is the Sun C++ compiler. This is
+ # necessary to make sure instantiated templates are included
+ # in the archive.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
+ ;;
+ gcx*)
+ # Green Hills C++ Compiler
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+
+ # The C++ compiler must be used to create the archive.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
+ ;;
+ *)
+ # GNU C++ compiler with Solaris linker
+ if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs'
+ if $CC --version | grep -v '^2\.7' > /dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd="$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\""
+ else
+ # g++ 2.7 appears to require `-G' NOT `-shared' on this
+ # platform.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd="$CC -G $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\""
+ fi
+
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir'
+ fi
+ ;;
+ esac
+ ;;
+ sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
+ _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ runpath_var='LD_RUN_PATH'
+
+ case $cc_basename in
+ CC*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ ;;
+ sysv5* | sco3.2v5* | sco5v6*)
+ # Note: We can NOT use -z defs as we might desire, because we do not
+ # link with -lc, and that would cause any symbols used from libc to
+ # always be unresolved, which means just about no library would
+ # ever link correctly. If we're not using GNU ld we use -z text
+ # though, which does catch some bad symbols but isn't as heavy-handed
+ # as -z defs.
+ # For security reasons, it is highly recommended that you always
+ # use absolute paths for naming shared libraries, and exclude the
+ # DT_RUNPATH tag from executables and libraries. But doing so
+ # requires that you compile everything twice, which is a pain.
+ # So that behaviour is only enabled if SCOABSPATH is set to a
+ # non-empty value in the environment. Most likely only useful for
+ # creating official distributions of packages.
+ # This is a hack until libtool officially supports absolute path
+ # names for shared libraries.
+ _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':'
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+ runpath_var='LD_RUN_PATH'
+
+ case $cc_basename in
+ CC*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ ;;
+ tandem*)
+ case $cc_basename in
+ NCC*)
+ # NonStop-UX NCC 3.20
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ ;;
+ vxworks*)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+esac
+AC_MSG_RESULT([$_LT_AC_TAGVAR(ld_shlibs, $1)])
+test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+_LT_AC_TAGVAR(GCC, $1)="$GXX"
+_LT_AC_TAGVAR(LD, $1)="$LD"
+
+AC_LIBTOOL_POSTDEP_PREDEP($1)
+AC_LIBTOOL_PROG_COMPILER_PIC($1)
+AC_LIBTOOL_PROG_CC_C_O($1)
+AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1)
+AC_LIBTOOL_PROG_LD_SHLIBS($1)
+AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
+AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
+
+AC_LIBTOOL_CONFIG($1)
+
+AC_LANG_POP
+CC=$lt_save_CC
+LDCXX=$LD
+LD=$lt_save_LD
+GCC=$lt_save_GCC
+with_gnu_ldcxx=$with_gnu_ld
+with_gnu_ld=$lt_save_with_gnu_ld
+lt_cv_path_LDCXX=$lt_cv_path_LD
+lt_cv_path_LD=$lt_save_path_LD
+lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
+lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
+])# AC_LIBTOOL_LANG_CXX_CONFIG
+
+# AC_LIBTOOL_POSTDEP_PREDEP([TAGNAME])
+# ------------------------------------
+# Figure out "hidden" library dependencies from verbose
+# compiler output when linking a shared library.
+# Parse the compiler output and extract the necessary
+# objects, libraries and library flags.
+AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP],[
+dnl we can't use the lt_simple_compile_test_code here,
+dnl because it contains code intended for an executable,
+dnl not a library. It's possible we should let each
+dnl tag define a new lt_????_link_test_code variable,
+dnl but it's only used here...
+ifelse([$1],[],[cat > conftest.$ac_ext <<EOF
+int a;
+void foo (void) { a = 0; }
+EOF
+],[$1],[CXX],[cat > conftest.$ac_ext <<EOF
+class Foo
+{
+public:
+ Foo (void) { a = 0; }
+private:
+ int a;
+};
+EOF
+],[$1],[F77],[cat > conftest.$ac_ext <<EOF
+ subroutine foo
+ implicit none
+ integer*4 a
+ a=0
+ return
+ end
+EOF
+],[$1],[GCJ],[cat > conftest.$ac_ext <<EOF
+public class foo {
+ private int a;
+ public void bar (void) {
+ a = 0;
+ }
+};
+EOF
+])
+dnl Parse the compiler output and extract the necessary
+dnl objects, libraries and library flags.
+if AC_TRY_EVAL(ac_compile); then
+ # Parse the compiler output and extract the necessary
+ # objects, libraries and library flags.
+
+ # Sentinel used to keep track of whether or not we are before
+ # the conftest object file.
+ pre_test_object_deps_done=no
+
+ # The `*' in the case matches for architectures that use `case' in
+ # $output_verbose_cmd can trigger glob expansion during the loop
+ # eval without this substitution.
+ output_verbose_link_cmd=`$echo "X$output_verbose_link_cmd" | $Xsed -e "$no_glob_subst"`
+
+ for p in `eval $output_verbose_link_cmd`; do
+ case $p in
+
+ -L* | -R* | -l*)
+ # Some compilers place space between "-{L,R}" and the path.
+ # Remove the space.
+ if test $p = "-L" \
+ || test $p = "-R"; then
+ prev=$p
+ continue
+ else
+ prev=
+ fi
+
+ if test "$pre_test_object_deps_done" = no; then
+ case $p in
+ -L* | -R*)
+ # Internal compiler library paths should come after those
+ # provided the user. The postdeps already come after the
+ # user supplied libs so there is no need to process them.
+ if test -z "$_LT_AC_TAGVAR(compiler_lib_search_path, $1)"; then
+ _LT_AC_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}"
+ else
+ _LT_AC_TAGVAR(compiler_lib_search_path, $1)="${_LT_AC_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}"
+ fi
+ ;;
+ # The "-l" case would never come before the object being
+ # linked, so don't bother handling this case.
+ esac
+ else
+ if test -z "$_LT_AC_TAGVAR(postdeps, $1)"; then
+ _LT_AC_TAGVAR(postdeps, $1)="${prev}${p}"
+ else
+ _LT_AC_TAGVAR(postdeps, $1)="${_LT_AC_TAGVAR(postdeps, $1)} ${prev}${p}"
+ fi
+ fi
+ ;;
+
+ *.$objext)
+ # This assumes that the test object file only shows up
+ # once in the compiler output.
+ if test "$p" = "conftest.$objext"; then
+ pre_test_object_deps_done=yes
+ continue
+ fi
+
+ if test "$pre_test_object_deps_done" = no; then
+ if test -z "$_LT_AC_TAGVAR(predep_objects, $1)"; then
+ _LT_AC_TAGVAR(predep_objects, $1)="$p"
+ else
+ _LT_AC_TAGVAR(predep_objects, $1)="$_LT_AC_TAGVAR(predep_objects, $1) $p"
+ fi
+ else
+ if test -z "$_LT_AC_TAGVAR(postdep_objects, $1)"; then
+ _LT_AC_TAGVAR(postdep_objects, $1)="$p"
+ else
+ _LT_AC_TAGVAR(postdep_objects, $1)="$_LT_AC_TAGVAR(postdep_objects, $1) $p"
+ fi
+ fi
+ ;;
+
+ *) ;; # Ignore the rest.
+
+ esac
+ done
+
+ # Clean up.
+ rm -f a.out a.exe
+else
+ echo "libtool.m4: error: problem compiling $1 test program"
+fi
+
+$rm -f confest.$objext
+
+# PORTME: override above test on systems where it is broken
+ifelse([$1],[CXX],
+[case $host_os in
+interix3*)
+ # Interix 3.5 installs completely hosed .la files for C++, so rather than
+ # hack all around it, let's just trust "g++" to DTRT.
+ _LT_AC_TAGVAR(predep_objects,$1)=
+ _LT_AC_TAGVAR(postdep_objects,$1)=
+ _LT_AC_TAGVAR(postdeps,$1)=
+ ;;
+
+solaris*)
+ case $cc_basename in
+ CC*)
+ # Adding this requires a known-good setup of shared libraries for
+ # Sun compiler versions before 5.6, else PIC objects from an old
+ # archive will be linked into the output, leading to subtle bugs.
+ _LT_AC_TAGVAR(postdeps,$1)='-lCstd -lCrun'
+ ;;
+ esac
+ ;;
+esac
+])
+
+case " $_LT_AC_TAGVAR(postdeps, $1) " in
+*" -lc "*) _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no ;;
+esac
+])# AC_LIBTOOL_POSTDEP_PREDEP
+
+# AC_LIBTOOL_LANG_F77_CONFIG
+# --------------------------
+# Ensure that the configuration vars for the C compiler are
+# suitably defined. Those variables are subsequently used by
+# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
+AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG], [_LT_AC_LANG_F77_CONFIG(F77)])
+AC_DEFUN([_LT_AC_LANG_F77_CONFIG],
+[AC_REQUIRE([AC_PROG_F77])
+AC_LANG_PUSH(Fortran 77)
+
+_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_AC_TAGVAR(allow_undefined_flag, $1)=
+_LT_AC_TAGVAR(always_export_symbols, $1)=no
+_LT_AC_TAGVAR(archive_expsym_cmds, $1)=
+_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_AC_TAGVAR(hardcode_direct, $1)=no
+_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_AC_TAGVAR(hardcode_minus_L, $1)=no
+_LT_AC_TAGVAR(hardcode_automatic, $1)=no
+_LT_AC_TAGVAR(module_cmds, $1)=
+_LT_AC_TAGVAR(module_expsym_cmds, $1)=
+_LT_AC_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_AC_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_AC_TAGVAR(no_undefined_flag, $1)=
+_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for f77 test sources.
+ac_ext=f
+
+# Object file extension for compiled f77 test sources.
+objext=o
+_LT_AC_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code=" subroutine t\n return\n end\n"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code=" program t\n end\n"
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_AC_SYS_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+CC=${F77-"f77"}
+compiler=$CC
+_LT_AC_TAGVAR(compiler, $1)=$CC
+_LT_CC_BASENAME([$compiler])
+
+AC_MSG_CHECKING([if libtool supports shared libraries])
+AC_MSG_RESULT([$can_build_shared])
+
+AC_MSG_CHECKING([whether to build shared libraries])
+test "$can_build_shared" = "no" && enable_shared=no
+
+# On AIX, shared libraries and static libraries use the same namespace, and
+# are all built from PIC.
+case $host_os in
+aix3*)
+ test "$enable_shared" = yes && enable_static=no
+ if test -n "$RANLIB"; then
+ archive_cmds="$archive_cmds~\$RANLIB \$lib"
+ postinstall_cmds='$RANLIB $lib'
+ fi
+ ;;
+aix4* | aix5*)
+ if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+ test "$enable_shared" = yes && enable_static=no
+ fi
+ ;;
+esac
+AC_MSG_RESULT([$enable_shared])
+
+AC_MSG_CHECKING([whether to build static libraries])
+# Make sure either enable_shared or enable_static is yes.
+test "$enable_shared" = yes || enable_static=yes
+AC_MSG_RESULT([$enable_static])
+
+_LT_AC_TAGVAR(GCC, $1)="$G77"
+_LT_AC_TAGVAR(LD, $1)="$LD"
+
+AC_LIBTOOL_PROG_COMPILER_PIC($1)
+AC_LIBTOOL_PROG_CC_C_O($1)
+AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1)
+AC_LIBTOOL_PROG_LD_SHLIBS($1)
+AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
+AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
+
+AC_LIBTOOL_CONFIG($1)
+
+AC_LANG_POP
+CC="$lt_save_CC"
+])# AC_LIBTOOL_LANG_F77_CONFIG
+
+
+# AC_LIBTOOL_LANG_GCJ_CONFIG
+# --------------------------
+# Ensure that the configuration vars for the C compiler are
+# suitably defined. Those variables are subsequently used by
+# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
+AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG], [_LT_AC_LANG_GCJ_CONFIG(GCJ)])
+AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG],
+[AC_LANG_SAVE
+
+# Source file extension for Java test sources.
+ac_ext=java
+
+# Object file extension for compiled Java test sources.
+objext=o
+_LT_AC_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="class foo {}\n"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }\n'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_AC_SYS_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+CC=${GCJ-"gcj"}
+compiler=$CC
+_LT_AC_TAGVAR(compiler, $1)=$CC
+_LT_CC_BASENAME([$compiler])
+
+# GCJ did not exist at the time GCC didn't implicitly link libc in.
+_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+
+_LT_AC_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+
+AC_LIBTOOL_PROG_COMPILER_NO_RTTI($1)
+AC_LIBTOOL_PROG_COMPILER_PIC($1)
+AC_LIBTOOL_PROG_CC_C_O($1)
+AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1)
+AC_LIBTOOL_PROG_LD_SHLIBS($1)
+AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
+AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
+
+AC_LIBTOOL_CONFIG($1)
+
+AC_LANG_RESTORE
+CC="$lt_save_CC"
+])# AC_LIBTOOL_LANG_GCJ_CONFIG
+
+
+# AC_LIBTOOL_LANG_RC_CONFIG
+# -------------------------
+# Ensure that the configuration vars for the Windows resource compiler are
+# suitably defined. Those variables are subsequently used by
+# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
+AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG], [_LT_AC_LANG_RC_CONFIG(RC)])
+AC_DEFUN([_LT_AC_LANG_RC_CONFIG],
+[AC_LANG_SAVE
+
+# Source file extension for RC test sources.
+ac_ext=rc
+
+# Object file extension for compiled RC test sources.
+objext=o
+_LT_AC_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }\n'
+
+# Code to be used in simple link tests
+lt_simple_link_test_code="$lt_simple_compile_test_code"
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_AC_SYS_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+CC=${RC-"windres"}
+compiler=$CC
+_LT_AC_TAGVAR(compiler, $1)=$CC
+_LT_CC_BASENAME([$compiler])
+_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+
+AC_LIBTOOL_CONFIG($1)
+
+AC_LANG_RESTORE
+CC="$lt_save_CC"
+])# AC_LIBTOOL_LANG_RC_CONFIG
+
+
+# AC_LIBTOOL_CONFIG([TAGNAME])
+# ----------------------------
+# If TAGNAME is not passed, then create an initial libtool script
+# with a default configuration from the untagged config vars. Otherwise
+# add code to config.status for appending the configuration named by
+# TAGNAME from the matching tagged config vars.
+AC_DEFUN([AC_LIBTOOL_CONFIG],
+[# The else clause should only fire when bootstrapping the
+# libtool distribution, otherwise you forgot to ship ltmain.sh
+# with your package, and you will get complaints that there are
+# no rules to generate ltmain.sh.
+if test -f "$ltmain"; then
+ # See if we are running on zsh, and set the options which allow our commands through
+ # without removal of \ escapes.
+ if test -n "${ZSH_VERSION+set}" ; then
+ setopt NO_GLOB_SUBST
+ fi
+ # Now quote all the things that may contain metacharacters while being
+ # careful not to overquote the AC_SUBSTed values. We take copies of the
+ # variables and quote the copies for generation of the libtool script.
+ for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \
+ SED SHELL STRIP \
+ libname_spec library_names_spec soname_spec extract_expsyms_cmds \
+ old_striplib striplib file_magic_cmd finish_cmds finish_eval \
+ deplibs_check_method reload_flag reload_cmds need_locks \
+ lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
+ lt_cv_sys_global_symbol_to_c_name_address \
+ sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
+ old_postinstall_cmds old_postuninstall_cmds \
+ _LT_AC_TAGVAR(compiler, $1) \
+ _LT_AC_TAGVAR(CC, $1) \
+ _LT_AC_TAGVAR(LD, $1) \
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1) \
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1) \
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1) \
+ _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) \
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1) \
+ _LT_AC_TAGVAR(thread_safe_flag_spec, $1) \
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1) \
+ _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1) \
+ _LT_AC_TAGVAR(old_archive_cmds, $1) \
+ _LT_AC_TAGVAR(old_archive_from_new_cmds, $1) \
+ _LT_AC_TAGVAR(predep_objects, $1) \
+ _LT_AC_TAGVAR(postdep_objects, $1) \
+ _LT_AC_TAGVAR(predeps, $1) \
+ _LT_AC_TAGVAR(postdeps, $1) \
+ _LT_AC_TAGVAR(compiler_lib_search_path, $1) \
+ _LT_AC_TAGVAR(archive_cmds, $1) \
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1) \
+ _LT_AC_TAGVAR(postinstall_cmds, $1) \
+ _LT_AC_TAGVAR(postuninstall_cmds, $1) \
+ _LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1) \
+ _LT_AC_TAGVAR(allow_undefined_flag, $1) \
+ _LT_AC_TAGVAR(no_undefined_flag, $1) \
+ _LT_AC_TAGVAR(export_symbols_cmds, $1) \
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) \
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1) \
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1) \
+ _LT_AC_TAGVAR(hardcode_automatic, $1) \
+ _LT_AC_TAGVAR(module_cmds, $1) \
+ _LT_AC_TAGVAR(module_expsym_cmds, $1) \
+ _LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1) \
+ _LT_AC_TAGVAR(exclude_expsyms, $1) \
+ _LT_AC_TAGVAR(include_expsyms, $1); do
+
+ case $var in
+ _LT_AC_TAGVAR(old_archive_cmds, $1) | \
+ _LT_AC_TAGVAR(old_archive_from_new_cmds, $1) | \
+ _LT_AC_TAGVAR(archive_cmds, $1) | \
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1) | \
+ _LT_AC_TAGVAR(module_cmds, $1) | \
+ _LT_AC_TAGVAR(module_expsym_cmds, $1) | \
+ _LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1) | \
+ _LT_AC_TAGVAR(export_symbols_cmds, $1) | \
+ extract_expsyms_cmds | reload_cmds | finish_cmds | \
+ postinstall_cmds | postuninstall_cmds | \
+ old_postinstall_cmds | old_postuninstall_cmds | \
+ sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
+ # Double-quote double-evaled strings.
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
+ ;;
+ *)
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\""
+ ;;
+ esac
+ done
+
+ case $lt_echo in
+ *'\[$]0 --fallback-echo"')
+ lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\[$]0 --fallback-echo"[$]/[$]0 --fallback-echo"/'`
+ ;;
+ esac
+
+ifelse([$1], [],
+ [cfgfile="${ofile}T"
+ trap "$rm \"$cfgfile\"; exit 1" 1 2 15
+ $rm -f "$cfgfile"
+ AC_MSG_NOTICE([creating $ofile])],
+ [cfgfile="$ofile"])
+
+ cat <<__EOF__ >> "$cfgfile"
+ifelse([$1], [],
+[#! $SHELL
+
+# `$echo "$cfgfile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
+# Generated automatically by $PROGRAM (GNU $PACKAGE $VERSION$TIMESTAMP)
+# NOTE: Changes made to this file will be lost: look at ltmain.sh.
+#
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001
+# Free Software Foundation, Inc.
+#
+# This file is part of GNU Libtool:
+# Originally by Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
+#
+# 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 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, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# A sed program that does not truncate output.
+SED=$lt_SED
+
+# Sed that helps us avoid accidentally triggering echo(1) options like -n.
+Xsed="$SED -e 1s/^X//"
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+# The names of the tagged configurations supported by this script.
+available_tags=
+
+# ### BEGIN LIBTOOL CONFIG],
+[# ### BEGIN LIBTOOL TAG CONFIG: $tagname])
+
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+
+# Shell to use when invoking shell scripts.
+SHELL=$lt_SHELL
+
+# Whether or not to build shared libraries.
+build_libtool_libs=$enable_shared
+
+# Whether or not to build static libraries.
+build_old_libs=$enable_static
+
+# Whether or not to add -lc for building shared libraries.
+build_libtool_need_lc=$_LT_AC_TAGVAR(archive_cmds_need_lc, $1)
+
+# Whether or not to disallow shared libs when runtime libs are static
+allow_libtool_libs_with_static_runtimes=$_LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)
+
+# Whether or not to optimize for fast installation.
+fast_install=$enable_fast_install
+
+# The host system.
+host_alias=$host_alias
+host=$host
+host_os=$host_os
+
+# The build system.
+build_alias=$build_alias
+build=$build
+build_os=$build_os
+
+# An echo program that does not interpret backslashes.
+echo=$lt_echo
+
+# The archiver.
+AR=$lt_AR
+AR_FLAGS=$lt_AR_FLAGS
+
+# A C compiler.
+LTCC=$lt_LTCC
+
+# LTCC compiler flags.
+LTCFLAGS=$lt_LTCFLAGS
+
+# A language-specific compiler.
+CC=$lt_[]_LT_AC_TAGVAR(compiler, $1)
+
+# Is the compiler the GNU C compiler?
+with_gcc=$_LT_AC_TAGVAR(GCC, $1)
+
+gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\`
+gcc_ver=\`gcc -dumpversion\`
+
+# An ERE matcher.
+EGREP=$lt_EGREP
+
+# The linker used to build libraries.
+LD=$lt_[]_LT_AC_TAGVAR(LD, $1)
+
+# Whether we need hard or soft links.
+LN_S=$lt_LN_S
+
+# A BSD-compatible nm program.
+NM=$lt_NM
+
+# A symbol stripping program
+STRIP=$lt_STRIP
+
+# Used to examine libraries when file_magic_cmd begins "file"
+MAGIC_CMD=$MAGIC_CMD
+
+# Used on cygwin: DLL creation program.
+DLLTOOL="$DLLTOOL"
+
+# Used on cygwin: object dumper.
+OBJDUMP="$OBJDUMP"
+
+# Used on cygwin: assembler.
+AS="$AS"
+
+# The name of the directory that contains temporary libtool files.
+objdir=$objdir
+
+# How to create reloadable object files.
+reload_flag=$lt_reload_flag
+reload_cmds=$lt_reload_cmds
+
+# How to pass a linker flag through the compiler.
+wl=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)
+
+# Object file suffix (normally "o").
+objext="$ac_objext"
+
+# Old archive suffix (normally "a").
+libext="$libext"
+
+# Shared library suffix (normally ".so").
+shrext_cmds='$shrext_cmds'
+
+# Executable file suffix (normally "").
+exeext="$exeext"
+
+# Additional compiler flags for building library objects.
+pic_flag=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)
+pic_mode=$pic_mode
+
+# What is the maximum length of a command?
+max_cmd_len=$lt_cv_sys_max_cmd_len
+
+# Does compiler simultaneously support -c and -o options?
+compiler_c_o=$lt_[]_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)
+
+# Must we lock files when doing compilation?
+need_locks=$lt_need_locks
+
+# Do we need the lib prefix for modules?
+need_lib_prefix=$need_lib_prefix
+
+# Do we need a version for libraries?
+need_version=$need_version
+
+# Whether dlopen is supported.
+dlopen_support=$enable_dlopen
+
+# Whether dlopen of programs is supported.
+dlopen_self=$enable_dlopen_self
+
+# Whether dlopen of statically linked programs is supported.
+dlopen_self_static=$enable_dlopen_self_static
+
+# Compiler flag to prevent dynamic linking.
+link_static_flag=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_static, $1)
+
+# Compiler flag to turn off builtin functions.
+no_builtin_flag=$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)
+
+# Compiler flag to allow reflexive dlopens.
+export_dynamic_flag_spec=$lt_[]_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)
+
+# Compiler flag to generate shared objects directly from archives.
+whole_archive_flag_spec=$lt_[]_LT_AC_TAGVAR(whole_archive_flag_spec, $1)
+
+# Compiler flag to generate thread-safe objects.
+thread_safe_flag_spec=$lt_[]_LT_AC_TAGVAR(thread_safe_flag_spec, $1)
+
+# Library versioning type.
+version_type=$version_type
+
+# Format of library name prefix.
+libname_spec=$lt_libname_spec
+
+# List of archive names. First name is the real one, the rest are links.
+# The last name is the one that the linker finds with -lNAME.
+library_names_spec=$lt_library_names_spec
+
+# The coded name of the library, if different from the real name.
+soname_spec=$lt_soname_spec
+
+# Commands used to build and install an old-style archive.
+RANLIB=$lt_RANLIB
+old_archive_cmds=$lt_[]_LT_AC_TAGVAR(old_archive_cmds, $1)
+old_postinstall_cmds=$lt_old_postinstall_cmds
+old_postuninstall_cmds=$lt_old_postuninstall_cmds
+
+# Create an old-style archive from a shared archive.
+old_archive_from_new_cmds=$lt_[]_LT_AC_TAGVAR(old_archive_from_new_cmds, $1)
+
+# Create a temporary old-style archive to link instead of a shared archive.
+old_archive_from_expsyms_cmds=$lt_[]_LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1)
+
+# Commands used to build and install a shared archive.
+archive_cmds=$lt_[]_LT_AC_TAGVAR(archive_cmds, $1)
+archive_expsym_cmds=$lt_[]_LT_AC_TAGVAR(archive_expsym_cmds, $1)
+postinstall_cmds=$lt_postinstall_cmds
+postuninstall_cmds=$lt_postuninstall_cmds
+
+# Commands used to build a loadable module (assumed same as above if empty)
+module_cmds=$lt_[]_LT_AC_TAGVAR(module_cmds, $1)
+module_expsym_cmds=$lt_[]_LT_AC_TAGVAR(module_expsym_cmds, $1)
+
+# Commands to strip libraries.
+old_striplib=$lt_old_striplib
+striplib=$lt_striplib
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predep_objects=\`echo $lt_[]_LT_AC_TAGVAR(predep_objects, $1) | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdep_objects=\`echo $lt_[]_LT_AC_TAGVAR(postdep_objects, $1) | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predeps=$lt_[]_LT_AC_TAGVAR(predeps, $1)
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdeps=$lt_[]_LT_AC_TAGVAR(postdeps, $1)
+
+# The library search path used internally by the compiler when linking
+# a shared library.
+compiler_lib_search_path=\`echo $lt_[]_LT_AC_TAGVAR(compiler_lib_search_path, $1) | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Method to check whether dependent libraries are shared objects.
+deplibs_check_method=$lt_deplibs_check_method
+
+# Command to use when deplibs_check_method == file_magic.
+file_magic_cmd=$lt_file_magic_cmd
+
+# Flag that allows shared libraries with undefined symbols to be built.
+allow_undefined_flag=$lt_[]_LT_AC_TAGVAR(allow_undefined_flag, $1)
+
+# Flag that forces no undefined symbols.
+no_undefined_flag=$lt_[]_LT_AC_TAGVAR(no_undefined_flag, $1)
+
+# Commands used to finish a libtool library installation in a directory.
+finish_cmds=$lt_finish_cmds
+
+# Same as above, but a single script fragment to be evaled but not shown.
+finish_eval=$lt_finish_eval
+
+# Take the output of nm and produce a listing of raw symbols and C names.
+global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
+
+# Transform the output of nm in a proper C declaration
+global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
+
+# Transform the output of nm in a C name address pair
+global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address
+
+# This is the shared library runtime path variable.
+runpath_var=$runpath_var
+
+# This is the shared library path variable.
+shlibpath_var=$shlibpath_var
+
+# Is shlibpath searched before the hard-coded library search path?
+shlibpath_overrides_runpath=$shlibpath_overrides_runpath
+
+# How to hardcode a shared library path into an executable.
+hardcode_action=$_LT_AC_TAGVAR(hardcode_action, $1)
+
+# Whether we should hardcode library paths into libraries.
+hardcode_into_libs=$hardcode_into_libs
+
+# Flag to hardcode \$libdir into a binary during linking.
+# This must work even if \$libdir does not exist.
+hardcode_libdir_flag_spec=$lt_[]_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)
+
+# If ld is used when linking, flag to hardcode \$libdir into
+# a binary during linking. This must work even if \$libdir does
+# not exist.
+hardcode_libdir_flag_spec_ld=$lt_[]_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)
+
+# Whether we need a single -rpath flag with a separated argument.
+hardcode_libdir_separator=$lt_[]_LT_AC_TAGVAR(hardcode_libdir_separator, $1)
+
+# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the
+# resulting binary.
+hardcode_direct=$_LT_AC_TAGVAR(hardcode_direct, $1)
+
+# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
+# resulting binary.
+hardcode_minus_L=$_LT_AC_TAGVAR(hardcode_minus_L, $1)
+
+# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into
+# the resulting binary.
+hardcode_shlibpath_var=$_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)
+
+# Set to yes if building a shared library automatically hardcodes DIR into the library
+# and all subsequent libraries and executables linked against it.
+hardcode_automatic=$_LT_AC_TAGVAR(hardcode_automatic, $1)
+
+# Variables whose values should be saved in libtool wrapper scripts and
+# restored at relink time.
+variables_saved_for_relink="$variables_saved_for_relink"
+
+# Whether libtool must link a program against all its dependency libraries.
+link_all_deplibs=$_LT_AC_TAGVAR(link_all_deplibs, $1)
+
+# Compile-time system search path for libraries
+sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Run-time system search path for libraries
+sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec
+
+# Fix the shell variable \$srcfile for the compiler.
+fix_srcfile_path="$_LT_AC_TAGVAR(fix_srcfile_path, $1)"
+
+# Set to yes if exported symbols are required.
+always_export_symbols=$_LT_AC_TAGVAR(always_export_symbols, $1)
+
+# The commands to list exported symbols.
+export_symbols_cmds=$lt_[]_LT_AC_TAGVAR(export_symbols_cmds, $1)
+
+# The commands to extract the exported symbol list from a shared archive.
+extract_expsyms_cmds=$lt_extract_expsyms_cmds
+
+# Symbols that should not be listed in the preloaded symbols.
+exclude_expsyms=$lt_[]_LT_AC_TAGVAR(exclude_expsyms, $1)
+
+# Symbols that must always be exported.
+include_expsyms=$lt_[]_LT_AC_TAGVAR(include_expsyms, $1)
+
+ifelse([$1],[],
+[# ### END LIBTOOL CONFIG],
+[# ### END LIBTOOL TAG CONFIG: $tagname])
+
+__EOF__
+
+ifelse([$1],[], [
+ case $host_os in
+ aix3*)
+ cat <<\EOF >> "$cfgfile"
+
+# AIX sometimes has problems with the GCC collect2 program. For some
+# reason, if we set the COLLECT_NAMES environment variable, the problems
+# vanish in a puff of smoke.
+if test "X${COLLECT_NAMES+set}" != Xset; then
+ COLLECT_NAMES=
+ export COLLECT_NAMES
+fi
+EOF
+ ;;
+ esac
+
+ # We use sed instead of cat because bash on DJGPP gets confused if
+ # if finds mixed CR/LF and LF-only lines. Since sed operates in
+ # text mode, it properly converts lines to CR/LF. This bash problem
+ # is reportedly fixed, but why not run on old versions too?
+ sed '$q' "$ltmain" >> "$cfgfile" || (rm -f "$cfgfile"; exit 1)
+
+ mv -f "$cfgfile" "$ofile" || \
+ (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
+ chmod +x "$ofile"
+])
+else
+ # If there is no Makefile yet, we rely on a make rule to execute
+ # `config.status --recheck' to rerun these tests and create the
+ # libtool script then.
+ ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'`
+ if test -f "$ltmain_in"; then
+ test -f Makefile && make "$ltmain"
+ fi
+fi
+])# AC_LIBTOOL_CONFIG
+
+
+# AC_LIBTOOL_PROG_COMPILER_NO_RTTI([TAGNAME])
+# -------------------------------------------
+AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI],
+[AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl
+
+_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+
+if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
+
+ AC_LIBTOOL_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions],
+ lt_cv_prog_compiler_rtti_exceptions,
+ [-fno-rtti -fno-exceptions], [],
+ [_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"])
+fi
+])# AC_LIBTOOL_PROG_COMPILER_NO_RTTI
+
+
+# AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE
+# ---------------------------------
+AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE],
+[AC_REQUIRE([AC_CANONICAL_HOST])
+AC_REQUIRE([AC_PROG_NM])
+AC_REQUIRE([AC_OBJEXT])
+# Check for command to grab the raw symbol name followed by C symbol from nm.
+AC_MSG_CHECKING([command to parse $NM output from $compiler object])
+AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe],
+[
+# These are sane defaults that work on at least a few old systems.
+# [They come from Ultrix. What could be older than Ultrix?!! ;)]
+
+# Character class describing NM global symbol codes.
+symcode='[[BCDEGRST]]'
+
+# Regexp to match symbols that can be accessed directly from C.
+sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)'
+
+# Transform an extracted symbol line into a proper C declaration
+lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^. .* \(.*\)$/extern int \1;/p'"
+
+# Transform an extracted symbol line into symbol name and symbol address
+lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'"
+
+# Define system-specific variables.
+case $host_os in
+aix*)
+ symcode='[[BCDT]]'
+ ;;
+cygwin* | mingw* | pw32*)
+ symcode='[[ABCDGISTW]]'
+ ;;
+hpux*) # Its linker distinguishes data from code symbols
+ if test "$host_cpu" = ia64; then
+ symcode='[[ABCDEGRST]]'
+ fi
+ lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+ lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'"
+ ;;
+linux*)
+ if test "$host_cpu" = ia64; then
+ symcode='[[ABCDGIRSTW]]'
+ lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+ lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'"
+ fi
+ ;;
+irix* | nonstopux*)
+ symcode='[[BCDEGRST]]'
+ ;;
+osf*)
+ symcode='[[BCDEGQRST]]'
+ ;;
+solaris*)
+ symcode='[[BDRT]]'
+ ;;
+sco3.2v5*)
+ symcode='[[DT]]'
+ ;;
+sysv4.2uw2*)
+ symcode='[[DT]]'
+ ;;
+sysv5* | sco5v6* | unixware* | OpenUNIX*)
+ symcode='[[ABDT]]'
+ ;;
+sysv4)
+ symcode='[[DFNSTU]]'
+ ;;
+esac
+
+# Handle CRLF in mingw tool chain
+opt_cr=
+case $build_os in
+mingw*)
+ opt_cr=`echo 'x\{0,1\}' | tr x '\015'` # option cr in regexp
+ ;;
+esac
+
+# If we're using GNU nm, then use its standard symbol codes.
+case `$NM -V 2>&1` in
+*GNU* | *'with BFD'*)
+ symcode='[[ABCDGIRSTW]]' ;;
+esac
+
+# Try without a prefix undercore, then with it.
+for ac_symprfx in "" "_"; do
+
+ # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
+ symxfrm="\\1 $ac_symprfx\\2 \\2"
+
+ # Write the raw and C identifiers.
+ lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[ ]]\($symcode$symcode*\)[[ ]][[ ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
+
+ # Check to see that the pipe works correctly.
+ pipe_works=no
+
+ rm -f conftest*
+ cat > conftest.$ac_ext <<EOF
+#ifdef __cplusplus
+extern "C" {
+#endif
+char nm_test_var;
+void nm_test_func(){}
+#ifdef __cplusplus
+}
+#endif
+int main(){nm_test_var='a';nm_test_func();return(0);}
+EOF
+
+ if AC_TRY_EVAL(ac_compile); then
+ # Now try to grab the symbols.
+ nlist=conftest.nm
+ if AC_TRY_EVAL(NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) && test -s "$nlist"; then
+ # Try sorting and uniquifying the output.
+ if sort "$nlist" | uniq > "$nlist"T; then
+ mv -f "$nlist"T "$nlist"
+ else
+ rm -f "$nlist"T
+ fi
+
+ # Make sure that we snagged all the symbols we need.
+ if grep ' nm_test_var$' "$nlist" >/dev/null; then
+ if grep ' nm_test_func$' "$nlist" >/dev/null; then
+ cat <<EOF > conftest.$ac_ext
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+EOF
+ # Now generate the symbol file.
+ eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | grep -v main >> conftest.$ac_ext'
+
+ cat <<EOF >> conftest.$ac_ext
+#if defined (__STDC__) && __STDC__
+# define lt_ptr_t void *
+#else
+# define lt_ptr_t char *
+# define const
+#endif
+
+/* The mapping between symbol names and symbols. */
+const struct {
+ const char *name;
+ lt_ptr_t address;
+}
+lt_preloaded_symbols[[]] =
+{
+EOF
+ $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (lt_ptr_t) \&\2},/" < "$nlist" | grep -v main >> conftest.$ac_ext
+ cat <<\EOF >> conftest.$ac_ext
+ {0, (lt_ptr_t) 0}
+};
+
+#ifdef __cplusplus
+}
+#endif
+EOF
+ # Now try linking the two files.
+ mv conftest.$ac_objext conftstm.$ac_objext
+ lt_save_LIBS="$LIBS"
+ lt_save_CFLAGS="$CFLAGS"
+ LIBS="conftstm.$ac_objext"
+ CFLAGS="$CFLAGS$_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
+ if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then
+ pipe_works=yes
+ fi
+ LIBS="$lt_save_LIBS"
+ CFLAGS="$lt_save_CFLAGS"
+ else
+ echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD
+ fi
+ else
+ echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD
+ fi
+ else
+ echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
+ fi
+ else
+ echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD
+ cat conftest.$ac_ext >&5
+ fi
+ rm -f conftest* conftst*
+
+ # Do not use the global_symbol_pipe unless it works.
+ if test "$pipe_works" = yes; then
+ break
+ else
+ lt_cv_sys_global_symbol_pipe=
+ fi
+done
+])
+if test -z "$lt_cv_sys_global_symbol_pipe"; then
+ lt_cv_sys_global_symbol_to_cdecl=
+fi
+if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
+ AC_MSG_RESULT(failed)
+else
+ AC_MSG_RESULT(ok)
+fi
+]) # AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE
+
+
+# AC_LIBTOOL_PROG_COMPILER_PIC([TAGNAME])
+# ---------------------------------------
+AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC],
+[_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=
+_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
+_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=
+
+AC_MSG_CHECKING([for $compiler option to produce PIC])
+ ifelse([$1],[CXX],[
+ # C++ specific cases for pic, static, wl, etc.
+ if test "$GXX" = yes; then
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+ case $host_os in
+ aix*)
+ # All AIX code is PIC.
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ fi
+ ;;
+ amigaos*)
+ # FIXME: we need at least 68020 code to build shared libraries, but
+ # adding the `-m68020' flag to GCC prevents building anything better,
+ # like `-m68040'.
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+ ;;
+ beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+ # PIC is the default for these OSes.
+ ;;
+ mingw* | os2* | pw32*)
+ # This hack is so that the source file can tell whether it is being
+ # built for inclusion in a dll (and should export symbols for example).
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'
+ ;;
+ darwin* | rhapsody*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+ ;;
+ *djgpp*)
+ # DJGPP does not support shared libraries at all
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
+ ;;
+ interix3*)
+ # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+ # Instead, we relocate shared libraries at runtime.
+ ;;
+ sysv4*MP*)
+ if test -d /usr/nec; then
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+ fi
+ ;;
+ hpux*)
+ # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+ # not for PA HP-UX.
+ case $host_cpu in
+ hppa*64*|ia64*)
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+ ;;
+ esac
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+ ;;
+ esac
+ else
+ case $host_os in
+ aix4* | aix5*)
+ # All AIX code is PIC.
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ else
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+ fi
+ ;;
+ chorus*)
+ case $cc_basename in
+ cxch68*)
+ # Green Hills C++ Compiler
+ # _LT_AC_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
+ ;;
+ esac
+ ;;
+ darwin*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ case $cc_basename in
+ xlc*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-qnocommon'
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ ;;
+ esac
+ ;;
+ dgux*)
+ case $cc_basename in
+ ec++*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ ;;
+ ghcx*)
+ # Green Hills C++ Compiler
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ freebsd* | kfreebsd*-gnu | dragonfly*)
+ # FreeBSD uses GNU C++
+ ;;
+ hpux9* | hpux10* | hpux11*)
+ case $cc_basename in
+ CC*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+ if test "$host_cpu" != ia64; then
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+ fi
+ ;;
+ aCC*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+ case $host_cpu in
+ hppa*64*|ia64*)
+ # +Z the default
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+ ;;
+ esac
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ interix*)
+ # This is c89, which is MS Visual C++ (no shared libs)
+ # Anyone wants to do a port?
+ ;;
+ irix5* | irix6* | nonstopux*)
+ case $cc_basename in
+ CC*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+ # CC pic flag -KPIC is the default.
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ linux*)
+ case $cc_basename in
+ KCC*)
+ # KAI C++ Compiler
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+ ;;
+ icpc* | ecpc*)
+ # Intel C++
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static'
+ ;;
+ pgCC*)
+ # Portland Group C++ compiler.
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+ cxx*)
+ # Compaq C++
+ # Make sure the PIC flag is empty. It appears that all Alpha
+ # Linux and Compaq Tru64 Unix objects are PIC.
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ lynxos*)
+ ;;
+ m88k*)
+ ;;
+ mvs*)
+ case $cc_basename in
+ cxx*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ netbsd*)
+ ;;
+ osf3* | osf4* | osf5*)
+ case $cc_basename in
+ KCC*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+ ;;
+ RCC*)
+ # Rational C++ 2.4.1
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+ ;;
+ cxx*)
+ # Digital/Compaq C++
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ # Make sure the PIC flag is empty. It appears that all Alpha
+ # Linux and Compaq Tru64 Unix objects are PIC.
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ psos*)
+ ;;
+ solaris*)
+ case $cc_basename in
+ CC*)
+ # Sun C++ 4.2, 5.x and Centerline C++
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+ ;;
+ gcx*)
+ # Green Hills C++ Compiler
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ sunos4*)
+ case $cc_basename in
+ CC*)
+ # Sun C++ 4.x
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+ lcc*)
+ # Lucid
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ tandem*)
+ case $cc_basename in
+ NCC*)
+ # NonStop-UX NCC 3.20
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+ case $cc_basename in
+ CC*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+ esac
+ ;;
+ vxworks*)
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+ ;;
+ esac
+ fi
+],
+[
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+ case $host_os in
+ aix*)
+ # All AIX code is PIC.
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ fi
+ ;;
+
+ amigaos*)
+ # FIXME: we need at least 68020 code to build shared libraries, but
+ # adding the `-m68020' flag to GCC prevents building anything better,
+ # like `-m68040'.
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+ ;;
+
+ beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+ # PIC is the default for these OSes.
+ ;;
+
+ mingw* | pw32* | os2*)
+ # This hack is so that the source file can tell whether it is being
+ # built for inclusion in a dll (and should export symbols for example).
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'
+ ;;
+
+ darwin* | rhapsody*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+ ;;
+
+ interix3*)
+ # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+ # Instead, we relocate shared libraries at runtime.
+ ;;
+
+ msdosdjgpp*)
+ # Just because we use GCC doesn't mean we suddenly get shared libraries
+ # on systems that don't support them.
+ _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+ enable_shared=no
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec; then
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+ fi
+ ;;
+
+ hpux*)
+ # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+ # not for PA HP-UX.
+ case $host_cpu in
+ hppa*64*|ia64*)
+ # +Z the default
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+ ;;
+ esac
+ ;;
+
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+ ;;
+ esac
+ else
+ # PORTME Check for flag to pass linker flags through the system compiler.
+ case $host_os in
+ aix*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ else
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+ fi
+ ;;
+ darwin*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ case $cc_basename in
+ xlc*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-qnocommon'
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ ;;
+ esac
+ ;;
+
+ mingw* | pw32* | os2*)
+ # This hack is so that the source file can tell whether it is being
+ # built for inclusion in a dll (and should export symbols for example).
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'
+ ;;
+
+ hpux9* | hpux10* | hpux11*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+ # not for PA HP-UX.
+ case $host_cpu in
+ hppa*64*|ia64*)
+ # +Z the default
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+ ;;
+ esac
+ # Is there a better lt_prog_compiler_static that works with the bundled CC?
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+ ;;
+
+ irix5* | irix6* | nonstopux*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ # PIC (with -KPIC) is the default.
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+ ;;
+
+ newsos6)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+
+ linux*)
+ case $cc_basename in
+ icc* | ecc*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-static'
+ ;;
+ pgcc* | pgf77* | pgf90* | pgf95*)
+ # Portland Group compilers (*not* the Pentium gcc compiler,
+ # which looks to be a dead project)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+ ccc*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ # All Alpha code is PIC.
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+ ;;
+ esac
+ ;;
+
+ osf3* | osf4* | osf5*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ # All OSF/1 code is PIC.
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+ ;;
+
+ solaris*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ case $cc_basename in
+ f77* | f90* | f95*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';;
+ esac
+ ;;
+
+ sunos4*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+
+ sysv4 | sysv4.2uw2* | sysv4.3*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec ;then
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ fi
+ ;;
+
+ sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+
+ unicos*)
+ _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+ _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+ ;;
+
+ uts4*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+ _LT_AC_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+ ;;
+
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+ ;;
+ esac
+ fi
+])
+AC_MSG_RESULT([$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)])
+
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)"; then
+ AC_LIBTOOL_COMPILER_OPTION([if $compiler PIC flag $_LT_AC_TAGVAR(lt_prog_compiler_pic, $1) works],
+ _LT_AC_TAGVAR(lt_prog_compiler_pic_works, $1),
+ [$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)ifelse([$1],[],[ -DPIC],[ifelse([$1],[CXX],[ -DPIC],[])])], [],
+ [case $_LT_AC_TAGVAR(lt_prog_compiler_pic, $1) in
+ "" | " "*) ;;
+ *) _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)" ;;
+ esac],
+ [_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
+ _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no])
+fi
+case $host_os in
+ # For platforms which do not support PIC, -DPIC is meaningless:
+ *djgpp*)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=
+ ;;
+ *)
+ _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)ifelse([$1],[],[ -DPIC],[ifelse([$1],[CXX],[ -DPIC],[])])"
+ ;;
+esac
+
+#
+# Check to make sure the static flag actually works.
+#
+wl=$_LT_AC_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_AC_TAGVAR(lt_prog_compiler_static, $1)\"
+AC_LIBTOOL_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works],
+ _LT_AC_TAGVAR(lt_prog_compiler_static_works, $1),
+ $lt_tmp_static_flag,
+ [],
+ [_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=])
+])
+
+
+# AC_LIBTOOL_PROG_LD_SHLIBS([TAGNAME])
+# ------------------------------------
+# See if the linker supports building shared libraries.
+AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS],
+[AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+ifelse([$1],[CXX],[
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+ case $host_os in
+ aix4* | aix5*)
+ # If we're using GNU nm, then we don't want the "-C" option.
+ # -C means demangle to AIX nm, but means don't demangle with GNU nm
+ if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols'
+ else
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols'
+ fi
+ ;;
+ pw32*)
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds"
+ ;;
+ cygwin* | mingw*)
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]] /s/.* \([[^ ]]*\)/\1 DATA/;/^.* __nm__/s/^.* __nm__\([[^ ]]*\) [[^ ]]*/\1 DATA/;/^I /d;/^[[AITW]] /s/.* //'\'' | sort | uniq > $export_symbols'
+ ;;
+ *)
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+ ;;
+ esac
+],[
+ runpath_var=
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=
+ _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+ _LT_AC_TAGVAR(archive_cmds, $1)=
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)=
+ _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)=
+ _LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1)=
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+ _LT_AC_TAGVAR(thread_safe_flag_spec, $1)=
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=unknown
+ _LT_AC_TAGVAR(hardcode_automatic, $1)=no
+ _LT_AC_TAGVAR(module_cmds, $1)=
+ _LT_AC_TAGVAR(module_expsym_cmds, $1)=
+ _LT_AC_TAGVAR(always_export_symbols, $1)=no
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+ # include_expsyms should be a list of space-separated symbols to be *always*
+ # included in the symbol list
+ _LT_AC_TAGVAR(include_expsyms, $1)=
+ # exclude_expsyms can be an extended regexp of symbols to exclude
+ # it will be wrapped by ` (' and `)$', so one must not match beginning or
+ # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
+ # as well as any symbol that contains `d'.
+ _LT_AC_TAGVAR(exclude_expsyms, $1)="_GLOBAL_OFFSET_TABLE_"
+ # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
+ # platforms (ab)use it in PIC code, but their linkers get confused if
+ # the symbol is explicitly referenced. Since portable code cannot
+ # rely on this symbol name, it's probably fine to never include it in
+ # preloaded symbol tables.
+ extract_expsyms_cmds=
+ # Just being paranoid about ensuring that cc_basename is set.
+ _LT_CC_BASENAME([$compiler])
+ case $host_os in
+ cygwin* | mingw* | pw32*)
+ # FIXME: the MSVC++ port hasn't been tested in a loooong time
+ # When not using gcc, we currently assume that we are using
+ # Microsoft Visual C++.
+ if test "$GCC" != yes; then
+ with_gnu_ld=no
+ fi
+ ;;
+ interix*)
+ # we just hope/assume this is gcc and not c89 (= MSVC++)
+ with_gnu_ld=yes
+ ;;
+ openbsd*)
+ with_gnu_ld=no
+ ;;
+ esac
+
+ _LT_AC_TAGVAR(ld_shlibs, $1)=yes
+ if test "$with_gnu_ld" = yes; then
+ # If archive_cmds runs LD, not CC, wlarc should be empty
+ wlarc='${wl}'
+
+ # Set some defaults for GNU ld with shared library support. These
+ # are reset later if shared libraries are not supported. Putting them
+ # here allows them to be overridden if necessary.
+ runpath_var=LD_RUN_PATH
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+ # ancient GNU ld didn't support --whole-archive et. al.
+ if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+ else
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+ fi
+ supports_anon_versioning=no
+ case `$LD -v 2>/dev/null` in
+ *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
+ *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+ *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+ *\ 2.11.*) ;; # other 2.11 versions
+ *) supports_anon_versioning=yes ;;
+ esac
+
+ # See if GNU ld supports shared libraries.
+ case $host_os in
+ aix3* | aix4* | aix5*)
+ # On AIX/PPC, the GNU linker is very broken
+ if test "$host_cpu" != ia64; then
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ cat <<EOF 1>&2
+
+*** Warning: the GNU linker, at least up to release 2.9.1, is reported
+*** to be unable to reliably create shared libraries on AIX.
+*** Therefore, libtool is disabling shared libraries support. If you
+*** really care for shared libraries, you may want to modify your PATH
+*** so that a non-GNU linker is found, and then restart.
+
+EOF
+ fi
+ ;;
+
+ amigaos*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+
+ # Samuel A. Falvo II <kc5tja at dolphin.openprojects.net> reports
+ # that the semantics of dynamic libraries on AmigaOS, at least up
+ # to version 4, is to share data among multiple programs linked
+ # with the same dynamic library. Since this doesn't match the
+ # behavior of shared libraries on other platforms, we can't use
+ # them.
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+
+ beos*)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+ # support --undefined. This deserves some investigation. FIXME
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+
+ cygwin* | mingw* | pw32*)
+ # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+ # as there is no search path for DLLs.
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ _LT_AC_TAGVAR(always_export_symbols, $1)=no
+ _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]] /s/.* \([[^ ]]*\)/\1 DATA/'\'' | $SED -e '\''/^[[AITW]] /s/.* //'\'' | sort | uniq > $export_symbols'
+
+ if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ # If the export-symbols file already is a .def file (1st line
+ # is EXPORTS), use it as is; otherwise, prepend...
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+ cp $export_symbols $output_objdir/$soname.def;
+ else
+ echo EXPORTS > $output_objdir/$soname.def;
+ cat $export_symbols >> $output_objdir/$soname.def;
+ fi~
+ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+
+ interix3*)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+ # Instead, shared libraries are loaded at an image base (0x10000000 by
+ # default) and relocated if they conflict, which is a slow very memory
+ # consuming and fragmenting process. To avoid this, we pick a random,
+ # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+ # time. Moving up from 0x10000000 also allows more sbrk(2) space.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ ;;
+
+ linux*)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ tmp_addflag=
+ case $cc_basename,$host_cpu in
+ pgcc*) # Portland Group C compiler
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+ tmp_addflag=' $pic_flag'
+ ;;
+ pgf77* | pgf90* | pgf95*) # Portland Group f77 and f90 compilers
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+ tmp_addflag=' $pic_flag -Mnomain' ;;
+ ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64
+ tmp_addflag=' -i_dynamic' ;;
+ efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64
+ tmp_addflag=' -i_dynamic -nofor_main' ;;
+ ifc* | ifort*) # Intel Fortran compiler
+ tmp_addflag=' -nofor_main' ;;
+ esac
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+
+ if test $supports_anon_versioning = yes; then
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $output_objdir/$libname.ver~
+ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+ $echo "local: *; };" >> $output_objdir/$libname.ver~
+ $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+ fi
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+
+ netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
+ wlarc=
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ fi
+ ;;
+
+ solaris*)
+ if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ cat <<EOF 1>&2
+
+*** Warning: The releases 2.8.* of the GNU linker cannot reliably
+*** create shared libraries on Solaris systems. Therefore, libtool
+*** is disabling shared libraries support. We urge you to upgrade GNU
+*** binutils to release 2.9.1 or newer. Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+EOF
+ elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+
+ sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
+ case `$LD -v 2>&1` in
+ *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*)
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ cat <<_LT_EOF 1>&2
+
+*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
+*** reliably create shared libraries on SCO systems. Therefore, libtool
+*** is disabling shared libraries support. We urge you to upgrade GNU
+*** binutils to release 2.16.91.0.3 or newer. Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+ ;;
+ *)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file,$export_symbols -o $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ esac
+ ;;
+
+ sunos4*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ wlarc=
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ *)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ else
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ fi
+ ;;
+ esac
+
+ if test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no; then
+ runpath_var=
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=
+ fi
+ else
+ # PORTME fill in a description of your system's linker (not GNU ld)
+ case $host_os in
+ aix3*)
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ _LT_AC_TAGVAR(always_export_symbols, $1)=yes
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
+ # Note: this linker hardcodes the directories in LIBPATH if there
+ # are no directories specified by -L.
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+ # Neither direct hardcoding nor static linking is supported with a
+ # broken collect2.
+ _LT_AC_TAGVAR(hardcode_direct, $1)=unsupported
+ fi
+ ;;
+
+ aix4* | aix5*)
+ if test "$host_cpu" = ia64; then
+ # On IA64, the linker does run time linking by default, so we don't
+ # have to do anything special.
+ aix_use_runtimelinking=no
+ exp_sym_flag='-Bexport'
+ no_entry_flag=""
+ else
+ # If we're using GNU nm, then we don't want the "-C" option.
+ # -C means demangle to AIX nm, but means don't demangle with GNU nm
+ if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols'
+ else
+ _LT_AC_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\[$]2 == "T") || (\[$]2 == "D") || (\[$]2 == "B")) && ([substr](\[$]3,1,1) != ".")) { print \[$]3 } }'\'' | sort -u > $export_symbols'
+ fi
+ aix_use_runtimelinking=no
+
+ # Test if we are trying to use run time linking or normal
+ # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+ # need to do runtime linking.
+ case $host_os in aix4.[[23]]|aix4.[[23]].*|aix5*)
+ for ld_flag in $LDFLAGS; do
+ if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+ aix_use_runtimelinking=yes
+ break
+ fi
+ done
+ ;;
+ esac
+
+ exp_sym_flag='-bexport'
+ no_entry_flag='-bnoentry'
+ fi
+
+ # When large executables or shared objects are built, AIX ld can
+ # have problems creating the table of contents. If linking a library
+ # or program results in "error TOC overflow" add -mminimal-toc to
+ # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not
+ # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+ _LT_AC_TAGVAR(archive_cmds, $1)=''
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':'
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+
+ if test "$GCC" = yes; then
+ case $host_os in aix4.[[012]]|aix4.[[012]].*)
+ # We only want to do this on AIX 4.2 and lower, the check
+ # below for broken collect2 doesn't work under 4.3+
+ collect2name=`${CC} -print-prog-name=collect2`
+ if test -f "$collect2name" && \
+ strings "$collect2name" | grep resolve_lib_name >/dev/null
+ then
+ # We have reworked collect2
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ else
+ # We have old collect2
+ _LT_AC_TAGVAR(hardcode_direct, $1)=unsupported
+ # It fails to find uninstalled libraries when the uninstalled
+ # path is not listed in the libpath. Setting hardcode_minus_L
+ # to unsupported forces relinking
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=
+ fi
+ ;;
+ esac
+ shared_flag='-shared'
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag="$shared_flag "'${wl}-G'
+ fi
+ else
+ # not using gcc
+ if test "$host_cpu" = ia64; then
+ # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+ # chokes on -Wl,-G. The following line is correct:
+ shared_flag='-G'
+ else
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag='${wl}-G'
+ else
+ shared_flag='${wl}-bM:SRE'
+ fi
+ fi
+ fi
+
+ # It seems that -bexpall does not export symbols beginning with
+ # underscore (_), so it is better to generate a list of symbols to export.
+ _LT_AC_TAGVAR(always_export_symbols, $1)=yes
+ if test "$aix_use_runtimelinking" = yes; then
+ # Warning - without using the other runtime loading flags (-brtl),
+ # -berok will link without error, but may produce a broken library.
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='-berok'
+ # Determine the default libpath from the value encoded in an empty executable.
+ _LT_AC_SYS_LIBPATH_AIX
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+ else
+ if test "$host_cpu" = ia64; then
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+ else
+ # Determine the default libpath from the value encoded in an empty executable.
+ _LT_AC_SYS_LIBPATH_AIX
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+ # Warning - without using the other run time loading flags,
+ # -berok will link without error, but may produce a broken library.
+ _LT_AC_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+ # Exported symbols can be pulled into shared objects from archives
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes
+ # This is similar to how AIX traditionally builds its shared libraries.
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+ fi
+ fi
+ ;;
+
+ amigaos*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ # see comment about different semantics on the GNU ld section
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+
+ bsdi[[45]]*)
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic
+ ;;
+
+ cygwin* | mingw* | pw32*)
+ # When not using gcc, we currently assume that we are using
+ # Microsoft Visual C++.
+ # hardcode_libdir_flag_spec is actually meaningless, as there is
+ # no search path for DLLs.
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ # Tell ltmain to make .lib files, not .a files.
+ libext=lib
+ # Tell ltmain to make .dll files, not .so files.
+ shrext_cmds=".dll"
+ # FIXME: Setting linknames here is a bad hack.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames='
+ # The linker will automatically build a .lib file if we build a DLL.
+ _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)='true'
+ # FIXME: Should let the user specify the lib program.
+ _LT_AC_TAGVAR(old_archive_cmds, $1)='lib /OUT:$oldlib$oldobjs$old_deplibs'
+ _LT_AC_TAGVAR(fix_srcfile_path, $1)='`cygpath -w "$srcfile"`'
+ _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+ ;;
+
+ darwin* | rhapsody*)
+ case $host_os in
+ rhapsody* | darwin1.[[012]])
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}suppress'
+ ;;
+ *) # Darwin 1.3 on
+ if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ else
+ case ${MACOSX_DEPLOYMENT_TARGET} in
+ 10.[[012]])
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ ;;
+ 10.*)
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-undefined ${wl}dynamic_lookup'
+ ;;
+ esac
+ fi
+ ;;
+ esac
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_automatic, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=''
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+ if test "$GCC" = yes ; then
+ output_verbose_link_cmd='echo'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
+ _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ else
+ case $cc_basename in
+ xlc*)
+ output_verbose_link_cmd='echo'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
+ _LT_AC_TAGVAR(module_cmds, $1)='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ _LT_AC_TAGVAR(module_expsym_cmds, $1)='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ ;;
+ *)
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ fi
+ ;;
+
+ dgux*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ freebsd1*)
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+
+ # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
+ # support. Future versions do this automatically, but an explicit c++rt0.o
+ # does not break anything, and helps significantly (at the cost of a little
+ # extra space).
+ freebsd2.2*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ # Unfortunately, older versions of FreeBSD 2 do not have this feature.
+ freebsd2*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
+ freebsd* | kfreebsd*-gnu | dragonfly*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ hpux9*)
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ ;;
+
+ hpux10*)
+ if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
+ fi
+ if test "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ fi
+ ;;
+
+ hpux11*)
+ if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+ case $host_cpu in
+ hppa*64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ ia64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ else
+ case $host_cpu in
+ hppa*64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ ia64*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ fi
+ if test "$with_gnu_ld" = no; then
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+
+ case $host_cpu in
+ hppa*64*|ia64*)
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+ *)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ ;;
+ esac
+ fi
+ ;;
+
+ irix5* | irix6* | nonstopux*)
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='-rpath $libdir'
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+ ;;
+
+ netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ newsos6)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ openbsd*)
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+ else
+ case $host_os in
+ openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ ;;
+ *)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+ ;;
+ esac
+ fi
+ ;;
+
+ os2*)
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=unsupported
+ _LT_AC_TAGVAR(archive_cmds, $1)='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
+ _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
+ ;;
+
+ osf3*)
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ else
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ ;;
+
+ osf4* | osf5*) # as osf3* with the addition of -msym flag
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+ else
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~
+ $LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp'
+
+ # Both c and cxx compiler support -rpath directly
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=:
+ ;;
+
+ solaris*)
+ _LT_AC_TAGVAR(no_undefined_flag, $1)=' -z text'
+ if test "$GCC" = yes; then
+ wlarc='${wl}'
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp'
+ else
+ wlarc=''
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ case $host_os in
+ solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+ *)
+ # The compiler driver will combine linker options so we
+ # cannot just pass the convience library names through
+ # without $wl, iff we do not link with $LD.
+ # Luckily, gcc supports the same syntax we need for Sun Studio.
+ # Supported since Solaris 2.6 (maybe 2.5.1?)
+ case $wlarc in
+ '')
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' ;;
+ *)
+ _LT_AC_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract' ;;
+ esac ;;
+ esac
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+ ;;
+
+ sunos4*)
+ if test "x$host_vendor" = xsequent; then
+ # Use $CC to link under sequent, because it throws in some extra .o
+ # files that make .init and .fini sections work.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
+ fi
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes
+ _LT_AC_TAGVAR(hardcode_minus_L, $1)=yes
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ sysv4)
+ case $host_vendor in
+ sni)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=yes # is this really true???
+ ;;
+ siemens)
+ ## LD is ld it makes a PLAMLIB
+ ## CC just makes a GrossModule.
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no
+ ;;
+ motorola)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie
+ ;;
+ esac
+ runpath_var='LD_RUN_PATH'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ sysv4.3*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport'
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ runpath_var=LD_RUN_PATH
+ hardcode_runpath_var=yes
+ _LT_AC_TAGVAR(ld_shlibs, $1)=yes
+ fi
+ ;;
+
+ sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7*)
+ _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ runpath_var='LD_RUN_PATH'
+
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ fi
+ ;;
+
+ sysv5* | sco3.2v5* | sco5v6*)
+ # Note: We can NOT use -z defs as we might desire, because we do not
+ # link with -lc, and that would cause any symbols used from libc to
+ # always be unresolved, which means just about no library would
+ # ever link correctly. If we're not using GNU ld we use -z text
+ # though, which does catch some bad symbols but isn't as heavy-handed
+ # as -z defs.
+ _LT_AC_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
+ _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=':'
+ _LT_AC_TAGVAR(link_all_deplibs, $1)=yes
+ _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+ runpath_var='LD_RUN_PATH'
+
+ if test "$GCC" = yes; then
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ _LT_AC_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ _LT_AC_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ fi
+ ;;
+
+ uts4*)
+ _LT_AC_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+ _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=no
+ ;;
+
+ *)
+ _LT_AC_TAGVAR(ld_shlibs, $1)=no
+ ;;
+ esac
+ fi
+])
+AC_MSG_RESULT([$_LT_AC_TAGVAR(ld_shlibs, $1)])
+test "$_LT_AC_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+#
+# Do we need to explicitly link libc?
+#
+case "x$_LT_AC_TAGVAR(archive_cmds_need_lc, $1)" in
+x|xyes)
+ # Assume -lc should be added
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes
+
+ if test "$enable_shared" = yes && test "$GCC" = yes; then
+ case $_LT_AC_TAGVAR(archive_cmds, $1) in
+ *'~'*)
+ # FIXME: we may have to deal with multi-command sequences.
+ ;;
+ '$CC '*)
+ # Test whether the compiler implicitly links with -lc since on some
+ # systems, -lgcc has to come before -lc. If gcc already passes -lc
+ # to ld, don't add -lc before -lgcc.
+ AC_MSG_CHECKING([whether -lc should be explicitly linked in])
+ $rm conftest*
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+ if AC_TRY_EVAL(ac_compile) 2>conftest.err; then
+ soname=conftest
+ lib=conftest
+ libobjs=conftest.$ac_objext
+ deplibs=
+ wl=$_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)
+ pic_flag=$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)
+ compiler_flags=-v
+ linker_flags=-v
+ verstring=
+ output_objdir=.
+ libname=conftest
+ lt_save_allow_undefined_flag=$_LT_AC_TAGVAR(allow_undefined_flag, $1)
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=
+ if AC_TRY_EVAL(_LT_AC_TAGVAR(archive_cmds, $1) 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1)
+ then
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=no
+ else
+ _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=yes
+ fi
+ _LT_AC_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag
+ else
+ cat conftest.err 1>&5
+ fi
+ $rm conftest*
+ AC_MSG_RESULT([$_LT_AC_TAGVAR(archive_cmds_need_lc, $1)])
+ ;;
+ esac
+ fi
+ ;;
+esac
+])# AC_LIBTOOL_PROG_LD_SHLIBS
+
+
+# _LT_AC_FILE_LTDLL_C
+# -------------------
+# Be careful that the start marker always follows a newline.
+AC_DEFUN([_LT_AC_FILE_LTDLL_C], [
+# /* ltdll.c starts here */
+# #define WIN32_LEAN_AND_MEAN
+# #include <windows.h>
+# #undef WIN32_LEAN_AND_MEAN
+# #include <stdio.h>
+#
+# #ifndef __CYGWIN__
+# # ifdef __CYGWIN32__
+# # define __CYGWIN__ __CYGWIN32__
+# # endif
+# #endif
+#
+# #ifdef __cplusplus
+# extern "C" {
+# #endif
+# BOOL APIENTRY DllMain (HINSTANCE hInst, DWORD reason, LPVOID reserved);
+# #ifdef __cplusplus
+# }
+# #endif
+#
+# #ifdef __CYGWIN__
+# #include <cygwin/cygwin_dll.h>
+# DECLARE_CYGWIN_DLL( DllMain );
+# #endif
+# HINSTANCE __hDllInstance_base;
+#
+# BOOL APIENTRY
+# DllMain (HINSTANCE hInst, DWORD reason, LPVOID reserved)
+# {
+# __hDllInstance_base = hInst;
+# return TRUE;
+# }
+# /* ltdll.c ends here */
+])# _LT_AC_FILE_LTDLL_C
+
+
+# _LT_AC_TAGVAR(VARNAME, [TAGNAME])
+# ---------------------------------
+AC_DEFUN([_LT_AC_TAGVAR], [ifelse([$2], [], [$1], [$1_$2])])
+
+
+# old names
+AC_DEFUN([AM_PROG_LIBTOOL], [AC_PROG_LIBTOOL])
+AC_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)])
+AC_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)])
+AC_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)])
+AC_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)])
+AC_DEFUN([AM_PROG_LD], [AC_PROG_LD])
+AC_DEFUN([AM_PROG_NM], [AC_PROG_NM])
+
+# This is just to silence aclocal about the macro not being used
+ifelse([AC_DISABLE_FAST_INSTALL])
+
+AC_DEFUN([LT_AC_PROG_GCJ],
+[AC_CHECK_TOOL(GCJ, gcj, no)
+ test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2"
+ AC_SUBST(GCJFLAGS)
+])
+
+AC_DEFUN([LT_AC_PROG_RC],
+[AC_CHECK_TOOL(RC, windres, no)
+])
+
+# NOTE: This macro has been submitted for inclusion into #
+# GNU Autoconf as AC_PROG_SED. When it is available in #
+# a released version of Autoconf we should remove this #
+# macro and use it instead. #
+# LT_AC_PROG_SED
+# --------------
+# Check for a fully-functional sed program, that truncates
+# as few characters as possible. Prefer GNU sed if found.
+AC_DEFUN([LT_AC_PROG_SED],
+[AC_MSG_CHECKING([for a sed that does not truncate output])
+AC_CACHE_VAL(lt_cv_path_SED,
+[# Loop through the user's path and test for sed and gsed.
+# Then use that list of sed's as ones to test for truncation.
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for lt_ac_prog in sed gsed; do
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
+ lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
+ fi
+ done
+ done
+done
+IFS=$as_save_IFS
+lt_ac_max=0
+lt_ac_count=0
+# Add /usr/xpg4/bin/sed as it is typically found on Solaris
+# along with /bin/sed that truncates output.
+for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
+ test ! -f $lt_ac_sed && continue
+ cat /dev/null > conftest.in
+ lt_ac_count=0
+ echo $ECHO_N "0123456789$ECHO_C" >conftest.in
+ # Check for GNU sed and select it if it is found.
+ if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
+ lt_cv_path_SED=$lt_ac_sed
+ break
+ fi
+ while true; do
+ cat conftest.in conftest.in >conftest.tmp
+ mv conftest.tmp conftest.in
+ cp conftest.in conftest.nl
+ echo >>conftest.nl
+ $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
+ cmp -s conftest.out conftest.nl || break
+ # 10000 chars as input seems more than enough
+ test $lt_ac_count -gt 10 && break
+ lt_ac_count=`expr $lt_ac_count + 1`
+ if test $lt_ac_count -gt $lt_ac_max; then
+ lt_ac_max=$lt_ac_count
+ lt_cv_path_SED=$lt_ac_sed
+ fi
+ done
+done
+])
+SED=$lt_cv_path_SED
+AC_SUBST([SED])
+AC_MSG_RESULT([$SED])
+])
+
+# Copyright (C) 2002, 2003, 2005 Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# AM_AUTOMAKE_VERSION(VERSION)
+# ----------------------------
+# Automake X.Y traces this macro to ensure aclocal.m4 has been
+# generated from the m4 files accompanying Automake X.Y.
+AC_DEFUN([AM_AUTOMAKE_VERSION], [am__api_version="1.9"])
+
+# AM_SET_CURRENT_AUTOMAKE_VERSION
+# -------------------------------
+# Call AM_AUTOMAKE_VERSION so it can be traced.
+# This function is AC_REQUIREd by AC_INIT_AUTOMAKE.
+AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION],
+ [AM_AUTOMAKE_VERSION([1.9.6])])
+
+# AM_AUX_DIR_EXPAND -*- Autoconf -*-
+
+# Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets
+# $ac_aux_dir to `$srcdir/foo'. In other projects, it is set to
+# `$srcdir', `$srcdir/..', or `$srcdir/../..'.
+#
+# Of course, Automake must honor this variable whenever it calls a
+# tool from the auxiliary directory. The problem is that $srcdir (and
+# therefore $ac_aux_dir as well) can be either absolute or relative,
+# depending on how configure is run. This is pretty annoying, since
+# it makes $ac_aux_dir quite unusable in subdirectories: in the top
+# source directory, any form will work fine, but in subdirectories a
+# relative path needs to be adjusted first.
+#
+# $ac_aux_dir/missing
+# fails when called from a subdirectory if $ac_aux_dir is relative
+# $top_srcdir/$ac_aux_dir/missing
+# fails if $ac_aux_dir is absolute,
+# fails when called from a subdirectory in a VPATH build with
+# a relative $ac_aux_dir
+#
+# The reason of the latter failure is that $top_srcdir and $ac_aux_dir
+# are both prefixed by $srcdir. In an in-source build this is usually
+# harmless because $srcdir is `.', but things will broke when you
+# start a VPATH build or use an absolute $srcdir.
+#
+# So we could use something similar to $top_srcdir/$ac_aux_dir/missing,
+# iff we strip the leading $srcdir from $ac_aux_dir. That would be:
+# am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"`
+# and then we would define $MISSING as
+# MISSING="\${SHELL} $am_aux_dir/missing"
+# This will work as long as MISSING is not called from configure, because
+# unfortunately $(top_srcdir) has no meaning in configure.
+# However there are other variables, like CC, which are often used in
+# configure, and could therefore not use this "fixed" $ac_aux_dir.
+#
+# Another solution, used here, is to always expand $ac_aux_dir to an
+# absolute PATH. The drawback is that using absolute paths prevent a
+# configured tree to be moved without reconfiguration.
+
+AC_DEFUN([AM_AUX_DIR_EXPAND],
+[dnl Rely on autoconf to set up CDPATH properly.
+AC_PREREQ([2.50])dnl
+# expand $ac_aux_dir to an absolute path
+am_aux_dir=`cd $ac_aux_dir && pwd`
+])
+
+# AM_CONDITIONAL -*- Autoconf -*-
+
+# Copyright (C) 1997, 2000, 2001, 2003, 2004, 2005
+# Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# serial 7
+
+# AM_CONDITIONAL(NAME, SHELL-CONDITION)
+# -------------------------------------
+# Define a conditional.
+AC_DEFUN([AM_CONDITIONAL],
+[AC_PREREQ(2.52)dnl
+ ifelse([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])],
+ [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl
+AC_SUBST([$1_TRUE])
+AC_SUBST([$1_FALSE])
+if $2; then
+ $1_TRUE=
+ $1_FALSE='#'
+else
+ $1_TRUE='#'
+ $1_FALSE=
+fi
+AC_CONFIG_COMMANDS_PRE(
+[if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then
+ AC_MSG_ERROR([[conditional "$1" was never defined.
+Usually this means the macro was only invoked conditionally.]])
+fi])])
+
+
+# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005
+# Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# serial 8
+
+# There are a few dirty hacks below to avoid letting `AC_PROG_CC' be
+# written in clear, in which case automake, when reading aclocal.m4,
+# will think it sees a *use*, and therefore will trigger all it's
+# C support machinery. Also note that it means that autoscan, seeing
+# CC etc. in the Makefile, will ask for an AC_PROG_CC use...
+
+
+# _AM_DEPENDENCIES(NAME)
+# ----------------------
+# See how the compiler implements dependency checking.
+# NAME is "CC", "CXX", "GCJ", or "OBJC".
+# We try a few techniques and use that to set a single cache variable.
+#
+# We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was
+# modified to invoke _AM_DEPENDENCIES(CC); we would have a circular
+# dependency, and given that the user is not expected to run this macro,
+# just rely on AC_PROG_CC.
+AC_DEFUN([_AM_DEPENDENCIES],
+[AC_REQUIRE([AM_SET_DEPDIR])dnl
+AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl
+AC_REQUIRE([AM_MAKE_INCLUDE])dnl
+AC_REQUIRE([AM_DEP_TRACK])dnl
+
+ifelse([$1], CC, [depcc="$CC" am_compiler_list=],
+ [$1], CXX, [depcc="$CXX" am_compiler_list=],
+ [$1], OBJC, [depcc="$OBJC" am_compiler_list='gcc3 gcc'],
+ [$1], GCJ, [depcc="$GCJ" am_compiler_list='gcc3 gcc'],
+ [depcc="$$1" am_compiler_list=])
+
+AC_CACHE_CHECK([dependency style of $depcc],
+ [am_cv_$1_dependencies_compiler_type],
+[if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then
+ # We make a subdir and do the tests there. Otherwise we can end up
+ # making bogus files that we don't know about and never remove. For
+ # instance it was reported that on HP-UX the gcc test will end up
+ # making a dummy file named `D' -- because `-MD' means `put the output
+ # in D'.
+ mkdir conftest.dir
+ # Copy depcomp to subdir because otherwise we won't find it if we're
+ # using a relative directory.
+ cp "$am_depcomp" conftest.dir
+ cd conftest.dir
+ # We will build objects and dependencies in a subdirectory because
+ # it helps to detect inapplicable dependency modes. For instance
+ # both Tru64's cc and ICC support -MD to output dependencies as a
+ # side effect of compilation, but ICC will put the dependencies in
+ # the current directory while Tru64 will put them in the object
+ # directory.
+ mkdir sub
+
+ am_cv_$1_dependencies_compiler_type=none
+ if test "$am_compiler_list" = ""; then
+ am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp`
+ fi
+ for depmode in $am_compiler_list; do
+ # Setup a source with many dependencies, because some compilers
+ # like to wrap large dependency lists on column 80 (with \), and
+ # we should not choose a depcomp mode which is confused by this.
+ #
+ # We need to recreate these files for each test, as the compiler may
+ # overwrite some of them when testing with obscure command lines.
+ # This happens at least with the AIX C compiler.
+ : > sub/conftest.c
+ for i in 1 2 3 4 5 6; do
+ echo '#include "conftst'$i'.h"' >> sub/conftest.c
+ # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with
+ # Solaris 8's {/usr,}/bin/sh.
+ touch sub/conftst$i.h
+ done
+ echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf
+
+ case $depmode in
+ nosideeffect)
+ # after this tag, mechanisms are not by side-effect, so they'll
+ # only be used when explicitly requested
+ if test "x$enable_dependency_tracking" = xyes; then
+ continue
+ else
+ break
+ fi
+ ;;
+ none) break ;;
+ esac
+ # We check with `-c' and `-o' for the sake of the "dashmstdout"
+ # mode. It turns out that the SunPro C++ compiler does not properly
+ # handle `-M -o', and we need to detect this.
+ if depmode=$depmode \
+ source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \
+ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \
+ $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \
+ >/dev/null 2>conftest.err &&
+ grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 &&
+ grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 &&
+ ${MAKE-make} -s -f confmf > /dev/null 2>&1; then
+ # icc doesn't choke on unknown options, it will just issue warnings
+ # or remarks (even with -Werror). So we grep stderr for any message
+ # that says an option was ignored or not supported.
+ # When given -MP, icc 7.0 and 7.1 complain thusly:
+ # icc: Command line warning: ignoring option '-M'; no argument required
+ # The diagnosis changed in icc 8.0:
+ # icc: Command line remark: option '-MP' not supported
+ if (grep 'ignoring option' conftest.err ||
+ grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else
+ am_cv_$1_dependencies_compiler_type=$depmode
+ break
+ fi
+ fi
+ done
+
+ cd ..
+ rm -rf conftest.dir
+else
+ am_cv_$1_dependencies_compiler_type=none
+fi
+])
+AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type])
+AM_CONDITIONAL([am__fastdep$1], [
+ test "x$enable_dependency_tracking" != xno \
+ && test "$am_cv_$1_dependencies_compiler_type" = gcc3])
+])
+
+
+# AM_SET_DEPDIR
+# -------------
+# Choose a directory name for dependency files.
+# This macro is AC_REQUIREd in _AM_DEPENDENCIES
+AC_DEFUN([AM_SET_DEPDIR],
+[AC_REQUIRE([AM_SET_LEADING_DOT])dnl
+AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl
+])
+
+
+# AM_DEP_TRACK
+# ------------
+AC_DEFUN([AM_DEP_TRACK],
+[AC_ARG_ENABLE(dependency-tracking,
+[ --disable-dependency-tracking speeds up one-time build
+ --enable-dependency-tracking do not reject slow dependency extractors])
+if test "x$enable_dependency_tracking" != xno; then
+ am_depcomp="$ac_aux_dir/depcomp"
+ AMDEPBACKSLASH='\'
+fi
+AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno])
+AC_SUBST([AMDEPBACKSLASH])
+])
+
+# Generate code to set up dependency tracking. -*- Autoconf -*-
+
+# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005
+# Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+#serial 3
+
+# _AM_OUTPUT_DEPENDENCY_COMMANDS
+# ------------------------------
+AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS],
+[for mf in $CONFIG_FILES; do
+ # Strip MF so we end up with the name of the file.
+ mf=`echo "$mf" | sed -e 's/:.*$//'`
+ # Check whether this is an Automake generated Makefile or not.
+ # We used to match only the files named `Makefile.in', but
+ # some people rename them; so instead we look at the file content.
+ # Grep'ing the first line is not enough: some people post-process
+ # each Makefile.in and add a new line on top of each file to say so.
+ # So let's grep whole file.
+ if grep '^#.*generated by automake' $mf > /dev/null 2>&1; then
+ dirpart=`AS_DIRNAME("$mf")`
+ else
+ continue
+ fi
+ # Extract the definition of DEPDIR, am__include, and am__quote
+ # from the Makefile without running `make'.
+ DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"`
+ test -z "$DEPDIR" && continue
+ am__include=`sed -n 's/^am__include = //p' < "$mf"`
+ test -z "am__include" && continue
+ am__quote=`sed -n 's/^am__quote = //p' < "$mf"`
+ # When using ansi2knr, U may be empty or an underscore; expand it
+ U=`sed -n 's/^U = //p' < "$mf"`
+ # Find all dependency output files, they are included files with
+ # $(DEPDIR) in their names. We invoke sed twice because it is the
+ # simplest approach to changing $(DEPDIR) to its actual value in the
+ # expansion.
+ for file in `sed -n "
+ s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \
+ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do
+ # Make sure the directory exists.
+ test -f "$dirpart/$file" && continue
+ fdir=`AS_DIRNAME(["$file"])`
+ AS_MKDIR_P([$dirpart/$fdir])
+ # echo "creating $dirpart/$file"
+ echo '# dummy' > "$dirpart/$file"
+ done
+done
+])# _AM_OUTPUT_DEPENDENCY_COMMANDS
+
+
+# AM_OUTPUT_DEPENDENCY_COMMANDS
+# -----------------------------
+# This macro should only be invoked once -- use via AC_REQUIRE.
+#
+# This code is only required when automatic dependency tracking
+# is enabled. FIXME. This creates each `.P' file that we will
+# need in order to bootstrap the dependency handling code.
+AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS],
+[AC_CONFIG_COMMANDS([depfiles],
+ [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS],
+ [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"])
+])
+
+# Do all the work for Automake. -*- Autoconf -*-
+
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
+# Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# serial 12
+
+# This macro actually does too much. Some checks are only needed if
+# your package does certain things. But this isn't really a big deal.
+
+# AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE])
+# AM_INIT_AUTOMAKE([OPTIONS])
+# -----------------------------------------------
+# The call with PACKAGE and VERSION arguments is the old style
+# call (pre autoconf-2.50), which is being phased out. PACKAGE
+# and VERSION should now be passed to AC_INIT and removed from
+# the call to AM_INIT_AUTOMAKE.
+# We support both call styles for the transition. After
+# the next Automake release, Autoconf can make the AC_INIT
+# arguments mandatory, and then we can depend on a new Autoconf
+# release and drop the old call support.
+AC_DEFUN([AM_INIT_AUTOMAKE],
+[AC_PREREQ([2.58])dnl
+dnl Autoconf wants to disallow AM_ names. We explicitly allow
+dnl the ones we care about.
+m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl
+AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl
+AC_REQUIRE([AC_PROG_INSTALL])dnl
+# test to see if srcdir already configured
+if test "`cd $srcdir && pwd`" != "`pwd`" &&
+ test -f $srcdir/config.status; then
+ AC_MSG_ERROR([source directory already configured; run "make distclean" there first])
+fi
+
+# test whether we have cygpath
+if test -z "$CYGPATH_W"; then
+ if (cygpath --version) >/dev/null 2>/dev/null; then
+ CYGPATH_W='cygpath -w'
+ else
+ CYGPATH_W=echo
+ fi
+fi
+AC_SUBST([CYGPATH_W])
+
+# Define the identity of the package.
+dnl Distinguish between old-style and new-style calls.
+m4_ifval([$2],
+[m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl
+ AC_SUBST([PACKAGE], [$1])dnl
+ AC_SUBST([VERSION], [$2])],
+[_AM_SET_OPTIONS([$1])dnl
+ AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl
+ AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl
+
+_AM_IF_OPTION([no-define],,
+[AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of package])
+ AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version number of package])])dnl
+
+# Some tools Automake needs.
+AC_REQUIRE([AM_SANITY_CHECK])dnl
+AC_REQUIRE([AC_ARG_PROGRAM])dnl
+AM_MISSING_PROG(ACLOCAL, aclocal-${am__api_version})
+AM_MISSING_PROG(AUTOCONF, autoconf)
+AM_MISSING_PROG(AUTOMAKE, automake-${am__api_version})
+AM_MISSING_PROG(AUTOHEADER, autoheader)
+AM_MISSING_PROG(MAKEINFO, makeinfo)
+AM_PROG_INSTALL_SH
+AM_PROG_INSTALL_STRIP
+AC_REQUIRE([AM_PROG_MKDIR_P])dnl
+# We need awk for the "check" target. The system "awk" is bad on
+# some platforms.
+AC_REQUIRE([AC_PROG_AWK])dnl
+AC_REQUIRE([AC_PROG_MAKE_SET])dnl
+AC_REQUIRE([AM_SET_LEADING_DOT])dnl
+_AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])],
+ [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])],
+ [_AM_PROG_TAR([v7])])])
+_AM_IF_OPTION([no-dependencies],,
+[AC_PROVIDE_IFELSE([AC_PROG_CC],
+ [_AM_DEPENDENCIES(CC)],
+ [define([AC_PROG_CC],
+ defn([AC_PROG_CC])[_AM_DEPENDENCIES(CC)])])dnl
+AC_PROVIDE_IFELSE([AC_PROG_CXX],
+ [_AM_DEPENDENCIES(CXX)],
+ [define([AC_PROG_CXX],
+ defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl
+])
+])
+
+
+# When config.status generates a header, we must update the stamp-h file.
+# This file resides in the same directory as the config header
+# that is generated. The stamp files are numbered to have different names.
+
+# Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the
+# loop where config.status creates the headers, so we can generate
+# our stamp files there.
+AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK],
+[# Compute $1's index in $config_headers.
+_am_stamp_count=1
+for _am_header in $config_headers :; do
+ case $_am_header in
+ $1 | $1:* )
+ break ;;
+ * )
+ _am_stamp_count=`expr $_am_stamp_count + 1` ;;
+ esac
+done
+echo "timestamp for $1" >`AS_DIRNAME([$1])`/stamp-h[]$_am_stamp_count])
+
+# Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# AM_PROG_INSTALL_SH
+# ------------------
+# Define $install_sh.
+AC_DEFUN([AM_PROG_INSTALL_SH],
+[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
+install_sh=${install_sh-"$am_aux_dir/install-sh"}
+AC_SUBST(install_sh)])
+
+# Copyright (C) 2003, 2005 Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# serial 2
+
+# Check whether the underlying file-system supports filenames
+# with a leading dot. For instance MS-DOS doesn't.
+AC_DEFUN([AM_SET_LEADING_DOT],
+[rm -rf .tst 2>/dev/null
+mkdir .tst 2>/dev/null
+if test -d .tst; then
+ am__leading_dot=.
+else
+ am__leading_dot=_
+fi
+rmdir .tst 2>/dev/null
+AC_SUBST([am__leading_dot])])
+
+# Check to see how 'make' treats includes. -*- Autoconf -*-
+
+# Copyright (C) 2001, 2002, 2003, 2005 Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# serial 3
+
+# AM_MAKE_INCLUDE()
+# -----------------
+# Check to see how make treats includes.
+AC_DEFUN([AM_MAKE_INCLUDE],
+[am_make=${MAKE-make}
+cat > confinc << 'END'
+am__doit:
+ @echo done
+.PHONY: am__doit
+END
+# If we don't find an include directive, just comment out the code.
+AC_MSG_CHECKING([for style of include used by $am_make])
+am__include="#"
+am__quote=
+_am_result=none
+# First try GNU make style include.
+echo "include confinc" > confmf
+# We grep out `Entering directory' and `Leaving directory'
+# messages which can occur if `w' ends up in MAKEFLAGS.
+# In particular we don't look at `^make:' because GNU make might
+# be invoked under some other name (usually "gmake"), in which
+# case it prints its new name instead of `make'.
+if test "`$am_make -s -f confmf 2> /dev/null | grep -v 'ing directory'`" = "done"; then
+ am__include=include
+ am__quote=
+ _am_result=GNU
+fi
+# Now try BSD make style include.
+if test "$am__include" = "#"; then
+ echo '.include "confinc"' > confmf
+ if test "`$am_make -s -f confmf 2> /dev/null`" = "done"; then
+ am__include=.include
+ am__quote="\""
+ _am_result=BSD
+ fi
+fi
+AC_SUBST([am__include])
+AC_SUBST([am__quote])
+AC_MSG_RESULT([$_am_result])
+rm -f confinc confmf
+])
+
+# Fake the existence of programs that GNU maintainers use. -*- Autoconf -*-
+
+# Copyright (C) 1997, 1999, 2000, 2001, 2003, 2005
+# Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# serial 4
+
+# AM_MISSING_PROG(NAME, PROGRAM)
+# ------------------------------
+AC_DEFUN([AM_MISSING_PROG],
+[AC_REQUIRE([AM_MISSING_HAS_RUN])
+$1=${$1-"${am_missing_run}$2"}
+AC_SUBST($1)])
+
+
+# AM_MISSING_HAS_RUN
+# ------------------
+# Define MISSING if not defined so far and test if it supports --run.
+# If it does, set am_missing_run to use it, otherwise, to nothing.
+AC_DEFUN([AM_MISSING_HAS_RUN],
+[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
+test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing"
+# Use eval to expand $SHELL
+if eval "$MISSING --run true"; then
+ am_missing_run="$MISSING --run "
+else
+ am_missing_run=
+ AC_MSG_WARN([`missing' script is too old or missing])
+fi
+])
+
+# Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# AM_PROG_MKDIR_P
+# ---------------
+# Check whether `mkdir -p' is supported, fallback to mkinstalldirs otherwise.
+#
+# Automake 1.8 used `mkdir -m 0755 -p --' to ensure that directories
+# created by `make install' are always world readable, even if the
+# installer happens to have an overly restrictive umask (e.g. 077).
+# This was a mistake. There are at least two reasons why we must not
+# use `-m 0755':
+# - it causes special bits like SGID to be ignored,
+# - it may be too restrictive (some setups expect 775 directories).
+#
+# Do not use -m 0755 and let people choose whatever they expect by
+# setting umask.
+#
+# We cannot accept any implementation of `mkdir' that recognizes `-p'.
+# Some implementations (such as Solaris 8's) are not thread-safe: if a
+# parallel make tries to run `mkdir -p a/b' and `mkdir -p a/c'
+# concurrently, both version can detect that a/ is missing, but only
+# one can create it and the other will error out. Consequently we
+# restrict ourselves to GNU make (using the --version option ensures
+# this.)
+AC_DEFUN([AM_PROG_MKDIR_P],
+[if mkdir -p --version . >/dev/null 2>&1 && test ! -d ./--version; then
+ # We used to keeping the `.' as first argument, in order to
+ # allow $(mkdir_p) to be used without argument. As in
+ # $(mkdir_p) $(somedir)
+ # where $(somedir) is conditionally defined. However this is wrong
+ # for two reasons:
+ # 1. if the package is installed by a user who cannot write `.'
+ # make install will fail,
+ # 2. the above comment should most certainly read
+ # $(mkdir_p) $(DESTDIR)$(somedir)
+ # so it does not work when $(somedir) is undefined and
+ # $(DESTDIR) is not.
+ # To support the latter case, we have to write
+ # test -z "$(somedir)" || $(mkdir_p) $(DESTDIR)$(somedir),
+ # so the `.' trick is pointless.
+ mkdir_p='mkdir -p --'
+else
+ # On NextStep and OpenStep, the `mkdir' command does not
+ # recognize any option. It will interpret all options as
+ # directories to create, and then abort because `.' already
+ # exists.
+ for d in ./-p ./--version;
+ do
+ test -d $d && rmdir $d
+ done
+ # $(mkinstalldirs) is defined by Automake if mkinstalldirs exists.
+ if test -f "$ac_aux_dir/mkinstalldirs"; then
+ mkdir_p='$(mkinstalldirs)'
+ else
+ mkdir_p='$(install_sh) -d'
+ fi
+fi
+AC_SUBST([mkdir_p])])
+
+# Helper functions for option handling. -*- Autoconf -*-
+
+# Copyright (C) 2001, 2002, 2003, 2005 Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# serial 3
+
+# _AM_MANGLE_OPTION(NAME)
+# -----------------------
+AC_DEFUN([_AM_MANGLE_OPTION],
+[[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])])
+
+# _AM_SET_OPTION(NAME)
+# ------------------------------
+# Set option NAME. Presently that only means defining a flag for this option.
+AC_DEFUN([_AM_SET_OPTION],
+[m4_define(_AM_MANGLE_OPTION([$1]), 1)])
+
+# _AM_SET_OPTIONS(OPTIONS)
+# ----------------------------------
+# OPTIONS is a space-separated list of Automake options.
+AC_DEFUN([_AM_SET_OPTIONS],
+[AC_FOREACH([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])])
+
+# _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET])
+# -------------------------------------------
+# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
+AC_DEFUN([_AM_IF_OPTION],
+[m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])])
+
+# Check to make sure that the build environment is sane. -*- Autoconf -*-
+
+# Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005
+# Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# serial 4
+
+# AM_SANITY_CHECK
+# ---------------
+AC_DEFUN([AM_SANITY_CHECK],
+[AC_MSG_CHECKING([whether build environment is sane])
+# Just in case
+sleep 1
+echo timestamp > conftest.file
+# Do `set' in a subshell so we don't clobber the current shell's
+# arguments. Must try -L first in case configure is actually a
+# symlink; some systems play weird games with the mod time of symlinks
+# (eg FreeBSD returns the mod time of the symlink's containing
+# directory).
+if (
+ set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null`
+ if test "$[*]" = "X"; then
+ # -L didn't work.
+ set X `ls -t $srcdir/configure conftest.file`
+ fi
+ rm -f conftest.file
+ if test "$[*]" != "X $srcdir/configure conftest.file" \
+ && test "$[*]" != "X conftest.file $srcdir/configure"; then
+
+ # If neither matched, then we have a broken ls. This can happen
+ # if, for instance, CONFIG_SHELL is bash and it inherits a
+ # broken ls alias from the environment. This has actually
+ # happened. Such a system could not be considered "sane".
+ AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken
+alias in your environment])
+ fi
+
+ test "$[2]" = conftest.file
+ )
+then
+ # Ok.
+ :
+else
+ AC_MSG_ERROR([newly created file is older than distributed files!
+Check your system clock])
+fi
+AC_MSG_RESULT(yes)])
+
+# Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# AM_PROG_INSTALL_STRIP
+# ---------------------
+# One issue with vendor `install' (even GNU) is that you can't
+# specify the program used to strip binaries. This is especially
+# annoying in cross-compiling environments, where the build's strip
+# is unlikely to handle the host's binaries.
+# Fortunately install-sh will honor a STRIPPROG variable, so we
+# always use install-sh in `make install-strip', and initialize
+# STRIPPROG with the value of the STRIP variable (set by the user).
+AC_DEFUN([AM_PROG_INSTALL_STRIP],
+[AC_REQUIRE([AM_PROG_INSTALL_SH])dnl
+# Installed binaries are usually stripped using `strip' when the user
+# run `make install-strip'. However `strip' might not be the right
+# tool to use in cross-compilation environments, therefore Automake
+# will honor the `STRIP' environment variable to overrule this program.
+dnl Don't test for $cross_compiling = yes, because it might be `maybe'.
+if test "$cross_compiling" != no; then
+ AC_CHECK_TOOL([STRIP], [strip], :)
+fi
+INSTALL_STRIP_PROGRAM="\${SHELL} \$(install_sh) -c -s"
+AC_SUBST([INSTALL_STRIP_PROGRAM])])
+
+# Check how to create a tarball. -*- Autoconf -*-
+
+# Copyright (C) 2004, 2005 Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# serial 2
+
+# _AM_PROG_TAR(FORMAT)
+# --------------------
+# Check how to create a tarball in format FORMAT.
+# FORMAT should be one of `v7', `ustar', or `pax'.
+#
+# Substitute a variable $(am__tar) that is a command
+# writing to stdout a FORMAT-tarball containing the directory
+# $tardir.
+# tardir=directory && $(am__tar) > result.tar
+#
+# Substitute a variable $(am__untar) that extract such
+# a tarball read from stdin.
+# $(am__untar) < result.tar
+AC_DEFUN([_AM_PROG_TAR],
+[# Always define AMTAR for backward compatibility.
+AM_MISSING_PROG([AMTAR], [tar])
+m4_if([$1], [v7],
+ [am__tar='${AMTAR} chof - "$$tardir"'; am__untar='${AMTAR} xf -'],
+ [m4_case([$1], [ustar],, [pax],,
+ [m4_fatal([Unknown tar format])])
+AC_MSG_CHECKING([how to create a $1 tar archive])
+# Loop over all known methods to create a tar archive until one works.
+_am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none'
+_am_tools=${am_cv_prog_tar_$1-$_am_tools}
+# Do not fold the above two line into one, because Tru64 sh and
+# Solaris sh will not grok spaces in the rhs of `-'.
+for _am_tool in $_am_tools
+do
+ case $_am_tool in
+ gnutar)
+ for _am_tar in tar gnutar gtar;
+ do
+ AM_RUN_LOG([$_am_tar --version]) && break
+ done
+ am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"'
+ am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"'
+ am__untar="$_am_tar -xf -"
+ ;;
+ plaintar)
+ # Must skip GNU tar: if it does not support --format= it doesn't create
+ # ustar tarball either.
+ (tar --version) >/dev/null 2>&1 && continue
+ am__tar='tar chf - "$$tardir"'
+ am__tar_='tar chf - "$tardir"'
+ am__untar='tar xf -'
+ ;;
+ pax)
+ am__tar='pax -L -x $1 -w "$$tardir"'
+ am__tar_='pax -L -x $1 -w "$tardir"'
+ am__untar='pax -r'
+ ;;
+ cpio)
+ am__tar='find "$$tardir" -print | cpio -o -H $1 -L'
+ am__tar_='find "$tardir" -print | cpio -o -H $1 -L'
+ am__untar='cpio -i -H $1 -d'
+ ;;
+ none)
+ am__tar=false
+ am__tar_=false
+ am__untar=false
+ ;;
+ esac
+
+ # If the value was cached, stop now. We just wanted to have am__tar
+ # and am__untar set.
+ test -n "${am_cv_prog_tar_$1}" && break
+
+ # tar/untar a dummy directory, and stop if the command works
+ rm -rf conftest.dir
+ mkdir conftest.dir
+ echo GrepMe > conftest.dir/file
+ AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar])
+ rm -rf conftest.dir
+ if test -s conftest.tar; then
+ AM_RUN_LOG([$am__untar <conftest.tar])
+ grep GrepMe conftest.dir/file >/dev/null 2>&1 && break
+ fi
+done
+rm -rf conftest.dir
+
+AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool])
+AC_MSG_RESULT([$am_cv_prog_tar_$1])])
+AC_SUBST([am__tar])
+AC_SUBST([am__untar])
+]) # _AM_PROG_TAR
+
diff --git a/jasper-1.900.1-6ct/configure b/jasper-1.900.1-6ct/configure
new file mode 100755
index 0000000..87e9b02
--- /dev/null
+++ b/jasper-1.900.1-6ct/configure
@@ -0,0 +1,23856 @@
+#! /bin/sh
+# Guess values for system-dependent variables and create Makefiles.
+# Generated by GNU Autoconf 2.59 for jasper 1.900.1.
+#
+# Copyright (C) 2003 Free Software Foundation, Inc.
+# This configure script is free software; the Free Software Foundation
+# gives unlimited permission to copy, distribute and modify it.
+## --------------------- ##
+## M4sh Initialization. ##
+## --------------------- ##
+
+# Be Bourne compatible
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+ emulate sh
+ NULLCMD=:
+ # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+ # is contrary to our usage. Disable this feature.
+ alias -g '${1+"$@"}'='"$@"'
+elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then
+ set -o posix
+fi
+DUALCASE=1; export DUALCASE # for MKS sh
+
+# Support unset when possible.
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+ as_unset=unset
+else
+ as_unset=false
+fi
+
+
+# Work around bugs in pre-3.0 UWIN ksh.
+$as_unset ENV MAIL MAILPATH
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+for as_var in \
+ LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
+ LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
+ LC_TELEPHONE LC_TIME
+do
+ if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
+ eval $as_var=C; export $as_var
+ else
+ $as_unset $as_var
+ fi
+done
+
+# Required to use basename.
+if expr a : '\(a\)' >/dev/null 2>&1; then
+ as_expr=expr
+else
+ as_expr=false
+fi
+
+if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then
+ as_basename=basename
+else
+ as_basename=false
+fi
+
+
+# Name of the executable.
+as_me=`$as_basename "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+ X"$0" : 'X\(//\)$' \| \
+ X"$0" : 'X\(/\)$' \| \
+ . : '\(.\)' 2>/dev/null ||
+echo X/"$0" |
+ sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; }
+ /^X\/\(\/\/\)$/{ s//\1/; q; }
+ /^X\/\(\/\).*/{ s//\1/; q; }
+ s/.*/./; q'`
+
+
+# PATH needs CR, and LINENO needs CR and PATH.
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+ echo "#! /bin/sh" >conf$$.sh
+ echo "exit 0" >>conf$$.sh
+ chmod +x conf$$.sh
+ if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+ PATH_SEPARATOR=';'
+ else
+ PATH_SEPARATOR=:
+ fi
+ rm -f conf$$.sh
+fi
+
+
+ as_lineno_1=$LINENO
+ as_lineno_2=$LINENO
+ as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
+ test "x$as_lineno_1" != "x$as_lineno_2" &&
+ test "x$as_lineno_3" = "x$as_lineno_2" || {
+ # Find who we are. Look in the path if we contain no path at all
+ # relative or not.
+ case $0 in
+ *[\\/]* ) as_myself=$0 ;;
+ *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+
+ ;;
+ esac
+ # We did not find ourselves, most probably we were run as `sh COMMAND'
+ # in which case we are not to be found in the path.
+ if test "x$as_myself" = x; then
+ as_myself=$0
+ fi
+ if test ! -f "$as_myself"; then
+ { echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2
+ { (exit 1); exit 1; }; }
+ fi
+ case $CONFIG_SHELL in
+ '')
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for as_base in sh bash ksh sh5; do
+ case $as_dir in
+ /*)
+ if ("$as_dir/$as_base" -c '
+ as_lineno_1=$LINENO
+ as_lineno_2=$LINENO
+ as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
+ test "x$as_lineno_1" != "x$as_lineno_2" &&
+ test "x$as_lineno_3" = "x$as_lineno_2" ') 2>/dev/null; then
+ $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; }
+ $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; }
+ CONFIG_SHELL=$as_dir/$as_base
+ export CONFIG_SHELL
+ exec "$CONFIG_SHELL" "$0" ${1+"$@"}
+ fi;;
+ esac
+ done
+done
+;;
+ esac
+
+ # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
+ # uniformly replaced by the line number. The first 'sed' inserts a
+ # line-number line before each line; the second 'sed' does the real
+ # work. The second script uses 'N' to pair each line-number line
+ # with the numbered line, and appends trailing '-' during
+ # substitution so that $LINENO is not a special case at line end.
+ # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
+ # second 'sed' script. Blame Lee E. McMahon for sed's syntax. :-)
+ sed '=' <$as_myself |
+ sed '
+ N
+ s,$,-,
+ : loop
+ s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3,
+ t loop
+ s,-$,,
+ s,^['$as_cr_digits']*\n,,
+ ' >$as_me.lineno &&
+ chmod +x $as_me.lineno ||
+ { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
+ { (exit 1); exit 1; }; }
+
+ # Don't try to exec as it changes $[0], causing all sort of problems
+ # (the dirname of $[0] is not the place where we might find the
+ # original and so on. Autoconf is especially sensible to this).
+ . ./$as_me.lineno
+ # Exit status is that of the last command.
+ exit
+}
+
+
+case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in
+ *c*,-n*) ECHO_N= ECHO_C='
+' ECHO_T=' ' ;;
+ *c*,* ) ECHO_N=-n ECHO_C= ECHO_T= ;;
+ *) ECHO_N= ECHO_C='\c' ECHO_T= ;;
+esac
+
+if expr a : '\(a\)' >/dev/null 2>&1; then
+ as_expr=expr
+else
+ as_expr=false
+fi
+
+rm -f conf$$ conf$$.exe conf$$.file
+echo >conf$$.file
+if ln -s conf$$.file conf$$ 2>/dev/null; then
+ # We could just check for DJGPP; but this test a) works b) is more generic
+ # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04).
+ if test -f conf$$.exe; then
+ # Don't use ln at all; we don't have any links
+ as_ln_s='cp -p'
+ else
+ as_ln_s='ln -s'
+ fi
+elif ln conf$$.file conf$$ 2>/dev/null; then
+ as_ln_s=ln
+else
+ as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.file
+
+if mkdir -p . 2>/dev/null; then
+ as_mkdir_p=:
+else
+ test -d ./-p && rmdir ./-p
+ as_mkdir_p=false
+fi
+
+as_executable_p="test -f"
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.
+as_nl='
+'
+IFS=" $as_nl"
+
+# CDPATH.
+$as_unset CDPATH
+
+
+
+# Check that we are running under the correct shell.
+SHELL=${CONFIG_SHELL-/bin/sh}
+
+case X$ECHO in
+X*--fallback-echo)
+ # Remove one level of quotation (which was required for Make).
+ ECHO=`echo "$ECHO" | sed 's,\\\\\$\\$0,'$0','`
+ ;;
+esac
+
+echo=${ECHO-echo}
+if test "X$1" = X--no-reexec; then
+ # Discard the --no-reexec flag, and continue.
+ shift
+elif test "X$1" = X--fallback-echo; then
+ # Avoid inline document here, it may be left over
+ :
+elif test "X`($echo '\t') 2>/dev/null`" = 'X\t' ; then
+ # Yippee, $echo works!
+ :
+else
+ # Restart under the correct shell.
+ exec $SHELL "$0" --no-reexec ${1+"$@"}
+fi
+
+if test "X$1" = X--fallback-echo; then
+ # used as fallback echo
+ shift
+ cat <<EOF
+$*
+EOF
+ exit 0
+fi
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+if test -z "$ECHO"; then
+if test "X${echo_test_string+set}" != Xset; then
+# find a string as large as possible, as long as the shell can cope with it
+ for cmd in 'sed 50q "$0"' 'sed 20q "$0"' 'sed 10q "$0"' 'sed 2q "$0"' 'echo test'; do
+ # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ...
+ if (echo_test_string=`eval $cmd`) 2>/dev/null &&
+ echo_test_string=`eval $cmd` &&
+ (test "X$echo_test_string" = "X$echo_test_string") 2>/dev/null
+ then
+ break
+ fi
+ done
+fi
+
+if test "X`($echo '\t') 2>/dev/null`" = 'X\t' &&
+ echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ :
+else
+ # The Solaris, AIX, and Digital Unix default echo programs unquote
+ # backslashes. This makes it impossible to quote backslashes using
+ # echo "$something" | sed 's/\\/\\\\/g'
+ #
+ # So, first we look for a working echo in the user's PATH.
+
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+ for dir in $PATH /usr/ucb; do
+ IFS="$lt_save_ifs"
+ if (test -f $dir/echo || test -f $dir/echo$ac_exeext) &&
+ test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' &&
+ echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ echo="$dir/echo"
+ break
+ fi
+ done
+ IFS="$lt_save_ifs"
+
+ if test "X$echo" = Xecho; then
+ # We didn't find a better echo, so look for alternatives.
+ if test "X`(print -r '\t') 2>/dev/null`" = 'X\t' &&
+ echo_testing_string=`(print -r "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ # This shell has a builtin print -r that does the trick.
+ echo='print -r'
+ elif (test -f /bin/ksh || test -f /bin/ksh$ac_exeext) &&
+ test "X$CONFIG_SHELL" != X/bin/ksh; then
+ # If we have ksh, try running configure again with it.
+ ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh}
+ export ORIGINAL_CONFIG_SHELL
+ CONFIG_SHELL=/bin/ksh
+ export CONFIG_SHELL
+ exec $CONFIG_SHELL "$0" --no-reexec ${1+"$@"}
+ else
+ # Try using printf.
+ echo='printf %s\n'
+ if test "X`($echo '\t') 2>/dev/null`" = 'X\t' &&
+ echo_testing_string=`($echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ # Cool, printf works
+ :
+ elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "$0" --fallback-echo '\t') 2>/dev/null` &&
+ test "X$echo_testing_string" = 'X\t' &&
+ echo_testing_string=`($ORIGINAL_CONFIG_SHELL "$0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL
+ export CONFIG_SHELL
+ SHELL="$CONFIG_SHELL"
+ export SHELL
+ echo="$CONFIG_SHELL $0 --fallback-echo"
+ elif echo_testing_string=`($CONFIG_SHELL "$0" --fallback-echo '\t') 2>/dev/null` &&
+ test "X$echo_testing_string" = 'X\t' &&
+ echo_testing_string=`($CONFIG_SHELL "$0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
+ test "X$echo_testing_string" = "X$echo_test_string"; then
+ echo="$CONFIG_SHELL $0 --fallback-echo"
+ else
+ # maybe with a smaller string...
+ prev=:
+
+ for cmd in 'echo test' 'sed 2q "$0"' 'sed 10q "$0"' 'sed 20q "$0"' 'sed 50q "$0"'; do
+ if (test "X$echo_test_string" = "X`eval $cmd`") 2>/dev/null
+ then
+ break
+ fi
+ prev="$cmd"
+ done
+
+ if test "$prev" != 'sed 50q "$0"'; then
+ echo_test_string=`eval $prev`
+ export echo_test_string
+ exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "$0" ${1+"$@"}
+ else
+ # Oops. We lost completely, so just stick with echo.
+ echo=echo
+ fi
+ fi
+ fi
+ fi
+fi
+fi
+
+# Copy echo and quote the copy suitably for passing to libtool from
+# the Makefile, instead of quoting the original, which is used later.
+ECHO=$echo
+if test "X$ECHO" = "X$CONFIG_SHELL $0 --fallback-echo"; then
+ ECHO="$CONFIG_SHELL \\\$\$0 --fallback-echo"
+fi
+
+
+
+
+tagnames=${tagnames+${tagnames},}CXX
+
+tagnames=${tagnames+${tagnames},}F77
+
+# Name of the host.
+# hostname on some systems (SVR3.2, Linux) returns a bogus exit status,
+# so uname gets run too.
+ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
+
+exec 6>&1
+
+#
+# Initializations.
+#
+ac_default_prefix=/usr/local
+ac_config_libobj_dir=.
+cross_compiling=no
+subdirs=
+MFLAGS=
+MAKEFLAGS=
+SHELL=${CONFIG_SHELL-/bin/sh}
+
+# Maximum number of lines to put in a shell here document.
+# This variable seems obsolete. It should probably be removed, and
+# only ac_max_sed_lines should be used.
+: ${ac_max_here_lines=38}
+
+# Identity of this package.
+PACKAGE_NAME='jasper'
+PACKAGE_TARNAME='jasper'
+PACKAGE_VERSION='1.900.1'
+PACKAGE_STRING='jasper 1.900.1'
+PACKAGE_BUGREPORT=''
+
+ac_unique_file="README"
+# Factoring default headers for most tests.
+ac_includes_default="\
+#include <stdio.h>
+#if HAVE_SYS_TYPES_H
+# include <sys/types.h>
+#endif
+#if HAVE_SYS_STAT_H
+# include <sys/stat.h>
+#endif
+#if STDC_HEADERS
+# include <stdlib.h>
+# include <stddef.h>
+#else
+# if HAVE_STDLIB_H
+# include <stdlib.h>
+# endif
+#endif
+#if HAVE_STRING_H
+# if !STDC_HEADERS && HAVE_MEMORY_H
+# include <memory.h>
+# endif
+# include <string.h>
+#endif
+#if HAVE_STRINGS_H
+# include <strings.h>
+#endif
+#if HAVE_INTTYPES_H
+# include <inttypes.h>
+#else
+# if HAVE_STDINT_H
+# include <stdint.h>
+# endif
+#endif
+#if HAVE_UNISTD_H
+# include <unistd.h>
+#endif"
+
+ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS build build_cpu build_vendor build_os host host_cpu host_vendor host_os target target_cpu target_vendor target_os INSTALL_PROGRAM INSTALL_SCRIPT INS [...]
+ac_subst_files=''
+
+# Initialize some variables set by options.
+ac_init_help=
+ac_init_version=false
+# The variables have the same names as the options, with
+# dashes changed to underlines.
+cache_file=/dev/null
+exec_prefix=NONE
+no_create=
+no_recursion=
+prefix=NONE
+program_prefix=NONE
+program_suffix=NONE
+program_transform_name=s,x,x,
+silent=
+site=
+srcdir=
+verbose=
+x_includes=NONE
+x_libraries=NONE
+
+# Installation directory options.
+# These are left unexpanded so users can "make install exec_prefix=/foo"
+# and all the variables that are supposed to be based on exec_prefix
+# by default will actually change.
+# Use braces instead of parens because sh, perl, etc. also accept them.
+bindir='${exec_prefix}/bin'
+sbindir='${exec_prefix}/sbin'
+libexecdir='${exec_prefix}/libexec'
+datadir='${prefix}/share'
+sysconfdir='${prefix}/etc'
+sharedstatedir='${prefix}/com'
+localstatedir='${prefix}/var'
+libdir='${exec_prefix}/lib'
+includedir='${prefix}/include'
+oldincludedir='/usr/include'
+infodir='${prefix}/info'
+mandir='${prefix}/man'
+
+ac_prev=
+for ac_option
+do
+ # If the previous option needs an argument, assign it.
+ if test -n "$ac_prev"; then
+ eval "$ac_prev=\$ac_option"
+ ac_prev=
+ continue
+ fi
+
+ ac_optarg=`expr "x$ac_option" : 'x[^=]*=\(.*\)'`
+
+ # Accept the important Cygnus configure options, so we can diagnose typos.
+
+ case $ac_option in
+
+ -bindir | --bindir | --bindi | --bind | --bin | --bi)
+ ac_prev=bindir ;;
+ -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
+ bindir=$ac_optarg ;;
+
+ -build | --build | --buil | --bui | --bu)
+ ac_prev=build_alias ;;
+ -build=* | --build=* | --buil=* | --bui=* | --bu=*)
+ build_alias=$ac_optarg ;;
+
+ -cache-file | --cache-file | --cache-fil | --cache-fi \
+ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
+ ac_prev=cache_file ;;
+ -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
+ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
+ cache_file=$ac_optarg ;;
+
+ --config-cache | -C)
+ cache_file=config.cache ;;
+
+ -datadir | --datadir | --datadi | --datad | --data | --dat | --da)
+ ac_prev=datadir ;;
+ -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
+ | --da=*)
+ datadir=$ac_optarg ;;
+
+ -disable-* | --disable-*)
+ ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
+ # Reject names that are not valid shell variable names.
+ expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null &&
+ { echo "$as_me: error: invalid feature name: $ac_feature" >&2
+ { (exit 1); exit 1; }; }
+ ac_feature=`echo $ac_feature | sed 's/-/_/g'`
+ eval "enable_$ac_feature=no" ;;
+
+ -enable-* | --enable-*)
+ ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
+ # Reject names that are not valid shell variable names.
+ expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null &&
+ { echo "$as_me: error: invalid feature name: $ac_feature" >&2
+ { (exit 1); exit 1; }; }
+ ac_feature=`echo $ac_feature | sed 's/-/_/g'`
+ case $ac_option in
+ *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;;
+ *) ac_optarg=yes ;;
+ esac
+ eval "enable_$ac_feature='$ac_optarg'" ;;
+
+ -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
+ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
+ | --exec | --exe | --ex)
+ ac_prev=exec_prefix ;;
+ -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
+ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
+ | --exec=* | --exe=* | --ex=*)
+ exec_prefix=$ac_optarg ;;
+
+ -gas | --gas | --ga | --g)
+ # Obsolete; use --with-gas.
+ with_gas=yes ;;
+
+ -help | --help | --hel | --he | -h)
+ ac_init_help=long ;;
+ -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
+ ac_init_help=recursive ;;
+ -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
+ ac_init_help=short ;;
+
+ -host | --host | --hos | --ho)
+ ac_prev=host_alias ;;
+ -host=* | --host=* | --hos=* | --ho=*)
+ host_alias=$ac_optarg ;;
+
+ -includedir | --includedir | --includedi | --included | --include \
+ | --includ | --inclu | --incl | --inc)
+ ac_prev=includedir ;;
+ -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
+ | --includ=* | --inclu=* | --incl=* | --inc=*)
+ includedir=$ac_optarg ;;
+
+ -infodir | --infodir | --infodi | --infod | --info | --inf)
+ ac_prev=infodir ;;
+ -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
+ infodir=$ac_optarg ;;
+
+ -libdir | --libdir | --libdi | --libd)
+ ac_prev=libdir ;;
+ -libdir=* | --libdir=* | --libdi=* | --libd=*)
+ libdir=$ac_optarg ;;
+
+ -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
+ | --libexe | --libex | --libe)
+ ac_prev=libexecdir ;;
+ -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
+ | --libexe=* | --libex=* | --libe=*)
+ libexecdir=$ac_optarg ;;
+
+ -localstatedir | --localstatedir | --localstatedi | --localstated \
+ | --localstate | --localstat | --localsta | --localst \
+ | --locals | --local | --loca | --loc | --lo)
+ ac_prev=localstatedir ;;
+ -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
+ | --localstate=* | --localstat=* | --localsta=* | --localst=* \
+ | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
+ localstatedir=$ac_optarg ;;
+
+ -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
+ ac_prev=mandir ;;
+ -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
+ mandir=$ac_optarg ;;
+
+ -nfp | --nfp | --nf)
+ # Obsolete; use --without-fp.
+ with_fp=no ;;
+
+ -no-create | --no-create | --no-creat | --no-crea | --no-cre \
+ | --no-cr | --no-c | -n)
+ no_create=yes ;;
+
+ -no-recursion | --no-recursion | --no-recursio | --no-recursi \
+ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
+ no_recursion=yes ;;
+
+ -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
+ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
+ | --oldin | --oldi | --old | --ol | --o)
+ ac_prev=oldincludedir ;;
+ -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
+ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
+ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
+ oldincludedir=$ac_optarg ;;
+
+ -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+ ac_prev=prefix ;;
+ -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
+ prefix=$ac_optarg ;;
+
+ -program-prefix | --program-prefix | --program-prefi | --program-pref \
+ | --program-pre | --program-pr | --program-p)
+ ac_prev=program_prefix ;;
+ -program-prefix=* | --program-prefix=* | --program-prefi=* \
+ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
+ program_prefix=$ac_optarg ;;
+
+ -program-suffix | --program-suffix | --program-suffi | --program-suff \
+ | --program-suf | --program-su | --program-s)
+ ac_prev=program_suffix ;;
+ -program-suffix=* | --program-suffix=* | --program-suffi=* \
+ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
+ program_suffix=$ac_optarg ;;
+
+ -program-transform-name | --program-transform-name \
+ | --program-transform-nam | --program-transform-na \
+ | --program-transform-n | --program-transform- \
+ | --program-transform | --program-transfor \
+ | --program-transfo | --program-transf \
+ | --program-trans | --program-tran \
+ | --progr-tra | --program-tr | --program-t)
+ ac_prev=program_transform_name ;;
+ -program-transform-name=* | --program-transform-name=* \
+ | --program-transform-nam=* | --program-transform-na=* \
+ | --program-transform-n=* | --program-transform-=* \
+ | --program-transform=* | --program-transfor=* \
+ | --program-transfo=* | --program-transf=* \
+ | --program-trans=* | --program-tran=* \
+ | --progr-tra=* | --program-tr=* | --program-t=*)
+ program_transform_name=$ac_optarg ;;
+
+ -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+ | -silent | --silent | --silen | --sile | --sil)
+ silent=yes ;;
+
+ -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
+ ac_prev=sbindir ;;
+ -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
+ | --sbi=* | --sb=*)
+ sbindir=$ac_optarg ;;
+
+ -sharedstatedir | --sharedstatedir | --sharedstatedi \
+ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
+ | --sharedst | --shareds | --shared | --share | --shar \
+ | --sha | --sh)
+ ac_prev=sharedstatedir ;;
+ -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
+ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
+ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
+ | --sha=* | --sh=*)
+ sharedstatedir=$ac_optarg ;;
+
+ -site | --site | --sit)
+ ac_prev=site ;;
+ -site=* | --site=* | --sit=*)
+ site=$ac_optarg ;;
+
+ -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
+ ac_prev=srcdir ;;
+ -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
+ srcdir=$ac_optarg ;;
+
+ -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
+ | --syscon | --sysco | --sysc | --sys | --sy)
+ ac_prev=sysconfdir ;;
+ -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
+ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
+ sysconfdir=$ac_optarg ;;
+
+ -target | --target | --targe | --targ | --tar | --ta | --t)
+ ac_prev=target_alias ;;
+ -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
+ target_alias=$ac_optarg ;;
+
+ -v | -verbose | --verbose | --verbos | --verbo | --verb)
+ verbose=yes ;;
+
+ -version | --version | --versio | --versi | --vers | -V)
+ ac_init_version=: ;;
+
+ -with-* | --with-*)
+ ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
+ # Reject names that are not valid shell variable names.
+ expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null &&
+ { echo "$as_me: error: invalid package name: $ac_package" >&2
+ { (exit 1); exit 1; }; }
+ ac_package=`echo $ac_package| sed 's/-/_/g'`
+ case $ac_option in
+ *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;;
+ *) ac_optarg=yes ;;
+ esac
+ eval "with_$ac_package='$ac_optarg'" ;;
+
+ -without-* | --without-*)
+ ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'`
+ # Reject names that are not valid shell variable names.
+ expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null &&
+ { echo "$as_me: error: invalid package name: $ac_package" >&2
+ { (exit 1); exit 1; }; }
+ ac_package=`echo $ac_package | sed 's/-/_/g'`
+ eval "with_$ac_package=no" ;;
+
+ --x)
+ # Obsolete; use --with-x.
+ with_x=yes ;;
+
+ -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
+ | --x-incl | --x-inc | --x-in | --x-i)
+ ac_prev=x_includes ;;
+ -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
+ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
+ x_includes=$ac_optarg ;;
+
+ -x-libraries | --x-libraries | --x-librarie | --x-librari \
+ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
+ ac_prev=x_libraries ;;
+ -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
+ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
+ x_libraries=$ac_optarg ;;
+
+ -*) { echo "$as_me: error: unrecognized option: $ac_option
+Try \`$0 --help' for more information." >&2
+ { (exit 1); exit 1; }; }
+ ;;
+
+ *=*)
+ ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
+ # Reject names that are not valid shell variable names.
+ expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null &&
+ { echo "$as_me: error: invalid variable name: $ac_envvar" >&2
+ { (exit 1); exit 1; }; }
+ ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`
+ eval "$ac_envvar='$ac_optarg'"
+ export $ac_envvar ;;
+
+ *)
+ # FIXME: should be removed in autoconf 3.0.
+ echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+ expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+ echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+ : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}
+ ;;
+
+ esac
+done
+
+if test -n "$ac_prev"; then
+ ac_option=--`echo $ac_prev | sed 's/_/-/g'`
+ { echo "$as_me: error: missing argument to $ac_option" >&2
+ { (exit 1); exit 1; }; }
+fi
+
+# Be sure to have absolute paths.
+for ac_var in exec_prefix prefix
+do
+ eval ac_val=$`echo $ac_var`
+ case $ac_val in
+ [\\/$]* | ?:[\\/]* | NONE | '' ) ;;
+ *) { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
+ { (exit 1); exit 1; }; };;
+ esac
+done
+
+# Be sure to have absolute paths.
+for ac_var in bindir sbindir libexecdir datadir sysconfdir sharedstatedir \
+ localstatedir libdir includedir oldincludedir infodir mandir
+do
+ eval ac_val=$`echo $ac_var`
+ case $ac_val in
+ [\\/$]* | ?:[\\/]* ) ;;
+ *) { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
+ { (exit 1); exit 1; }; };;
+ esac
+done
+
+# There might be people who depend on the old broken behavior: `$host'
+# used to hold the argument of --host etc.
+# FIXME: To remove some day.
+build=$build_alias
+host=$host_alias
+target=$target_alias
+
+# FIXME: To remove some day.
+if test "x$host_alias" != x; then
+ if test "x$build_alias" = x; then
+ cross_compiling=maybe
+ echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host.
+ If a cross compiler is detected then cross compile mode will be used." >&2
+ elif test "x$build_alias" != "x$host_alias"; then
+ cross_compiling=yes
+ fi
+fi
+
+ac_tool_prefix=
+test -n "$host_alias" && ac_tool_prefix=$host_alias-
+
+test "$silent" = yes && exec 6>/dev/null
+
+
+# Find the source files, if location was not specified.
+if test -z "$srcdir"; then
+ ac_srcdir_defaulted=yes
+ # Try the directory containing this script, then its parent.
+ ac_confdir=`(dirname "$0") 2>/dev/null ||
+$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$0" : 'X\(//\)[^/]' \| \
+ X"$0" : 'X\(//\)$' \| \
+ X"$0" : 'X\(/\)' \| \
+ . : '\(.\)' 2>/dev/null ||
+echo X"$0" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+ /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+ /^X\(\/\/\)$/{ s//\1/; q; }
+ /^X\(\/\).*/{ s//\1/; q; }
+ s/.*/./; q'`
+ srcdir=$ac_confdir
+ if test ! -r $srcdir/$ac_unique_file; then
+ srcdir=..
+ fi
+else
+ ac_srcdir_defaulted=no
+fi
+if test ! -r $srcdir/$ac_unique_file; then
+ if test "$ac_srcdir_defaulted" = yes; then
+ { echo "$as_me: error: cannot find sources ($ac_unique_file) in $ac_confdir or .." >&2
+ { (exit 1); exit 1; }; }
+ else
+ { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2
+ { (exit 1); exit 1; }; }
+ fi
+fi
+(cd $srcdir && test -r ./$ac_unique_file) 2>/dev/null ||
+ { echo "$as_me: error: sources are in $srcdir, but \`cd $srcdir' does not work" >&2
+ { (exit 1); exit 1; }; }
+srcdir=`echo "$srcdir" | sed 's%\([^\\/]\)[\\/]*$%\1%'`
+ac_env_build_alias_set=${build_alias+set}
+ac_env_build_alias_value=$build_alias
+ac_cv_env_build_alias_set=${build_alias+set}
+ac_cv_env_build_alias_value=$build_alias
+ac_env_host_alias_set=${host_alias+set}
+ac_env_host_alias_value=$host_alias
+ac_cv_env_host_alias_set=${host_alias+set}
+ac_cv_env_host_alias_value=$host_alias
+ac_env_target_alias_set=${target_alias+set}
+ac_env_target_alias_value=$target_alias
+ac_cv_env_target_alias_set=${target_alias+set}
+ac_cv_env_target_alias_value=$target_alias
+ac_env_CC_set=${CC+set}
+ac_env_CC_value=$CC
+ac_cv_env_CC_set=${CC+set}
+ac_cv_env_CC_value=$CC
+ac_env_CFLAGS_set=${CFLAGS+set}
+ac_env_CFLAGS_value=$CFLAGS
+ac_cv_env_CFLAGS_set=${CFLAGS+set}
+ac_cv_env_CFLAGS_value=$CFLAGS
+ac_env_LDFLAGS_set=${LDFLAGS+set}
+ac_env_LDFLAGS_value=$LDFLAGS
+ac_cv_env_LDFLAGS_set=${LDFLAGS+set}
+ac_cv_env_LDFLAGS_value=$LDFLAGS
+ac_env_CPPFLAGS_set=${CPPFLAGS+set}
+ac_env_CPPFLAGS_value=$CPPFLAGS
+ac_cv_env_CPPFLAGS_set=${CPPFLAGS+set}
+ac_cv_env_CPPFLAGS_value=$CPPFLAGS
+ac_env_CPP_set=${CPP+set}
+ac_env_CPP_value=$CPP
+ac_cv_env_CPP_set=${CPP+set}
+ac_cv_env_CPP_value=$CPP
+ac_env_CXX_set=${CXX+set}
+ac_env_CXX_value=$CXX
+ac_cv_env_CXX_set=${CXX+set}
+ac_cv_env_CXX_value=$CXX
+ac_env_CXXFLAGS_set=${CXXFLAGS+set}
+ac_env_CXXFLAGS_value=$CXXFLAGS
+ac_cv_env_CXXFLAGS_set=${CXXFLAGS+set}
+ac_cv_env_CXXFLAGS_value=$CXXFLAGS
+ac_env_CXXCPP_set=${CXXCPP+set}
+ac_env_CXXCPP_value=$CXXCPP
+ac_cv_env_CXXCPP_set=${CXXCPP+set}
+ac_cv_env_CXXCPP_value=$CXXCPP
+ac_env_F77_set=${F77+set}
+ac_env_F77_value=$F77
+ac_cv_env_F77_set=${F77+set}
+ac_cv_env_F77_value=$F77
+ac_env_FFLAGS_set=${FFLAGS+set}
+ac_env_FFLAGS_value=$FFLAGS
+ac_cv_env_FFLAGS_set=${FFLAGS+set}
+ac_cv_env_FFLAGS_value=$FFLAGS
+
+#
+# Report the --help message.
+#
+if test "$ac_init_help" = "long"; then
+ # Omit some internal or obsolete options to make the list less imposing.
+ # This message is too long to be a string in the A/UX 3.1 sh.
+ cat <<_ACEOF
+\`configure' configures jasper 1.900.1 to adapt to many kinds of systems.
+
+Usage: $0 [OPTION]... [VAR=VALUE]...
+
+To assign environment variables (e.g., CC, CFLAGS...), specify them as
+VAR=VALUE. See below for descriptions of some of the useful variables.
+
+Defaults for the options are specified in brackets.
+
+Configuration:
+ -h, --help display this help and exit
+ --help=short display options specific to this package
+ --help=recursive display the short help of all the included packages
+ -V, --version display version information and exit
+ -q, --quiet, --silent do not print \`checking...' messages
+ --cache-file=FILE cache test results in FILE [disabled]
+ -C, --config-cache alias for \`--cache-file=config.cache'
+ -n, --no-create do not create output files
+ --srcdir=DIR find the sources in DIR [configure dir or \`..']
+
+_ACEOF
+
+ cat <<_ACEOF
+Installation directories:
+ --prefix=PREFIX install architecture-independent files in PREFIX
+ [$ac_default_prefix]
+ --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX
+ [PREFIX]
+
+By default, \`make install' will install all the files in
+\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify
+an installation prefix other than \`$ac_default_prefix' using \`--prefix',
+for instance \`--prefix=\$HOME'.
+
+For better control, use the options below.
+
+Fine tuning of the installation directories:
+ --bindir=DIR user executables [EPREFIX/bin]
+ --sbindir=DIR system admin executables [EPREFIX/sbin]
+ --libexecdir=DIR program executables [EPREFIX/libexec]
+ --datadir=DIR read-only architecture-independent data [PREFIX/share]
+ --sysconfdir=DIR read-only single-machine data [PREFIX/etc]
+ --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com]
+ --localstatedir=DIR modifiable single-machine data [PREFIX/var]
+ --libdir=DIR object code libraries [EPREFIX/lib]
+ --includedir=DIR C header files [PREFIX/include]
+ --oldincludedir=DIR C header files for non-gcc [/usr/include]
+ --infodir=DIR info documentation [PREFIX/info]
+ --mandir=DIR man documentation [PREFIX/man]
+_ACEOF
+
+ cat <<\_ACEOF
+
+Program names:
+ --program-prefix=PREFIX prepend PREFIX to installed program names
+ --program-suffix=SUFFIX append SUFFIX to installed program names
+ --program-transform-name=PROGRAM run sed PROGRAM on installed program names
+
+X features:
+ --x-includes=DIR X include files are in DIR
+ --x-libraries=DIR X library files are in DIR
+
+System types:
+ --build=BUILD configure for building on BUILD [guessed]
+ --host=HOST cross-compile to build programs to run on HOST [BUILD]
+ --target=TARGET configure for building compilers for TARGET [HOST]
+_ACEOF
+fi
+
+if test -n "$ac_init_help"; then
+ case $ac_init_help in
+ short | recursive ) echo "Configuration of jasper 1.900.1:";;
+ esac
+ cat <<\_ACEOF
+
+Optional Features:
+ --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no)
+ --enable-FEATURE[=ARG] include FEATURE [ARG=yes]
+ --disable-dependency-tracking speeds up one-time build
+ --enable-dependency-tracking do not reject slow dependency extractors
+ --enable-shared[=PKGS]
+ build shared libraries [default=no]
+ --enable-static[=PKGS]
+ build static libraries [default=yes]
+ --enable-fast-install[=PKGS]
+ optimize for fast installation [default=yes]
+ --disable-libtool-lock avoid locking (might break parallel builds)
+ --disable-libjpeg Force the IJG JPEG library to be ignored
+ --disable-opengl Disable use of OpenGL.
+ --enable-dmalloc use special memory allocator for debugging
+ --enable-debug add extra code for debugging
+ --enable-special0 enable something
+
+Optional Packages:
+ --with-PACKAGE[=ARG] use PACKAGE [ARG=yes]
+ --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no)
+ --with-gnu-ld assume the C compiler uses GNU ld [default=no]
+ --with-pic try to use only PIC/non-PIC objects [default=use
+ both]
+ --with-tags[=TAGS]
+ include additional configurations [automatic]
+ --with-x use the X Window System
+ --with-glut-include-dir=DIR Set GLUT include directory.
+ --with-glut-lib-dir=DIR Set GLUT library directory.
+
+Some influential environment variables:
+ CC C compiler command
+ CFLAGS C compiler flags
+ LDFLAGS linker flags, e.g. -L<lib dir> if you have libraries in a
+ nonstandard directory <lib dir>
+ CPPFLAGS C/C++ preprocessor flags, e.g. -I<include dir> if you have
+ headers in a nonstandard directory <include dir>
+ CPP C preprocessor
+ CXX C++ compiler command
+ CXXFLAGS C++ compiler flags
+ CXXCPP C++ preprocessor
+ F77 Fortran 77 compiler command
+ FFLAGS Fortran 77 compiler flags
+
+Use these variables to override the choices made by `configure' or to help
+it to find libraries and programs with nonstandard names/locations.
+
+_ACEOF
+fi
+
+if test "$ac_init_help" = "recursive"; then
+ # If there are subdirs, report their specific --help.
+ ac_popdir=`pwd`
+ for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
+ test -d $ac_dir || continue
+ ac_builddir=.
+
+if test "$ac_dir" != .; then
+ ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+ # A "../" for each directory in $ac_dir_suffix.
+ ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'`
+else
+ ac_dir_suffix= ac_top_builddir=
+fi
+
+case $srcdir in
+ .) # No --srcdir option. We are building in place.
+ ac_srcdir=.
+ if test -z "$ac_top_builddir"; then
+ ac_top_srcdir=.
+ else
+ ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'`
+ fi ;;
+ [\\/]* | ?:[\\/]* ) # Absolute path.
+ ac_srcdir=$srcdir$ac_dir_suffix;
+ ac_top_srcdir=$srcdir ;;
+ *) # Relative path.
+ ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix
+ ac_top_srcdir=$ac_top_builddir$srcdir ;;
+esac
+
+# Do not use `cd foo && pwd` to compute absolute paths, because
+# the directories may not exist.
+case `pwd` in
+.) ac_abs_builddir="$ac_dir";;
+*)
+ case "$ac_dir" in
+ .) ac_abs_builddir=`pwd`;;
+ [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";;
+ *) ac_abs_builddir=`pwd`/"$ac_dir";;
+ esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_top_builddir=${ac_top_builddir}.;;
+*)
+ case ${ac_top_builddir}. in
+ .) ac_abs_top_builddir=$ac_abs_builddir;;
+ [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;;
+ *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;;
+ esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_srcdir=$ac_srcdir;;
+*)
+ case $ac_srcdir in
+ .) ac_abs_srcdir=$ac_abs_builddir;;
+ [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;;
+ *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;;
+ esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_top_srcdir=$ac_top_srcdir;;
+*)
+ case $ac_top_srcdir in
+ .) ac_abs_top_srcdir=$ac_abs_builddir;;
+ [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;;
+ *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;;
+ esac;;
+esac
+
+ cd $ac_dir
+ # Check for guested configure; otherwise get Cygnus style configure.
+ if test -f $ac_srcdir/configure.gnu; then
+ echo
+ $SHELL $ac_srcdir/configure.gnu --help=recursive
+ elif test -f $ac_srcdir/configure; then
+ echo
+ $SHELL $ac_srcdir/configure --help=recursive
+ elif test -f $ac_srcdir/configure.ac ||
+ test -f $ac_srcdir/configure.in; then
+ echo
+ $ac_configure --help
+ else
+ echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
+ fi
+ cd $ac_popdir
+ done
+fi
+
+test -n "$ac_init_help" && exit 0
+if $ac_init_version; then
+ cat <<\_ACEOF
+jasper configure 1.900.1
+generated by GNU Autoconf 2.59
+
+Copyright (C) 2003 Free Software Foundation, Inc.
+This configure script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it.
+_ACEOF
+ exit 0
+fi
+exec 5>config.log
+cat >&5 <<_ACEOF
+This file contains any messages produced by compilers while
+running configure, to aid debugging if configure makes a mistake.
+
+It was created by jasper $as_me 1.900.1, which was
+generated by GNU Autoconf 2.59. Invocation command line was
+
+ $ $0 $@
+
+_ACEOF
+{
+cat <<_ASUNAME
+## --------- ##
+## Platform. ##
+## --------- ##
+
+hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
+/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown`
+
+/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown`
+/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
+hostinfo = `(hostinfo) 2>/dev/null || echo unknown`
+/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown`
+/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown`
+/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown`
+
+_ASUNAME
+
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ echo "PATH: $as_dir"
+done
+
+} >&5
+
+cat >&5 <<_ACEOF
+
+
+## ----------- ##
+## Core tests. ##
+## ----------- ##
+
+_ACEOF
+
+
+# Keep a trace of the command line.
+# Strip out --no-create and --no-recursion so they do not pile up.
+# Strip out --silent because we don't want to record it for future runs.
+# Also quote any args containing shell meta-characters.
+# Make two passes to allow for proper duplicate-argument suppression.
+ac_configure_args=
+ac_configure_args0=
+ac_configure_args1=
+ac_sep=
+ac_must_keep_next=false
+for ac_pass in 1 2
+do
+ for ac_arg
+ do
+ case $ac_arg in
+ -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
+ -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+ | -silent | --silent | --silen | --sile | --sil)
+ continue ;;
+ *" "*|*" "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*)
+ ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+ esac
+ case $ac_pass in
+ 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;;
+ 2)
+ ac_configure_args1="$ac_configure_args1 '$ac_arg'"
+ if test $ac_must_keep_next = true; then
+ ac_must_keep_next=false # Got value, back to normal.
+ else
+ case $ac_arg in
+ *=* | --config-cache | -C | -disable-* | --disable-* \
+ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
+ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
+ | -with-* | --with-* | -without-* | --without-* | --x)
+ case "$ac_configure_args0 " in
+ "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
+ esac
+ ;;
+ -* ) ac_must_keep_next=true ;;
+ esac
+ fi
+ ac_configure_args="$ac_configure_args$ac_sep'$ac_arg'"
+ # Get rid of the leading space.
+ ac_sep=" "
+ ;;
+ esac
+ done
+done
+$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; }
+$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; }
+
+# When interrupted or exit'd, cleanup temporary files, and complete
+# config.log. We remove comments because anyway the quotes in there
+# would cause problems or look ugly.
+# WARNING: Be sure not to use single quotes in there, as some shells,
+# such as our DU 5.0 friend, will then `close' the trap.
+trap 'exit_status=$?
+ # Save into config.log some information that might help in debugging.
+ {
+ echo
+
+ cat <<\_ASBOX
+## ---------------- ##
+## Cache variables. ##
+## ---------------- ##
+_ASBOX
+ echo
+ # The following way of writing the cache mishandles newlines in values,
+{
+ (set) 2>&1 |
+ case `(ac_space='"'"' '"'"'; set | grep ac_space) 2>&1` in
+ *ac_space=\ *)
+ sed -n \
+ "s/'"'"'/'"'"'\\\\'"'"''"'"'/g;
+ s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='"'"'\\2'"'"'/p"
+ ;;
+ *)
+ sed -n \
+ "s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p"
+ ;;
+ esac;
+}
+ echo
+
+ cat <<\_ASBOX
+## ----------------- ##
+## Output variables. ##
+## ----------------- ##
+_ASBOX
+ echo
+ for ac_var in $ac_subst_vars
+ do
+ eval ac_val=$`echo $ac_var`
+ echo "$ac_var='"'"'$ac_val'"'"'"
+ done | sort
+ echo
+
+ if test -n "$ac_subst_files"; then
+ cat <<\_ASBOX
+## ------------- ##
+## Output files. ##
+## ------------- ##
+_ASBOX
+ echo
+ for ac_var in $ac_subst_files
+ do
+ eval ac_val=$`echo $ac_var`
+ echo "$ac_var='"'"'$ac_val'"'"'"
+ done | sort
+ echo
+ fi
+
+ if test -s confdefs.h; then
+ cat <<\_ASBOX
+## ----------- ##
+## confdefs.h. ##
+## ----------- ##
+_ASBOX
+ echo
+ sed "/^$/d" confdefs.h | sort
+ echo
+ fi
+ test "$ac_signal" != 0 &&
+ echo "$as_me: caught signal $ac_signal"
+ echo "$as_me: exit $exit_status"
+ } >&5
+ rm -f core *.core &&
+ rm -rf conftest* confdefs* conf$$* $ac_clean_files &&
+ exit $exit_status
+ ' 0
+for ac_signal in 1 2 13 15; do
+ trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal
+done
+ac_signal=0
+
+# confdefs.h avoids OS command line length limits that DEFS can exceed.
+rm -rf conftest* confdefs.h
+# AIX cpp loses on an empty file, so make sure it contains at least a newline.
+echo >confdefs.h
+
+# Predefined preprocessor variables.
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_NAME "$PACKAGE_NAME"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_VERSION "$PACKAGE_VERSION"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_STRING "$PACKAGE_STRING"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
+_ACEOF
+
+
+# Let the site file select an alternate cache file if it wants to.
+# Prefer explicitly selected file to automatically selected ones.
+if test -z "$CONFIG_SITE"; then
+ if test "x$prefix" != xNONE; then
+ CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site"
+ else
+ CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site"
+ fi
+fi
+for ac_site_file in $CONFIG_SITE; do
+ if test -r "$ac_site_file"; then
+ { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5
+echo "$as_me: loading site script $ac_site_file" >&6;}
+ sed 's/^/| /' "$ac_site_file" >&5
+ . "$ac_site_file"
+ fi
+done
+
+if test -r "$cache_file"; then
+ # Some versions of bash will fail to source /dev/null (special
+ # files actually), so we avoid doing that.
+ if test -f "$cache_file"; then
+ { echo "$as_me:$LINENO: loading cache $cache_file" >&5
+echo "$as_me: loading cache $cache_file" >&6;}
+ case $cache_file in
+ [\\/]* | ?:[\\/]* ) . $cache_file;;
+ *) . ./$cache_file;;
+ esac
+ fi
+else
+ { echo "$as_me:$LINENO: creating cache $cache_file" >&5
+echo "$as_me: creating cache $cache_file" >&6;}
+ >$cache_file
+fi
+
+# Check that the precious variables saved in the cache have kept the same
+# value.
+ac_cache_corrupted=false
+for ac_var in `(set) 2>&1 |
+ sed -n 's/^ac_env_\([a-zA-Z_0-9]*\)_set=.*/\1/p'`; do
+ eval ac_old_set=\$ac_cv_env_${ac_var}_set
+ eval ac_new_set=\$ac_env_${ac_var}_set
+ eval ac_old_val="\$ac_cv_env_${ac_var}_value"
+ eval ac_new_val="\$ac_env_${ac_var}_value"
+ case $ac_old_set,$ac_new_set in
+ set,)
+ { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
+echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
+ ac_cache_corrupted=: ;;
+ ,set)
+ { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5
+echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+ ac_cache_corrupted=: ;;
+ ,);;
+ *)
+ if test "x$ac_old_val" != "x$ac_new_val"; then
+ { echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5
+echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
+ { echo "$as_me:$LINENO: former value: $ac_old_val" >&5
+echo "$as_me: former value: $ac_old_val" >&2;}
+ { echo "$as_me:$LINENO: current value: $ac_new_val" >&5
+echo "$as_me: current value: $ac_new_val" >&2;}
+ ac_cache_corrupted=:
+ fi;;
+ esac
+ # Pass precious variables to config.status.
+ if test "$ac_new_set" = set; then
+ case $ac_new_val in
+ *" "*|*" "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*)
+ ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+ *) ac_arg=$ac_var=$ac_new_val ;;
+ esac
+ case " $ac_configure_args " in
+ *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy.
+ *) ac_configure_args="$ac_configure_args '$ac_arg'" ;;
+ esac
+ fi
+done
+if $ac_cache_corrupted; then
+ { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5
+echo "$as_me: error: changes in the environment can compromise the build" >&2;}
+ { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5
+echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ac_aux_dir=
+for ac_dir in acaux $srcdir/acaux; do
+ if test -f $ac_dir/install-sh; then
+ ac_aux_dir=$ac_dir
+ ac_install_sh="$ac_aux_dir/install-sh -c"
+ break
+ elif test -f $ac_dir/install.sh; then
+ ac_aux_dir=$ac_dir
+ ac_install_sh="$ac_aux_dir/install.sh -c"
+ break
+ elif test -f $ac_dir/shtool; then
+ ac_aux_dir=$ac_dir
+ ac_install_sh="$ac_aux_dir/shtool install -c"
+ break
+ fi
+done
+if test -z "$ac_aux_dir"; then
+ { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in acaux $srcdir/acaux" >&5
+echo "$as_me: error: cannot find install-sh or install.sh in acaux $srcdir/acaux" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+ac_config_guess="$SHELL $ac_aux_dir/config.guess"
+ac_config_sub="$SHELL $ac_aux_dir/config.sub"
+ac_configure="$SHELL $ac_aux_dir/configure" # This should be Cygnus configure.
+
+
+# Detect the canonical host and target build environment.
+# Note: This precedes automake initialization to avoid warnings.
+# Make sure we can run config.sub.
+$ac_config_sub sun4 >/dev/null 2>&1 ||
+ { { echo "$as_me:$LINENO: error: cannot run $ac_config_sub" >&5
+echo "$as_me: error: cannot run $ac_config_sub" >&2;}
+ { (exit 1); exit 1; }; }
+
+echo "$as_me:$LINENO: checking build system type" >&5
+echo $ECHO_N "checking build system type... $ECHO_C" >&6
+if test "${ac_cv_build+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_cv_build_alias=$build_alias
+test -z "$ac_cv_build_alias" &&
+ ac_cv_build_alias=`$ac_config_guess`
+test -z "$ac_cv_build_alias" &&
+ { { echo "$as_me:$LINENO: error: cannot guess build type; you must specify one" >&5
+echo "$as_me: error: cannot guess build type; you must specify one" >&2;}
+ { (exit 1); exit 1; }; }
+ac_cv_build=`$ac_config_sub $ac_cv_build_alias` ||
+ { { echo "$as_me:$LINENO: error: $ac_config_sub $ac_cv_build_alias failed" >&5
+echo "$as_me: error: $ac_config_sub $ac_cv_build_alias failed" >&2;}
+ { (exit 1); exit 1; }; }
+
+fi
+echo "$as_me:$LINENO: result: $ac_cv_build" >&5
+echo "${ECHO_T}$ac_cv_build" >&6
+build=$ac_cv_build
+build_cpu=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'`
+build_vendor=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'`
+build_os=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'`
+
+
+echo "$as_me:$LINENO: checking host system type" >&5
+echo $ECHO_N "checking host system type... $ECHO_C" >&6
+if test "${ac_cv_host+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_cv_host_alias=$host_alias
+test -z "$ac_cv_host_alias" &&
+ ac_cv_host_alias=$ac_cv_build_alias
+ac_cv_host=`$ac_config_sub $ac_cv_host_alias` ||
+ { { echo "$as_me:$LINENO: error: $ac_config_sub $ac_cv_host_alias failed" >&5
+echo "$as_me: error: $ac_config_sub $ac_cv_host_alias failed" >&2;}
+ { (exit 1); exit 1; }; }
+
+fi
+echo "$as_me:$LINENO: result: $ac_cv_host" >&5
+echo "${ECHO_T}$ac_cv_host" >&6
+host=$ac_cv_host
+host_cpu=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'`
+host_vendor=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'`
+host_os=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'`
+
+
+echo "$as_me:$LINENO: checking target system type" >&5
+echo $ECHO_N "checking target system type... $ECHO_C" >&6
+if test "${ac_cv_target+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_cv_target_alias=$target_alias
+test "x$ac_cv_target_alias" = "x" &&
+ ac_cv_target_alias=$ac_cv_host_alias
+ac_cv_target=`$ac_config_sub $ac_cv_target_alias` ||
+ { { echo "$as_me:$LINENO: error: $ac_config_sub $ac_cv_target_alias failed" >&5
+echo "$as_me: error: $ac_config_sub $ac_cv_target_alias failed" >&2;}
+ { (exit 1); exit 1; }; }
+
+fi
+echo "$as_me:$LINENO: result: $ac_cv_target" >&5
+echo "${ECHO_T}$ac_cv_target" >&6
+target=$ac_cv_target
+target_cpu=`echo $ac_cv_target | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'`
+target_vendor=`echo $ac_cv_target | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'`
+target_os=`echo $ac_cv_target | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'`
+
+
+# The aliases save the names the user supplied, while $host etc.
+# will get canonicalized.
+test -n "$target_alias" &&
+ test "$program_prefix$program_suffix$program_transform_name" = \
+ NONENONEs,x,x, &&
+ program_prefix=${target_alias}-
+
+# Initialize automake.
+am__api_version="1.9"
+# Find a good install program. We prefer a C program (faster),
+# so one script is as good as another. But avoid the broken or
+# incompatible versions:
+# SysV /etc/install, /usr/sbin/install
+# SunOS /usr/etc/install
+# IRIX /sbin/install
+# AIX /bin/install
+# AmigaOS /C/install, which installs bootblocks on floppy discs
+# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag
+# AFS /usr/afsws/bin/install, which mishandles nonexistent args
+# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff"
+# OS/2's system install, which has a completely different semantic
+# ./install, which can be erroneously created by make from ./install.sh.
+echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5
+echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6
+if test -z "$INSTALL"; then
+if test "${ac_cv_path_install+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ # Account for people who put trailing slashes in PATH elements.
+case $as_dir/ in
+ ./ | .// | /cC/* | \
+ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \
+ ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \
+ /usr/ucb/* ) ;;
+ *)
+ # OSF1 and SCO ODT 3.0 have their own names for install.
+ # Don't use installbsd from OSF since it installs stuff as root
+ # by default.
+ for ac_prog in ginstall scoinst install; do
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then
+ if test $ac_prog = install &&
+ grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
+ # AIX install. It has an incompatible calling convention.
+ :
+ elif test $ac_prog = install &&
+ grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
+ # program-specific install script used by HP pwplus--don't use.
+ :
+ else
+ ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c"
+ break 3
+ fi
+ fi
+ done
+ done
+ ;;
+esac
+done
+
+
+fi
+ if test "${ac_cv_path_install+set}" = set; then
+ INSTALL=$ac_cv_path_install
+ else
+ # As a last resort, use the slow shell script. We don't cache a
+ # path for INSTALL within a source directory, because that will
+ # break other packages using the cache if that directory is
+ # removed, or if the path is relative.
+ INSTALL=$ac_install_sh
+ fi
+fi
+echo "$as_me:$LINENO: result: $INSTALL" >&5
+echo "${ECHO_T}$INSTALL" >&6
+
+# Use test -z because SunOS4 sh mishandles braces in ${var-val}.
+# It thinks the first close brace ends the variable substitution.
+test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}'
+
+test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}'
+
+test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644'
+
+echo "$as_me:$LINENO: checking whether build environment is sane" >&5
+echo $ECHO_N "checking whether build environment is sane... $ECHO_C" >&6
+# Just in case
+sleep 1
+echo timestamp > conftest.file
+# Do `set' in a subshell so we don't clobber the current shell's
+# arguments. Must try -L first in case configure is actually a
+# symlink; some systems play weird games with the mod time of symlinks
+# (eg FreeBSD returns the mod time of the symlink's containing
+# directory).
+if (
+ set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null`
+ if test "$*" = "X"; then
+ # -L didn't work.
+ set X `ls -t $srcdir/configure conftest.file`
+ fi
+ rm -f conftest.file
+ if test "$*" != "X $srcdir/configure conftest.file" \
+ && test "$*" != "X conftest.file $srcdir/configure"; then
+
+ # If neither matched, then we have a broken ls. This can happen
+ # if, for instance, CONFIG_SHELL is bash and it inherits a
+ # broken ls alias from the environment. This has actually
+ # happened. Such a system could not be considered "sane".
+ { { echo "$as_me:$LINENO: error: ls -t appears to fail. Make sure there is not a broken
+alias in your environment" >&5
+echo "$as_me: error: ls -t appears to fail. Make sure there is not a broken
+alias in your environment" >&2;}
+ { (exit 1); exit 1; }; }
+ fi
+
+ test "$2" = conftest.file
+ )
+then
+ # Ok.
+ :
+else
+ { { echo "$as_me:$LINENO: error: newly created file is older than distributed files!
+Check your system clock" >&5
+echo "$as_me: error: newly created file is older than distributed files!
+Check your system clock" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
+test "$program_prefix" != NONE &&
+ program_transform_name="s,^,$program_prefix,;$program_transform_name"
+# Use a double $ so make ignores it.
+test "$program_suffix" != NONE &&
+ program_transform_name="s,\$,$program_suffix,;$program_transform_name"
+# Double any \ or $. echo might interpret backslashes.
+# By default was `s,x,x', remove it if useless.
+cat <<\_ACEOF >conftest.sed
+s/[\\$]/&&/g;s/;s,x,x,$//
+_ACEOF
+program_transform_name=`echo $program_transform_name | sed -f conftest.sed`
+rm conftest.sed
+
+# expand $ac_aux_dir to an absolute path
+am_aux_dir=`cd $ac_aux_dir && pwd`
+
+test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing"
+# Use eval to expand $SHELL
+if eval "$MISSING --run true"; then
+ am_missing_run="$MISSING --run "
+else
+ am_missing_run=
+ { echo "$as_me:$LINENO: WARNING: \`missing' script is too old or missing" >&5
+echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;}
+fi
+
+if mkdir -p --version . >/dev/null 2>&1 && test ! -d ./--version; then
+ # We used to keeping the `.' as first argument, in order to
+ # allow $(mkdir_p) to be used without argument. As in
+ # $(mkdir_p) $(somedir)
+ # where $(somedir) is conditionally defined. However this is wrong
+ # for two reasons:
+ # 1. if the package is installed by a user who cannot write `.'
+ # make install will fail,
+ # 2. the above comment should most certainly read
+ # $(mkdir_p) $(DESTDIR)$(somedir)
+ # so it does not work when $(somedir) is undefined and
+ # $(DESTDIR) is not.
+ # To support the latter case, we have to write
+ # test -z "$(somedir)" || $(mkdir_p) $(DESTDIR)$(somedir),
+ # so the `.' trick is pointless.
+ mkdir_p='mkdir -p --'
+else
+ # On NextStep and OpenStep, the `mkdir' command does not
+ # recognize any option. It will interpret all options as
+ # directories to create, and then abort because `.' already
+ # exists.
+ for d in ./-p ./--version;
+ do
+ test -d $d && rmdir $d
+ done
+ # $(mkinstalldirs) is defined by Automake if mkinstalldirs exists.
+ if test -f "$ac_aux_dir/mkinstalldirs"; then
+ mkdir_p='$(mkinstalldirs)'
+ else
+ mkdir_p='$(install_sh) -d'
+ fi
+fi
+
+for ac_prog in gawk mawk nawk awk
+do
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_AWK+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$AWK"; then
+ ac_cv_prog_AWK="$AWK" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_AWK="$ac_prog"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+AWK=$ac_cv_prog_AWK
+if test -n "$AWK"; then
+ echo "$as_me:$LINENO: result: $AWK" >&5
+echo "${ECHO_T}$AWK" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ test -n "$AWK" && break
+done
+
+echo "$as_me:$LINENO: checking whether ${MAKE-make} sets \$(MAKE)" >&5
+echo $ECHO_N "checking whether ${MAKE-make} sets \$(MAKE)... $ECHO_C" >&6
+set dummy ${MAKE-make}; ac_make=`echo "$2" | sed 'y,:./+-,___p_,'`
+if eval "test \"\${ac_cv_prog_make_${ac_make}_set+set}\" = set"; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.make <<\_ACEOF
+all:
+ @echo 'ac_maketemp="$(MAKE)"'
+_ACEOF
+# GNU make sometimes prints "make[1]: Entering...", which would confuse us.
+eval `${MAKE-make} -f conftest.make 2>/dev/null | grep temp=`
+if test -n "$ac_maketemp"; then
+ eval ac_cv_prog_make_${ac_make}_set=yes
+else
+ eval ac_cv_prog_make_${ac_make}_set=no
+fi
+rm -f conftest.make
+fi
+if eval "test \"`echo '$ac_cv_prog_make_'${ac_make}_set`\" = yes"; then
+ echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
+ SET_MAKE=
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+ SET_MAKE="MAKE=${MAKE-make}"
+fi
+
+rm -rf .tst 2>/dev/null
+mkdir .tst 2>/dev/null
+if test -d .tst; then
+ am__leading_dot=.
+else
+ am__leading_dot=_
+fi
+rmdir .tst 2>/dev/null
+
+# test to see if srcdir already configured
+if test "`cd $srcdir && pwd`" != "`pwd`" &&
+ test -f $srcdir/config.status; then
+ { { echo "$as_me:$LINENO: error: source directory already configured; run \"make distclean\" there first" >&5
+echo "$as_me: error: source directory already configured; run \"make distclean\" there first" >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+# test whether we have cygpath
+if test -z "$CYGPATH_W"; then
+ if (cygpath --version) >/dev/null 2>/dev/null; then
+ CYGPATH_W='cygpath -w'
+ else
+ CYGPATH_W=echo
+ fi
+fi
+
+
+# Define the identity of the package.
+ PACKAGE='jasper'
+ VERSION='1.900.1'
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE "$PACKAGE"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define VERSION "$VERSION"
+_ACEOF
+
+# Some tools Automake needs.
+
+ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"}
+
+
+AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"}
+
+
+AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"}
+
+
+AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"}
+
+
+MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"}
+
+install_sh=${install_sh-"$am_aux_dir/install-sh"}
+
+# Installed binaries are usually stripped using `strip' when the user
+# run `make install-strip'. However `strip' might not be the right
+# tool to use in cross-compilation environments, therefore Automake
+# will honor the `STRIP' environment variable to overrule this program.
+if test "$cross_compiling" != no; then
+ if test -n "$ac_tool_prefix"; then
+ # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args.
+set dummy ${ac_tool_prefix}strip; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_STRIP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$STRIP"; then
+ ac_cv_prog_STRIP="$STRIP" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_STRIP="${ac_tool_prefix}strip"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+STRIP=$ac_cv_prog_STRIP
+if test -n "$STRIP"; then
+ echo "$as_me:$LINENO: result: $STRIP" >&5
+echo "${ECHO_T}$STRIP" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+fi
+if test -z "$ac_cv_prog_STRIP"; then
+ ac_ct_STRIP=$STRIP
+ # Extract the first word of "strip", so it can be a program name with args.
+set dummy strip; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_STRIP"; then
+ ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_ac_ct_STRIP="strip"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+ test -z "$ac_cv_prog_ac_ct_STRIP" && ac_cv_prog_ac_ct_STRIP=":"
+fi
+fi
+ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP
+if test -n "$ac_ct_STRIP"; then
+ echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5
+echo "${ECHO_T}$ac_ct_STRIP" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ STRIP=$ac_ct_STRIP
+else
+ STRIP="$ac_cv_prog_STRIP"
+fi
+
+fi
+INSTALL_STRIP_PROGRAM="\${SHELL} \$(install_sh) -c -s"
+
+# We need awk for the "check" target. The system "awk" is bad on
+# some platforms.
+# Always define AMTAR for backward compatibility.
+
+AMTAR=${AMTAR-"${am_missing_run}tar"}
+
+am__tar='${AMTAR} chof - "$$tardir"'; am__untar='${AMTAR} xf -'
+
+
+
+
+
+
+# Initialize version information parameters.
+JAS_MAJOR_VERSION=1
+JAS_MINOR_VERSION=900
+JAS_MICRO_VERSION=1
+JAS_VERSION=1.900.1
+
+
+
+
+cat >>confdefs.h <<_ACEOF
+#define JAS_VERSION "$JAS_VERSION"
+_ACEOF
+
+JAS_RPM_RELEASE=1
+
+
+# Initialize version information for libtool.
+LT_RELEASE=1.900
+LT_CURRENT=1
+LT_REVISION=0
+LT_AGE=0
+
+
+
+
+
+# Indicate a configure-based build is being used.
+cat >>confdefs.h <<\_ACEOF
+#define JAS_CONFIGURE 1
+_ACEOF
+
+
+############################################################
+# Configuration header file.
+############################################################
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+############################################################
+# Checks for programs.
+############################################################
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+if test -n "$ac_tool_prefix"; then
+ # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}gcc; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_CC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$CC"; then
+ ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_CC="${ac_tool_prefix}gcc"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+ echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+fi
+if test -z "$ac_cv_prog_CC"; then
+ ac_ct_CC=$CC
+ # Extract the first word of "gcc", so it can be a program name with args.
+set dummy gcc; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_CC"; then
+ ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_ac_ct_CC="gcc"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+ echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
+echo "${ECHO_T}$ac_ct_CC" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ CC=$ac_ct_CC
+else
+ CC="$ac_cv_prog_CC"
+fi
+
+if test -z "$CC"; then
+ if test -n "$ac_tool_prefix"; then
+ # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}cc; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_CC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$CC"; then
+ ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_CC="${ac_tool_prefix}cc"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+ echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+fi
+if test -z "$ac_cv_prog_CC"; then
+ ac_ct_CC=$CC
+ # Extract the first word of "cc", so it can be a program name with args.
+set dummy cc; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_CC"; then
+ ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_ac_ct_CC="cc"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+ echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
+echo "${ECHO_T}$ac_ct_CC" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ CC=$ac_ct_CC
+else
+ CC="$ac_cv_prog_CC"
+fi
+
+fi
+if test -z "$CC"; then
+ # Extract the first word of "cc", so it can be a program name with args.
+set dummy cc; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_CC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$CC"; then
+ ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+ ac_prog_rejected=no
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
+ ac_prog_rejected=yes
+ continue
+ fi
+ ac_cv_prog_CC="cc"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+if test $ac_prog_rejected = yes; then
+ # We found a bogon in the path, so make sure we never use it.
+ set dummy $ac_cv_prog_CC
+ shift
+ if test $# != 0; then
+ # We chose a different compiler from the bogus one.
+ # However, it has the same basename, so the bogon will be chosen
+ # first if we set CC to just the basename; use the full file name.
+ shift
+ ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
+ fi
+fi
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+ echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+fi
+if test -z "$CC"; then
+ if test -n "$ac_tool_prefix"; then
+ for ac_prog in cl
+ do
+ # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_CC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$CC"; then
+ ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+ echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ test -n "$CC" && break
+ done
+fi
+if test -z "$CC"; then
+ ac_ct_CC=$CC
+ for ac_prog in cl
+do
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_CC"; then
+ ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_ac_ct_CC="$ac_prog"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+ echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
+echo "${ECHO_T}$ac_ct_CC" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ test -n "$ac_ct_CC" && break
+done
+
+ CC=$ac_ct_CC
+fi
+
+fi
+
+
+test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH
+See \`config.log' for more details." >&5
+echo "$as_me: error: no acceptable C compiler found in \$PATH
+See \`config.log' for more details." >&2;}
+ { (exit 1); exit 1; }; }
+
+# Provide some information about the compiler.
+echo "$as_me:$LINENO:" \
+ "checking for C compiler version" >&5
+ac_compiler=`set X $ac_compile; echo $2`
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5
+ (eval $ac_compiler --version </dev/null >&5) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v </dev/null >&5\"") >&5
+ (eval $ac_compiler -v </dev/null >&5) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V </dev/null >&5\"") >&5
+ (eval $ac_compiler -V </dev/null >&5) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files a.out a.exe b.out"
+# Try to create an executable without -o first, disregard a.out.
+# It will help us diagnose broken compilers, and finding out an intuition
+# of exeext.
+echo "$as_me:$LINENO: checking for C compiler default output file name" >&5
+echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6
+ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
+if { (eval echo "$as_me:$LINENO: \"$ac_link_default\"") >&5
+ (eval $ac_link_default) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ # Find the output, starting from the most likely. This scheme is
+# not robust to junk in `.', hence go to wildcards (a.*) only as a last
+# resort.
+
+# Be careful to initialize this variable, since it used to be cached.
+# Otherwise an old cache value of `no' led to `EXEEXT = no' in a Makefile.
+ac_cv_exeext=
+# b.out is created by i960 compilers.
+for ac_file in a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out
+do
+ test -f "$ac_file" || continue
+ case $ac_file in
+ *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj )
+ ;;
+ conftest.$ac_ext )
+ # This is the source file.
+ ;;
+ [ab].out )
+ # We found the default executable, but exeext='' is most
+ # certainly right.
+ break;;
+ *.* )
+ ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+ # FIXME: I believe we export ac_cv_exeext for Libtool,
+ # but it would be cool to find out if it's true. Does anybody
+ # maintain Libtool? --akim.
+ export ac_cv_exeext
+ break;;
+ * )
+ break;;
+ esac
+done
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { echo "$as_me:$LINENO: error: C compiler cannot create executables
+See \`config.log' for more details." >&5
+echo "$as_me: error: C compiler cannot create executables
+See \`config.log' for more details." >&2;}
+ { (exit 77); exit 77; }; }
+fi
+
+ac_exeext=$ac_cv_exeext
+echo "$as_me:$LINENO: result: $ac_file" >&5
+echo "${ECHO_T}$ac_file" >&6
+
+# Check the compiler produces executables we can run. If not, either
+# the compiler is broken, or we cross compile.
+echo "$as_me:$LINENO: checking whether the C compiler works" >&5
+echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6
+# FIXME: These cross compiler hacks should be removed for Autoconf 3.0
+# If not cross compiling, check that we can run a simple program.
+if test "$cross_compiling" != yes; then
+ if { ac_try='./$ac_file'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ cross_compiling=no
+ else
+ if test "$cross_compiling" = maybe; then
+ cross_compiling=yes
+ else
+ { { echo "$as_me:$LINENO: error: cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details." >&2;}
+ { (exit 1); exit 1; }; }
+ fi
+ fi
+fi
+echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
+
+rm -f a.out a.exe conftest$ac_cv_exeext b.out
+ac_clean_files=$ac_clean_files_save
+# Check the compiler produces executables we can run. If not, either
+# the compiler is broken, or we cross compile.
+echo "$as_me:$LINENO: checking whether we are cross compiling" >&5
+echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6
+echo "$as_me:$LINENO: result: $cross_compiling" >&5
+echo "${ECHO_T}$cross_compiling" >&6
+
+echo "$as_me:$LINENO: checking for suffix of executables" >&5
+echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ # If both `conftest.exe' and `conftest' are `present' (well, observable)
+# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will
+# work properly (i.e., refer to `conftest.exe'), while it won't with
+# `rm'.
+for ac_file in conftest.exe conftest conftest.*; do
+ test -f "$ac_file" || continue
+ case $ac_file in
+ *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj ) ;;
+ *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+ export ac_cv_exeext
+ break;;
+ * ) break;;
+ esac
+done
+else
+ { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+rm -f conftest$ac_cv_exeext
+echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5
+echo "${ECHO_T}$ac_cv_exeext" >&6
+
+rm -f conftest.$ac_ext
+EXEEXT=$ac_cv_exeext
+ac_exeext=$EXEEXT
+echo "$as_me:$LINENO: checking for suffix of object files" >&5
+echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6
+if test "${ac_cv_objext+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.o conftest.obj
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ for ac_file in `(ls conftest.o conftest.obj; ls conftest.*) 2>/dev/null`; do
+ case $ac_file in
+ *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg ) ;;
+ *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
+ break;;
+ esac
+done
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot compute suffix of object files: cannot compile
+See \`config.log' for more details." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+rm -f conftest.$ac_cv_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_objext" >&5
+echo "${ECHO_T}$ac_cv_objext" >&6
+OBJEXT=$ac_cv_objext
+ac_objext=$OBJEXT
+echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6
+if test "${ac_cv_c_compiler_gnu+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+#ifndef __GNUC__
+ choke me
+#endif
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_compiler_gnu=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_compiler_gnu=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_c_compiler_gnu=$ac_compiler_gnu
+
+fi
+echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6
+GCC=`test $ac_compiler_gnu = yes && echo yes`
+ac_test_CFLAGS=${CFLAGS+set}
+ac_save_CFLAGS=$CFLAGS
+CFLAGS="-g"
+echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5
+echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6
+if test "${ac_cv_prog_cc_g+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_prog_cc_g=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_prog_cc_g=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5
+echo "${ECHO_T}$ac_cv_prog_cc_g" >&6
+if test "$ac_test_CFLAGS" = set; then
+ CFLAGS=$ac_save_CFLAGS
+elif test $ac_cv_prog_cc_g = yes; then
+ if test "$GCC" = yes; then
+ CFLAGS="-g -O2"
+ else
+ CFLAGS="-g"
+ fi
+else
+ if test "$GCC" = yes; then
+ CFLAGS="-O2"
+ else
+ CFLAGS=
+ fi
+fi
+echo "$as_me:$LINENO: checking for $CC option to accept ANSI C" >&5
+echo $ECHO_N "checking for $CC option to accept ANSI C... $ECHO_C" >&6
+if test "${ac_cv_prog_cc_stdc+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_cv_prog_cc_stdc=no
+ac_save_CC=$CC
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <stdarg.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */
+struct buf { int x; };
+FILE * (*rcsopen) (struct buf *, struct stat *, int);
+static char *e (p, i)
+ char **p;
+ int i;
+{
+ return p[i];
+}
+static char *f (char * (*g) (char **, int), char **p, ...)
+{
+ char *s;
+ va_list v;
+ va_start (v,p);
+ s = g (p, va_arg (v,int));
+ va_end (v);
+ return s;
+}
+
+/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has
+ function prototypes and stuff, but not '\xHH' hex character constants.
+ These don't provoke an error unfortunately, instead are silently treated
+ as 'x'. The following induces an error, until -std1 is added to get
+ proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an
+ array size at least. It's necessary to write '\x00'==0 to get something
+ that's true only with -std1. */
+int osf4_cc_array ['\x00' == 0 ? 1 : -1];
+
+int test (int i, double x);
+struct s1 {int (*f) (int a);};
+struct s2 {int (*f) (double a);};
+int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
+int argc;
+char **argv;
+int
+main ()
+{
+return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1];
+ ;
+ return 0;
+}
+_ACEOF
+# Don't try gcc -ansi; that turns off useful extensions and
+# breaks some systems' header files.
+# AIX -qlanglvl=ansi
+# Ultrix and OSF/1 -std1
+# HP-UX 10.20 and later -Ae
+# HP-UX older versions -Aa -D_HPUX_SOURCE
+# SVR4 -Xc -D__EXTENSIONS__
+for ac_arg in "" -qlanglvl=ansi -std1 -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+do
+ CC="$ac_save_CC $ac_arg"
+ rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_prog_cc_stdc=$ac_arg
+break
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext
+done
+rm -f conftest.$ac_ext conftest.$ac_objext
+CC=$ac_save_CC
+
+fi
+
+case "x$ac_cv_prog_cc_stdc" in
+ x|xno)
+ echo "$as_me:$LINENO: result: none needed" >&5
+echo "${ECHO_T}none needed" >&6 ;;
+ *)
+ echo "$as_me:$LINENO: result: $ac_cv_prog_cc_stdc" >&5
+echo "${ECHO_T}$ac_cv_prog_cc_stdc" >&6
+ CC="$CC $ac_cv_prog_cc_stdc" ;;
+esac
+
+# Some people use a C++ compiler to compile C. Since we use `exit',
+# in C++ we need to declare it. In case someone uses the same compiler
+# for both compiling C and C++ we need to have the C++ compiler decide
+# the declaration of exit, since it's the most demanding environment.
+cat >conftest.$ac_ext <<_ACEOF
+#ifndef __cplusplus
+ choke me
+#endif
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ for ac_declaration in \
+ '' \
+ 'extern "C" void std::exit (int) throw (); using std::exit;' \
+ 'extern "C" void std::exit (int); using std::exit;' \
+ 'extern "C" void exit (int) throw ();' \
+ 'extern "C" void exit (int);' \
+ 'void exit (int);'
+do
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_declaration
+#include <stdlib.h>
+int
+main ()
+{
+exit (42);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ :
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+continue
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_declaration
+int
+main ()
+{
+exit (42);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ break
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+done
+rm -f conftest*
+if test -n "$ac_declaration"; then
+ echo '#ifdef __cplusplus' >>confdefs.h
+ echo $ac_declaration >>confdefs.h
+ echo '#endif' >>confdefs.h
+fi
+
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+DEPDIR="${am__leading_dot}deps"
+
+ ac_config_commands="$ac_config_commands depfiles"
+
+
+am_make=${MAKE-make}
+cat > confinc << 'END'
+am__doit:
+ @echo done
+.PHONY: am__doit
+END
+# If we don't find an include directive, just comment out the code.
+echo "$as_me:$LINENO: checking for style of include used by $am_make" >&5
+echo $ECHO_N "checking for style of include used by $am_make... $ECHO_C" >&6
+am__include="#"
+am__quote=
+_am_result=none
+# First try GNU make style include.
+echo "include confinc" > confmf
+# We grep out `Entering directory' and `Leaving directory'
+# messages which can occur if `w' ends up in MAKEFLAGS.
+# In particular we don't look at `^make:' because GNU make might
+# be invoked under some other name (usually "gmake"), in which
+# case it prints its new name instead of `make'.
+if test "`$am_make -s -f confmf 2> /dev/null | grep -v 'ing directory'`" = "done"; then
+ am__include=include
+ am__quote=
+ _am_result=GNU
+fi
+# Now try BSD make style include.
+if test "$am__include" = "#"; then
+ echo '.include "confinc"' > confmf
+ if test "`$am_make -s -f confmf 2> /dev/null`" = "done"; then
+ am__include=.include
+ am__quote="\""
+ _am_result=BSD
+ fi
+fi
+
+
+echo "$as_me:$LINENO: result: $_am_result" >&5
+echo "${ECHO_T}$_am_result" >&6
+rm -f confinc confmf
+
+# Check whether --enable-dependency-tracking or --disable-dependency-tracking was given.
+if test "${enable_dependency_tracking+set}" = set; then
+ enableval="$enable_dependency_tracking"
+
+fi;
+if test "x$enable_dependency_tracking" != xno; then
+ am_depcomp="$ac_aux_dir/depcomp"
+ AMDEPBACKSLASH='\'
+fi
+
+
+if test "x$enable_dependency_tracking" != xno; then
+ AMDEP_TRUE=
+ AMDEP_FALSE='#'
+else
+ AMDEP_TRUE='#'
+ AMDEP_FALSE=
+fi
+
+
+
+
+depcc="$CC" am_compiler_list=
+
+echo "$as_me:$LINENO: checking dependency style of $depcc" >&5
+echo $ECHO_N "checking dependency style of $depcc... $ECHO_C" >&6
+if test "${am_cv_CC_dependencies_compiler_type+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then
+ # We make a subdir and do the tests there. Otherwise we can end up
+ # making bogus files that we don't know about and never remove. For
+ # instance it was reported that on HP-UX the gcc test will end up
+ # making a dummy file named `D' -- because `-MD' means `put the output
+ # in D'.
+ mkdir conftest.dir
+ # Copy depcomp to subdir because otherwise we won't find it if we're
+ # using a relative directory.
+ cp "$am_depcomp" conftest.dir
+ cd conftest.dir
+ # We will build objects and dependencies in a subdirectory because
+ # it helps to detect inapplicable dependency modes. For instance
+ # both Tru64's cc and ICC support -MD to output dependencies as a
+ # side effect of compilation, but ICC will put the dependencies in
+ # the current directory while Tru64 will put them in the object
+ # directory.
+ mkdir sub
+
+ am_cv_CC_dependencies_compiler_type=none
+ if test "$am_compiler_list" = ""; then
+ am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp`
+ fi
+ for depmode in $am_compiler_list; do
+ # Setup a source with many dependencies, because some compilers
+ # like to wrap large dependency lists on column 80 (with \), and
+ # we should not choose a depcomp mode which is confused by this.
+ #
+ # We need to recreate these files for each test, as the compiler may
+ # overwrite some of them when testing with obscure command lines.
+ # This happens at least with the AIX C compiler.
+ : > sub/conftest.c
+ for i in 1 2 3 4 5 6; do
+ echo '#include "conftst'$i'.h"' >> sub/conftest.c
+ # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with
+ # Solaris 8's {/usr,}/bin/sh.
+ touch sub/conftst$i.h
+ done
+ echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf
+
+ case $depmode in
+ nosideeffect)
+ # after this tag, mechanisms are not by side-effect, so they'll
+ # only be used when explicitly requested
+ if test "x$enable_dependency_tracking" = xyes; then
+ continue
+ else
+ break
+ fi
+ ;;
+ none) break ;;
+ esac
+ # We check with `-c' and `-o' for the sake of the "dashmstdout"
+ # mode. It turns out that the SunPro C++ compiler does not properly
+ # handle `-M -o', and we need to detect this.
+ if depmode=$depmode \
+ source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \
+ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \
+ $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \
+ >/dev/null 2>conftest.err &&
+ grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 &&
+ grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 &&
+ ${MAKE-make} -s -f confmf > /dev/null 2>&1; then
+ # icc doesn't choke on unknown options, it will just issue warnings
+ # or remarks (even with -Werror). So we grep stderr for any message
+ # that says an option was ignored or not supported.
+ # When given -MP, icc 7.0 and 7.1 complain thusly:
+ # icc: Command line warning: ignoring option '-M'; no argument required
+ # The diagnosis changed in icc 8.0:
+ # icc: Command line remark: option '-MP' not supported
+ if (grep 'ignoring option' conftest.err ||
+ grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else
+ am_cv_CC_dependencies_compiler_type=$depmode
+ break
+ fi
+ fi
+ done
+
+ cd ..
+ rm -rf conftest.dir
+else
+ am_cv_CC_dependencies_compiler_type=none
+fi
+
+fi
+echo "$as_me:$LINENO: result: $am_cv_CC_dependencies_compiler_type" >&5
+echo "${ECHO_T}$am_cv_CC_dependencies_compiler_type" >&6
+CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type
+
+
+
+if
+ test "x$enable_dependency_tracking" != xno \
+ && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then
+ am__fastdepCC_TRUE=
+ am__fastdepCC_FALSE='#'
+else
+ am__fastdepCC_TRUE='#'
+ am__fastdepCC_FALSE=
+fi
+
+
+# Find a good install program. We prefer a C program (faster),
+# so one script is as good as another. But avoid the broken or
+# incompatible versions:
+# SysV /etc/install, /usr/sbin/install
+# SunOS /usr/etc/install
+# IRIX /sbin/install
+# AIX /bin/install
+# AmigaOS /C/install, which installs bootblocks on floppy discs
+# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag
+# AFS /usr/afsws/bin/install, which mishandles nonexistent args
+# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff"
+# OS/2's system install, which has a completely different semantic
+# ./install, which can be erroneously created by make from ./install.sh.
+echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5
+echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6
+if test -z "$INSTALL"; then
+if test "${ac_cv_path_install+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ # Account for people who put trailing slashes in PATH elements.
+case $as_dir/ in
+ ./ | .// | /cC/* | \
+ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \
+ ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \
+ /usr/ucb/* ) ;;
+ *)
+ # OSF1 and SCO ODT 3.0 have their own names for install.
+ # Don't use installbsd from OSF since it installs stuff as root
+ # by default.
+ for ac_prog in ginstall scoinst install; do
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then
+ if test $ac_prog = install &&
+ grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
+ # AIX install. It has an incompatible calling convention.
+ :
+ elif test $ac_prog = install &&
+ grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
+ # program-specific install script used by HP pwplus--don't use.
+ :
+ else
+ ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c"
+ break 3
+ fi
+ fi
+ done
+ done
+ ;;
+esac
+done
+
+
+fi
+ if test "${ac_cv_path_install+set}" = set; then
+ INSTALL=$ac_cv_path_install
+ else
+ # As a last resort, use the slow shell script. We don't cache a
+ # path for INSTALL within a source directory, because that will
+ # break other packages using the cache if that directory is
+ # removed, or if the path is relative.
+ INSTALL=$ac_install_sh
+ fi
+fi
+echo "$as_me:$LINENO: result: $INSTALL" >&5
+echo "${ECHO_T}$INSTALL" >&6
+
+# Use test -z because SunOS4 sh mishandles braces in ${var-val}.
+# It thinks the first close brace ends the variable substitution.
+test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}'
+
+test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}'
+
+test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644'
+
+if test -n "$ac_tool_prefix"; then
+ # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
+set dummy ${ac_tool_prefix}ranlib; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_RANLIB+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$RANLIB"; then
+ ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+RANLIB=$ac_cv_prog_RANLIB
+if test -n "$RANLIB"; then
+ echo "$as_me:$LINENO: result: $RANLIB" >&5
+echo "${ECHO_T}$RANLIB" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+fi
+if test -z "$ac_cv_prog_RANLIB"; then
+ ac_ct_RANLIB=$RANLIB
+ # Extract the first word of "ranlib", so it can be a program name with args.
+set dummy ranlib; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_RANLIB"; then
+ ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_ac_ct_RANLIB="ranlib"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+ test -z "$ac_cv_prog_ac_ct_RANLIB" && ac_cv_prog_ac_ct_RANLIB=":"
+fi
+fi
+ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
+if test -n "$ac_ct_RANLIB"; then
+ echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5
+echo "${ECHO_T}$ac_ct_RANLIB" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ RANLIB=$ac_ct_RANLIB
+else
+ RANLIB="$ac_cv_prog_RANLIB"
+fi
+
+# AC_PROG_AWK
+# AC_PROG_CPP
+# AC_PROG_LN_S
+
+# Check whether --enable-shared or --disable-shared was given.
+if test "${enable_shared+set}" = set; then
+ enableval="$enable_shared"
+ p=${PACKAGE-default}
+ case $enableval in
+ yes) enable_shared=yes ;;
+ no) enable_shared=no ;;
+ *)
+ enable_shared=no
+ # Look at the argument we got. We use all the common list separators.
+ lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+ for pkg in $enableval; do
+ IFS="$lt_save_ifs"
+ if test "X$pkg" = "X$p"; then
+ enable_shared=yes
+ fi
+ done
+ IFS="$lt_save_ifs"
+ ;;
+ esac
+else
+ enable_shared=no
+fi;
+
+
+# Check whether --enable-static or --disable-static was given.
+if test "${enable_static+set}" = set; then
+ enableval="$enable_static"
+ p=${PACKAGE-default}
+ case $enableval in
+ yes) enable_static=yes ;;
+ no) enable_static=no ;;
+ *)
+ enable_static=no
+ # Look at the argument we got. We use all the common list separators.
+ lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+ for pkg in $enableval; do
+ IFS="$lt_save_ifs"
+ if test "X$pkg" = "X$p"; then
+ enable_static=yes
+ fi
+ done
+ IFS="$lt_save_ifs"
+ ;;
+ esac
+else
+ enable_static=yes
+fi;
+
+# Check whether --enable-fast-install or --disable-fast-install was given.
+if test "${enable_fast_install+set}" = set; then
+ enableval="$enable_fast_install"
+ p=${PACKAGE-default}
+ case $enableval in
+ yes) enable_fast_install=yes ;;
+ no) enable_fast_install=no ;;
+ *)
+ enable_fast_install=no
+ # Look at the argument we got. We use all the common list separators.
+ lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+ for pkg in $enableval; do
+ IFS="$lt_save_ifs"
+ if test "X$pkg" = "X$p"; then
+ enable_fast_install=yes
+ fi
+ done
+ IFS="$lt_save_ifs"
+ ;;
+ esac
+else
+ enable_fast_install=yes
+fi;
+
+echo "$as_me:$LINENO: checking for a sed that does not truncate output" >&5
+echo $ECHO_N "checking for a sed that does not truncate output... $ECHO_C" >&6
+if test "${lt_cv_path_SED+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ # Loop through the user's path and test for sed and gsed.
+# Then use that list of sed's as ones to test for truncation.
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for lt_ac_prog in sed gsed; do
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
+ lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
+ fi
+ done
+ done
+done
+IFS=$as_save_IFS
+lt_ac_max=0
+lt_ac_count=0
+# Add /usr/xpg4/bin/sed as it is typically found on Solaris
+# along with /bin/sed that truncates output.
+for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
+ test ! -f $lt_ac_sed && continue
+ cat /dev/null > conftest.in
+ lt_ac_count=0
+ echo $ECHO_N "0123456789$ECHO_C" >conftest.in
+ # Check for GNU sed and select it if it is found.
+ if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
+ lt_cv_path_SED=$lt_ac_sed
+ break
+ fi
+ while true; do
+ cat conftest.in conftest.in >conftest.tmp
+ mv conftest.tmp conftest.in
+ cp conftest.in conftest.nl
+ echo >>conftest.nl
+ $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
+ cmp -s conftest.out conftest.nl || break
+ # 10000 chars as input seems more than enough
+ test $lt_ac_count -gt 10 && break
+ lt_ac_count=`expr $lt_ac_count + 1`
+ if test $lt_ac_count -gt $lt_ac_max; then
+ lt_ac_max=$lt_ac_count
+ lt_cv_path_SED=$lt_ac_sed
+ fi
+ done
+done
+
+fi
+
+SED=$lt_cv_path_SED
+
+echo "$as_me:$LINENO: result: $SED" >&5
+echo "${ECHO_T}$SED" >&6
+
+echo "$as_me:$LINENO: checking for egrep" >&5
+echo $ECHO_N "checking for egrep... $ECHO_C" >&6
+if test "${ac_cv_prog_egrep+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if echo a | (grep -E '(a|b)') >/dev/null 2>&1
+ then ac_cv_prog_egrep='grep -E'
+ else ac_cv_prog_egrep='egrep'
+ fi
+fi
+echo "$as_me:$LINENO: result: $ac_cv_prog_egrep" >&5
+echo "${ECHO_T}$ac_cv_prog_egrep" >&6
+ EGREP=$ac_cv_prog_egrep
+
+
+
+# Check whether --with-gnu-ld or --without-gnu-ld was given.
+if test "${with_gnu_ld+set}" = set; then
+ withval="$with_gnu_ld"
+ test "$withval" = no || with_gnu_ld=yes
+else
+ with_gnu_ld=no
+fi;
+ac_prog=ld
+if test "$GCC" = yes; then
+ # Check if gcc -print-prog-name=ld gives a path.
+ echo "$as_me:$LINENO: checking for ld used by $CC" >&5
+echo $ECHO_N "checking for ld used by $CC... $ECHO_C" >&6
+ case $host in
+ *-*-mingw*)
+ # gcc leaves a trailing carriage return which upsets mingw
+ ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+ *)
+ ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+ esac
+ case $ac_prog in
+ # Accept absolute paths.
+ [\\/]* | ?:[\\/]*)
+ re_direlt='/[^/][^/]*/\.\./'
+ # Canonicalize the pathname of ld
+ ac_prog=`echo $ac_prog| $SED 's%\\\\%/%g'`
+ while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do
+ ac_prog=`echo $ac_prog| $SED "s%$re_direlt%/%"`
+ done
+ test -z "$LD" && LD="$ac_prog"
+ ;;
+ "")
+ # If it fails, then pretend we aren't using GCC.
+ ac_prog=ld
+ ;;
+ *)
+ # If it is relative, then search for the first ld in PATH.
+ with_gnu_ld=unknown
+ ;;
+ esac
+elif test "$with_gnu_ld" = yes; then
+ echo "$as_me:$LINENO: checking for GNU ld" >&5
+echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6
+else
+ echo "$as_me:$LINENO: checking for non-GNU ld" >&5
+echo $ECHO_N "checking for non-GNU ld... $ECHO_C" >&6
+fi
+if test "${lt_cv_path_LD+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -z "$LD"; then
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+ for ac_dir in $PATH; do
+ IFS="$lt_save_ifs"
+ test -z "$ac_dir" && ac_dir=.
+ if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+ lt_cv_path_LD="$ac_dir/$ac_prog"
+ # Check to see if the program is GNU ld. I'd rather use --version,
+ # but apparently some variants of GNU ld only accept -v.
+ # Break only if it was the GNU/non-GNU ld that we prefer.
+ case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
+ *GNU* | *'with BFD'*)
+ test "$with_gnu_ld" != no && break
+ ;;
+ *)
+ test "$with_gnu_ld" != yes && break
+ ;;
+ esac
+ fi
+ done
+ IFS="$lt_save_ifs"
+else
+ lt_cv_path_LD="$LD" # Let the user override the test with a path.
+fi
+fi
+
+LD="$lt_cv_path_LD"
+if test -n "$LD"; then
+ echo "$as_me:$LINENO: result: $LD" >&5
+echo "${ECHO_T}$LD" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+test -z "$LD" && { { echo "$as_me:$LINENO: error: no acceptable ld found in \$PATH" >&5
+echo "$as_me: error: no acceptable ld found in \$PATH" >&2;}
+ { (exit 1); exit 1; }; }
+echo "$as_me:$LINENO: checking if the linker ($LD) is GNU ld" >&5
+echo $ECHO_N "checking if the linker ($LD) is GNU ld... $ECHO_C" >&6
+if test "${lt_cv_prog_gnu_ld+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ # I'd rather use --version here, but apparently some GNU lds only accept -v.
+case `$LD -v 2>&1 </dev/null` in
+*GNU* | *'with BFD'*)
+ lt_cv_prog_gnu_ld=yes
+ ;;
+*)
+ lt_cv_prog_gnu_ld=no
+ ;;
+esac
+fi
+echo "$as_me:$LINENO: result: $lt_cv_prog_gnu_ld" >&5
+echo "${ECHO_T}$lt_cv_prog_gnu_ld" >&6
+with_gnu_ld=$lt_cv_prog_gnu_ld
+
+
+echo "$as_me:$LINENO: checking for $LD option to reload object files" >&5
+echo $ECHO_N "checking for $LD option to reload object files... $ECHO_C" >&6
+if test "${lt_cv_ld_reload_flag+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_cv_ld_reload_flag='-r'
+fi
+echo "$as_me:$LINENO: result: $lt_cv_ld_reload_flag" >&5
+echo "${ECHO_T}$lt_cv_ld_reload_flag" >&6
+reload_flag=$lt_cv_ld_reload_flag
+case $reload_flag in
+"" | " "*) ;;
+*) reload_flag=" $reload_flag" ;;
+esac
+reload_cmds='$LD$reload_flag -o $output$reload_objs'
+case $host_os in
+ darwin*)
+ if test "$GCC" = yes; then
+ reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
+ else
+ reload_cmds='$LD$reload_flag -o $output$reload_objs'
+ fi
+ ;;
+esac
+
+echo "$as_me:$LINENO: checking for BSD-compatible nm" >&5
+echo $ECHO_N "checking for BSD-compatible nm... $ECHO_C" >&6
+if test "${lt_cv_path_NM+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$NM"; then
+ # Let the user override the test.
+ lt_cv_path_NM="$NM"
+else
+ lt_nm_to_check="${ac_tool_prefix}nm"
+ if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
+ lt_nm_to_check="$lt_nm_to_check nm"
+ fi
+ for lt_tmp_nm in $lt_nm_to_check; do
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+ for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
+ IFS="$lt_save_ifs"
+ test -z "$ac_dir" && ac_dir=.
+ tmp_nm="$ac_dir/$lt_tmp_nm"
+ if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+ # Check to see if the nm accepts a BSD-compat flag.
+ # Adding the `sed 1q' prevents false positives on HP-UX, which says:
+ # nm: unknown option "B" ignored
+ # Tru64's nm complains that /dev/null is an invalid object file
+ case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
+ */dev/null* | *'Invalid file or object type'*)
+ lt_cv_path_NM="$tmp_nm -B"
+ break
+ ;;
+ *)
+ case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
+ */dev/null*)
+ lt_cv_path_NM="$tmp_nm -p"
+ break
+ ;;
+ *)
+ lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
+ continue # so that we can try to find one that supports BSD flags
+ ;;
+ esac
+ ;;
+ esac
+ fi
+ done
+ IFS="$lt_save_ifs"
+ done
+ test -z "$lt_cv_path_NM" && lt_cv_path_NM=nm
+fi
+fi
+echo "$as_me:$LINENO: result: $lt_cv_path_NM" >&5
+echo "${ECHO_T}$lt_cv_path_NM" >&6
+NM="$lt_cv_path_NM"
+
+echo "$as_me:$LINENO: checking whether ln -s works" >&5
+echo $ECHO_N "checking whether ln -s works... $ECHO_C" >&6
+LN_S=$as_ln_s
+if test "$LN_S" = "ln -s"; then
+ echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
+else
+ echo "$as_me:$LINENO: result: no, using $LN_S" >&5
+echo "${ECHO_T}no, using $LN_S" >&6
+fi
+
+echo "$as_me:$LINENO: checking how to recognise dependent libraries" >&5
+echo $ECHO_N "checking how to recognise dependent libraries... $ECHO_C" >&6
+if test "${lt_cv_deplibs_check_method+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_cv_file_magic_cmd='$MAGIC_CMD'
+lt_cv_file_magic_test_file=
+lt_cv_deplibs_check_method='unknown'
+# Need to set the preceding variable on all platforms that support
+# interlibrary dependencies.
+# 'none' -- dependencies not supported.
+# `unknown' -- same as none, but documents that we really don't know.
+# 'pass_all' -- all dependencies passed with no checks.
+# 'test_compile' -- check by making test program.
+# 'file_magic [[regex]]' -- check by looking for files in library path
+# which responds to the $file_magic_cmd with a given extended regex.
+# If you have `file' or equivalent on your system and you're not sure
+# whether `pass_all' will *always* work, you probably want this one.
+
+case $host_os in
+aix4* | aix5*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+beos*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+bsdi[45]*)
+ lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)'
+ lt_cv_file_magic_cmd='/usr/bin/file -L'
+ lt_cv_file_magic_test_file=/shlib/libc.so
+ ;;
+
+cygwin*)
+ # func_win32_libid is a shell function defined in ltmain.sh
+ lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+ lt_cv_file_magic_cmd='func_win32_libid'
+ ;;
+
+mingw* | pw32*)
+ # Base MSYS/MinGW do not provide the 'file' command needed by
+ # func_win32_libid shell function, so use a weaker test based on 'objdump'.
+ lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?'
+ lt_cv_file_magic_cmd='$OBJDUMP -f'
+ ;;
+
+darwin* | rhapsody*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+freebsd* | kfreebsd*-gnu | dragonfly*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then
+ case $host_cpu in
+ i*86 )
+ # Not sure whether the presence of OpenBSD here was a mistake.
+ # Let's accept both of them until this is cleared up.
+ lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library'
+ lt_cv_file_magic_cmd=/usr/bin/file
+ lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
+ ;;
+ esac
+ else
+ lt_cv_deplibs_check_method=pass_all
+ fi
+ ;;
+
+gnu*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+hpux10.20* | hpux11*)
+ lt_cv_file_magic_cmd=/usr/bin/file
+ case $host_cpu in
+ ia64*)
+ lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64'
+ lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
+ ;;
+ hppa*64*)
+ lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]'
+ lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
+ ;;
+ *)
+ lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9].[0-9]) shared library'
+ lt_cv_file_magic_test_file=/usr/lib/libc.sl
+ ;;
+ esac
+ ;;
+
+interix3*)
+ # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
+ lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$'
+ ;;
+
+irix5* | irix6* | nonstopux*)
+ case $LD in
+ *-32|*"-32 ") libmagic=32-bit;;
+ *-n32|*"-n32 ") libmagic=N32;;
+ *-64|*"-64 ") libmagic=64-bit;;
+ *) libmagic=never-match;;
+ esac
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+# This must be Linux ELF.
+linux*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then
+ lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$'
+ else
+ lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$'
+ fi
+ ;;
+
+newos6*)
+ lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)'
+ lt_cv_file_magic_cmd=/usr/bin/file
+ lt_cv_file_magic_test_file=/usr/lib/libnls.so
+ ;;
+
+nto-qnx*)
+ lt_cv_deplibs_check_method=unknown
+ ;;
+
+openbsd*)
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$'
+ else
+ lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$'
+ fi
+ ;;
+
+osf3* | osf4* | osf5*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+solaris*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+
+sysv4 | sysv4.3*)
+ case $host_vendor in
+ motorola)
+ lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]'
+ lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
+ ;;
+ ncr)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+ sequent)
+ lt_cv_file_magic_cmd='/bin/file'
+ lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )'
+ ;;
+ sni)
+ lt_cv_file_magic_cmd='/bin/file'
+ lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib"
+ lt_cv_file_magic_test_file=/lib/libc.so
+ ;;
+ siemens)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+ pc)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+ esac
+ ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+ lt_cv_deplibs_check_method=pass_all
+ ;;
+esac
+
+fi
+echo "$as_me:$LINENO: result: $lt_cv_deplibs_check_method" >&5
+echo "${ECHO_T}$lt_cv_deplibs_check_method" >&6
+file_magic_cmd=$lt_cv_file_magic_cmd
+deplibs_check_method=$lt_cv_deplibs_check_method
+test -z "$deplibs_check_method" && deplibs_check_method=unknown
+
+
+
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+
+
+# Check whether --enable-libtool-lock or --disable-libtool-lock was given.
+if test "${enable_libtool_lock+set}" = set; then
+ enableval="$enable_libtool_lock"
+
+fi;
+test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
+
+# Some flags need to be propagated to the compiler or linker for good
+# libtool support.
+case $host in
+ia64-*-hpux*)
+ # Find out which ABI we are using.
+ echo 'int i;' > conftest.$ac_ext
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ case `/usr/bin/file conftest.$ac_objext` in
+ *ELF-32*)
+ HPUX_IA64_MODE="32"
+ ;;
+ *ELF-64*)
+ HPUX_IA64_MODE="64"
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+*-*-irix6*)
+ # Find out which ABI we are using.
+ echo '#line 3944 "configure"' > conftest.$ac_ext
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ if test "$lt_cv_prog_gnu_ld" = yes; then
+ case `/usr/bin/file conftest.$ac_objext` in
+ *32-bit*)
+ LD="${LD-ld} -melf32bsmip"
+ ;;
+ *N32*)
+ LD="${LD-ld} -melf32bmipn32"
+ ;;
+ *64-bit*)
+ LD="${LD-ld} -melf64bmip"
+ ;;
+ esac
+ else
+ case `/usr/bin/file conftest.$ac_objext` in
+ *32-bit*)
+ LD="${LD-ld} -32"
+ ;;
+ *N32*)
+ LD="${LD-ld} -n32"
+ ;;
+ *64-bit*)
+ LD="${LD-ld} -64"
+ ;;
+ esac
+ fi
+ fi
+ rm -rf conftest*
+ ;;
+
+x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*|s390*-*linux*|sparc*-*linux*)
+ # Find out which ABI we are using.
+ echo 'int i;' > conftest.$ac_ext
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ case `/usr/bin/file conftest.o` in
+ *32-bit*)
+ case $host in
+ x86_64-*linux*)
+ LD="${LD-ld} -m elf_i386"
+ ;;
+ ppc64-*linux*|powerpc64-*linux*)
+ LD="${LD-ld} -m elf32ppclinux"
+ ;;
+ s390x-*linux*)
+ LD="${LD-ld} -m elf_s390"
+ ;;
+ sparc64-*linux*)
+ LD="${LD-ld} -m elf32_sparc"
+ ;;
+ esac
+ ;;
+ *64-bit*)
+ case $host in
+ x86_64-*linux*)
+ LD="${LD-ld} -m elf_x86_64"
+ ;;
+ ppc*-*linux*|powerpc*-*linux*)
+ LD="${LD-ld} -m elf64ppc"
+ ;;
+ s390*-*linux*)
+ LD="${LD-ld} -m elf64_s390"
+ ;;
+ sparc*-*linux*)
+ LD="${LD-ld} -m elf64_sparc"
+ ;;
+ esac
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+
+*-*-sco3.2v5*)
+ # On SCO OpenServer 5, we need -belf to get full-featured binaries.
+ SAVE_CFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS -belf"
+ echo "$as_me:$LINENO: checking whether the C compiler needs -belf" >&5
+echo $ECHO_N "checking whether the C compiler needs -belf... $ECHO_C" >&6
+if test "${lt_cv_cc_needs_belf+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ lt_cv_cc_needs_belf=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+lt_cv_cc_needs_belf=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+ ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+fi
+echo "$as_me:$LINENO: result: $lt_cv_cc_needs_belf" >&5
+echo "${ECHO_T}$lt_cv_cc_needs_belf" >&6
+ if test x"$lt_cv_cc_needs_belf" != x"yes"; then
+ # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
+ CFLAGS="$SAVE_CFLAGS"
+ fi
+ ;;
+sparc*-*solaris*)
+ # Find out which ABI we are using.
+ echo 'int i;' > conftest.$ac_ext
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ case `/usr/bin/file conftest.o` in
+ *64-bit*)
+ case $lt_cv_prog_gnu_ld in
+ yes*) LD="${LD-ld} -m elf64_sparc" ;;
+ *) LD="${LD-ld} -64" ;;
+ esac
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+
+
+esac
+
+need_locks="$enable_libtool_lock"
+
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5
+echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6
+# On Suns, sometimes $CPP names a directory.
+if test -n "$CPP" && test -d "$CPP"; then
+ CPP=
+fi
+if test -z "$CPP"; then
+ if test "${ac_cv_prog_CPP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ # Double quotes because CPP needs to be expanded
+ for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
+ do
+ ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+ # Use a header file that comes with gcc, so configuring glibc
+ # with a fresh cross-compiler works.
+ # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ # <limits.h> exists even on freestanding compilers.
+ # On the NeXT, cc -E runs the code through the compiler's parser,
+ # not just through cpp. "Syntax error" is here to catch this case.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+ Syntax error
+_ACEOF
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+ (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ :
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.$ac_ext
+
+ # OK, works on sane cases. Now check whether non-existent headers
+ # can be detected and how.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+ (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ # Broken: success on invalid input.
+continue
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
+ break
+fi
+
+ done
+ ac_cv_prog_CPP=$CPP
+
+fi
+ CPP=$ac_cv_prog_CPP
+else
+ ac_cv_prog_CPP=$CPP
+fi
+echo "$as_me:$LINENO: result: $CPP" >&5
+echo "${ECHO_T}$CPP" >&6
+ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+ # Use a header file that comes with gcc, so configuring glibc
+ # with a fresh cross-compiler works.
+ # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ # <limits.h> exists even on freestanding compilers.
+ # On the NeXT, cc -E runs the code through the compiler's parser,
+ # not just through cpp. "Syntax error" is here to catch this case.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+ Syntax error
+_ACEOF
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+ (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ :
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.$ac_ext
+
+ # OK, works on sane cases. Now check whether non-existent headers
+ # can be detected and how.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+ (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ # Broken: success on invalid input.
+continue
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
+ :
+else
+ { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details." >&5
+echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+echo "$as_me:$LINENO: checking for ANSI C header files" >&5
+echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6
+if test "${ac_cv_header_stdc+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_header_stdc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_header_stdc=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+
+if test $ac_cv_header_stdc = yes; then
+ # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <string.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+ $EGREP "memchr" >/dev/null 2>&1; then
+ :
+else
+ ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+ # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <stdlib.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+ $EGREP "free" >/dev/null 2>&1; then
+ :
+else
+ ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+ # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
+ if test "$cross_compiling" = yes; then
+ :
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <ctype.h>
+#if ((' ' & 0x0FF) == 0x020)
+# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
+# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
+#else
+# define ISLOWER(c) \
+ (('a' <= (c) && (c) <= 'i') \
+ || ('j' <= (c) && (c) <= 'r') \
+ || ('s' <= (c) && (c) <= 'z'))
+# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
+#endif
+
+#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
+int
+main ()
+{
+ int i;
+ for (i = 0; i < 256; i++)
+ if (XOR (islower (i), ISLOWER (i))
+ || toupper (i) != TOUPPER (i))
+ exit(2);
+ exit (0);
+}
+_ACEOF
+rm -f conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ :
+else
+ echo "$as_me: program exited with status $ac_status" >&5
+echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+( exit $ac_status )
+ac_cv_header_stdc=no
+fi
+rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+fi
+fi
+fi
+echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5
+echo "${ECHO_T}$ac_cv_header_stdc" >&6
+if test $ac_cv_header_stdc = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define STDC_HEADERS 1
+_ACEOF
+
+fi
+
+# On IRIX 5.3, sys/types and inttypes.h are conflicting.
+
+
+
+
+
+
+
+
+
+for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
+ inttypes.h stdint.h unistd.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_Header=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+eval "$as_ac_Header=no"
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+
+for ac_header in dlfcn.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
+ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
+else
+ # Is the header compilable?
+echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_header_compiler=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6
+
+# Is the header present?
+echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+ (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+rm -f conftest.err conftest.$ac_ext
+echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ (
+ cat <<\_ASBOX
+## --------------------------------- ##
+## Report this to the jasper lists. ##
+## --------------------------------- ##
+_ASBOX
+ ) |
+ sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+ac_ext=cc
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+if test -n "$ac_tool_prefix"; then
+ for ac_prog in $CCC g++ c++ gpp aCC CC cxx cc++ cl FCC KCC RCC xlC_r xlC
+ do
+ # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_CXX+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$CXX"; then
+ ac_cv_prog_CXX="$CXX" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_CXX="$ac_tool_prefix$ac_prog"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+CXX=$ac_cv_prog_CXX
+if test -n "$CXX"; then
+ echo "$as_me:$LINENO: result: $CXX" >&5
+echo "${ECHO_T}$CXX" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ test -n "$CXX" && break
+ done
+fi
+if test -z "$CXX"; then
+ ac_ct_CXX=$CXX
+ for ac_prog in $CCC g++ c++ gpp aCC CC cxx cc++ cl FCC KCC RCC xlC_r xlC
+do
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_ac_ct_CXX+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_CXX"; then
+ ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_ac_ct_CXX="$ac_prog"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+ac_ct_CXX=$ac_cv_prog_ac_ct_CXX
+if test -n "$ac_ct_CXX"; then
+ echo "$as_me:$LINENO: result: $ac_ct_CXX" >&5
+echo "${ECHO_T}$ac_ct_CXX" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ test -n "$ac_ct_CXX" && break
+done
+test -n "$ac_ct_CXX" || ac_ct_CXX="g++"
+
+ CXX=$ac_ct_CXX
+fi
+
+
+# Provide some information about the compiler.
+echo "$as_me:$LINENO:" \
+ "checking for C++ compiler version" >&5
+ac_compiler=`set X $ac_compile; echo $2`
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5
+ (eval $ac_compiler --version </dev/null >&5) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v </dev/null >&5\"") >&5
+ (eval $ac_compiler -v </dev/null >&5) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V </dev/null >&5\"") >&5
+ (eval $ac_compiler -V </dev/null >&5) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+
+echo "$as_me:$LINENO: checking whether we are using the GNU C++ compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU C++ compiler... $ECHO_C" >&6
+if test "${ac_cv_cxx_compiler_gnu+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+#ifndef __GNUC__
+ choke me
+#endif
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_compiler_gnu=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_compiler_gnu=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_cxx_compiler_gnu=$ac_compiler_gnu
+
+fi
+echo "$as_me:$LINENO: result: $ac_cv_cxx_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_cxx_compiler_gnu" >&6
+GXX=`test $ac_compiler_gnu = yes && echo yes`
+ac_test_CXXFLAGS=${CXXFLAGS+set}
+ac_save_CXXFLAGS=$CXXFLAGS
+CXXFLAGS="-g"
+echo "$as_me:$LINENO: checking whether $CXX accepts -g" >&5
+echo $ECHO_N "checking whether $CXX accepts -g... $ECHO_C" >&6
+if test "${ac_cv_prog_cxx_g+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_prog_cxx_g=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_prog_cxx_g=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_prog_cxx_g" >&5
+echo "${ECHO_T}$ac_cv_prog_cxx_g" >&6
+if test "$ac_test_CXXFLAGS" = set; then
+ CXXFLAGS=$ac_save_CXXFLAGS
+elif test $ac_cv_prog_cxx_g = yes; then
+ if test "$GXX" = yes; then
+ CXXFLAGS="-g -O2"
+ else
+ CXXFLAGS="-g"
+ fi
+else
+ if test "$GXX" = yes; then
+ CXXFLAGS="-O2"
+ else
+ CXXFLAGS=
+ fi
+fi
+for ac_declaration in \
+ '' \
+ 'extern "C" void std::exit (int) throw (); using std::exit;' \
+ 'extern "C" void std::exit (int); using std::exit;' \
+ 'extern "C" void exit (int) throw ();' \
+ 'extern "C" void exit (int);' \
+ 'void exit (int);'
+do
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_declaration
+#include <stdlib.h>
+int
+main ()
+{
+exit (42);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ :
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+continue
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_declaration
+int
+main ()
+{
+exit (42);
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ break
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+done
+rm -f conftest*
+if test -n "$ac_declaration"; then
+ echo '#ifdef __cplusplus' >>confdefs.h
+ echo $ac_declaration >>confdefs.h
+ echo '#endif' >>confdefs.h
+fi
+
+ac_ext=cc
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+depcc="$CXX" am_compiler_list=
+
+echo "$as_me:$LINENO: checking dependency style of $depcc" >&5
+echo $ECHO_N "checking dependency style of $depcc... $ECHO_C" >&6
+if test "${am_cv_CXX_dependencies_compiler_type+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then
+ # We make a subdir and do the tests there. Otherwise we can end up
+ # making bogus files that we don't know about and never remove. For
+ # instance it was reported that on HP-UX the gcc test will end up
+ # making a dummy file named `D' -- because `-MD' means `put the output
+ # in D'.
+ mkdir conftest.dir
+ # Copy depcomp to subdir because otherwise we won't find it if we're
+ # using a relative directory.
+ cp "$am_depcomp" conftest.dir
+ cd conftest.dir
+ # We will build objects and dependencies in a subdirectory because
+ # it helps to detect inapplicable dependency modes. For instance
+ # both Tru64's cc and ICC support -MD to output dependencies as a
+ # side effect of compilation, but ICC will put the dependencies in
+ # the current directory while Tru64 will put them in the object
+ # directory.
+ mkdir sub
+
+ am_cv_CXX_dependencies_compiler_type=none
+ if test "$am_compiler_list" = ""; then
+ am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp`
+ fi
+ for depmode in $am_compiler_list; do
+ # Setup a source with many dependencies, because some compilers
+ # like to wrap large dependency lists on column 80 (with \), and
+ # we should not choose a depcomp mode which is confused by this.
+ #
+ # We need to recreate these files for each test, as the compiler may
+ # overwrite some of them when testing with obscure command lines.
+ # This happens at least with the AIX C compiler.
+ : > sub/conftest.c
+ for i in 1 2 3 4 5 6; do
+ echo '#include "conftst'$i'.h"' >> sub/conftest.c
+ # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with
+ # Solaris 8's {/usr,}/bin/sh.
+ touch sub/conftst$i.h
+ done
+ echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf
+
+ case $depmode in
+ nosideeffect)
+ # after this tag, mechanisms are not by side-effect, so they'll
+ # only be used when explicitly requested
+ if test "x$enable_dependency_tracking" = xyes; then
+ continue
+ else
+ break
+ fi
+ ;;
+ none) break ;;
+ esac
+ # We check with `-c' and `-o' for the sake of the "dashmstdout"
+ # mode. It turns out that the SunPro C++ compiler does not properly
+ # handle `-M -o', and we need to detect this.
+ if depmode=$depmode \
+ source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \
+ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \
+ $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \
+ >/dev/null 2>conftest.err &&
+ grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 &&
+ grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 &&
+ ${MAKE-make} -s -f confmf > /dev/null 2>&1; then
+ # icc doesn't choke on unknown options, it will just issue warnings
+ # or remarks (even with -Werror). So we grep stderr for any message
+ # that says an option was ignored or not supported.
+ # When given -MP, icc 7.0 and 7.1 complain thusly:
+ # icc: Command line warning: ignoring option '-M'; no argument required
+ # The diagnosis changed in icc 8.0:
+ # icc: Command line remark: option '-MP' not supported
+ if (grep 'ignoring option' conftest.err ||
+ grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else
+ am_cv_CXX_dependencies_compiler_type=$depmode
+ break
+ fi
+ fi
+ done
+
+ cd ..
+ rm -rf conftest.dir
+else
+ am_cv_CXX_dependencies_compiler_type=none
+fi
+
+fi
+echo "$as_me:$LINENO: result: $am_cv_CXX_dependencies_compiler_type" >&5
+echo "${ECHO_T}$am_cv_CXX_dependencies_compiler_type" >&6
+CXXDEPMODE=depmode=$am_cv_CXX_dependencies_compiler_type
+
+
+
+if
+ test "x$enable_dependency_tracking" != xno \
+ && test "$am_cv_CXX_dependencies_compiler_type" = gcc3; then
+ am__fastdepCXX_TRUE=
+ am__fastdepCXX_FALSE='#'
+else
+ am__fastdepCXX_TRUE='#'
+ am__fastdepCXX_FALSE=
+fi
+
+
+
+
+if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
+ ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
+ (test "X$CXX" != "Xg++"))) ; then
+ ac_ext=cc
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+echo "$as_me:$LINENO: checking how to run the C++ preprocessor" >&5
+echo $ECHO_N "checking how to run the C++ preprocessor... $ECHO_C" >&6
+if test -z "$CXXCPP"; then
+ if test "${ac_cv_prog_CXXCPP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ # Double quotes because CXXCPP needs to be expanded
+ for CXXCPP in "$CXX -E" "/lib/cpp"
+ do
+ ac_preproc_ok=false
+for ac_cxx_preproc_warn_flag in '' yes
+do
+ # Use a header file that comes with gcc, so configuring glibc
+ # with a fresh cross-compiler works.
+ # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ # <limits.h> exists even on freestanding compilers.
+ # On the NeXT, cc -E runs the code through the compiler's parser,
+ # not just through cpp. "Syntax error" is here to catch this case.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+ Syntax error
+_ACEOF
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+ (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_cxx_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ :
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.$ac_ext
+
+ # OK, works on sane cases. Now check whether non-existent headers
+ # can be detected and how.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+ (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_cxx_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ # Broken: success on invalid input.
+continue
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
+ break
+fi
+
+ done
+ ac_cv_prog_CXXCPP=$CXXCPP
+
+fi
+ CXXCPP=$ac_cv_prog_CXXCPP
+else
+ ac_cv_prog_CXXCPP=$CXXCPP
+fi
+echo "$as_me:$LINENO: result: $CXXCPP" >&5
+echo "${ECHO_T}$CXXCPP" >&6
+ac_preproc_ok=false
+for ac_cxx_preproc_warn_flag in '' yes
+do
+ # Use a header file that comes with gcc, so configuring glibc
+ # with a fresh cross-compiler works.
+ # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ # <limits.h> exists even on freestanding compilers.
+ # On the NeXT, cc -E runs the code through the compiler's parser,
+ # not just through cpp. "Syntax error" is here to catch this case.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+ Syntax error
+_ACEOF
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+ (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_cxx_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ :
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.$ac_ext
+
+ # OK, works on sane cases. Now check whether non-existent headers
+ # can be detected and how.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+ (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_cxx_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_cxx_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ # Broken: success on invalid input.
+continue
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
+ :
+else
+ { { echo "$as_me:$LINENO: error: C++ preprocessor \"$CXXCPP\" fails sanity check
+See \`config.log' for more details." >&5
+echo "$as_me: error: C++ preprocessor \"$CXXCPP\" fails sanity check
+See \`config.log' for more details." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+ac_ext=cc
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+fi
+
+
+ac_ext=f
+ac_compile='$F77 -c $FFLAGS conftest.$ac_ext >&5'
+ac_link='$F77 -o conftest$ac_exeext $FFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_f77_compiler_gnu
+if test -n "$ac_tool_prefix"; then
+ for ac_prog in g77 f77 xlf frt pgf77 fort77 fl32 af77 f90 xlf90 pgf90 epcf90 f95 fort xlf95 ifc efc pgf95 lf95 gfortran
+ do
+ # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_F77+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$F77"; then
+ ac_cv_prog_F77="$F77" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_F77="$ac_tool_prefix$ac_prog"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+F77=$ac_cv_prog_F77
+if test -n "$F77"; then
+ echo "$as_me:$LINENO: result: $F77" >&5
+echo "${ECHO_T}$F77" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ test -n "$F77" && break
+ done
+fi
+if test -z "$F77"; then
+ ac_ct_F77=$F77
+ for ac_prog in g77 f77 xlf frt pgf77 fort77 fl32 af77 f90 xlf90 pgf90 epcf90 f95 fort xlf95 ifc efc pgf95 lf95 gfortran
+do
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_ac_ct_F77+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_F77"; then
+ ac_cv_prog_ac_ct_F77="$ac_ct_F77" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_ac_ct_F77="$ac_prog"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+ac_ct_F77=$ac_cv_prog_ac_ct_F77
+if test -n "$ac_ct_F77"; then
+ echo "$as_me:$LINENO: result: $ac_ct_F77" >&5
+echo "${ECHO_T}$ac_ct_F77" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ test -n "$ac_ct_F77" && break
+done
+
+ F77=$ac_ct_F77
+fi
+
+
+# Provide some information about the compiler.
+echo "$as_me:5543:" \
+ "checking for Fortran 77 compiler version" >&5
+ac_compiler=`set X $ac_compile; echo $2`
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5
+ (eval $ac_compiler --version </dev/null >&5) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v </dev/null >&5\"") >&5
+ (eval $ac_compiler -v </dev/null >&5) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V </dev/null >&5\"") >&5
+ (eval $ac_compiler -V </dev/null >&5) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+rm -f a.out
+
+# If we don't use `.F' as extension, the preprocessor is not run on the
+# input file. (Note that this only needs to work for GNU compilers.)
+ac_save_ext=$ac_ext
+ac_ext=F
+echo "$as_me:$LINENO: checking whether we are using the GNU Fortran 77 compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU Fortran 77 compiler... $ECHO_C" >&6
+if test "${ac_cv_f77_compiler_gnu+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+ program main
+#ifndef __GNUC__
+ choke me
+#endif
+
+ end
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_f77_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_compiler_gnu=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_compiler_gnu=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_f77_compiler_gnu=$ac_compiler_gnu
+
+fi
+echo "$as_me:$LINENO: result: $ac_cv_f77_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_f77_compiler_gnu" >&6
+ac_ext=$ac_save_ext
+ac_test_FFLAGS=${FFLAGS+set}
+ac_save_FFLAGS=$FFLAGS
+FFLAGS=
+echo "$as_me:$LINENO: checking whether $F77 accepts -g" >&5
+echo $ECHO_N "checking whether $F77 accepts -g... $ECHO_C" >&6
+if test "${ac_cv_prog_f77_g+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ FFLAGS=-g
+cat >conftest.$ac_ext <<_ACEOF
+ program main
+
+ end
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_f77_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_prog_f77_g=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_prog_f77_g=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+echo "$as_me:$LINENO: result: $ac_cv_prog_f77_g" >&5
+echo "${ECHO_T}$ac_cv_prog_f77_g" >&6
+if test "$ac_test_FFLAGS" = set; then
+ FFLAGS=$ac_save_FFLAGS
+elif test $ac_cv_prog_f77_g = yes; then
+ if test "x$ac_cv_f77_compiler_gnu" = xyes; then
+ FFLAGS="-g -O2"
+ else
+ FFLAGS="-g"
+ fi
+else
+ if test "x$ac_cv_f77_compiler_gnu" = xyes; then
+ FFLAGS="-O2"
+ else
+ FFLAGS=
+ fi
+fi
+
+G77=`test $ac_compiler_gnu = yes && echo yes`
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+
+# Autoconf 2.13's AC_OBJEXT and AC_EXEEXT macros only works for C compilers!
+
+# find the maximum length of command line arguments
+echo "$as_me:$LINENO: checking the maximum length of command line arguments" >&5
+echo $ECHO_N "checking the maximum length of command line arguments... $ECHO_C" >&6
+if test "${lt_cv_sys_max_cmd_len+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ i=0
+ teststring="ABCD"
+
+ case $build_os in
+ msdosdjgpp*)
+ # On DJGPP, this test can blow up pretty badly due to problems in libc
+ # (any single argument exceeding 2000 bytes causes a buffer overrun
+ # during glob expansion). Even if it were fixed, the result of this
+ # check would be larger than it should be.
+ lt_cv_sys_max_cmd_len=12288; # 12K is about right
+ ;;
+
+ gnu*)
+ # Under GNU Hurd, this test is not required because there is
+ # no limit to the length of command line arguments.
+ # Libtool will interpret -1 as no limit whatsoever
+ lt_cv_sys_max_cmd_len=-1;
+ ;;
+
+ cygwin* | mingw*)
+ # On Win9x/ME, this test blows up -- it succeeds, but takes
+ # about 5 minutes as the teststring grows exponentially.
+ # Worse, since 9x/ME are not pre-emptively multitasking,
+ # you end up with a "frozen" computer, even though with patience
+ # the test eventually succeeds (with a max line length of 256k).
+ # Instead, let's just punt: use the minimum linelength reported by
+ # all of the supported platforms: 8192 (on NT/2K/XP).
+ lt_cv_sys_max_cmd_len=8192;
+ ;;
+
+ amigaos*)
+ # On AmigaOS with pdksh, this test takes hours, literally.
+ # So we just punt and use a minimum line length of 8192.
+ lt_cv_sys_max_cmd_len=8192;
+ ;;
+
+ netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
+ # This has been around since 386BSD, at least. Likely further.
+ if test -x /sbin/sysctl; then
+ lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
+ elif test -x /usr/sbin/sysctl; then
+ lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
+ else
+ lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs
+ fi
+ # And add a safety zone
+ lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+ lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+ ;;
+
+ interix*)
+ # We know the value 262144 and hardcode it with a safety zone (like BSD)
+ lt_cv_sys_max_cmd_len=196608
+ ;;
+
+ osf*)
+ # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
+ # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
+ # nice to cause kernel panics so lets avoid the loop below.
+ # First set a reasonable default.
+ lt_cv_sys_max_cmd_len=16384
+ #
+ if test -x /sbin/sysconfig; then
+ case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
+ *1*) lt_cv_sys_max_cmd_len=-1 ;;
+ esac
+ fi
+ ;;
+ sco3.2v5*)
+ lt_cv_sys_max_cmd_len=102400
+ ;;
+ sysv5* | sco5v6* | sysv4.2uw2*)
+ kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
+ if test -n "$kargmax"; then
+ lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[ ]//'`
+ else
+ lt_cv_sys_max_cmd_len=32768
+ fi
+ ;;
+ *)
+ # If test is not a shell built-in, we'll probably end up computing a
+ # maximum length that is only half of the actual maximum length, but
+ # we can't tell.
+ SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
+ while (test "X"`$SHELL $0 --fallback-echo "X$teststring" 2>/dev/null` \
+ = "XX$teststring") >/dev/null 2>&1 &&
+ new_result=`expr "X$teststring" : ".*" 2>&1` &&
+ lt_cv_sys_max_cmd_len=$new_result &&
+ test $i != 17 # 1/2 MB should be enough
+ do
+ i=`expr $i + 1`
+ teststring=$teststring$teststring
+ done
+ teststring=
+ # Add a significant safety factor because C++ compilers can tack on massive
+ # amounts of additional arguments before passing them to the linker.
+ # It appears as though 1/2 is a usable value.
+ lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
+ ;;
+ esac
+
+fi
+
+if test -n $lt_cv_sys_max_cmd_len ; then
+ echo "$as_me:$LINENO: result: $lt_cv_sys_max_cmd_len" >&5
+echo "${ECHO_T}$lt_cv_sys_max_cmd_len" >&6
+else
+ echo "$as_me:$LINENO: result: none" >&5
+echo "${ECHO_T}none" >&6
+fi
+
+
+
+
+# Check for command to grab the raw symbol name followed by C symbol from nm.
+echo "$as_me:$LINENO: checking command to parse $NM output from $compiler object" >&5
+echo $ECHO_N "checking command to parse $NM output from $compiler object... $ECHO_C" >&6
+if test "${lt_cv_sys_global_symbol_pipe+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+
+# These are sane defaults that work on at least a few old systems.
+# [They come from Ultrix. What could be older than Ultrix?!! ;)]
+
+# Character class describing NM global symbol codes.
+symcode='[BCDEGRST]'
+
+# Regexp to match symbols that can be accessed directly from C.
+sympat='\([_A-Za-z][_A-Za-z0-9]*\)'
+
+# Transform an extracted symbol line into a proper C declaration
+lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^. .* \(.*\)$/extern int \1;/p'"
+
+# Transform an extracted symbol line into symbol name and symbol address
+lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode \([^ ]*\) \([^ ]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'"
+
+# Define system-specific variables.
+case $host_os in
+aix*)
+ symcode='[BCDT]'
+ ;;
+cygwin* | mingw* | pw32*)
+ symcode='[ABCDGISTW]'
+ ;;
+hpux*) # Its linker distinguishes data from code symbols
+ if test "$host_cpu" = ia64; then
+ symcode='[ABCDEGRST]'
+ fi
+ lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+ lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'"
+ ;;
+linux*)
+ if test "$host_cpu" = ia64; then
+ symcode='[ABCDGIRSTW]'
+ lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+ lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (lt_ptr) \&\2},/p'"
+ fi
+ ;;
+irix* | nonstopux*)
+ symcode='[BCDEGRST]'
+ ;;
+osf*)
+ symcode='[BCDEGQRST]'
+ ;;
+solaris*)
+ symcode='[BDRT]'
+ ;;
+sco3.2v5*)
+ symcode='[DT]'
+ ;;
+sysv4.2uw2*)
+ symcode='[DT]'
+ ;;
+sysv5* | sco5v6* | unixware* | OpenUNIX*)
+ symcode='[ABDT]'
+ ;;
+sysv4)
+ symcode='[DFNSTU]'
+ ;;
+esac
+
+# Handle CRLF in mingw tool chain
+opt_cr=
+case $build_os in
+mingw*)
+ opt_cr=`echo 'x\{0,1\}' | tr x '\015'` # option cr in regexp
+ ;;
+esac
+
+# If we're using GNU nm, then use its standard symbol codes.
+case `$NM -V 2>&1` in
+*GNU* | *'with BFD'*)
+ symcode='[ABCDGIRSTW]' ;;
+esac
+
+# Try without a prefix undercore, then with it.
+for ac_symprfx in "" "_"; do
+
+ # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
+ symxfrm="\\1 $ac_symprfx\\2 \\2"
+
+ # Write the raw and C identifiers.
+ lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
+
+ # Check to see that the pipe works correctly.
+ pipe_works=no
+
+ rm -f conftest*
+ cat > conftest.$ac_ext <<EOF
+#ifdef __cplusplus
+extern "C" {
+#endif
+char nm_test_var;
+void nm_test_func(){}
+#ifdef __cplusplus
+}
+#endif
+int main(){nm_test_var='a';nm_test_func();return(0);}
+EOF
+
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ # Now try to grab the symbols.
+ nlist=conftest.nm
+ if { (eval echo "$as_me:$LINENO: \"$NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist\"") >&5
+ (eval $NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && test -s "$nlist"; then
+ # Try sorting and uniquifying the output.
+ if sort "$nlist" | uniq > "$nlist"T; then
+ mv -f "$nlist"T "$nlist"
+ else
+ rm -f "$nlist"T
+ fi
+
+ # Make sure that we snagged all the symbols we need.
+ if grep ' nm_test_var$' "$nlist" >/dev/null; then
+ if grep ' nm_test_func$' "$nlist" >/dev/null; then
+ cat <<EOF > conftest.$ac_ext
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+EOF
+ # Now generate the symbol file.
+ eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | grep -v main >> conftest.$ac_ext'
+
+ cat <<EOF >> conftest.$ac_ext
+#if defined (__STDC__) && __STDC__
+# define lt_ptr_t void *
+#else
+# define lt_ptr_t char *
+# define const
+#endif
+
+/* The mapping between symbol names and symbols. */
+const struct {
+ const char *name;
+ lt_ptr_t address;
+}
+lt_preloaded_symbols[] =
+{
+EOF
+ $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (lt_ptr_t) \&\2},/" < "$nlist" | grep -v main >> conftest.$ac_ext
+ cat <<\EOF >> conftest.$ac_ext
+ {0, (lt_ptr_t) 0}
+};
+
+#ifdef __cplusplus
+}
+#endif
+EOF
+ # Now try linking the two files.
+ mv conftest.$ac_objext conftstm.$ac_objext
+ lt_save_LIBS="$LIBS"
+ lt_save_CFLAGS="$CFLAGS"
+ LIBS="conftstm.$ac_objext"
+ CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag"
+ if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && test -s conftest${ac_exeext}; then
+ pipe_works=yes
+ fi
+ LIBS="$lt_save_LIBS"
+ CFLAGS="$lt_save_CFLAGS"
+ else
+ echo "cannot find nm_test_func in $nlist" >&5
+ fi
+ else
+ echo "cannot find nm_test_var in $nlist" >&5
+ fi
+ else
+ echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5
+ fi
+ else
+ echo "$progname: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ fi
+ rm -f conftest* conftst*
+
+ # Do not use the global_symbol_pipe unless it works.
+ if test "$pipe_works" = yes; then
+ break
+ else
+ lt_cv_sys_global_symbol_pipe=
+ fi
+done
+
+fi
+
+if test -z "$lt_cv_sys_global_symbol_pipe"; then
+ lt_cv_sys_global_symbol_to_cdecl=
+fi
+if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
+ echo "$as_me:$LINENO: result: failed" >&5
+echo "${ECHO_T}failed" >&6
+else
+ echo "$as_me:$LINENO: result: ok" >&5
+echo "${ECHO_T}ok" >&6
+fi
+
+echo "$as_me:$LINENO: checking for objdir" >&5
+echo $ECHO_N "checking for objdir... $ECHO_C" >&6
+if test "${lt_cv_objdir+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ rm -f .libs 2>/dev/null
+mkdir .libs 2>/dev/null
+if test -d .libs; then
+ lt_cv_objdir=.libs
+else
+ # MS-DOS does not allow filenames that begin with a dot.
+ lt_cv_objdir=_libs
+fi
+rmdir .libs 2>/dev/null
+fi
+echo "$as_me:$LINENO: result: $lt_cv_objdir" >&5
+echo "${ECHO_T}$lt_cv_objdir" >&6
+objdir=$lt_cv_objdir
+
+
+
+
+
+case $host_os in
+aix3*)
+ # AIX sometimes has problems with the GCC collect2 program. For some
+ # reason, if we set the COLLECT_NAMES environment variable, the problems
+ # vanish in a puff of smoke.
+ if test "X${COLLECT_NAMES+set}" != Xset; then
+ COLLECT_NAMES=
+ export COLLECT_NAMES
+ fi
+ ;;
+esac
+
+# Sed substitution that helps us do robust quoting. It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed='sed -e 1s/^X//'
+sed_quote_subst='s/\([\\"\\`$\\\\]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst='s/\([\\"\\`\\\\]\)/\\\1/g'
+
+# Sed substitution to delay expansion of an escaped shell variable in a
+# double_quote_subst'ed string.
+delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
+
+# Sed substitution to avoid accidental globbing in evaled expressions
+no_glob_subst='s/\*/\\\*/g'
+
+# Constants:
+rm="rm -f"
+
+# Global variables:
+default_ofile=libtool
+can_build_shared=yes
+
+# All known linkers require a `.a' archive for static linking (except MSVC,
+# which needs '.lib').
+libext=a
+ltmain="$ac_aux_dir/ltmain.sh"
+ofile="$default_ofile"
+with_gnu_ld="$lt_cv_prog_gnu_ld"
+
+if test -n "$ac_tool_prefix"; then
+ # Extract the first word of "${ac_tool_prefix}ar", so it can be a program name with args.
+set dummy ${ac_tool_prefix}ar; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_AR+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$AR"; then
+ ac_cv_prog_AR="$AR" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_AR="${ac_tool_prefix}ar"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+AR=$ac_cv_prog_AR
+if test -n "$AR"; then
+ echo "$as_me:$LINENO: result: $AR" >&5
+echo "${ECHO_T}$AR" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+fi
+if test -z "$ac_cv_prog_AR"; then
+ ac_ct_AR=$AR
+ # Extract the first word of "ar", so it can be a program name with args.
+set dummy ar; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_ac_ct_AR+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_AR"; then
+ ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_ac_ct_AR="ar"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+ test -z "$ac_cv_prog_ac_ct_AR" && ac_cv_prog_ac_ct_AR="false"
+fi
+fi
+ac_ct_AR=$ac_cv_prog_ac_ct_AR
+if test -n "$ac_ct_AR"; then
+ echo "$as_me:$LINENO: result: $ac_ct_AR" >&5
+echo "${ECHO_T}$ac_ct_AR" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ AR=$ac_ct_AR
+else
+ AR="$ac_cv_prog_AR"
+fi
+
+if test -n "$ac_tool_prefix"; then
+ # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
+set dummy ${ac_tool_prefix}ranlib; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_RANLIB+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$RANLIB"; then
+ ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+RANLIB=$ac_cv_prog_RANLIB
+if test -n "$RANLIB"; then
+ echo "$as_me:$LINENO: result: $RANLIB" >&5
+echo "${ECHO_T}$RANLIB" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+fi
+if test -z "$ac_cv_prog_RANLIB"; then
+ ac_ct_RANLIB=$RANLIB
+ # Extract the first word of "ranlib", so it can be a program name with args.
+set dummy ranlib; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_RANLIB"; then
+ ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_ac_ct_RANLIB="ranlib"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+ test -z "$ac_cv_prog_ac_ct_RANLIB" && ac_cv_prog_ac_ct_RANLIB=":"
+fi
+fi
+ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
+if test -n "$ac_ct_RANLIB"; then
+ echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5
+echo "${ECHO_T}$ac_ct_RANLIB" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ RANLIB=$ac_ct_RANLIB
+else
+ RANLIB="$ac_cv_prog_RANLIB"
+fi
+
+if test -n "$ac_tool_prefix"; then
+ # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args.
+set dummy ${ac_tool_prefix}strip; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_STRIP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$STRIP"; then
+ ac_cv_prog_STRIP="$STRIP" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_STRIP="${ac_tool_prefix}strip"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+fi
+fi
+STRIP=$ac_cv_prog_STRIP
+if test -n "$STRIP"; then
+ echo "$as_me:$LINENO: result: $STRIP" >&5
+echo "${ECHO_T}$STRIP" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+fi
+if test -z "$ac_cv_prog_STRIP"; then
+ ac_ct_STRIP=$STRIP
+ # Extract the first word of "strip", so it can be a program name with args.
+set dummy strip; ac_word=$2
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -n "$ac_ct_STRIP"; then
+ ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for ac_exec_ext in '' $ac_executable_extensions; do
+ if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+ ac_cv_prog_ac_ct_STRIP="strip"
+ echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+ break 2
+ fi
+done
+done
+
+ test -z "$ac_cv_prog_ac_ct_STRIP" && ac_cv_prog_ac_ct_STRIP=":"
+fi
+fi
+ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP
+if test -n "$ac_ct_STRIP"; then
+ echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5
+echo "${ECHO_T}$ac_ct_STRIP" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ STRIP=$ac_ct_STRIP
+else
+ STRIP="$ac_cv_prog_STRIP"
+fi
+
+
+old_CC="$CC"
+old_CFLAGS="$CFLAGS"
+
+# Set sane defaults for various variables
+test -z "$AR" && AR=ar
+test -z "$AR_FLAGS" && AR_FLAGS=cru
+test -z "$AS" && AS=as
+test -z "$CC" && CC=cc
+test -z "$LTCC" && LTCC=$CC
+test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+test -z "$LD" && LD=ld
+test -z "$LN_S" && LN_S="ln -s"
+test -z "$MAGIC_CMD" && MAGIC_CMD=file
+test -z "$NM" && NM=nm
+test -z "$SED" && SED=sed
+test -z "$OBJDUMP" && OBJDUMP=objdump
+test -z "$RANLIB" && RANLIB=:
+test -z "$STRIP" && STRIP=:
+test -z "$ac_objext" && ac_objext=o
+
+# Determine commands to create old-style static archives.
+old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs'
+old_postinstall_cmds='chmod 644 $oldlib'
+old_postuninstall_cmds=
+
+if test -n "$RANLIB"; then
+ case $host_os in
+ openbsd*)
+ old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib"
+ ;;
+ *)
+ old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib"
+ ;;
+ esac
+ old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib"
+fi
+
+for cc_temp in $compiler""; do
+ case $cc_temp in
+ compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
+ distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
+ \-*) ;;
+ *) break;;
+ esac
+done
+cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+
+
+# Only perform the check for file, if the check method requires it
+case $deplibs_check_method in
+file_magic*)
+ if test "$file_magic_cmd" = '$MAGIC_CMD'; then
+ echo "$as_me:$LINENO: checking for ${ac_tool_prefix}file" >&5
+echo $ECHO_N "checking for ${ac_tool_prefix}file... $ECHO_C" >&6
+if test "${lt_cv_path_MAGIC_CMD+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $MAGIC_CMD in
+[\\/*] | ?:[\\/]*)
+ lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+ ;;
+*)
+ lt_save_MAGIC_CMD="$MAGIC_CMD"
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+ ac_dummy="/usr/bin$PATH_SEPARATOR$PATH"
+ for ac_dir in $ac_dummy; do
+ IFS="$lt_save_ifs"
+ test -z "$ac_dir" && ac_dir=.
+ if test -f $ac_dir/${ac_tool_prefix}file; then
+ lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file"
+ if test -n "$file_magic_test_file"; then
+ case $deplibs_check_method in
+ "file_magic "*)
+ file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+ MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+ if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
+ $EGREP "$file_magic_regex" > /dev/null; then
+ :
+ else
+ cat <<EOF 1>&2
+
+*** Warning: the command libtool uses to detect shared libraries,
+*** $file_magic_cmd, produces output that libtool cannot recognize.
+*** The result is that libtool may fail to recognize shared libraries
+*** as such. This will affect the creation of libtool libraries that
+*** depend on shared libraries, but programs linked with such libtool
+*** libraries will work regardless of this problem. Nevertheless, you
+*** may want to report the problem to your system manager and/or to
+*** bug-libtool at gnu.org
+
+EOF
+ fi ;;
+ esac
+ fi
+ break
+ fi
+ done
+ IFS="$lt_save_ifs"
+ MAGIC_CMD="$lt_save_MAGIC_CMD"
+ ;;
+esac
+fi
+
+MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+if test -n "$MAGIC_CMD"; then
+ echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5
+echo "${ECHO_T}$MAGIC_CMD" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+if test -z "$lt_cv_path_MAGIC_CMD"; then
+ if test -n "$ac_tool_prefix"; then
+ echo "$as_me:$LINENO: checking for file" >&5
+echo $ECHO_N "checking for file... $ECHO_C" >&6
+if test "${lt_cv_path_MAGIC_CMD+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ case $MAGIC_CMD in
+[\\/*] | ?:[\\/]*)
+ lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+ ;;
+*)
+ lt_save_MAGIC_CMD="$MAGIC_CMD"
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+ ac_dummy="/usr/bin$PATH_SEPARATOR$PATH"
+ for ac_dir in $ac_dummy; do
+ IFS="$lt_save_ifs"
+ test -z "$ac_dir" && ac_dir=.
+ if test -f $ac_dir/file; then
+ lt_cv_path_MAGIC_CMD="$ac_dir/file"
+ if test -n "$file_magic_test_file"; then
+ case $deplibs_check_method in
+ "file_magic "*)
+ file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+ MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+ if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
+ $EGREP "$file_magic_regex" > /dev/null; then
+ :
+ else
+ cat <<EOF 1>&2
+
+*** Warning: the command libtool uses to detect shared libraries,
+*** $file_magic_cmd, produces output that libtool cannot recognize.
+*** The result is that libtool may fail to recognize shared libraries
+*** as such. This will affect the creation of libtool libraries that
+*** depend on shared libraries, but programs linked with such libtool
+*** libraries will work regardless of this problem. Nevertheless, you
+*** may want to report the problem to your system manager and/or to
+*** bug-libtool at gnu.org
+
+EOF
+ fi ;;
+ esac
+ fi
+ break
+ fi
+ done
+ IFS="$lt_save_ifs"
+ MAGIC_CMD="$lt_save_MAGIC_CMD"
+ ;;
+esac
+fi
+
+MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+if test -n "$MAGIC_CMD"; then
+ echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5
+echo "${ECHO_T}$MAGIC_CMD" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+
+ else
+ MAGIC_CMD=:
+ fi
+fi
+
+ fi
+ ;;
+esac
+
+enable_dlopen=no
+enable_win32_dll=no
+
+# Check whether --enable-libtool-lock or --disable-libtool-lock was given.
+if test "${enable_libtool_lock+set}" = set; then
+ enableval="$enable_libtool_lock"
+
+fi;
+test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
+
+
+# Check whether --with-pic or --without-pic was given.
+if test "${with_pic+set}" = set; then
+ withval="$with_pic"
+ pic_mode="$withval"
+else
+ pic_mode=default
+fi;
+test -z "$pic_mode" && pic_mode=default
+
+# Use C for the default configuration in the libtool script
+tagname=
+lt_save_CC="$CC"
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+# Source file extension for C test sources.
+ac_ext=c
+
+# Object file extension for compiled C test sources.
+objext=o
+objext=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="int some_variable = 0;\n"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='int main(){return(0);}\n'
+
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+
+
+# save warnings/boilerplate of simple test code
+ac_outfile=conftest.$ac_objext
+printf "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$rm conftest*
+
+ac_outfile=conftest.$ac_objext
+printf "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$rm conftest*
+
+
+
+lt_prog_compiler_no_builtin_flag=
+
+if test "$GCC" = yes; then
+ lt_prog_compiler_no_builtin_flag=' -fno-builtin'
+
+
+echo "$as_me:$LINENO: checking if $compiler supports -fno-rtti -fno-exceptions" >&5
+echo $ECHO_N "checking if $compiler supports -fno-rtti -fno-exceptions... $ECHO_C" >&6
+if test "${lt_cv_prog_compiler_rtti_exceptions+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_cv_prog_compiler_rtti_exceptions=no
+ ac_outfile=conftest.$ac_objext
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+ lt_compiler_flag="-fno-rtti -fno-exceptions"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ # The option is referenced via a variable to avoid confusing sed.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:6606: $lt_compile\"" >&5)
+ (eval "$lt_compile" 2>conftest.err)
+ ac_status=$?
+ cat conftest.err >&5
+ echo "$as_me:6610: \$? = $ac_status" >&5
+ if (exit $ac_status) && test -s "$ac_outfile"; then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings other than the usual output.
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+ lt_cv_prog_compiler_rtti_exceptions=yes
+ fi
+ fi
+ $rm conftest*
+
+fi
+echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_rtti_exceptions" >&5
+echo "${ECHO_T}$lt_cv_prog_compiler_rtti_exceptions" >&6
+
+if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then
+ lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions"
+else
+ :
+fi
+
+fi
+
+lt_prog_compiler_wl=
+lt_prog_compiler_pic=
+lt_prog_compiler_static=
+
+echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
+echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6
+
+ if test "$GCC" = yes; then
+ lt_prog_compiler_wl='-Wl,'
+ lt_prog_compiler_static='-static'
+
+ case $host_os in
+ aix*)
+ # All AIX code is PIC.
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ lt_prog_compiler_static='-Bstatic'
+ fi
+ ;;
+
+ amigaos*)
+ # FIXME: we need at least 68020 code to build shared libraries, but
+ # adding the `-m68020' flag to GCC prevents building anything better,
+ # like `-m68040'.
+ lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4'
+ ;;
+
+ beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+ # PIC is the default for these OSes.
+ ;;
+
+ mingw* | pw32* | os2*)
+ # This hack is so that the source file can tell whether it is being
+ # built for inclusion in a dll (and should export symbols for example).
+ lt_prog_compiler_pic='-DDLL_EXPORT'
+ ;;
+
+ darwin* | rhapsody*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ lt_prog_compiler_pic='-fno-common'
+ ;;
+
+ interix3*)
+ # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+ # Instead, we relocate shared libraries at runtime.
+ ;;
+
+ msdosdjgpp*)
+ # Just because we use GCC doesn't mean we suddenly get shared libraries
+ # on systems that don't support them.
+ lt_prog_compiler_can_build_shared=no
+ enable_shared=no
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec; then
+ lt_prog_compiler_pic=-Kconform_pic
+ fi
+ ;;
+
+ hpux*)
+ # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+ # not for PA HP-UX.
+ case $host_cpu in
+ hppa*64*|ia64*)
+ # +Z the default
+ ;;
+ *)
+ lt_prog_compiler_pic='-fPIC'
+ ;;
+ esac
+ ;;
+
+ *)
+ lt_prog_compiler_pic='-fPIC'
+ ;;
+ esac
+ else
+ # PORTME Check for flag to pass linker flags through the system compiler.
+ case $host_os in
+ aix*)
+ lt_prog_compiler_wl='-Wl,'
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ lt_prog_compiler_static='-Bstatic'
+ else
+ lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp'
+ fi
+ ;;
+ darwin*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ case $cc_basename in
+ xlc*)
+ lt_prog_compiler_pic='-qnocommon'
+ lt_prog_compiler_wl='-Wl,'
+ ;;
+ esac
+ ;;
+
+ mingw* | pw32* | os2*)
+ # This hack is so that the source file can tell whether it is being
+ # built for inclusion in a dll (and should export symbols for example).
+ lt_prog_compiler_pic='-DDLL_EXPORT'
+ ;;
+
+ hpux9* | hpux10* | hpux11*)
+ lt_prog_compiler_wl='-Wl,'
+ # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+ # not for PA HP-UX.
+ case $host_cpu in
+ hppa*64*|ia64*)
+ # +Z the default
+ ;;
+ *)
+ lt_prog_compiler_pic='+Z'
+ ;;
+ esac
+ # Is there a better lt_prog_compiler_static that works with the bundled CC?
+ lt_prog_compiler_static='${wl}-a ${wl}archive'
+ ;;
+
+ irix5* | irix6* | nonstopux*)
+ lt_prog_compiler_wl='-Wl,'
+ # PIC (with -KPIC) is the default.
+ lt_prog_compiler_static='-non_shared'
+ ;;
+
+ newsos6)
+ lt_prog_compiler_pic='-KPIC'
+ lt_prog_compiler_static='-Bstatic'
+ ;;
+
+ linux*)
+ case $cc_basename in
+ icc* | ecc*)
+ lt_prog_compiler_wl='-Wl,'
+ lt_prog_compiler_pic='-KPIC'
+ lt_prog_compiler_static='-static'
+ ;;
+ pgcc* | pgf77* | pgf90* | pgf95*)
+ # Portland Group compilers (*not* the Pentium gcc compiler,
+ # which looks to be a dead project)
+ lt_prog_compiler_wl='-Wl,'
+ lt_prog_compiler_pic='-fpic'
+ lt_prog_compiler_static='-Bstatic'
+ ;;
+ ccc*)
+ lt_prog_compiler_wl='-Wl,'
+ # All Alpha code is PIC.
+ lt_prog_compiler_static='-non_shared'
+ ;;
+ esac
+ ;;
+
+ osf3* | osf4* | osf5*)
+ lt_prog_compiler_wl='-Wl,'
+ # All OSF/1 code is PIC.
+ lt_prog_compiler_static='-non_shared'
+ ;;
+
+ solaris*)
+ lt_prog_compiler_pic='-KPIC'
+ lt_prog_compiler_static='-Bstatic'
+ case $cc_basename in
+ f77* | f90* | f95*)
+ lt_prog_compiler_wl='-Qoption ld ';;
+ *)
+ lt_prog_compiler_wl='-Wl,';;
+ esac
+ ;;
+
+ sunos4*)
+ lt_prog_compiler_wl='-Qoption ld '
+ lt_prog_compiler_pic='-PIC'
+ lt_prog_compiler_static='-Bstatic'
+ ;;
+
+ sysv4 | sysv4.2uw2* | sysv4.3*)
+ lt_prog_compiler_wl='-Wl,'
+ lt_prog_compiler_pic='-KPIC'
+ lt_prog_compiler_static='-Bstatic'
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec ;then
+ lt_prog_compiler_pic='-Kconform_pic'
+ lt_prog_compiler_static='-Bstatic'
+ fi
+ ;;
+
+ sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+ lt_prog_compiler_wl='-Wl,'
+ lt_prog_compiler_pic='-KPIC'
+ lt_prog_compiler_static='-Bstatic'
+ ;;
+
+ unicos*)
+ lt_prog_compiler_wl='-Wl,'
+ lt_prog_compiler_can_build_shared=no
+ ;;
+
+ uts4*)
+ lt_prog_compiler_pic='-pic'
+ lt_prog_compiler_static='-Bstatic'
+ ;;
+
+ *)
+ lt_prog_compiler_can_build_shared=no
+ ;;
+ esac
+ fi
+
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic" >&6
+
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$lt_prog_compiler_pic"; then
+
+echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5
+echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic works... $ECHO_C" >&6
+if test "${lt_prog_compiler_pic_works+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_prog_compiler_pic_works=no
+ ac_outfile=conftest.$ac_objext
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+ lt_compiler_flag="$lt_prog_compiler_pic -DPIC"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ # The option is referenced via a variable to avoid confusing sed.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:6874: $lt_compile\"" >&5)
+ (eval "$lt_compile" 2>conftest.err)
+ ac_status=$?
+ cat conftest.err >&5
+ echo "$as_me:6878: \$? = $ac_status" >&5
+ if (exit $ac_status) && test -s "$ac_outfile"; then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings other than the usual output.
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+ lt_prog_compiler_pic_works=yes
+ fi
+ fi
+ $rm conftest*
+
+fi
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_works" >&6
+
+if test x"$lt_prog_compiler_pic_works" = xyes; then
+ case $lt_prog_compiler_pic in
+ "" | " "*) ;;
+ *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;;
+ esac
+else
+ lt_prog_compiler_pic=
+ lt_prog_compiler_can_build_shared=no
+fi
+
+fi
+case $host_os in
+ # For platforms which do not support PIC, -DPIC is meaningless:
+ *djgpp*)
+ lt_prog_compiler_pic=
+ ;;
+ *)
+ lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC"
+ ;;
+esac
+
+#
+# Check to make sure the static flag actually works.
+#
+wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\"
+echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
+echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6
+if test "${lt_prog_compiler_static_works+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_prog_compiler_static_works=no
+ save_LDFLAGS="$LDFLAGS"
+ LDFLAGS="$LDFLAGS $lt_tmp_static_flag"
+ printf "$lt_simple_link_test_code" > conftest.$ac_ext
+ if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+ # The linker can only warn and ignore the option if not recognized
+ # So say no if there are warnings
+ if test -s conftest.err; then
+ # Append any errors to the config.log.
+ cat conftest.err 1>&5
+ $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if diff conftest.exp conftest.er2 >/dev/null; then
+ lt_prog_compiler_static_works=yes
+ fi
+ else
+ lt_prog_compiler_static_works=yes
+ fi
+ fi
+ $rm conftest*
+ LDFLAGS="$save_LDFLAGS"
+
+fi
+echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works" >&5
+echo "${ECHO_T}$lt_prog_compiler_static_works" >&6
+
+if test x"$lt_prog_compiler_static_works" = xyes; then
+ :
+else
+ lt_prog_compiler_static=
+fi
+
+
+echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
+echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6
+if test "${lt_cv_prog_compiler_c_o+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_cv_prog_compiler_c_o=no
+ $rm -r conftest 2>/dev/null
+ mkdir conftest
+ cd conftest
+ mkdir out
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+ lt_compiler_flag="-o out/conftest2.$ac_objext"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:6978: $lt_compile\"" >&5)
+ (eval "$lt_compile" 2>out/conftest.err)
+ ac_status=$?
+ cat out/conftest.err >&5
+ echo "$as_me:6982: \$? = $ac_status" >&5
+ if (exit $ac_status) && test -s out/conftest2.$ac_objext
+ then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
+ $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+ if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+ lt_cv_prog_compiler_c_o=yes
+ fi
+ fi
+ chmod u+w . 2>&5
+ $rm conftest*
+ # SGI C++ compiler will create directory out/ii_files/ for
+ # template instantiation
+ test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files
+ $rm out/* && rmdir out
+ cd ..
+ rmdir conftest
+ $rm conftest*
+
+fi
+echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o" >&5
+echo "${ECHO_T}$lt_cv_prog_compiler_c_o" >&6
+
+
+hard_links="nottested"
+if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then
+ # do not overwrite the value of need_locks provided by the user
+ echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
+echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6
+ hard_links=yes
+ $rm conftest*
+ ln conftest.a conftest.b 2>/dev/null && hard_links=no
+ touch conftest.a
+ ln conftest.a conftest.b 2>&5 || hard_links=no
+ ln conftest.a conftest.b 2>/dev/null && hard_links=no
+ echo "$as_me:$LINENO: result: $hard_links" >&5
+echo "${ECHO_T}$hard_links" >&6
+ if test "$hard_links" = no; then
+ { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
+echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
+ need_locks=warn
+ fi
+else
+ need_locks=no
+fi
+
+echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6
+
+ runpath_var=
+ allow_undefined_flag=
+ enable_shared_with_static_runtimes=no
+ archive_cmds=
+ archive_expsym_cmds=
+ old_archive_From_new_cmds=
+ old_archive_from_expsyms_cmds=
+ export_dynamic_flag_spec=
+ whole_archive_flag_spec=
+ thread_safe_flag_spec=
+ hardcode_libdir_flag_spec=
+ hardcode_libdir_flag_spec_ld=
+ hardcode_libdir_separator=
+ hardcode_direct=no
+ hardcode_minus_L=no
+ hardcode_shlibpath_var=unsupported
+ link_all_deplibs=unknown
+ hardcode_automatic=no
+ module_cmds=
+ module_expsym_cmds=
+ always_export_symbols=no
+ export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+ # include_expsyms should be a list of space-separated symbols to be *always*
+ # included in the symbol list
+ include_expsyms=
+ # exclude_expsyms can be an extended regexp of symbols to exclude
+ # it will be wrapped by ` (' and `)$', so one must not match beginning or
+ # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
+ # as well as any symbol that contains `d'.
+ exclude_expsyms="_GLOBAL_OFFSET_TABLE_"
+ # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
+ # platforms (ab)use it in PIC code, but their linkers get confused if
+ # the symbol is explicitly referenced. Since portable code cannot
+ # rely on this symbol name, it's probably fine to never include it in
+ # preloaded symbol tables.
+ extract_expsyms_cmds=
+ # Just being paranoid about ensuring that cc_basename is set.
+ for cc_temp in $compiler""; do
+ case $cc_temp in
+ compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
+ distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
+ \-*) ;;
+ *) break;;
+ esac
+done
+cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+
+ case $host_os in
+ cygwin* | mingw* | pw32*)
+ # FIXME: the MSVC++ port hasn't been tested in a loooong time
+ # When not using gcc, we currently assume that we are using
+ # Microsoft Visual C++.
+ if test "$GCC" != yes; then
+ with_gnu_ld=no
+ fi
+ ;;
+ interix*)
+ # we just hope/assume this is gcc and not c89 (= MSVC++)
+ with_gnu_ld=yes
+ ;;
+ openbsd*)
+ with_gnu_ld=no
+ ;;
+ esac
+
+ ld_shlibs=yes
+ if test "$with_gnu_ld" = yes; then
+ # If archive_cmds runs LD, not CC, wlarc should be empty
+ wlarc='${wl}'
+
+ # Set some defaults for GNU ld with shared library support. These
+ # are reset later if shared libraries are not supported. Putting them
+ # here allows them to be overridden if necessary.
+ runpath_var=LD_RUN_PATH
+ hardcode_libdir_flag_spec='${wl}--rpath ${wl}$libdir'
+ export_dynamic_flag_spec='${wl}--export-dynamic'
+ # ancient GNU ld didn't support --whole-archive et. al.
+ if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
+ whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+ else
+ whole_archive_flag_spec=
+ fi
+ supports_anon_versioning=no
+ case `$LD -v 2>/dev/null` in
+ *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
+ *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+ *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+ *\ 2.11.*) ;; # other 2.11 versions
+ *) supports_anon_versioning=yes ;;
+ esac
+
+ # See if GNU ld supports shared libraries.
+ case $host_os in
+ aix3* | aix4* | aix5*)
+ # On AIX/PPC, the GNU linker is very broken
+ if test "$host_cpu" != ia64; then
+ ld_shlibs=no
+ cat <<EOF 1>&2
+
+*** Warning: the GNU linker, at least up to release 2.9.1, is reported
+*** to be unable to reliably create shared libraries on AIX.
+*** Therefore, libtool is disabling shared libraries support. If you
+*** really care for shared libraries, you may want to modify your PATH
+*** so that a non-GNU linker is found, and then restart.
+
+EOF
+ fi
+ ;;
+
+ amigaos*)
+ archive_cmds='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+ hardcode_libdir_flag_spec='-L$libdir'
+ hardcode_minus_L=yes
+
+ # Samuel A. Falvo II <kc5tja at dolphin.openprojects.net> reports
+ # that the semantics of dynamic libraries on AmigaOS, at least up
+ # to version 4, is to share data among multiple programs linked
+ # with the same dynamic library. Since this doesn't match the
+ # behavior of shared libraries on other platforms, we can't use
+ # them.
+ ld_shlibs=no
+ ;;
+
+ beos*)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ allow_undefined_flag=unsupported
+ # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+ # support --undefined. This deserves some investigation. FIXME
+ archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ else
+ ld_shlibs=no
+ fi
+ ;;
+
+ cygwin* | mingw* | pw32*)
+ # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless,
+ # as there is no search path for DLLs.
+ hardcode_libdir_flag_spec='-L$libdir'
+ allow_undefined_flag=unsupported
+ always_export_symbols=no
+ enable_shared_with_static_runtimes=yes
+ export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols'
+
+ if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
+ archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ # If the export-symbols file already is a .def file (1st line
+ # is EXPORTS), use it as is; otherwise, prepend...
+ archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+ cp $export_symbols $output_objdir/$soname.def;
+ else
+ echo EXPORTS > $output_objdir/$soname.def;
+ cat $export_symbols >> $output_objdir/$soname.def;
+ fi~
+ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ else
+ ld_shlibs=no
+ fi
+ ;;
+
+ interix3*)
+ hardcode_direct=no
+ hardcode_shlibpath_var=no
+ hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
+ export_dynamic_flag_spec='${wl}-E'
+ # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+ # Instead, shared libraries are loaded at an image base (0x10000000 by
+ # default) and relocated if they conflict, which is a slow very memory
+ # consuming and fragmenting process. To avoid this, we pick a random,
+ # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+ # time. Moving up from 0x10000000 also allows more sbrk(2) space.
+ archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ ;;
+
+ linux*)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ tmp_addflag=
+ case $cc_basename,$host_cpu in
+ pgcc*) # Portland Group C compiler
+ whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+ tmp_addflag=' $pic_flag'
+ ;;
+ pgf77* | pgf90* | pgf95*) # Portland Group f77 and f90 compilers
+ whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+ tmp_addflag=' $pic_flag -Mnomain' ;;
+ ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64
+ tmp_addflag=' -i_dynamic' ;;
+ efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64
+ tmp_addflag=' -i_dynamic -nofor_main' ;;
+ ifc* | ifort*) # Intel Fortran compiler
+ tmp_addflag=' -nofor_main' ;;
+ esac
+ archive_cmds='$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+
+ if test $supports_anon_versioning = yes; then
+ archive_expsym_cmds='$echo "{ global:" > $output_objdir/$libname.ver~
+ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+ $echo "local: *; };" >> $output_objdir/$libname.ver~
+ $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+ fi
+ else
+ ld_shlibs=no
+ fi
+ ;;
+
+ netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
+ wlarc=
+ else
+ archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ fi
+ ;;
+
+ solaris*)
+ if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
+ ld_shlibs=no
+ cat <<EOF 1>&2
+
+*** Warning: The releases 2.8.* of the GNU linker cannot reliably
+*** create shared libraries on Solaris systems. Therefore, libtool
+*** is disabling shared libraries support. We urge you to upgrade GNU
+*** binutils to release 2.9.1 or newer. Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+EOF
+ elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ else
+ ld_shlibs=no
+ fi
+ ;;
+
+ sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
+ case `$LD -v 2>&1` in
+ *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*)
+ ld_shlibs=no
+ cat <<_LT_EOF 1>&2
+
+*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
+*** reliably create shared libraries on SCO systems. Therefore, libtool
+*** is disabling shared libraries support. We urge you to upgrade GNU
+*** binutils to release 2.16.91.0.3 or newer. Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+ ;;
+ *)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ hardcode_libdir_flag_spec='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`'
+ archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib'
+ archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file,$export_symbols -o $lib'
+ else
+ ld_shlibs=no
+ fi
+ ;;
+ esac
+ ;;
+
+ sunos4*)
+ archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ wlarc=
+ hardcode_direct=yes
+ hardcode_shlibpath_var=no
+ ;;
+
+ *)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ else
+ ld_shlibs=no
+ fi
+ ;;
+ esac
+
+ if test "$ld_shlibs" = no; then
+ runpath_var=
+ hardcode_libdir_flag_spec=
+ export_dynamic_flag_spec=
+ whole_archive_flag_spec=
+ fi
+ else
+ # PORTME fill in a description of your system's linker (not GNU ld)
+ case $host_os in
+ aix3*)
+ allow_undefined_flag=unsupported
+ always_export_symbols=yes
+ archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
+ # Note: this linker hardcodes the directories in LIBPATH if there
+ # are no directories specified by -L.
+ hardcode_minus_L=yes
+ if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+ # Neither direct hardcoding nor static linking is supported with a
+ # broken collect2.
+ hardcode_direct=unsupported
+ fi
+ ;;
+
+ aix4* | aix5*)
+ if test "$host_cpu" = ia64; then
+ # On IA64, the linker does run time linking by default, so we don't
+ # have to do anything special.
+ aix_use_runtimelinking=no
+ exp_sym_flag='-Bexport'
+ no_entry_flag=""
+ else
+ # If we're using GNU nm, then we don't want the "-C" option.
+ # -C means demangle to AIX nm, but means don't demangle with GNU nm
+ if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
+ export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
+ else
+ export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
+ fi
+ aix_use_runtimelinking=no
+
+ # Test if we are trying to use run time linking or normal
+ # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+ # need to do runtime linking.
+ case $host_os in aix4.[23]|aix4.[23].*|aix5*)
+ for ld_flag in $LDFLAGS; do
+ if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+ aix_use_runtimelinking=yes
+ break
+ fi
+ done
+ ;;
+ esac
+
+ exp_sym_flag='-bexport'
+ no_entry_flag='-bnoentry'
+ fi
+
+ # When large executables or shared objects are built, AIX ld can
+ # have problems creating the table of contents. If linking a library
+ # or program results in "error TOC overflow" add -mminimal-toc to
+ # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not
+ # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+ archive_cmds=''
+ hardcode_direct=yes
+ hardcode_libdir_separator=':'
+ link_all_deplibs=yes
+
+ if test "$GCC" = yes; then
+ case $host_os in aix4.[012]|aix4.[012].*)
+ # We only want to do this on AIX 4.2 and lower, the check
+ # below for broken collect2 doesn't work under 4.3+
+ collect2name=`${CC} -print-prog-name=collect2`
+ if test -f "$collect2name" && \
+ strings "$collect2name" | grep resolve_lib_name >/dev/null
+ then
+ # We have reworked collect2
+ hardcode_direct=yes
+ else
+ # We have old collect2
+ hardcode_direct=unsupported
+ # It fails to find uninstalled libraries when the uninstalled
+ # path is not listed in the libpath. Setting hardcode_minus_L
+ # to unsupported forces relinking
+ hardcode_minus_L=yes
+ hardcode_libdir_flag_spec='-L$libdir'
+ hardcode_libdir_separator=
+ fi
+ ;;
+ esac
+ shared_flag='-shared'
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag="$shared_flag "'${wl}-G'
+ fi
+ else
+ # not using gcc
+ if test "$host_cpu" = ia64; then
+ # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+ # chokes on -Wl,-G. The following line is correct:
+ shared_flag='-G'
+ else
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag='${wl}-G'
+ else
+ shared_flag='${wl}-bM:SRE'
+ fi
+ fi
+ fi
+
+ # It seems that -bexpall does not export symbols beginning with
+ # underscore (_), so it is better to generate a list of symbols to export.
+ always_export_symbols=yes
+ if test "$aix_use_runtimelinking" = yes; then
+ # Warning - without using the other runtime loading flags (-brtl),
+ # -berok will link without error, but may produce a broken library.
+ allow_undefined_flag='-berok'
+ # Determine the default libpath from the value encoded in an empty executable.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`; fi
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+
+ hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath"
+ archive_expsym_cmds="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+ else
+ if test "$host_cpu" = ia64; then
+ hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib'
+ allow_undefined_flag="-z nodefs"
+ archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+ else
+ # Determine the default libpath from the value encoded in an empty executable.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`; fi
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+
+ hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath"
+ # Warning - without using the other run time loading flags,
+ # -berok will link without error, but may produce a broken library.
+ no_undefined_flag=' ${wl}-bernotok'
+ allow_undefined_flag=' ${wl}-berok'
+ # Exported symbols can be pulled into shared objects from archives
+ whole_archive_flag_spec='$convenience'
+ archive_cmds_need_lc=yes
+ # This is similar to how AIX traditionally builds its shared libraries.
+ archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+ fi
+ fi
+ ;;
+
+ amigaos*)
+ archive_cmds='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+ hardcode_libdir_flag_spec='-L$libdir'
+ hardcode_minus_L=yes
+ # see comment about different semantics on the GNU ld section
+ ld_shlibs=no
+ ;;
+
+ bsdi[45]*)
+ export_dynamic_flag_spec=-rdynamic
+ ;;
+
+ cygwin* | mingw* | pw32*)
+ # When not using gcc, we currently assume that we are using
+ # Microsoft Visual C++.
+ # hardcode_libdir_flag_spec is actually meaningless, as there is
+ # no search path for DLLs.
+ hardcode_libdir_flag_spec=' '
+ allow_undefined_flag=unsupported
+ # Tell ltmain to make .lib files, not .a files.
+ libext=lib
+ # Tell ltmain to make .dll files, not .so files.
+ shrext_cmds=".dll"
+ # FIXME: Setting linknames here is a bad hack.
+ archive_cmds='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames='
+ # The linker will automatically build a .lib file if we build a DLL.
+ old_archive_From_new_cmds='true'
+ # FIXME: Should let the user specify the lib program.
+ old_archive_cmds='lib /OUT:$oldlib$oldobjs$old_deplibs'
+ fix_srcfile_path='`cygpath -w "$srcfile"`'
+ enable_shared_with_static_runtimes=yes
+ ;;
+
+ darwin* | rhapsody*)
+ case $host_os in
+ rhapsody* | darwin1.[012])
+ allow_undefined_flag='${wl}-undefined ${wl}suppress'
+ ;;
+ *) # Darwin 1.3 on
+ if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
+ allow_undefined_flag='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ else
+ case ${MACOSX_DEPLOYMENT_TARGET} in
+ 10.[012])
+ allow_undefined_flag='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ ;;
+ 10.*)
+ allow_undefined_flag='${wl}-undefined ${wl}dynamic_lookup'
+ ;;
+ esac
+ fi
+ ;;
+ esac
+ archive_cmds_need_lc=no
+ hardcode_direct=no
+ hardcode_automatic=yes
+ hardcode_shlibpath_var=unsupported
+ whole_archive_flag_spec=''
+ link_all_deplibs=yes
+ if test "$GCC" = yes ; then
+ output_verbose_link_cmd='echo'
+ archive_cmds='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
+ module_cmds='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ archive_expsym_cmds='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ module_expsym_cmds='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ else
+ case $cc_basename in
+ xlc*)
+ output_verbose_link_cmd='echo'
+ archive_cmds='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
+ module_cmds='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ archive_expsym_cmds='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ module_expsym_cmds='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ ;;
+ *)
+ ld_shlibs=no
+ ;;
+ esac
+ fi
+ ;;
+
+ dgux*)
+ archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_libdir_flag_spec='-L$libdir'
+ hardcode_shlibpath_var=no
+ ;;
+
+ freebsd1*)
+ ld_shlibs=no
+ ;;
+
+ # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
+ # support. Future versions do this automatically, but an explicit c++rt0.o
+ # does not break anything, and helps significantly (at the cost of a little
+ # extra space).
+ freebsd2.2*)
+ archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
+ hardcode_libdir_flag_spec='-R$libdir'
+ hardcode_direct=yes
+ hardcode_shlibpath_var=no
+ ;;
+
+ # Unfortunately, older versions of FreeBSD 2 do not have this feature.
+ freebsd2*)
+ archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_direct=yes
+ hardcode_minus_L=yes
+ hardcode_shlibpath_var=no
+ ;;
+
+ # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
+ freebsd* | kfreebsd*-gnu | dragonfly*)
+ archive_cmds='$CC -shared -o $lib $libobjs $deplibs $compiler_flags'
+ hardcode_libdir_flag_spec='-R$libdir'
+ hardcode_direct=yes
+ hardcode_shlibpath_var=no
+ ;;
+
+ hpux9*)
+ if test "$GCC" = yes; then
+ archive_cmds='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ else
+ archive_cmds='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ fi
+ hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+ hardcode_libdir_separator=:
+ hardcode_direct=yes
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ hardcode_minus_L=yes
+ export_dynamic_flag_spec='${wl}-E'
+ ;;
+
+ hpux10*)
+ if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+ archive_cmds='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
+ fi
+ if test "$with_gnu_ld" = no; then
+ hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+ hardcode_libdir_separator=:
+
+ hardcode_direct=yes
+ export_dynamic_flag_spec='${wl}-E'
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ hardcode_minus_L=yes
+ fi
+ ;;
+
+ hpux11*)
+ if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+ case $host_cpu in
+ hppa*64*)
+ archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ ia64*)
+ archive_cmds='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ archive_cmds='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ else
+ case $host_cpu in
+ hppa*64*)
+ archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ ia64*)
+ archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ fi
+ if test "$with_gnu_ld" = no; then
+ hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+ hardcode_libdir_separator=:
+
+ case $host_cpu in
+ hppa*64*|ia64*)
+ hardcode_libdir_flag_spec_ld='+b $libdir'
+ hardcode_direct=no
+ hardcode_shlibpath_var=no
+ ;;
+ *)
+ hardcode_direct=yes
+ export_dynamic_flag_spec='${wl}-E'
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ hardcode_minus_L=yes
+ ;;
+ esac
+ fi
+ ;;
+
+ irix5* | irix6* | nonstopux*)
+ if test "$GCC" = yes; then
+ archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ else
+ archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ hardcode_libdir_flag_spec_ld='-rpath $libdir'
+ fi
+ hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator=:
+ link_all_deplibs=yes
+ ;;
+
+ netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out
+ else
+ archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF
+ fi
+ hardcode_libdir_flag_spec='-R$libdir'
+ hardcode_direct=yes
+ hardcode_shlibpath_var=no
+ ;;
+
+ newsos6)
+ archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_direct=yes
+ hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator=:
+ hardcode_shlibpath_var=no
+ ;;
+
+ openbsd*)
+ hardcode_direct=yes
+ hardcode_shlibpath_var=no
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
+ hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
+ export_dynamic_flag_spec='${wl}-E'
+ else
+ case $host_os in
+ openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*)
+ archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_libdir_flag_spec='-R$libdir'
+ ;;
+ *)
+ archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+ hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
+ ;;
+ esac
+ fi
+ ;;
+
+ os2*)
+ hardcode_libdir_flag_spec='-L$libdir'
+ hardcode_minus_L=yes
+ allow_undefined_flag=unsupported
+ archive_cmds='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
+ old_archive_From_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
+ ;;
+
+ osf3*)
+ if test "$GCC" = yes; then
+ allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*'
+ archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ else
+ allow_undefined_flag=' -expect_unresolved \*'
+ archive_cmds='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ fi
+ hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator=:
+ ;;
+
+ osf4* | osf5*) # as osf3* with the addition of -msym flag
+ if test "$GCC" = yes; then
+ allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*'
+ archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+ else
+ allow_undefined_flag=' -expect_unresolved \*'
+ archive_cmds='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~
+ $LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp'
+
+ # Both c and cxx compiler support -rpath directly
+ hardcode_libdir_flag_spec='-rpath $libdir'
+ fi
+ hardcode_libdir_separator=:
+ ;;
+
+ solaris*)
+ no_undefined_flag=' -z text'
+ if test "$GCC" = yes; then
+ wlarc='${wl}'
+ archive_cmds='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp'
+ else
+ wlarc=''
+ archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ archive_expsym_cmds='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
+ fi
+ hardcode_libdir_flag_spec='-R$libdir'
+ hardcode_shlibpath_var=no
+ case $host_os in
+ solaris2.[0-5] | solaris2.[0-5].*) ;;
+ *)
+ # The compiler driver will combine linker options so we
+ # cannot just pass the convience library names through
+ # without $wl, iff we do not link with $LD.
+ # Luckily, gcc supports the same syntax we need for Sun Studio.
+ # Supported since Solaris 2.6 (maybe 2.5.1?)
+ case $wlarc in
+ '')
+ whole_archive_flag_spec='-z allextract$convenience -z defaultextract' ;;
+ *)
+ whole_archive_flag_spec='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract' ;;
+ esac ;;
+ esac
+ link_all_deplibs=yes
+ ;;
+
+ sunos4*)
+ if test "x$host_vendor" = xsequent; then
+ # Use $CC to link under sequent, because it throws in some extra .o
+ # files that make .init and .fini sections work.
+ archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
+ fi
+ hardcode_libdir_flag_spec='-L$libdir'
+ hardcode_direct=yes
+ hardcode_minus_L=yes
+ hardcode_shlibpath_var=no
+ ;;
+
+ sysv4)
+ case $host_vendor in
+ sni)
+ archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_direct=yes # is this really true???
+ ;;
+ siemens)
+ ## LD is ld it makes a PLAMLIB
+ ## CC just makes a GrossModule.
+ archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+ reload_cmds='$CC -r -o $output$reload_objs'
+ hardcode_direct=no
+ ;;
+ motorola)
+ archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_direct=no #Motorola manual says yes, but my tests say they lie
+ ;;
+ esac
+ runpath_var='LD_RUN_PATH'
+ hardcode_shlibpath_var=no
+ ;;
+
+ sysv4.3*)
+ archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_shlibpath_var=no
+ export_dynamic_flag_spec='-Bexport'
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec; then
+ archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_shlibpath_var=no
+ runpath_var=LD_RUN_PATH
+ hardcode_runpath_var=yes
+ ld_shlibs=yes
+ fi
+ ;;
+
+ sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7*)
+ no_undefined_flag='${wl}-z,text'
+ archive_cmds_need_lc=no
+ hardcode_shlibpath_var=no
+ runpath_var='LD_RUN_PATH'
+
+ if test "$GCC" = yes; then
+ archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ fi
+ ;;
+
+ sysv5* | sco3.2v5* | sco5v6*)
+ # Note: We can NOT use -z defs as we might desire, because we do not
+ # link with -lc, and that would cause any symbols used from libc to
+ # always be unresolved, which means just about no library would
+ # ever link correctly. If we're not using GNU ld we use -z text
+ # though, which does catch some bad symbols but isn't as heavy-handed
+ # as -z defs.
+ no_undefined_flag='${wl}-z,text'
+ allow_undefined_flag='${wl}-z,nodefs'
+ archive_cmds_need_lc=no
+ hardcode_shlibpath_var=no
+ hardcode_libdir_flag_spec='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
+ hardcode_libdir_separator=':'
+ link_all_deplibs=yes
+ export_dynamic_flag_spec='${wl}-Bexport'
+ runpath_var='LD_RUN_PATH'
+
+ if test "$GCC" = yes; then
+ archive_cmds='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ archive_cmds='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ fi
+ ;;
+
+ uts4*)
+ archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_libdir_flag_spec='-L$libdir'
+ hardcode_shlibpath_var=no
+ ;;
+
+ *)
+ ld_shlibs=no
+ ;;
+ esac
+ fi
+
+echo "$as_me:$LINENO: result: $ld_shlibs" >&5
+echo "${ECHO_T}$ld_shlibs" >&6
+test "$ld_shlibs" = no && can_build_shared=no
+
+#
+# Do we need to explicitly link libc?
+#
+case "x$archive_cmds_need_lc" in
+x|xyes)
+ # Assume -lc should be added
+ archive_cmds_need_lc=yes
+
+ if test "$enable_shared" = yes && test "$GCC" = yes; then
+ case $archive_cmds in
+ *'~'*)
+ # FIXME: we may have to deal with multi-command sequences.
+ ;;
+ '$CC '*)
+ # Test whether the compiler implicitly links with -lc since on some
+ # systems, -lgcc has to come before -lc. If gcc already passes -lc
+ # to ld, don't add -lc before -lgcc.
+ echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
+echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6
+ $rm conftest*
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } 2>conftest.err; then
+ soname=conftest
+ lib=conftest
+ libobjs=conftest.$ac_objext
+ deplibs=
+ wl=$lt_prog_compiler_wl
+ pic_flag=$lt_prog_compiler_pic
+ compiler_flags=-v
+ linker_flags=-v
+ verstring=
+ output_objdir=.
+ libname=conftest
+ lt_save_allow_undefined_flag=$allow_undefined_flag
+ allow_undefined_flag=
+ if { (eval echo "$as_me:$LINENO: \"$archive_cmds 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5
+ (eval $archive_cmds 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+ then
+ archive_cmds_need_lc=no
+ else
+ archive_cmds_need_lc=yes
+ fi
+ allow_undefined_flag=$lt_save_allow_undefined_flag
+ else
+ cat conftest.err 1>&5
+ fi
+ $rm conftest*
+ echo "$as_me:$LINENO: result: $archive_cmds_need_lc" >&5
+echo "${ECHO_T}$archive_cmds_need_lc" >&6
+ ;;
+ esac
+ fi
+ ;;
+esac
+
+echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
+echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
+ # if the path contains ";" then we assume it to be the separator
+ # otherwise default to the standard path separator (i.e. ":") - it is
+ # assumed that no part of a normal pathname contains ";" but that should
+ # okay in the real world where ";" in dirpaths is itself problematic.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+else
+ sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+ shlibpath_var=LIBPATH
+
+ # AIX 3 has no versioning support, so we append a major version to the name.
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+
+aix4* | aix5*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ hardcode_into_libs=yes
+ if test "$host_cpu" = ia64; then
+ # AIX 5 supports IA64
+ library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ else
+ # With GCC up to 2.95.x, collect2 would create an import file
+ # for dependence libraries. The import file would start with
+ # the line `#! .'. This would cause the generated library to
+ # depend on `.', always an invalid library. This was fixed in
+ # development snapshots of GCC prior to 3.0.
+ case $host_os in
+ aix4 | aix4.[01] | aix4.[01].*)
+ if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+ echo ' yes '
+ echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
+ :
+ else
+ can_build_shared=no
+ fi
+ ;;
+ esac
+ # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+ # soname into executable. Probably we can add versioning support to
+ # collect2, so additional links can be useful in future.
+ if test "$aix_use_runtimelinking" = yes; then
+ # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+ # instead of lib<name>.a to let people know that these are not
+ # typical AIX shared libraries.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ else
+ # We preserve .a as extension for shared libraries through AIX4.2
+ # and later when we are not doing run time linking.
+ library_names_spec='${libname}${release}.a $libname.a'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ fi
+ shlibpath_var=LIBPATH
+ fi
+ ;;
+
+amigaos*)
+ library_names_spec='$libname.ixlibrary $libname.a'
+ # Create ${libname}_ixlibrary.a entries in /sys/libs.
+ finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+ ;;
+
+beos*)
+ library_names_spec='${libname}${shared_ext}'
+ dynamic_linker="$host_os ld.so"
+ shlibpath_var=LIBRARY_PATH
+ ;;
+
+bsdi[45]*)
+ version_type=linux
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+ sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+ # the default ld.so.conf also contains /usr/contrib/lib and
+ # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+ # libtool to hard-code these into programs
+ ;;
+
+cygwin* | mingw* | pw32*)
+ version_type=windows
+ shrext_cmds=".dll"
+ need_version=no
+ need_lib_prefix=no
+
+ case $GCC,$host_os in
+ yes,cygwin* | yes,mingw* | yes,pw32*)
+ library_names_spec='$libname.dll.a'
+ # DLL is installed to $(libdir)/../bin by postinstall_cmds
+ postinstall_cmds='base_file=`basename \${file}`~
+ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~
+ dldir=$destdir/`dirname \$dlpath`~
+ test -d \$dldir || mkdir -p \$dldir~
+ $install_prog $dir/$dlname \$dldir/$dlname~
+ chmod a+x \$dldir/$dlname'
+ postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+ dlpath=$dir/\$dldll~
+ $rm \$dlpath'
+ shlibpath_overrides_runpath=yes
+
+ case $host_os in
+ cygwin*)
+ # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+ soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib"
+ ;;
+ mingw*)
+ # MinGW DLLs use traditional 'lib' prefix
+ soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then
+ # It is most probably a Windows format PATH printed by
+ # mingw gcc, but we are running on Cygwin. Gcc prints its search
+ # path with ; separators, and with drive letters. We can handle the
+ # drive letters (cygwin fileutils understands them), so leave them,
+ # especially as we might pass files found there to a mingw objdump,
+ # which wouldn't understand a cygwinified path. Ahh.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+ ;;
+ pw32*)
+ # pw32 DLLs use 'pw' prefix rather than 'lib'
+ library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ ;;
+ esac
+ ;;
+
+ *)
+ library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib'
+ ;;
+ esac
+ dynamic_linker='Win32 ld.exe'
+ # FIXME: first we should search . and the directory the executable is in
+ shlibpath_var=PATH
+ ;;
+
+darwin* | rhapsody*)
+ dynamic_linker="$host_os dyld"
+ version_type=darwin
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+ soname_spec='${libname}${release}${major}$shared_ext'
+ shlibpath_overrides_runpath=yes
+ shlibpath_var=DYLD_LIBRARY_PATH
+ shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+ # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
+ if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
+ else
+ sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib'
+ fi
+ sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+ ;;
+
+dgux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+freebsd1*)
+ dynamic_linker=no
+ ;;
+
+kfreebsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+freebsd* | dragonfly*)
+ # DragonFly does not have aout. When/if they implement a new
+ # versioning mechanism, adjust this.
+ if test -x /usr/bin/objformat; then
+ objformat=`/usr/bin/objformat`
+ else
+ case $host_os in
+ freebsd[123]*) objformat=aout ;;
+ *) objformat=elf ;;
+ esac
+ fi
+ version_type=freebsd-$objformat
+ case $version_type in
+ freebsd-elf*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ need_version=no
+ need_lib_prefix=no
+ ;;
+ freebsd-*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+ need_version=yes
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_os in
+ freebsd2*)
+ shlibpath_overrides_runpath=yes
+ ;;
+ freebsd3.[01]* | freebsdelf3.[01]*)
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
+ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+ freebsd*) # from 4.6 on
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ esac
+ ;;
+
+gnu*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ ;;
+
+hpux9* | hpux10* | hpux11*)
+ # Give a soname corresponding to the major version so that dld.sl refuses to
+ # link against other versions.
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ case $host_cpu in
+ ia64*)
+ shrext_cmds='.so'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.so"
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ if test "X$HPUX_IA64_MODE" = X32; then
+ sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+ else
+ sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+ fi
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ hppa*64*)
+ shrext_cmds='.sl'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ *)
+ shrext_cmds='.sl'
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=SHLIB_PATH
+ shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+ esac
+ # HP-UX runs *really* slowly unless shared libraries are mode 555.
+ postinstall_cmds='chmod 555 $lib'
+ ;;
+
+interix3*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+
+irix5* | irix6* | nonstopux*)
+ case $host_os in
+ nonstopux*) version_type=nonstopux ;;
+ *)
+ if test "$lt_cv_prog_gnu_ld" = yes; then
+ version_type=linux
+ else
+ version_type=irix
+ fi ;;
+ esac
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+ case $host_os in
+ irix5* | nonstopux*)
+ libsuff= shlibsuff=
+ ;;
+ *)
+ case $LD in # libtool.m4 will add one of these switches to LD
+ *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+ libsuff= shlibsuff= libmagic=32-bit;;
+ *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+ libsuff=32 shlibsuff=N32 libmagic=N32;;
+ *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+ libsuff=64 shlibsuff=64 libmagic=64-bit;;
+ *) libsuff= shlibsuff= libmagic=never-match;;
+ esac
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+ sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+ hardcode_into_libs=yes
+ ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+ dynamic_linker=no
+ ;;
+
+# This must be Linux ELF.
+linux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ # This implies no fast_install, which is unacceptable.
+ # Some rework will be needed to allow for fast_install
+ # before this can be enabled.
+ hardcode_into_libs=yes
+
+ # find out which ABI we are using
+ libsuff=
+ case "$host_cpu" in
+ x86_64*|s390x*|powerpc64*)
+ echo '#line 8447 "configure"' > conftest.$ac_ext
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ case `/usr/bin/file conftest.$ac_objext` in
+ *64-bit*)
+ libsuff=64
+ sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}"
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+ esac
+
+ # Append ld.so.conf contents to the search path
+ if test -f /etc/ld.so.conf; then
+ lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+ sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra"
+ fi
+
+ # We used to test for /lib/ld.so.1 and disable shared libraries on
+ # powerpc, because MkLinux only supported shared libraries with the
+ # GNU dynamic linker. Since this was broken with cross compilers,
+ # most powerpc-linux boxes support dynamic linking these days and
+ # people can always --disable-shared, the test was removed, and we
+ # assume the GNU/Linux dynamic linker is in use.
+ dynamic_linker='GNU/Linux ld.so'
+ ;;
+
+knetbsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+netbsd*)
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ dynamic_linker='NetBSD (a.out) ld.so'
+ else
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='NetBSD ld.elf_so'
+ fi
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+
+newsos6)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+nto-qnx*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+openbsd*)
+ version_type=sunos
+ sys_lib_dlsearch_path_spec="/usr/lib"
+ need_lib_prefix=no
+ # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+ case $host_os in
+ openbsd3.3 | openbsd3.3.*) need_version=yes ;;
+ *) need_version=no ;;
+ esac
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ case $host_os in
+ openbsd2.[89] | openbsd2.[89].*)
+ shlibpath_overrides_runpath=no
+ ;;
+ *)
+ shlibpath_overrides_runpath=yes
+ ;;
+ esac
+ else
+ shlibpath_overrides_runpath=yes
+ fi
+ ;;
+
+os2*)
+ libname_spec='$name'
+ shrext_cmds=".dll"
+ need_lib_prefix=no
+ library_names_spec='$libname${shared_ext} $libname.a'
+ dynamic_linker='OS/2 ld.exe'
+ shlibpath_var=LIBPATH
+ ;;
+
+osf3* | osf4* | osf5*)
+ version_type=osf
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+ sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+ ;;
+
+solaris*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ # ldd complains unless libraries are executable
+ postinstall_cmds='chmod +x $lib'
+ ;;
+
+sunos4*)
+ version_type=sunos
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ if test "$with_gnu_ld" = yes; then
+ need_lib_prefix=no
+ fi
+ need_version=yes
+ ;;
+
+sysv4 | sysv4.3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_vendor in
+ sni)
+ shlibpath_overrides_runpath=no
+ need_lib_prefix=no
+ export_dynamic_flag_spec='${wl}-Blargedynsym'
+ runpath_var=LD_RUN_PATH
+ ;;
+ siemens)
+ need_lib_prefix=no
+ ;;
+ motorola)
+ need_lib_prefix=no
+ need_version=no
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+ ;;
+ esac
+ ;;
+
+sysv4*MP*)
+ if test -d /usr/nec ;then
+ version_type=linux
+ library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+ soname_spec='$libname${shared_ext}.$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ fi
+ ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+ version_type=freebsd-elf
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ if test "$with_gnu_ld" = yes; then
+ sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+ shlibpath_overrides_runpath=no
+ else
+ sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+ shlibpath_overrides_runpath=yes
+ case $host_os in
+ sco3.2v5*)
+ sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+ ;;
+ esac
+ fi
+ sys_lib_dlsearch_path_spec='/usr/lib'
+ ;;
+
+uts4*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+*)
+ dynamic_linker=no
+ ;;
+esac
+echo "$as_me:$LINENO: result: $dynamic_linker" >&5
+echo "${ECHO_T}$dynamic_linker" >&6
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+ variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
+echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
+echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
+hardcode_action=
+if test -n "$hardcode_libdir_flag_spec" || \
+ test -n "$runpath_var" || \
+ test "X$hardcode_automatic" = "Xyes" ; then
+
+ # We can hardcode non-existant directories.
+ if test "$hardcode_direct" != no &&
+ # If the only mechanism to avoid hardcoding is shlibpath_var, we
+ # have to relink, otherwise we might link with an installed library
+ # when we should be linking with a yet-to-be-installed one
+ ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, )" != no &&
+ test "$hardcode_minus_L" != no; then
+ # Linking always hardcodes the temporary library directory.
+ hardcode_action=relink
+ else
+ # We can link without hardcoding, and we can hardcode nonexisting dirs.
+ hardcode_action=immediate
+ fi
+else
+ # We cannot hardcode anything, or else we can only hardcode existing
+ # directories.
+ hardcode_action=unsupported
+fi
+echo "$as_me:$LINENO: result: $hardcode_action" >&5
+echo "${ECHO_T}$hardcode_action" >&6
+
+if test "$hardcode_action" = relink; then
+ # Fast installation is not supported
+ enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+ test "$enable_shared" = no; then
+ # Fast installation is not necessary
+ enable_fast_install=needless
+fi
+
+striplib=
+old_striplib=
+echo "$as_me:$LINENO: checking whether stripping libraries is possible" >&5
+echo $ECHO_N "checking whether stripping libraries is possible... $ECHO_C" >&6
+if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then
+ test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
+ test -z "$striplib" && striplib="$STRIP --strip-unneeded"
+ echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+ case $host_os in
+ darwin*)
+ if test -n "$STRIP" ; then
+ striplib="$STRIP -x"
+ echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
+ else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+ ;;
+ *)
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+ ;;
+ esac
+fi
+
+if test "x$enable_dlopen" != xyes; then
+ enable_dlopen=unknown
+ enable_dlopen_self=unknown
+ enable_dlopen_self_static=unknown
+else
+ lt_cv_dlopen=no
+ lt_cv_dlopen_libs=
+
+ case $host_os in
+ beos*)
+ lt_cv_dlopen="load_add_on"
+ lt_cv_dlopen_libs=
+ lt_cv_dlopen_self=yes
+ ;;
+
+ mingw* | pw32*)
+ lt_cv_dlopen="LoadLibrary"
+ lt_cv_dlopen_libs=
+ ;;
+
+ cygwin*)
+ lt_cv_dlopen="dlopen"
+ lt_cv_dlopen_libs=
+ ;;
+
+ darwin*)
+ # if libdl is installed we need to link against it
+ echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5
+echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6
+if test "${ac_cv_lib_dl_dlopen+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char dlopen ();
+int
+main ()
+{
+dlopen ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_dl_dlopen=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_dl_dlopen=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6
+if test $ac_cv_lib_dl_dlopen = yes; then
+ lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
+else
+
+ lt_cv_dlopen="dyld"
+ lt_cv_dlopen_libs=
+ lt_cv_dlopen_self=yes
+
+fi
+
+ ;;
+
+ *)
+ echo "$as_me:$LINENO: checking for shl_load" >&5
+echo $ECHO_N "checking for shl_load... $ECHO_C" >&6
+if test "${ac_cv_func_shl_load+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define shl_load to an innocuous variant, in case <limits.h> declares shl_load.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define shl_load innocuous_shl_load
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char shl_load (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef shl_load
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char shl_load ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined (__stub_shl_load) || defined (__stub___shl_load)
+choke me
+#else
+char (*f) () = shl_load;
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+int
+main ()
+{
+return f != shl_load;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_shl_load=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_func_shl_load=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_func_shl_load" >&5
+echo "${ECHO_T}$ac_cv_func_shl_load" >&6
+if test $ac_cv_func_shl_load = yes; then
+ lt_cv_dlopen="shl_load"
+else
+ echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5
+echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6
+if test "${ac_cv_lib_dld_shl_load+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldld $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char shl_load ();
+int
+main ()
+{
+shl_load ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_dld_shl_load=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_dld_shl_load=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5
+echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6
+if test $ac_cv_lib_dld_shl_load = yes; then
+ lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-dld"
+else
+ echo "$as_me:$LINENO: checking for dlopen" >&5
+echo $ECHO_N "checking for dlopen... $ECHO_C" >&6
+if test "${ac_cv_func_dlopen+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define dlopen to an innocuous variant, in case <limits.h> declares dlopen.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define dlopen innocuous_dlopen
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char dlopen (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef dlopen
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char dlopen ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined (__stub_dlopen) || defined (__stub___dlopen)
+choke me
+#else
+char (*f) () = dlopen;
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+int
+main ()
+{
+return f != dlopen;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_dlopen=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_func_dlopen=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_func_dlopen" >&5
+echo "${ECHO_T}$ac_cv_func_dlopen" >&6
+if test $ac_cv_func_dlopen = yes; then
+ lt_cv_dlopen="dlopen"
+else
+ echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5
+echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6
+if test "${ac_cv_lib_dl_dlopen+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char dlopen ();
+int
+main ()
+{
+dlopen ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_dl_dlopen=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_dl_dlopen=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6
+if test $ac_cv_lib_dl_dlopen = yes; then
+ lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
+else
+ echo "$as_me:$LINENO: checking for dlopen in -lsvld" >&5
+echo $ECHO_N "checking for dlopen in -lsvld... $ECHO_C" >&6
+if test "${ac_cv_lib_svld_dlopen+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lsvld $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char dlopen ();
+int
+main ()
+{
+dlopen ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_svld_dlopen=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_svld_dlopen=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_svld_dlopen" >&5
+echo "${ECHO_T}$ac_cv_lib_svld_dlopen" >&6
+if test $ac_cv_lib_svld_dlopen = yes; then
+ lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"
+else
+ echo "$as_me:$LINENO: checking for dld_link in -ldld" >&5
+echo $ECHO_N "checking for dld_link in -ldld... $ECHO_C" >&6
+if test "${ac_cv_lib_dld_dld_link+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldld $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char dld_link ();
+int
+main ()
+{
+dld_link ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_dld_dld_link=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_dld_dld_link=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dld_dld_link" >&5
+echo "${ECHO_T}$ac_cv_lib_dld_dld_link" >&6
+if test $ac_cv_lib_dld_dld_link = yes; then
+ lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-dld"
+fi
+
+
+fi
+
+
+fi
+
+
+fi
+
+
+fi
+
+
+fi
+
+ ;;
+ esac
+
+ if test "x$lt_cv_dlopen" != xno; then
+ enable_dlopen=yes
+ else
+ enable_dlopen=no
+ fi
+
+ case $lt_cv_dlopen in
+ dlopen)
+ save_CPPFLAGS="$CPPFLAGS"
+ test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
+
+ save_LDFLAGS="$LDFLAGS"
+ wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
+
+ save_LIBS="$LIBS"
+ LIBS="$lt_cv_dlopen_libs $LIBS"
+
+ echo "$as_me:$LINENO: checking whether a program can dlopen itself" >&5
+echo $ECHO_N "checking whether a program can dlopen itself... $ECHO_C" >&6
+if test "${lt_cv_dlopen_self+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test "$cross_compiling" = yes; then :
+ lt_cv_dlopen_self=cross
+else
+ lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+ lt_status=$lt_dlunknown
+ cat > conftest.$ac_ext <<EOF
+#line 9344 "configure"
+#include "confdefs.h"
+
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef RTLD_GLOBAL
+# define LT_DLGLOBAL RTLD_GLOBAL
+#else
+# ifdef DL_GLOBAL
+# define LT_DLGLOBAL DL_GLOBAL
+# else
+# define LT_DLGLOBAL 0
+# endif
+#endif
+
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+ find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+# ifdef RTLD_LAZY
+# define LT_DLLAZY_OR_NOW RTLD_LAZY
+# else
+# ifdef DL_LAZY
+# define LT_DLLAZY_OR_NOW DL_LAZY
+# else
+# ifdef RTLD_NOW
+# define LT_DLLAZY_OR_NOW RTLD_NOW
+# else
+# ifdef DL_NOW
+# define LT_DLLAZY_OR_NOW DL_NOW
+# else
+# define LT_DLLAZY_OR_NOW 0
+# endif
+# endif
+# endif
+# endif
+#endif
+
+#ifdef __cplusplus
+extern "C" void exit (int);
+#endif
+
+void fnord() { int i=42;}
+int main ()
+{
+ void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+ int status = $lt_dlunknown;
+
+ if (self)
+ {
+ if (dlsym (self,"fnord")) status = $lt_dlno_uscore;
+ else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
+ /* dlclose (self); */
+ }
+ else
+ puts (dlerror ());
+
+ exit (status);
+}
+EOF
+ if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then
+ (./conftest; exit; ) >&5 2>/dev/null
+ lt_status=$?
+ case x$lt_status in
+ x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;;
+ x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;;
+ x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;;
+ esac
+ else :
+ # compilation failed
+ lt_cv_dlopen_self=no
+ fi
+fi
+rm -fr conftest*
+
+
+fi
+echo "$as_me:$LINENO: result: $lt_cv_dlopen_self" >&5
+echo "${ECHO_T}$lt_cv_dlopen_self" >&6
+
+ if test "x$lt_cv_dlopen_self" = xyes; then
+ wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
+ echo "$as_me:$LINENO: checking whether a statically linked program can dlopen itself" >&5
+echo $ECHO_N "checking whether a statically linked program can dlopen itself... $ECHO_C" >&6
+if test "${lt_cv_dlopen_self_static+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test "$cross_compiling" = yes; then :
+ lt_cv_dlopen_self_static=cross
+else
+ lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+ lt_status=$lt_dlunknown
+ cat > conftest.$ac_ext <<EOF
+#line 9444 "configure"
+#include "confdefs.h"
+
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef RTLD_GLOBAL
+# define LT_DLGLOBAL RTLD_GLOBAL
+#else
+# ifdef DL_GLOBAL
+# define LT_DLGLOBAL DL_GLOBAL
+# else
+# define LT_DLGLOBAL 0
+# endif
+#endif
+
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+ find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+# ifdef RTLD_LAZY
+# define LT_DLLAZY_OR_NOW RTLD_LAZY
+# else
+# ifdef DL_LAZY
+# define LT_DLLAZY_OR_NOW DL_LAZY
+# else
+# ifdef RTLD_NOW
+# define LT_DLLAZY_OR_NOW RTLD_NOW
+# else
+# ifdef DL_NOW
+# define LT_DLLAZY_OR_NOW DL_NOW
+# else
+# define LT_DLLAZY_OR_NOW 0
+# endif
+# endif
+# endif
+# endif
+#endif
+
+#ifdef __cplusplus
+extern "C" void exit (int);
+#endif
+
+void fnord() { int i=42;}
+int main ()
+{
+ void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+ int status = $lt_dlunknown;
+
+ if (self)
+ {
+ if (dlsym (self,"fnord")) status = $lt_dlno_uscore;
+ else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
+ /* dlclose (self); */
+ }
+ else
+ puts (dlerror ());
+
+ exit (status);
+}
+EOF
+ if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then
+ (./conftest; exit; ) >&5 2>/dev/null
+ lt_status=$?
+ case x$lt_status in
+ x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;;
+ x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;;
+ x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;;
+ esac
+ else :
+ # compilation failed
+ lt_cv_dlopen_self_static=no
+ fi
+fi
+rm -fr conftest*
+
+
+fi
+echo "$as_me:$LINENO: result: $lt_cv_dlopen_self_static" >&5
+echo "${ECHO_T}$lt_cv_dlopen_self_static" >&6
+ fi
+
+ CPPFLAGS="$save_CPPFLAGS"
+ LDFLAGS="$save_LDFLAGS"
+ LIBS="$save_LIBS"
+ ;;
+ esac
+
+ case $lt_cv_dlopen_self in
+ yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
+ *) enable_dlopen_self=unknown ;;
+ esac
+
+ case $lt_cv_dlopen_self_static in
+ yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
+ *) enable_dlopen_self_static=unknown ;;
+ esac
+fi
+
+
+# Report which library types will actually be built
+echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5
+echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&6
+echo "$as_me:$LINENO: result: $can_build_shared" >&5
+echo "${ECHO_T}$can_build_shared" >&6
+
+echo "$as_me:$LINENO: checking whether to build shared libraries" >&5
+echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6
+test "$can_build_shared" = "no" && enable_shared=no
+
+# On AIX, shared libraries and static libraries use the same namespace, and
+# are all built from PIC.
+case $host_os in
+aix3*)
+ test "$enable_shared" = yes && enable_static=no
+ if test -n "$RANLIB"; then
+ archive_cmds="$archive_cmds~\$RANLIB \$lib"
+ postinstall_cmds='$RANLIB $lib'
+ fi
+ ;;
+
+aix4* | aix5*)
+ if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+ test "$enable_shared" = yes && enable_static=no
+ fi
+ ;;
+esac
+echo "$as_me:$LINENO: result: $enable_shared" >&5
+echo "${ECHO_T}$enable_shared" >&6
+
+echo "$as_me:$LINENO: checking whether to build static libraries" >&5
+echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6
+# Make sure either enable_shared or enable_static is yes.
+test "$enable_shared" = yes || enable_static=yes
+echo "$as_me:$LINENO: result: $enable_static" >&5
+echo "${ECHO_T}$enable_static" >&6
+
+# The else clause should only fire when bootstrapping the
+# libtool distribution, otherwise you forgot to ship ltmain.sh
+# with your package, and you will get complaints that there are
+# no rules to generate ltmain.sh.
+if test -f "$ltmain"; then
+ # See if we are running on zsh, and set the options which allow our commands through
+ # without removal of \ escapes.
+ if test -n "${ZSH_VERSION+set}" ; then
+ setopt NO_GLOB_SUBST
+ fi
+ # Now quote all the things that may contain metacharacters while being
+ # careful not to overquote the AC_SUBSTed values. We take copies of the
+ # variables and quote the copies for generation of the libtool script.
+ for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \
+ SED SHELL STRIP \
+ libname_spec library_names_spec soname_spec extract_expsyms_cmds \
+ old_striplib striplib file_magic_cmd finish_cmds finish_eval \
+ deplibs_check_method reload_flag reload_cmds need_locks \
+ lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
+ lt_cv_sys_global_symbol_to_c_name_address \
+ sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
+ old_postinstall_cmds old_postuninstall_cmds \
+ compiler \
+ CC \
+ LD \
+ lt_prog_compiler_wl \
+ lt_prog_compiler_pic \
+ lt_prog_compiler_static \
+ lt_prog_compiler_no_builtin_flag \
+ export_dynamic_flag_spec \
+ thread_safe_flag_spec \
+ whole_archive_flag_spec \
+ enable_shared_with_static_runtimes \
+ old_archive_cmds \
+ old_archive_from_new_cmds \
+ predep_objects \
+ postdep_objects \
+ predeps \
+ postdeps \
+ compiler_lib_search_path \
+ archive_cmds \
+ archive_expsym_cmds \
+ postinstall_cmds \
+ postuninstall_cmds \
+ old_archive_from_expsyms_cmds \
+ allow_undefined_flag \
+ no_undefined_flag \
+ export_symbols_cmds \
+ hardcode_libdir_flag_spec \
+ hardcode_libdir_flag_spec_ld \
+ hardcode_libdir_separator \
+ hardcode_automatic \
+ module_cmds \
+ module_expsym_cmds \
+ lt_cv_prog_compiler_c_o \
+ exclude_expsyms \
+ include_expsyms; do
+
+ case $var in
+ old_archive_cmds | \
+ old_archive_from_new_cmds | \
+ archive_cmds | \
+ archive_expsym_cmds | \
+ module_cmds | \
+ module_expsym_cmds | \
+ old_archive_from_expsyms_cmds | \
+ export_symbols_cmds | \
+ extract_expsyms_cmds | reload_cmds | finish_cmds | \
+ postinstall_cmds | postuninstall_cmds | \
+ old_postinstall_cmds | old_postuninstall_cmds | \
+ sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
+ # Double-quote double-evaled strings.
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
+ ;;
+ *)
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\""
+ ;;
+ esac
+ done
+
+ case $lt_echo in
+ *'\$0 --fallback-echo"')
+ lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'`
+ ;;
+ esac
+
+cfgfile="${ofile}T"
+ trap "$rm \"$cfgfile\"; exit 1" 1 2 15
+ $rm -f "$cfgfile"
+ { echo "$as_me:$LINENO: creating $ofile" >&5
+echo "$as_me: creating $ofile" >&6;}
+
+ cat <<__EOF__ >> "$cfgfile"
+#! $SHELL
+
+# `$echo "$cfgfile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
+# Generated automatically by $PROGRAM (GNU $PACKAGE $VERSION$TIMESTAMP)
+# NOTE: Changes made to this file will be lost: look at ltmain.sh.
+#
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001
+# Free Software Foundation, Inc.
+#
+# This file is part of GNU Libtool:
+# Originally by Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
+#
+# 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 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, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# A sed program that does not truncate output.
+SED=$lt_SED
+
+# Sed that helps us avoid accidentally triggering echo(1) options like -n.
+Xsed="$SED -e 1s/^X//"
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+# The names of the tagged configurations supported by this script.
+available_tags=
+
+# ### BEGIN LIBTOOL CONFIG
+
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+
+# Shell to use when invoking shell scripts.
+SHELL=$lt_SHELL
+
+# Whether or not to build shared libraries.
+build_libtool_libs=$enable_shared
+
+# Whether or not to build static libraries.
+build_old_libs=$enable_static
+
+# Whether or not to add -lc for building shared libraries.
+build_libtool_need_lc=$archive_cmds_need_lc
+
+# Whether or not to disallow shared libs when runtime libs are static
+allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes
+
+# Whether or not to optimize for fast installation.
+fast_install=$enable_fast_install
+
+# The host system.
+host_alias=$host_alias
+host=$host
+host_os=$host_os
+
+# The build system.
+build_alias=$build_alias
+build=$build
+build_os=$build_os
+
+# An echo program that does not interpret backslashes.
+echo=$lt_echo
+
+# The archiver.
+AR=$lt_AR
+AR_FLAGS=$lt_AR_FLAGS
+
+# A C compiler.
+LTCC=$lt_LTCC
+
+# LTCC compiler flags.
+LTCFLAGS=$lt_LTCFLAGS
+
+# A language-specific compiler.
+CC=$lt_compiler
+
+# Is the compiler the GNU C compiler?
+with_gcc=$GCC
+
+gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\`
+gcc_ver=\`gcc -dumpversion\`
+
+# An ERE matcher.
+EGREP=$lt_EGREP
+
+# The linker used to build libraries.
+LD=$lt_LD
+
+# Whether we need hard or soft links.
+LN_S=$lt_LN_S
+
+# A BSD-compatible nm program.
+NM=$lt_NM
+
+# A symbol stripping program
+STRIP=$lt_STRIP
+
+# Used to examine libraries when file_magic_cmd begins "file"
+MAGIC_CMD=$MAGIC_CMD
+
+# Used on cygwin: DLL creation program.
+DLLTOOL="$DLLTOOL"
+
+# Used on cygwin: object dumper.
+OBJDUMP="$OBJDUMP"
+
+# Used on cygwin: assembler.
+AS="$AS"
+
+# The name of the directory that contains temporary libtool files.
+objdir=$objdir
+
+# How to create reloadable object files.
+reload_flag=$lt_reload_flag
+reload_cmds=$lt_reload_cmds
+
+# How to pass a linker flag through the compiler.
+wl=$lt_lt_prog_compiler_wl
+
+# Object file suffix (normally "o").
+objext="$ac_objext"
+
+# Old archive suffix (normally "a").
+libext="$libext"
+
+# Shared library suffix (normally ".so").
+shrext_cmds='$shrext_cmds'
+
+# Executable file suffix (normally "").
+exeext="$exeext"
+
+# Additional compiler flags for building library objects.
+pic_flag=$lt_lt_prog_compiler_pic
+pic_mode=$pic_mode
+
+# What is the maximum length of a command?
+max_cmd_len=$lt_cv_sys_max_cmd_len
+
+# Does compiler simultaneously support -c and -o options?
+compiler_c_o=$lt_lt_cv_prog_compiler_c_o
+
+# Must we lock files when doing compilation?
+need_locks=$lt_need_locks
+
+# Do we need the lib prefix for modules?
+need_lib_prefix=$need_lib_prefix
+
+# Do we need a version for libraries?
+need_version=$need_version
+
+# Whether dlopen is supported.
+dlopen_support=$enable_dlopen
+
+# Whether dlopen of programs is supported.
+dlopen_self=$enable_dlopen_self
+
+# Whether dlopen of statically linked programs is supported.
+dlopen_self_static=$enable_dlopen_self_static
+
+# Compiler flag to prevent dynamic linking.
+link_static_flag=$lt_lt_prog_compiler_static
+
+# Compiler flag to turn off builtin functions.
+no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag
+
+# Compiler flag to allow reflexive dlopens.
+export_dynamic_flag_spec=$lt_export_dynamic_flag_spec
+
+# Compiler flag to generate shared objects directly from archives.
+whole_archive_flag_spec=$lt_whole_archive_flag_spec
+
+# Compiler flag to generate thread-safe objects.
+thread_safe_flag_spec=$lt_thread_safe_flag_spec
+
+# Library versioning type.
+version_type=$version_type
+
+# Format of library name prefix.
+libname_spec=$lt_libname_spec
+
+# List of archive names. First name is the real one, the rest are links.
+# The last name is the one that the linker finds with -lNAME.
+library_names_spec=$lt_library_names_spec
+
+# The coded name of the library, if different from the real name.
+soname_spec=$lt_soname_spec
+
+# Commands used to build and install an old-style archive.
+RANLIB=$lt_RANLIB
+old_archive_cmds=$lt_old_archive_cmds
+old_postinstall_cmds=$lt_old_postinstall_cmds
+old_postuninstall_cmds=$lt_old_postuninstall_cmds
+
+# Create an old-style archive from a shared archive.
+old_archive_from_new_cmds=$lt_old_archive_from_new_cmds
+
+# Create a temporary old-style archive to link instead of a shared archive.
+old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds
+
+# Commands used to build and install a shared archive.
+archive_cmds=$lt_archive_cmds
+archive_expsym_cmds=$lt_archive_expsym_cmds
+postinstall_cmds=$lt_postinstall_cmds
+postuninstall_cmds=$lt_postuninstall_cmds
+
+# Commands used to build a loadable module (assumed same as above if empty)
+module_cmds=$lt_module_cmds
+module_expsym_cmds=$lt_module_expsym_cmds
+
+# Commands to strip libraries.
+old_striplib=$lt_old_striplib
+striplib=$lt_striplib
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predep_objects=\`echo $lt_predep_objects | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdep_objects=\`echo $lt_postdep_objects | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predeps=$lt_predeps
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdeps=$lt_postdeps
+
+# The library search path used internally by the compiler when linking
+# a shared library.
+compiler_lib_search_path=\`echo $lt_compiler_lib_search_path | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Method to check whether dependent libraries are shared objects.
+deplibs_check_method=$lt_deplibs_check_method
+
+# Command to use when deplibs_check_method == file_magic.
+file_magic_cmd=$lt_file_magic_cmd
+
+# Flag that allows shared libraries with undefined symbols to be built.
+allow_undefined_flag=$lt_allow_undefined_flag
+
+# Flag that forces no undefined symbols.
+no_undefined_flag=$lt_no_undefined_flag
+
+# Commands used to finish a libtool library installation in a directory.
+finish_cmds=$lt_finish_cmds
+
+# Same as above, but a single script fragment to be evaled but not shown.
+finish_eval=$lt_finish_eval
+
+# Take the output of nm and produce a listing of raw symbols and C names.
+global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
+
+# Transform the output of nm in a proper C declaration
+global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
+
+# Transform the output of nm in a C name address pair
+global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address
+
+# This is the shared library runtime path variable.
+runpath_var=$runpath_var
+
+# This is the shared library path variable.
+shlibpath_var=$shlibpath_var
+
+# Is shlibpath searched before the hard-coded library search path?
+shlibpath_overrides_runpath=$shlibpath_overrides_runpath
+
+# How to hardcode a shared library path into an executable.
+hardcode_action=$hardcode_action
+
+# Whether we should hardcode library paths into libraries.
+hardcode_into_libs=$hardcode_into_libs
+
+# Flag to hardcode \$libdir into a binary during linking.
+# This must work even if \$libdir does not exist.
+hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec
+
+# If ld is used when linking, flag to hardcode \$libdir into
+# a binary during linking. This must work even if \$libdir does
+# not exist.
+hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld
+
+# Whether we need a single -rpath flag with a separated argument.
+hardcode_libdir_separator=$lt_hardcode_libdir_separator
+
+# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the
+# resulting binary.
+hardcode_direct=$hardcode_direct
+
+# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
+# resulting binary.
+hardcode_minus_L=$hardcode_minus_L
+
+# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into
+# the resulting binary.
+hardcode_shlibpath_var=$hardcode_shlibpath_var
+
+# Set to yes if building a shared library automatically hardcodes DIR into the library
+# and all subsequent libraries and executables linked against it.
+hardcode_automatic=$hardcode_automatic
+
+# Variables whose values should be saved in libtool wrapper scripts and
+# restored at relink time.
+variables_saved_for_relink="$variables_saved_for_relink"
+
+# Whether libtool must link a program against all its dependency libraries.
+link_all_deplibs=$link_all_deplibs
+
+# Compile-time system search path for libraries
+sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Run-time system search path for libraries
+sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec
+
+# Fix the shell variable \$srcfile for the compiler.
+fix_srcfile_path="$fix_srcfile_path"
+
+# Set to yes if exported symbols are required.
+always_export_symbols=$always_export_symbols
+
+# The commands to list exported symbols.
+export_symbols_cmds=$lt_export_symbols_cmds
+
+# The commands to extract the exported symbol list from a shared archive.
+extract_expsyms_cmds=$lt_extract_expsyms_cmds
+
+# Symbols that should not be listed in the preloaded symbols.
+exclude_expsyms=$lt_exclude_expsyms
+
+# Symbols that must always be exported.
+include_expsyms=$lt_include_expsyms
+
+# ### END LIBTOOL CONFIG
+
+__EOF__
+
+
+ case $host_os in
+ aix3*)
+ cat <<\EOF >> "$cfgfile"
+
+# AIX sometimes has problems with the GCC collect2 program. For some
+# reason, if we set the COLLECT_NAMES environment variable, the problems
+# vanish in a puff of smoke.
+if test "X${COLLECT_NAMES+set}" != Xset; then
+ COLLECT_NAMES=
+ export COLLECT_NAMES
+fi
+EOF
+ ;;
+ esac
+
+ # We use sed instead of cat because bash on DJGPP gets confused if
+ # if finds mixed CR/LF and LF-only lines. Since sed operates in
+ # text mode, it properly converts lines to CR/LF. This bash problem
+ # is reportedly fixed, but why not run on old versions too?
+ sed '$q' "$ltmain" >> "$cfgfile" || (rm -f "$cfgfile"; exit 1)
+
+ mv -f "$cfgfile" "$ofile" || \
+ (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
+ chmod +x "$ofile"
+
+else
+ # If there is no Makefile yet, we rely on a make rule to execute
+ # `config.status --recheck' to rerun these tests and create the
+ # libtool script then.
+ ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'`
+ if test -f "$ltmain_in"; then
+ test -f Makefile && make "$ltmain"
+ fi
+fi
+
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+CC="$lt_save_CC"
+
+
+# Check whether --with-tags or --without-tags was given.
+if test "${with_tags+set}" = set; then
+ withval="$with_tags"
+ tagnames="$withval"
+fi;
+
+if test -f "$ltmain" && test -n "$tagnames"; then
+ if test ! -f "${ofile}"; then
+ { echo "$as_me:$LINENO: WARNING: output file \`$ofile' does not exist" >&5
+echo "$as_me: WARNING: output file \`$ofile' does not exist" >&2;}
+ fi
+
+ if test -z "$LTCC"; then
+ eval "`$SHELL ${ofile} --config | grep '^LTCC='`"
+ if test -z "$LTCC"; then
+ { echo "$as_me:$LINENO: WARNING: output file \`$ofile' does not look like a libtool script" >&5
+echo "$as_me: WARNING: output file \`$ofile' does not look like a libtool script" >&2;}
+ else
+ { echo "$as_me:$LINENO: WARNING: using \`LTCC=$LTCC', extracted from \`$ofile'" >&5
+echo "$as_me: WARNING: using \`LTCC=$LTCC', extracted from \`$ofile'" >&2;}
+ fi
+ fi
+ if test -z "$LTCFLAGS"; then
+ eval "`$SHELL ${ofile} --config | grep '^LTCFLAGS='`"
+ fi
+
+ # Extract list of available tagged configurations in $ofile.
+ # Note that this assumes the entire list is on one line.
+ available_tags=`grep "^available_tags=" "${ofile}" | $SED -e 's/available_tags=\(.*$\)/\1/' -e 's/\"//g'`
+
+ lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+ for tagname in $tagnames; do
+ IFS="$lt_save_ifs"
+ # Check whether tagname contains only valid characters
+ case `$echo "X$tagname" | $Xsed -e 's:[-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,/]::g'` in
+ "") ;;
+ *) { { echo "$as_me:$LINENO: error: invalid tag name: $tagname" >&5
+echo "$as_me: error: invalid tag name: $tagname" >&2;}
+ { (exit 1); exit 1; }; }
+ ;;
+ esac
+
+ if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "${ofile}" > /dev/null
+ then
+ { { echo "$as_me:$LINENO: error: tag name \"$tagname\" already exists" >&5
+echo "$as_me: error: tag name \"$tagname\" already exists" >&2;}
+ { (exit 1); exit 1; }; }
+ fi
+
+ # Update the list of available tags.
+ if test -n "$tagname"; then
+ echo appending configuration tag \"$tagname\" to $ofile
+
+ case $tagname in
+ CXX)
+ if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
+ ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
+ (test "X$CXX" != "Xg++"))) ; then
+ ac_ext=cc
+ac_cpp='$CXXCPP $CPPFLAGS'
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
+
+
+
+
+archive_cmds_need_lc_CXX=no
+allow_undefined_flag_CXX=
+always_export_symbols_CXX=no
+archive_expsym_cmds_CXX=
+export_dynamic_flag_spec_CXX=
+hardcode_direct_CXX=no
+hardcode_libdir_flag_spec_CXX=
+hardcode_libdir_flag_spec_ld_CXX=
+hardcode_libdir_separator_CXX=
+hardcode_minus_L_CXX=no
+hardcode_shlibpath_var_CXX=unsupported
+hardcode_automatic_CXX=no
+module_cmds_CXX=
+module_expsym_cmds_CXX=
+link_all_deplibs_CXX=unknown
+old_archive_cmds_CXX=$old_archive_cmds
+no_undefined_flag_CXX=
+whole_archive_flag_spec_CXX=
+enable_shared_with_static_runtimes_CXX=no
+
+# Dependencies to place before and after the object being linked:
+predep_objects_CXX=
+postdep_objects_CXX=
+predeps_CXX=
+postdeps_CXX=
+compiler_lib_search_path_CXX=
+
+# Source file extension for C++ test sources.
+ac_ext=cpp
+
+# Object file extension for compiled C++ test sources.
+objext=o
+objext_CXX=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="int some_variable = 0;\n"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='int main(int, char *[]) { return(0); }\n'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+
+
+# save warnings/boilerplate of simple test code
+ac_outfile=conftest.$ac_objext
+printf "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$rm conftest*
+
+ac_outfile=conftest.$ac_objext
+printf "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$rm conftest*
+
+
+# Allow CC to be a program name with arguments.
+lt_save_CC=$CC
+lt_save_LD=$LD
+lt_save_GCC=$GCC
+GCC=$GXX
+lt_save_with_gnu_ld=$with_gnu_ld
+lt_save_path_LD=$lt_cv_path_LD
+if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
+ lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
+else
+ $as_unset lt_cv_prog_gnu_ld
+fi
+if test -n "${lt_cv_path_LDCXX+set}"; then
+ lt_cv_path_LD=$lt_cv_path_LDCXX
+else
+ $as_unset lt_cv_path_LD
+fi
+test -z "${LDCXX+set}" || LD=$LDCXX
+CC=${CXX-"c++"}
+compiler=$CC
+compiler_CXX=$CC
+for cc_temp in $compiler""; do
+ case $cc_temp in
+ compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
+ distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
+ \-*) ;;
+ *) break;;
+ esac
+done
+cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+
+
+# We don't want -fno-exception wen compiling C++ code, so set the
+# no_builtin_flag separately
+if test "$GXX" = yes; then
+ lt_prog_compiler_no_builtin_flag_CXX=' -fno-builtin'
+else
+ lt_prog_compiler_no_builtin_flag_CXX=
+fi
+
+if test "$GXX" = yes; then
+ # Set up default GNU C++ configuration
+
+
+# Check whether --with-gnu-ld or --without-gnu-ld was given.
+if test "${with_gnu_ld+set}" = set; then
+ withval="$with_gnu_ld"
+ test "$withval" = no || with_gnu_ld=yes
+else
+ with_gnu_ld=no
+fi;
+ac_prog=ld
+if test "$GCC" = yes; then
+ # Check if gcc -print-prog-name=ld gives a path.
+ echo "$as_me:$LINENO: checking for ld used by $CC" >&5
+echo $ECHO_N "checking for ld used by $CC... $ECHO_C" >&6
+ case $host in
+ *-*-mingw*)
+ # gcc leaves a trailing carriage return which upsets mingw
+ ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+ *)
+ ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+ esac
+ case $ac_prog in
+ # Accept absolute paths.
+ [\\/]* | ?:[\\/]*)
+ re_direlt='/[^/][^/]*/\.\./'
+ # Canonicalize the pathname of ld
+ ac_prog=`echo $ac_prog| $SED 's%\\\\%/%g'`
+ while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do
+ ac_prog=`echo $ac_prog| $SED "s%$re_direlt%/%"`
+ done
+ test -z "$LD" && LD="$ac_prog"
+ ;;
+ "")
+ # If it fails, then pretend we aren't using GCC.
+ ac_prog=ld
+ ;;
+ *)
+ # If it is relative, then search for the first ld in PATH.
+ with_gnu_ld=unknown
+ ;;
+ esac
+elif test "$with_gnu_ld" = yes; then
+ echo "$as_me:$LINENO: checking for GNU ld" >&5
+echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6
+else
+ echo "$as_me:$LINENO: checking for non-GNU ld" >&5
+echo $ECHO_N "checking for non-GNU ld... $ECHO_C" >&6
+fi
+if test "${lt_cv_path_LD+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test -z "$LD"; then
+ lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+ for ac_dir in $PATH; do
+ IFS="$lt_save_ifs"
+ test -z "$ac_dir" && ac_dir=.
+ if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+ lt_cv_path_LD="$ac_dir/$ac_prog"
+ # Check to see if the program is GNU ld. I'd rather use --version,
+ # but apparently some variants of GNU ld only accept -v.
+ # Break only if it was the GNU/non-GNU ld that we prefer.
+ case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
+ *GNU* | *'with BFD'*)
+ test "$with_gnu_ld" != no && break
+ ;;
+ *)
+ test "$with_gnu_ld" != yes && break
+ ;;
+ esac
+ fi
+ done
+ IFS="$lt_save_ifs"
+else
+ lt_cv_path_LD="$LD" # Let the user override the test with a path.
+fi
+fi
+
+LD="$lt_cv_path_LD"
+if test -n "$LD"; then
+ echo "$as_me:$LINENO: result: $LD" >&5
+echo "${ECHO_T}$LD" >&6
+else
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+test -z "$LD" && { { echo "$as_me:$LINENO: error: no acceptable ld found in \$PATH" >&5
+echo "$as_me: error: no acceptable ld found in \$PATH" >&2;}
+ { (exit 1); exit 1; }; }
+echo "$as_me:$LINENO: checking if the linker ($LD) is GNU ld" >&5
+echo $ECHO_N "checking if the linker ($LD) is GNU ld... $ECHO_C" >&6
+if test "${lt_cv_prog_gnu_ld+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ # I'd rather use --version here, but apparently some GNU lds only accept -v.
+case `$LD -v 2>&1 </dev/null` in
+*GNU* | *'with BFD'*)
+ lt_cv_prog_gnu_ld=yes
+ ;;
+*)
+ lt_cv_prog_gnu_ld=no
+ ;;
+esac
+fi
+echo "$as_me:$LINENO: result: $lt_cv_prog_gnu_ld" >&5
+echo "${ECHO_T}$lt_cv_prog_gnu_ld" >&6
+with_gnu_ld=$lt_cv_prog_gnu_ld
+
+
+
+ # Check if GNU C++ uses GNU ld as the underlying linker, since the
+ # archiving commands below assume that GNU ld is being used.
+ if test "$with_gnu_ld" = yes; then
+ archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ archive_expsym_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+
+ hardcode_libdir_flag_spec_CXX='${wl}--rpath ${wl}$libdir'
+ export_dynamic_flag_spec_CXX='${wl}--export-dynamic'
+
+ # If archive_cmds runs LD, not CC, wlarc should be empty
+ # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
+ # investigate it a little bit more. (MM)
+ wlarc='${wl}'
+
+ # ancient GNU ld didn't support --whole-archive et. al.
+ if eval "`$CC -print-prog-name=ld` --help 2>&1" | \
+ grep 'no-whole-archive' > /dev/null; then
+ whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+ else
+ whole_archive_flag_spec_CXX=
+ fi
+ else
+ with_gnu_ld=no
+ wlarc=
+
+ # A generic and very simple default shared library creation
+ # command for GNU C++ for the case where it uses the native
+ # linker, instead of GNU ld. If possible, this setting should
+ # overridden to take advantage of the native linker features on
+ # the platform it is being used on.
+ archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+ fi
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"'
+
+else
+ GXX=no
+ with_gnu_ld=no
+ wlarc=
+fi
+
+# PORTME: fill in a description of your system's C++ link characteristics
+echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6
+ld_shlibs_CXX=yes
+case $host_os in
+ aix3*)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ aix4* | aix5*)
+ if test "$host_cpu" = ia64; then
+ # On IA64, the linker does run time linking by default, so we don't
+ # have to do anything special.
+ aix_use_runtimelinking=no
+ exp_sym_flag='-Bexport'
+ no_entry_flag=""
+ else
+ aix_use_runtimelinking=no
+
+ # Test if we are trying to use run time linking or normal
+ # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+ # need to do runtime linking.
+ case $host_os in aix4.[23]|aix4.[23].*|aix5*)
+ for ld_flag in $LDFLAGS; do
+ case $ld_flag in
+ *-brtl*)
+ aix_use_runtimelinking=yes
+ break
+ ;;
+ esac
+ done
+ ;;
+ esac
+
+ exp_sym_flag='-bexport'
+ no_entry_flag='-bnoentry'
+ fi
+
+ # When large executables or shared objects are built, AIX ld can
+ # have problems creating the table of contents. If linking a library
+ # or program results in "error TOC overflow" add -mminimal-toc to
+ # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not
+ # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+ archive_cmds_CXX=''
+ hardcode_direct_CXX=yes
+ hardcode_libdir_separator_CXX=':'
+ link_all_deplibs_CXX=yes
+
+ if test "$GXX" = yes; then
+ case $host_os in aix4.[012]|aix4.[012].*)
+ # We only want to do this on AIX 4.2 and lower, the check
+ # below for broken collect2 doesn't work under 4.3+
+ collect2name=`${CC} -print-prog-name=collect2`
+ if test -f "$collect2name" && \
+ strings "$collect2name" | grep resolve_lib_name >/dev/null
+ then
+ # We have reworked collect2
+ hardcode_direct_CXX=yes
+ else
+ # We have old collect2
+ hardcode_direct_CXX=unsupported
+ # It fails to find uninstalled libraries when the uninstalled
+ # path is not listed in the libpath. Setting hardcode_minus_L
+ # to unsupported forces relinking
+ hardcode_minus_L_CXX=yes
+ hardcode_libdir_flag_spec_CXX='-L$libdir'
+ hardcode_libdir_separator_CXX=
+ fi
+ ;;
+ esac
+ shared_flag='-shared'
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag="$shared_flag "'${wl}-G'
+ fi
+ else
+ # not using gcc
+ if test "$host_cpu" = ia64; then
+ # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+ # chokes on -Wl,-G. The following line is correct:
+ shared_flag='-G'
+ else
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag='${wl}-G'
+ else
+ shared_flag='${wl}-bM:SRE'
+ fi
+ fi
+ fi
+
+ # It seems that -bexpall does not export symbols beginning with
+ # underscore (_), so it is better to generate a list of symbols to export.
+ always_export_symbols_CXX=yes
+ if test "$aix_use_runtimelinking" = yes; then
+ # Warning - without using the other runtime loading flags (-brtl),
+ # -berok will link without error, but may produce a broken library.
+ allow_undefined_flag_CXX='-berok'
+ # Determine the default libpath from the value encoded in an empty executable.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`; fi
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+
+ hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath"
+
+ archive_expsym_cmds_CXX="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+ else
+ if test "$host_cpu" = ia64; then
+ hardcode_libdir_flag_spec_CXX='${wl}-R $libdir:/usr/lib:/lib'
+ allow_undefined_flag_CXX="-z nodefs"
+ archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+ else
+ # Determine the default libpath from the value encoded in an empty executable.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_cxx_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`; fi
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+
+ hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath"
+ # Warning - without using the other run time loading flags,
+ # -berok will link without error, but may produce a broken library.
+ no_undefined_flag_CXX=' ${wl}-bernotok'
+ allow_undefined_flag_CXX=' ${wl}-berok'
+ # Exported symbols can be pulled into shared objects from archives
+ whole_archive_flag_spec_CXX='$convenience'
+ archive_cmds_need_lc_CXX=yes
+ # This is similar to how AIX traditionally builds its shared libraries.
+ archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+ fi
+ fi
+ ;;
+
+ beos*)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ allow_undefined_flag_CXX=unsupported
+ # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+ # support --undefined. This deserves some investigation. FIXME
+ archive_cmds_CXX='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ else
+ ld_shlibs_CXX=no
+ fi
+ ;;
+
+ chorus*)
+ case $cc_basename in
+ *)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ esac
+ ;;
+
+ cygwin* | mingw* | pw32*)
+ # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, CXX) is actually meaningless,
+ # as there is no search path for DLLs.
+ hardcode_libdir_flag_spec_CXX='-L$libdir'
+ allow_undefined_flag_CXX=unsupported
+ always_export_symbols_CXX=no
+ enable_shared_with_static_runtimes_CXX=yes
+
+ if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
+ archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ # If the export-symbols file already is a .def file (1st line
+ # is EXPORTS), use it as is; otherwise, prepend...
+ archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+ cp $export_symbols $output_objdir/$soname.def;
+ else
+ echo EXPORTS > $output_objdir/$soname.def;
+ cat $export_symbols >> $output_objdir/$soname.def;
+ fi~
+ $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ else
+ ld_shlibs_CXX=no
+ fi
+ ;;
+ darwin* | rhapsody*)
+ case $host_os in
+ rhapsody* | darwin1.[012])
+ allow_undefined_flag_CXX='${wl}-undefined ${wl}suppress'
+ ;;
+ *) # Darwin 1.3 on
+ if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
+ allow_undefined_flag_CXX='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ else
+ case ${MACOSX_DEPLOYMENT_TARGET} in
+ 10.[012])
+ allow_undefined_flag_CXX='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ ;;
+ 10.*)
+ allow_undefined_flag_CXX='${wl}-undefined ${wl}dynamic_lookup'
+ ;;
+ esac
+ fi
+ ;;
+ esac
+ archive_cmds_need_lc_CXX=no
+ hardcode_direct_CXX=no
+ hardcode_automatic_CXX=yes
+ hardcode_shlibpath_var_CXX=unsupported
+ whole_archive_flag_spec_CXX=''
+ link_all_deplibs_CXX=yes
+
+ if test "$GXX" = yes ; then
+ lt_int_apple_cc_single_mod=no
+ output_verbose_link_cmd='echo'
+ if $CC -dumpspecs 2>&1 | $EGREP 'single_module' >/dev/null ; then
+ lt_int_apple_cc_single_mod=yes
+ fi
+ if test "X$lt_int_apple_cc_single_mod" = Xyes ; then
+ archive_cmds_CXX='$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
+ else
+ archive_cmds_CXX='$CC -r -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
+ fi
+ module_cmds_CXX='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ if test "X$lt_int_apple_cc_single_mod" = Xyes ; then
+ archive_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ else
+ archive_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -r -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ fi
+ module_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ else
+ case $cc_basename in
+ xlc*)
+ output_verbose_link_cmd='echo'
+ archive_cmds_CXX='$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
+ module_cmds_CXX='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ archive_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ module_expsym_cmds_CXX='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ ;;
+ *)
+ ld_shlibs_CXX=no
+ ;;
+ esac
+ fi
+ ;;
+
+ dgux*)
+ case $cc_basename in
+ ec++*)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ ghcx*)
+ # Green Hills C++ Compiler
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ esac
+ ;;
+ freebsd[12]*)
+ # C++ shared libraries reported to be fairly broken before switch to ELF
+ ld_shlibs_CXX=no
+ ;;
+ freebsd-elf*)
+ archive_cmds_need_lc_CXX=no
+ ;;
+ freebsd* | kfreebsd*-gnu | dragonfly*)
+ # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
+ # conventions
+ ld_shlibs_CXX=yes
+ ;;
+ gnu*)
+ ;;
+ hpux9*)
+ hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir'
+ hardcode_libdir_separator_CXX=:
+ export_dynamic_flag_spec_CXX='${wl}-E'
+ hardcode_direct_CXX=yes
+ hardcode_minus_L_CXX=yes # Not in the search PATH,
+ # but as the default
+ # location of the library.
+
+ case $cc_basename in
+ CC*)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ aCC*)
+ archive_cmds_CXX='$rm $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "[-]L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ *)
+ if test "$GXX" = yes; then
+ archive_cmds_CXX='$rm $output_objdir/$soname~$CC -shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ else
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ fi
+ ;;
+ esac
+ ;;
+ hpux10*|hpux11*)
+ if test $with_gnu_ld = no; then
+ hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir'
+ hardcode_libdir_separator_CXX=:
+
+ case $host_cpu in
+ hppa*64*|ia64*)
+ hardcode_libdir_flag_spec_ld_CXX='+b $libdir'
+ ;;
+ *)
+ export_dynamic_flag_spec_CXX='${wl}-E'
+ ;;
+ esac
+ fi
+ case $host_cpu in
+ hppa*64*|ia64*)
+ hardcode_direct_CXX=no
+ hardcode_shlibpath_var_CXX=no
+ ;;
+ *)
+ hardcode_direct_CXX=yes
+ hardcode_minus_L_CXX=yes # Not in the search PATH,
+ # but as the default
+ # location of the library.
+ ;;
+ esac
+
+ case $cc_basename in
+ CC*)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ aCC*)
+ case $host_cpu in
+ hppa*64*)
+ archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ ia64*)
+ archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ *)
+ archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ esac
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | grep "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ *)
+ if test "$GXX" = yes; then
+ if test $with_gnu_ld = no; then
+ case $host_cpu in
+ hppa*64*)
+ archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ ia64*)
+ archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ *)
+ archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ ;;
+ esac
+ fi
+ else
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ fi
+ ;;
+ esac
+ ;;
+ interix3*)
+ hardcode_direct_CXX=no
+ hardcode_shlibpath_var_CXX=no
+ hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir'
+ export_dynamic_flag_spec_CXX='${wl}-E'
+ # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+ # Instead, shared libraries are loaded at an image base (0x10000000 by
+ # default) and relocated if they conflict, which is a slow very memory
+ # consuming and fragmenting process. To avoid this, we pick a random,
+ # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+ # time. Moving up from 0x10000000 also allows more sbrk(2) space.
+ archive_cmds_CXX='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ archive_expsym_cmds_CXX='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ ;;
+ irix5* | irix6*)
+ case $cc_basename in
+ CC*)
+ # SGI C++
+ archive_cmds_CXX='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+
+ # Archives containing C++ object files must be created using
+ # "CC -ar", where "CC" is the IRIX C++ compiler. This is
+ # necessary to make sure instantiated templates are included
+ # in the archive.
+ old_archive_cmds_CXX='$CC -ar -WR,-u -o $oldlib $oldobjs'
+ ;;
+ *)
+ if test "$GXX" = yes; then
+ if test "$with_gnu_ld" = no; then
+ archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ else
+ archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` -o $lib'
+ fi
+ fi
+ link_all_deplibs_CXX=yes
+ ;;
+ esac
+ hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator_CXX=:
+ ;;
+ linux*)
+ case $cc_basename in
+ KCC*)
+ # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+ # KCC will only create a shared library if the output file
+ # ends with ".so" (or ".sl" for HP-UX), so rename the library
+ # to its proper name (with version) after linking.
+ archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+ archive_expsym_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | grep "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+
+ hardcode_libdir_flag_spec_CXX='${wl}--rpath,$libdir'
+ export_dynamic_flag_spec_CXX='${wl}--export-dynamic'
+
+ # Archives containing C++ object files must be created using
+ # "CC -Bstatic", where "CC" is the KAI C++ compiler.
+ old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs'
+ ;;
+ icpc*)
+ # Intel C++
+ with_gnu_ld=yes
+ # version 8.0 and above of icpc choke on multiply defined symbols
+ # if we add $predep_objects and $postdep_objects, however 7.1 and
+ # earlier do not add the objects themselves.
+ case `$CC -V 2>&1` in
+ *"Version 7."*)
+ archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ ;;
+ *) # Version 8.0 or newer
+ tmp_idyn=
+ case $host_cpu in
+ ia64*) tmp_idyn=' -i_dynamic';;
+ esac
+ archive_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ archive_expsym_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ ;;
+ esac
+ archive_cmds_need_lc_CXX=no
+ hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir'
+ export_dynamic_flag_spec_CXX='${wl}--export-dynamic'
+ whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+ ;;
+ pgCC*)
+ # Portland Group C++ compiler
+ archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+ archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+
+ hardcode_libdir_flag_spec_CXX='${wl}--rpath ${wl}$libdir'
+ export_dynamic_flag_spec_CXX='${wl}--export-dynamic'
+ whole_archive_flag_spec_CXX='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+ ;;
+ cxx*)
+ # Compaq C++
+ archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
+
+ runpath_var=LD_RUN_PATH
+ hardcode_libdir_flag_spec_CXX='-rpath $libdir'
+ hardcode_libdir_separator_CXX=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ esac
+ ;;
+ lynxos*)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ m88k*)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ mvs*)
+ case $cc_basename in
+ cxx*)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ esac
+ ;;
+ netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ archive_cmds_CXX='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags'
+ wlarc=
+ hardcode_libdir_flag_spec_CXX='-R$libdir'
+ hardcode_direct_CXX=yes
+ hardcode_shlibpath_var_CXX=no
+ fi
+ # Workaround some broken pre-1.5 toolchains
+ output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
+ ;;
+ openbsd2*)
+ # C++ shared libraries are fairly broken
+ ld_shlibs_CXX=no
+ ;;
+ openbsd*)
+ hardcode_direct_CXX=yes
+ hardcode_shlibpath_var_CXX=no
+ archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+ hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir'
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
+ export_dynamic_flag_spec_CXX='${wl}-E'
+ whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+ fi
+ output_verbose_link_cmd='echo'
+ ;;
+ osf3*)
+ case $cc_basename in
+ KCC*)
+ # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+ # KCC will only create a shared library if the output file
+ # ends with ".so" (or ".sl" for HP-UX), so rename the library
+ # to its proper name (with version) after linking.
+ archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+
+ hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir'
+ hardcode_libdir_separator_CXX=:
+
+ # Archives containing C++ object files must be created using
+ # "CC -Bstatic", where "CC" is the KAI C++ compiler.
+ old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs'
+
+ ;;
+ RCC*)
+ # Rational C++ 2.4.1
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ cxx*)
+ allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*'
+ archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && echo ${wl}-set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+
+ hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator_CXX=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ *)
+ if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+ allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*'
+ archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+
+ hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator_CXX=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"'
+
+ else
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ fi
+ ;;
+ esac
+ ;;
+ osf4* | osf5*)
+ case $cc_basename in
+ KCC*)
+ # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+ # KCC will only create a shared library if the output file
+ # ends with ".so" (or ".sl" for HP-UX), so rename the library
+ # to its proper name (with version) after linking.
+ archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+
+ hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir'
+ hardcode_libdir_separator_CXX=:
+
+ # Archives containing C++ object files must be created using
+ # the KAI C++ compiler.
+ old_archive_cmds_CXX='$CC -o $oldlib $oldobjs'
+ ;;
+ RCC*)
+ # Rational C++ 2.4.1
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ cxx*)
+ allow_undefined_flag_CXX=' -expect_unresolved \*'
+ archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ archive_expsym_cmds_CXX='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
+ echo "-hidden">> $lib.exp~
+ $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname -Wl,-input -Wl,$lib.exp `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~
+ $rm $lib.exp'
+
+ hardcode_libdir_flag_spec_CXX='-rpath $libdir'
+ hardcode_libdir_separator_CXX=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ #
+ # There doesn't appear to be a way to prevent this compiler from
+ # explicitly linking system object files so we need to strip them
+ # from the output so that they don't get included in the library
+ # dependencies.
+ output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "ld" | grep -v "ld:"`; templist=`echo $templist | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; echo $list'
+ ;;
+ *)
+ if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+ allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*'
+ archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+
+ hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator_CXX=:
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep "\-L"'
+
+ else
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ fi
+ ;;
+ esac
+ ;;
+ psos*)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ sunos4*)
+ case $cc_basename in
+ CC*)
+ # Sun C++ 4.x
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ lcc*)
+ # Lucid
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ esac
+ ;;
+ solaris*)
+ case $cc_basename in
+ CC*)
+ # Sun C++ 4.2, 5.x and Centerline C++
+ archive_cmds_need_lc_CXX=yes
+ no_undefined_flag_CXX=' -zdefs'
+ archive_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+ archive_expsym_cmds_CXX='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
+
+ hardcode_libdir_flag_spec_CXX='-R$libdir'
+ hardcode_shlibpath_var_CXX=no
+ case $host_os in
+ solaris2.[0-5] | solaris2.[0-5].*) ;;
+ *)
+ # The C++ compiler is used as linker so we must use $wl
+ # flag to pass the commands to the underlying system
+ # linker. We must also pass each convience library through
+ # to the system linker between allextract/defaultextract.
+ # The C++ compiler will combine linker options so we
+ # cannot just pass the convience library names through
+ # without $wl.
+ # Supported since Solaris 2.6 (maybe 2.5.1?)
+ whole_archive_flag_spec_CXX='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract'
+ ;;
+ esac
+ link_all_deplibs_CXX=yes
+
+ output_verbose_link_cmd='echo'
+
+ # Archives containing C++ object files must be created using
+ # "CC -xar", where "CC" is the Sun C++ compiler. This is
+ # necessary to make sure instantiated templates are included
+ # in the archive.
+ old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs'
+ ;;
+ gcx*)
+ # Green Hills C++ Compiler
+ archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+
+ # The C++ compiler must be used to create the archive.
+ old_archive_cmds_CXX='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
+ ;;
+ *)
+ # GNU C++ compiler with Solaris linker
+ if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+ no_undefined_flag_CXX=' ${wl}-z ${wl}defs'
+ if $CC --version | grep -v '^2\.7' > /dev/null; then
+ archive_cmds_CXX='$CC -shared -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+ archive_expsym_cmds_CXX='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd="$CC -shared $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\""
+ else
+ # g++ 2.7 appears to require `-G' NOT `-shared' on this
+ # platform.
+ archive_cmds_CXX='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+ archive_expsym_cmds_CXX='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
+
+ # Commands to make compiler produce verbose output that lists
+ # what "hidden" libraries, object files and flags are used when
+ # linking a shared library.
+ output_verbose_link_cmd="$CC -G $CFLAGS -v conftest.$objext 2>&1 | grep \"\-L\""
+ fi
+
+ hardcode_libdir_flag_spec_CXX='${wl}-R $wl$libdir'
+ fi
+ ;;
+ esac
+ ;;
+ sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*)
+ no_undefined_flag_CXX='${wl}-z,text'
+ archive_cmds_need_lc_CXX=no
+ hardcode_shlibpath_var_CXX=no
+ runpath_var='LD_RUN_PATH'
+
+ case $cc_basename in
+ CC*)
+ archive_cmds_CXX='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ archive_cmds_CXX='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ ;;
+ sysv5* | sco3.2v5* | sco5v6*)
+ # Note: We can NOT use -z defs as we might desire, because we do not
+ # link with -lc, and that would cause any symbols used from libc to
+ # always be unresolved, which means just about no library would
+ # ever link correctly. If we're not using GNU ld we use -z text
+ # though, which does catch some bad symbols but isn't as heavy-handed
+ # as -z defs.
+ # For security reasons, it is highly recommended that you always
+ # use absolute paths for naming shared libraries, and exclude the
+ # DT_RUNPATH tag from executables and libraries. But doing so
+ # requires that you compile everything twice, which is a pain.
+ # So that behaviour is only enabled if SCOABSPATH is set to a
+ # non-empty value in the environment. Most likely only useful for
+ # creating official distributions of packages.
+ # This is a hack until libtool officially supports absolute path
+ # names for shared libraries.
+ no_undefined_flag_CXX='${wl}-z,text'
+ allow_undefined_flag_CXX='${wl}-z,nodefs'
+ archive_cmds_need_lc_CXX=no
+ hardcode_shlibpath_var_CXX=no
+ hardcode_libdir_flag_spec_CXX='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
+ hardcode_libdir_separator_CXX=':'
+ link_all_deplibs_CXX=yes
+ export_dynamic_flag_spec_CXX='${wl}-Bexport'
+ runpath_var='LD_RUN_PATH'
+
+ case $cc_basename in
+ CC*)
+ archive_cmds_CXX='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ archive_cmds_CXX='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ ;;
+ tandem*)
+ case $cc_basename in
+ NCC*)
+ # NonStop-UX NCC 3.20
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ esac
+ ;;
+ vxworks*)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+ *)
+ # FIXME: insert proper C++ library support
+ ld_shlibs_CXX=no
+ ;;
+esac
+echo "$as_me:$LINENO: result: $ld_shlibs_CXX" >&5
+echo "${ECHO_T}$ld_shlibs_CXX" >&6
+test "$ld_shlibs_CXX" = no && can_build_shared=no
+
+GCC_CXX="$GXX"
+LD_CXX="$LD"
+
+
+cat > conftest.$ac_ext <<EOF
+class Foo
+{
+public:
+ Foo (void) { a = 0; }
+private:
+ int a;
+};
+EOF
+
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ # Parse the compiler output and extract the necessary
+ # objects, libraries and library flags.
+
+ # Sentinel used to keep track of whether or not we are before
+ # the conftest object file.
+ pre_test_object_deps_done=no
+
+ # The `*' in the case matches for architectures that use `case' in
+ # $output_verbose_cmd can trigger glob expansion during the loop
+ # eval without this substitution.
+ output_verbose_link_cmd=`$echo "X$output_verbose_link_cmd" | $Xsed -e "$no_glob_subst"`
+
+ for p in `eval $output_verbose_link_cmd`; do
+ case $p in
+
+ -L* | -R* | -l*)
+ # Some compilers place space between "-{L,R}" and the path.
+ # Remove the space.
+ if test $p = "-L" \
+ || test $p = "-R"; then
+ prev=$p
+ continue
+ else
+ prev=
+ fi
+
+ if test "$pre_test_object_deps_done" = no; then
+ case $p in
+ -L* | -R*)
+ # Internal compiler library paths should come after those
+ # provided the user. The postdeps already come after the
+ # user supplied libs so there is no need to process them.
+ if test -z "$compiler_lib_search_path_CXX"; then
+ compiler_lib_search_path_CXX="${prev}${p}"
+ else
+ compiler_lib_search_path_CXX="${compiler_lib_search_path_CXX} ${prev}${p}"
+ fi
+ ;;
+ # The "-l" case would never come before the object being
+ # linked, so don't bother handling this case.
+ esac
+ else
+ if test -z "$postdeps_CXX"; then
+ postdeps_CXX="${prev}${p}"
+ else
+ postdeps_CXX="${postdeps_CXX} ${prev}${p}"
+ fi
+ fi
+ ;;
+
+ *.$objext)
+ # This assumes that the test object file only shows up
+ # once in the compiler output.
+ if test "$p" = "conftest.$objext"; then
+ pre_test_object_deps_done=yes
+ continue
+ fi
+
+ if test "$pre_test_object_deps_done" = no; then
+ if test -z "$predep_objects_CXX"; then
+ predep_objects_CXX="$p"
+ else
+ predep_objects_CXX="$predep_objects_CXX $p"
+ fi
+ else
+ if test -z "$postdep_objects_CXX"; then
+ postdep_objects_CXX="$p"
+ else
+ postdep_objects_CXX="$postdep_objects_CXX $p"
+ fi
+ fi
+ ;;
+
+ *) ;; # Ignore the rest.
+
+ esac
+ done
+
+ # Clean up.
+ rm -f a.out a.exe
+else
+ echo "libtool.m4: error: problem compiling CXX test program"
+fi
+
+$rm -f confest.$objext
+
+# PORTME: override above test on systems where it is broken
+case $host_os in
+interix3*)
+ # Interix 3.5 installs completely hosed .la files for C++, so rather than
+ # hack all around it, let's just trust "g++" to DTRT.
+ predep_objects_CXX=
+ postdep_objects_CXX=
+ postdeps_CXX=
+ ;;
+
+solaris*)
+ case $cc_basename in
+ CC*)
+ # Adding this requires a known-good setup of shared libraries for
+ # Sun compiler versions before 5.6, else PIC objects from an old
+ # archive will be linked into the output, leading to subtle bugs.
+ postdeps_CXX='-lCstd -lCrun'
+ ;;
+ esac
+ ;;
+esac
+
+
+case " $postdeps_CXX " in
+*" -lc "*) archive_cmds_need_lc_CXX=no ;;
+esac
+
+lt_prog_compiler_wl_CXX=
+lt_prog_compiler_pic_CXX=
+lt_prog_compiler_static_CXX=
+
+echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
+echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6
+
+ # C++ specific cases for pic, static, wl, etc.
+ if test "$GXX" = yes; then
+ lt_prog_compiler_wl_CXX='-Wl,'
+ lt_prog_compiler_static_CXX='-static'
+
+ case $host_os in
+ aix*)
+ # All AIX code is PIC.
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ lt_prog_compiler_static_CXX='-Bstatic'
+ fi
+ ;;
+ amigaos*)
+ # FIXME: we need at least 68020 code to build shared libraries, but
+ # adding the `-m68020' flag to GCC prevents building anything better,
+ # like `-m68040'.
+ lt_prog_compiler_pic_CXX='-m68020 -resident32 -malways-restore-a4'
+ ;;
+ beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+ # PIC is the default for these OSes.
+ ;;
+ mingw* | os2* | pw32*)
+ # This hack is so that the source file can tell whether it is being
+ # built for inclusion in a dll (and should export symbols for example).
+ lt_prog_compiler_pic_CXX='-DDLL_EXPORT'
+ ;;
+ darwin* | rhapsody*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ lt_prog_compiler_pic_CXX='-fno-common'
+ ;;
+ *djgpp*)
+ # DJGPP does not support shared libraries at all
+ lt_prog_compiler_pic_CXX=
+ ;;
+ interix3*)
+ # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+ # Instead, we relocate shared libraries at runtime.
+ ;;
+ sysv4*MP*)
+ if test -d /usr/nec; then
+ lt_prog_compiler_pic_CXX=-Kconform_pic
+ fi
+ ;;
+ hpux*)
+ # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+ # not for PA HP-UX.
+ case $host_cpu in
+ hppa*64*|ia64*)
+ ;;
+ *)
+ lt_prog_compiler_pic_CXX='-fPIC'
+ ;;
+ esac
+ ;;
+ *)
+ lt_prog_compiler_pic_CXX='-fPIC'
+ ;;
+ esac
+ else
+ case $host_os in
+ aix4* | aix5*)
+ # All AIX code is PIC.
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ lt_prog_compiler_static_CXX='-Bstatic'
+ else
+ lt_prog_compiler_static_CXX='-bnso -bI:/lib/syscalls.exp'
+ fi
+ ;;
+ chorus*)
+ case $cc_basename in
+ cxch68*)
+ # Green Hills C++ Compiler
+ # _LT_AC_TAGVAR(lt_prog_compiler_static, CXX)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
+ ;;
+ esac
+ ;;
+ darwin*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ case $cc_basename in
+ xlc*)
+ lt_prog_compiler_pic_CXX='-qnocommon'
+ lt_prog_compiler_wl_CXX='-Wl,'
+ ;;
+ esac
+ ;;
+ dgux*)
+ case $cc_basename in
+ ec++*)
+ lt_prog_compiler_pic_CXX='-KPIC'
+ ;;
+ ghcx*)
+ # Green Hills C++ Compiler
+ lt_prog_compiler_pic_CXX='-pic'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ freebsd* | kfreebsd*-gnu | dragonfly*)
+ # FreeBSD uses GNU C++
+ ;;
+ hpux9* | hpux10* | hpux11*)
+ case $cc_basename in
+ CC*)
+ lt_prog_compiler_wl_CXX='-Wl,'
+ lt_prog_compiler_static_CXX='${wl}-a ${wl}archive'
+ if test "$host_cpu" != ia64; then
+ lt_prog_compiler_pic_CXX='+Z'
+ fi
+ ;;
+ aCC*)
+ lt_prog_compiler_wl_CXX='-Wl,'
+ lt_prog_compiler_static_CXX='${wl}-a ${wl}archive'
+ case $host_cpu in
+ hppa*64*|ia64*)
+ # +Z the default
+ ;;
+ *)
+ lt_prog_compiler_pic_CXX='+Z'
+ ;;
+ esac
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ interix*)
+ # This is c89, which is MS Visual C++ (no shared libs)
+ # Anyone wants to do a port?
+ ;;
+ irix5* | irix6* | nonstopux*)
+ case $cc_basename in
+ CC*)
+ lt_prog_compiler_wl_CXX='-Wl,'
+ lt_prog_compiler_static_CXX='-non_shared'
+ # CC pic flag -KPIC is the default.
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ linux*)
+ case $cc_basename in
+ KCC*)
+ # KAI C++ Compiler
+ lt_prog_compiler_wl_CXX='--backend -Wl,'
+ lt_prog_compiler_pic_CXX='-fPIC'
+ ;;
+ icpc* | ecpc*)
+ # Intel C++
+ lt_prog_compiler_wl_CXX='-Wl,'
+ lt_prog_compiler_pic_CXX='-KPIC'
+ lt_prog_compiler_static_CXX='-static'
+ ;;
+ pgCC*)
+ # Portland Group C++ compiler.
+ lt_prog_compiler_wl_CXX='-Wl,'
+ lt_prog_compiler_pic_CXX='-fpic'
+ lt_prog_compiler_static_CXX='-Bstatic'
+ ;;
+ cxx*)
+ # Compaq C++
+ # Make sure the PIC flag is empty. It appears that all Alpha
+ # Linux and Compaq Tru64 Unix objects are PIC.
+ lt_prog_compiler_pic_CXX=
+ lt_prog_compiler_static_CXX='-non_shared'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ lynxos*)
+ ;;
+ m88k*)
+ ;;
+ mvs*)
+ case $cc_basename in
+ cxx*)
+ lt_prog_compiler_pic_CXX='-W c,exportall'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ netbsd*)
+ ;;
+ osf3* | osf4* | osf5*)
+ case $cc_basename in
+ KCC*)
+ lt_prog_compiler_wl_CXX='--backend -Wl,'
+ ;;
+ RCC*)
+ # Rational C++ 2.4.1
+ lt_prog_compiler_pic_CXX='-pic'
+ ;;
+ cxx*)
+ # Digital/Compaq C++
+ lt_prog_compiler_wl_CXX='-Wl,'
+ # Make sure the PIC flag is empty. It appears that all Alpha
+ # Linux and Compaq Tru64 Unix objects are PIC.
+ lt_prog_compiler_pic_CXX=
+ lt_prog_compiler_static_CXX='-non_shared'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ psos*)
+ ;;
+ solaris*)
+ case $cc_basename in
+ CC*)
+ # Sun C++ 4.2, 5.x and Centerline C++
+ lt_prog_compiler_pic_CXX='-KPIC'
+ lt_prog_compiler_static_CXX='-Bstatic'
+ lt_prog_compiler_wl_CXX='-Qoption ld '
+ ;;
+ gcx*)
+ # Green Hills C++ Compiler
+ lt_prog_compiler_pic_CXX='-PIC'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ sunos4*)
+ case $cc_basename in
+ CC*)
+ # Sun C++ 4.x
+ lt_prog_compiler_pic_CXX='-pic'
+ lt_prog_compiler_static_CXX='-Bstatic'
+ ;;
+ lcc*)
+ # Lucid
+ lt_prog_compiler_pic_CXX='-pic'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ tandem*)
+ case $cc_basename in
+ NCC*)
+ # NonStop-UX NCC 3.20
+ lt_prog_compiler_pic_CXX='-KPIC'
+ ;;
+ *)
+ ;;
+ esac
+ ;;
+ sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+ case $cc_basename in
+ CC*)
+ lt_prog_compiler_wl_CXX='-Wl,'
+ lt_prog_compiler_pic_CXX='-KPIC'
+ lt_prog_compiler_static_CXX='-Bstatic'
+ ;;
+ esac
+ ;;
+ vxworks*)
+ ;;
+ *)
+ lt_prog_compiler_can_build_shared_CXX=no
+ ;;
+ esac
+ fi
+
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_CXX" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_CXX" >&6
+
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$lt_prog_compiler_pic_CXX"; then
+
+echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works" >&5
+echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works... $ECHO_C" >&6
+if test "${lt_prog_compiler_pic_works_CXX+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_prog_compiler_pic_works_CXX=no
+ ac_outfile=conftest.$ac_objext
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+ lt_compiler_flag="$lt_prog_compiler_pic_CXX -DPIC"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ # The option is referenced via a variable to avoid confusing sed.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:11787: $lt_compile\"" >&5)
+ (eval "$lt_compile" 2>conftest.err)
+ ac_status=$?
+ cat conftest.err >&5
+ echo "$as_me:11791: \$? = $ac_status" >&5
+ if (exit $ac_status) && test -s "$ac_outfile"; then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings other than the usual output.
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+ lt_prog_compiler_pic_works_CXX=yes
+ fi
+ fi
+ $rm conftest*
+
+fi
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_CXX" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_works_CXX" >&6
+
+if test x"$lt_prog_compiler_pic_works_CXX" = xyes; then
+ case $lt_prog_compiler_pic_CXX in
+ "" | " "*) ;;
+ *) lt_prog_compiler_pic_CXX=" $lt_prog_compiler_pic_CXX" ;;
+ esac
+else
+ lt_prog_compiler_pic_CXX=
+ lt_prog_compiler_can_build_shared_CXX=no
+fi
+
+fi
+case $host_os in
+ # For platforms which do not support PIC, -DPIC is meaningless:
+ *djgpp*)
+ lt_prog_compiler_pic_CXX=
+ ;;
+ *)
+ lt_prog_compiler_pic_CXX="$lt_prog_compiler_pic_CXX -DPIC"
+ ;;
+esac
+
+#
+# Check to make sure the static flag actually works.
+#
+wl=$lt_prog_compiler_wl_CXX eval lt_tmp_static_flag=\"$lt_prog_compiler_static_CXX\"
+echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
+echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6
+if test "${lt_prog_compiler_static_works_CXX+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_prog_compiler_static_works_CXX=no
+ save_LDFLAGS="$LDFLAGS"
+ LDFLAGS="$LDFLAGS $lt_tmp_static_flag"
+ printf "$lt_simple_link_test_code" > conftest.$ac_ext
+ if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+ # The linker can only warn and ignore the option if not recognized
+ # So say no if there are warnings
+ if test -s conftest.err; then
+ # Append any errors to the config.log.
+ cat conftest.err 1>&5
+ $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if diff conftest.exp conftest.er2 >/dev/null; then
+ lt_prog_compiler_static_works_CXX=yes
+ fi
+ else
+ lt_prog_compiler_static_works_CXX=yes
+ fi
+ fi
+ $rm conftest*
+ LDFLAGS="$save_LDFLAGS"
+
+fi
+echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_CXX" >&5
+echo "${ECHO_T}$lt_prog_compiler_static_works_CXX" >&6
+
+if test x"$lt_prog_compiler_static_works_CXX" = xyes; then
+ :
+else
+ lt_prog_compiler_static_CXX=
+fi
+
+
+echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
+echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6
+if test "${lt_cv_prog_compiler_c_o_CXX+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_cv_prog_compiler_c_o_CXX=no
+ $rm -r conftest 2>/dev/null
+ mkdir conftest
+ cd conftest
+ mkdir out
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+ lt_compiler_flag="-o out/conftest2.$ac_objext"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:11891: $lt_compile\"" >&5)
+ (eval "$lt_compile" 2>out/conftest.err)
+ ac_status=$?
+ cat out/conftest.err >&5
+ echo "$as_me:11895: \$? = $ac_status" >&5
+ if (exit $ac_status) && test -s out/conftest2.$ac_objext
+ then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
+ $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+ if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+ lt_cv_prog_compiler_c_o_CXX=yes
+ fi
+ fi
+ chmod u+w . 2>&5
+ $rm conftest*
+ # SGI C++ compiler will create directory out/ii_files/ for
+ # template instantiation
+ test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files
+ $rm out/* && rmdir out
+ cd ..
+ rmdir conftest
+ $rm conftest*
+
+fi
+echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_CXX" >&5
+echo "${ECHO_T}$lt_cv_prog_compiler_c_o_CXX" >&6
+
+
+hard_links="nottested"
+if test "$lt_cv_prog_compiler_c_o_CXX" = no && test "$need_locks" != no; then
+ # do not overwrite the value of need_locks provided by the user
+ echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
+echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6
+ hard_links=yes
+ $rm conftest*
+ ln conftest.a conftest.b 2>/dev/null && hard_links=no
+ touch conftest.a
+ ln conftest.a conftest.b 2>&5 || hard_links=no
+ ln conftest.a conftest.b 2>/dev/null && hard_links=no
+ echo "$as_me:$LINENO: result: $hard_links" >&5
+echo "${ECHO_T}$hard_links" >&6
+ if test "$hard_links" = no; then
+ { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
+echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
+ need_locks=warn
+ fi
+else
+ need_locks=no
+fi
+
+echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6
+
+ export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+ case $host_os in
+ aix4* | aix5*)
+ # If we're using GNU nm, then we don't want the "-C" option.
+ # -C means demangle to AIX nm, but means don't demangle with GNU nm
+ if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
+ export_symbols_cmds_CXX='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
+ else
+ export_symbols_cmds_CXX='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
+ fi
+ ;;
+ pw32*)
+ export_symbols_cmds_CXX="$ltdll_cmds"
+ ;;
+ cygwin* | mingw*)
+ export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS] /s/.* \([^ ]*\)/\1 DATA/;/^.* __nm__/s/^.* __nm__\([^ ]*\) [^ ]*/\1 DATA/;/^I /d;/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols'
+ ;;
+ *)
+ export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+ ;;
+ esac
+
+echo "$as_me:$LINENO: result: $ld_shlibs_CXX" >&5
+echo "${ECHO_T}$ld_shlibs_CXX" >&6
+test "$ld_shlibs_CXX" = no && can_build_shared=no
+
+#
+# Do we need to explicitly link libc?
+#
+case "x$archive_cmds_need_lc_CXX" in
+x|xyes)
+ # Assume -lc should be added
+ archive_cmds_need_lc_CXX=yes
+
+ if test "$enable_shared" = yes && test "$GCC" = yes; then
+ case $archive_cmds_CXX in
+ *'~'*)
+ # FIXME: we may have to deal with multi-command sequences.
+ ;;
+ '$CC '*)
+ # Test whether the compiler implicitly links with -lc since on some
+ # systems, -lgcc has to come before -lc. If gcc already passes -lc
+ # to ld, don't add -lc before -lgcc.
+ echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
+echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6
+ $rm conftest*
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } 2>conftest.err; then
+ soname=conftest
+ lib=conftest
+ libobjs=conftest.$ac_objext
+ deplibs=
+ wl=$lt_prog_compiler_wl_CXX
+ pic_flag=$lt_prog_compiler_pic_CXX
+ compiler_flags=-v
+ linker_flags=-v
+ verstring=
+ output_objdir=.
+ libname=conftest
+ lt_save_allow_undefined_flag=$allow_undefined_flag_CXX
+ allow_undefined_flag_CXX=
+ if { (eval echo "$as_me:$LINENO: \"$archive_cmds_CXX 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5
+ (eval $archive_cmds_CXX 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+ then
+ archive_cmds_need_lc_CXX=no
+ else
+ archive_cmds_need_lc_CXX=yes
+ fi
+ allow_undefined_flag_CXX=$lt_save_allow_undefined_flag
+ else
+ cat conftest.err 1>&5
+ fi
+ $rm conftest*
+ echo "$as_me:$LINENO: result: $archive_cmds_need_lc_CXX" >&5
+echo "${ECHO_T}$archive_cmds_need_lc_CXX" >&6
+ ;;
+ esac
+ fi
+ ;;
+esac
+
+echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
+echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
+ # if the path contains ";" then we assume it to be the separator
+ # otherwise default to the standard path separator (i.e. ":") - it is
+ # assumed that no part of a normal pathname contains ";" but that should
+ # okay in the real world where ";" in dirpaths is itself problematic.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+else
+ sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+ shlibpath_var=LIBPATH
+
+ # AIX 3 has no versioning support, so we append a major version to the name.
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+
+aix4* | aix5*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ hardcode_into_libs=yes
+ if test "$host_cpu" = ia64; then
+ # AIX 5 supports IA64
+ library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ else
+ # With GCC up to 2.95.x, collect2 would create an import file
+ # for dependence libraries. The import file would start with
+ # the line `#! .'. This would cause the generated library to
+ # depend on `.', always an invalid library. This was fixed in
+ # development snapshots of GCC prior to 3.0.
+ case $host_os in
+ aix4 | aix4.[01] | aix4.[01].*)
+ if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+ echo ' yes '
+ echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
+ :
+ else
+ can_build_shared=no
+ fi
+ ;;
+ esac
+ # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+ # soname into executable. Probably we can add versioning support to
+ # collect2, so additional links can be useful in future.
+ if test "$aix_use_runtimelinking" = yes; then
+ # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+ # instead of lib<name>.a to let people know that these are not
+ # typical AIX shared libraries.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ else
+ # We preserve .a as extension for shared libraries through AIX4.2
+ # and later when we are not doing run time linking.
+ library_names_spec='${libname}${release}.a $libname.a'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ fi
+ shlibpath_var=LIBPATH
+ fi
+ ;;
+
+amigaos*)
+ library_names_spec='$libname.ixlibrary $libname.a'
+ # Create ${libname}_ixlibrary.a entries in /sys/libs.
+ finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+ ;;
+
+beos*)
+ library_names_spec='${libname}${shared_ext}'
+ dynamic_linker="$host_os ld.so"
+ shlibpath_var=LIBRARY_PATH
+ ;;
+
+bsdi[45]*)
+ version_type=linux
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+ sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+ # the default ld.so.conf also contains /usr/contrib/lib and
+ # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+ # libtool to hard-code these into programs
+ ;;
+
+cygwin* | mingw* | pw32*)
+ version_type=windows
+ shrext_cmds=".dll"
+ need_version=no
+ need_lib_prefix=no
+
+ case $GCC,$host_os in
+ yes,cygwin* | yes,mingw* | yes,pw32*)
+ library_names_spec='$libname.dll.a'
+ # DLL is installed to $(libdir)/../bin by postinstall_cmds
+ postinstall_cmds='base_file=`basename \${file}`~
+ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~
+ dldir=$destdir/`dirname \$dlpath`~
+ test -d \$dldir || mkdir -p \$dldir~
+ $install_prog $dir/$dlname \$dldir/$dlname~
+ chmod a+x \$dldir/$dlname'
+ postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+ dlpath=$dir/\$dldll~
+ $rm \$dlpath'
+ shlibpath_overrides_runpath=yes
+
+ case $host_os in
+ cygwin*)
+ # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+ soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib"
+ ;;
+ mingw*)
+ # MinGW DLLs use traditional 'lib' prefix
+ soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then
+ # It is most probably a Windows format PATH printed by
+ # mingw gcc, but we are running on Cygwin. Gcc prints its search
+ # path with ; separators, and with drive letters. We can handle the
+ # drive letters (cygwin fileutils understands them), so leave them,
+ # especially as we might pass files found there to a mingw objdump,
+ # which wouldn't understand a cygwinified path. Ahh.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+ ;;
+ pw32*)
+ # pw32 DLLs use 'pw' prefix rather than 'lib'
+ library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ ;;
+ esac
+ ;;
+
+ *)
+ library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib'
+ ;;
+ esac
+ dynamic_linker='Win32 ld.exe'
+ # FIXME: first we should search . and the directory the executable is in
+ shlibpath_var=PATH
+ ;;
+
+darwin* | rhapsody*)
+ dynamic_linker="$host_os dyld"
+ version_type=darwin
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+ soname_spec='${libname}${release}${major}$shared_ext'
+ shlibpath_overrides_runpath=yes
+ shlibpath_var=DYLD_LIBRARY_PATH
+ shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+ # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
+ if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
+ else
+ sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib'
+ fi
+ sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+ ;;
+
+dgux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+freebsd1*)
+ dynamic_linker=no
+ ;;
+
+kfreebsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+freebsd* | dragonfly*)
+ # DragonFly does not have aout. When/if they implement a new
+ # versioning mechanism, adjust this.
+ if test -x /usr/bin/objformat; then
+ objformat=`/usr/bin/objformat`
+ else
+ case $host_os in
+ freebsd[123]*) objformat=aout ;;
+ *) objformat=elf ;;
+ esac
+ fi
+ version_type=freebsd-$objformat
+ case $version_type in
+ freebsd-elf*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ need_version=no
+ need_lib_prefix=no
+ ;;
+ freebsd-*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+ need_version=yes
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_os in
+ freebsd2*)
+ shlibpath_overrides_runpath=yes
+ ;;
+ freebsd3.[01]* | freebsdelf3.[01]*)
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
+ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+ freebsd*) # from 4.6 on
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ esac
+ ;;
+
+gnu*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ ;;
+
+hpux9* | hpux10* | hpux11*)
+ # Give a soname corresponding to the major version so that dld.sl refuses to
+ # link against other versions.
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ case $host_cpu in
+ ia64*)
+ shrext_cmds='.so'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.so"
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ if test "X$HPUX_IA64_MODE" = X32; then
+ sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+ else
+ sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+ fi
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ hppa*64*)
+ shrext_cmds='.sl'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ *)
+ shrext_cmds='.sl'
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=SHLIB_PATH
+ shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+ esac
+ # HP-UX runs *really* slowly unless shared libraries are mode 555.
+ postinstall_cmds='chmod 555 $lib'
+ ;;
+
+interix3*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+
+irix5* | irix6* | nonstopux*)
+ case $host_os in
+ nonstopux*) version_type=nonstopux ;;
+ *)
+ if test "$lt_cv_prog_gnu_ld" = yes; then
+ version_type=linux
+ else
+ version_type=irix
+ fi ;;
+ esac
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+ case $host_os in
+ irix5* | nonstopux*)
+ libsuff= shlibsuff=
+ ;;
+ *)
+ case $LD in # libtool.m4 will add one of these switches to LD
+ *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+ libsuff= shlibsuff= libmagic=32-bit;;
+ *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+ libsuff=32 shlibsuff=N32 libmagic=N32;;
+ *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+ libsuff=64 shlibsuff=64 libmagic=64-bit;;
+ *) libsuff= shlibsuff= libmagic=never-match;;
+ esac
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+ sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+ hardcode_into_libs=yes
+ ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+ dynamic_linker=no
+ ;;
+
+# This must be Linux ELF.
+linux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ # This implies no fast_install, which is unacceptable.
+ # Some rework will be needed to allow for fast_install
+ # before this can be enabled.
+ hardcode_into_libs=yes
+
+ # find out which ABI we are using
+ libsuff=
+ case "$host_cpu" in
+ x86_64*|s390x*|powerpc64*)
+ echo '#line 12427 "configure"' > conftest.$ac_ext
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ case `/usr/bin/file conftest.$ac_objext` in
+ *64-bit*)
+ libsuff=64
+ sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}"
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+ esac
+
+ # Append ld.so.conf contents to the search path
+ if test -f /etc/ld.so.conf; then
+ lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+ sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra"
+ fi
+
+ # We used to test for /lib/ld.so.1 and disable shared libraries on
+ # powerpc, because MkLinux only supported shared libraries with the
+ # GNU dynamic linker. Since this was broken with cross compilers,
+ # most powerpc-linux boxes support dynamic linking these days and
+ # people can always --disable-shared, the test was removed, and we
+ # assume the GNU/Linux dynamic linker is in use.
+ dynamic_linker='GNU/Linux ld.so'
+ ;;
+
+knetbsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+netbsd*)
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ dynamic_linker='NetBSD (a.out) ld.so'
+ else
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='NetBSD ld.elf_so'
+ fi
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+
+newsos6)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+nto-qnx*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+openbsd*)
+ version_type=sunos
+ sys_lib_dlsearch_path_spec="/usr/lib"
+ need_lib_prefix=no
+ # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+ case $host_os in
+ openbsd3.3 | openbsd3.3.*) need_version=yes ;;
+ *) need_version=no ;;
+ esac
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ case $host_os in
+ openbsd2.[89] | openbsd2.[89].*)
+ shlibpath_overrides_runpath=no
+ ;;
+ *)
+ shlibpath_overrides_runpath=yes
+ ;;
+ esac
+ else
+ shlibpath_overrides_runpath=yes
+ fi
+ ;;
+
+os2*)
+ libname_spec='$name'
+ shrext_cmds=".dll"
+ need_lib_prefix=no
+ library_names_spec='$libname${shared_ext} $libname.a'
+ dynamic_linker='OS/2 ld.exe'
+ shlibpath_var=LIBPATH
+ ;;
+
+osf3* | osf4* | osf5*)
+ version_type=osf
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+ sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+ ;;
+
+solaris*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ # ldd complains unless libraries are executable
+ postinstall_cmds='chmod +x $lib'
+ ;;
+
+sunos4*)
+ version_type=sunos
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ if test "$with_gnu_ld" = yes; then
+ need_lib_prefix=no
+ fi
+ need_version=yes
+ ;;
+
+sysv4 | sysv4.3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_vendor in
+ sni)
+ shlibpath_overrides_runpath=no
+ need_lib_prefix=no
+ export_dynamic_flag_spec='${wl}-Blargedynsym'
+ runpath_var=LD_RUN_PATH
+ ;;
+ siemens)
+ need_lib_prefix=no
+ ;;
+ motorola)
+ need_lib_prefix=no
+ need_version=no
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+ ;;
+ esac
+ ;;
+
+sysv4*MP*)
+ if test -d /usr/nec ;then
+ version_type=linux
+ library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+ soname_spec='$libname${shared_ext}.$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ fi
+ ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+ version_type=freebsd-elf
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ if test "$with_gnu_ld" = yes; then
+ sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+ shlibpath_overrides_runpath=no
+ else
+ sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+ shlibpath_overrides_runpath=yes
+ case $host_os in
+ sco3.2v5*)
+ sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+ ;;
+ esac
+ fi
+ sys_lib_dlsearch_path_spec='/usr/lib'
+ ;;
+
+uts4*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+*)
+ dynamic_linker=no
+ ;;
+esac
+echo "$as_me:$LINENO: result: $dynamic_linker" >&5
+echo "${ECHO_T}$dynamic_linker" >&6
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+ variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
+echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
+echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
+hardcode_action_CXX=
+if test -n "$hardcode_libdir_flag_spec_CXX" || \
+ test -n "$runpath_var_CXX" || \
+ test "X$hardcode_automatic_CXX" = "Xyes" ; then
+
+ # We can hardcode non-existant directories.
+ if test "$hardcode_direct_CXX" != no &&
+ # If the only mechanism to avoid hardcoding is shlibpath_var, we
+ # have to relink, otherwise we might link with an installed library
+ # when we should be linking with a yet-to-be-installed one
+ ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, CXX)" != no &&
+ test "$hardcode_minus_L_CXX" != no; then
+ # Linking always hardcodes the temporary library directory.
+ hardcode_action_CXX=relink
+ else
+ # We can link without hardcoding, and we can hardcode nonexisting dirs.
+ hardcode_action_CXX=immediate
+ fi
+else
+ # We cannot hardcode anything, or else we can only hardcode existing
+ # directories.
+ hardcode_action_CXX=unsupported
+fi
+echo "$as_me:$LINENO: result: $hardcode_action_CXX" >&5
+echo "${ECHO_T}$hardcode_action_CXX" >&6
+
+if test "$hardcode_action_CXX" = relink; then
+ # Fast installation is not supported
+ enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+ test "$enable_shared" = no; then
+ # Fast installation is not necessary
+ enable_fast_install=needless
+fi
+
+
+# The else clause should only fire when bootstrapping the
+# libtool distribution, otherwise you forgot to ship ltmain.sh
+# with your package, and you will get complaints that there are
+# no rules to generate ltmain.sh.
+if test -f "$ltmain"; then
+ # See if we are running on zsh, and set the options which allow our commands through
+ # without removal of \ escapes.
+ if test -n "${ZSH_VERSION+set}" ; then
+ setopt NO_GLOB_SUBST
+ fi
+ # Now quote all the things that may contain metacharacters while being
+ # careful not to overquote the AC_SUBSTed values. We take copies of the
+ # variables and quote the copies for generation of the libtool script.
+ for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \
+ SED SHELL STRIP \
+ libname_spec library_names_spec soname_spec extract_expsyms_cmds \
+ old_striplib striplib file_magic_cmd finish_cmds finish_eval \
+ deplibs_check_method reload_flag reload_cmds need_locks \
+ lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
+ lt_cv_sys_global_symbol_to_c_name_address \
+ sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
+ old_postinstall_cmds old_postuninstall_cmds \
+ compiler_CXX \
+ CC_CXX \
+ LD_CXX \
+ lt_prog_compiler_wl_CXX \
+ lt_prog_compiler_pic_CXX \
+ lt_prog_compiler_static_CXX \
+ lt_prog_compiler_no_builtin_flag_CXX \
+ export_dynamic_flag_spec_CXX \
+ thread_safe_flag_spec_CXX \
+ whole_archive_flag_spec_CXX \
+ enable_shared_with_static_runtimes_CXX \
+ old_archive_cmds_CXX \
+ old_archive_from_new_cmds_CXX \
+ predep_objects_CXX \
+ postdep_objects_CXX \
+ predeps_CXX \
+ postdeps_CXX \
+ compiler_lib_search_path_CXX \
+ archive_cmds_CXX \
+ archive_expsym_cmds_CXX \
+ postinstall_cmds_CXX \
+ postuninstall_cmds_CXX \
+ old_archive_from_expsyms_cmds_CXX \
+ allow_undefined_flag_CXX \
+ no_undefined_flag_CXX \
+ export_symbols_cmds_CXX \
+ hardcode_libdir_flag_spec_CXX \
+ hardcode_libdir_flag_spec_ld_CXX \
+ hardcode_libdir_separator_CXX \
+ hardcode_automatic_CXX \
+ module_cmds_CXX \
+ module_expsym_cmds_CXX \
+ lt_cv_prog_compiler_c_o_CXX \
+ exclude_expsyms_CXX \
+ include_expsyms_CXX; do
+
+ case $var in
+ old_archive_cmds_CXX | \
+ old_archive_from_new_cmds_CXX | \
+ archive_cmds_CXX | \
+ archive_expsym_cmds_CXX | \
+ module_cmds_CXX | \
+ module_expsym_cmds_CXX | \
+ old_archive_from_expsyms_cmds_CXX | \
+ export_symbols_cmds_CXX | \
+ extract_expsyms_cmds | reload_cmds | finish_cmds | \
+ postinstall_cmds | postuninstall_cmds | \
+ old_postinstall_cmds | old_postuninstall_cmds | \
+ sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
+ # Double-quote double-evaled strings.
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
+ ;;
+ *)
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\""
+ ;;
+ esac
+ done
+
+ case $lt_echo in
+ *'\$0 --fallback-echo"')
+ lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'`
+ ;;
+ esac
+
+cfgfile="$ofile"
+
+ cat <<__EOF__ >> "$cfgfile"
+# ### BEGIN LIBTOOL TAG CONFIG: $tagname
+
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+
+# Shell to use when invoking shell scripts.
+SHELL=$lt_SHELL
+
+# Whether or not to build shared libraries.
+build_libtool_libs=$enable_shared
+
+# Whether or not to build static libraries.
+build_old_libs=$enable_static
+
+# Whether or not to add -lc for building shared libraries.
+build_libtool_need_lc=$archive_cmds_need_lc_CXX
+
+# Whether or not to disallow shared libs when runtime libs are static
+allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_CXX
+
+# Whether or not to optimize for fast installation.
+fast_install=$enable_fast_install
+
+# The host system.
+host_alias=$host_alias
+host=$host
+host_os=$host_os
+
+# The build system.
+build_alias=$build_alias
+build=$build
+build_os=$build_os
+
+# An echo program that does not interpret backslashes.
+echo=$lt_echo
+
+# The archiver.
+AR=$lt_AR
+AR_FLAGS=$lt_AR_FLAGS
+
+# A C compiler.
+LTCC=$lt_LTCC
+
+# LTCC compiler flags.
+LTCFLAGS=$lt_LTCFLAGS
+
+# A language-specific compiler.
+CC=$lt_compiler_CXX
+
+# Is the compiler the GNU C compiler?
+with_gcc=$GCC_CXX
+
+gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\`
+gcc_ver=\`gcc -dumpversion\`
+
+# An ERE matcher.
+EGREP=$lt_EGREP
+
+# The linker used to build libraries.
+LD=$lt_LD_CXX
+
+# Whether we need hard or soft links.
+LN_S=$lt_LN_S
+
+# A BSD-compatible nm program.
+NM=$lt_NM
+
+# A symbol stripping program
+STRIP=$lt_STRIP
+
+# Used to examine libraries when file_magic_cmd begins "file"
+MAGIC_CMD=$MAGIC_CMD
+
+# Used on cygwin: DLL creation program.
+DLLTOOL="$DLLTOOL"
+
+# Used on cygwin: object dumper.
+OBJDUMP="$OBJDUMP"
+
+# Used on cygwin: assembler.
+AS="$AS"
+
+# The name of the directory that contains temporary libtool files.
+objdir=$objdir
+
+# How to create reloadable object files.
+reload_flag=$lt_reload_flag
+reload_cmds=$lt_reload_cmds
+
+# How to pass a linker flag through the compiler.
+wl=$lt_lt_prog_compiler_wl_CXX
+
+# Object file suffix (normally "o").
+objext="$ac_objext"
+
+# Old archive suffix (normally "a").
+libext="$libext"
+
+# Shared library suffix (normally ".so").
+shrext_cmds='$shrext_cmds'
+
+# Executable file suffix (normally "").
+exeext="$exeext"
+
+# Additional compiler flags for building library objects.
+pic_flag=$lt_lt_prog_compiler_pic_CXX
+pic_mode=$pic_mode
+
+# What is the maximum length of a command?
+max_cmd_len=$lt_cv_sys_max_cmd_len
+
+# Does compiler simultaneously support -c and -o options?
+compiler_c_o=$lt_lt_cv_prog_compiler_c_o_CXX
+
+# Must we lock files when doing compilation?
+need_locks=$lt_need_locks
+
+# Do we need the lib prefix for modules?
+need_lib_prefix=$need_lib_prefix
+
+# Do we need a version for libraries?
+need_version=$need_version
+
+# Whether dlopen is supported.
+dlopen_support=$enable_dlopen
+
+# Whether dlopen of programs is supported.
+dlopen_self=$enable_dlopen_self
+
+# Whether dlopen of statically linked programs is supported.
+dlopen_self_static=$enable_dlopen_self_static
+
+# Compiler flag to prevent dynamic linking.
+link_static_flag=$lt_lt_prog_compiler_static_CXX
+
+# Compiler flag to turn off builtin functions.
+no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_CXX
+
+# Compiler flag to allow reflexive dlopens.
+export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_CXX
+
+# Compiler flag to generate shared objects directly from archives.
+whole_archive_flag_spec=$lt_whole_archive_flag_spec_CXX
+
+# Compiler flag to generate thread-safe objects.
+thread_safe_flag_spec=$lt_thread_safe_flag_spec_CXX
+
+# Library versioning type.
+version_type=$version_type
+
+# Format of library name prefix.
+libname_spec=$lt_libname_spec
+
+# List of archive names. First name is the real one, the rest are links.
+# The last name is the one that the linker finds with -lNAME.
+library_names_spec=$lt_library_names_spec
+
+# The coded name of the library, if different from the real name.
+soname_spec=$lt_soname_spec
+
+# Commands used to build and install an old-style archive.
+RANLIB=$lt_RANLIB
+old_archive_cmds=$lt_old_archive_cmds_CXX
+old_postinstall_cmds=$lt_old_postinstall_cmds
+old_postuninstall_cmds=$lt_old_postuninstall_cmds
+
+# Create an old-style archive from a shared archive.
+old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_CXX
+
+# Create a temporary old-style archive to link instead of a shared archive.
+old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_CXX
+
+# Commands used to build and install a shared archive.
+archive_cmds=$lt_archive_cmds_CXX
+archive_expsym_cmds=$lt_archive_expsym_cmds_CXX
+postinstall_cmds=$lt_postinstall_cmds
+postuninstall_cmds=$lt_postuninstall_cmds
+
+# Commands used to build a loadable module (assumed same as above if empty)
+module_cmds=$lt_module_cmds_CXX
+module_expsym_cmds=$lt_module_expsym_cmds_CXX
+
+# Commands to strip libraries.
+old_striplib=$lt_old_striplib
+striplib=$lt_striplib
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predep_objects=\`echo $lt_predep_objects_CXX | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdep_objects=\`echo $lt_postdep_objects_CXX | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predeps=$lt_predeps_CXX
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdeps=$lt_postdeps_CXX
+
+# The library search path used internally by the compiler when linking
+# a shared library.
+compiler_lib_search_path=\`echo $lt_compiler_lib_search_path_CXX | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Method to check whether dependent libraries are shared objects.
+deplibs_check_method=$lt_deplibs_check_method
+
+# Command to use when deplibs_check_method == file_magic.
+file_magic_cmd=$lt_file_magic_cmd
+
+# Flag that allows shared libraries with undefined symbols to be built.
+allow_undefined_flag=$lt_allow_undefined_flag_CXX
+
+# Flag that forces no undefined symbols.
+no_undefined_flag=$lt_no_undefined_flag_CXX
+
+# Commands used to finish a libtool library installation in a directory.
+finish_cmds=$lt_finish_cmds
+
+# Same as above, but a single script fragment to be evaled but not shown.
+finish_eval=$lt_finish_eval
+
+# Take the output of nm and produce a listing of raw symbols and C names.
+global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
+
+# Transform the output of nm in a proper C declaration
+global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
+
+# Transform the output of nm in a C name address pair
+global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address
+
+# This is the shared library runtime path variable.
+runpath_var=$runpath_var
+
+# This is the shared library path variable.
+shlibpath_var=$shlibpath_var
+
+# Is shlibpath searched before the hard-coded library search path?
+shlibpath_overrides_runpath=$shlibpath_overrides_runpath
+
+# How to hardcode a shared library path into an executable.
+hardcode_action=$hardcode_action_CXX
+
+# Whether we should hardcode library paths into libraries.
+hardcode_into_libs=$hardcode_into_libs
+
+# Flag to hardcode \$libdir into a binary during linking.
+# This must work even if \$libdir does not exist.
+hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_CXX
+
+# If ld is used when linking, flag to hardcode \$libdir into
+# a binary during linking. This must work even if \$libdir does
+# not exist.
+hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_CXX
+
+# Whether we need a single -rpath flag with a separated argument.
+hardcode_libdir_separator=$lt_hardcode_libdir_separator_CXX
+
+# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the
+# resulting binary.
+hardcode_direct=$hardcode_direct_CXX
+
+# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
+# resulting binary.
+hardcode_minus_L=$hardcode_minus_L_CXX
+
+# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into
+# the resulting binary.
+hardcode_shlibpath_var=$hardcode_shlibpath_var_CXX
+
+# Set to yes if building a shared library automatically hardcodes DIR into the library
+# and all subsequent libraries and executables linked against it.
+hardcode_automatic=$hardcode_automatic_CXX
+
+# Variables whose values should be saved in libtool wrapper scripts and
+# restored at relink time.
+variables_saved_for_relink="$variables_saved_for_relink"
+
+# Whether libtool must link a program against all its dependency libraries.
+link_all_deplibs=$link_all_deplibs_CXX
+
+# Compile-time system search path for libraries
+sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Run-time system search path for libraries
+sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec
+
+# Fix the shell variable \$srcfile for the compiler.
+fix_srcfile_path="$fix_srcfile_path_CXX"
+
+# Set to yes if exported symbols are required.
+always_export_symbols=$always_export_symbols_CXX
+
+# The commands to list exported symbols.
+export_symbols_cmds=$lt_export_symbols_cmds_CXX
+
+# The commands to extract the exported symbol list from a shared archive.
+extract_expsyms_cmds=$lt_extract_expsyms_cmds
+
+# Symbols that should not be listed in the preloaded symbols.
+exclude_expsyms=$lt_exclude_expsyms_CXX
+
+# Symbols that must always be exported.
+include_expsyms=$lt_include_expsyms_CXX
+
+# ### END LIBTOOL TAG CONFIG: $tagname
+
+__EOF__
+
+
+else
+ # If there is no Makefile yet, we rely on a make rule to execute
+ # `config.status --recheck' to rerun these tests and create the
+ # libtool script then.
+ ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'`
+ if test -f "$ltmain_in"; then
+ test -f Makefile && make "$ltmain"
+ fi
+fi
+
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+CC=$lt_save_CC
+LDCXX=$LD
+LD=$lt_save_LD
+GCC=$lt_save_GCC
+with_gnu_ldcxx=$with_gnu_ld
+with_gnu_ld=$lt_save_with_gnu_ld
+lt_cv_path_LDCXX=$lt_cv_path_LD
+lt_cv_path_LD=$lt_save_path_LD
+lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
+lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
+
+ else
+ tagname=""
+ fi
+ ;;
+
+ F77)
+ if test -n "$F77" && test "X$F77" != "Xno"; then
+
+ac_ext=f
+ac_compile='$F77 -c $FFLAGS conftest.$ac_ext >&5'
+ac_link='$F77 -o conftest$ac_exeext $FFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_f77_compiler_gnu
+
+
+archive_cmds_need_lc_F77=no
+allow_undefined_flag_F77=
+always_export_symbols_F77=no
+archive_expsym_cmds_F77=
+export_dynamic_flag_spec_F77=
+hardcode_direct_F77=no
+hardcode_libdir_flag_spec_F77=
+hardcode_libdir_flag_spec_ld_F77=
+hardcode_libdir_separator_F77=
+hardcode_minus_L_F77=no
+hardcode_automatic_F77=no
+module_cmds_F77=
+module_expsym_cmds_F77=
+link_all_deplibs_F77=unknown
+old_archive_cmds_F77=$old_archive_cmds
+no_undefined_flag_F77=
+whole_archive_flag_spec_F77=
+enable_shared_with_static_runtimes_F77=no
+
+# Source file extension for f77 test sources.
+ac_ext=f
+
+# Object file extension for compiled f77 test sources.
+objext=o
+objext_F77=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code=" subroutine t\n return\n end\n"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code=" program t\n end\n"
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+
+
+# save warnings/boilerplate of simple test code
+ac_outfile=conftest.$ac_objext
+printf "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$rm conftest*
+
+ac_outfile=conftest.$ac_objext
+printf "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$rm conftest*
+
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+CC=${F77-"f77"}
+compiler=$CC
+compiler_F77=$CC
+for cc_temp in $compiler""; do
+ case $cc_temp in
+ compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
+ distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
+ \-*) ;;
+ *) break;;
+ esac
+done
+cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+
+
+echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5
+echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&6
+echo "$as_me:$LINENO: result: $can_build_shared" >&5
+echo "${ECHO_T}$can_build_shared" >&6
+
+echo "$as_me:$LINENO: checking whether to build shared libraries" >&5
+echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6
+test "$can_build_shared" = "no" && enable_shared=no
+
+# On AIX, shared libraries and static libraries use the same namespace, and
+# are all built from PIC.
+case $host_os in
+aix3*)
+ test "$enable_shared" = yes && enable_static=no
+ if test -n "$RANLIB"; then
+ archive_cmds="$archive_cmds~\$RANLIB \$lib"
+ postinstall_cmds='$RANLIB $lib'
+ fi
+ ;;
+aix4* | aix5*)
+ if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+ test "$enable_shared" = yes && enable_static=no
+ fi
+ ;;
+esac
+echo "$as_me:$LINENO: result: $enable_shared" >&5
+echo "${ECHO_T}$enable_shared" >&6
+
+echo "$as_me:$LINENO: checking whether to build static libraries" >&5
+echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6
+# Make sure either enable_shared or enable_static is yes.
+test "$enable_shared" = yes || enable_static=yes
+echo "$as_me:$LINENO: result: $enable_static" >&5
+echo "${ECHO_T}$enable_static" >&6
+
+GCC_F77="$G77"
+LD_F77="$LD"
+
+lt_prog_compiler_wl_F77=
+lt_prog_compiler_pic_F77=
+lt_prog_compiler_static_F77=
+
+echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
+echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6
+
+ if test "$GCC" = yes; then
+ lt_prog_compiler_wl_F77='-Wl,'
+ lt_prog_compiler_static_F77='-static'
+
+ case $host_os in
+ aix*)
+ # All AIX code is PIC.
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ lt_prog_compiler_static_F77='-Bstatic'
+ fi
+ ;;
+
+ amigaos*)
+ # FIXME: we need at least 68020 code to build shared libraries, but
+ # adding the `-m68020' flag to GCC prevents building anything better,
+ # like `-m68040'.
+ lt_prog_compiler_pic_F77='-m68020 -resident32 -malways-restore-a4'
+ ;;
+
+ beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+ # PIC is the default for these OSes.
+ ;;
+
+ mingw* | pw32* | os2*)
+ # This hack is so that the source file can tell whether it is being
+ # built for inclusion in a dll (and should export symbols for example).
+ lt_prog_compiler_pic_F77='-DDLL_EXPORT'
+ ;;
+
+ darwin* | rhapsody*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ lt_prog_compiler_pic_F77='-fno-common'
+ ;;
+
+ interix3*)
+ # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+ # Instead, we relocate shared libraries at runtime.
+ ;;
+
+ msdosdjgpp*)
+ # Just because we use GCC doesn't mean we suddenly get shared libraries
+ # on systems that don't support them.
+ lt_prog_compiler_can_build_shared_F77=no
+ enable_shared=no
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec; then
+ lt_prog_compiler_pic_F77=-Kconform_pic
+ fi
+ ;;
+
+ hpux*)
+ # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+ # not for PA HP-UX.
+ case $host_cpu in
+ hppa*64*|ia64*)
+ # +Z the default
+ ;;
+ *)
+ lt_prog_compiler_pic_F77='-fPIC'
+ ;;
+ esac
+ ;;
+
+ *)
+ lt_prog_compiler_pic_F77='-fPIC'
+ ;;
+ esac
+ else
+ # PORTME Check for flag to pass linker flags through the system compiler.
+ case $host_os in
+ aix*)
+ lt_prog_compiler_wl_F77='-Wl,'
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ lt_prog_compiler_static_F77='-Bstatic'
+ else
+ lt_prog_compiler_static_F77='-bnso -bI:/lib/syscalls.exp'
+ fi
+ ;;
+ darwin*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ case $cc_basename in
+ xlc*)
+ lt_prog_compiler_pic_F77='-qnocommon'
+ lt_prog_compiler_wl_F77='-Wl,'
+ ;;
+ esac
+ ;;
+
+ mingw* | pw32* | os2*)
+ # This hack is so that the source file can tell whether it is being
+ # built for inclusion in a dll (and should export symbols for example).
+ lt_prog_compiler_pic_F77='-DDLL_EXPORT'
+ ;;
+
+ hpux9* | hpux10* | hpux11*)
+ lt_prog_compiler_wl_F77='-Wl,'
+ # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+ # not for PA HP-UX.
+ case $host_cpu in
+ hppa*64*|ia64*)
+ # +Z the default
+ ;;
+ *)
+ lt_prog_compiler_pic_F77='+Z'
+ ;;
+ esac
+ # Is there a better lt_prog_compiler_static that works with the bundled CC?
+ lt_prog_compiler_static_F77='${wl}-a ${wl}archive'
+ ;;
+
+ irix5* | irix6* | nonstopux*)
+ lt_prog_compiler_wl_F77='-Wl,'
+ # PIC (with -KPIC) is the default.
+ lt_prog_compiler_static_F77='-non_shared'
+ ;;
+
+ newsos6)
+ lt_prog_compiler_pic_F77='-KPIC'
+ lt_prog_compiler_static_F77='-Bstatic'
+ ;;
+
+ linux*)
+ case $cc_basename in
+ icc* | ecc*)
+ lt_prog_compiler_wl_F77='-Wl,'
+ lt_prog_compiler_pic_F77='-KPIC'
+ lt_prog_compiler_static_F77='-static'
+ ;;
+ pgcc* | pgf77* | pgf90* | pgf95*)
+ # Portland Group compilers (*not* the Pentium gcc compiler,
+ # which looks to be a dead project)
+ lt_prog_compiler_wl_F77='-Wl,'
+ lt_prog_compiler_pic_F77='-fpic'
+ lt_prog_compiler_static_F77='-Bstatic'
+ ;;
+ ccc*)
+ lt_prog_compiler_wl_F77='-Wl,'
+ # All Alpha code is PIC.
+ lt_prog_compiler_static_F77='-non_shared'
+ ;;
+ esac
+ ;;
+
+ osf3* | osf4* | osf5*)
+ lt_prog_compiler_wl_F77='-Wl,'
+ # All OSF/1 code is PIC.
+ lt_prog_compiler_static_F77='-non_shared'
+ ;;
+
+ solaris*)
+ lt_prog_compiler_pic_F77='-KPIC'
+ lt_prog_compiler_static_F77='-Bstatic'
+ case $cc_basename in
+ f77* | f90* | f95*)
+ lt_prog_compiler_wl_F77='-Qoption ld ';;
+ *)
+ lt_prog_compiler_wl_F77='-Wl,';;
+ esac
+ ;;
+
+ sunos4*)
+ lt_prog_compiler_wl_F77='-Qoption ld '
+ lt_prog_compiler_pic_F77='-PIC'
+ lt_prog_compiler_static_F77='-Bstatic'
+ ;;
+
+ sysv4 | sysv4.2uw2* | sysv4.3*)
+ lt_prog_compiler_wl_F77='-Wl,'
+ lt_prog_compiler_pic_F77='-KPIC'
+ lt_prog_compiler_static_F77='-Bstatic'
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec ;then
+ lt_prog_compiler_pic_F77='-Kconform_pic'
+ lt_prog_compiler_static_F77='-Bstatic'
+ fi
+ ;;
+
+ sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+ lt_prog_compiler_wl_F77='-Wl,'
+ lt_prog_compiler_pic_F77='-KPIC'
+ lt_prog_compiler_static_F77='-Bstatic'
+ ;;
+
+ unicos*)
+ lt_prog_compiler_wl_F77='-Wl,'
+ lt_prog_compiler_can_build_shared_F77=no
+ ;;
+
+ uts4*)
+ lt_prog_compiler_pic_F77='-pic'
+ lt_prog_compiler_static_F77='-Bstatic'
+ ;;
+
+ *)
+ lt_prog_compiler_can_build_shared_F77=no
+ ;;
+ esac
+ fi
+
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_F77" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_F77" >&6
+
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$lt_prog_compiler_pic_F77"; then
+
+echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works" >&5
+echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_F77 works... $ECHO_C" >&6
+if test "${lt_prog_compiler_pic_works_F77+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_prog_compiler_pic_works_F77=no
+ ac_outfile=conftest.$ac_objext
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+ lt_compiler_flag="$lt_prog_compiler_pic_F77"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ # The option is referenced via a variable to avoid confusing sed.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:13485: $lt_compile\"" >&5)
+ (eval "$lt_compile" 2>conftest.err)
+ ac_status=$?
+ cat conftest.err >&5
+ echo "$as_me:13489: \$? = $ac_status" >&5
+ if (exit $ac_status) && test -s "$ac_outfile"; then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings other than the usual output.
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+ lt_prog_compiler_pic_works_F77=yes
+ fi
+ fi
+ $rm conftest*
+
+fi
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_F77" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_works_F77" >&6
+
+if test x"$lt_prog_compiler_pic_works_F77" = xyes; then
+ case $lt_prog_compiler_pic_F77 in
+ "" | " "*) ;;
+ *) lt_prog_compiler_pic_F77=" $lt_prog_compiler_pic_F77" ;;
+ esac
+else
+ lt_prog_compiler_pic_F77=
+ lt_prog_compiler_can_build_shared_F77=no
+fi
+
+fi
+case $host_os in
+ # For platforms which do not support PIC, -DPIC is meaningless:
+ *djgpp*)
+ lt_prog_compiler_pic_F77=
+ ;;
+ *)
+ lt_prog_compiler_pic_F77="$lt_prog_compiler_pic_F77"
+ ;;
+esac
+
+#
+# Check to make sure the static flag actually works.
+#
+wl=$lt_prog_compiler_wl_F77 eval lt_tmp_static_flag=\"$lt_prog_compiler_static_F77\"
+echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
+echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6
+if test "${lt_prog_compiler_static_works_F77+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_prog_compiler_static_works_F77=no
+ save_LDFLAGS="$LDFLAGS"
+ LDFLAGS="$LDFLAGS $lt_tmp_static_flag"
+ printf "$lt_simple_link_test_code" > conftest.$ac_ext
+ if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+ # The linker can only warn and ignore the option if not recognized
+ # So say no if there are warnings
+ if test -s conftest.err; then
+ # Append any errors to the config.log.
+ cat conftest.err 1>&5
+ $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if diff conftest.exp conftest.er2 >/dev/null; then
+ lt_prog_compiler_static_works_F77=yes
+ fi
+ else
+ lt_prog_compiler_static_works_F77=yes
+ fi
+ fi
+ $rm conftest*
+ LDFLAGS="$save_LDFLAGS"
+
+fi
+echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_F77" >&5
+echo "${ECHO_T}$lt_prog_compiler_static_works_F77" >&6
+
+if test x"$lt_prog_compiler_static_works_F77" = xyes; then
+ :
+else
+ lt_prog_compiler_static_F77=
+fi
+
+
+echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
+echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6
+if test "${lt_cv_prog_compiler_c_o_F77+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_cv_prog_compiler_c_o_F77=no
+ $rm -r conftest 2>/dev/null
+ mkdir conftest
+ cd conftest
+ mkdir out
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+ lt_compiler_flag="-o out/conftest2.$ac_objext"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:13589: $lt_compile\"" >&5)
+ (eval "$lt_compile" 2>out/conftest.err)
+ ac_status=$?
+ cat out/conftest.err >&5
+ echo "$as_me:13593: \$? = $ac_status" >&5
+ if (exit $ac_status) && test -s out/conftest2.$ac_objext
+ then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
+ $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+ if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+ lt_cv_prog_compiler_c_o_F77=yes
+ fi
+ fi
+ chmod u+w . 2>&5
+ $rm conftest*
+ # SGI C++ compiler will create directory out/ii_files/ for
+ # template instantiation
+ test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files
+ $rm out/* && rmdir out
+ cd ..
+ rmdir conftest
+ $rm conftest*
+
+fi
+echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_F77" >&5
+echo "${ECHO_T}$lt_cv_prog_compiler_c_o_F77" >&6
+
+
+hard_links="nottested"
+if test "$lt_cv_prog_compiler_c_o_F77" = no && test "$need_locks" != no; then
+ # do not overwrite the value of need_locks provided by the user
+ echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
+echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6
+ hard_links=yes
+ $rm conftest*
+ ln conftest.a conftest.b 2>/dev/null && hard_links=no
+ touch conftest.a
+ ln conftest.a conftest.b 2>&5 || hard_links=no
+ ln conftest.a conftest.b 2>/dev/null && hard_links=no
+ echo "$as_me:$LINENO: result: $hard_links" >&5
+echo "${ECHO_T}$hard_links" >&6
+ if test "$hard_links" = no; then
+ { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
+echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
+ need_locks=warn
+ fi
+else
+ need_locks=no
+fi
+
+echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6
+
+ runpath_var=
+ allow_undefined_flag_F77=
+ enable_shared_with_static_runtimes_F77=no
+ archive_cmds_F77=
+ archive_expsym_cmds_F77=
+ old_archive_From_new_cmds_F77=
+ old_archive_from_expsyms_cmds_F77=
+ export_dynamic_flag_spec_F77=
+ whole_archive_flag_spec_F77=
+ thread_safe_flag_spec_F77=
+ hardcode_libdir_flag_spec_F77=
+ hardcode_libdir_flag_spec_ld_F77=
+ hardcode_libdir_separator_F77=
+ hardcode_direct_F77=no
+ hardcode_minus_L_F77=no
+ hardcode_shlibpath_var_F77=unsupported
+ link_all_deplibs_F77=unknown
+ hardcode_automatic_F77=no
+ module_cmds_F77=
+ module_expsym_cmds_F77=
+ always_export_symbols_F77=no
+ export_symbols_cmds_F77='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+ # include_expsyms should be a list of space-separated symbols to be *always*
+ # included in the symbol list
+ include_expsyms_F77=
+ # exclude_expsyms can be an extended regexp of symbols to exclude
+ # it will be wrapped by ` (' and `)$', so one must not match beginning or
+ # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
+ # as well as any symbol that contains `d'.
+ exclude_expsyms_F77="_GLOBAL_OFFSET_TABLE_"
+ # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
+ # platforms (ab)use it in PIC code, but their linkers get confused if
+ # the symbol is explicitly referenced. Since portable code cannot
+ # rely on this symbol name, it's probably fine to never include it in
+ # preloaded symbol tables.
+ extract_expsyms_cmds=
+ # Just being paranoid about ensuring that cc_basename is set.
+ for cc_temp in $compiler""; do
+ case $cc_temp in
+ compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
+ distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
+ \-*) ;;
+ *) break;;
+ esac
+done
+cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+
+ case $host_os in
+ cygwin* | mingw* | pw32*)
+ # FIXME: the MSVC++ port hasn't been tested in a loooong time
+ # When not using gcc, we currently assume that we are using
+ # Microsoft Visual C++.
+ if test "$GCC" != yes; then
+ with_gnu_ld=no
+ fi
+ ;;
+ interix*)
+ # we just hope/assume this is gcc and not c89 (= MSVC++)
+ with_gnu_ld=yes
+ ;;
+ openbsd*)
+ with_gnu_ld=no
+ ;;
+ esac
+
+ ld_shlibs_F77=yes
+ if test "$with_gnu_ld" = yes; then
+ # If archive_cmds runs LD, not CC, wlarc should be empty
+ wlarc='${wl}'
+
+ # Set some defaults for GNU ld with shared library support. These
+ # are reset later if shared libraries are not supported. Putting them
+ # here allows them to be overridden if necessary.
+ runpath_var=LD_RUN_PATH
+ hardcode_libdir_flag_spec_F77='${wl}--rpath ${wl}$libdir'
+ export_dynamic_flag_spec_F77='${wl}--export-dynamic'
+ # ancient GNU ld didn't support --whole-archive et. al.
+ if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
+ whole_archive_flag_spec_F77="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+ else
+ whole_archive_flag_spec_F77=
+ fi
+ supports_anon_versioning=no
+ case `$LD -v 2>/dev/null` in
+ *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
+ *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+ *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+ *\ 2.11.*) ;; # other 2.11 versions
+ *) supports_anon_versioning=yes ;;
+ esac
+
+ # See if GNU ld supports shared libraries.
+ case $host_os in
+ aix3* | aix4* | aix5*)
+ # On AIX/PPC, the GNU linker is very broken
+ if test "$host_cpu" != ia64; then
+ ld_shlibs_F77=no
+ cat <<EOF 1>&2
+
+*** Warning: the GNU linker, at least up to release 2.9.1, is reported
+*** to be unable to reliably create shared libraries on AIX.
+*** Therefore, libtool is disabling shared libraries support. If you
+*** really care for shared libraries, you may want to modify your PATH
+*** so that a non-GNU linker is found, and then restart.
+
+EOF
+ fi
+ ;;
+
+ amigaos*)
+ archive_cmds_F77='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+ hardcode_libdir_flag_spec_F77='-L$libdir'
+ hardcode_minus_L_F77=yes
+
+ # Samuel A. Falvo II <kc5tja at dolphin.openprojects.net> reports
+ # that the semantics of dynamic libraries on AmigaOS, at least up
+ # to version 4, is to share data among multiple programs linked
+ # with the same dynamic library. Since this doesn't match the
+ # behavior of shared libraries on other platforms, we can't use
+ # them.
+ ld_shlibs_F77=no
+ ;;
+
+ beos*)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ allow_undefined_flag_F77=unsupported
+ # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+ # support --undefined. This deserves some investigation. FIXME
+ archive_cmds_F77='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ else
+ ld_shlibs_F77=no
+ fi
+ ;;
+
+ cygwin* | mingw* | pw32*)
+ # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, F77) is actually meaningless,
+ # as there is no search path for DLLs.
+ hardcode_libdir_flag_spec_F77='-L$libdir'
+ allow_undefined_flag_F77=unsupported
+ always_export_symbols_F77=no
+ enable_shared_with_static_runtimes_F77=yes
+ export_symbols_cmds_F77='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols'
+
+ if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
+ archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ # If the export-symbols file already is a .def file (1st line
+ # is EXPORTS), use it as is; otherwise, prepend...
+ archive_expsym_cmds_F77='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+ cp $export_symbols $output_objdir/$soname.def;
+ else
+ echo EXPORTS > $output_objdir/$soname.def;
+ cat $export_symbols >> $output_objdir/$soname.def;
+ fi~
+ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ else
+ ld_shlibs_F77=no
+ fi
+ ;;
+
+ interix3*)
+ hardcode_direct_F77=no
+ hardcode_shlibpath_var_F77=no
+ hardcode_libdir_flag_spec_F77='${wl}-rpath,$libdir'
+ export_dynamic_flag_spec_F77='${wl}-E'
+ # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+ # Instead, shared libraries are loaded at an image base (0x10000000 by
+ # default) and relocated if they conflict, which is a slow very memory
+ # consuming and fragmenting process. To avoid this, we pick a random,
+ # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+ # time. Moving up from 0x10000000 also allows more sbrk(2) space.
+ archive_cmds_F77='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ archive_expsym_cmds_F77='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ ;;
+
+ linux*)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ tmp_addflag=
+ case $cc_basename,$host_cpu in
+ pgcc*) # Portland Group C compiler
+ whole_archive_flag_spec_F77='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+ tmp_addflag=' $pic_flag'
+ ;;
+ pgf77* | pgf90* | pgf95*) # Portland Group f77 and f90 compilers
+ whole_archive_flag_spec_F77='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+ tmp_addflag=' $pic_flag -Mnomain' ;;
+ ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64
+ tmp_addflag=' -i_dynamic' ;;
+ efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64
+ tmp_addflag=' -i_dynamic -nofor_main' ;;
+ ifc* | ifort*) # Intel Fortran compiler
+ tmp_addflag=' -nofor_main' ;;
+ esac
+ archive_cmds_F77='$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+
+ if test $supports_anon_versioning = yes; then
+ archive_expsym_cmds_F77='$echo "{ global:" > $output_objdir/$libname.ver~
+ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+ $echo "local: *; };" >> $output_objdir/$libname.ver~
+ $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+ fi
+ else
+ ld_shlibs_F77=no
+ fi
+ ;;
+
+ netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ archive_cmds_F77='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
+ wlarc=
+ else
+ archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ fi
+ ;;
+
+ solaris*)
+ if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
+ ld_shlibs_F77=no
+ cat <<EOF 1>&2
+
+*** Warning: The releases 2.8.* of the GNU linker cannot reliably
+*** create shared libraries on Solaris systems. Therefore, libtool
+*** is disabling shared libraries support. We urge you to upgrade GNU
+*** binutils to release 2.9.1 or newer. Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+EOF
+ elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ else
+ ld_shlibs_F77=no
+ fi
+ ;;
+
+ sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
+ case `$LD -v 2>&1` in
+ *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*)
+ ld_shlibs_F77=no
+ cat <<_LT_EOF 1>&2
+
+*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
+*** reliably create shared libraries on SCO systems. Therefore, libtool
+*** is disabling shared libraries support. We urge you to upgrade GNU
+*** binutils to release 2.16.91.0.3 or newer. Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+ ;;
+ *)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ hardcode_libdir_flag_spec_F77='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`'
+ archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib'
+ archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file,$export_symbols -o $lib'
+ else
+ ld_shlibs_F77=no
+ fi
+ ;;
+ esac
+ ;;
+
+ sunos4*)
+ archive_cmds_F77='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ wlarc=
+ hardcode_direct_F77=yes
+ hardcode_shlibpath_var_F77=no
+ ;;
+
+ *)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ archive_expsym_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ else
+ ld_shlibs_F77=no
+ fi
+ ;;
+ esac
+
+ if test "$ld_shlibs_F77" = no; then
+ runpath_var=
+ hardcode_libdir_flag_spec_F77=
+ export_dynamic_flag_spec_F77=
+ whole_archive_flag_spec_F77=
+ fi
+ else
+ # PORTME fill in a description of your system's linker (not GNU ld)
+ case $host_os in
+ aix3*)
+ allow_undefined_flag_F77=unsupported
+ always_export_symbols_F77=yes
+ archive_expsym_cmds_F77='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
+ # Note: this linker hardcodes the directories in LIBPATH if there
+ # are no directories specified by -L.
+ hardcode_minus_L_F77=yes
+ if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+ # Neither direct hardcoding nor static linking is supported with a
+ # broken collect2.
+ hardcode_direct_F77=unsupported
+ fi
+ ;;
+
+ aix4* | aix5*)
+ if test "$host_cpu" = ia64; then
+ # On IA64, the linker does run time linking by default, so we don't
+ # have to do anything special.
+ aix_use_runtimelinking=no
+ exp_sym_flag='-Bexport'
+ no_entry_flag=""
+ else
+ # If we're using GNU nm, then we don't want the "-C" option.
+ # -C means demangle to AIX nm, but means don't demangle with GNU nm
+ if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
+ export_symbols_cmds_F77='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
+ else
+ export_symbols_cmds_F77='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
+ fi
+ aix_use_runtimelinking=no
+
+ # Test if we are trying to use run time linking or normal
+ # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+ # need to do runtime linking.
+ case $host_os in aix4.[23]|aix4.[23].*|aix5*)
+ for ld_flag in $LDFLAGS; do
+ if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+ aix_use_runtimelinking=yes
+ break
+ fi
+ done
+ ;;
+ esac
+
+ exp_sym_flag='-bexport'
+ no_entry_flag='-bnoentry'
+ fi
+
+ # When large executables or shared objects are built, AIX ld can
+ # have problems creating the table of contents. If linking a library
+ # or program results in "error TOC overflow" add -mminimal-toc to
+ # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not
+ # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+ archive_cmds_F77=''
+ hardcode_direct_F77=yes
+ hardcode_libdir_separator_F77=':'
+ link_all_deplibs_F77=yes
+
+ if test "$GCC" = yes; then
+ case $host_os in aix4.[012]|aix4.[012].*)
+ # We only want to do this on AIX 4.2 and lower, the check
+ # below for broken collect2 doesn't work under 4.3+
+ collect2name=`${CC} -print-prog-name=collect2`
+ if test -f "$collect2name" && \
+ strings "$collect2name" | grep resolve_lib_name >/dev/null
+ then
+ # We have reworked collect2
+ hardcode_direct_F77=yes
+ else
+ # We have old collect2
+ hardcode_direct_F77=unsupported
+ # It fails to find uninstalled libraries when the uninstalled
+ # path is not listed in the libpath. Setting hardcode_minus_L
+ # to unsupported forces relinking
+ hardcode_minus_L_F77=yes
+ hardcode_libdir_flag_spec_F77='-L$libdir'
+ hardcode_libdir_separator_F77=
+ fi
+ ;;
+ esac
+ shared_flag='-shared'
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag="$shared_flag "'${wl}-G'
+ fi
+ else
+ # not using gcc
+ if test "$host_cpu" = ia64; then
+ # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+ # chokes on -Wl,-G. The following line is correct:
+ shared_flag='-G'
+ else
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag='${wl}-G'
+ else
+ shared_flag='${wl}-bM:SRE'
+ fi
+ fi
+ fi
+
+ # It seems that -bexpall does not export symbols beginning with
+ # underscore (_), so it is better to generate a list of symbols to export.
+ always_export_symbols_F77=yes
+ if test "$aix_use_runtimelinking" = yes; then
+ # Warning - without using the other runtime loading flags (-brtl),
+ # -berok will link without error, but may produce a broken library.
+ allow_undefined_flag_F77='-berok'
+ # Determine the default libpath from the value encoded in an empty executable.
+ cat >conftest.$ac_ext <<_ACEOF
+ program main
+
+ end
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_f77_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`; fi
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+
+ hardcode_libdir_flag_spec_F77='${wl}-blibpath:$libdir:'"$aix_libpath"
+ archive_expsym_cmds_F77="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+ else
+ if test "$host_cpu" = ia64; then
+ hardcode_libdir_flag_spec_F77='${wl}-R $libdir:/usr/lib:/lib'
+ allow_undefined_flag_F77="-z nodefs"
+ archive_expsym_cmds_F77="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+ else
+ # Determine the default libpath from the value encoded in an empty executable.
+ cat >conftest.$ac_ext <<_ACEOF
+ program main
+
+ end
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_f77_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`; fi
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+
+ hardcode_libdir_flag_spec_F77='${wl}-blibpath:$libdir:'"$aix_libpath"
+ # Warning - without using the other run time loading flags,
+ # -berok will link without error, but may produce a broken library.
+ no_undefined_flag_F77=' ${wl}-bernotok'
+ allow_undefined_flag_F77=' ${wl}-berok'
+ # Exported symbols can be pulled into shared objects from archives
+ whole_archive_flag_spec_F77='$convenience'
+ archive_cmds_need_lc_F77=yes
+ # This is similar to how AIX traditionally builds its shared libraries.
+ archive_expsym_cmds_F77="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+ fi
+ fi
+ ;;
+
+ amigaos*)
+ archive_cmds_F77='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+ hardcode_libdir_flag_spec_F77='-L$libdir'
+ hardcode_minus_L_F77=yes
+ # see comment about different semantics on the GNU ld section
+ ld_shlibs_F77=no
+ ;;
+
+ bsdi[45]*)
+ export_dynamic_flag_spec_F77=-rdynamic
+ ;;
+
+ cygwin* | mingw* | pw32*)
+ # When not using gcc, we currently assume that we are using
+ # Microsoft Visual C++.
+ # hardcode_libdir_flag_spec is actually meaningless, as there is
+ # no search path for DLLs.
+ hardcode_libdir_flag_spec_F77=' '
+ allow_undefined_flag_F77=unsupported
+ # Tell ltmain to make .lib files, not .a files.
+ libext=lib
+ # Tell ltmain to make .dll files, not .so files.
+ shrext_cmds=".dll"
+ # FIXME: Setting linknames here is a bad hack.
+ archive_cmds_F77='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames='
+ # The linker will automatically build a .lib file if we build a DLL.
+ old_archive_From_new_cmds_F77='true'
+ # FIXME: Should let the user specify the lib program.
+ old_archive_cmds_F77='lib /OUT:$oldlib$oldobjs$old_deplibs'
+ fix_srcfile_path_F77='`cygpath -w "$srcfile"`'
+ enable_shared_with_static_runtimes_F77=yes
+ ;;
+
+ darwin* | rhapsody*)
+ case $host_os in
+ rhapsody* | darwin1.[012])
+ allow_undefined_flag_F77='${wl}-undefined ${wl}suppress'
+ ;;
+ *) # Darwin 1.3 on
+ if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
+ allow_undefined_flag_F77='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ else
+ case ${MACOSX_DEPLOYMENT_TARGET} in
+ 10.[012])
+ allow_undefined_flag_F77='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ ;;
+ 10.*)
+ allow_undefined_flag_F77='${wl}-undefined ${wl}dynamic_lookup'
+ ;;
+ esac
+ fi
+ ;;
+ esac
+ archive_cmds_need_lc_F77=no
+ hardcode_direct_F77=no
+ hardcode_automatic_F77=yes
+ hardcode_shlibpath_var_F77=unsupported
+ whole_archive_flag_spec_F77=''
+ link_all_deplibs_F77=yes
+ if test "$GCC" = yes ; then
+ output_verbose_link_cmd='echo'
+ archive_cmds_F77='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
+ module_cmds_F77='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ archive_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ module_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ else
+ case $cc_basename in
+ xlc*)
+ output_verbose_link_cmd='echo'
+ archive_cmds_F77='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
+ module_cmds_F77='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ archive_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ module_expsym_cmds_F77='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ ;;
+ *)
+ ld_shlibs_F77=no
+ ;;
+ esac
+ fi
+ ;;
+
+ dgux*)
+ archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_libdir_flag_spec_F77='-L$libdir'
+ hardcode_shlibpath_var_F77=no
+ ;;
+
+ freebsd1*)
+ ld_shlibs_F77=no
+ ;;
+
+ # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
+ # support. Future versions do this automatically, but an explicit c++rt0.o
+ # does not break anything, and helps significantly (at the cost of a little
+ # extra space).
+ freebsd2.2*)
+ archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
+ hardcode_libdir_flag_spec_F77='-R$libdir'
+ hardcode_direct_F77=yes
+ hardcode_shlibpath_var_F77=no
+ ;;
+
+ # Unfortunately, older versions of FreeBSD 2 do not have this feature.
+ freebsd2*)
+ archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_direct_F77=yes
+ hardcode_minus_L_F77=yes
+ hardcode_shlibpath_var_F77=no
+ ;;
+
+ # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
+ freebsd* | kfreebsd*-gnu | dragonfly*)
+ archive_cmds_F77='$CC -shared -o $lib $libobjs $deplibs $compiler_flags'
+ hardcode_libdir_flag_spec_F77='-R$libdir'
+ hardcode_direct_F77=yes
+ hardcode_shlibpath_var_F77=no
+ ;;
+
+ hpux9*)
+ if test "$GCC" = yes; then
+ archive_cmds_F77='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ else
+ archive_cmds_F77='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ fi
+ hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir'
+ hardcode_libdir_separator_F77=:
+ hardcode_direct_F77=yes
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ hardcode_minus_L_F77=yes
+ export_dynamic_flag_spec_F77='${wl}-E'
+ ;;
+
+ hpux10*)
+ if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+ archive_cmds_F77='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ archive_cmds_F77='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
+ fi
+ if test "$with_gnu_ld" = no; then
+ hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir'
+ hardcode_libdir_separator_F77=:
+
+ hardcode_direct_F77=yes
+ export_dynamic_flag_spec_F77='${wl}-E'
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ hardcode_minus_L_F77=yes
+ fi
+ ;;
+
+ hpux11*)
+ if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+ case $host_cpu in
+ hppa*64*)
+ archive_cmds_F77='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ ia64*)
+ archive_cmds_F77='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ archive_cmds_F77='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ else
+ case $host_cpu in
+ hppa*64*)
+ archive_cmds_F77='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ ia64*)
+ archive_cmds_F77='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ archive_cmds_F77='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ fi
+ if test "$with_gnu_ld" = no; then
+ hardcode_libdir_flag_spec_F77='${wl}+b ${wl}$libdir'
+ hardcode_libdir_separator_F77=:
+
+ case $host_cpu in
+ hppa*64*|ia64*)
+ hardcode_libdir_flag_spec_ld_F77='+b $libdir'
+ hardcode_direct_F77=no
+ hardcode_shlibpath_var_F77=no
+ ;;
+ *)
+ hardcode_direct_F77=yes
+ export_dynamic_flag_spec_F77='${wl}-E'
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ hardcode_minus_L_F77=yes
+ ;;
+ esac
+ fi
+ ;;
+
+ irix5* | irix6* | nonstopux*)
+ if test "$GCC" = yes; then
+ archive_cmds_F77='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ else
+ archive_cmds_F77='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ hardcode_libdir_flag_spec_ld_F77='-rpath $libdir'
+ fi
+ hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator_F77=:
+ link_all_deplibs_F77=yes
+ ;;
+
+ netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out
+ else
+ archive_cmds_F77='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF
+ fi
+ hardcode_libdir_flag_spec_F77='-R$libdir'
+ hardcode_direct_F77=yes
+ hardcode_shlibpath_var_F77=no
+ ;;
+
+ newsos6)
+ archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_direct_F77=yes
+ hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator_F77=:
+ hardcode_shlibpath_var_F77=no
+ ;;
+
+ openbsd*)
+ hardcode_direct_F77=yes
+ hardcode_shlibpath_var_F77=no
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ archive_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
+ hardcode_libdir_flag_spec_F77='${wl}-rpath,$libdir'
+ export_dynamic_flag_spec_F77='${wl}-E'
+ else
+ case $host_os in
+ openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*)
+ archive_cmds_F77='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_libdir_flag_spec_F77='-R$libdir'
+ ;;
+ *)
+ archive_cmds_F77='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+ hardcode_libdir_flag_spec_F77='${wl}-rpath,$libdir'
+ ;;
+ esac
+ fi
+ ;;
+
+ os2*)
+ hardcode_libdir_flag_spec_F77='-L$libdir'
+ hardcode_minus_L_F77=yes
+ allow_undefined_flag_F77=unsupported
+ archive_cmds_F77='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
+ old_archive_From_new_cmds_F77='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
+ ;;
+
+ osf3*)
+ if test "$GCC" = yes; then
+ allow_undefined_flag_F77=' ${wl}-expect_unresolved ${wl}\*'
+ archive_cmds_F77='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ else
+ allow_undefined_flag_F77=' -expect_unresolved \*'
+ archive_cmds_F77='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ fi
+ hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator_F77=:
+ ;;
+
+ osf4* | osf5*) # as osf3* with the addition of -msym flag
+ if test "$GCC" = yes; then
+ allow_undefined_flag_F77=' ${wl}-expect_unresolved ${wl}\*'
+ archive_cmds_F77='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ hardcode_libdir_flag_spec_F77='${wl}-rpath ${wl}$libdir'
+ else
+ allow_undefined_flag_F77=' -expect_unresolved \*'
+ archive_cmds_F77='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ archive_expsym_cmds_F77='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~
+ $LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp'
+
+ # Both c and cxx compiler support -rpath directly
+ hardcode_libdir_flag_spec_F77='-rpath $libdir'
+ fi
+ hardcode_libdir_separator_F77=:
+ ;;
+
+ solaris*)
+ no_undefined_flag_F77=' -z text'
+ if test "$GCC" = yes; then
+ wlarc='${wl}'
+ archive_cmds_F77='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_F77='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp'
+ else
+ wlarc=''
+ archive_cmds_F77='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ archive_expsym_cmds_F77='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
+ fi
+ hardcode_libdir_flag_spec_F77='-R$libdir'
+ hardcode_shlibpath_var_F77=no
+ case $host_os in
+ solaris2.[0-5] | solaris2.[0-5].*) ;;
+ *)
+ # The compiler driver will combine linker options so we
+ # cannot just pass the convience library names through
+ # without $wl, iff we do not link with $LD.
+ # Luckily, gcc supports the same syntax we need for Sun Studio.
+ # Supported since Solaris 2.6 (maybe 2.5.1?)
+ case $wlarc in
+ '')
+ whole_archive_flag_spec_F77='-z allextract$convenience -z defaultextract' ;;
+ *)
+ whole_archive_flag_spec_F77='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract' ;;
+ esac ;;
+ esac
+ link_all_deplibs_F77=yes
+ ;;
+
+ sunos4*)
+ if test "x$host_vendor" = xsequent; then
+ # Use $CC to link under sequent, because it throws in some extra .o
+ # files that make .init and .fini sections work.
+ archive_cmds_F77='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ archive_cmds_F77='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
+ fi
+ hardcode_libdir_flag_spec_F77='-L$libdir'
+ hardcode_direct_F77=yes
+ hardcode_minus_L_F77=yes
+ hardcode_shlibpath_var_F77=no
+ ;;
+
+ sysv4)
+ case $host_vendor in
+ sni)
+ archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_direct_F77=yes # is this really true???
+ ;;
+ siemens)
+ ## LD is ld it makes a PLAMLIB
+ ## CC just makes a GrossModule.
+ archive_cmds_F77='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+ reload_cmds_F77='$CC -r -o $output$reload_objs'
+ hardcode_direct_F77=no
+ ;;
+ motorola)
+ archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_direct_F77=no #Motorola manual says yes, but my tests say they lie
+ ;;
+ esac
+ runpath_var='LD_RUN_PATH'
+ hardcode_shlibpath_var_F77=no
+ ;;
+
+ sysv4.3*)
+ archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_shlibpath_var_F77=no
+ export_dynamic_flag_spec_F77='-Bexport'
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec; then
+ archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_shlibpath_var_F77=no
+ runpath_var=LD_RUN_PATH
+ hardcode_runpath_var=yes
+ ld_shlibs_F77=yes
+ fi
+ ;;
+
+ sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7*)
+ no_undefined_flag_F77='${wl}-z,text'
+ archive_cmds_need_lc_F77=no
+ hardcode_shlibpath_var_F77=no
+ runpath_var='LD_RUN_PATH'
+
+ if test "$GCC" = yes; then
+ archive_cmds_F77='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_F77='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ archive_cmds_F77='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_F77='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ fi
+ ;;
+
+ sysv5* | sco3.2v5* | sco5v6*)
+ # Note: We can NOT use -z defs as we might desire, because we do not
+ # link with -lc, and that would cause any symbols used from libc to
+ # always be unresolved, which means just about no library would
+ # ever link correctly. If we're not using GNU ld we use -z text
+ # though, which does catch some bad symbols but isn't as heavy-handed
+ # as -z defs.
+ no_undefined_flag_F77='${wl}-z,text'
+ allow_undefined_flag_F77='${wl}-z,nodefs'
+ archive_cmds_need_lc_F77=no
+ hardcode_shlibpath_var_F77=no
+ hardcode_libdir_flag_spec_F77='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
+ hardcode_libdir_separator_F77=':'
+ link_all_deplibs_F77=yes
+ export_dynamic_flag_spec_F77='${wl}-Bexport'
+ runpath_var='LD_RUN_PATH'
+
+ if test "$GCC" = yes; then
+ archive_cmds_F77='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_F77='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ archive_cmds_F77='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_F77='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ fi
+ ;;
+
+ uts4*)
+ archive_cmds_F77='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_libdir_flag_spec_F77='-L$libdir'
+ hardcode_shlibpath_var_F77=no
+ ;;
+
+ *)
+ ld_shlibs_F77=no
+ ;;
+ esac
+ fi
+
+echo "$as_me:$LINENO: result: $ld_shlibs_F77" >&5
+echo "${ECHO_T}$ld_shlibs_F77" >&6
+test "$ld_shlibs_F77" = no && can_build_shared=no
+
+#
+# Do we need to explicitly link libc?
+#
+case "x$archive_cmds_need_lc_F77" in
+x|xyes)
+ # Assume -lc should be added
+ archive_cmds_need_lc_F77=yes
+
+ if test "$enable_shared" = yes && test "$GCC" = yes; then
+ case $archive_cmds_F77 in
+ *'~'*)
+ # FIXME: we may have to deal with multi-command sequences.
+ ;;
+ '$CC '*)
+ # Test whether the compiler implicitly links with -lc since on some
+ # systems, -lgcc has to come before -lc. If gcc already passes -lc
+ # to ld, don't add -lc before -lgcc.
+ echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
+echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6
+ $rm conftest*
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } 2>conftest.err; then
+ soname=conftest
+ lib=conftest
+ libobjs=conftest.$ac_objext
+ deplibs=
+ wl=$lt_prog_compiler_wl_F77
+ pic_flag=$lt_prog_compiler_pic_F77
+ compiler_flags=-v
+ linker_flags=-v
+ verstring=
+ output_objdir=.
+ libname=conftest
+ lt_save_allow_undefined_flag=$allow_undefined_flag_F77
+ allow_undefined_flag_F77=
+ if { (eval echo "$as_me:$LINENO: \"$archive_cmds_F77 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5
+ (eval $archive_cmds_F77 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+ then
+ archive_cmds_need_lc_F77=no
+ else
+ archive_cmds_need_lc_F77=yes
+ fi
+ allow_undefined_flag_F77=$lt_save_allow_undefined_flag
+ else
+ cat conftest.err 1>&5
+ fi
+ $rm conftest*
+ echo "$as_me:$LINENO: result: $archive_cmds_need_lc_F77" >&5
+echo "${ECHO_T}$archive_cmds_need_lc_F77" >&6
+ ;;
+ esac
+ fi
+ ;;
+esac
+
+echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
+echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
+ # if the path contains ";" then we assume it to be the separator
+ # otherwise default to the standard path separator (i.e. ":") - it is
+ # assumed that no part of a normal pathname contains ";" but that should
+ # okay in the real world where ";" in dirpaths is itself problematic.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+else
+ sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+ shlibpath_var=LIBPATH
+
+ # AIX 3 has no versioning support, so we append a major version to the name.
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+
+aix4* | aix5*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ hardcode_into_libs=yes
+ if test "$host_cpu" = ia64; then
+ # AIX 5 supports IA64
+ library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ else
+ # With GCC up to 2.95.x, collect2 would create an import file
+ # for dependence libraries. The import file would start with
+ # the line `#! .'. This would cause the generated library to
+ # depend on `.', always an invalid library. This was fixed in
+ # development snapshots of GCC prior to 3.0.
+ case $host_os in
+ aix4 | aix4.[01] | aix4.[01].*)
+ if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+ echo ' yes '
+ echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
+ :
+ else
+ can_build_shared=no
+ fi
+ ;;
+ esac
+ # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+ # soname into executable. Probably we can add versioning support to
+ # collect2, so additional links can be useful in future.
+ if test "$aix_use_runtimelinking" = yes; then
+ # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+ # instead of lib<name>.a to let people know that these are not
+ # typical AIX shared libraries.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ else
+ # We preserve .a as extension for shared libraries through AIX4.2
+ # and later when we are not doing run time linking.
+ library_names_spec='${libname}${release}.a $libname.a'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ fi
+ shlibpath_var=LIBPATH
+ fi
+ ;;
+
+amigaos*)
+ library_names_spec='$libname.ixlibrary $libname.a'
+ # Create ${libname}_ixlibrary.a entries in /sys/libs.
+ finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+ ;;
+
+beos*)
+ library_names_spec='${libname}${shared_ext}'
+ dynamic_linker="$host_os ld.so"
+ shlibpath_var=LIBRARY_PATH
+ ;;
+
+bsdi[45]*)
+ version_type=linux
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+ sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+ # the default ld.so.conf also contains /usr/contrib/lib and
+ # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+ # libtool to hard-code these into programs
+ ;;
+
+cygwin* | mingw* | pw32*)
+ version_type=windows
+ shrext_cmds=".dll"
+ need_version=no
+ need_lib_prefix=no
+
+ case $GCC,$host_os in
+ yes,cygwin* | yes,mingw* | yes,pw32*)
+ library_names_spec='$libname.dll.a'
+ # DLL is installed to $(libdir)/../bin by postinstall_cmds
+ postinstall_cmds='base_file=`basename \${file}`~
+ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~
+ dldir=$destdir/`dirname \$dlpath`~
+ test -d \$dldir || mkdir -p \$dldir~
+ $install_prog $dir/$dlname \$dldir/$dlname~
+ chmod a+x \$dldir/$dlname'
+ postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+ dlpath=$dir/\$dldll~
+ $rm \$dlpath'
+ shlibpath_overrides_runpath=yes
+
+ case $host_os in
+ cygwin*)
+ # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+ soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib"
+ ;;
+ mingw*)
+ # MinGW DLLs use traditional 'lib' prefix
+ soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then
+ # It is most probably a Windows format PATH printed by
+ # mingw gcc, but we are running on Cygwin. Gcc prints its search
+ # path with ; separators, and with drive letters. We can handle the
+ # drive letters (cygwin fileutils understands them), so leave them,
+ # especially as we might pass files found there to a mingw objdump,
+ # which wouldn't understand a cygwinified path. Ahh.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+ ;;
+ pw32*)
+ # pw32 DLLs use 'pw' prefix rather than 'lib'
+ library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ ;;
+ esac
+ ;;
+
+ *)
+ library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib'
+ ;;
+ esac
+ dynamic_linker='Win32 ld.exe'
+ # FIXME: first we should search . and the directory the executable is in
+ shlibpath_var=PATH
+ ;;
+
+darwin* | rhapsody*)
+ dynamic_linker="$host_os dyld"
+ version_type=darwin
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+ soname_spec='${libname}${release}${major}$shared_ext'
+ shlibpath_overrides_runpath=yes
+ shlibpath_var=DYLD_LIBRARY_PATH
+ shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+ # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
+ if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
+ else
+ sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib'
+ fi
+ sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+ ;;
+
+dgux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+freebsd1*)
+ dynamic_linker=no
+ ;;
+
+kfreebsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+freebsd* | dragonfly*)
+ # DragonFly does not have aout. When/if they implement a new
+ # versioning mechanism, adjust this.
+ if test -x /usr/bin/objformat; then
+ objformat=`/usr/bin/objformat`
+ else
+ case $host_os in
+ freebsd[123]*) objformat=aout ;;
+ *) objformat=elf ;;
+ esac
+ fi
+ version_type=freebsd-$objformat
+ case $version_type in
+ freebsd-elf*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ need_version=no
+ need_lib_prefix=no
+ ;;
+ freebsd-*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+ need_version=yes
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_os in
+ freebsd2*)
+ shlibpath_overrides_runpath=yes
+ ;;
+ freebsd3.[01]* | freebsdelf3.[01]*)
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
+ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+ freebsd*) # from 4.6 on
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ esac
+ ;;
+
+gnu*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ ;;
+
+hpux9* | hpux10* | hpux11*)
+ # Give a soname corresponding to the major version so that dld.sl refuses to
+ # link against other versions.
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ case $host_cpu in
+ ia64*)
+ shrext_cmds='.so'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.so"
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ if test "X$HPUX_IA64_MODE" = X32; then
+ sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+ else
+ sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+ fi
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ hppa*64*)
+ shrext_cmds='.sl'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ *)
+ shrext_cmds='.sl'
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=SHLIB_PATH
+ shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+ esac
+ # HP-UX runs *really* slowly unless shared libraries are mode 555.
+ postinstall_cmds='chmod 555 $lib'
+ ;;
+
+interix3*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+
+irix5* | irix6* | nonstopux*)
+ case $host_os in
+ nonstopux*) version_type=nonstopux ;;
+ *)
+ if test "$lt_cv_prog_gnu_ld" = yes; then
+ version_type=linux
+ else
+ version_type=irix
+ fi ;;
+ esac
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+ case $host_os in
+ irix5* | nonstopux*)
+ libsuff= shlibsuff=
+ ;;
+ *)
+ case $LD in # libtool.m4 will add one of these switches to LD
+ *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+ libsuff= shlibsuff= libmagic=32-bit;;
+ *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+ libsuff=32 shlibsuff=N32 libmagic=N32;;
+ *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+ libsuff=64 shlibsuff=64 libmagic=64-bit;;
+ *) libsuff= shlibsuff= libmagic=never-match;;
+ esac
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+ sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+ hardcode_into_libs=yes
+ ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+ dynamic_linker=no
+ ;;
+
+# This must be Linux ELF.
+linux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ # This implies no fast_install, which is unacceptable.
+ # Some rework will be needed to allow for fast_install
+ # before this can be enabled.
+ hardcode_into_libs=yes
+
+ # find out which ABI we are using
+ libsuff=
+ case "$host_cpu" in
+ x86_64*|s390x*|powerpc64*)
+ echo '#line 15038 "configure"' > conftest.$ac_ext
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ case `/usr/bin/file conftest.$ac_objext` in
+ *64-bit*)
+ libsuff=64
+ sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}"
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+ esac
+
+ # Append ld.so.conf contents to the search path
+ if test -f /etc/ld.so.conf; then
+ lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+ sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra"
+ fi
+
+ # We used to test for /lib/ld.so.1 and disable shared libraries on
+ # powerpc, because MkLinux only supported shared libraries with the
+ # GNU dynamic linker. Since this was broken with cross compilers,
+ # most powerpc-linux boxes support dynamic linking these days and
+ # people can always --disable-shared, the test was removed, and we
+ # assume the GNU/Linux dynamic linker is in use.
+ dynamic_linker='GNU/Linux ld.so'
+ ;;
+
+knetbsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+netbsd*)
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ dynamic_linker='NetBSD (a.out) ld.so'
+ else
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='NetBSD ld.elf_so'
+ fi
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+
+newsos6)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+nto-qnx*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+openbsd*)
+ version_type=sunos
+ sys_lib_dlsearch_path_spec="/usr/lib"
+ need_lib_prefix=no
+ # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+ case $host_os in
+ openbsd3.3 | openbsd3.3.*) need_version=yes ;;
+ *) need_version=no ;;
+ esac
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ case $host_os in
+ openbsd2.[89] | openbsd2.[89].*)
+ shlibpath_overrides_runpath=no
+ ;;
+ *)
+ shlibpath_overrides_runpath=yes
+ ;;
+ esac
+ else
+ shlibpath_overrides_runpath=yes
+ fi
+ ;;
+
+os2*)
+ libname_spec='$name'
+ shrext_cmds=".dll"
+ need_lib_prefix=no
+ library_names_spec='$libname${shared_ext} $libname.a'
+ dynamic_linker='OS/2 ld.exe'
+ shlibpath_var=LIBPATH
+ ;;
+
+osf3* | osf4* | osf5*)
+ version_type=osf
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+ sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+ ;;
+
+solaris*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ # ldd complains unless libraries are executable
+ postinstall_cmds='chmod +x $lib'
+ ;;
+
+sunos4*)
+ version_type=sunos
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ if test "$with_gnu_ld" = yes; then
+ need_lib_prefix=no
+ fi
+ need_version=yes
+ ;;
+
+sysv4 | sysv4.3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_vendor in
+ sni)
+ shlibpath_overrides_runpath=no
+ need_lib_prefix=no
+ export_dynamic_flag_spec='${wl}-Blargedynsym'
+ runpath_var=LD_RUN_PATH
+ ;;
+ siemens)
+ need_lib_prefix=no
+ ;;
+ motorola)
+ need_lib_prefix=no
+ need_version=no
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+ ;;
+ esac
+ ;;
+
+sysv4*MP*)
+ if test -d /usr/nec ;then
+ version_type=linux
+ library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+ soname_spec='$libname${shared_ext}.$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ fi
+ ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+ version_type=freebsd-elf
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ if test "$with_gnu_ld" = yes; then
+ sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+ shlibpath_overrides_runpath=no
+ else
+ sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+ shlibpath_overrides_runpath=yes
+ case $host_os in
+ sco3.2v5*)
+ sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+ ;;
+ esac
+ fi
+ sys_lib_dlsearch_path_spec='/usr/lib'
+ ;;
+
+uts4*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+*)
+ dynamic_linker=no
+ ;;
+esac
+echo "$as_me:$LINENO: result: $dynamic_linker" >&5
+echo "${ECHO_T}$dynamic_linker" >&6
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+ variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
+echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
+echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
+hardcode_action_F77=
+if test -n "$hardcode_libdir_flag_spec_F77" || \
+ test -n "$runpath_var_F77" || \
+ test "X$hardcode_automatic_F77" = "Xyes" ; then
+
+ # We can hardcode non-existant directories.
+ if test "$hardcode_direct_F77" != no &&
+ # If the only mechanism to avoid hardcoding is shlibpath_var, we
+ # have to relink, otherwise we might link with an installed library
+ # when we should be linking with a yet-to-be-installed one
+ ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, F77)" != no &&
+ test "$hardcode_minus_L_F77" != no; then
+ # Linking always hardcodes the temporary library directory.
+ hardcode_action_F77=relink
+ else
+ # We can link without hardcoding, and we can hardcode nonexisting dirs.
+ hardcode_action_F77=immediate
+ fi
+else
+ # We cannot hardcode anything, or else we can only hardcode existing
+ # directories.
+ hardcode_action_F77=unsupported
+fi
+echo "$as_me:$LINENO: result: $hardcode_action_F77" >&5
+echo "${ECHO_T}$hardcode_action_F77" >&6
+
+if test "$hardcode_action_F77" = relink; then
+ # Fast installation is not supported
+ enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+ test "$enable_shared" = no; then
+ # Fast installation is not necessary
+ enable_fast_install=needless
+fi
+
+
+# The else clause should only fire when bootstrapping the
+# libtool distribution, otherwise you forgot to ship ltmain.sh
+# with your package, and you will get complaints that there are
+# no rules to generate ltmain.sh.
+if test -f "$ltmain"; then
+ # See if we are running on zsh, and set the options which allow our commands through
+ # without removal of \ escapes.
+ if test -n "${ZSH_VERSION+set}" ; then
+ setopt NO_GLOB_SUBST
+ fi
+ # Now quote all the things that may contain metacharacters while being
+ # careful not to overquote the AC_SUBSTed values. We take copies of the
+ # variables and quote the copies for generation of the libtool script.
+ for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \
+ SED SHELL STRIP \
+ libname_spec library_names_spec soname_spec extract_expsyms_cmds \
+ old_striplib striplib file_magic_cmd finish_cmds finish_eval \
+ deplibs_check_method reload_flag reload_cmds need_locks \
+ lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
+ lt_cv_sys_global_symbol_to_c_name_address \
+ sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
+ old_postinstall_cmds old_postuninstall_cmds \
+ compiler_F77 \
+ CC_F77 \
+ LD_F77 \
+ lt_prog_compiler_wl_F77 \
+ lt_prog_compiler_pic_F77 \
+ lt_prog_compiler_static_F77 \
+ lt_prog_compiler_no_builtin_flag_F77 \
+ export_dynamic_flag_spec_F77 \
+ thread_safe_flag_spec_F77 \
+ whole_archive_flag_spec_F77 \
+ enable_shared_with_static_runtimes_F77 \
+ old_archive_cmds_F77 \
+ old_archive_from_new_cmds_F77 \
+ predep_objects_F77 \
+ postdep_objects_F77 \
+ predeps_F77 \
+ postdeps_F77 \
+ compiler_lib_search_path_F77 \
+ archive_cmds_F77 \
+ archive_expsym_cmds_F77 \
+ postinstall_cmds_F77 \
+ postuninstall_cmds_F77 \
+ old_archive_from_expsyms_cmds_F77 \
+ allow_undefined_flag_F77 \
+ no_undefined_flag_F77 \
+ export_symbols_cmds_F77 \
+ hardcode_libdir_flag_spec_F77 \
+ hardcode_libdir_flag_spec_ld_F77 \
+ hardcode_libdir_separator_F77 \
+ hardcode_automatic_F77 \
+ module_cmds_F77 \
+ module_expsym_cmds_F77 \
+ lt_cv_prog_compiler_c_o_F77 \
+ exclude_expsyms_F77 \
+ include_expsyms_F77; do
+
+ case $var in
+ old_archive_cmds_F77 | \
+ old_archive_from_new_cmds_F77 | \
+ archive_cmds_F77 | \
+ archive_expsym_cmds_F77 | \
+ module_cmds_F77 | \
+ module_expsym_cmds_F77 | \
+ old_archive_from_expsyms_cmds_F77 | \
+ export_symbols_cmds_F77 | \
+ extract_expsyms_cmds | reload_cmds | finish_cmds | \
+ postinstall_cmds | postuninstall_cmds | \
+ old_postinstall_cmds | old_postuninstall_cmds | \
+ sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
+ # Double-quote double-evaled strings.
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
+ ;;
+ *)
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\""
+ ;;
+ esac
+ done
+
+ case $lt_echo in
+ *'\$0 --fallback-echo"')
+ lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'`
+ ;;
+ esac
+
+cfgfile="$ofile"
+
+ cat <<__EOF__ >> "$cfgfile"
+# ### BEGIN LIBTOOL TAG CONFIG: $tagname
+
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+
+# Shell to use when invoking shell scripts.
+SHELL=$lt_SHELL
+
+# Whether or not to build shared libraries.
+build_libtool_libs=$enable_shared
+
+# Whether or not to build static libraries.
+build_old_libs=$enable_static
+
+# Whether or not to add -lc for building shared libraries.
+build_libtool_need_lc=$archive_cmds_need_lc_F77
+
+# Whether or not to disallow shared libs when runtime libs are static
+allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_F77
+
+# Whether or not to optimize for fast installation.
+fast_install=$enable_fast_install
+
+# The host system.
+host_alias=$host_alias
+host=$host
+host_os=$host_os
+
+# The build system.
+build_alias=$build_alias
+build=$build
+build_os=$build_os
+
+# An echo program that does not interpret backslashes.
+echo=$lt_echo
+
+# The archiver.
+AR=$lt_AR
+AR_FLAGS=$lt_AR_FLAGS
+
+# A C compiler.
+LTCC=$lt_LTCC
+
+# LTCC compiler flags.
+LTCFLAGS=$lt_LTCFLAGS
+
+# A language-specific compiler.
+CC=$lt_compiler_F77
+
+# Is the compiler the GNU C compiler?
+with_gcc=$GCC_F77
+
+gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\`
+gcc_ver=\`gcc -dumpversion\`
+
+# An ERE matcher.
+EGREP=$lt_EGREP
+
+# The linker used to build libraries.
+LD=$lt_LD_F77
+
+# Whether we need hard or soft links.
+LN_S=$lt_LN_S
+
+# A BSD-compatible nm program.
+NM=$lt_NM
+
+# A symbol stripping program
+STRIP=$lt_STRIP
+
+# Used to examine libraries when file_magic_cmd begins "file"
+MAGIC_CMD=$MAGIC_CMD
+
+# Used on cygwin: DLL creation program.
+DLLTOOL="$DLLTOOL"
+
+# Used on cygwin: object dumper.
+OBJDUMP="$OBJDUMP"
+
+# Used on cygwin: assembler.
+AS="$AS"
+
+# The name of the directory that contains temporary libtool files.
+objdir=$objdir
+
+# How to create reloadable object files.
+reload_flag=$lt_reload_flag
+reload_cmds=$lt_reload_cmds
+
+# How to pass a linker flag through the compiler.
+wl=$lt_lt_prog_compiler_wl_F77
+
+# Object file suffix (normally "o").
+objext="$ac_objext"
+
+# Old archive suffix (normally "a").
+libext="$libext"
+
+# Shared library suffix (normally ".so").
+shrext_cmds='$shrext_cmds'
+
+# Executable file suffix (normally "").
+exeext="$exeext"
+
+# Additional compiler flags for building library objects.
+pic_flag=$lt_lt_prog_compiler_pic_F77
+pic_mode=$pic_mode
+
+# What is the maximum length of a command?
+max_cmd_len=$lt_cv_sys_max_cmd_len
+
+# Does compiler simultaneously support -c and -o options?
+compiler_c_o=$lt_lt_cv_prog_compiler_c_o_F77
+
+# Must we lock files when doing compilation?
+need_locks=$lt_need_locks
+
+# Do we need the lib prefix for modules?
+need_lib_prefix=$need_lib_prefix
+
+# Do we need a version for libraries?
+need_version=$need_version
+
+# Whether dlopen is supported.
+dlopen_support=$enable_dlopen
+
+# Whether dlopen of programs is supported.
+dlopen_self=$enable_dlopen_self
+
+# Whether dlopen of statically linked programs is supported.
+dlopen_self_static=$enable_dlopen_self_static
+
+# Compiler flag to prevent dynamic linking.
+link_static_flag=$lt_lt_prog_compiler_static_F77
+
+# Compiler flag to turn off builtin functions.
+no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_F77
+
+# Compiler flag to allow reflexive dlopens.
+export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_F77
+
+# Compiler flag to generate shared objects directly from archives.
+whole_archive_flag_spec=$lt_whole_archive_flag_spec_F77
+
+# Compiler flag to generate thread-safe objects.
+thread_safe_flag_spec=$lt_thread_safe_flag_spec_F77
+
+# Library versioning type.
+version_type=$version_type
+
+# Format of library name prefix.
+libname_spec=$lt_libname_spec
+
+# List of archive names. First name is the real one, the rest are links.
+# The last name is the one that the linker finds with -lNAME.
+library_names_spec=$lt_library_names_spec
+
+# The coded name of the library, if different from the real name.
+soname_spec=$lt_soname_spec
+
+# Commands used to build and install an old-style archive.
+RANLIB=$lt_RANLIB
+old_archive_cmds=$lt_old_archive_cmds_F77
+old_postinstall_cmds=$lt_old_postinstall_cmds
+old_postuninstall_cmds=$lt_old_postuninstall_cmds
+
+# Create an old-style archive from a shared archive.
+old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_F77
+
+# Create a temporary old-style archive to link instead of a shared archive.
+old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_F77
+
+# Commands used to build and install a shared archive.
+archive_cmds=$lt_archive_cmds_F77
+archive_expsym_cmds=$lt_archive_expsym_cmds_F77
+postinstall_cmds=$lt_postinstall_cmds
+postuninstall_cmds=$lt_postuninstall_cmds
+
+# Commands used to build a loadable module (assumed same as above if empty)
+module_cmds=$lt_module_cmds_F77
+module_expsym_cmds=$lt_module_expsym_cmds_F77
+
+# Commands to strip libraries.
+old_striplib=$lt_old_striplib
+striplib=$lt_striplib
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predep_objects=\`echo $lt_predep_objects_F77 | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdep_objects=\`echo $lt_postdep_objects_F77 | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predeps=$lt_predeps_F77
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdeps=$lt_postdeps_F77
+
+# The library search path used internally by the compiler when linking
+# a shared library.
+compiler_lib_search_path=\`echo $lt_compiler_lib_search_path_F77 | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Method to check whether dependent libraries are shared objects.
+deplibs_check_method=$lt_deplibs_check_method
+
+# Command to use when deplibs_check_method == file_magic.
+file_magic_cmd=$lt_file_magic_cmd
+
+# Flag that allows shared libraries with undefined symbols to be built.
+allow_undefined_flag=$lt_allow_undefined_flag_F77
+
+# Flag that forces no undefined symbols.
+no_undefined_flag=$lt_no_undefined_flag_F77
+
+# Commands used to finish a libtool library installation in a directory.
+finish_cmds=$lt_finish_cmds
+
+# Same as above, but a single script fragment to be evaled but not shown.
+finish_eval=$lt_finish_eval
+
+# Take the output of nm and produce a listing of raw symbols and C names.
+global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
+
+# Transform the output of nm in a proper C declaration
+global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
+
+# Transform the output of nm in a C name address pair
+global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address
+
+# This is the shared library runtime path variable.
+runpath_var=$runpath_var
+
+# This is the shared library path variable.
+shlibpath_var=$shlibpath_var
+
+# Is shlibpath searched before the hard-coded library search path?
+shlibpath_overrides_runpath=$shlibpath_overrides_runpath
+
+# How to hardcode a shared library path into an executable.
+hardcode_action=$hardcode_action_F77
+
+# Whether we should hardcode library paths into libraries.
+hardcode_into_libs=$hardcode_into_libs
+
+# Flag to hardcode \$libdir into a binary during linking.
+# This must work even if \$libdir does not exist.
+hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_F77
+
+# If ld is used when linking, flag to hardcode \$libdir into
+# a binary during linking. This must work even if \$libdir does
+# not exist.
+hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_F77
+
+# Whether we need a single -rpath flag with a separated argument.
+hardcode_libdir_separator=$lt_hardcode_libdir_separator_F77
+
+# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the
+# resulting binary.
+hardcode_direct=$hardcode_direct_F77
+
+# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
+# resulting binary.
+hardcode_minus_L=$hardcode_minus_L_F77
+
+# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into
+# the resulting binary.
+hardcode_shlibpath_var=$hardcode_shlibpath_var_F77
+
+# Set to yes if building a shared library automatically hardcodes DIR into the library
+# and all subsequent libraries and executables linked against it.
+hardcode_automatic=$hardcode_automatic_F77
+
+# Variables whose values should be saved in libtool wrapper scripts and
+# restored at relink time.
+variables_saved_for_relink="$variables_saved_for_relink"
+
+# Whether libtool must link a program against all its dependency libraries.
+link_all_deplibs=$link_all_deplibs_F77
+
+# Compile-time system search path for libraries
+sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Run-time system search path for libraries
+sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec
+
+# Fix the shell variable \$srcfile for the compiler.
+fix_srcfile_path="$fix_srcfile_path_F77"
+
+# Set to yes if exported symbols are required.
+always_export_symbols=$always_export_symbols_F77
+
+# The commands to list exported symbols.
+export_symbols_cmds=$lt_export_symbols_cmds_F77
+
+# The commands to extract the exported symbol list from a shared archive.
+extract_expsyms_cmds=$lt_extract_expsyms_cmds
+
+# Symbols that should not be listed in the preloaded symbols.
+exclude_expsyms=$lt_exclude_expsyms_F77
+
+# Symbols that must always be exported.
+include_expsyms=$lt_include_expsyms_F77
+
+# ### END LIBTOOL TAG CONFIG: $tagname
+
+__EOF__
+
+
+else
+ # If there is no Makefile yet, we rely on a make rule to execute
+ # `config.status --recheck' to rerun these tests and create the
+ # libtool script then.
+ ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'`
+ if test -f "$ltmain_in"; then
+ test -f Makefile && make "$ltmain"
+ fi
+fi
+
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+CC="$lt_save_CC"
+
+ else
+ tagname=""
+ fi
+ ;;
+
+ GCJ)
+ if test -n "$GCJ" && test "X$GCJ" != "Xno"; then
+
+
+
+# Source file extension for Java test sources.
+ac_ext=java
+
+# Object file extension for compiled Java test sources.
+objext=o
+objext_GCJ=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="class foo {}\n"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='public class conftest { public static void main(String[] argv) {}; }\n'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+
+
+# save warnings/boilerplate of simple test code
+ac_outfile=conftest.$ac_objext
+printf "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$rm conftest*
+
+ac_outfile=conftest.$ac_objext
+printf "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$rm conftest*
+
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+CC=${GCJ-"gcj"}
+compiler=$CC
+compiler_GCJ=$CC
+for cc_temp in $compiler""; do
+ case $cc_temp in
+ compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
+ distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
+ \-*) ;;
+ *) break;;
+ esac
+done
+cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+
+
+# GCJ did not exist at the time GCC didn't implicitly link libc in.
+archive_cmds_need_lc_GCJ=no
+
+old_archive_cmds_GCJ=$old_archive_cmds
+
+
+lt_prog_compiler_no_builtin_flag_GCJ=
+
+if test "$GCC" = yes; then
+ lt_prog_compiler_no_builtin_flag_GCJ=' -fno-builtin'
+
+
+echo "$as_me:$LINENO: checking if $compiler supports -fno-rtti -fno-exceptions" >&5
+echo $ECHO_N "checking if $compiler supports -fno-rtti -fno-exceptions... $ECHO_C" >&6
+if test "${lt_cv_prog_compiler_rtti_exceptions+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_cv_prog_compiler_rtti_exceptions=no
+ ac_outfile=conftest.$ac_objext
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+ lt_compiler_flag="-fno-rtti -fno-exceptions"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ # The option is referenced via a variable to avoid confusing sed.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:15816: $lt_compile\"" >&5)
+ (eval "$lt_compile" 2>conftest.err)
+ ac_status=$?
+ cat conftest.err >&5
+ echo "$as_me:15820: \$? = $ac_status" >&5
+ if (exit $ac_status) && test -s "$ac_outfile"; then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings other than the usual output.
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+ lt_cv_prog_compiler_rtti_exceptions=yes
+ fi
+ fi
+ $rm conftest*
+
+fi
+echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_rtti_exceptions" >&5
+echo "${ECHO_T}$lt_cv_prog_compiler_rtti_exceptions" >&6
+
+if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then
+ lt_prog_compiler_no_builtin_flag_GCJ="$lt_prog_compiler_no_builtin_flag_GCJ -fno-rtti -fno-exceptions"
+else
+ :
+fi
+
+fi
+
+lt_prog_compiler_wl_GCJ=
+lt_prog_compiler_pic_GCJ=
+lt_prog_compiler_static_GCJ=
+
+echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
+echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6
+
+ if test "$GCC" = yes; then
+ lt_prog_compiler_wl_GCJ='-Wl,'
+ lt_prog_compiler_static_GCJ='-static'
+
+ case $host_os in
+ aix*)
+ # All AIX code is PIC.
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ lt_prog_compiler_static_GCJ='-Bstatic'
+ fi
+ ;;
+
+ amigaos*)
+ # FIXME: we need at least 68020 code to build shared libraries, but
+ # adding the `-m68020' flag to GCC prevents building anything better,
+ # like `-m68040'.
+ lt_prog_compiler_pic_GCJ='-m68020 -resident32 -malways-restore-a4'
+ ;;
+
+ beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+ # PIC is the default for these OSes.
+ ;;
+
+ mingw* | pw32* | os2*)
+ # This hack is so that the source file can tell whether it is being
+ # built for inclusion in a dll (and should export symbols for example).
+ lt_prog_compiler_pic_GCJ='-DDLL_EXPORT'
+ ;;
+
+ darwin* | rhapsody*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ lt_prog_compiler_pic_GCJ='-fno-common'
+ ;;
+
+ interix3*)
+ # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+ # Instead, we relocate shared libraries at runtime.
+ ;;
+
+ msdosdjgpp*)
+ # Just because we use GCC doesn't mean we suddenly get shared libraries
+ # on systems that don't support them.
+ lt_prog_compiler_can_build_shared_GCJ=no
+ enable_shared=no
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec; then
+ lt_prog_compiler_pic_GCJ=-Kconform_pic
+ fi
+ ;;
+
+ hpux*)
+ # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+ # not for PA HP-UX.
+ case $host_cpu in
+ hppa*64*|ia64*)
+ # +Z the default
+ ;;
+ *)
+ lt_prog_compiler_pic_GCJ='-fPIC'
+ ;;
+ esac
+ ;;
+
+ *)
+ lt_prog_compiler_pic_GCJ='-fPIC'
+ ;;
+ esac
+ else
+ # PORTME Check for flag to pass linker flags through the system compiler.
+ case $host_os in
+ aix*)
+ lt_prog_compiler_wl_GCJ='-Wl,'
+ if test "$host_cpu" = ia64; then
+ # AIX 5 now supports IA64 processor
+ lt_prog_compiler_static_GCJ='-Bstatic'
+ else
+ lt_prog_compiler_static_GCJ='-bnso -bI:/lib/syscalls.exp'
+ fi
+ ;;
+ darwin*)
+ # PIC is the default on this platform
+ # Common symbols not allowed in MH_DYLIB files
+ case $cc_basename in
+ xlc*)
+ lt_prog_compiler_pic_GCJ='-qnocommon'
+ lt_prog_compiler_wl_GCJ='-Wl,'
+ ;;
+ esac
+ ;;
+
+ mingw* | pw32* | os2*)
+ # This hack is so that the source file can tell whether it is being
+ # built for inclusion in a dll (and should export symbols for example).
+ lt_prog_compiler_pic_GCJ='-DDLL_EXPORT'
+ ;;
+
+ hpux9* | hpux10* | hpux11*)
+ lt_prog_compiler_wl_GCJ='-Wl,'
+ # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+ # not for PA HP-UX.
+ case $host_cpu in
+ hppa*64*|ia64*)
+ # +Z the default
+ ;;
+ *)
+ lt_prog_compiler_pic_GCJ='+Z'
+ ;;
+ esac
+ # Is there a better lt_prog_compiler_static that works with the bundled CC?
+ lt_prog_compiler_static_GCJ='${wl}-a ${wl}archive'
+ ;;
+
+ irix5* | irix6* | nonstopux*)
+ lt_prog_compiler_wl_GCJ='-Wl,'
+ # PIC (with -KPIC) is the default.
+ lt_prog_compiler_static_GCJ='-non_shared'
+ ;;
+
+ newsos6)
+ lt_prog_compiler_pic_GCJ='-KPIC'
+ lt_prog_compiler_static_GCJ='-Bstatic'
+ ;;
+
+ linux*)
+ case $cc_basename in
+ icc* | ecc*)
+ lt_prog_compiler_wl_GCJ='-Wl,'
+ lt_prog_compiler_pic_GCJ='-KPIC'
+ lt_prog_compiler_static_GCJ='-static'
+ ;;
+ pgcc* | pgf77* | pgf90* | pgf95*)
+ # Portland Group compilers (*not* the Pentium gcc compiler,
+ # which looks to be a dead project)
+ lt_prog_compiler_wl_GCJ='-Wl,'
+ lt_prog_compiler_pic_GCJ='-fpic'
+ lt_prog_compiler_static_GCJ='-Bstatic'
+ ;;
+ ccc*)
+ lt_prog_compiler_wl_GCJ='-Wl,'
+ # All Alpha code is PIC.
+ lt_prog_compiler_static_GCJ='-non_shared'
+ ;;
+ esac
+ ;;
+
+ osf3* | osf4* | osf5*)
+ lt_prog_compiler_wl_GCJ='-Wl,'
+ # All OSF/1 code is PIC.
+ lt_prog_compiler_static_GCJ='-non_shared'
+ ;;
+
+ solaris*)
+ lt_prog_compiler_pic_GCJ='-KPIC'
+ lt_prog_compiler_static_GCJ='-Bstatic'
+ case $cc_basename in
+ f77* | f90* | f95*)
+ lt_prog_compiler_wl_GCJ='-Qoption ld ';;
+ *)
+ lt_prog_compiler_wl_GCJ='-Wl,';;
+ esac
+ ;;
+
+ sunos4*)
+ lt_prog_compiler_wl_GCJ='-Qoption ld '
+ lt_prog_compiler_pic_GCJ='-PIC'
+ lt_prog_compiler_static_GCJ='-Bstatic'
+ ;;
+
+ sysv4 | sysv4.2uw2* | sysv4.3*)
+ lt_prog_compiler_wl_GCJ='-Wl,'
+ lt_prog_compiler_pic_GCJ='-KPIC'
+ lt_prog_compiler_static_GCJ='-Bstatic'
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec ;then
+ lt_prog_compiler_pic_GCJ='-Kconform_pic'
+ lt_prog_compiler_static_GCJ='-Bstatic'
+ fi
+ ;;
+
+ sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+ lt_prog_compiler_wl_GCJ='-Wl,'
+ lt_prog_compiler_pic_GCJ='-KPIC'
+ lt_prog_compiler_static_GCJ='-Bstatic'
+ ;;
+
+ unicos*)
+ lt_prog_compiler_wl_GCJ='-Wl,'
+ lt_prog_compiler_can_build_shared_GCJ=no
+ ;;
+
+ uts4*)
+ lt_prog_compiler_pic_GCJ='-pic'
+ lt_prog_compiler_static_GCJ='-Bstatic'
+ ;;
+
+ *)
+ lt_prog_compiler_can_build_shared_GCJ=no
+ ;;
+ esac
+ fi
+
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_GCJ" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_GCJ" >&6
+
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$lt_prog_compiler_pic_GCJ"; then
+
+echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_pic_GCJ works" >&5
+echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_GCJ works... $ECHO_C" >&6
+if test "${lt_prog_compiler_pic_works_GCJ+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_prog_compiler_pic_works_GCJ=no
+ ac_outfile=conftest.$ac_objext
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+ lt_compiler_flag="$lt_prog_compiler_pic_GCJ"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ # The option is referenced via a variable to avoid confusing sed.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:16084: $lt_compile\"" >&5)
+ (eval "$lt_compile" 2>conftest.err)
+ ac_status=$?
+ cat conftest.err >&5
+ echo "$as_me:16088: \$? = $ac_status" >&5
+ if (exit $ac_status) && test -s "$ac_outfile"; then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings other than the usual output.
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+ lt_prog_compiler_pic_works_GCJ=yes
+ fi
+ fi
+ $rm conftest*
+
+fi
+echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_GCJ" >&5
+echo "${ECHO_T}$lt_prog_compiler_pic_works_GCJ" >&6
+
+if test x"$lt_prog_compiler_pic_works_GCJ" = xyes; then
+ case $lt_prog_compiler_pic_GCJ in
+ "" | " "*) ;;
+ *) lt_prog_compiler_pic_GCJ=" $lt_prog_compiler_pic_GCJ" ;;
+ esac
+else
+ lt_prog_compiler_pic_GCJ=
+ lt_prog_compiler_can_build_shared_GCJ=no
+fi
+
+fi
+case $host_os in
+ # For platforms which do not support PIC, -DPIC is meaningless:
+ *djgpp*)
+ lt_prog_compiler_pic_GCJ=
+ ;;
+ *)
+ lt_prog_compiler_pic_GCJ="$lt_prog_compiler_pic_GCJ"
+ ;;
+esac
+
+#
+# Check to make sure the static flag actually works.
+#
+wl=$lt_prog_compiler_wl_GCJ eval lt_tmp_static_flag=\"$lt_prog_compiler_static_GCJ\"
+echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_flag works" >&5
+echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works... $ECHO_C" >&6
+if test "${lt_prog_compiler_static_works_GCJ+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_prog_compiler_static_works_GCJ=no
+ save_LDFLAGS="$LDFLAGS"
+ LDFLAGS="$LDFLAGS $lt_tmp_static_flag"
+ printf "$lt_simple_link_test_code" > conftest.$ac_ext
+ if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+ # The linker can only warn and ignore the option if not recognized
+ # So say no if there are warnings
+ if test -s conftest.err; then
+ # Append any errors to the config.log.
+ cat conftest.err 1>&5
+ $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
+ $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+ if diff conftest.exp conftest.er2 >/dev/null; then
+ lt_prog_compiler_static_works_GCJ=yes
+ fi
+ else
+ lt_prog_compiler_static_works_GCJ=yes
+ fi
+ fi
+ $rm conftest*
+ LDFLAGS="$save_LDFLAGS"
+
+fi
+echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_GCJ" >&5
+echo "${ECHO_T}$lt_prog_compiler_static_works_GCJ" >&6
+
+if test x"$lt_prog_compiler_static_works_GCJ" = xyes; then
+ :
+else
+ lt_prog_compiler_static_GCJ=
+fi
+
+
+echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_objext" >&5
+echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECHO_C" >&6
+if test "${lt_cv_prog_compiler_c_o_GCJ+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ lt_cv_prog_compiler_c_o_GCJ=no
+ $rm -r conftest 2>/dev/null
+ mkdir conftest
+ cd conftest
+ mkdir out
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+ lt_compiler_flag="-o out/conftest2.$ac_objext"
+ # Insert the option either (1) after the last *FLAGS variable, or
+ # (2) before a word containing "conftest.", or (3) at the end.
+ # Note that $ac_compile itself does not contain backslashes and begins
+ # with a dollar sign (not a hyphen), so the echo should work correctly.
+ lt_compile=`echo "$ac_compile" | $SED \
+ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+ -e 's:$: $lt_compiler_flag:'`
+ (eval echo "\"\$as_me:16188: $lt_compile\"" >&5)
+ (eval "$lt_compile" 2>out/conftest.err)
+ ac_status=$?
+ cat out/conftest.err >&5
+ echo "$as_me:16192: \$? = $ac_status" >&5
+ if (exit $ac_status) && test -s out/conftest2.$ac_objext
+ then
+ # The compiler can only warn and ignore the option if not recognized
+ # So say no if there are warnings
+ $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
+ $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+ if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+ lt_cv_prog_compiler_c_o_GCJ=yes
+ fi
+ fi
+ chmod u+w . 2>&5
+ $rm conftest*
+ # SGI C++ compiler will create directory out/ii_files/ for
+ # template instantiation
+ test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files
+ $rm out/* && rmdir out
+ cd ..
+ rmdir conftest
+ $rm conftest*
+
+fi
+echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_GCJ" >&5
+echo "${ECHO_T}$lt_cv_prog_compiler_c_o_GCJ" >&6
+
+
+hard_links="nottested"
+if test "$lt_cv_prog_compiler_c_o_GCJ" = no && test "$need_locks" != no; then
+ # do not overwrite the value of need_locks provided by the user
+ echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
+echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6
+ hard_links=yes
+ $rm conftest*
+ ln conftest.a conftest.b 2>/dev/null && hard_links=no
+ touch conftest.a
+ ln conftest.a conftest.b 2>&5 || hard_links=no
+ ln conftest.a conftest.b 2>/dev/null && hard_links=no
+ echo "$as_me:$LINENO: result: $hard_links" >&5
+echo "${ECHO_T}$hard_links" >&6
+ if test "$hard_links" = no; then
+ { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
+echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
+ need_locks=warn
+ fi
+else
+ need_locks=no
+fi
+
+echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) supports shared libraries" >&5
+echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared libraries... $ECHO_C" >&6
+
+ runpath_var=
+ allow_undefined_flag_GCJ=
+ enable_shared_with_static_runtimes_GCJ=no
+ archive_cmds_GCJ=
+ archive_expsym_cmds_GCJ=
+ old_archive_From_new_cmds_GCJ=
+ old_archive_from_expsyms_cmds_GCJ=
+ export_dynamic_flag_spec_GCJ=
+ whole_archive_flag_spec_GCJ=
+ thread_safe_flag_spec_GCJ=
+ hardcode_libdir_flag_spec_GCJ=
+ hardcode_libdir_flag_spec_ld_GCJ=
+ hardcode_libdir_separator_GCJ=
+ hardcode_direct_GCJ=no
+ hardcode_minus_L_GCJ=no
+ hardcode_shlibpath_var_GCJ=unsupported
+ link_all_deplibs_GCJ=unknown
+ hardcode_automatic_GCJ=no
+ module_cmds_GCJ=
+ module_expsym_cmds_GCJ=
+ always_export_symbols_GCJ=no
+ export_symbols_cmds_GCJ='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+ # include_expsyms should be a list of space-separated symbols to be *always*
+ # included in the symbol list
+ include_expsyms_GCJ=
+ # exclude_expsyms can be an extended regexp of symbols to exclude
+ # it will be wrapped by ` (' and `)$', so one must not match beginning or
+ # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
+ # as well as any symbol that contains `d'.
+ exclude_expsyms_GCJ="_GLOBAL_OFFSET_TABLE_"
+ # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
+ # platforms (ab)use it in PIC code, but their linkers get confused if
+ # the symbol is explicitly referenced. Since portable code cannot
+ # rely on this symbol name, it's probably fine to never include it in
+ # preloaded symbol tables.
+ extract_expsyms_cmds=
+ # Just being paranoid about ensuring that cc_basename is set.
+ for cc_temp in $compiler""; do
+ case $cc_temp in
+ compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
+ distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
+ \-*) ;;
+ *) break;;
+ esac
+done
+cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+
+ case $host_os in
+ cygwin* | mingw* | pw32*)
+ # FIXME: the MSVC++ port hasn't been tested in a loooong time
+ # When not using gcc, we currently assume that we are using
+ # Microsoft Visual C++.
+ if test "$GCC" != yes; then
+ with_gnu_ld=no
+ fi
+ ;;
+ interix*)
+ # we just hope/assume this is gcc and not c89 (= MSVC++)
+ with_gnu_ld=yes
+ ;;
+ openbsd*)
+ with_gnu_ld=no
+ ;;
+ esac
+
+ ld_shlibs_GCJ=yes
+ if test "$with_gnu_ld" = yes; then
+ # If archive_cmds runs LD, not CC, wlarc should be empty
+ wlarc='${wl}'
+
+ # Set some defaults for GNU ld with shared library support. These
+ # are reset later if shared libraries are not supported. Putting them
+ # here allows them to be overridden if necessary.
+ runpath_var=LD_RUN_PATH
+ hardcode_libdir_flag_spec_GCJ='${wl}--rpath ${wl}$libdir'
+ export_dynamic_flag_spec_GCJ='${wl}--export-dynamic'
+ # ancient GNU ld didn't support --whole-archive et. al.
+ if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
+ whole_archive_flag_spec_GCJ="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+ else
+ whole_archive_flag_spec_GCJ=
+ fi
+ supports_anon_versioning=no
+ case `$LD -v 2>/dev/null` in
+ *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
+ *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+ *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+ *\ 2.11.*) ;; # other 2.11 versions
+ *) supports_anon_versioning=yes ;;
+ esac
+
+ # See if GNU ld supports shared libraries.
+ case $host_os in
+ aix3* | aix4* | aix5*)
+ # On AIX/PPC, the GNU linker is very broken
+ if test "$host_cpu" != ia64; then
+ ld_shlibs_GCJ=no
+ cat <<EOF 1>&2
+
+*** Warning: the GNU linker, at least up to release 2.9.1, is reported
+*** to be unable to reliably create shared libraries on AIX.
+*** Therefore, libtool is disabling shared libraries support. If you
+*** really care for shared libraries, you may want to modify your PATH
+*** so that a non-GNU linker is found, and then restart.
+
+EOF
+ fi
+ ;;
+
+ amigaos*)
+ archive_cmds_GCJ='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+ hardcode_libdir_flag_spec_GCJ='-L$libdir'
+ hardcode_minus_L_GCJ=yes
+
+ # Samuel A. Falvo II <kc5tja at dolphin.openprojects.net> reports
+ # that the semantics of dynamic libraries on AmigaOS, at least up
+ # to version 4, is to share data among multiple programs linked
+ # with the same dynamic library. Since this doesn't match the
+ # behavior of shared libraries on other platforms, we can't use
+ # them.
+ ld_shlibs_GCJ=no
+ ;;
+
+ beos*)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ allow_undefined_flag_GCJ=unsupported
+ # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
+ # support --undefined. This deserves some investigation. FIXME
+ archive_cmds_GCJ='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ else
+ ld_shlibs_GCJ=no
+ fi
+ ;;
+
+ cygwin* | mingw* | pw32*)
+ # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, GCJ) is actually meaningless,
+ # as there is no search path for DLLs.
+ hardcode_libdir_flag_spec_GCJ='-L$libdir'
+ allow_undefined_flag_GCJ=unsupported
+ always_export_symbols_GCJ=no
+ enable_shared_with_static_runtimes_GCJ=yes
+ export_symbols_cmds_GCJ='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols'
+
+ if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
+ archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ # If the export-symbols file already is a .def file (1st line
+ # is EXPORTS), use it as is; otherwise, prepend...
+ archive_expsym_cmds_GCJ='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+ cp $export_symbols $output_objdir/$soname.def;
+ else
+ echo EXPORTS > $output_objdir/$soname.def;
+ cat $export_symbols >> $output_objdir/$soname.def;
+ fi~
+ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+ else
+ ld_shlibs_GCJ=no
+ fi
+ ;;
+
+ interix3*)
+ hardcode_direct_GCJ=no
+ hardcode_shlibpath_var_GCJ=no
+ hardcode_libdir_flag_spec_GCJ='${wl}-rpath,$libdir'
+ export_dynamic_flag_spec_GCJ='${wl}-E'
+ # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+ # Instead, shared libraries are loaded at an image base (0x10000000 by
+ # default) and relocated if they conflict, which is a slow very memory
+ # consuming and fragmenting process. To avoid this, we pick a random,
+ # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+ # time. Moving up from 0x10000000 also allows more sbrk(2) space.
+ archive_cmds_GCJ='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ archive_expsym_cmds_GCJ='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+ ;;
+
+ linux*)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ tmp_addflag=
+ case $cc_basename,$host_cpu in
+ pgcc*) # Portland Group C compiler
+ whole_archive_flag_spec_GCJ='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+ tmp_addflag=' $pic_flag'
+ ;;
+ pgf77* | pgf90* | pgf95*) # Portland Group f77 and f90 compilers
+ whole_archive_flag_spec_GCJ='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+ tmp_addflag=' $pic_flag -Mnomain' ;;
+ ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64
+ tmp_addflag=' -i_dynamic' ;;
+ efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64
+ tmp_addflag=' -i_dynamic -nofor_main' ;;
+ ifc* | ifort*) # Intel Fortran compiler
+ tmp_addflag=' -nofor_main' ;;
+ esac
+ archive_cmds_GCJ='$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+
+ if test $supports_anon_versioning = yes; then
+ archive_expsym_cmds_GCJ='$echo "{ global:" > $output_objdir/$libname.ver~
+ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+ $echo "local: *; };" >> $output_objdir/$libname.ver~
+ $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+ fi
+ else
+ ld_shlibs_GCJ=no
+ fi
+ ;;
+
+ netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ archive_cmds_GCJ='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
+ wlarc=
+ else
+ archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ archive_expsym_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ fi
+ ;;
+
+ solaris*)
+ if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
+ ld_shlibs_GCJ=no
+ cat <<EOF 1>&2
+
+*** Warning: The releases 2.8.* of the GNU linker cannot reliably
+*** create shared libraries on Solaris systems. Therefore, libtool
+*** is disabling shared libraries support. We urge you to upgrade GNU
+*** binutils to release 2.9.1 or newer. Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+EOF
+ elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ archive_expsym_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ else
+ ld_shlibs_GCJ=no
+ fi
+ ;;
+
+ sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
+ case `$LD -v 2>&1` in
+ *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*)
+ ld_shlibs_GCJ=no
+ cat <<_LT_EOF 1>&2
+
+*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
+*** reliably create shared libraries on SCO systems. Therefore, libtool
+*** is disabling shared libraries support. We urge you to upgrade GNU
+*** binutils to release 2.16.91.0.3 or newer. Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+ ;;
+ *)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ hardcode_libdir_flag_spec_GCJ='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`'
+ archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib'
+ archive_expsym_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file,$export_symbols -o $lib'
+ else
+ ld_shlibs_GCJ=no
+ fi
+ ;;
+ esac
+ ;;
+
+ sunos4*)
+ archive_cmds_GCJ='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ wlarc=
+ hardcode_direct_GCJ=yes
+ hardcode_shlibpath_var_GCJ=no
+ ;;
+
+ *)
+ if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+ archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+ archive_expsym_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+ else
+ ld_shlibs_GCJ=no
+ fi
+ ;;
+ esac
+
+ if test "$ld_shlibs_GCJ" = no; then
+ runpath_var=
+ hardcode_libdir_flag_spec_GCJ=
+ export_dynamic_flag_spec_GCJ=
+ whole_archive_flag_spec_GCJ=
+ fi
+ else
+ # PORTME fill in a description of your system's linker (not GNU ld)
+ case $host_os in
+ aix3*)
+ allow_undefined_flag_GCJ=unsupported
+ always_export_symbols_GCJ=yes
+ archive_expsym_cmds_GCJ='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
+ # Note: this linker hardcodes the directories in LIBPATH if there
+ # are no directories specified by -L.
+ hardcode_minus_L_GCJ=yes
+ if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+ # Neither direct hardcoding nor static linking is supported with a
+ # broken collect2.
+ hardcode_direct_GCJ=unsupported
+ fi
+ ;;
+
+ aix4* | aix5*)
+ if test "$host_cpu" = ia64; then
+ # On IA64, the linker does run time linking by default, so we don't
+ # have to do anything special.
+ aix_use_runtimelinking=no
+ exp_sym_flag='-Bexport'
+ no_entry_flag=""
+ else
+ # If we're using GNU nm, then we don't want the "-C" option.
+ # -C means demangle to AIX nm, but means don't demangle with GNU nm
+ if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
+ export_symbols_cmds_GCJ='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
+ else
+ export_symbols_cmds_GCJ='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$2 == "T") || (\$2 == "D") || (\$2 == "B")) && (substr(\$3,1,1) != ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
+ fi
+ aix_use_runtimelinking=no
+
+ # Test if we are trying to use run time linking or normal
+ # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+ # need to do runtime linking.
+ case $host_os in aix4.[23]|aix4.[23].*|aix5*)
+ for ld_flag in $LDFLAGS; do
+ if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+ aix_use_runtimelinking=yes
+ break
+ fi
+ done
+ ;;
+ esac
+
+ exp_sym_flag='-bexport'
+ no_entry_flag='-bnoentry'
+ fi
+
+ # When large executables or shared objects are built, AIX ld can
+ # have problems creating the table of contents. If linking a library
+ # or program results in "error TOC overflow" add -mminimal-toc to
+ # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not
+ # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+ archive_cmds_GCJ=''
+ hardcode_direct_GCJ=yes
+ hardcode_libdir_separator_GCJ=':'
+ link_all_deplibs_GCJ=yes
+
+ if test "$GCC" = yes; then
+ case $host_os in aix4.[012]|aix4.[012].*)
+ # We only want to do this on AIX 4.2 and lower, the check
+ # below for broken collect2 doesn't work under 4.3+
+ collect2name=`${CC} -print-prog-name=collect2`
+ if test -f "$collect2name" && \
+ strings "$collect2name" | grep resolve_lib_name >/dev/null
+ then
+ # We have reworked collect2
+ hardcode_direct_GCJ=yes
+ else
+ # We have old collect2
+ hardcode_direct_GCJ=unsupported
+ # It fails to find uninstalled libraries when the uninstalled
+ # path is not listed in the libpath. Setting hardcode_minus_L
+ # to unsupported forces relinking
+ hardcode_minus_L_GCJ=yes
+ hardcode_libdir_flag_spec_GCJ='-L$libdir'
+ hardcode_libdir_separator_GCJ=
+ fi
+ ;;
+ esac
+ shared_flag='-shared'
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag="$shared_flag "'${wl}-G'
+ fi
+ else
+ # not using gcc
+ if test "$host_cpu" = ia64; then
+ # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+ # chokes on -Wl,-G. The following line is correct:
+ shared_flag='-G'
+ else
+ if test "$aix_use_runtimelinking" = yes; then
+ shared_flag='${wl}-G'
+ else
+ shared_flag='${wl}-bM:SRE'
+ fi
+ fi
+ fi
+
+ # It seems that -bexpall does not export symbols beginning with
+ # underscore (_), so it is better to generate a list of symbols to export.
+ always_export_symbols_GCJ=yes
+ if test "$aix_use_runtimelinking" = yes; then
+ # Warning - without using the other runtime loading flags (-brtl),
+ # -berok will link without error, but may produce a broken library.
+ allow_undefined_flag_GCJ='-berok'
+ # Determine the default libpath from the value encoded in an empty executable.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`; fi
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+
+ hardcode_libdir_flag_spec_GCJ='${wl}-blibpath:$libdir:'"$aix_libpath"
+ archive_expsym_cmds_GCJ="\$CC"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+ else
+ if test "$host_cpu" = ia64; then
+ hardcode_libdir_flag_spec_GCJ='${wl}-R $libdir:/usr/lib:/lib'
+ allow_undefined_flag_GCJ="-z nodefs"
+ archive_expsym_cmds_GCJ="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+ else
+ # Determine the default libpath from the value encoded in an empty executable.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; }
+}'`; fi
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+
+ hardcode_libdir_flag_spec_GCJ='${wl}-blibpath:$libdir:'"$aix_libpath"
+ # Warning - without using the other run time loading flags,
+ # -berok will link without error, but may produce a broken library.
+ no_undefined_flag_GCJ=' ${wl}-bernotok'
+ allow_undefined_flag_GCJ=' ${wl}-berok'
+ # Exported symbols can be pulled into shared objects from archives
+ whole_archive_flag_spec_GCJ='$convenience'
+ archive_cmds_need_lc_GCJ=yes
+ # This is similar to how AIX traditionally builds its shared libraries.
+ archive_expsym_cmds_GCJ="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+ fi
+ fi
+ ;;
+
+ amigaos*)
+ archive_cmds_GCJ='$rm $output_objdir/a2ixlibrary.data~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+ hardcode_libdir_flag_spec_GCJ='-L$libdir'
+ hardcode_minus_L_GCJ=yes
+ # see comment about different semantics on the GNU ld section
+ ld_shlibs_GCJ=no
+ ;;
+
+ bsdi[45]*)
+ export_dynamic_flag_spec_GCJ=-rdynamic
+ ;;
+
+ cygwin* | mingw* | pw32*)
+ # When not using gcc, we currently assume that we are using
+ # Microsoft Visual C++.
+ # hardcode_libdir_flag_spec is actually meaningless, as there is
+ # no search path for DLLs.
+ hardcode_libdir_flag_spec_GCJ=' '
+ allow_undefined_flag_GCJ=unsupported
+ # Tell ltmain to make .lib files, not .a files.
+ libext=lib
+ # Tell ltmain to make .dll files, not .so files.
+ shrext_cmds=".dll"
+ # FIXME: Setting linknames here is a bad hack.
+ archive_cmds_GCJ='$CC -o $lib $libobjs $compiler_flags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames='
+ # The linker will automatically build a .lib file if we build a DLL.
+ old_archive_From_new_cmds_GCJ='true'
+ # FIXME: Should let the user specify the lib program.
+ old_archive_cmds_GCJ='lib /OUT:$oldlib$oldobjs$old_deplibs'
+ fix_srcfile_path_GCJ='`cygpath -w "$srcfile"`'
+ enable_shared_with_static_runtimes_GCJ=yes
+ ;;
+
+ darwin* | rhapsody*)
+ case $host_os in
+ rhapsody* | darwin1.[012])
+ allow_undefined_flag_GCJ='${wl}-undefined ${wl}suppress'
+ ;;
+ *) # Darwin 1.3 on
+ if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
+ allow_undefined_flag_GCJ='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ else
+ case ${MACOSX_DEPLOYMENT_TARGET} in
+ 10.[012])
+ allow_undefined_flag_GCJ='${wl}-flat_namespace ${wl}-undefined ${wl}suppress'
+ ;;
+ 10.*)
+ allow_undefined_flag_GCJ='${wl}-undefined ${wl}dynamic_lookup'
+ ;;
+ esac
+ fi
+ ;;
+ esac
+ archive_cmds_need_lc_GCJ=no
+ hardcode_direct_GCJ=no
+ hardcode_automatic_GCJ=yes
+ hardcode_shlibpath_var_GCJ=unsupported
+ whole_archive_flag_spec_GCJ=''
+ link_all_deplibs_GCJ=yes
+ if test "$GCC" = yes ; then
+ output_verbose_link_cmd='echo'
+ archive_cmds_GCJ='$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
+ module_cmds_GCJ='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ archive_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ module_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ else
+ case $cc_basename in
+ xlc*)
+ output_verbose_link_cmd='echo'
+ archive_cmds_GCJ='$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname` $verstring'
+ module_cmds_GCJ='$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags'
+ # Don't fix this by using the ld -exported_symbols_list flag, it doesn't exist in older darwin lds
+ archive_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ module_expsym_cmds_GCJ='sed -e "s,#.*,," -e "s,^[ ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $allow_undefined_flag -o $lib -bundle $libobjs $deplibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
+ ;;
+ *)
+ ld_shlibs_GCJ=no
+ ;;
+ esac
+ fi
+ ;;
+
+ dgux*)
+ archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_libdir_flag_spec_GCJ='-L$libdir'
+ hardcode_shlibpath_var_GCJ=no
+ ;;
+
+ freebsd1*)
+ ld_shlibs_GCJ=no
+ ;;
+
+ # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
+ # support. Future versions do this automatically, but an explicit c++rt0.o
+ # does not break anything, and helps significantly (at the cost of a little
+ # extra space).
+ freebsd2.2*)
+ archive_cmds_GCJ='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
+ hardcode_libdir_flag_spec_GCJ='-R$libdir'
+ hardcode_direct_GCJ=yes
+ hardcode_shlibpath_var_GCJ=no
+ ;;
+
+ # Unfortunately, older versions of FreeBSD 2 do not have this feature.
+ freebsd2*)
+ archive_cmds_GCJ='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_direct_GCJ=yes
+ hardcode_minus_L_GCJ=yes
+ hardcode_shlibpath_var_GCJ=no
+ ;;
+
+ # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
+ freebsd* | kfreebsd*-gnu | dragonfly*)
+ archive_cmds_GCJ='$CC -shared -o $lib $libobjs $deplibs $compiler_flags'
+ hardcode_libdir_flag_spec_GCJ='-R$libdir'
+ hardcode_direct_GCJ=yes
+ hardcode_shlibpath_var_GCJ=no
+ ;;
+
+ hpux9*)
+ if test "$GCC" = yes; then
+ archive_cmds_GCJ='$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ else
+ archive_cmds_GCJ='$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+ fi
+ hardcode_libdir_flag_spec_GCJ='${wl}+b ${wl}$libdir'
+ hardcode_libdir_separator_GCJ=:
+ hardcode_direct_GCJ=yes
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ hardcode_minus_L_GCJ=yes
+ export_dynamic_flag_spec_GCJ='${wl}-E'
+ ;;
+
+ hpux10*)
+ if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+ archive_cmds_GCJ='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ archive_cmds_GCJ='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
+ fi
+ if test "$with_gnu_ld" = no; then
+ hardcode_libdir_flag_spec_GCJ='${wl}+b ${wl}$libdir'
+ hardcode_libdir_separator_GCJ=:
+
+ hardcode_direct_GCJ=yes
+ export_dynamic_flag_spec_GCJ='${wl}-E'
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ hardcode_minus_L_GCJ=yes
+ fi
+ ;;
+
+ hpux11*)
+ if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+ case $host_cpu in
+ hppa*64*)
+ archive_cmds_GCJ='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ ia64*)
+ archive_cmds_GCJ='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ archive_cmds_GCJ='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ else
+ case $host_cpu in
+ hppa*64*)
+ archive_cmds_GCJ='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ ia64*)
+ archive_cmds_GCJ='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ *)
+ archive_cmds_GCJ='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+ ;;
+ esac
+ fi
+ if test "$with_gnu_ld" = no; then
+ hardcode_libdir_flag_spec_GCJ='${wl}+b ${wl}$libdir'
+ hardcode_libdir_separator_GCJ=:
+
+ case $host_cpu in
+ hppa*64*|ia64*)
+ hardcode_libdir_flag_spec_ld_GCJ='+b $libdir'
+ hardcode_direct_GCJ=no
+ hardcode_shlibpath_var_GCJ=no
+ ;;
+ *)
+ hardcode_direct_GCJ=yes
+ export_dynamic_flag_spec_GCJ='${wl}-E'
+
+ # hardcode_minus_L: Not really in the search PATH,
+ # but as the default location of the library.
+ hardcode_minus_L_GCJ=yes
+ ;;
+ esac
+ fi
+ ;;
+
+ irix5* | irix6* | nonstopux*)
+ if test "$GCC" = yes; then
+ archive_cmds_GCJ='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ else
+ archive_cmds_GCJ='$LD -shared $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ hardcode_libdir_flag_spec_ld_GCJ='-rpath $libdir'
+ fi
+ hardcode_libdir_flag_spec_GCJ='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator_GCJ=:
+ link_all_deplibs_GCJ=yes
+ ;;
+
+ netbsd*)
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ archive_cmds_GCJ='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out
+ else
+ archive_cmds_GCJ='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF
+ fi
+ hardcode_libdir_flag_spec_GCJ='-R$libdir'
+ hardcode_direct_GCJ=yes
+ hardcode_shlibpath_var_GCJ=no
+ ;;
+
+ newsos6)
+ archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_direct_GCJ=yes
+ hardcode_libdir_flag_spec_GCJ='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator_GCJ=:
+ hardcode_shlibpath_var_GCJ=no
+ ;;
+
+ openbsd*)
+ hardcode_direct_GCJ=yes
+ hardcode_shlibpath_var_GCJ=no
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ archive_cmds_GCJ='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_GCJ='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
+ hardcode_libdir_flag_spec_GCJ='${wl}-rpath,$libdir'
+ export_dynamic_flag_spec_GCJ='${wl}-E'
+ else
+ case $host_os in
+ openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*)
+ archive_cmds_GCJ='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_libdir_flag_spec_GCJ='-R$libdir'
+ ;;
+ *)
+ archive_cmds_GCJ='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+ hardcode_libdir_flag_spec_GCJ='${wl}-rpath,$libdir'
+ ;;
+ esac
+ fi
+ ;;
+
+ os2*)
+ hardcode_libdir_flag_spec_GCJ='-L$libdir'
+ hardcode_minus_L_GCJ=yes
+ allow_undefined_flag_GCJ=unsupported
+ archive_cmds_GCJ='$echo "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
+ old_archive_From_new_cmds_GCJ='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
+ ;;
+
+ osf3*)
+ if test "$GCC" = yes; then
+ allow_undefined_flag_GCJ=' ${wl}-expect_unresolved ${wl}\*'
+ archive_cmds_GCJ='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ else
+ allow_undefined_flag_GCJ=' -expect_unresolved \*'
+ archive_cmds_GCJ='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ fi
+ hardcode_libdir_flag_spec_GCJ='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator_GCJ=:
+ ;;
+
+ osf4* | osf5*) # as osf3* with the addition of -msym flag
+ if test "$GCC" = yes; then
+ allow_undefined_flag_GCJ=' ${wl}-expect_unresolved ${wl}\*'
+ archive_cmds_GCJ='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+ hardcode_libdir_flag_spec_GCJ='${wl}-rpath ${wl}$libdir'
+ else
+ allow_undefined_flag_GCJ=' -expect_unresolved \*'
+ archive_cmds_GCJ='$LD -shared${allow_undefined_flag} $libobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
+ archive_expsym_cmds_GCJ='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~
+ $LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verstring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp'
+
+ # Both c and cxx compiler support -rpath directly
+ hardcode_libdir_flag_spec_GCJ='-rpath $libdir'
+ fi
+ hardcode_libdir_separator_GCJ=:
+ ;;
+
+ solaris*)
+ no_undefined_flag_GCJ=' -z text'
+ if test "$GCC" = yes; then
+ wlarc='${wl}'
+ archive_cmds_GCJ='$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_GCJ='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$rm $lib.exp'
+ else
+ wlarc=''
+ archive_cmds_GCJ='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ archive_expsym_cmds_GCJ='$echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
+ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$rm $lib.exp'
+ fi
+ hardcode_libdir_flag_spec_GCJ='-R$libdir'
+ hardcode_shlibpath_var_GCJ=no
+ case $host_os in
+ solaris2.[0-5] | solaris2.[0-5].*) ;;
+ *)
+ # The compiler driver will combine linker options so we
+ # cannot just pass the convience library names through
+ # without $wl, iff we do not link with $LD.
+ # Luckily, gcc supports the same syntax we need for Sun Studio.
+ # Supported since Solaris 2.6 (maybe 2.5.1?)
+ case $wlarc in
+ '')
+ whole_archive_flag_spec_GCJ='-z allextract$convenience -z defaultextract' ;;
+ *)
+ whole_archive_flag_spec_GCJ='${wl}-z ${wl}allextract`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract' ;;
+ esac ;;
+ esac
+ link_all_deplibs_GCJ=yes
+ ;;
+
+ sunos4*)
+ if test "x$host_vendor" = xsequent; then
+ # Use $CC to link under sequent, because it throws in some extra .o
+ # files that make .init and .fini sections work.
+ archive_cmds_GCJ='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ archive_cmds_GCJ='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
+ fi
+ hardcode_libdir_flag_spec_GCJ='-L$libdir'
+ hardcode_direct_GCJ=yes
+ hardcode_minus_L_GCJ=yes
+ hardcode_shlibpath_var_GCJ=no
+ ;;
+
+ sysv4)
+ case $host_vendor in
+ sni)
+ archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_direct_GCJ=yes # is this really true???
+ ;;
+ siemens)
+ ## LD is ld it makes a PLAMLIB
+ ## CC just makes a GrossModule.
+ archive_cmds_GCJ='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+ reload_cmds_GCJ='$CC -r -o $output$reload_objs'
+ hardcode_direct_GCJ=no
+ ;;
+ motorola)
+ archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_direct_GCJ=no #Motorola manual says yes, but my tests say they lie
+ ;;
+ esac
+ runpath_var='LD_RUN_PATH'
+ hardcode_shlibpath_var_GCJ=no
+ ;;
+
+ sysv4.3*)
+ archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_shlibpath_var_GCJ=no
+ export_dynamic_flag_spec_GCJ='-Bexport'
+ ;;
+
+ sysv4*MP*)
+ if test -d /usr/nec; then
+ archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_shlibpath_var_GCJ=no
+ runpath_var=LD_RUN_PATH
+ hardcode_runpath_var=yes
+ ld_shlibs_GCJ=yes
+ fi
+ ;;
+
+ sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7*)
+ no_undefined_flag_GCJ='${wl}-z,text'
+ archive_cmds_need_lc_GCJ=no
+ hardcode_shlibpath_var_GCJ=no
+ runpath_var='LD_RUN_PATH'
+
+ if test "$GCC" = yes; then
+ archive_cmds_GCJ='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_GCJ='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ archive_cmds_GCJ='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_GCJ='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+ fi
+ ;;
+
+ sysv5* | sco3.2v5* | sco5v6*)
+ # Note: We can NOT use -z defs as we might desire, because we do not
+ # link with -lc, and that would cause any symbols used from libc to
+ # always be unresolved, which means just about no library would
+ # ever link correctly. If we're not using GNU ld we use -z text
+ # though, which does catch some bad symbols but isn't as heavy-handed
+ # as -z defs.
+ no_undefined_flag_GCJ='${wl}-z,text'
+ allow_undefined_flag_GCJ='${wl}-z,nodefs'
+ archive_cmds_need_lc_GCJ=no
+ hardcode_shlibpath_var_GCJ=no
+ hardcode_libdir_flag_spec_GCJ='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
+ hardcode_libdir_separator_GCJ=':'
+ link_all_deplibs_GCJ=yes
+ export_dynamic_flag_spec_GCJ='${wl}-Bexport'
+ runpath_var='LD_RUN_PATH'
+
+ if test "$GCC" = yes; then
+ archive_cmds_GCJ='$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_GCJ='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ else
+ archive_cmds_GCJ='$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ archive_expsym_cmds_GCJ='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
+ fi
+ ;;
+
+ uts4*)
+ archive_cmds_GCJ='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+ hardcode_libdir_flag_spec_GCJ='-L$libdir'
+ hardcode_shlibpath_var_GCJ=no
+ ;;
+
+ *)
+ ld_shlibs_GCJ=no
+ ;;
+ esac
+ fi
+
+echo "$as_me:$LINENO: result: $ld_shlibs_GCJ" >&5
+echo "${ECHO_T}$ld_shlibs_GCJ" >&6
+test "$ld_shlibs_GCJ" = no && can_build_shared=no
+
+#
+# Do we need to explicitly link libc?
+#
+case "x$archive_cmds_need_lc_GCJ" in
+x|xyes)
+ # Assume -lc should be added
+ archive_cmds_need_lc_GCJ=yes
+
+ if test "$enable_shared" = yes && test "$GCC" = yes; then
+ case $archive_cmds_GCJ in
+ *'~'*)
+ # FIXME: we may have to deal with multi-command sequences.
+ ;;
+ '$CC '*)
+ # Test whether the compiler implicitly links with -lc since on some
+ # systems, -lgcc has to come before -lc. If gcc already passes -lc
+ # to ld, don't add -lc before -lgcc.
+ echo "$as_me:$LINENO: checking whether -lc should be explicitly linked in" >&5
+echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO_C" >&6
+ $rm conftest*
+ printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } 2>conftest.err; then
+ soname=conftest
+ lib=conftest
+ libobjs=conftest.$ac_objext
+ deplibs=
+ wl=$lt_prog_compiler_wl_GCJ
+ pic_flag=$lt_prog_compiler_pic_GCJ
+ compiler_flags=-v
+ linker_flags=-v
+ verstring=
+ output_objdir=.
+ libname=conftest
+ lt_save_allow_undefined_flag=$allow_undefined_flag_GCJ
+ allow_undefined_flag_GCJ=
+ if { (eval echo "$as_me:$LINENO: \"$archive_cmds_GCJ 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1\"") >&5
+ (eval $archive_cmds_GCJ 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }
+ then
+ archive_cmds_need_lc_GCJ=no
+ else
+ archive_cmds_need_lc_GCJ=yes
+ fi
+ allow_undefined_flag_GCJ=$lt_save_allow_undefined_flag
+ else
+ cat conftest.err 1>&5
+ fi
+ $rm conftest*
+ echo "$as_me:$LINENO: result: $archive_cmds_need_lc_GCJ" >&5
+echo "${ECHO_T}$archive_cmds_need_lc_GCJ" >&6
+ ;;
+ esac
+ fi
+ ;;
+esac
+
+echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
+echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
+ # if the path contains ";" then we assume it to be the separator
+ # otherwise default to the standard path separator (i.e. ":") - it is
+ # assumed that no part of a normal pathname contains ";" but that should
+ # okay in the real world where ";" in dirpaths is itself problematic.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+else
+ sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+ shlibpath_var=LIBPATH
+
+ # AIX 3 has no versioning support, so we append a major version to the name.
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+
+aix4* | aix5*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ hardcode_into_libs=yes
+ if test "$host_cpu" = ia64; then
+ # AIX 5 supports IA64
+ library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ else
+ # With GCC up to 2.95.x, collect2 would create an import file
+ # for dependence libraries. The import file would start with
+ # the line `#! .'. This would cause the generated library to
+ # depend on `.', always an invalid library. This was fixed in
+ # development snapshots of GCC prior to 3.0.
+ case $host_os in
+ aix4 | aix4.[01] | aix4.[01].*)
+ if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+ echo ' yes '
+ echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
+ :
+ else
+ can_build_shared=no
+ fi
+ ;;
+ esac
+ # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+ # soname into executable. Probably we can add versioning support to
+ # collect2, so additional links can be useful in future.
+ if test "$aix_use_runtimelinking" = yes; then
+ # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+ # instead of lib<name>.a to let people know that these are not
+ # typical AIX shared libraries.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ else
+ # We preserve .a as extension for shared libraries through AIX4.2
+ # and later when we are not doing run time linking.
+ library_names_spec='${libname}${release}.a $libname.a'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ fi
+ shlibpath_var=LIBPATH
+ fi
+ ;;
+
+amigaos*)
+ library_names_spec='$libname.ixlibrary $libname.a'
+ # Create ${libname}_ixlibrary.a entries in /sys/libs.
+ finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+ ;;
+
+beos*)
+ library_names_spec='${libname}${shared_ext}'
+ dynamic_linker="$host_os ld.so"
+ shlibpath_var=LIBRARY_PATH
+ ;;
+
+bsdi[45]*)
+ version_type=linux
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+ sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+ # the default ld.so.conf also contains /usr/contrib/lib and
+ # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+ # libtool to hard-code these into programs
+ ;;
+
+cygwin* | mingw* | pw32*)
+ version_type=windows
+ shrext_cmds=".dll"
+ need_version=no
+ need_lib_prefix=no
+
+ case $GCC,$host_os in
+ yes,cygwin* | yes,mingw* | yes,pw32*)
+ library_names_spec='$libname.dll.a'
+ # DLL is installed to $(libdir)/../bin by postinstall_cmds
+ postinstall_cmds='base_file=`basename \${file}`~
+ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dlname'\''`~
+ dldir=$destdir/`dirname \$dlpath`~
+ test -d \$dldir || mkdir -p \$dldir~
+ $install_prog $dir/$dlname \$dldir/$dlname~
+ chmod a+x \$dldir/$dlname'
+ postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+ dlpath=$dir/\$dldll~
+ $rm \$dlpath'
+ shlibpath_overrides_runpath=yes
+
+ case $host_os in
+ cygwin*)
+ # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+ soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib"
+ ;;
+ mingw*)
+ # MinGW DLLs use traditional 'lib' prefix
+ soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ sys_lib_search_path_spec=`$CC -print-search-dirs | grep "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+ if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null; then
+ # It is most probably a Windows format PATH printed by
+ # mingw gcc, but we are running on Cygwin. Gcc prints its search
+ # path with ; separators, and with drive letters. We can handle the
+ # drive letters (cygwin fileutils understands them), so leave them,
+ # especially as we might pass files found there to a mingw objdump,
+ # which wouldn't understand a cygwinified path. Ahh.
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+ else
+ sys_lib_search_path_spec=`echo "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+ fi
+ ;;
+ pw32*)
+ # pw32 DLLs use 'pw' prefix rather than 'lib'
+ library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+ ;;
+ esac
+ ;;
+
+ *)
+ library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib'
+ ;;
+ esac
+ dynamic_linker='Win32 ld.exe'
+ # FIXME: first we should search . and the directory the executable is in
+ shlibpath_var=PATH
+ ;;
+
+darwin* | rhapsody*)
+ dynamic_linker="$host_os dyld"
+ version_type=darwin
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${versuffix}$shared_ext ${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+ soname_spec='${libname}${release}${major}$shared_ext'
+ shlibpath_overrides_runpath=yes
+ shlibpath_var=DYLD_LIBRARY_PATH
+ shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+ # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
+ if test "$GCC" = yes; then
+ sys_lib_search_path_spec=`$CC -print-search-dirs | tr "\n" "$PATH_SEPARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^libraries:" | sed -e "s/^libraries://" -e "s,=/,/,g" -e "s,$PATH_SEPARATOR, ,g" -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
+ else
+ sys_lib_search_path_spec='/lib /usr/lib /usr/local/lib'
+ fi
+ sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+ ;;
+
+dgux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+freebsd1*)
+ dynamic_linker=no
+ ;;
+
+kfreebsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+freebsd* | dragonfly*)
+ # DragonFly does not have aout. When/if they implement a new
+ # versioning mechanism, adjust this.
+ if test -x /usr/bin/objformat; then
+ objformat=`/usr/bin/objformat`
+ else
+ case $host_os in
+ freebsd[123]*) objformat=aout ;;
+ *) objformat=elf ;;
+ esac
+ fi
+ version_type=freebsd-$objformat
+ case $version_type in
+ freebsd-elf*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ need_version=no
+ need_lib_prefix=no
+ ;;
+ freebsd-*)
+ library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+ need_version=yes
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_os in
+ freebsd2*)
+ shlibpath_overrides_runpath=yes
+ ;;
+ freebsd3.[01]* | freebsdelf3.[01]*)
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
+ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+ freebsd*) # from 4.6 on
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+ esac
+ ;;
+
+gnu*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ ;;
+
+hpux9* | hpux10* | hpux11*)
+ # Give a soname corresponding to the major version so that dld.sl refuses to
+ # link against other versions.
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ case $host_cpu in
+ ia64*)
+ shrext_cmds='.so'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.so"
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ if test "X$HPUX_IA64_MODE" = X32; then
+ sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+ else
+ sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+ fi
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ hppa*64*)
+ shrext_cmds='.sl'
+ hardcode_into_libs=yes
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+ shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+ sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+ ;;
+ *)
+ shrext_cmds='.sl'
+ dynamic_linker="$host_os dld.sl"
+ shlibpath_var=SHLIB_PATH
+ shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ ;;
+ esac
+ # HP-UX runs *really* slowly unless shared libraries are mode 555.
+ postinstall_cmds='chmod 555 $lib'
+ ;;
+
+interix3*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ ;;
+
+irix5* | irix6* | nonstopux*)
+ case $host_os in
+ nonstopux*) version_type=nonstopux ;;
+ *)
+ if test "$lt_cv_prog_gnu_ld" = yes; then
+ version_type=linux
+ else
+ version_type=irix
+ fi ;;
+ esac
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+ case $host_os in
+ irix5* | nonstopux*)
+ libsuff= shlibsuff=
+ ;;
+ *)
+ case $LD in # libtool.m4 will add one of these switches to LD
+ *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+ libsuff= shlibsuff= libmagic=32-bit;;
+ *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+ libsuff=32 shlibsuff=N32 libmagic=N32;;
+ *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+ libsuff=64 shlibsuff=64 libmagic=64-bit;;
+ *) libsuff= shlibsuff= libmagic=never-match;;
+ esac
+ ;;
+ esac
+ shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+ sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+ hardcode_into_libs=yes
+ ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+ dynamic_linker=no
+ ;;
+
+# This must be Linux ELF.
+linux*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ # This implies no fast_install, which is unacceptable.
+ # Some rework will be needed to allow for fast_install
+ # before this can be enabled.
+ hardcode_into_libs=yes
+
+ # find out which ABI we are using
+ libsuff=
+ case "$host_cpu" in
+ x86_64*|s390x*|powerpc64*)
+ echo '#line 17657 "configure"' > conftest.$ac_ext
+ if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; then
+ case `/usr/bin/file conftest.$ac_objext` in
+ *64-bit*)
+ libsuff=64
+ sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}"
+ ;;
+ esac
+ fi
+ rm -rf conftest*
+ ;;
+ esac
+
+ # Append ld.so.conf contents to the search path
+ if test -f /etc/ld.so.conf; then
+ lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+ sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra"
+ fi
+
+ # We used to test for /lib/ld.so.1 and disable shared libraries on
+ # powerpc, because MkLinux only supported shared libraries with the
+ # GNU dynamic linker. Since this was broken with cross compilers,
+ # most powerpc-linux boxes support dynamic linking these days and
+ # people can always --disable-shared, the test was removed, and we
+ # assume the GNU/Linux dynamic linker is in use.
+ dynamic_linker='GNU/Linux ld.so'
+ ;;
+
+knetbsd*-gnu)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=no
+ hardcode_into_libs=yes
+ dynamic_linker='GNU ld.so'
+ ;;
+
+netbsd*)
+ version_type=sunos
+ need_lib_prefix=no
+ need_version=no
+ if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ dynamic_linker='NetBSD (a.out) ld.so'
+ else
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ dynamic_linker='NetBSD ld.elf_so'
+ fi
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ ;;
+
+newsos6)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+nto-qnx*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ ;;
+
+openbsd*)
+ version_type=sunos
+ sys_lib_dlsearch_path_spec="/usr/lib"
+ need_lib_prefix=no
+ # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+ case $host_os in
+ openbsd3.3 | openbsd3.3.*) need_version=yes ;;
+ *) need_version=no ;;
+ esac
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+ case $host_os in
+ openbsd2.[89] | openbsd2.[89].*)
+ shlibpath_overrides_runpath=no
+ ;;
+ *)
+ shlibpath_overrides_runpath=yes
+ ;;
+ esac
+ else
+ shlibpath_overrides_runpath=yes
+ fi
+ ;;
+
+os2*)
+ libname_spec='$name'
+ shrext_cmds=".dll"
+ need_lib_prefix=no
+ library_names_spec='$libname${shared_ext} $libname.a'
+ dynamic_linker='OS/2 ld.exe'
+ shlibpath_var=LIBPATH
+ ;;
+
+osf3* | osf4* | osf5*)
+ version_type=osf
+ need_lib_prefix=no
+ need_version=no
+ soname_spec='${libname}${release}${shared_ext}$major'
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ shlibpath_var=LD_LIBRARY_PATH
+ sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+ sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+ ;;
+
+solaris*)
+ version_type=linux
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ hardcode_into_libs=yes
+ # ldd complains unless libraries are executable
+ postinstall_cmds='chmod +x $lib'
+ ;;
+
+sunos4*)
+ version_type=sunos
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+ finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ shlibpath_overrides_runpath=yes
+ if test "$with_gnu_ld" = yes; then
+ need_lib_prefix=no
+ fi
+ need_version=yes
+ ;;
+
+sysv4 | sysv4.3*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ case $host_vendor in
+ sni)
+ shlibpath_overrides_runpath=no
+ need_lib_prefix=no
+ export_dynamic_flag_spec='${wl}-Blargedynsym'
+ runpath_var=LD_RUN_PATH
+ ;;
+ siemens)
+ need_lib_prefix=no
+ ;;
+ motorola)
+ need_lib_prefix=no
+ need_version=no
+ shlibpath_overrides_runpath=no
+ sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+ ;;
+ esac
+ ;;
+
+sysv4*MP*)
+ if test -d /usr/nec ;then
+ version_type=linux
+ library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+ soname_spec='$libname${shared_ext}.$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ fi
+ ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+ version_type=freebsd-elf
+ need_lib_prefix=no
+ need_version=no
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ hardcode_into_libs=yes
+ if test "$with_gnu_ld" = yes; then
+ sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+ shlibpath_overrides_runpath=no
+ else
+ sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+ shlibpath_overrides_runpath=yes
+ case $host_os in
+ sco3.2v5*)
+ sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+ ;;
+ esac
+ fi
+ sys_lib_dlsearch_path_spec='/usr/lib'
+ ;;
+
+uts4*)
+ version_type=linux
+ library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+ soname_spec='${libname}${release}${shared_ext}$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+*)
+ dynamic_linker=no
+ ;;
+esac
+echo "$as_me:$LINENO: result: $dynamic_linker" >&5
+echo "${ECHO_T}$dynamic_linker" >&6
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+ variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
+echo "$as_me:$LINENO: checking how to hardcode library paths into programs" >&5
+echo $ECHO_N "checking how to hardcode library paths into programs... $ECHO_C" >&6
+hardcode_action_GCJ=
+if test -n "$hardcode_libdir_flag_spec_GCJ" || \
+ test -n "$runpath_var_GCJ" || \
+ test "X$hardcode_automatic_GCJ" = "Xyes" ; then
+
+ # We can hardcode non-existant directories.
+ if test "$hardcode_direct_GCJ" != no &&
+ # If the only mechanism to avoid hardcoding is shlibpath_var, we
+ # have to relink, otherwise we might link with an installed library
+ # when we should be linking with a yet-to-be-installed one
+ ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, GCJ)" != no &&
+ test "$hardcode_minus_L_GCJ" != no; then
+ # Linking always hardcodes the temporary library directory.
+ hardcode_action_GCJ=relink
+ else
+ # We can link without hardcoding, and we can hardcode nonexisting dirs.
+ hardcode_action_GCJ=immediate
+ fi
+else
+ # We cannot hardcode anything, or else we can only hardcode existing
+ # directories.
+ hardcode_action_GCJ=unsupported
+fi
+echo "$as_me:$LINENO: result: $hardcode_action_GCJ" >&5
+echo "${ECHO_T}$hardcode_action_GCJ" >&6
+
+if test "$hardcode_action_GCJ" = relink; then
+ # Fast installation is not supported
+ enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+ test "$enable_shared" = no; then
+ # Fast installation is not necessary
+ enable_fast_install=needless
+fi
+
+
+# The else clause should only fire when bootstrapping the
+# libtool distribution, otherwise you forgot to ship ltmain.sh
+# with your package, and you will get complaints that there are
+# no rules to generate ltmain.sh.
+if test -f "$ltmain"; then
+ # See if we are running on zsh, and set the options which allow our commands through
+ # without removal of \ escapes.
+ if test -n "${ZSH_VERSION+set}" ; then
+ setopt NO_GLOB_SUBST
+ fi
+ # Now quote all the things that may contain metacharacters while being
+ # careful not to overquote the AC_SUBSTed values. We take copies of the
+ # variables and quote the copies for generation of the libtool script.
+ for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \
+ SED SHELL STRIP \
+ libname_spec library_names_spec soname_spec extract_expsyms_cmds \
+ old_striplib striplib file_magic_cmd finish_cmds finish_eval \
+ deplibs_check_method reload_flag reload_cmds need_locks \
+ lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
+ lt_cv_sys_global_symbol_to_c_name_address \
+ sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
+ old_postinstall_cmds old_postuninstall_cmds \
+ compiler_GCJ \
+ CC_GCJ \
+ LD_GCJ \
+ lt_prog_compiler_wl_GCJ \
+ lt_prog_compiler_pic_GCJ \
+ lt_prog_compiler_static_GCJ \
+ lt_prog_compiler_no_builtin_flag_GCJ \
+ export_dynamic_flag_spec_GCJ \
+ thread_safe_flag_spec_GCJ \
+ whole_archive_flag_spec_GCJ \
+ enable_shared_with_static_runtimes_GCJ \
+ old_archive_cmds_GCJ \
+ old_archive_from_new_cmds_GCJ \
+ predep_objects_GCJ \
+ postdep_objects_GCJ \
+ predeps_GCJ \
+ postdeps_GCJ \
+ compiler_lib_search_path_GCJ \
+ archive_cmds_GCJ \
+ archive_expsym_cmds_GCJ \
+ postinstall_cmds_GCJ \
+ postuninstall_cmds_GCJ \
+ old_archive_from_expsyms_cmds_GCJ \
+ allow_undefined_flag_GCJ \
+ no_undefined_flag_GCJ \
+ export_symbols_cmds_GCJ \
+ hardcode_libdir_flag_spec_GCJ \
+ hardcode_libdir_flag_spec_ld_GCJ \
+ hardcode_libdir_separator_GCJ \
+ hardcode_automatic_GCJ \
+ module_cmds_GCJ \
+ module_expsym_cmds_GCJ \
+ lt_cv_prog_compiler_c_o_GCJ \
+ exclude_expsyms_GCJ \
+ include_expsyms_GCJ; do
+
+ case $var in
+ old_archive_cmds_GCJ | \
+ old_archive_from_new_cmds_GCJ | \
+ archive_cmds_GCJ | \
+ archive_expsym_cmds_GCJ | \
+ module_cmds_GCJ | \
+ module_expsym_cmds_GCJ | \
+ old_archive_from_expsyms_cmds_GCJ | \
+ export_symbols_cmds_GCJ | \
+ extract_expsyms_cmds | reload_cmds | finish_cmds | \
+ postinstall_cmds | postuninstall_cmds | \
+ old_postinstall_cmds | old_postuninstall_cmds | \
+ sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
+ # Double-quote double-evaled strings.
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
+ ;;
+ *)
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\""
+ ;;
+ esac
+ done
+
+ case $lt_echo in
+ *'\$0 --fallback-echo"')
+ lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'`
+ ;;
+ esac
+
+cfgfile="$ofile"
+
+ cat <<__EOF__ >> "$cfgfile"
+# ### BEGIN LIBTOOL TAG CONFIG: $tagname
+
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+
+# Shell to use when invoking shell scripts.
+SHELL=$lt_SHELL
+
+# Whether or not to build shared libraries.
+build_libtool_libs=$enable_shared
+
+# Whether or not to build static libraries.
+build_old_libs=$enable_static
+
+# Whether or not to add -lc for building shared libraries.
+build_libtool_need_lc=$archive_cmds_need_lc_GCJ
+
+# Whether or not to disallow shared libs when runtime libs are static
+allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_GCJ
+
+# Whether or not to optimize for fast installation.
+fast_install=$enable_fast_install
+
+# The host system.
+host_alias=$host_alias
+host=$host
+host_os=$host_os
+
+# The build system.
+build_alias=$build_alias
+build=$build
+build_os=$build_os
+
+# An echo program that does not interpret backslashes.
+echo=$lt_echo
+
+# The archiver.
+AR=$lt_AR
+AR_FLAGS=$lt_AR_FLAGS
+
+# A C compiler.
+LTCC=$lt_LTCC
+
+# LTCC compiler flags.
+LTCFLAGS=$lt_LTCFLAGS
+
+# A language-specific compiler.
+CC=$lt_compiler_GCJ
+
+# Is the compiler the GNU C compiler?
+with_gcc=$GCC_GCJ
+
+gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\`
+gcc_ver=\`gcc -dumpversion\`
+
+# An ERE matcher.
+EGREP=$lt_EGREP
+
+# The linker used to build libraries.
+LD=$lt_LD_GCJ
+
+# Whether we need hard or soft links.
+LN_S=$lt_LN_S
+
+# A BSD-compatible nm program.
+NM=$lt_NM
+
+# A symbol stripping program
+STRIP=$lt_STRIP
+
+# Used to examine libraries when file_magic_cmd begins "file"
+MAGIC_CMD=$MAGIC_CMD
+
+# Used on cygwin: DLL creation program.
+DLLTOOL="$DLLTOOL"
+
+# Used on cygwin: object dumper.
+OBJDUMP="$OBJDUMP"
+
+# Used on cygwin: assembler.
+AS="$AS"
+
+# The name of the directory that contains temporary libtool files.
+objdir=$objdir
+
+# How to create reloadable object files.
+reload_flag=$lt_reload_flag
+reload_cmds=$lt_reload_cmds
+
+# How to pass a linker flag through the compiler.
+wl=$lt_lt_prog_compiler_wl_GCJ
+
+# Object file suffix (normally "o").
+objext="$ac_objext"
+
+# Old archive suffix (normally "a").
+libext="$libext"
+
+# Shared library suffix (normally ".so").
+shrext_cmds='$shrext_cmds'
+
+# Executable file suffix (normally "").
+exeext="$exeext"
+
+# Additional compiler flags for building library objects.
+pic_flag=$lt_lt_prog_compiler_pic_GCJ
+pic_mode=$pic_mode
+
+# What is the maximum length of a command?
+max_cmd_len=$lt_cv_sys_max_cmd_len
+
+# Does compiler simultaneously support -c and -o options?
+compiler_c_o=$lt_lt_cv_prog_compiler_c_o_GCJ
+
+# Must we lock files when doing compilation?
+need_locks=$lt_need_locks
+
+# Do we need the lib prefix for modules?
+need_lib_prefix=$need_lib_prefix
+
+# Do we need a version for libraries?
+need_version=$need_version
+
+# Whether dlopen is supported.
+dlopen_support=$enable_dlopen
+
+# Whether dlopen of programs is supported.
+dlopen_self=$enable_dlopen_self
+
+# Whether dlopen of statically linked programs is supported.
+dlopen_self_static=$enable_dlopen_self_static
+
+# Compiler flag to prevent dynamic linking.
+link_static_flag=$lt_lt_prog_compiler_static_GCJ
+
+# Compiler flag to turn off builtin functions.
+no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_GCJ
+
+# Compiler flag to allow reflexive dlopens.
+export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_GCJ
+
+# Compiler flag to generate shared objects directly from archives.
+whole_archive_flag_spec=$lt_whole_archive_flag_spec_GCJ
+
+# Compiler flag to generate thread-safe objects.
+thread_safe_flag_spec=$lt_thread_safe_flag_spec_GCJ
+
+# Library versioning type.
+version_type=$version_type
+
+# Format of library name prefix.
+libname_spec=$lt_libname_spec
+
+# List of archive names. First name is the real one, the rest are links.
+# The last name is the one that the linker finds with -lNAME.
+library_names_spec=$lt_library_names_spec
+
+# The coded name of the library, if different from the real name.
+soname_spec=$lt_soname_spec
+
+# Commands used to build and install an old-style archive.
+RANLIB=$lt_RANLIB
+old_archive_cmds=$lt_old_archive_cmds_GCJ
+old_postinstall_cmds=$lt_old_postinstall_cmds
+old_postuninstall_cmds=$lt_old_postuninstall_cmds
+
+# Create an old-style archive from a shared archive.
+old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_GCJ
+
+# Create a temporary old-style archive to link instead of a shared archive.
+old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_GCJ
+
+# Commands used to build and install a shared archive.
+archive_cmds=$lt_archive_cmds_GCJ
+archive_expsym_cmds=$lt_archive_expsym_cmds_GCJ
+postinstall_cmds=$lt_postinstall_cmds
+postuninstall_cmds=$lt_postuninstall_cmds
+
+# Commands used to build a loadable module (assumed same as above if empty)
+module_cmds=$lt_module_cmds_GCJ
+module_expsym_cmds=$lt_module_expsym_cmds_GCJ
+
+# Commands to strip libraries.
+old_striplib=$lt_old_striplib
+striplib=$lt_striplib
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predep_objects=\`echo $lt_predep_objects_GCJ | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdep_objects=\`echo $lt_postdep_objects_GCJ | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predeps=$lt_predeps_GCJ
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdeps=$lt_postdeps_GCJ
+
+# The library search path used internally by the compiler when linking
+# a shared library.
+compiler_lib_search_path=\`echo $lt_compiler_lib_search_path_GCJ | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Method to check whether dependent libraries are shared objects.
+deplibs_check_method=$lt_deplibs_check_method
+
+# Command to use when deplibs_check_method == file_magic.
+file_magic_cmd=$lt_file_magic_cmd
+
+# Flag that allows shared libraries with undefined symbols to be built.
+allow_undefined_flag=$lt_allow_undefined_flag_GCJ
+
+# Flag that forces no undefined symbols.
+no_undefined_flag=$lt_no_undefined_flag_GCJ
+
+# Commands used to finish a libtool library installation in a directory.
+finish_cmds=$lt_finish_cmds
+
+# Same as above, but a single script fragment to be evaled but not shown.
+finish_eval=$lt_finish_eval
+
+# Take the output of nm and produce a listing of raw symbols and C names.
+global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
+
+# Transform the output of nm in a proper C declaration
+global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
+
+# Transform the output of nm in a C name address pair
+global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address
+
+# This is the shared library runtime path variable.
+runpath_var=$runpath_var
+
+# This is the shared library path variable.
+shlibpath_var=$shlibpath_var
+
+# Is shlibpath searched before the hard-coded library search path?
+shlibpath_overrides_runpath=$shlibpath_overrides_runpath
+
+# How to hardcode a shared library path into an executable.
+hardcode_action=$hardcode_action_GCJ
+
+# Whether we should hardcode library paths into libraries.
+hardcode_into_libs=$hardcode_into_libs
+
+# Flag to hardcode \$libdir into a binary during linking.
+# This must work even if \$libdir does not exist.
+hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_GCJ
+
+# If ld is used when linking, flag to hardcode \$libdir into
+# a binary during linking. This must work even if \$libdir does
+# not exist.
+hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_GCJ
+
+# Whether we need a single -rpath flag with a separated argument.
+hardcode_libdir_separator=$lt_hardcode_libdir_separator_GCJ
+
+# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the
+# resulting binary.
+hardcode_direct=$hardcode_direct_GCJ
+
+# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
+# resulting binary.
+hardcode_minus_L=$hardcode_minus_L_GCJ
+
+# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into
+# the resulting binary.
+hardcode_shlibpath_var=$hardcode_shlibpath_var_GCJ
+
+# Set to yes if building a shared library automatically hardcodes DIR into the library
+# and all subsequent libraries and executables linked against it.
+hardcode_automatic=$hardcode_automatic_GCJ
+
+# Variables whose values should be saved in libtool wrapper scripts and
+# restored at relink time.
+variables_saved_for_relink="$variables_saved_for_relink"
+
+# Whether libtool must link a program against all its dependency libraries.
+link_all_deplibs=$link_all_deplibs_GCJ
+
+# Compile-time system search path for libraries
+sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Run-time system search path for libraries
+sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec
+
+# Fix the shell variable \$srcfile for the compiler.
+fix_srcfile_path="$fix_srcfile_path_GCJ"
+
+# Set to yes if exported symbols are required.
+always_export_symbols=$always_export_symbols_GCJ
+
+# The commands to list exported symbols.
+export_symbols_cmds=$lt_export_symbols_cmds_GCJ
+
+# The commands to extract the exported symbol list from a shared archive.
+extract_expsyms_cmds=$lt_extract_expsyms_cmds
+
+# Symbols that should not be listed in the preloaded symbols.
+exclude_expsyms=$lt_exclude_expsyms_GCJ
+
+# Symbols that must always be exported.
+include_expsyms=$lt_include_expsyms_GCJ
+
+# ### END LIBTOOL TAG CONFIG: $tagname
+
+__EOF__
+
+
+else
+ # If there is no Makefile yet, we rely on a make rule to execute
+ # `config.status --recheck' to rerun these tests and create the
+ # libtool script then.
+ ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'`
+ if test -f "$ltmain_in"; then
+ test -f Makefile && make "$ltmain"
+ fi
+fi
+
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+CC="$lt_save_CC"
+
+ else
+ tagname=""
+ fi
+ ;;
+
+ RC)
+
+
+
+# Source file extension for RC test sources.
+ac_ext=rc
+
+# Object file extension for compiled RC test sources.
+objext=o
+objext_RC=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }\n'
+
+# Code to be used in simple link tests
+lt_simple_link_test_code="$lt_simple_compile_test_code"
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+
+
+# save warnings/boilerplate of simple test code
+ac_outfile=conftest.$ac_objext
+printf "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$rm conftest*
+
+ac_outfile=conftest.$ac_objext
+printf "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$rm conftest*
+
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+CC=${RC-"windres"}
+compiler=$CC
+compiler_RC=$CC
+for cc_temp in $compiler""; do
+ case $cc_temp in
+ compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
+ distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
+ \-*) ;;
+ *) break;;
+ esac
+done
+cc_basename=`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+
+lt_cv_prog_compiler_c_o_RC=yes
+
+# The else clause should only fire when bootstrapping the
+# libtool distribution, otherwise you forgot to ship ltmain.sh
+# with your package, and you will get complaints that there are
+# no rules to generate ltmain.sh.
+if test -f "$ltmain"; then
+ # See if we are running on zsh, and set the options which allow our commands through
+ # without removal of \ escapes.
+ if test -n "${ZSH_VERSION+set}" ; then
+ setopt NO_GLOB_SUBST
+ fi
+ # Now quote all the things that may contain metacharacters while being
+ # careful not to overquote the AC_SUBSTed values. We take copies of the
+ # variables and quote the copies for generation of the libtool script.
+ for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTCFLAGS NM \
+ SED SHELL STRIP \
+ libname_spec library_names_spec soname_spec extract_expsyms_cmds \
+ old_striplib striplib file_magic_cmd finish_cmds finish_eval \
+ deplibs_check_method reload_flag reload_cmds need_locks \
+ lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
+ lt_cv_sys_global_symbol_to_c_name_address \
+ sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
+ old_postinstall_cmds old_postuninstall_cmds \
+ compiler_RC \
+ CC_RC \
+ LD_RC \
+ lt_prog_compiler_wl_RC \
+ lt_prog_compiler_pic_RC \
+ lt_prog_compiler_static_RC \
+ lt_prog_compiler_no_builtin_flag_RC \
+ export_dynamic_flag_spec_RC \
+ thread_safe_flag_spec_RC \
+ whole_archive_flag_spec_RC \
+ enable_shared_with_static_runtimes_RC \
+ old_archive_cmds_RC \
+ old_archive_from_new_cmds_RC \
+ predep_objects_RC \
+ postdep_objects_RC \
+ predeps_RC \
+ postdeps_RC \
+ compiler_lib_search_path_RC \
+ archive_cmds_RC \
+ archive_expsym_cmds_RC \
+ postinstall_cmds_RC \
+ postuninstall_cmds_RC \
+ old_archive_from_expsyms_cmds_RC \
+ allow_undefined_flag_RC \
+ no_undefined_flag_RC \
+ export_symbols_cmds_RC \
+ hardcode_libdir_flag_spec_RC \
+ hardcode_libdir_flag_spec_ld_RC \
+ hardcode_libdir_separator_RC \
+ hardcode_automatic_RC \
+ module_cmds_RC \
+ module_expsym_cmds_RC \
+ lt_cv_prog_compiler_c_o_RC \
+ exclude_expsyms_RC \
+ include_expsyms_RC; do
+
+ case $var in
+ old_archive_cmds_RC | \
+ old_archive_from_new_cmds_RC | \
+ archive_cmds_RC | \
+ archive_expsym_cmds_RC | \
+ module_cmds_RC | \
+ module_expsym_cmds_RC | \
+ old_archive_from_expsyms_cmds_RC | \
+ export_symbols_cmds_RC | \
+ extract_expsyms_cmds | reload_cmds | finish_cmds | \
+ postinstall_cmds | postuninstall_cmds | \
+ old_postinstall_cmds | old_postuninstall_cmds | \
+ sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
+ # Double-quote double-evaled strings.
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
+ ;;
+ *)
+ eval "lt_$var=\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`\\\""
+ ;;
+ esac
+ done
+
+ case $lt_echo in
+ *'\$0 --fallback-echo"')
+ lt_echo=`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$/$0 --fallback-echo"/'`
+ ;;
+ esac
+
+cfgfile="$ofile"
+
+ cat <<__EOF__ >> "$cfgfile"
+# ### BEGIN LIBTOOL TAG CONFIG: $tagname
+
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+
+# Shell to use when invoking shell scripts.
+SHELL=$lt_SHELL
+
+# Whether or not to build shared libraries.
+build_libtool_libs=$enable_shared
+
+# Whether or not to build static libraries.
+build_old_libs=$enable_static
+
+# Whether or not to add -lc for building shared libraries.
+build_libtool_need_lc=$archive_cmds_need_lc_RC
+
+# Whether or not to disallow shared libs when runtime libs are static
+allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_RC
+
+# Whether or not to optimize for fast installation.
+fast_install=$enable_fast_install
+
+# The host system.
+host_alias=$host_alias
+host=$host
+host_os=$host_os
+
+# The build system.
+build_alias=$build_alias
+build=$build
+build_os=$build_os
+
+# An echo program that does not interpret backslashes.
+echo=$lt_echo
+
+# The archiver.
+AR=$lt_AR
+AR_FLAGS=$lt_AR_FLAGS
+
+# A C compiler.
+LTCC=$lt_LTCC
+
+# LTCC compiler flags.
+LTCFLAGS=$lt_LTCFLAGS
+
+# A language-specific compiler.
+CC=$lt_compiler_RC
+
+# Is the compiler the GNU C compiler?
+with_gcc=$GCC_RC
+
+gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\`
+gcc_ver=\`gcc -dumpversion\`
+
+# An ERE matcher.
+EGREP=$lt_EGREP
+
+# The linker used to build libraries.
+LD=$lt_LD_RC
+
+# Whether we need hard or soft links.
+LN_S=$lt_LN_S
+
+# A BSD-compatible nm program.
+NM=$lt_NM
+
+# A symbol stripping program
+STRIP=$lt_STRIP
+
+# Used to examine libraries when file_magic_cmd begins "file"
+MAGIC_CMD=$MAGIC_CMD
+
+# Used on cygwin: DLL creation program.
+DLLTOOL="$DLLTOOL"
+
+# Used on cygwin: object dumper.
+OBJDUMP="$OBJDUMP"
+
+# Used on cygwin: assembler.
+AS="$AS"
+
+# The name of the directory that contains temporary libtool files.
+objdir=$objdir
+
+# How to create reloadable object files.
+reload_flag=$lt_reload_flag
+reload_cmds=$lt_reload_cmds
+
+# How to pass a linker flag through the compiler.
+wl=$lt_lt_prog_compiler_wl_RC
+
+# Object file suffix (normally "o").
+objext="$ac_objext"
+
+# Old archive suffix (normally "a").
+libext="$libext"
+
+# Shared library suffix (normally ".so").
+shrext_cmds='$shrext_cmds'
+
+# Executable file suffix (normally "").
+exeext="$exeext"
+
+# Additional compiler flags for building library objects.
+pic_flag=$lt_lt_prog_compiler_pic_RC
+pic_mode=$pic_mode
+
+# What is the maximum length of a command?
+max_cmd_len=$lt_cv_sys_max_cmd_len
+
+# Does compiler simultaneously support -c and -o options?
+compiler_c_o=$lt_lt_cv_prog_compiler_c_o_RC
+
+# Must we lock files when doing compilation?
+need_locks=$lt_need_locks
+
+# Do we need the lib prefix for modules?
+need_lib_prefix=$need_lib_prefix
+
+# Do we need a version for libraries?
+need_version=$need_version
+
+# Whether dlopen is supported.
+dlopen_support=$enable_dlopen
+
+# Whether dlopen of programs is supported.
+dlopen_self=$enable_dlopen_self
+
+# Whether dlopen of statically linked programs is supported.
+dlopen_self_static=$enable_dlopen_self_static
+
+# Compiler flag to prevent dynamic linking.
+link_static_flag=$lt_lt_prog_compiler_static_RC
+
+# Compiler flag to turn off builtin functions.
+no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_RC
+
+# Compiler flag to allow reflexive dlopens.
+export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_RC
+
+# Compiler flag to generate shared objects directly from archives.
+whole_archive_flag_spec=$lt_whole_archive_flag_spec_RC
+
+# Compiler flag to generate thread-safe objects.
+thread_safe_flag_spec=$lt_thread_safe_flag_spec_RC
+
+# Library versioning type.
+version_type=$version_type
+
+# Format of library name prefix.
+libname_spec=$lt_libname_spec
+
+# List of archive names. First name is the real one, the rest are links.
+# The last name is the one that the linker finds with -lNAME.
+library_names_spec=$lt_library_names_spec
+
+# The coded name of the library, if different from the real name.
+soname_spec=$lt_soname_spec
+
+# Commands used to build and install an old-style archive.
+RANLIB=$lt_RANLIB
+old_archive_cmds=$lt_old_archive_cmds_RC
+old_postinstall_cmds=$lt_old_postinstall_cmds
+old_postuninstall_cmds=$lt_old_postuninstall_cmds
+
+# Create an old-style archive from a shared archive.
+old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_RC
+
+# Create a temporary old-style archive to link instead of a shared archive.
+old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_RC
+
+# Commands used to build and install a shared archive.
+archive_cmds=$lt_archive_cmds_RC
+archive_expsym_cmds=$lt_archive_expsym_cmds_RC
+postinstall_cmds=$lt_postinstall_cmds
+postuninstall_cmds=$lt_postuninstall_cmds
+
+# Commands used to build a loadable module (assumed same as above if empty)
+module_cmds=$lt_module_cmds_RC
+module_expsym_cmds=$lt_module_expsym_cmds_RC
+
+# Commands to strip libraries.
+old_striplib=$lt_old_striplib
+striplib=$lt_striplib
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predep_objects=\`echo $lt_predep_objects_RC | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdep_objects=\`echo $lt_postdep_objects_RC | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Dependencies to place before the objects being linked to create a
+# shared library.
+predeps=$lt_predeps_RC
+
+# Dependencies to place after the objects being linked to create a
+# shared library.
+postdeps=$lt_postdeps_RC
+
+# The library search path used internally by the compiler when linking
+# a shared library.
+compiler_lib_search_path=\`echo $lt_compiler_lib_search_path_RC | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Method to check whether dependent libraries are shared objects.
+deplibs_check_method=$lt_deplibs_check_method
+
+# Command to use when deplibs_check_method == file_magic.
+file_magic_cmd=$lt_file_magic_cmd
+
+# Flag that allows shared libraries with undefined symbols to be built.
+allow_undefined_flag=$lt_allow_undefined_flag_RC
+
+# Flag that forces no undefined symbols.
+no_undefined_flag=$lt_no_undefined_flag_RC
+
+# Commands used to finish a libtool library installation in a directory.
+finish_cmds=$lt_finish_cmds
+
+# Same as above, but a single script fragment to be evaled but not shown.
+finish_eval=$lt_finish_eval
+
+# Take the output of nm and produce a listing of raw symbols and C names.
+global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
+
+# Transform the output of nm in a proper C declaration
+global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
+
+# Transform the output of nm in a C name address pair
+global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address
+
+# This is the shared library runtime path variable.
+runpath_var=$runpath_var
+
+# This is the shared library path variable.
+shlibpath_var=$shlibpath_var
+
+# Is shlibpath searched before the hard-coded library search path?
+shlibpath_overrides_runpath=$shlibpath_overrides_runpath
+
+# How to hardcode a shared library path into an executable.
+hardcode_action=$hardcode_action_RC
+
+# Whether we should hardcode library paths into libraries.
+hardcode_into_libs=$hardcode_into_libs
+
+# Flag to hardcode \$libdir into a binary during linking.
+# This must work even if \$libdir does not exist.
+hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_RC
+
+# If ld is used when linking, flag to hardcode \$libdir into
+# a binary during linking. This must work even if \$libdir does
+# not exist.
+hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld_RC
+
+# Whether we need a single -rpath flag with a separated argument.
+hardcode_libdir_separator=$lt_hardcode_libdir_separator_RC
+
+# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the
+# resulting binary.
+hardcode_direct=$hardcode_direct_RC
+
+# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
+# resulting binary.
+hardcode_minus_L=$hardcode_minus_L_RC
+
+# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into
+# the resulting binary.
+hardcode_shlibpath_var=$hardcode_shlibpath_var_RC
+
+# Set to yes if building a shared library automatically hardcodes DIR into the library
+# and all subsequent libraries and executables linked against it.
+hardcode_automatic=$hardcode_automatic_RC
+
+# Variables whose values should be saved in libtool wrapper scripts and
+# restored at relink time.
+variables_saved_for_relink="$variables_saved_for_relink"
+
+# Whether libtool must link a program against all its dependency libraries.
+link_all_deplibs=$link_all_deplibs_RC
+
+# Compile-time system search path for libraries
+sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\`
+
+# Run-time system search path for libraries
+sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec
+
+# Fix the shell variable \$srcfile for the compiler.
+fix_srcfile_path="$fix_srcfile_path_RC"
+
+# Set to yes if exported symbols are required.
+always_export_symbols=$always_export_symbols_RC
+
+# The commands to list exported symbols.
+export_symbols_cmds=$lt_export_symbols_cmds_RC
+
+# The commands to extract the exported symbol list from a shared archive.
+extract_expsyms_cmds=$lt_extract_expsyms_cmds
+
+# Symbols that should not be listed in the preloaded symbols.
+exclude_expsyms=$lt_exclude_expsyms_RC
+
+# Symbols that must always be exported.
+include_expsyms=$lt_include_expsyms_RC
+
+# ### END LIBTOOL TAG CONFIG: $tagname
+
+__EOF__
+
+
+else
+ # If there is no Makefile yet, we rely on a make rule to execute
+ # `config.status --recheck' to rerun these tests and create the
+ # libtool script then.
+ ltmain_in=`echo $ltmain | sed -e 's/\.sh$/.in/'`
+ if test -f "$ltmain_in"; then
+ test -f Makefile && make "$ltmain"
+ fi
+fi
+
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+CC="$lt_save_CC"
+
+ ;;
+
+ *)
+ { { echo "$as_me:$LINENO: error: Unsupported tag name: $tagname" >&5
+echo "$as_me: error: Unsupported tag name: $tagname" >&2;}
+ { (exit 1); exit 1; }; }
+ ;;
+ esac
+
+ # Append the new tag name to the list of available tags.
+ if test -n "$tagname" ; then
+ available_tags="$available_tags $tagname"
+ fi
+ fi
+ done
+ IFS="$lt_save_ifs"
+
+ # Now substitute the updated list of available tags.
+ if eval "sed -e 's/^available_tags=.*\$/available_tags=\"$available_tags\"/' \"$ofile\" > \"${ofile}T\""; then
+ mv "${ofile}T" "$ofile"
+ chmod +x "$ofile"
+ else
+ rm -f "${ofile}T"
+ { { echo "$as_me:$LINENO: error: unable to update list of available tagged configurations." >&5
+echo "$as_me: error: unable to update list of available tagged configurations." >&2;}
+ { (exit 1); exit 1; }; }
+ fi
+fi
+
+
+
+# This can be used to rebuild libtool when needed
+LIBTOOL_DEPS="$ac_aux_dir/ltmain.sh"
+
+# Always use our own libtool.
+LIBTOOL='$(SHELL) $(top_builddir)/libtool'
+
+# Prevent multiple expansion
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+echo "$as_me:$LINENO: checking for X" >&5
+echo $ECHO_N "checking for X... $ECHO_C" >&6
+
+
+# Check whether --with-x or --without-x was given.
+if test "${with_x+set}" = set; then
+ withval="$with_x"
+
+fi;
+# $have_x is `yes', `no', `disabled', or empty when we do not yet know.
+if test "x$with_x" = xno; then
+ # The user explicitly disabled X.
+ have_x=disabled
+else
+ if test "x$x_includes" != xNONE && test "x$x_libraries" != xNONE; then
+ # Both variables are already set.
+ have_x=yes
+ else
+ if test "${ac_cv_have_x+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ # One or both of the vars are not set, and there is no cached value.
+ac_x_includes=no ac_x_libraries=no
+rm -fr conftest.dir
+if mkdir conftest.dir; then
+ cd conftest.dir
+ # Make sure to not put "make" in the Imakefile rules, since we grep it out.
+ cat >Imakefile <<'_ACEOF'
+acfindx:
+ @echo 'ac_im_incroot="${INCROOT}"; ac_im_usrlibdir="${USRLIBDIR}"; ac_im_libdir="${LIBDIR}"'
+_ACEOF
+ if (xmkmf) >/dev/null 2>/dev/null && test -f Makefile; then
+ # GNU make sometimes prints "make[1]: Entering...", which would confuse us.
+ eval `${MAKE-make} acfindx 2>/dev/null | grep -v make`
+ # Open Windows xmkmf reportedly sets LIBDIR instead of USRLIBDIR.
+ for ac_extension in a so sl; do
+ if test ! -f $ac_im_usrlibdir/libX11.$ac_extension &&
+ test -f $ac_im_libdir/libX11.$ac_extension; then
+ ac_im_usrlibdir=$ac_im_libdir; break
+ fi
+ done
+ # Screen out bogus values from the imake configuration. They are
+ # bogus both because they are the default anyway, and because
+ # using them would break gcc on systems where it needs fixed includes.
+ case $ac_im_incroot in
+ /usr/include) ;;
+ *) test -f "$ac_im_incroot/X11/Xos.h" && ac_x_includes=$ac_im_incroot;;
+ esac
+ case $ac_im_usrlibdir in
+ /usr/lib | /lib) ;;
+ *) test -d "$ac_im_usrlibdir" && ac_x_libraries=$ac_im_usrlibdir ;;
+ esac
+ fi
+ cd ..
+ rm -fr conftest.dir
+fi
+
+# Standard set of common directories for X headers.
+# Check X11 before X11Rn because it is often a symlink to the current release.
+ac_x_header_dirs='
+/usr/X11/include
+/usr/X11R6/include
+/usr/X11R5/include
+/usr/X11R4/include
+
+/usr/include/X11
+/usr/include/X11R6
+/usr/include/X11R5
+/usr/include/X11R4
+
+/usr/local/X11/include
+/usr/local/X11R6/include
+/usr/local/X11R5/include
+/usr/local/X11R4/include
+
+/usr/local/include/X11
+/usr/local/include/X11R6
+/usr/local/include/X11R5
+/usr/local/include/X11R4
+
+/usr/X386/include
+/usr/x386/include
+/usr/XFree86/include/X11
+
+/usr/include
+/usr/local/include
+/usr/unsupported/include
+/usr/athena/include
+/usr/local/x11r5/include
+/usr/lpp/Xamples/include
+
+/usr/openwin/include
+/usr/openwin/share/include'
+
+if test "$ac_x_includes" = no; then
+ # Guess where to find include files, by looking for Xlib.h.
+ # First, try using that file with no special directory specified.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <X11/Xlib.h>
+_ACEOF
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+ (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ # We can compile using X headers with no special include directory.
+ac_x_includes=
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ for ac_dir in $ac_x_header_dirs; do
+ if test -r "$ac_dir/X11/Xlib.h"; then
+ ac_x_includes=$ac_dir
+ break
+ fi
+done
+fi
+rm -f conftest.err conftest.$ac_ext
+fi # $ac_x_includes = no
+
+if test "$ac_x_libraries" = no; then
+ # Check for the libraries.
+ # See if we find them without any special options.
+ # Don't add to $LIBS permanently.
+ ac_save_LIBS=$LIBS
+ LIBS="-lX11 $LIBS"
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <X11/Xlib.h>
+int
+main ()
+{
+XrmInitialize ()
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ LIBS=$ac_save_LIBS
+# We can link X programs with no special library path.
+ac_x_libraries=
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+LIBS=$ac_save_LIBS
+for ac_dir in `echo "$ac_x_includes $ac_x_header_dirs" | sed s/include/lib/g`
+do
+ # Don't even attempt the hair of trying to link an X program!
+ for ac_extension in a so sl; do
+ if test -r $ac_dir/libXt.$ac_extension; then
+ ac_x_libraries=$ac_dir
+ break 2
+ fi
+ done
+done
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi # $ac_x_libraries = no
+
+if test "$ac_x_includes" = no || test "$ac_x_libraries" = no; then
+ # Didn't find X anywhere. Cache the known absence of X.
+ ac_cv_have_x="have_x=no"
+else
+ # Record where we found X for the cache.
+ ac_cv_have_x="have_x=yes \
+ ac_x_includes=$ac_x_includes ac_x_libraries=$ac_x_libraries"
+fi
+fi
+
+ fi
+ eval "$ac_cv_have_x"
+fi # $with_x != no
+
+if test "$have_x" != yes; then
+ echo "$as_me:$LINENO: result: $have_x" >&5
+echo "${ECHO_T}$have_x" >&6
+ no_x=yes
+else
+ # If each of the values was on the command line, it overrides each guess.
+ test "x$x_includes" = xNONE && x_includes=$ac_x_includes
+ test "x$x_libraries" = xNONE && x_libraries=$ac_x_libraries
+ # Update the cache value to reflect the command line values.
+ ac_cv_have_x="have_x=yes \
+ ac_x_includes=$x_includes ac_x_libraries=$x_libraries"
+ echo "$as_me:$LINENO: result: libraries $x_libraries, headers $x_includes" >&5
+echo "${ECHO_T}libraries $x_libraries, headers $x_includes" >&6
+fi
+
+if test "$no_x" = yes; then
+ # Not all programs may use this symbol, but it does not hurt to define it.
+
+cat >>confdefs.h <<\_ACEOF
+#define X_DISPLAY_MISSING 1
+_ACEOF
+
+ X_CFLAGS= X_PRE_LIBS= X_LIBS= X_EXTRA_LIBS=
+else
+ if test -n "$x_includes"; then
+ X_CFLAGS="$X_CFLAGS -I$x_includes"
+ fi
+
+ # It would also be nice to do this for all -L options, not just this one.
+ if test -n "$x_libraries"; then
+ X_LIBS="$X_LIBS -L$x_libraries"
+ # For Solaris; some versions of Sun CC require a space after -R and
+ # others require no space. Words are not sufficient . . . .
+ case `(uname -sr) 2>/dev/null` in
+ "SunOS 5"*)
+ echo "$as_me:$LINENO: checking whether -R must be followed by a space" >&5
+echo $ECHO_N "checking whether -R must be followed by a space... $ECHO_C" >&6
+ ac_xsave_LIBS=$LIBS; LIBS="$LIBS -R$x_libraries"
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_R_nospace=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_R_nospace=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+ if test $ac_R_nospace = yes; then
+ echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+ X_LIBS="$X_LIBS -R$x_libraries"
+ else
+ LIBS="$ac_xsave_LIBS -R $x_libraries"
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_R_space=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_R_space=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+ if test $ac_R_space = yes; then
+ echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6
+ X_LIBS="$X_LIBS -R $x_libraries"
+ else
+ echo "$as_me:$LINENO: result: neither works" >&5
+echo "${ECHO_T}neither works" >&6
+ fi
+ fi
+ LIBS=$ac_xsave_LIBS
+ esac
+ fi
+
+ # Check for system-dependent libraries X programs must link with.
+ # Do this before checking for the system-independent R6 libraries
+ # (-lICE), since we may need -lsocket or whatever for X linking.
+
+ if test "$ISC" = yes; then
+ X_EXTRA_LIBS="$X_EXTRA_LIBS -lnsl_s -linet"
+ else
+ # Martyn Johnson says this is needed for Ultrix, if the X
+ # libraries were built with DECnet support. And Karl Berry says
+ # the Alpha needs dnet_stub (dnet does not exist).
+ ac_xsave_LIBS="$LIBS"; LIBS="$LIBS $X_LIBS -lX11"
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char XOpenDisplay ();
+int
+main ()
+{
+XOpenDisplay ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ :
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+echo "$as_me:$LINENO: checking for dnet_ntoa in -ldnet" >&5
+echo $ECHO_N "checking for dnet_ntoa in -ldnet... $ECHO_C" >&6
+if test "${ac_cv_lib_dnet_dnet_ntoa+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldnet $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char dnet_ntoa ();
+int
+main ()
+{
+dnet_ntoa ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_dnet_dnet_ntoa=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_dnet_dnet_ntoa=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dnet_dnet_ntoa" >&5
+echo "${ECHO_T}$ac_cv_lib_dnet_dnet_ntoa" >&6
+if test $ac_cv_lib_dnet_dnet_ntoa = yes; then
+ X_EXTRA_LIBS="$X_EXTRA_LIBS -ldnet"
+fi
+
+ if test $ac_cv_lib_dnet_dnet_ntoa = no; then
+ echo "$as_me:$LINENO: checking for dnet_ntoa in -ldnet_stub" >&5
+echo $ECHO_N "checking for dnet_ntoa in -ldnet_stub... $ECHO_C" >&6
+if test "${ac_cv_lib_dnet_stub_dnet_ntoa+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldnet_stub $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char dnet_ntoa ();
+int
+main ()
+{
+dnet_ntoa ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_dnet_stub_dnet_ntoa=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_dnet_stub_dnet_ntoa=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_dnet_stub_dnet_ntoa" >&5
+echo "${ECHO_T}$ac_cv_lib_dnet_stub_dnet_ntoa" >&6
+if test $ac_cv_lib_dnet_stub_dnet_ntoa = yes; then
+ X_EXTRA_LIBS="$X_EXTRA_LIBS -ldnet_stub"
+fi
+
+ fi
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+ LIBS="$ac_xsave_LIBS"
+
+ # msh at cis.ufl.edu says -lnsl (and -lsocket) are needed for his 386/AT,
+ # to get the SysV transport functions.
+ # Chad R. Larson says the Pyramis MIS-ES running DC/OSx (SVR4)
+ # needs -lnsl.
+ # The nsl library prevents programs from opening the X display
+ # on Irix 5.2, according to T.E. Dickey.
+ # The functions gethostbyname, getservbyname, and inet_addr are
+ # in -lbsd on LynxOS 3.0.1/i386, according to Lars Hecking.
+ echo "$as_me:$LINENO: checking for gethostbyname" >&5
+echo $ECHO_N "checking for gethostbyname... $ECHO_C" >&6
+if test "${ac_cv_func_gethostbyname+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define gethostbyname to an innocuous variant, in case <limits.h> declares gethostbyname.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define gethostbyname innocuous_gethostbyname
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char gethostbyname (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef gethostbyname
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char gethostbyname ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined (__stub_gethostbyname) || defined (__stub___gethostbyname)
+choke me
+#else
+char (*f) () = gethostbyname;
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+int
+main ()
+{
+return f != gethostbyname;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_gethostbyname=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_func_gethostbyname=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_func_gethostbyname" >&5
+echo "${ECHO_T}$ac_cv_func_gethostbyname" >&6
+
+ if test $ac_cv_func_gethostbyname = no; then
+ echo "$as_me:$LINENO: checking for gethostbyname in -lnsl" >&5
+echo $ECHO_N "checking for gethostbyname in -lnsl... $ECHO_C" >&6
+if test "${ac_cv_lib_nsl_gethostbyname+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lnsl $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char gethostbyname ();
+int
+main ()
+{
+gethostbyname ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_nsl_gethostbyname=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_nsl_gethostbyname=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_nsl_gethostbyname" >&5
+echo "${ECHO_T}$ac_cv_lib_nsl_gethostbyname" >&6
+if test $ac_cv_lib_nsl_gethostbyname = yes; then
+ X_EXTRA_LIBS="$X_EXTRA_LIBS -lnsl"
+fi
+
+ if test $ac_cv_lib_nsl_gethostbyname = no; then
+ echo "$as_me:$LINENO: checking for gethostbyname in -lbsd" >&5
+echo $ECHO_N "checking for gethostbyname in -lbsd... $ECHO_C" >&6
+if test "${ac_cv_lib_bsd_gethostbyname+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lbsd $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char gethostbyname ();
+int
+main ()
+{
+gethostbyname ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_bsd_gethostbyname=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_bsd_gethostbyname=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_gethostbyname" >&5
+echo "${ECHO_T}$ac_cv_lib_bsd_gethostbyname" >&6
+if test $ac_cv_lib_bsd_gethostbyname = yes; then
+ X_EXTRA_LIBS="$X_EXTRA_LIBS -lbsd"
+fi
+
+ fi
+ fi
+
+ # lieder at skyler.mavd.honeywell.com says without -lsocket,
+ # socket/setsockopt and other routines are undefined under SCO ODT
+ # 2.0. But -lsocket is broken on IRIX 5.2 (and is not necessary
+ # on later versions), says Simon Leinen: it contains gethostby*
+ # variants that don't use the name server (or something). -lsocket
+ # must be given before -lnsl if both are needed. We assume that
+ # if connect needs -lnsl, so does gethostbyname.
+ echo "$as_me:$LINENO: checking for connect" >&5
+echo $ECHO_N "checking for connect... $ECHO_C" >&6
+if test "${ac_cv_func_connect+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define connect to an innocuous variant, in case <limits.h> declares connect.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define connect innocuous_connect
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char connect (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef connect
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char connect ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined (__stub_connect) || defined (__stub___connect)
+choke me
+#else
+char (*f) () = connect;
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+int
+main ()
+{
+return f != connect;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_connect=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_func_connect=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_func_connect" >&5
+echo "${ECHO_T}$ac_cv_func_connect" >&6
+
+ if test $ac_cv_func_connect = no; then
+ echo "$as_me:$LINENO: checking for connect in -lsocket" >&5
+echo $ECHO_N "checking for connect in -lsocket... $ECHO_C" >&6
+if test "${ac_cv_lib_socket_connect+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lsocket $X_EXTRA_LIBS $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char connect ();
+int
+main ()
+{
+connect ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_socket_connect=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_socket_connect=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_socket_connect" >&5
+echo "${ECHO_T}$ac_cv_lib_socket_connect" >&6
+if test $ac_cv_lib_socket_connect = yes; then
+ X_EXTRA_LIBS="-lsocket $X_EXTRA_LIBS"
+fi
+
+ fi
+
+ # Guillermo Gomez says -lposix is necessary on A/UX.
+ echo "$as_me:$LINENO: checking for remove" >&5
+echo $ECHO_N "checking for remove... $ECHO_C" >&6
+if test "${ac_cv_func_remove+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define remove to an innocuous variant, in case <limits.h> declares remove.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define remove innocuous_remove
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char remove (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef remove
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char remove ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined (__stub_remove) || defined (__stub___remove)
+choke me
+#else
+char (*f) () = remove;
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+int
+main ()
+{
+return f != remove;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_remove=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_func_remove=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_func_remove" >&5
+echo "${ECHO_T}$ac_cv_func_remove" >&6
+
+ if test $ac_cv_func_remove = no; then
+ echo "$as_me:$LINENO: checking for remove in -lposix" >&5
+echo $ECHO_N "checking for remove in -lposix... $ECHO_C" >&6
+if test "${ac_cv_lib_posix_remove+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lposix $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char remove ();
+int
+main ()
+{
+remove ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_posix_remove=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_posix_remove=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_posix_remove" >&5
+echo "${ECHO_T}$ac_cv_lib_posix_remove" >&6
+if test $ac_cv_lib_posix_remove = yes; then
+ X_EXTRA_LIBS="$X_EXTRA_LIBS -lposix"
+fi
+
+ fi
+
+ # BSDI BSD/OS 2.1 needs -lipc for XOpenDisplay.
+ echo "$as_me:$LINENO: checking for shmat" >&5
+echo $ECHO_N "checking for shmat... $ECHO_C" >&6
+if test "${ac_cv_func_shmat+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define shmat to an innocuous variant, in case <limits.h> declares shmat.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define shmat innocuous_shmat
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char shmat (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef shmat
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char shmat ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined (__stub_shmat) || defined (__stub___shmat)
+choke me
+#else
+char (*f) () = shmat;
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+int
+main ()
+{
+return f != shmat;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func_shmat=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_func_shmat=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_func_shmat" >&5
+echo "${ECHO_T}$ac_cv_func_shmat" >&6
+
+ if test $ac_cv_func_shmat = no; then
+ echo "$as_me:$LINENO: checking for shmat in -lipc" >&5
+echo $ECHO_N "checking for shmat in -lipc... $ECHO_C" >&6
+if test "${ac_cv_lib_ipc_shmat+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lipc $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char shmat ();
+int
+main ()
+{
+shmat ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_ipc_shmat=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_ipc_shmat=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_ipc_shmat" >&5
+echo "${ECHO_T}$ac_cv_lib_ipc_shmat" >&6
+if test $ac_cv_lib_ipc_shmat = yes; then
+ X_EXTRA_LIBS="$X_EXTRA_LIBS -lipc"
+fi
+
+ fi
+ fi
+
+ # Check for libraries that X11R6 Xt/Xaw programs need.
+ ac_save_LDFLAGS=$LDFLAGS
+ test -n "$x_libraries" && LDFLAGS="$LDFLAGS -L$x_libraries"
+ # SM needs ICE to (dynamically) link under SunOS 4.x (so we have to
+ # check for ICE first), but we must link in the order -lSM -lICE or
+ # we get undefined symbols. So assume we have SM if we have ICE.
+ # These have to be linked with before -lX11, unlike the other
+ # libraries we check for below, so use a different variable.
+ # John Interrante, Karl Berry
+ echo "$as_me:$LINENO: checking for IceConnectionNumber in -lICE" >&5
+echo $ECHO_N "checking for IceConnectionNumber in -lICE... $ECHO_C" >&6
+if test "${ac_cv_lib_ICE_IceConnectionNumber+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lICE $X_EXTRA_LIBS $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char IceConnectionNumber ();
+int
+main ()
+{
+IceConnectionNumber ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_ICE_IceConnectionNumber=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_ICE_IceConnectionNumber=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_ICE_IceConnectionNumber" >&5
+echo "${ECHO_T}$ac_cv_lib_ICE_IceConnectionNumber" >&6
+if test $ac_cv_lib_ICE_IceConnectionNumber = yes; then
+ X_PRE_LIBS="$X_PRE_LIBS -lSM -lICE"
+fi
+
+ LDFLAGS=$ac_save_LDFLAGS
+
+fi
+
+
+echo "$as_me:$LINENO: checking whether variable-length arrays are supported" >&5
+echo $ECHO_N "checking whether variable-length arrays are supported... $ECHO_C" >&6
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+
+ int n; int foo[n];
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; cat >>confdefs.h <<\_ACEOF
+#define HAVE_VLA 1
+_ACEOF
+
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+
+
+############################################################
+# Check for the IJG JPEG library.
+############################################################
+
+# Allow the user to explicitly specify whether the JPEG library is present.
+# Check whether --enable-libjpeg or --disable-libjpeg was given.
+if test "${enable_libjpeg+set}" = set; then
+ enableval="$enable_libjpeg"
+
+case "${enableval}" in
+yes)
+ ENABLE_LIBJPEG=yes;;
+no)
+ ENABLE_LIBJPEG=no;;
+*)
+ { { echo "$as_me:$LINENO: error: bad value ${enableval} for --disable-libjpeg" >&5
+echo "$as_me: error: bad value ${enableval} for --disable-libjpeg" >&2;}
+ { (exit 1); exit 1; }; }
+ ;;
+esac
+
+else
+ ENABLE_LIBJPEG=yes
+fi;
+
+HAVE_LIBJPEG=no
+if test $ENABLE_LIBJPEG = yes; then
+ # Check for the JPEG library.
+ echo "$as_me:$LINENO: checking for jpeg_destroy in -ljpeg" >&5
+echo $ECHO_N "checking for jpeg_destroy in -ljpeg... $ECHO_C" >&6
+if test "${ac_cv_lib_jpeg_jpeg_destroy+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-ljpeg $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char jpeg_destroy ();
+int
+main ()
+{
+jpeg_destroy ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_jpeg_jpeg_destroy=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_jpeg_jpeg_destroy=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_jpeg_jpeg_destroy" >&5
+echo "${ECHO_T}$ac_cv_lib_jpeg_jpeg_destroy" >&6
+if test $ac_cv_lib_jpeg_jpeg_destroy = yes; then
+ HAVE_LIBJPEG=yes
+else
+ HAVE_LIBJPEG=no
+fi
+
+ if test $HAVE_LIBJPEG = yes; then
+ LIBS="$LIBS -ljpeg"
+ fi
+fi
+
+
+if test $HAVE_LIBJPEG = yes; then
+ HAVE_LIBJPEG_TRUE=
+ HAVE_LIBJPEG_FALSE='#'
+else
+ HAVE_LIBJPEG_TRUE='#'
+ HAVE_LIBJPEG_FALSE=
+fi
+
+
+############################################################
+# Check for OpenGL libraries.
+############################################################
+
+
+# Check whether --with-glut-include-dir or --without-glut-include-dir was given.
+if test "${with_glut_include_dir+set}" = set; then
+ withval="$with_glut_include_dir"
+
+ case "$withval" in
+ /*)
+ CFLAGS="$CFLAGS -I$withval"
+ CPPFLAGS="$CPPFLAGS -I$withval";;
+ *)
+ { { echo "$as_me:$LINENO: error: --with-glut-include-dir requires absolute path" >&5
+echo "$as_me: error: --with-glut-include-dir requires absolute path" >&2;}
+ { (exit 1); exit 1; }; }
+ ;;
+ esac
+
+fi;
+
+# Check whether --with-glut-lib-dir or --without-glut-lib-dir was given.
+if test "${with_glut_lib_dir+set}" = set; then
+ withval="$with_glut_lib_dir"
+
+ case "$withval" in
+ /*)
+ LIBS="$LIBS -L$withval";;
+ *)
+ { { echo "$as_me:$LINENO: error: --with-glut-lib-dir requires absolute path" >&5
+echo "$as_me: error: --with-glut-lib-dir requires absolute path" >&2;}
+ { (exit 1); exit 1; }; }
+ ;;
+ esac
+
+fi;
+
+# Check whether --enable-opengl or --disable-opengl was given.
+if test "${enable_opengl+set}" = set; then
+ enableval="$enable_opengl"
+
+ case "$enableval" in
+ yes)
+ ENABLE_OPENGL=yes;;
+ no)
+ ENABLE_OPENGL=no;;
+ *)
+ { { echo "$as_me:$LINENO: error: bad value ${enableval} for --disable-libjpeg" >&5
+echo "$as_me: error: bad value ${enableval} for --disable-libjpeg" >&2;}
+ { (exit 1); exit 1; }; }
+ ;;
+ esac
+
+else
+ ENABLE_OPENGL=yes
+fi;
+
+HAVE_OPENGL=no
+OPENGL_LIBS=""
+if test $ENABLE_OPENGL = yes; then
+ if test $HAVE_OPENGL = no; then
+ TMPLIBS="-lglut -lGL -lGLU $X_PRE_LIBS -lX11 -lXmu -lXi -lXext -lXt $X_EXTRA_LIBS $X_LIBS"
+ echo "$as_me:$LINENO: checking for glutInit in -lglut" >&5
+echo $ECHO_N "checking for glutInit in -lglut... $ECHO_C" >&6
+if test "${ac_cv_lib_glut_glutInit+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lglut $TMPLIBS $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char glutInit ();
+int
+main ()
+{
+glutInit ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_glut_glutInit=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_glut_glutInit=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_glut_glutInit" >&5
+echo "${ECHO_T}$ac_cv_lib_glut_glutInit" >&6
+if test $ac_cv_lib_glut_glutInit = yes; then
+ HAVE_OPENGL=yes;
+ OPENGL_LIBS=$TMPLIBS
+else
+ HAVE_OPENGL=no
+fi
+
+ fi
+ if test "${ac_cv_header_GL_glut_h+set}" = set; then
+ echo "$as_me:$LINENO: checking for GL/glut.h" >&5
+echo $ECHO_N "checking for GL/glut.h... $ECHO_C" >&6
+if test "${ac_cv_header_GL_glut_h+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+echo "$as_me:$LINENO: result: $ac_cv_header_GL_glut_h" >&5
+echo "${ECHO_T}$ac_cv_header_GL_glut_h" >&6
+else
+ # Is the header compilable?
+echo "$as_me:$LINENO: checking GL/glut.h usability" >&5
+echo $ECHO_N "checking GL/glut.h usability... $ECHO_C" >&6
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <GL/glut.h>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_header_compiler=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6
+
+# Is the header present?
+echo "$as_me:$LINENO: checking GL/glut.h presence" >&5
+echo $ECHO_N "checking GL/glut.h presence... $ECHO_C" >&6
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <GL/glut.h>
+_ACEOF
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+ (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+rm -f conftest.err conftest.$ac_ext
+echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: GL/glut.h: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: GL/glut.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: GL/glut.h: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: GL/glut.h: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: GL/glut.h: present but cannot be compiled" >&5
+echo "$as_me: WARNING: GL/glut.h: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: GL/glut.h: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: GL/glut.h: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: GL/glut.h: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: GL/glut.h: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: GL/glut.h: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: GL/glut.h: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: GL/glut.h: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: GL/glut.h: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: GL/glut.h: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: GL/glut.h: in the future, the compiler will take precedence" >&2;}
+ (
+ cat <<\_ASBOX
+## --------------------------------- ##
+## Report this to the jasper lists. ##
+## --------------------------------- ##
+_ASBOX
+ ) |
+ sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+echo "$as_me:$LINENO: checking for GL/glut.h" >&5
+echo $ECHO_N "checking for GL/glut.h... $ECHO_C" >&6
+if test "${ac_cv_header_GL_glut_h+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_cv_header_GL_glut_h=$ac_header_preproc
+fi
+echo "$as_me:$LINENO: result: $ac_cv_header_GL_glut_h" >&5
+echo "${ECHO_T}$ac_cv_header_GL_glut_h" >&6
+
+fi
+if test $ac_cv_header_GL_glut_h = yes; then
+ :
+else
+ HAVE_OPENGL=no; OPENGL_LIBS="";
+fi
+
+
+fi
+
+
+
+if test $HAVE_OPENGL = yes; then
+ HAVE_OPENGL_TRUE=
+ HAVE_OPENGL_FALSE='#'
+else
+ HAVE_OPENGL_TRUE='#'
+ HAVE_OPENGL_FALSE=
+fi
+
+
+echo "$as_me:$LINENO: checking whether OpenGL libraries and headers were detected" >&5
+echo $ECHO_N "checking whether OpenGL libraries and headers were detected... $ECHO_C" >&6
+echo "$as_me:$LINENO: result: $HAVE_OPENGL" >&5
+echo "${ECHO_T}$HAVE_OPENGL" >&6
+
+############################################################
+# Check for other libraries.
+############################################################
+
+# Check for the math library.
+
+echo "$as_me:$LINENO: checking for main in -lm" >&5
+echo $ECHO_N "checking for main in -lm... $ECHO_C" >&6
+if test "${ac_cv_lib_m_main+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+
+int
+main ()
+{
+main ();
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_lib_m_main=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_lib_m_main=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+echo "$as_me:$LINENO: result: $ac_cv_lib_m_main" >&5
+echo "${ECHO_T}$ac_cv_lib_m_main" >&6
+if test $ac_cv_lib_m_main = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBM 1
+_ACEOF
+
+ LIBS="-lm $LIBS"
+
+fi
+
+
+############################################################
+# Check for header files.
+############################################################
+
+echo "$as_me:$LINENO: checking for ANSI C header files" >&5
+echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6
+if test "${ac_cv_header_stdc+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
+
+int
+main ()
+{
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_header_stdc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_header_stdc=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+
+if test $ac_cv_header_stdc = yes; then
+ # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <string.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+ $EGREP "memchr" >/dev/null 2>&1; then
+ :
+else
+ ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+ # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <stdlib.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+ $EGREP "free" >/dev/null 2>&1; then
+ :
+else
+ ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+ # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
+ if test "$cross_compiling" = yes; then
+ :
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <ctype.h>
+#if ((' ' & 0x0FF) == 0x020)
+# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
+# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
+#else
+# define ISLOWER(c) \
+ (('a' <= (c) && (c) <= 'i') \
+ || ('j' <= (c) && (c) <= 'r') \
+ || ('s' <= (c) && (c) <= 'z'))
+# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
+#endif
+
+#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
+int
+main ()
+{
+ int i;
+ for (i = 0; i < 256; i++)
+ if (XOR (islower (i), ISLOWER (i))
+ || toupper (i) != TOUPPER (i))
+ exit(2);
+ exit (0);
+}
+_ACEOF
+rm -f conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ :
+else
+ echo "$as_me: program exited with status $ac_status" >&5
+echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+( exit $ac_status )
+ac_cv_header_stdc=no
+fi
+rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+fi
+fi
+fi
+echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5
+echo "${ECHO_T}$ac_cv_header_stdc" >&6
+if test $ac_cv_header_stdc = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define STDC_HEADERS 1
+_ACEOF
+
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+for ac_header in fcntl.h limits.h unistd.h stdint.h stdbool.h io.h windows.h sys/types.h sys/time.h stdlib.h stddef.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
+ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
+else
+ # Is the header compilable?
+echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+#include <$ac_header>
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_header_compiler=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_header_compiler=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6
+
+# Is the header present?
+echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#include <$ac_header>
+_ACEOF
+if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
+ (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } >/dev/null; then
+ if test -s conftest.err; then
+ ac_cpp_err=$ac_c_preproc_warn_flag
+ ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
+ else
+ ac_cpp_err=
+ fi
+else
+ ac_cpp_err=yes
+fi
+if test -z "$ac_cpp_err"; then
+ ac_header_preproc=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_header_preproc=no
+fi
+rm -f conftest.err conftest.$ac_ext
+echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6
+
+# So? What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+ yes:no: )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+ ac_header_preproc=yes
+ ;;
+ no:yes:* )
+ { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+ { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+ (
+ cat <<\_ASBOX
+## --------------------------------- ##
+## Report this to the jasper lists. ##
+## --------------------------------- ##
+_ASBOX
+ ) |
+ sed "s/^/$as_me: WARNING: /" >&2
+ ;;
+esac
+echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
+if eval "test \"\${$as_ac_Header+set}\" = set"; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ eval "$as_ac_Header=\$ac_header_preproc"
+fi
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
+
+fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+############################################################
+# Check for typedefs, structures, and compiler characteristics.
+############################################################
+
+echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5
+echo $ECHO_N "checking for an ANSI C-conforming const... $ECHO_C" >&6
+if test "${ac_cv_c_const+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+/* FIXME: Include the comments suggested by Paul. */
+#ifndef __cplusplus
+ /* Ultrix mips cc rejects this. */
+ typedef int charset[2];
+ const charset x;
+ /* SunOS 4.1.1 cc rejects this. */
+ char const *const *ccp;
+ char **p;
+ /* NEC SVR4.0.2 mips cc rejects this. */
+ struct point {int x, y;};
+ static struct point const zero = {0,0};
+ /* AIX XL C 1.02.0.0 rejects this.
+ It does not let you subtract one const X* pointer from another in
+ an arm of an if-expression whose if-part is not a constant
+ expression */
+ const char *g = "string";
+ ccp = &g + (g ? g-g : 0);
+ /* HPUX 7.0 cc rejects these. */
+ ++ccp;
+ p = (char**) ccp;
+ ccp = (char const *const *) p;
+ { /* SCO 3.2v4 cc rejects this. */
+ char *t;
+ char const *s = 0 ? (char *) 0 : (char const *) 0;
+
+ *t++ = 0;
+ }
+ { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */
+ int x[] = {25, 17};
+ const int *foo = &x[0];
+ ++foo;
+ }
+ { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */
+ typedef const int *iptr;
+ iptr p = 0;
+ ++p;
+ }
+ { /* AIX XL C 1.02.0.0 rejects this saying
+ "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */
+ struct s { int j; const int *ap[3]; };
+ struct s *b; b->j = 5;
+ }
+ { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
+ const int foo = 10;
+ }
+#endif
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_c_const=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_c_const=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5
+echo "${ECHO_T}$ac_cv_c_const" >&6
+if test $ac_cv_c_const = no; then
+
+cat >>confdefs.h <<\_ACEOF
+#define const
+_ACEOF
+
+fi
+
+echo "$as_me:$LINENO: checking for inline" >&5
+echo $ECHO_N "checking for inline... $ECHO_C" >&6
+if test "${ac_cv_c_inline+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ ac_cv_c_inline=no
+for ac_kw in inline __inline__ __inline; do
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+#ifndef __cplusplus
+typedef int foo_t;
+static $ac_kw foo_t static_foo () {return 0; }
+$ac_kw foo_t foo () {return 0; }
+#endif
+
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_c_inline=$ac_kw; break
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+done
+
+fi
+echo "$as_me:$LINENO: result: $ac_cv_c_inline" >&5
+echo "${ECHO_T}$ac_cv_c_inline" >&6
+
+
+case $ac_cv_c_inline in
+ inline | yes) ;;
+ *)
+ case $ac_cv_c_inline in
+ no) ac_val=;;
+ *) ac_val=$ac_cv_c_inline;;
+ esac
+ cat >>confdefs.h <<_ACEOF
+#ifndef __cplusplus
+#define inline $ac_val
+#endif
+_ACEOF
+ ;;
+esac
+
+echo "$as_me:$LINENO: checking for size_t" >&5
+echo $ECHO_N "checking for size_t... $ECHO_C" >&6
+if test "${ac_cv_type_size_t+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+int
+main ()
+{
+if ((size_t *) 0)
+ return 0;
+if (sizeof (size_t))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_size_t=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_type_size_t=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5
+echo "${ECHO_T}$ac_cv_type_size_t" >&6
+if test $ac_cv_type_size_t = yes; then
+ :
+else
+
+cat >>confdefs.h <<_ACEOF
+#define size_t unsigned
+_ACEOF
+
+fi
+
+echo "$as_me:$LINENO: checking for uchar" >&5
+echo $ECHO_N "checking for uchar... $ECHO_C" >&6
+if test "${ac_cv_type_uchar+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+int
+main ()
+{
+if ((uchar *) 0)
+ return 0;
+if (sizeof (uchar))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_uchar=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_type_uchar=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_type_uchar" >&5
+echo "${ECHO_T}$ac_cv_type_uchar" >&6
+if test $ac_cv_type_uchar = yes; then
+ :
+else
+
+cat >>confdefs.h <<_ACEOF
+#define uchar unsigned char
+_ACEOF
+
+fi
+
+echo "$as_me:$LINENO: checking for ushort" >&5
+echo $ECHO_N "checking for ushort... $ECHO_C" >&6
+if test "${ac_cv_type_ushort+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+int
+main ()
+{
+if ((ushort *) 0)
+ return 0;
+if (sizeof (ushort))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_ushort=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_type_ushort=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_type_ushort" >&5
+echo "${ECHO_T}$ac_cv_type_ushort" >&6
+if test $ac_cv_type_ushort = yes; then
+ :
+else
+
+cat >>confdefs.h <<_ACEOF
+#define ushort unsigned short
+_ACEOF
+
+fi
+
+echo "$as_me:$LINENO: checking for uint" >&5
+echo $ECHO_N "checking for uint... $ECHO_C" >&6
+if test "${ac_cv_type_uint+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+int
+main ()
+{
+if ((uint *) 0)
+ return 0;
+if (sizeof (uint))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_uint=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_type_uint=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_type_uint" >&5
+echo "${ECHO_T}$ac_cv_type_uint" >&6
+if test $ac_cv_type_uint = yes; then
+ :
+else
+
+cat >>confdefs.h <<_ACEOF
+#define uint unsigned int
+_ACEOF
+
+fi
+
+echo "$as_me:$LINENO: checking for ulong" >&5
+echo $ECHO_N "checking for ulong... $ECHO_C" >&6
+if test "${ac_cv_type_ulong+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+int
+main ()
+{
+if ((ulong *) 0)
+ return 0;
+if (sizeof (ulong))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_ulong=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_type_ulong=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_type_ulong" >&5
+echo "${ECHO_T}$ac_cv_type_ulong" >&6
+if test $ac_cv_type_ulong = yes; then
+ :
+else
+
+cat >>confdefs.h <<_ACEOF
+#define ulong unsigned long
+_ACEOF
+
+fi
+
+echo "$as_me:$LINENO: checking for longlong" >&5
+echo $ECHO_N "checking for longlong... $ECHO_C" >&6
+if test "${ac_cv_type_longlong+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+int
+main ()
+{
+if ((longlong *) 0)
+ return 0;
+if (sizeof (longlong))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_longlong=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_type_longlong=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_type_longlong" >&5
+echo "${ECHO_T}$ac_cv_type_longlong" >&6
+if test $ac_cv_type_longlong = yes; then
+ :
+else
+
+cat >>confdefs.h <<_ACEOF
+#define longlong long long
+_ACEOF
+
+fi
+
+echo "$as_me:$LINENO: checking for ulonglong" >&5
+echo $ECHO_N "checking for ulonglong... $ECHO_C" >&6
+if test "${ac_cv_type_ulonglong+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+int
+main ()
+{
+if ((ulonglong *) 0)
+ return 0;
+if (sizeof (ulonglong))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_ulonglong=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_type_ulonglong=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_type_ulonglong" >&5
+echo "${ECHO_T}$ac_cv_type_ulonglong" >&6
+if test $ac_cv_type_ulonglong = yes; then
+ :
+else
+
+cat >>confdefs.h <<_ACEOF
+#define ulonglong unsigned long long
+_ACEOF
+
+fi
+
+echo "$as_me:$LINENO: checking for ssize_t" >&5
+echo $ECHO_N "checking for ssize_t... $ECHO_C" >&6
+if test "${ac_cv_type_ssize_t+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+int
+main ()
+{
+if ((ssize_t *) 0)
+ return 0;
+if (sizeof (ssize_t))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+ (eval $ac_compile) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest.$ac_objext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_type_ssize_t=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_type_ssize_t=no
+fi
+rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_type_ssize_t" >&5
+echo "${ECHO_T}$ac_cv_type_ssize_t" >&6
+if test $ac_cv_type_ssize_t = yes; then
+ :
+else
+
+cat >>confdefs.h <<_ACEOF
+#define ssize_t int
+_ACEOF
+
+fi
+
+
+for ac_func in gettimeofday
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6
+if eval "test \"\${$as_ac_var+set}\" = set"; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
+choke me
+#else
+char (*f) () = $ac_func;
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+int
+main ()
+{
+return f != $ac_func;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+eval "$as_ac_var=no"
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+for ac_func in getrusage
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6
+if eval "test \"\${$as_ac_var+set}\" = set"; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
+choke me
+#else
+char (*f) () = $ac_func;
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+int
+main ()
+{
+return f != $ac_func;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+eval "$as_ac_var=no"
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+############################################################
+# Checks for library functions.
+############################################################
+
+
+for ac_func in vprintf
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6
+if eval "test \"\${$as_ac_var+set}\" = set"; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char $ac_func (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined (__stub_$ac_func) || defined (__stub___$ac_func)
+choke me
+#else
+char (*f) () = $ac_func;
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+int
+main ()
+{
+return f != $ac_func;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ eval "$as_ac_var=yes"
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+eval "$as_ac_var=no"
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5
+echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6
+if test `eval echo '${'$as_ac_var'}'` = yes; then
+ cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+echo "$as_me:$LINENO: checking for _doprnt" >&5
+echo $ECHO_N "checking for _doprnt... $ECHO_C" >&6
+if test "${ac_cv_func__doprnt+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+/* Define _doprnt to an innocuous variant, in case <limits.h> declares _doprnt.
+ For example, HP-UX 11i <limits.h> declares gettimeofday. */
+#define _doprnt innocuous__doprnt
+
+/* System header to define __stub macros and hopefully few prototypes,
+ which can conflict with char _doprnt (); below.
+ Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+ <limits.h> exists even on freestanding compilers. */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef _doprnt
+
+/* Override any gcc2 internal prototype to avoid an error. */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* We use char because int might match the return type of a gcc2
+ builtin and then its argument prototype would still apply. */
+char _doprnt ();
+/* The GNU C library defines this for functions which it implements
+ to always fail with ENOSYS. Some functions are actually named
+ something starting with __ and the normal name is an alias. */
+#if defined (__stub__doprnt) || defined (__stub____doprnt)
+choke me
+#else
+char (*f) () = _doprnt;
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+int
+main ()
+{
+return f != _doprnt;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+ (eval $ac_link) 2>conftest.er1
+ ac_status=$?
+ grep -v '^ *+' conftest.er1 >conftest.err
+ rm -f conftest.er1
+ cat conftest.err >&5
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } &&
+ { ac_try='test -z "$ac_c_werror_flag"
+ || test ! -s conftest.err'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; } &&
+ { ac_try='test -s conftest$ac_exeext'
+ { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+ (eval $ac_try) 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_func__doprnt=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ac_cv_func__doprnt=no
+fi
+rm -f conftest.err conftest.$ac_objext \
+ conftest$ac_exeext conftest.$ac_ext
+fi
+echo "$as_me:$LINENO: result: $ac_cv_func__doprnt" >&5
+echo "${ECHO_T}$ac_cv_func__doprnt" >&6
+if test $ac_cv_func__doprnt = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_DOPRNT 1
+_ACEOF
+
+fi
+
+fi
+done
+
+
+
+############################################################
+# Enable/disable special memory allocator for debugging.
+############################################################
+
+# Check whether --enable-dmalloc or --disable-dmalloc was given.
+if test "${enable_dmalloc+set}" = set; then
+ enableval="$enable_dmalloc"
+
+case "${enableval}" in
+yes)
+ cat >>confdefs.h <<\_ACEOF
+#define DEBUG_MEMALLOC 1
+_ACEOF
+
+ ;;
+no)
+ ;;
+*)
+ { { echo "$as_me:$LINENO: error: bad value ${enableval} for --enable-dmalloc" >&5
+echo "$as_me: error: bad value ${enableval} for --enable-dmalloc" >&2;}
+ { (exit 1); exit 1; }; }
+ ;;
+esac
+
+fi;
+
+############################################################
+# Enable/disable extra code for debugging.
+############################################################
+
+# Check whether --enable-debug or --disable-debug was given.
+if test "${enable_debug+set}" = set; then
+ enableval="$enable_debug"
+
+case "${enableval}" in
+yes)
+ debug=yes
+ cat >>confdefs.h <<\_ACEOF
+#define DEBUG 1
+_ACEOF
+
+ cat >>confdefs.h <<\_ACEOF
+#define DEBUG_OVERFLOW 1
+_ACEOF
+
+ if test "$GCC" = yes; then
+ CFLAGS="-g -O0"
+ fi
+ ;;
+no)
+ debug=no
+ ;;
+*)
+ { { echo "$as_me:$LINENO: error: bad value ${enableval} for --enable-debug" >&5
+echo "$as_me: error: bad value ${enableval} for --enable-debug" >&2;}
+ { (exit 1); exit 1; }; }
+ ;;
+esac
+
+else
+ debug=no
+fi;
+
+if test "$GCC" = yes; then
+ CFLAGS="$CFLAGS"
+ #CFLAGS="$CFLAGS -std=c99"
+ #CFLAGS="$CFLAGS -pedantic"
+ #CFLAGS="$CFLAGS -pedantic-errors"
+ #CFLAGS="$CFLAGS -W -Wall -Wno-long-long -Wformat -Wmissing-prototypes -Wstrict-prototypes"
+fi
+
+############################################################
+# Extra stuff for research purposes.
+############################################################
+
+# Check whether --enable-special0 or --disable-special0 was given.
+if test "${enable_special0+set}" = set; then
+ enableval="$enable_special0"
+
+case "${enableval}" in
+yes)
+ if test "$GCC" = yes; then
+ CFLAGS="-g -O0"
+ fi
+ ;;
+no)
+ ;;
+*)
+ { { echo "$as_me:$LINENO: error: bad value ${enableval} for --enable-special0" >&5
+echo "$as_me: error: bad value ${enableval} for --enable-special0" >&2;}
+ { (exit 1); exit 1; }; }
+ ;;
+esac
+
+fi;
+
+if test -n "$EXTRACFLAGS"; then
+ CFLAGS="$CFLAGS $EXTRACFLAGS"
+fi
+
+############################################################
+# Generate the configuration header file.
+############################################################
+
+ ac_config_headers="$ac_config_headers src/libjasper/include/jasper/jas_config.h"
+
+
+############################################################
+# Generate the makefiles.
+############################################################
+
+ ac_config_files="$ac_config_files Makefile src/Makefile src/appl/Makefile src/libjasper/Makefile src/libjasper/base/Makefile src/libjasper/bmp/Makefile src/libjasper/include/Makefile src/libjasper/include/jasper/Makefile src/libjasper/jp2/Makefile src/libjasper/jpc/Makefile src/libjasper/jpg/Makefile src/libjasper/mif/Ma [...]
+
+cat >confcache <<\_ACEOF
+# This file is a shell script that caches the results of configure
+# tests run on this system so they can be shared between configure
+# scripts and configure runs, see configure's option --config-cache.
+# It is not useful on other systems. If it contains results you don't
+# want to keep, you may remove or edit it.
+#
+# config.status only pays attention to the cache file if you give it
+# the --recheck option to rerun configure.
+#
+# `ac_cv_env_foo' variables (set or unset) will be overridden when
+# loading this file, other *unset* `ac_cv_foo' will be assigned the
+# following values.
+
+_ACEOF
+
+# The following way of writing the cache mishandles newlines in values,
+# but we know of no workaround that is simple, portable, and efficient.
+# So, don't put newlines in cache variables' values.
+# Ultrix sh set writes to stderr and can't be redirected directly,
+# and sets the high bit in the cache file unless we assign to the vars.
+{
+ (set) 2>&1 |
+ case `(ac_space=' '; set | grep ac_space) 2>&1` in
+ *ac_space=\ *)
+ # `set' does not quote correctly, so add quotes (double-quote
+ # substitution turns \\\\ into \\, and sed turns \\ into \).
+ sed -n \
+ "s/'/'\\\\''/g;
+ s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
+ ;;
+ *)
+ # `set' quotes correctly as required by POSIX, so do not add quotes.
+ sed -n \
+ "s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p"
+ ;;
+ esac;
+} |
+ sed '
+ t clear
+ : clear
+ s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
+ t end
+ /^ac_cv_env/!s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
+ : end' >>confcache
+if diff $cache_file confcache >/dev/null 2>&1; then :; else
+ if test -w $cache_file; then
+ test "x$cache_file" != "x/dev/null" && echo "updating cache $cache_file"
+ cat confcache >$cache_file
+ else
+ echo "not updating unwritable cache $cache_file"
+ fi
+fi
+rm -f confcache
+
+test "x$prefix" = xNONE && prefix=$ac_default_prefix
+# Let make expand exec_prefix.
+test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
+
+# VPATH may cause trouble with some makes, so we remove $(srcdir),
+# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and
+# trailing colons and then remove the whole line if VPATH becomes empty
+# (actually we leave an empty line to preserve line numbers).
+if test "x$srcdir" = x.; then
+ ac_vpsub='/^[ ]*VPATH[ ]*=/{
+s/:*\$(srcdir):*/:/;
+s/:*\${srcdir}:*/:/;
+s/:*@srcdir@:*/:/;
+s/^\([^=]*=[ ]*\):*/\1/;
+s/:*$//;
+s/^[^=]*=[ ]*$//;
+}'
+fi
+
+DEFS=-DHAVE_CONFIG_H
+
+ac_libobjs=
+ac_ltlibobjs=
+for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
+ # 1. Remove the extension, and $U if already installed.
+ ac_i=`echo "$ac_i" |
+ sed 's/\$U\././;s/\.o$//;s/\.obj$//'`
+ # 2. Add them.
+ ac_libobjs="$ac_libobjs $ac_i\$U.$ac_objext"
+ ac_ltlibobjs="$ac_ltlibobjs $ac_i"'$U.lo'
+done
+LIBOBJS=$ac_libobjs
+
+LTLIBOBJS=$ac_ltlibobjs
+
+
+if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then
+ { { echo "$as_me:$LINENO: error: conditional \"AMDEP\" was never defined.
+Usually this means the macro was only invoked conditionally." >&5
+echo "$as_me: error: conditional \"AMDEP\" was never defined.
+Usually this means the macro was only invoked conditionally." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then
+ { { echo "$as_me:$LINENO: error: conditional \"am__fastdepCC\" was never defined.
+Usually this means the macro was only invoked conditionally." >&5
+echo "$as_me: error: conditional \"am__fastdepCC\" was never defined.
+Usually this means the macro was only invoked conditionally." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+if test -z "${am__fastdepCXX_TRUE}" && test -z "${am__fastdepCXX_FALSE}"; then
+ { { echo "$as_me:$LINENO: error: conditional \"am__fastdepCXX\" was never defined.
+Usually this means the macro was only invoked conditionally." >&5
+echo "$as_me: error: conditional \"am__fastdepCXX\" was never defined.
+Usually this means the macro was only invoked conditionally." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+if test -z "${HAVE_LIBJPEG_TRUE}" && test -z "${HAVE_LIBJPEG_FALSE}"; then
+ { { echo "$as_me:$LINENO: error: conditional \"HAVE_LIBJPEG\" was never defined.
+Usually this means the macro was only invoked conditionally." >&5
+echo "$as_me: error: conditional \"HAVE_LIBJPEG\" was never defined.
+Usually this means the macro was only invoked conditionally." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+if test -z "${HAVE_OPENGL_TRUE}" && test -z "${HAVE_OPENGL_FALSE}"; then
+ { { echo "$as_me:$LINENO: error: conditional \"HAVE_OPENGL\" was never defined.
+Usually this means the macro was only invoked conditionally." >&5
+echo "$as_me: error: conditional \"HAVE_OPENGL\" was never defined.
+Usually this means the macro was only invoked conditionally." >&2;}
+ { (exit 1); exit 1; }; }
+fi
+
+: ${CONFIG_STATUS=./config.status}
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files $CONFIG_STATUS"
+{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5
+echo "$as_me: creating $CONFIG_STATUS" >&6;}
+cat >$CONFIG_STATUS <<_ACEOF
+#! $SHELL
+# Generated by $as_me.
+# Run this file to recreate the current configuration.
+# Compiler output produced by configure, useful for debugging
+# configure, is in config.log if it exists.
+
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
+SHELL=\${CONFIG_SHELL-$SHELL}
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+## --------------------- ##
+## M4sh Initialization. ##
+## --------------------- ##
+
+# Be Bourne compatible
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+ emulate sh
+ NULLCMD=:
+ # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+ # is contrary to our usage. Disable this feature.
+ alias -g '${1+"$@"}'='"$@"'
+elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then
+ set -o posix
+fi
+DUALCASE=1; export DUALCASE # for MKS sh
+
+# Support unset when possible.
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+ as_unset=unset
+else
+ as_unset=false
+fi
+
+
+# Work around bugs in pre-3.0 UWIN ksh.
+$as_unset ENV MAIL MAILPATH
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+for as_var in \
+ LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
+ LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
+ LC_TELEPHONE LC_TIME
+do
+ if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
+ eval $as_var=C; export $as_var
+ else
+ $as_unset $as_var
+ fi
+done
+
+# Required to use basename.
+if expr a : '\(a\)' >/dev/null 2>&1; then
+ as_expr=expr
+else
+ as_expr=false
+fi
+
+if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then
+ as_basename=basename
+else
+ as_basename=false
+fi
+
+
+# Name of the executable.
+as_me=`$as_basename "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+ X"$0" : 'X\(//\)$' \| \
+ X"$0" : 'X\(/\)$' \| \
+ . : '\(.\)' 2>/dev/null ||
+echo X/"$0" |
+ sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; }
+ /^X\/\(\/\/\)$/{ s//\1/; q; }
+ /^X\/\(\/\).*/{ s//\1/; q; }
+ s/.*/./; q'`
+
+
+# PATH needs CR, and LINENO needs CR and PATH.
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+ echo "#! /bin/sh" >conf$$.sh
+ echo "exit 0" >>conf$$.sh
+ chmod +x conf$$.sh
+ if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+ PATH_SEPARATOR=';'
+ else
+ PATH_SEPARATOR=:
+ fi
+ rm -f conf$$.sh
+fi
+
+
+ as_lineno_1=$LINENO
+ as_lineno_2=$LINENO
+ as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
+ test "x$as_lineno_1" != "x$as_lineno_2" &&
+ test "x$as_lineno_3" = "x$as_lineno_2" || {
+ # Find who we are. Look in the path if we contain no path at all
+ # relative or not.
+ case $0 in
+ *[\\/]* ) as_myself=$0 ;;
+ *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+
+ ;;
+ esac
+ # We did not find ourselves, most probably we were run as `sh COMMAND'
+ # in which case we are not to be found in the path.
+ if test "x$as_myself" = x; then
+ as_myself=$0
+ fi
+ if test ! -f "$as_myself"; then
+ { { echo "$as_me:$LINENO: error: cannot find myself; rerun with an absolute path" >&5
+echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2;}
+ { (exit 1); exit 1; }; }
+ fi
+ case $CONFIG_SHELL in
+ '')
+ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ for as_base in sh bash ksh sh5; do
+ case $as_dir in
+ /*)
+ if ("$as_dir/$as_base" -c '
+ as_lineno_1=$LINENO
+ as_lineno_2=$LINENO
+ as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
+ test "x$as_lineno_1" != "x$as_lineno_2" &&
+ test "x$as_lineno_3" = "x$as_lineno_2" ') 2>/dev/null; then
+ $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; }
+ $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; }
+ CONFIG_SHELL=$as_dir/$as_base
+ export CONFIG_SHELL
+ exec "$CONFIG_SHELL" "$0" ${1+"$@"}
+ fi;;
+ esac
+ done
+done
+;;
+ esac
+
+ # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
+ # uniformly replaced by the line number. The first 'sed' inserts a
+ # line-number line before each line; the second 'sed' does the real
+ # work. The second script uses 'N' to pair each line-number line
+ # with the numbered line, and appends trailing '-' during
+ # substitution so that $LINENO is not a special case at line end.
+ # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
+ # second 'sed' script. Blame Lee E. McMahon for sed's syntax. :-)
+ sed '=' <$as_myself |
+ sed '
+ N
+ s,$,-,
+ : loop
+ s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3,
+ t loop
+ s,-$,,
+ s,^['$as_cr_digits']*\n,,
+ ' >$as_me.lineno &&
+ chmod +x $as_me.lineno ||
+ { { echo "$as_me:$LINENO: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&5
+echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2;}
+ { (exit 1); exit 1; }; }
+
+ # Don't try to exec as it changes $[0], causing all sort of problems
+ # (the dirname of $[0] is not the place where we might find the
+ # original and so on. Autoconf is especially sensible to this).
+ . ./$as_me.lineno
+ # Exit status is that of the last command.
+ exit
+}
+
+
+case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in
+ *c*,-n*) ECHO_N= ECHO_C='
+' ECHO_T=' ' ;;
+ *c*,* ) ECHO_N=-n ECHO_C= ECHO_T= ;;
+ *) ECHO_N= ECHO_C='\c' ECHO_T= ;;
+esac
+
+if expr a : '\(a\)' >/dev/null 2>&1; then
+ as_expr=expr
+else
+ as_expr=false
+fi
+
+rm -f conf$$ conf$$.exe conf$$.file
+echo >conf$$.file
+if ln -s conf$$.file conf$$ 2>/dev/null; then
+ # We could just check for DJGPP; but this test a) works b) is more generic
+ # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04).
+ if test -f conf$$.exe; then
+ # Don't use ln at all; we don't have any links
+ as_ln_s='cp -p'
+ else
+ as_ln_s='ln -s'
+ fi
+elif ln conf$$.file conf$$ 2>/dev/null; then
+ as_ln_s=ln
+else
+ as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.file
+
+if mkdir -p . 2>/dev/null; then
+ as_mkdir_p=:
+else
+ test -d ./-p && rmdir ./-p
+ as_mkdir_p=false
+fi
+
+as_executable_p="test -f"
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.
+as_nl='
+'
+IFS=" $as_nl"
+
+# CDPATH.
+$as_unset CDPATH
+
+exec 6>&1
+
+# Open the log real soon, to keep \$[0] and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling. Logging --version etc. is OK.
+exec 5>>config.log
+{
+ echo
+ sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+} >&5
+cat >&5 <<_CSEOF
+
+This file was extended by jasper $as_me 1.900.1, which was
+generated by GNU Autoconf 2.59. Invocation command line was
+
+ CONFIG_FILES = $CONFIG_FILES
+ CONFIG_HEADERS = $CONFIG_HEADERS
+ CONFIG_LINKS = $CONFIG_LINKS
+ CONFIG_COMMANDS = $CONFIG_COMMANDS
+ $ $0 $@
+
+_CSEOF
+echo "on `(hostname || uname -n) 2>/dev/null | sed 1q`" >&5
+echo >&5
+_ACEOF
+
+# Files that config.status was made for.
+if test -n "$ac_config_files"; then
+ echo "config_files=\"$ac_config_files\"" >>$CONFIG_STATUS
+fi
+
+if test -n "$ac_config_headers"; then
+ echo "config_headers=\"$ac_config_headers\"" >>$CONFIG_STATUS
+fi
+
+if test -n "$ac_config_links"; then
+ echo "config_links=\"$ac_config_links\"" >>$CONFIG_STATUS
+fi
+
+if test -n "$ac_config_commands"; then
+ echo "config_commands=\"$ac_config_commands\"" >>$CONFIG_STATUS
+fi
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+
+ac_cs_usage="\
+\`$as_me' instantiates files from templates according to the
+current configuration.
+
+Usage: $0 [OPTIONS] [FILE]...
+
+ -h, --help print this help, then exit
+ -V, --version print version number, then exit
+ -q, --quiet do not print progress messages
+ -d, --debug don't remove temporary files
+ --recheck update $as_me by reconfiguring in the same conditions
+ --file=FILE[:TEMPLATE]
+ instantiate the configuration file FILE
+ --header=FILE[:TEMPLATE]
+ instantiate the configuration header FILE
+
+Configuration files:
+$config_files
+
+Configuration headers:
+$config_headers
+
+Configuration commands:
+$config_commands
+
+Report bugs to <bug-autoconf at gnu.org>."
+_ACEOF
+
+cat >>$CONFIG_STATUS <<_ACEOF
+ac_cs_version="\\
+jasper config.status 1.900.1
+configured by $0, generated by GNU Autoconf 2.59,
+ with options \\"`echo "$ac_configure_args" | sed 's/[\\""\`\$]/\\\\&/g'`\\"
+
+Copyright (C) 2003 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
+srcdir=$srcdir
+INSTALL="$INSTALL"
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+# If no file are specified by the user, then we need to provide default
+# value. By we need to know if files were specified by the user.
+ac_need_defaults=:
+while test $# != 0
+do
+ case $1 in
+ --*=*)
+ ac_option=`expr "x$1" : 'x\([^=]*\)='`
+ ac_optarg=`expr "x$1" : 'x[^=]*=\(.*\)'`
+ ac_shift=:
+ ;;
+ -*)
+ ac_option=$1
+ ac_optarg=$2
+ ac_shift=shift
+ ;;
+ *) # This is not an option, so the user has probably given explicit
+ # arguments.
+ ac_option=$1
+ ac_need_defaults=false;;
+ esac
+
+ case $ac_option in
+ # Handling of the options.
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+ -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
+ ac_cs_recheck=: ;;
+ --version | --vers* | -V )
+ echo "$ac_cs_version"; exit 0 ;;
+ --he | --h)
+ # Conflict between --help and --header
+ { { echo "$as_me:$LINENO: error: ambiguous option: $1
+Try \`$0 --help' for more information." >&5
+echo "$as_me: error: ambiguous option: $1
+Try \`$0 --help' for more information." >&2;}
+ { (exit 1); exit 1; }; };;
+ --help | --hel | -h )
+ echo "$ac_cs_usage"; exit 0 ;;
+ --debug | --d* | -d )
+ debug=: ;;
+ --file | --fil | --fi | --f )
+ $ac_shift
+ CONFIG_FILES="$CONFIG_FILES $ac_optarg"
+ ac_need_defaults=false;;
+ --header | --heade | --head | --hea )
+ $ac_shift
+ CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg"
+ ac_need_defaults=false;;
+ -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+ | -silent | --silent | --silen | --sile | --sil | --si | --s)
+ ac_cs_silent=: ;;
+
+ # This is an error.
+ -*) { { echo "$as_me:$LINENO: error: unrecognized option: $1
+Try \`$0 --help' for more information." >&5
+echo "$as_me: error: unrecognized option: $1
+Try \`$0 --help' for more information." >&2;}
+ { (exit 1); exit 1; }; } ;;
+
+ *) ac_config_targets="$ac_config_targets $1" ;;
+
+ esac
+ shift
+done
+
+ac_configure_extra_args=
+
+if $ac_cs_silent; then
+ exec 6>/dev/null
+ ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+if \$ac_cs_recheck; then
+ echo "running $SHELL $0 " $ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6
+ exec $SHELL $0 $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+fi
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<_ACEOF
+#
+# INIT-COMMANDS section.
+#
+
+AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"
+
+_ACEOF
+
+
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+for ac_config_target in $ac_config_targets
+do
+ case "$ac_config_target" in
+ # Handling of arguments.
+ "Makefile" ) CONFIG_FILES="$CONFIG_FILES Makefile" ;;
+ "src/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/Makefile" ;;
+ "src/appl/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/appl/Makefile" ;;
+ "src/libjasper/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/libjasper/Makefile" ;;
+ "src/libjasper/base/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/libjasper/base/Makefile" ;;
+ "src/libjasper/bmp/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/libjasper/bmp/Makefile" ;;
+ "src/libjasper/include/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/libjasper/include/Makefile" ;;
+ "src/libjasper/include/jasper/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/libjasper/include/jasper/Makefile" ;;
+ "src/libjasper/jp2/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/libjasper/jp2/Makefile" ;;
+ "src/libjasper/jpc/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/libjasper/jpc/Makefile" ;;
+ "src/libjasper/jpg/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/libjasper/jpg/Makefile" ;;
+ "src/libjasper/mif/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/libjasper/mif/Makefile" ;;
+ "src/libjasper/pgx/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/libjasper/pgx/Makefile" ;;
+ "src/libjasper/pnm/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/libjasper/pnm/Makefile" ;;
+ "src/libjasper/ras/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/libjasper/ras/Makefile" ;;
+ "src/msvc/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/msvc/Makefile" ;;
+ "jasper.spec" ) CONFIG_FILES="$CONFIG_FILES jasper.spec" ;;
+ "depfiles" ) CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;;
+ "src/libjasper/include/jasper/jas_config.h" ) CONFIG_HEADERS="$CONFIG_HEADERS src/libjasper/include/jasper/jas_config.h" ;;
+ *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5
+echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
+ { (exit 1); exit 1; }; };;
+ esac
+done
+
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used. Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+ test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+ test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
+ test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands
+fi
+
+# Have a temporary directory for convenience. Make it in the build tree
+# simply because there is no reason to put it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Create a temporary directory, and hook for its removal unless debugging.
+$debug ||
+{
+ trap 'exit_status=$?; rm -rf $tmp && exit $exit_status' 0
+ trap '{ (exit 1); exit 1; }' 1 2 13 15
+}
+
+# Create a (secure) tmp directory for tmp files.
+
+{
+ tmp=`(umask 077 && mktemp -d -q "./confstatXXXXXX") 2>/dev/null` &&
+ test -n "$tmp" && test -d "$tmp"
+} ||
+{
+ tmp=./confstat$$-$RANDOM
+ (umask 077 && mkdir $tmp)
+} ||
+{
+ echo "$me: cannot create a temporary directory in ." >&2
+ { (exit 1); exit 1; }
+}
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<_ACEOF
+
+#
+# CONFIG_FILES section.
+#
+
+# No need to generate the scripts if there are no CONFIG_FILES.
+# This happens for instance when ./config.status config.h
+if test -n "\$CONFIG_FILES"; then
+ # Protect against being on the right side of a sed subst in config.status.
+ sed 's/,@/@@/; s/@,/@@/; s/,;t t\$/@;t t/; /@;t t\$/s/[\\\\&,]/\\\\&/g;
+ s/@@/,@/; s/@@/@,/; s/@;t t\$/,;t t/' >\$tmp/subs.sed <<\\CEOF
+s, at SHELL@,$SHELL,;t t
+s, at PATH_SEPARATOR@,$PATH_SEPARATOR,;t t
+s, at PACKAGE_NAME@,$PACKAGE_NAME,;t t
+s, at PACKAGE_TARNAME@,$PACKAGE_TARNAME,;t t
+s, at PACKAGE_VERSION@,$PACKAGE_VERSION,;t t
+s, at PACKAGE_STRING@,$PACKAGE_STRING,;t t
+s, at PACKAGE_BUGREPORT@,$PACKAGE_BUGREPORT,;t t
+s, at exec_prefix@,$exec_prefix,;t t
+s, at prefix@,$prefix,;t t
+s, at program_transform_name@,$program_transform_name,;t t
+s, at bindir@,$bindir,;t t
+s, at sbindir@,$sbindir,;t t
+s, at libexecdir@,$libexecdir,;t t
+s, at datadir@,$datadir,;t t
+s, at sysconfdir@,$sysconfdir,;t t
+s, at sharedstatedir@,$sharedstatedir,;t t
+s, at localstatedir@,$localstatedir,;t t
+s, at libdir@,$libdir,;t t
+s, at includedir@,$includedir,;t t
+s, at oldincludedir@,$oldincludedir,;t t
+s, at infodir@,$infodir,;t t
+s, at mandir@,$mandir,;t t
+s, at build_alias@,$build_alias,;t t
+s, at host_alias@,$host_alias,;t t
+s, at target_alias@,$target_alias,;t t
+s, at DEFS@,$DEFS,;t t
+s, at ECHO_C@,$ECHO_C,;t t
+s, at ECHO_N@,$ECHO_N,;t t
+s, at ECHO_T@,$ECHO_T,;t t
+s, at LIBS@,$LIBS,;t t
+s, at build@,$build,;t t
+s, at build_cpu@,$build_cpu,;t t
+s, at build_vendor@,$build_vendor,;t t
+s, at build_os@,$build_os,;t t
+s, at host@,$host,;t t
+s, at host_cpu@,$host_cpu,;t t
+s, at host_vendor@,$host_vendor,;t t
+s, at host_os@,$host_os,;t t
+s, at target@,$target,;t t
+s, at target_cpu@,$target_cpu,;t t
+s, at target_vendor@,$target_vendor,;t t
+s, at target_os@,$target_os,;t t
+s, at INSTALL_PROGRAM@,$INSTALL_PROGRAM,;t t
+s, at INSTALL_SCRIPT@,$INSTALL_SCRIPT,;t t
+s, at INSTALL_DATA@,$INSTALL_DATA,;t t
+s, at CYGPATH_W@,$CYGPATH_W,;t t
+s, at PACKAGE@,$PACKAGE,;t t
+s, at VERSION@,$VERSION,;t t
+s, at ACLOCAL@,$ACLOCAL,;t t
+s, at AUTOCONF@,$AUTOCONF,;t t
+s, at AUTOMAKE@,$AUTOMAKE,;t t
+s, at AUTOHEADER@,$AUTOHEADER,;t t
+s, at MAKEINFO@,$MAKEINFO,;t t
+s, at install_sh@,$install_sh,;t t
+s, at STRIP@,$STRIP,;t t
+s, at ac_ct_STRIP@,$ac_ct_STRIP,;t t
+s, at INSTALL_STRIP_PROGRAM@,$INSTALL_STRIP_PROGRAM,;t t
+s, at mkdir_p@,$mkdir_p,;t t
+s, at AWK@,$AWK,;t t
+s, at SET_MAKE@,$SET_MAKE,;t t
+s, at am__leading_dot@,$am__leading_dot,;t t
+s, at AMTAR@,$AMTAR,;t t
+s, at am__tar@,$am__tar,;t t
+s, at am__untar@,$am__untar,;t t
+s, at JAS_MAJOR_VERSION@,$JAS_MAJOR_VERSION,;t t
+s, at JAS_MINOR_VERSION@,$JAS_MINOR_VERSION,;t t
+s, at JAS_MICRO_VERSION@,$JAS_MICRO_VERSION,;t t
+s, at JAS_VERSION@,$JAS_VERSION,;t t
+s, at JAS_RPM_RELEASE@,$JAS_RPM_RELEASE,;t t
+s, at LT_RELEASE@,$LT_RELEASE,;t t
+s, at LT_CURRENT@,$LT_CURRENT,;t t
+s, at LT_REVISION@,$LT_REVISION,;t t
+s, at LT_AGE@,$LT_AGE,;t t
+s, at CC@,$CC,;t t
+s, at CFLAGS@,$CFLAGS,;t t
+s, at LDFLAGS@,$LDFLAGS,;t t
+s, at CPPFLAGS@,$CPPFLAGS,;t t
+s, at ac_ct_CC@,$ac_ct_CC,;t t
+s, at EXEEXT@,$EXEEXT,;t t
+s, at OBJEXT@,$OBJEXT,;t t
+s, at DEPDIR@,$DEPDIR,;t t
+s, at am__include@,$am__include,;t t
+s, at am__quote@,$am__quote,;t t
+s, at AMDEP_TRUE@,$AMDEP_TRUE,;t t
+s, at AMDEP_FALSE@,$AMDEP_FALSE,;t t
+s, at AMDEPBACKSLASH@,$AMDEPBACKSLASH,;t t
+s, at CCDEPMODE@,$CCDEPMODE,;t t
+s, at am__fastdepCC_TRUE@,$am__fastdepCC_TRUE,;t t
+s, at am__fastdepCC_FALSE@,$am__fastdepCC_FALSE,;t t
+s, at RANLIB@,$RANLIB,;t t
+s, at ac_ct_RANLIB@,$ac_ct_RANLIB,;t t
+s, at SED@,$SED,;t t
+s, at EGREP@,$EGREP,;t t
+s, at LN_S@,$LN_S,;t t
+s, at ECHO@,$ECHO,;t t
+s, at AR@,$AR,;t t
+s, at ac_ct_AR@,$ac_ct_AR,;t t
+s, at CPP@,$CPP,;t t
+s, at CXX@,$CXX,;t t
+s, at CXXFLAGS@,$CXXFLAGS,;t t
+s, at ac_ct_CXX@,$ac_ct_CXX,;t t
+s, at CXXDEPMODE@,$CXXDEPMODE,;t t
+s, at am__fastdepCXX_TRUE@,$am__fastdepCXX_TRUE,;t t
+s, at am__fastdepCXX_FALSE@,$am__fastdepCXX_FALSE,;t t
+s, at CXXCPP@,$CXXCPP,;t t
+s, at F77@,$F77,;t t
+s, at FFLAGS@,$FFLAGS,;t t
+s, at ac_ct_F77@,$ac_ct_F77,;t t
+s, at LIBTOOL@,$LIBTOOL,;t t
+s, at X_CFLAGS@,$X_CFLAGS,;t t
+s, at X_PRE_LIBS@,$X_PRE_LIBS,;t t
+s, at X_LIBS@,$X_LIBS,;t t
+s, at X_EXTRA_LIBS@,$X_EXTRA_LIBS,;t t
+s, at HAVE_LIBJPEG_TRUE@,$HAVE_LIBJPEG_TRUE,;t t
+s, at HAVE_LIBJPEG_FALSE@,$HAVE_LIBJPEG_FALSE,;t t
+s, at HAVE_OPENGL_TRUE@,$HAVE_OPENGL_TRUE,;t t
+s, at HAVE_OPENGL_FALSE@,$HAVE_OPENGL_FALSE,;t t
+s, at OPENGL_LIBS@,$OPENGL_LIBS,;t t
+s, at LIBOBJS@,$LIBOBJS,;t t
+s, at LTLIBOBJS@,$LTLIBOBJS,;t t
+CEOF
+
+_ACEOF
+
+ cat >>$CONFIG_STATUS <<\_ACEOF
+ # Split the substitutions into bite-sized pieces for seds with
+ # small command number limits, like on Digital OSF/1 and HP-UX.
+ ac_max_sed_lines=48
+ ac_sed_frag=1 # Number of current file.
+ ac_beg=1 # First line for current file.
+ ac_end=$ac_max_sed_lines # Line after last line for current file.
+ ac_more_lines=:
+ ac_sed_cmds=
+ while $ac_more_lines; do
+ if test $ac_beg -gt 1; then
+ sed "1,${ac_beg}d; ${ac_end}q" $tmp/subs.sed >$tmp/subs.frag
+ else
+ sed "${ac_end}q" $tmp/subs.sed >$tmp/subs.frag
+ fi
+ if test ! -s $tmp/subs.frag; then
+ ac_more_lines=false
+ else
+ # The purpose of the label and of the branching condition is to
+ # speed up the sed processing (if there are no `@' at all, there
+ # is no need to browse any of the substitutions).
+ # These are the two extra sed commands mentioned above.
+ (echo ':t
+ /@[a-zA-Z_][a-zA-Z_0-9]*@/!b' && cat $tmp/subs.frag) >$tmp/subs-$ac_sed_frag.sed
+ if test -z "$ac_sed_cmds"; then
+ ac_sed_cmds="sed -f $tmp/subs-$ac_sed_frag.sed"
+ else
+ ac_sed_cmds="$ac_sed_cmds | sed -f $tmp/subs-$ac_sed_frag.sed"
+ fi
+ ac_sed_frag=`expr $ac_sed_frag + 1`
+ ac_beg=$ac_end
+ ac_end=`expr $ac_end + $ac_max_sed_lines`
+ fi
+ done
+ if test -z "$ac_sed_cmds"; then
+ ac_sed_cmds=cat
+ fi
+fi # test -n "$CONFIG_FILES"
+
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+for ac_file in : $CONFIG_FILES; do test "x$ac_file" = x: && continue
+ # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
+ case $ac_file in
+ - | *:- | *:-:* ) # input from stdin
+ cat >$tmp/stdin
+ ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
+ ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
+ *:* ) ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
+ ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
+ * ) ac_file_in=$ac_file.in ;;
+ esac
+
+ # Compute @srcdir@, @top_srcdir@, and @INSTALL@ for subdirectories.
+ ac_dir=`(dirname "$ac_file") 2>/dev/null ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$ac_file" : 'X\(//\)[^/]' \| \
+ X"$ac_file" : 'X\(//\)$' \| \
+ X"$ac_file" : 'X\(/\)' \| \
+ . : '\(.\)' 2>/dev/null ||
+echo X"$ac_file" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+ /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+ /^X\(\/\/\)$/{ s//\1/; q; }
+ /^X\(\/\).*/{ s//\1/; q; }
+ s/.*/./; q'`
+ { if $as_mkdir_p; then
+ mkdir -p "$ac_dir"
+ else
+ as_dir="$ac_dir"
+ as_dirs=
+ while test ! -d "$as_dir"; do
+ as_dirs="$as_dir $as_dirs"
+ as_dir=`(dirname "$as_dir") 2>/dev/null ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$as_dir" : 'X\(//\)[^/]' \| \
+ X"$as_dir" : 'X\(//\)$' \| \
+ X"$as_dir" : 'X\(/\)' \| \
+ . : '\(.\)' 2>/dev/null ||
+echo X"$as_dir" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+ /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+ /^X\(\/\/\)$/{ s//\1/; q; }
+ /^X\(\/\).*/{ s//\1/; q; }
+ s/.*/./; q'`
+ done
+ test ! -n "$as_dirs" || mkdir $as_dirs
+ fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5
+echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;}
+ { (exit 1); exit 1; }; }; }
+
+ ac_builddir=.
+
+if test "$ac_dir" != .; then
+ ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+ # A "../" for each directory in $ac_dir_suffix.
+ ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'`
+else
+ ac_dir_suffix= ac_top_builddir=
+fi
+
+case $srcdir in
+ .) # No --srcdir option. We are building in place.
+ ac_srcdir=.
+ if test -z "$ac_top_builddir"; then
+ ac_top_srcdir=.
+ else
+ ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'`
+ fi ;;
+ [\\/]* | ?:[\\/]* ) # Absolute path.
+ ac_srcdir=$srcdir$ac_dir_suffix;
+ ac_top_srcdir=$srcdir ;;
+ *) # Relative path.
+ ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix
+ ac_top_srcdir=$ac_top_builddir$srcdir ;;
+esac
+
+# Do not use `cd foo && pwd` to compute absolute paths, because
+# the directories may not exist.
+case `pwd` in
+.) ac_abs_builddir="$ac_dir";;
+*)
+ case "$ac_dir" in
+ .) ac_abs_builddir=`pwd`;;
+ [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";;
+ *) ac_abs_builddir=`pwd`/"$ac_dir";;
+ esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_top_builddir=${ac_top_builddir}.;;
+*)
+ case ${ac_top_builddir}. in
+ .) ac_abs_top_builddir=$ac_abs_builddir;;
+ [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;;
+ *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;;
+ esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_srcdir=$ac_srcdir;;
+*)
+ case $ac_srcdir in
+ .) ac_abs_srcdir=$ac_abs_builddir;;
+ [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;;
+ *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;;
+ esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_top_srcdir=$ac_top_srcdir;;
+*)
+ case $ac_top_srcdir in
+ .) ac_abs_top_srcdir=$ac_abs_builddir;;
+ [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;;
+ *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;;
+ esac;;
+esac
+
+
+ case $INSTALL in
+ [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;;
+ *) ac_INSTALL=$ac_top_builddir$INSTALL ;;
+ esac
+
+ if test x"$ac_file" != x-; then
+ { echo "$as_me:$LINENO: creating $ac_file" >&5
+echo "$as_me: creating $ac_file" >&6;}
+ rm -f "$ac_file"
+ fi
+ # Let's still pretend it is `configure' which instantiates (i.e., don't
+ # use $as_me), people would be surprised to read:
+ # /* config.h. Generated by config.status. */
+ if test x"$ac_file" = x-; then
+ configure_input=
+ else
+ configure_input="$ac_file. "
+ fi
+ configure_input=$configure_input"Generated from `echo $ac_file_in |
+ sed 's,.*/,,'` by configure."
+
+ # First look for the input files in the build tree, otherwise in the
+ # src tree.
+ ac_file_inputs=`IFS=:
+ for f in $ac_file_in; do
+ case $f in
+ -) echo $tmp/stdin ;;
+ [\\/$]*)
+ # Absolute (can't be DOS-style, as IFS=:)
+ test -f "$f" || { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
+echo "$as_me: error: cannot find input file: $f" >&2;}
+ { (exit 1); exit 1; }; }
+ echo "$f";;
+ *) # Relative
+ if test -f "$f"; then
+ # Build tree
+ echo "$f"
+ elif test -f "$srcdir/$f"; then
+ # Source tree
+ echo "$srcdir/$f"
+ else
+ # /dev/null tree
+ { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
+echo "$as_me: error: cannot find input file: $f" >&2;}
+ { (exit 1); exit 1; }; }
+ fi;;
+ esac
+ done` || { (exit 1); exit 1; }
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+ sed "$ac_vpsub
+$extrasub
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s, at configure_input@,$configure_input,;t t
+s, at srcdir@,$ac_srcdir,;t t
+s, at abs_srcdir@,$ac_abs_srcdir,;t t
+s, at top_srcdir@,$ac_top_srcdir,;t t
+s, at abs_top_srcdir@,$ac_abs_top_srcdir,;t t
+s, at builddir@,$ac_builddir,;t t
+s, at abs_builddir@,$ac_abs_builddir,;t t
+s, at top_builddir@,$ac_top_builddir,;t t
+s, at abs_top_builddir@,$ac_abs_top_builddir,;t t
+s, at INSTALL@,$ac_INSTALL,;t t
+" $ac_file_inputs | (eval "$ac_sed_cmds") >$tmp/out
+ rm -f $tmp/stdin
+ if test x"$ac_file" != x-; then
+ mv $tmp/out $ac_file
+ else
+ cat $tmp/out
+ rm -f $tmp/out
+ fi
+
+done
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+
+#
+# CONFIG_HEADER section.
+#
+
+# These sed commands are passed to sed as "A NAME B NAME C VALUE D", where
+# NAME is the cpp macro being defined and VALUE is the value it is being given.
+#
+# ac_d sets the value in "#define NAME VALUE" lines.
+ac_dA='s,^\([ ]*\)#\([ ]*define[ ][ ]*\)'
+ac_dB='[ ].*$,\1#\2'
+ac_dC=' '
+ac_dD=',;t'
+# ac_u turns "#undef NAME" without trailing blanks into "#define NAME VALUE".
+ac_uA='s,^\([ ]*\)#\([ ]*\)undef\([ ][ ]*\)'
+ac_uB='$,\1#\2define\3'
+ac_uC=' '
+ac_uD=',;t'
+
+for ac_file in : $CONFIG_HEADERS; do test "x$ac_file" = x: && continue
+ # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
+ case $ac_file in
+ - | *:- | *:-:* ) # input from stdin
+ cat >$tmp/stdin
+ ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
+ ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
+ *:* ) ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
+ ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
+ * ) ac_file_in=$ac_file.in ;;
+ esac
+
+ test x"$ac_file" != x- && { echo "$as_me:$LINENO: creating $ac_file" >&5
+echo "$as_me: creating $ac_file" >&6;}
+
+ # First look for the input files in the build tree, otherwise in the
+ # src tree.
+ ac_file_inputs=`IFS=:
+ for f in $ac_file_in; do
+ case $f in
+ -) echo $tmp/stdin ;;
+ [\\/$]*)
+ # Absolute (can't be DOS-style, as IFS=:)
+ test -f "$f" || { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
+echo "$as_me: error: cannot find input file: $f" >&2;}
+ { (exit 1); exit 1; }; }
+ # Do quote $f, to prevent DOS paths from being IFS'd.
+ echo "$f";;
+ *) # Relative
+ if test -f "$f"; then
+ # Build tree
+ echo "$f"
+ elif test -f "$srcdir/$f"; then
+ # Source tree
+ echo "$srcdir/$f"
+ else
+ # /dev/null tree
+ { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
+echo "$as_me: error: cannot find input file: $f" >&2;}
+ { (exit 1); exit 1; }; }
+ fi;;
+ esac
+ done` || { (exit 1); exit 1; }
+ # Remove the trailing spaces.
+ sed 's/[ ]*$//' $ac_file_inputs >$tmp/in
+
+_ACEOF
+
+# Transform confdefs.h into two sed scripts, `conftest.defines' and
+# `conftest.undefs', that substitutes the proper values into
+# config.h.in to produce config.h. The first handles `#define'
+# templates, and the second `#undef' templates.
+# And first: Protect against being on the right side of a sed subst in
+# config.status. Protect against being in an unquoted here document
+# in config.status.
+rm -f conftest.defines conftest.undefs
+# Using a here document instead of a string reduces the quoting nightmare.
+# Putting comments in sed scripts is not portable.
+#
+# `end' is used to avoid that the second main sed command (meant for
+# 0-ary CPP macros) applies to n-ary macro definitions.
+# See the Autoconf documentation for `clear'.
+cat >confdef2sed.sed <<\_ACEOF
+s/[\\&,]/\\&/g
+s,[\\$`],\\&,g
+t clear
+: clear
+s,^[ ]*#[ ]*define[ ][ ]*\([^ (][^ (]*\)\(([^)]*)\)[ ]*\(.*\)$,${ac_dA}\1${ac_dB}\1\2${ac_dC}\3${ac_dD},gp
+t end
+s,^[ ]*#[ ]*define[ ][ ]*\([^ ][^ ]*\)[ ]*\(.*\)$,${ac_dA}\1${ac_dB}\1${ac_dC}\2${ac_dD},gp
+: end
+_ACEOF
+# If some macros were called several times there might be several times
+# the same #defines, which is useless. Nevertheless, we may not want to
+# sort them, since we want the *last* AC-DEFINE to be honored.
+uniq confdefs.h | sed -n -f confdef2sed.sed >conftest.defines
+sed 's/ac_d/ac_u/g' conftest.defines >conftest.undefs
+rm -f confdef2sed.sed
+
+# This sed command replaces #undef with comments. This is necessary, for
+# example, in the case of _POSIX_SOURCE, which is predefined and required
+# on some systems where configure will not decide to define it.
+cat >>conftest.undefs <<\_ACEOF
+s,^[ ]*#[ ]*undef[ ][ ]*[a-zA-Z_][a-zA-Z_0-9]*,/* & */,
+_ACEOF
+
+# Break up conftest.defines because some shells have a limit on the size
+# of here documents, and old seds have small limits too (100 cmds).
+echo ' # Handle all the #define templates only if necessary.' >>$CONFIG_STATUS
+echo ' if grep "^[ ]*#[ ]*define" $tmp/in >/dev/null; then' >>$CONFIG_STATUS
+echo ' # If there are no defines, we may have an empty if/fi' >>$CONFIG_STATUS
+echo ' :' >>$CONFIG_STATUS
+rm -f conftest.tail
+while grep . conftest.defines >/dev/null
+do
+ # Write a limited-size here document to $tmp/defines.sed.
+ echo ' cat >$tmp/defines.sed <<CEOF' >>$CONFIG_STATUS
+ # Speed up: don't consider the non `#define' lines.
+ echo '/^[ ]*#[ ]*define/!b' >>$CONFIG_STATUS
+ # Work around the forget-to-reset-the-flag bug.
+ echo 't clr' >>$CONFIG_STATUS
+ echo ': clr' >>$CONFIG_STATUS
+ sed ${ac_max_here_lines}q conftest.defines >>$CONFIG_STATUS
+ echo 'CEOF
+ sed -f $tmp/defines.sed $tmp/in >$tmp/out
+ rm -f $tmp/in
+ mv $tmp/out $tmp/in
+' >>$CONFIG_STATUS
+ sed 1,${ac_max_here_lines}d conftest.defines >conftest.tail
+ rm -f conftest.defines
+ mv conftest.tail conftest.defines
+done
+rm -f conftest.defines
+echo ' fi # grep' >>$CONFIG_STATUS
+echo >>$CONFIG_STATUS
+
+# Break up conftest.undefs because some shells have a limit on the size
+# of here documents, and old seds have small limits too (100 cmds).
+echo ' # Handle all the #undef templates' >>$CONFIG_STATUS
+rm -f conftest.tail
+while grep . conftest.undefs >/dev/null
+do
+ # Write a limited-size here document to $tmp/undefs.sed.
+ echo ' cat >$tmp/undefs.sed <<CEOF' >>$CONFIG_STATUS
+ # Speed up: don't consider the non `#undef'
+ echo '/^[ ]*#[ ]*undef/!b' >>$CONFIG_STATUS
+ # Work around the forget-to-reset-the-flag bug.
+ echo 't clr' >>$CONFIG_STATUS
+ echo ': clr' >>$CONFIG_STATUS
+ sed ${ac_max_here_lines}q conftest.undefs >>$CONFIG_STATUS
+ echo 'CEOF
+ sed -f $tmp/undefs.sed $tmp/in >$tmp/out
+ rm -f $tmp/in
+ mv $tmp/out $tmp/in
+' >>$CONFIG_STATUS
+ sed 1,${ac_max_here_lines}d conftest.undefs >conftest.tail
+ rm -f conftest.undefs
+ mv conftest.tail conftest.undefs
+done
+rm -f conftest.undefs
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+ # Let's still pretend it is `configure' which instantiates (i.e., don't
+ # use $as_me), people would be surprised to read:
+ # /* config.h. Generated by config.status. */
+ if test x"$ac_file" = x-; then
+ echo "/* Generated by configure. */" >$tmp/config.h
+ else
+ echo "/* $ac_file. Generated by configure. */" >$tmp/config.h
+ fi
+ cat $tmp/in >>$tmp/config.h
+ rm -f $tmp/in
+ if test x"$ac_file" != x-; then
+ if diff $ac_file $tmp/config.h >/dev/null 2>&1; then
+ { echo "$as_me:$LINENO: $ac_file is unchanged" >&5
+echo "$as_me: $ac_file is unchanged" >&6;}
+ else
+ ac_dir=`(dirname "$ac_file") 2>/dev/null ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$ac_file" : 'X\(//\)[^/]' \| \
+ X"$ac_file" : 'X\(//\)$' \| \
+ X"$ac_file" : 'X\(/\)' \| \
+ . : '\(.\)' 2>/dev/null ||
+echo X"$ac_file" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+ /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+ /^X\(\/\/\)$/{ s//\1/; q; }
+ /^X\(\/\).*/{ s//\1/; q; }
+ s/.*/./; q'`
+ { if $as_mkdir_p; then
+ mkdir -p "$ac_dir"
+ else
+ as_dir="$ac_dir"
+ as_dirs=
+ while test ! -d "$as_dir"; do
+ as_dirs="$as_dir $as_dirs"
+ as_dir=`(dirname "$as_dir") 2>/dev/null ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$as_dir" : 'X\(//\)[^/]' \| \
+ X"$as_dir" : 'X\(//\)$' \| \
+ X"$as_dir" : 'X\(/\)' \| \
+ . : '\(.\)' 2>/dev/null ||
+echo X"$as_dir" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+ /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+ /^X\(\/\/\)$/{ s//\1/; q; }
+ /^X\(\/\).*/{ s//\1/; q; }
+ s/.*/./; q'`
+ done
+ test ! -n "$as_dirs" || mkdir $as_dirs
+ fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5
+echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;}
+ { (exit 1); exit 1; }; }; }
+
+ rm -f $ac_file
+ mv $tmp/config.h $ac_file
+ fi
+ else
+ cat $tmp/config.h
+ rm -f $tmp/config.h
+ fi
+# Compute $ac_file's index in $config_headers.
+_am_stamp_count=1
+for _am_header in $config_headers :; do
+ case $_am_header in
+ $ac_file | $ac_file:* )
+ break ;;
+ * )
+ _am_stamp_count=`expr $_am_stamp_count + 1` ;;
+ esac
+done
+echo "timestamp for $ac_file" >`(dirname $ac_file) 2>/dev/null ||
+$as_expr X$ac_file : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X$ac_file : 'X\(//\)[^/]' \| \
+ X$ac_file : 'X\(//\)$' \| \
+ X$ac_file : 'X\(/\)' \| \
+ . : '\(.\)' 2>/dev/null ||
+echo X$ac_file |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+ /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+ /^X\(\/\/\)$/{ s//\1/; q; }
+ /^X\(\/\).*/{ s//\1/; q; }
+ s/.*/./; q'`/stamp-h$_am_stamp_count
+done
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+
+#
+# CONFIG_COMMANDS section.
+#
+for ac_file in : $CONFIG_COMMANDS; do test "x$ac_file" = x: && continue
+ ac_dest=`echo "$ac_file" | sed 's,:.*,,'`
+ ac_source=`echo "$ac_file" | sed 's,[^:]*:,,'`
+ ac_dir=`(dirname "$ac_dest") 2>/dev/null ||
+$as_expr X"$ac_dest" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$ac_dest" : 'X\(//\)[^/]' \| \
+ X"$ac_dest" : 'X\(//\)$' \| \
+ X"$ac_dest" : 'X\(/\)' \| \
+ . : '\(.\)' 2>/dev/null ||
+echo X"$ac_dest" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+ /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+ /^X\(\/\/\)$/{ s//\1/; q; }
+ /^X\(\/\).*/{ s//\1/; q; }
+ s/.*/./; q'`
+ { if $as_mkdir_p; then
+ mkdir -p "$ac_dir"
+ else
+ as_dir="$ac_dir"
+ as_dirs=
+ while test ! -d "$as_dir"; do
+ as_dirs="$as_dir $as_dirs"
+ as_dir=`(dirname "$as_dir") 2>/dev/null ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$as_dir" : 'X\(//\)[^/]' \| \
+ X"$as_dir" : 'X\(//\)$' \| \
+ X"$as_dir" : 'X\(/\)' \| \
+ . : '\(.\)' 2>/dev/null ||
+echo X"$as_dir" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+ /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+ /^X\(\/\/\)$/{ s//\1/; q; }
+ /^X\(\/\).*/{ s//\1/; q; }
+ s/.*/./; q'`
+ done
+ test ! -n "$as_dirs" || mkdir $as_dirs
+ fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5
+echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;}
+ { (exit 1); exit 1; }; }; }
+
+ ac_builddir=.
+
+if test "$ac_dir" != .; then
+ ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+ # A "../" for each directory in $ac_dir_suffix.
+ ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'`
+else
+ ac_dir_suffix= ac_top_builddir=
+fi
+
+case $srcdir in
+ .) # No --srcdir option. We are building in place.
+ ac_srcdir=.
+ if test -z "$ac_top_builddir"; then
+ ac_top_srcdir=.
+ else
+ ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'`
+ fi ;;
+ [\\/]* | ?:[\\/]* ) # Absolute path.
+ ac_srcdir=$srcdir$ac_dir_suffix;
+ ac_top_srcdir=$srcdir ;;
+ *) # Relative path.
+ ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix
+ ac_top_srcdir=$ac_top_builddir$srcdir ;;
+esac
+
+# Do not use `cd foo && pwd` to compute absolute paths, because
+# the directories may not exist.
+case `pwd` in
+.) ac_abs_builddir="$ac_dir";;
+*)
+ case "$ac_dir" in
+ .) ac_abs_builddir=`pwd`;;
+ [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";;
+ *) ac_abs_builddir=`pwd`/"$ac_dir";;
+ esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_top_builddir=${ac_top_builddir}.;;
+*)
+ case ${ac_top_builddir}. in
+ .) ac_abs_top_builddir=$ac_abs_builddir;;
+ [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;;
+ *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;;
+ esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_srcdir=$ac_srcdir;;
+*)
+ case $ac_srcdir in
+ .) ac_abs_srcdir=$ac_abs_builddir;;
+ [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;;
+ *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;;
+ esac;;
+esac
+case $ac_abs_builddir in
+.) ac_abs_top_srcdir=$ac_top_srcdir;;
+*)
+ case $ac_top_srcdir in
+ .) ac_abs_top_srcdir=$ac_abs_builddir;;
+ [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;;
+ *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;;
+ esac;;
+esac
+
+
+ { echo "$as_me:$LINENO: executing $ac_dest commands" >&5
+echo "$as_me: executing $ac_dest commands" >&6;}
+ case $ac_dest in
+ depfiles ) test x"$AMDEP_TRUE" != x"" || for mf in $CONFIG_FILES; do
+ # Strip MF so we end up with the name of the file.
+ mf=`echo "$mf" | sed -e 's/:.*$//'`
+ # Check whether this is an Automake generated Makefile or not.
+ # We used to match only the files named `Makefile.in', but
+ # some people rename them; so instead we look at the file content.
+ # Grep'ing the first line is not enough: some people post-process
+ # each Makefile.in and add a new line on top of each file to say so.
+ # So let's grep whole file.
+ if grep '^#.*generated by automake' $mf > /dev/null 2>&1; then
+ dirpart=`(dirname "$mf") 2>/dev/null ||
+$as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$mf" : 'X\(//\)[^/]' \| \
+ X"$mf" : 'X\(//\)$' \| \
+ X"$mf" : 'X\(/\)' \| \
+ . : '\(.\)' 2>/dev/null ||
+echo X"$mf" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+ /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+ /^X\(\/\/\)$/{ s//\1/; q; }
+ /^X\(\/\).*/{ s//\1/; q; }
+ s/.*/./; q'`
+ else
+ continue
+ fi
+ # Extract the definition of DEPDIR, am__include, and am__quote
+ # from the Makefile without running `make'.
+ DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"`
+ test -z "$DEPDIR" && continue
+ am__include=`sed -n 's/^am__include = //p' < "$mf"`
+ test -z "am__include" && continue
+ am__quote=`sed -n 's/^am__quote = //p' < "$mf"`
+ # When using ansi2knr, U may be empty or an underscore; expand it
+ U=`sed -n 's/^U = //p' < "$mf"`
+ # Find all dependency output files, they are included files with
+ # $(DEPDIR) in their names. We invoke sed twice because it is the
+ # simplest approach to changing $(DEPDIR) to its actual value in the
+ # expansion.
+ for file in `sed -n "
+ s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \
+ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do
+ # Make sure the directory exists.
+ test -f "$dirpart/$file" && continue
+ fdir=`(dirname "$file") 2>/dev/null ||
+$as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$file" : 'X\(//\)[^/]' \| \
+ X"$file" : 'X\(//\)$' \| \
+ X"$file" : 'X\(/\)' \| \
+ . : '\(.\)' 2>/dev/null ||
+echo X"$file" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+ /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+ /^X\(\/\/\)$/{ s//\1/; q; }
+ /^X\(\/\).*/{ s//\1/; q; }
+ s/.*/./; q'`
+ { if $as_mkdir_p; then
+ mkdir -p $dirpart/$fdir
+ else
+ as_dir=$dirpart/$fdir
+ as_dirs=
+ while test ! -d "$as_dir"; do
+ as_dirs="$as_dir $as_dirs"
+ as_dir=`(dirname "$as_dir") 2>/dev/null ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$as_dir" : 'X\(//\)[^/]' \| \
+ X"$as_dir" : 'X\(//\)$' \| \
+ X"$as_dir" : 'X\(/\)' \| \
+ . : '\(.\)' 2>/dev/null ||
+echo X"$as_dir" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
+ /^X\(\/\/\)[^/].*/{ s//\1/; q; }
+ /^X\(\/\/\)$/{ s//\1/; q; }
+ /^X\(\/\).*/{ s//\1/; q; }
+ s/.*/./; q'`
+ done
+ test ! -n "$as_dirs" || mkdir $as_dirs
+ fi || { { echo "$as_me:$LINENO: error: cannot create directory $dirpart/$fdir" >&5
+echo "$as_me: error: cannot create directory $dirpart/$fdir" >&2;}
+ { (exit 1); exit 1; }; }; }
+
+ # echo "creating $dirpart/$file"
+ echo '# dummy' > "$dirpart/$file"
+ done
+done
+ ;;
+ esac
+done
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+
+{ (exit 0); exit 0; }
+_ACEOF
+chmod +x $CONFIG_STATUS
+ac_clean_files=$ac_clean_files_save
+
+
+# configure is writing to config.log, and then calls config.status.
+# config.status does its own redirection, appending to config.log.
+# Unfortunately, on DOS this fails, as config.log is still kept open
+# by configure, so config.status won't be able to write to it; its
+# output is simply discarded. So we exec the FD to /dev/null,
+# effectively closing config.log, so it can be properly (re)opened and
+# appended to by config.status. When coming back to configure, we
+# need to make the FD available again.
+if test "$no_create" != yes; then
+ ac_cs_success=:
+ ac_config_status_args=
+ test "$silent" = yes &&
+ ac_config_status_args="$ac_config_status_args --quiet"
+ exec 5>/dev/null
+ $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
+ exec 5>>config.log
+ # Use ||, not &&, to avoid exiting from the if with $? = 1, which
+ # would make configure fail if this is the last instruction.
+ $ac_cs_success || { (exit 1); exit 1; }
+fi
+
+
diff --git a/jasper-1.900.1-6ct/configure.ac b/jasper-1.900.1-6ct/configure.ac
new file mode 100644
index 0000000..9b53e0a
--- /dev/null
+++ b/jasper-1.900.1-6ct/configure.ac
@@ -0,0 +1,405 @@
+dnl ****************************************************************************
+dnl Copyright (c) 2001-2004 Michael David Adams.
+dnl All rights reserved.
+dnl
+dnl The complete licensing terms for this software can be found in the file
+dnl named "LICENSE" in this software distribution.
+dnl ****************************************************************************
+
+dnl The package name.
+define(AC_JAS_NAME, jasper)
+
+dnl ************************************************************
+dnl Package version information.
+dnl ************************************************************
+
+dnl The major, minor, and micro version numbers of the package.
+define(AC_JAS_MAJOR_VERSION, 1)
+define(AC_JAS_MINOR_VERSION, 900)
+define(AC_JAS_MICRO_VERSION, 1)
+
+dnl The package version.
+define(AC_JAS_VERSION,
+ AC_JAS_MAJOR_VERSION.AC_JAS_MINOR_VERSION.AC_JAS_MICRO_VERSION)
+
+dnl ************************************************************
+dnl RPM version information.
+dnl ************************************************************
+
+define(AC_JAS_RPM_RELEASE, 1)
+
+dnl ************************************************************
+dnl Dynamically-linked library version information (for Libtool).
+dnl ************************************************************
+
+dnl Guidelines for updating these definitions:
+dnl 1) If the library source code has changed at all since the last update,
+dnl then increment REVISION.
+dnl 2) If any interfaces have been added, removed, or changed since the last
+dnl update, increment CURRENT, and set REVISION to zero.
+dnl 3) If any interfaces have been added since the last public release, then
+dnl increment AGE.
+dnl 4) If any interfaces have been removed since the last public release, then
+dnl set AGE to zero.
+
+dnl The most recent interface number that this library implements.
+define(AC_JAS_LT_CURRENT, 1)
+
+dnl The implementation number of the current interface.
+define(AC_JAS_LT_REVISION, 0)
+
+dnl The difference between the newest and oldest interfaces that this library
+dnl implements. In other words, the library implements all of the interface
+dnl numbers in the range from current - age to current.
+define(AC_JAS_LT_AGE, 0)
+
+dnl The release number of the library.
+define(AC_JAS_LT_RELEASE, AC_JAS_MAJOR_VERSION.AC_JAS_MINOR_VERSION)
+
+dnl ****************************************************************************
+dnl NOTHING BELOW THIS LINE SHOULD REQUIRE MODIFICATION (IDEALLY :-)
+dnl ****************************************************************************
+
+dnl Initialize autoconf.
+AC_INIT(AC_JAS_NAME, AC_JAS_VERSION)
+AC_PREREQ(2.59)
+AC_CONFIG_SRCDIR(README)
+dnl Note: Avoid the temptation to call the auxiliary directory "aux" because
+dnl Microsoft Windows will barf if you try to use "aux" as a directory name. :-(
+AC_CONFIG_AUX_DIR(acaux)
+
+# Detect the canonical host and target build environment.
+# Note: This precedes automake initialization to avoid warnings.
+AC_CANONICAL_BUILD
+AC_CANONICAL_HOST
+AC_CANONICAL_TARGET
+
+# Initialize automake.
+AM_INIT_AUTOMAKE
+
+# Initialize version information parameters.
+JAS_MAJOR_VERSION=AC_JAS_MAJOR_VERSION
+JAS_MINOR_VERSION=AC_JAS_MINOR_VERSION
+JAS_MICRO_VERSION=AC_JAS_MICRO_VERSION
+JAS_VERSION=AC_JAS_VERSION
+AC_SUBST(JAS_MAJOR_VERSION)
+AC_SUBST(JAS_MINOR_VERSION)
+AC_SUBST(JAS_MICRO_VERSION)
+AC_SUBST(JAS_VERSION)
+AC_DEFINE_UNQUOTED(JAS_VERSION, "$JAS_VERSION")
+JAS_RPM_RELEASE=AC_JAS_RPM_RELEASE
+AC_SUBST(JAS_RPM_RELEASE)
+
+# Initialize version information for libtool.
+LT_RELEASE=AC_JAS_LT_RELEASE
+LT_CURRENT=AC_JAS_LT_CURRENT
+LT_REVISION=AC_JAS_LT_REVISION
+LT_AGE=AC_JAS_LT_AGE
+AC_SUBST(LT_RELEASE)
+AC_SUBST(LT_CURRENT)
+AC_SUBST(LT_REVISION)
+AC_SUBST(LT_AGE)
+
+# Indicate a configure-based build is being used.
+AC_DEFINE(JAS_CONFIGURE)
+
+############################################################
+# Configuration header file.
+############################################################
+
+AH_TEMPLATE([DEBUG_OVERFLOW], [Debugging overflow detection])
+AH_TEMPLATE([JAS_CONFIGURE], [JasPer configure])
+AH_TEMPLATE([JAS_VERSION], [JasPer version])
+AH_TEMPLATE([DEBUG_MEMALLOC], [Debugging memory allocator])
+AH_TEMPLATE([DEBUG], [Extra debugging support])
+AH_TEMPLATE([HAVE_VLA], [Have variable length arrays])
+
+AH_TOP([
+/* Avoid problems due to multiple inclusion. */
+#ifndef JAS_CONFIG_H
+#define JAS_CONFIG_H
+
+/* This preprocessor symbol identifies the version of JasPer. */
+#undef JAS_VERSION
+/* If configure is being used, this symbol will be defined automatically
+ at this point in the configuration header file. */
+
+/* The preprocessor symbol JAS_WIN_MSVC_BUILD should not be defined
+ unless the JasPer software is being built under Microsoft Windows
+ using Microsoft Visual C. */
+#if !defined(JAS_WIN_MSVC_BUILD)
+/* A configure-based build is being used. */
+
+])
+
+AH_BOTTOM([
+#else
+/* A configure-based build is not being used. */
+#include <jasper/jas_config2.h>
+#endif
+
+#endif
+])
+
+############################################################
+# Checks for programs.
+############################################################
+
+AC_PROG_CC
+AC_PROG_INSTALL
+AC_PROG_RANLIB
+# AC_PROG_AWK
+# AC_PROG_CPP
+# AC_PROG_LN_S
+
+AM_DISABLE_SHARED
+AC_PROG_LIBTOOL
+
+AC_PATH_XTRA
+
+AC_MSG_CHECKING(whether variable-length arrays are supported)
+AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[
+ int n; int foo[n];
+]])],[AC_MSG_RESULT(yes); AC_DEFINE(HAVE_VLA)],[AC_MSG_RESULT(no)])
+
+dnl AC_TRY_COMPILE is obsolete
+dnl AC_TRY_COMPILE([], [
+dnl int n; int foo[n];
+dnl ], [AC_MSG_RESULT(yes); AC_DEFINE(HAVE_VLA)], AC_MSG_RESULT(no))
+
+############################################################
+# Check for the IJG JPEG library.
+############################################################
+
+# Allow the user to explicitly specify whether the JPEG library is present.
+AC_ARG_ENABLE(libjpeg,
+[ --disable-libjpeg Force the IJG JPEG library to be ignored],
+[
+case "${enableval}" in
+yes)
+ ENABLE_LIBJPEG=yes;;
+no)
+ ENABLE_LIBJPEG=no;;
+*)
+ AC_MSG_ERROR(bad value ${enableval} for --disable-libjpeg)
+ ;;
+esac
+], ENABLE_LIBJPEG=yes)
+
+HAVE_LIBJPEG=no
+if test $ENABLE_LIBJPEG = yes; then
+ # Check for the JPEG library.
+ AC_CHECK_LIB(jpeg, jpeg_destroy, HAVE_LIBJPEG=yes, HAVE_LIBJPEG=no)
+ if test $HAVE_LIBJPEG = yes; then
+ LIBS="$LIBS -ljpeg"
+ fi
+fi
+AM_CONDITIONAL(HAVE_LIBJPEG, test $HAVE_LIBJPEG = yes)
+
+############################################################
+# Check for OpenGL libraries.
+############################################################
+
+AC_ARG_WITH(glut-include-dir,
+[ --with-glut-include-dir=DIR Set GLUT include directory.],
+[
+ case "$withval" in
+ /*)
+ CFLAGS="$CFLAGS -I$withval"
+ CPPFLAGS="$CPPFLAGS -I$withval";;
+ *)
+ AC_MSG_ERROR(--with-glut-include-dir requires absolute path)
+ ;;
+ esac
+],
+)
+AC_ARG_WITH(glut-lib-dir,
+[ --with-glut-lib-dir=DIR Set GLUT library directory.],
+[
+ case "$withval" in
+ /*)
+ LIBS="$LIBS -L$withval";;
+ *)
+ AC_MSG_ERROR(--with-glut-lib-dir requires absolute path)
+ ;;
+ esac
+],
+)
+
+AC_ARG_ENABLE(opengl,
+[ --disable-opengl Disable use of OpenGL. ],
+[
+ case "$enableval" in
+ yes)
+ ENABLE_OPENGL=yes;;
+ no)
+ ENABLE_OPENGL=no;;
+ *)
+ AC_MSG_ERROR(bad value ${enableval} for --disable-libjpeg)
+ ;;
+ esac
+],
+ENABLE_OPENGL=yes)
+
+HAVE_OPENGL=no
+OPENGL_LIBS=""
+if test $ENABLE_OPENGL = yes; then
+ if test $HAVE_OPENGL = no; then
+ TMPLIBS="-lglut -lGL -lGLU $X_PRE_LIBS -lX11 -lXmu -lXi -lXext -lXt $X_EXTRA_LIBS $X_LIBS"
+ AC_CHECK_LIB(glut, glutInit, [HAVE_OPENGL=yes;
+ OPENGL_LIBS=$TMPLIBS], HAVE_OPENGL=no, $TMPLIBS)
+ fi
+ AC_CHECK_HEADER(GL/glut.h,, [HAVE_OPENGL=no; OPENGL_LIBS="";])
+fi
+
+AM_CONDITIONAL(HAVE_OPENGL, test $HAVE_OPENGL = yes)
+AC_SUBST(OPENGL_LIBS)
+AC_MSG_CHECKING([whether OpenGL libraries and headers were detected])
+AC_MSG_RESULT($HAVE_OPENGL)
+
+############################################################
+# Check for other libraries.
+############################################################
+
+# Check for the math library.
+AC_CHECK_LIB(m, main)
+
+############################################################
+# Check for header files.
+############################################################
+
+AC_HEADER_STDC
+AC_CHECK_HEADERS(fcntl.h limits.h unistd.h stdint.h stdbool.h io.h windows.h sys/types.h sys/time.h stdlib.h stddef.h)
+
+############################################################
+# Check for typedefs, structures, and compiler characteristics.
+############################################################
+
+AC_C_CONST
+AC_C_INLINE
+AC_TYPE_SIZE_T
+dnl AC_CHECK_TYPE(bool, int)
+AC_CHECK_TYPE(uchar, unsigned char)
+AC_CHECK_TYPE(ushort, unsigned short)
+AC_CHECK_TYPE(uint, unsigned int)
+AC_CHECK_TYPE(ulong, unsigned long)
+AC_CHECK_TYPE(longlong, long long)
+AC_CHECK_TYPE(ulonglong, unsigned long long)
+AC_CHECK_TYPE(ssize_t, int)
+AC_CHECK_FUNCS(gettimeofday)
+AC_CHECK_FUNCS(getrusage)
+
+############################################################
+# Checks for library functions.
+############################################################
+
+AC_FUNC_VPRINTF
+
+############################################################
+# Enable/disable special memory allocator for debugging.
+############################################################
+
+AC_ARG_ENABLE(dmalloc,
+[ --enable-dmalloc use special memory allocator for debugging],
+[
+case "${enableval}" in
+yes)
+ AC_DEFINE(DEBUG_MEMALLOC)
+ ;;
+no)
+ ;;
+*)
+ AC_MSG_ERROR(bad value ${enableval} for --enable-dmalloc)
+ ;;
+esac
+], )
+
+############################################################
+# Enable/disable extra code for debugging.
+############################################################
+
+AC_ARG_ENABLE(debug,
+[ --enable-debug add extra code for debugging],
+[
+case "${enableval}" in
+yes)
+ debug=yes
+ AC_DEFINE(DEBUG)
+ AC_DEFINE(DEBUG_OVERFLOW)
+ if test "$GCC" = yes; then
+ CFLAGS="-g -O0"
+ fi
+ ;;
+no)
+ debug=no
+ ;;
+*)
+ AC_MSG_ERROR(bad value ${enableval} for --enable-debug)
+ ;;
+esac
+], [debug=no])
+
+if test "$GCC" = yes; then
+ CFLAGS="$CFLAGS"
+ #CFLAGS="$CFLAGS -std=c99"
+ #CFLAGS="$CFLAGS -pedantic"
+ #CFLAGS="$CFLAGS -pedantic-errors"
+ #CFLAGS="$CFLAGS -W -Wall -Wno-long-long -Wformat -Wmissing-prototypes -Wstrict-prototypes"
+fi
+
+############################################################
+# Extra stuff for research purposes.
+############################################################
+
+AC_ARG_ENABLE(special0,
+[ --enable-special0 enable something],
+[
+case "${enableval}" in
+yes)
+ if test "$GCC" = yes; then
+ CFLAGS="-g -O0"
+ fi
+ ;;
+no)
+ ;;
+*)
+ AC_MSG_ERROR(bad value ${enableval} for --enable-special0)
+ ;;
+esac
+], [])
+
+if test -n "$EXTRACFLAGS"; then
+ CFLAGS="$CFLAGS $EXTRACFLAGS"
+fi
+
+############################################################
+# Generate the configuration header file.
+############################################################
+
+AC_CONFIG_HEADERS([src/libjasper/include/jasper/jas_config.h])
+
+############################################################
+# Generate the makefiles.
+############################################################
+
+AC_CONFIG_FILES([
+Makefile
+src/Makefile
+src/appl/Makefile
+src/libjasper/Makefile
+src/libjasper/base/Makefile
+src/libjasper/bmp/Makefile
+src/libjasper/include/Makefile
+src/libjasper/include/jasper/Makefile
+src/libjasper/jp2/Makefile
+src/libjasper/jpc/Makefile
+src/libjasper/jpg/Makefile
+src/libjasper/mif/Makefile
+src/libjasper/pgx/Makefile
+src/libjasper/pnm/Makefile
+src/libjasper/ras/Makefile
+src/msvc/Makefile
+jasper.spec
+])
+AC_OUTPUT
+
diff --git a/jasper-1.900.1-6ct/data/colorprofiles/README b/jasper-1.900.1-6ct/data/colorprofiles/README
new file mode 100644
index 0000000..a9be7b0
--- /dev/null
+++ b/jasper-1.900.1-6ct/data/colorprofiles/README
@@ -0,0 +1,18 @@
+This directory contains a number of ICC color profiles.
+
+Some of the more important profiles include:
+
+sgray.icm
+ JPEG-2000 JP2 standard gray enumerated color space
+ This profile was provided by Scott Houchin of Kodak.
+
+srgb.icm
+ JPEG-2000 JP2 standard RGB (i.e., sRGB) enumerated color space
+ This profile was provided by Scott Houchin of Kodak.
+
+sycc.icm
+ JPEG-2000 JP2 standard YCC enumerated color space
+ This profile was provided by Jack Holm of Hewlett Packard.
+
+A number of other profiles in this directory were provided by Scott
+Houchin of Kodak.
diff --git a/jasper-1.900.1-6ct/data/colorprofiles/erimm.icm b/jasper-1.900.1-6ct/data/colorprofiles/erimm.icm
new file mode 100644
index 0000000..956fa54
Binary files /dev/null and b/jasper-1.900.1-6ct/data/colorprofiles/erimm.icm differ
diff --git a/jasper-1.900.1-6ct/data/colorprofiles/esrgb.icm b/jasper-1.900.1-6ct/data/colorprofiles/esrgb.icm
new file mode 100644
index 0000000..28f9a0b
Binary files /dev/null and b/jasper-1.900.1-6ct/data/colorprofiles/esrgb.icm differ
diff --git a/jasper-1.900.1-6ct/data/colorprofiles/esrgbgrey.icm b/jasper-1.900.1-6ct/data/colorprofiles/esrgbgrey.icm
new file mode 100644
index 0000000..92e5fde
Binary files /dev/null and b/jasper-1.900.1-6ct/data/colorprofiles/esrgbgrey.icm differ
diff --git a/jasper-1.900.1-6ct/data/colorprofiles/grey.icm b/jasper-1.900.1-6ct/data/colorprofiles/grey.icm
new file mode 100644
index 0000000..3ea8aed
Binary files /dev/null and b/jasper-1.900.1-6ct/data/colorprofiles/grey.icm differ
diff --git a/jasper-1.900.1-6ct/data/colorprofiles/greyromm.icm b/jasper-1.900.1-6ct/data/colorprofiles/greyromm.icm
new file mode 100644
index 0000000..fb85fcb
Binary files /dev/null and b/jasper-1.900.1-6ct/data/colorprofiles/greyromm.icm differ
diff --git a/jasper-1.900.1-6ct/data/colorprofiles/romm.icm b/jasper-1.900.1-6ct/data/colorprofiles/romm.icm
new file mode 100644
index 0000000..3145cff
Binary files /dev/null and b/jasper-1.900.1-6ct/data/colorprofiles/romm.icm differ
diff --git a/jasper-1.900.1-6ct/data/colorprofiles/sgray.icm b/jasper-1.900.1-6ct/data/colorprofiles/sgray.icm
new file mode 100644
index 0000000..aa3c808
Binary files /dev/null and b/jasper-1.900.1-6ct/data/colorprofiles/sgray.icm differ
diff --git a/jasper-1.900.1-6ct/data/colorprofiles/srgb.icm b/jasper-1.900.1-6ct/data/colorprofiles/srgb.icm
new file mode 100644
index 0000000..7f9d18d
Binary files /dev/null and b/jasper-1.900.1-6ct/data/colorprofiles/srgb.icm differ
diff --git a/jasper-1.900.1-6ct/data/colorprofiles/sycc.icm b/jasper-1.900.1-6ct/data/colorprofiles/sycc.icm
new file mode 100644
index 0000000..30ae7c1
Binary files /dev/null and b/jasper-1.900.1-6ct/data/colorprofiles/sycc.icm differ
diff --git a/jasper-1.900.1-6ct/data/images/README b/jasper-1.900.1-6ct/data/images/README
new file mode 100644
index 0000000..851b8d6
--- /dev/null
+++ b/jasper-1.900.1-6ct/data/images/README
@@ -0,0 +1,11 @@
+This directory contains numerous test images, stored in various formats.
+
+goldenears
+goldenears_gray
+ A picture taken at Golden Ears Provincial Park,
+ located near Maple Ridge, BC, Canada.
+
+stawamuschief
+stawamuschief_gray
+ A picture taken at Stawamus Chief Provincial Park,
+ located close to Squamish, BC, Canada.
diff --git a/jasper-1.900.1-6ct/data/images/example.mif b/jasper-1.900.1-6ct/data/images/example.mif
new file mode 100644
index 0000000..a3da788
--- /dev/null
+++ b/jasper-1.900.1-6ct/data/images/example.mif
@@ -0,0 +1,11 @@
+MIF
+component tlx=0 tly=0 sampperx=4 samppery=2 width=32 height=64 prec=8 sgnd=0
+component tlx=0 tly=0 sampperx=2 samppery=4 width=64 height=32 prec=8 sgnd=1
+end
+P5
+32 64
+255
+||||����������������������������|||������������������������������|�|�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������û�������������������û���������������Ü���������������û�������������Ü���������������� [...]
+64 32
+255
+||||������������������������������������������������������������|||��������������������������������������������������������������|�|������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ [...]
\ No newline at end of file
diff --git a/jasper-1.900.1-6ct/data/images/example.mif0 b/jasper-1.900.1-6ct/data/images/example.mif0
new file mode 100644
index 0000000..c29ce51
--- /dev/null
+++ b/jasper-1.900.1-6ct/data/images/example.mif0
@@ -0,0 +1,11 @@
+MIF
+
+# This is an example of a MIF file.
+# Comments begin with a hash symbol (i.e., '#') and proceed to the end of line.
+# The first four characters of a MIF file must be in order: M, I, F, linefeed.
+
+component tlx=0 tly=0 sampperx=4 samppery=2 width=32 height=64 prec=8 sgnd=0 data=goldenears.pgm
+component tlx=0 tly=0 sampperx=2 samppery=4 width=64 height=32 prec=8 sgnd=1 data=goldenears.pgm
+
+# This is the end of the header.
+end
diff --git a/jasper-1.900.1-6ct/data/images/feep.pnm b/jasper-1.900.1-6ct/data/images/feep.pnm
new file mode 100644
index 0000000..e3bdff1
--- /dev/null
+++ b/jasper-1.900.1-6ct/data/images/feep.pnm
@@ -0,0 +1,11 @@
+P1
+# feep.pbm
+24 7
+0 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 1 1 0 0 1 1 1 1 0 0 1 1 1 1 0
+0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0
+0 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 1 0
+0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0
+0 1 0 0 0 0 0 1 1 1 1 0 0 1 1 1 1 0 0 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
+
diff --git a/jasper-1.900.1-6ct/data/images/feep2.pnm b/jasper-1.900.1-6ct/data/images/feep2.pnm
new file mode 100644
index 0000000..bbd3968
--- /dev/null
+++ b/jasper-1.900.1-6ct/data/images/feep2.pnm
@@ -0,0 +1,11 @@
+P1
+# feep.pbm
+24 7
+000000000000000000000000
+011110011110011110011110 # 111111111111111111111111
+010000010000010000010010
+011100011100011100011110
+010000010000010000010000
+010000011110011110010000
+000000000000000000000000
+
diff --git a/jasper-1.900.1-6ct/data/images/goldenears.bmp b/jasper-1.900.1-6ct/data/images/goldenears.bmp
new file mode 100644
index 0000000..95f3c28
Binary files /dev/null and b/jasper-1.900.1-6ct/data/images/goldenears.bmp differ
diff --git a/jasper-1.900.1-6ct/data/images/goldenears.jpg b/jasper-1.900.1-6ct/data/images/goldenears.jpg
new file mode 100644
index 0000000..7c933a3
Binary files /dev/null and b/jasper-1.900.1-6ct/data/images/goldenears.jpg differ
diff --git a/jasper-1.900.1-6ct/data/images/goldenears.pnm b/jasper-1.900.1-6ct/data/images/goldenears.pnm
new file mode 100644
index 0000000..112712d
--- /dev/null
+++ b/jasper-1.900.1-6ct/data/images/goldenears.pnm
@@ -0,0 +1,292 @@
+P6
+128 96
+255
+V��\��a��`��g~�c��d��f��e��h��m��n��p��q��y���ҋ�֖�ٞ�ؚ�ؘ�ٙ�ס�ڡ�ڜ�ؚ�ؗ�ٌ�ؐ�ؐ�ؓ�ۉ�ۊ�ځ��|��y��}�܄����w���ۄ��y��y��x��y�ہ�߃�݈�ވ�ߐ�ߕ�ݝ�ߟ�ߥ�ޥ�ߪ�ਰयߜ�ަ�ެ�߮�ⰷ㭶ᱹ㳻ⱶⰺ䰸为䲻⳼崼㲾㰷⨶᧲⢱ߨ�㤮ᥲߞ�ݔ�ߕ�ߙ�����ߎ�߇�����߇�ބ��~�߀�߅�߅�݄���ߋ���߁��}�܁�݂�݃�݂�܅�݂�݀�݁�ۆ�܄�އ�܃�ڂ��~��}��|��|��z��z��|��y��z��w��Z��]��_��a��c��c��f��e��g��i��k��n��r��u��z�Ӈ�Ր�י�؞�؝�؛�٠�١�ٜ�ڝ�ڙ�ٛ�ڙ�ّ�ُ�ڋ�܈�ۈ�ۀ��{��}��}��~��}��{��}�ہ��|��}��}���݁�ކ�އ�݊�ߒ���ݟ�ߢ�ި�ߨ�᮶᭵⫳⪲߬�୵⬵᬴ᬵ⪵᮷Ⲹ⯸⳺䲻䯸㭵⩶⩳��ޥ�⡭᛫ߢ�ᣮ╧ߋ�ߊ�������������������߃�����߅�߂���ށ�݀�߂�ނ�ހ�݀�ރ [...]
+XKD��m����}r���p��d��s��m��_{�Xt�_v�_{�`z�_{�Tr�Vm�]y�[u�Ri�I`zJ\tBSiBPcFTeBRf=Qd>VjI[sJ\rI\tAVl;M_BSfAOf1<I7FT<K^5DT:GT;FW6?L at K]<I[7DOMe�Qm�Ts�Li~Ph�Rl�Rh|Og}Sl�Uo�Zv�Um�L]oVh~]r�\q�Wm�dz�u��t��h��cv�j~�o��o��r��z��{��o�du�l{�hu�WdyWezQ[jVfxf}�Zo�\q�fx�hw�cy�o��l�����v��g|�i}�dw�cx�j��m��t��s��l��o��t��s��u��u��w��u��w��z��v��w��{��x��y��v��t��aW]�ri���������z��v��s��u��{��{��%-8cRG��������m��k��l��r��d|�Ul�Rh`y�_|�\t�Mc�Mc|[t�Zv�Xs�Oj�Nf{J^v?NaBScLatRk�J`|9CW9=I<CNBXgL_wGYnAPc8AN [...]
B70�zf������o��k��Vl[s�c~�d��b��f��g��b{�b}�]x�\s�\r�Sj�]v�Vk�OcxQf|N`vPezSk�Sf}P`xSh~K]mPapHWjEWdJatK]rHWdGYfFVeDSaAQ`AQ^GRbEPaOj~Qn�Tu�Sm�H`oMbrZm�c��Wn�Vk�Xp�NdvSh|Zp�Wm}ax�n��q��o��i}�cx�Thvar�g{�fw�jw�hx�m|�q��u��y��h{�_r�fs�ew�Xm{ex�v��p��bs�gu�kx�n~�h|�m��s��q��~�����v��r��s��d|�_r�hy�p��k��v��y����v��t��n��i~�v��u��t��r��o��AKXA85PEB]PM�|v��}jXJ�m]v`Yn]U����ew�r��N[w
"
bSFyjZ������h��e��k��j}�j��_z�Tm�Qi{Zq�[r�`x�at�Xl�PcwUn�Sg�L^pSi~HWkHUeES^FVaJUdFXeI\jLauJWjIZjOezOe{RezR^rJYjCM[29>5=B49>49=KfwPh~Sm�Us�Xx�Wr�Xo�Vn�Th|QexUh}UjzUhx\l|Xj}e}�as�`p�at�i|�g{�j}�i{�`t�hx�m|�i}�q��x��v��u��gt�i|�{��t��i|�m��u��k}�v��x��[o{`ofy�jw�o��r��r��o��s��{��w��h|�f{�j��d|�d{�p��o��fz�bv�fz�hz�o��s��m��r��j}�`u�M\i+%&J@>KB:^PJm^WYKDI>6 3)(wfe������TYh518_UDsgTn`N{jZ���������dx�h�m�av�Uj{R`oL]gPcpQgw[p�cv�Xj}Wf|LXjEVbJ^nK`rIYgL]kTnTkQewRjzXp�L_qFVc>IRARZ;DN37 [...]
:2/aRKʹ�λ���y��x��y��������ʻ�̹����q��_w�UdpTdn_q�cw�_s�Xk\r�XlTj~Vm�PdwNarO`sTj~Vj}Qh{K^pJVgJ[kK]oQfxRexN`tHSbIWfGQa at IR;JP?KW<HSFT`?GP9 at D=GTRjvQfsPfsQfuTk~Yr�]{�\w�RhwVhyXjwUftRdrXhw`m[lev�i�j��r��p��n��m��s��p��h}�o�y��o��lz�gu�gs�hs�ly�s}�^n{]p~hz�\gr]et`r�r����r��o��dt�hx�ey�o��v��v��m��n��n��br�ft�g~�g~�m��r��y��z��x��v��q��p��k��r��y��x��j��
+
%!
+
70-LB>vc[��{����þ���������������ƶ��ȿ���o��Tp�Ugzcx�h�av�Wo�Yr�Zo�Xm�Ws�Um�UbsS_mWfvPevOcrZn{Un�Qe~M^qL\pKYjFRaALXCR]CPVCS[FS^BNZ:EN=DL9 at H19;6?BYq�Zp�Yp�ShzVn�\u�\q�Ym}Xk|Zp~VfrZjv^lzWjxVixZl~d|�cz�bu�p��r��j��k{�ao|gv�j�ix�p��r��kz�y��{��p�es�ds�cu�s��m��Zly[lygy�cq�ar�hz�g|�i~�p�u��}��w��m|�et�ev�q��z��v��g}�e{�m��l��dy�cs�[n{bv�s��v��n��v��x��t�����L[i
,$"0('
O=3��~Ȳ�Ȱ�������������������ɸ�´����iotP`gOcsWq�az�ay�Xn�Vk}Xi~SbsNYgHS^M]kI[iHXdSbn]n�Vh{WhyO^pGYgHXbK_oRk|[p�UfzN]oM^qG[iCP]:AH>QZK]pPkSk�Yr�Xo�Yp�by�^s�Vn~Vl�Tl}HYdP`nVgtWiz_r�k|�j|�k|�i��s��p��o��v��r��j{�j{�l|�dp~ht�fv�p�u��t��m~�hy�k~�jy�du�et�p�v��gu�iw�r��s��u��v��v��g�n�u��p��o��t��t��n|�cu�n~�iy�ar�gv�mz�m|�p��r��v��x��w��v��q��l��j~�>FL
+
$
5,)& PE=�oc��u������������������������Ǵ�Ⱥ����������{��l|�iy�arRdqFV^M]iRetShzL^mDT]GV_NZeNZaP_iTapWjyYk|SamR]hHW_FS^DQ[ES[FPZGOV?MP?KS;CHOk{Rk|Up�Tr�Wq�^t�Zt�[t�Yt�PhvUft\o}cx�h}�iz�f{�`u�ZhwZjydv�m}�q�k{�jx�jz�dw�gr�q��s��kx�m{�dv�`rj{�ds|]js^mwZhr_mxhw�s��o}�p�o}�j}�jz�jw�s��w��q��t��s��p��h~�o��u��x��w��m~�bs{hx�u��y��z��w��t��q��n}�dt~dvp��q��{��Tai
+
'
70)/*)'$"<3/H;6\JGs^Zwfb�uq������������������������������������������������t{�qz�n}�jz�bnuSdkRbjM\fQgqRfyM[iO`nO_nM_hTdnVerOX\EPML[`O_iUbmP]cWj{Vn}TkzVk|Ul{\p~\q�at�Zlw]r�cw�ev�bq}ar�bt�]m{]p|^ozaozew�w��m}�dt�kz�s��u��s��w��k��cs�iu�gu�]mwWeoTaiMX\FW\Udmjw�s��p�k{�v��z��iz�gx�ev�ky�m~�jx�j|�j�k{�l{�n~�jz�m~�s��t��v��w��u��v��t��u��w��v��v��{��|��z��w��z��HSf
+
+
+
+
2*&!)$"2)':.,+!"2'&>52K@?ZIF{hd��|�wr�wr��y�����|������������ɽ����������������������������������z{zoutbilPYWQ[`N\fIW_?IK6CA at NUIV`N]jWjzZo}YnzXlvVjvRgwXm�bv�ny�t��o|�nz�o{�mx�bq{`oyeth{�r��v��r��o��n{�lv�m|�kz�kw�dq�jv�bx�ew�fu�^lybp}ar|dq~ao~iv�gu�fs�hr�et�i{�hx�j{�h|�l�iz�cu�hv�et�fv�o|�ky�o~�l~�k��l��n��o��p��s��u��u��v��p��n~�r��k{�kz�jwx~�egk?C=#
+
+
$
#
<0,F96UH?VK@=72,$&4,*LAAXMK�ys�sm�ri~rn������������������������������������������������������������������������zzwtwvikoTfvUiwSepVfsVjyJcxLbxM\oR_pZh{ap~foyet�ft�eq}eu�ds�Zfr[hvmv�p~�fw�]mx_kscny`nzal}bo~_jyZgs\kwar~fq~kv�my�gu�co~^lcr�ap}am|gp�aq�cr�cn~hn{io|hx�fv�ex�hu�it~`mtes~aq{[lrbmwcp|ev�n}�q��p�kz�k|�mx�oy�ku}OXahx�q��RNVmcd�|���OIJ
+
-"$
#
+
+
(5,+B82QEAE855-,H>;:1.;43 at 65D<:]RP\QNc[Z��~����vo�yp�vqwhb�wo��z��}��z�}q��y��������w��s��y��|��z���������������������TfrQalTesUivScjO`gQakYitWeqXgwZly`o|bt�\p�[m}Vhx[kyao~\kwYgtco}dp}cs|dr~iw�gr~fqzix�fw�l{�r��l|�ix�gu�]lzZiyNTaTQZb^eicjhaf]W`aYb`TWA56?6;SKNSOW^dq^n{\lvbox^msbp{^ks^lscox`ls]nt^nw`lvssy`ho]hjkrykx�k{�
UMT��PLK6-+A43]QT
+
+
&"!=204.+%
-#",%'800=64C98I<9QFDD99C<8NIEbYWcURth`yibn^Vm`Xo^Wq\Sl]R�na�od�uj�~r��{�t��{�����r�qxf]��v�����x�xl�zr�xn^s{_t�bx�\ox\lt\mxXkt[lu`q}cr_ozbr~aq}]lyar~]ny]oYjx_lyft�ew�YenYbnUZcRU_ccoefpcbpww�qq|jjxehw`dt[gz`n�IT^:25C;>B;=JDEG<<@57J at BC;=GAAQKIC:9MAGccnfv~`mtdnu`nu_mvfofw�o��n~�kz�[XYJ<?cVT���������~��''(MA>7//#
' "
+
+.((
+%#3)*.%&+%&3..D>>803.),:23<01?54F;:G84I84n_WiXOyf[iXP`QIq^S|g\dRG~najbjXS\LEaUMq_Vzh`}mdzh`|mfZmx[ozZkt[jr^my\px\mu\nwau�du�^q|^mycq~^mwZiscqzbmxdu�h{�`kvMQ[E at GE?JGALC;E=6 at 405$ &%5-2,$'6.34,15/:]dtFTX@;::32D=<A:;:422,-724B<>cWZ_USQIIJB at RHKXYfs~�s��v��u��s��u��p��u��agp=32VMD��|������B64
A74
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
($&1+-'$"
!
.(&80/I<9]PITHD=2.QC=\MEcSLYJE\NFTFBG=9[NEWIBZKF\LG[KDZmwYnxVlvZnzZoyZjuap}dx�ct�dv�dv�]nw_o|bs�fx�ky�fw�^mvfu0:6-'.0,5*'.
% !
('(4-.,&&-')\_pR\_
+
+
+@:@VPM911;55;450**& -(+J at CF=?G at DF>B<44*!!MLWfp|p{�{��~��~��z��v��_fh:31YQP�~�����zvl``ZP#
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
.''"
)"!(!
( 4*)A83SIESECD72K<5N at 8TF=J?9MA:XgmYisVjtVhqZhwYhq[gq]kyUdmWdm_nyiw�dr}gs�eq|_jvZgq]kv\jx at PP"$$
%
-'#.+'*(%930=>842/=>>A>=DADGKWP[qKU`
'!%$
"&!!+$&*&('"$.(,=69?88KFJKDF<50;8,FIGfqzrzv~�x��u��u��~��Wbj
+
+ C>BcX[aVU&"
+
+
+
+
+
+
+
+
+
+
+
+
+
+
0+**&%&
$ 5,(:0+G<6XJBH=9>31\isWfoVgq\mvZhqXhp]irYhp\ju_ny_nxit�gu�dp|anzdqXfnYfs_iyWdpMU^7 at D*03369899?BAHIDDE:AA8FGFJJKRTZX`iT]lUbvJWg
'$ 1.*40*0,'(&$2+*;22RFGd\[LKD?>2CE9\deo�q}�t~�s�t��n{�r��NW\
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
(#"#
)!!
+
+
Xdo[is]p}`o|_o{^p|\ny\jx`p}[iw_l{WdqSaqbk|nt�t{�t}�qv|xy�x|ptuz~�qx{ckpT[aQTWSUWOVUNVS\adZcbknsry~pw|nv^eqAHL7:6AA7CC=@C:AD;EF=?@7=@9CE<@A:FFAOSJQVK]a^msyx}�x��}����{��lz�eu�RZb#$
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
]r|^r}\lwXgrZiu^iq\kv[jt[hqVaiO_hNYfIYgMVeQVeW\giippoonpptuv|�~���������{zynpokqqafj\ch`gogmtiq|gr~dlvfmzemv[aePTOSUOPTLNQERVMTYRX]X\d_ad`^dbY_Y`b`koox}������v{yy����x��mw�mt�U`h>A<47/+.'%(" !
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+`flZglWejWbc[cfVbcXac[eh\ej]gnWcjQ^eJVZHQYFR[COWIS_^frjpzjq}sx}rtxnqvnt{mrxoszqw{mv{lrvilonu{mwktylqwot}u|�kvx\aZ[^W[^U`d]ejdfnhckfdjeegacd_^e_bdejkpmrwuz~uzywyz||~x}}xyyuvxru|klrYZ\EHI<=@*./!$%
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
bXX\abZghZcbYba\dcZdf^ff[ef\df]fi\bd\ej_js_hp`lt\hpVcm[eq[aicjsgnvimvlu|lrxmtzorsrwztz{y~�rwwquzu|�pw|mqtpuxovzqwvfodmqkqwumvqltnstqputjslirlmrrkrphkihmomrxku|nu|qw|ovzpw~kpuach\]bV\bHIO;>D05=.2:"(/
+
+
+
+41*
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+i]Z\ZUKOLUWTX][X]_[bf]hl]hj_fj\eiahkbkpdluensfmrgnrjqtltyktwkppjqrmuvjppjpoovvvy|ty{x�q{{nvopwvy~�z��{��{��z��z��vxqw{vz}xw~vw}yx~|wzzmuomqmostryzryxlsqortntvjruqz�qx�jt}gp|ZflLV]DKTAHR>GQ7=E49 at 46<226
*" 3/)
FB5qgO��oqpe
+
+
+
+
+
+
+
+
+
+
+
+
+eXUYRM;98FCKTQ]YXd`bj`ej`johnp������}~~cikioujtzkqyptynuzs{�qx{v|�w��t{{vz~y|�u{}w{{w{}xz|���{��y~�z�{~�y~�s{vu{ty~x{}wx�x|�{}�{��u|vntmlmhprqnrqrwzq}�mu{ow}jswejofmshntaltco{]hwXepTajOXaISZCHNQOT::=
&& /-(#$" !"$"
IB;[PB�|qwns
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ XOSe][Z^aKU\QVaW]e\flajpMNSRIP�u{���b^bfhijnmjosouzpx{lvyqvzt{v{w}�w}�|��vyztwwx|~z�z��x~�y}}{��z��|��}����~�~~��}�~y�||yz}uz~yv{wpuontnlpmopnrxyrz~ox}pwsw|p{�m|�mz|q{�n}�iu~ns{mt{hnqkps_glT\aLRVNXXLPK:A99=548165.86/DD;GH=FG>AB9==6572.-('(#"
!"## "
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ a`\hc\]`_YdiZci\gnS]a;;:*'%KBHZY]LBGdakhpuqtyu|�t|�uzwzy|z�y|~ryzz�����|~~y}}z}}vyy{|}��}��}�}}}{~{plm�~����������~x~zu|xuwvqvuqsrpspstutvuqtnnurruvtx{u}�v��t�u|�nwxntwotvvzyy�z��w~~ryvrwyuz|lni_bWY]PX]MU\MWYKX[I]`PZZKRWJOPDEH>BG=CE<EI?AE;680'*#
#%&(*- ,/ (+
,/!'*
"
+
+
+
+
+
+
+ fjc^]X[ciVagRT\RT\@AE;97>=;523RLSVUVLIKXX_ggopvzt}�v{�v|z��x�|~|w~~u{z{{�z~~x|{x|}w}~{}x{yvvyqturuvrvv76:�rr�����������}ywwvsgkajmgnpkmrjjpfjndnriqvrqxypvrosotwwwz}r}}w�x}�u}~{}�����������vxqsvjkoahn[np]oveos`knWknWhkVceR``MXZKRTGQRDSSCQTEQTELMBCE;8<2.2)'(""
!#$%%'
*+/2!25%59+?E;JPOIPO?FE at MK6>?
+
+362=>?LT^EIRFJPLNSQSYQSXGHKBADMLLTWWcefknrlpvktwswzu{}t|�{��v~�v{}��}��{�~�z��{��vy|{|}��z��y~�x~�ow~ent47:rdd����u�{t��~�zsvmi����xkjempimqirvnmskmmipsonvptupwxsx|zw|~wxy{}}{�������~�����������z��xvufyzi}�q~o|{g{{gwyest`loXhhScfQ`cO^bM[[IZ]HX\IXVFUVCVYGTVFNQ at MP?KJ<9<113(**# !
$&'),!/0(:;3HKGNUTW]`X^_021
@HBELJ;A at 399,//%+*
..3FKOSY^SZaUahZae]ckX`fTY_TZ]^adcfghlmkprlppoqrlpojplswyuwzrvtptpqqnsvtwxzvv{|}�~��wz|yz}ootjhmqntnnrgjockzCMTA6=�xz����wsqefNFLc]d������a\\ifld`eebaijfjlj]YYvv}{~����~�|�|�����~����������������|��x��~��|��s��w��z��v~�pxvcrs[su]qpYjkSjkRpqZrrZloXilShiRdeObbNbdO`bM_`LdbNdbNabO]]JWZHMOAAE79;0,/&!#
"$%%(*-
./!57+9<.7:(<A1BF;HKBRXUW^^Y`bSZ[GOPHPQ//1^mp[ehZ`aZei\gj_ei^fi^fjcgmbhlfikfliilkmolornorrrwwnwwpwvnusrurptpousstwxuyprtOOScX`���prlKKJA?<@<7 [...]
!%&"-.+TZMTXJWZSZ]Z[\X]a^\`[\b`_fdcdeedcddaca^gefgijjjmmmrprxnsxot{qswklokkplpwZbf583
KCCVNGJE at eYY�������{{lbbULO]YZWXS;95&&!+)'VUXhkjy{y��~�������������������������������������������������|��{��y��z}�kuy_ux]wuaqqWlnTiiRciObcKeeNhkQmnUloVqrWvu[xx]yx^wuZqqXnpTlnSknTlmRmpWmmVlnUjlShmRglTcfQ\aLPR at FI;>A4=@29<128--4+-2*,3*,1*6=1XdS_fX>@5/0(&*$
\ No newline at end of file
diff --git a/jasper-1.900.1-6ct/data/images/goldenears.ras b/jasper-1.900.1-6ct/data/images/goldenears.ras
new file mode 100644
index 0000000..1b1eae8
Binary files /dev/null and b/jasper-1.900.1-6ct/data/images/goldenears.ras differ
diff --git a/jasper-1.900.1-6ct/data/images/goldenears_gray.jpg b/jasper-1.900.1-6ct/data/images/goldenears_gray.jpg
new file mode 100644
index 0000000..c1af713
Binary files /dev/null and b/jasper-1.900.1-6ct/data/images/goldenears_gray.jpg differ
diff --git a/jasper-1.900.1-6ct/data/images/goldenears_gray.pnm b/jasper-1.900.1-6ct/data/images/goldenears_gray.pnm
new file mode 100644
index 0000000..f403637
--- /dev/null
+++ b/jasper-1.900.1-6ct/data/images/goldenears_gray.pnm
@@ -0,0 +1,451 @@
+P5
+128 96
+255
+||||��������������������������������������������������������������������û������������������������������������������������������|||������������������������������������������������������������������������������������������������������������������������������|�|����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� [...]
+S�����|��ssssssllsld[[KKSSKSS[[SKSK;DKDDD;KKDdllddddddlld[dllls��|s|�|���|s|sdd[d|llsss����||ss|���|���������������|[s���������,[�������slds|s[dssld[[KS[d[D;DS[[KDDKKSKD;;,ddlsllsssddddlll|�ss|s�||s|ssslsdS[|�lS[l��sl||s|||s��||s|������������[D[���������|$,[���ss|l||sl[[ddSdd[[[[dd[SKDSSKD;4,;SKS[[dlsssslslllldddddlsssssslldlll|ss||dd|�������s�����������||s|�������sKK[|�d�|��|��S;|���|ll|||||s|ssllsddd[ddd[d[[SS[[SSSSKKSKdlld[[l|ldl[dlds|�||sdsssss|���slssds�|sss|||�������sls��������| [...]
+Sl��||||�sldllssl[ld[dSSKSSS[[SSddd[SK;;;4[dllsllldddddld|sls|s||ls|||���s|��||�|��llss|��|���|||ss��ssss|���|s[$DDSdKD,l��[4Sldl���s||sd[[[dlsldSS[[S[ldddl[SKKD4K[SKS[Sdd[l[[SS[ddddlls|s|ssll|ss|ssss����sl|��ss|�||||��||ss���ssldl|��|sls�D,$$;;
+4S���������|sddlslllddld[[ddd[S[[d[[SSSKDKDSD;Ddddddlssddddddlls||�|||�|||�||ssss|ll|ddl��|�sss���|�|lss|��������|���|
+
+$
+4Dl��˴�����˴|lds|sllllll[[dd[lld[[SKKSKKSKDDD;;llldlllldlddlddlsss|�||ls|s��s��|sss||ldssls|||���|ls���|s�|ssls�������S
+
+$,D������������l[[lssldd[[S[SS[ldd[SS[dld[[SKDK[ddlllsllldS[ddl||||�||�||s|lss|��|s|sss|�ss�����||�||��|s|sls|||������||D
+
+$,$Ds���������������|sldS[dd[SS[S[[dld[SSKSSKKDDddlllsllsddls|sssdds|||sssl||ssslsldldls�||||ss�����||����|ss������|ss|��[
+
+
+$4,$4DKdl|����������������|||sld[[ddS[[[ddSKS[[[dlddllllllssllslllls�|ss����|ssslddSSds|||��sss||s|||s|s|����������������S
+
+
+
+
+
+,$,4$,4DKl�||���������������|slSS[SDDKS[dlldddls|||||sllss|��||s|ssssssslllslsssssss|s|sssssss||||�|||���||�s|s|lD$
+
+
+
+
+
+$$4;KK4$,DS||ss���������������������|sldd[dd[[[[dlllslssdds|sdlllllldlllssslllllslsllsssssslllllls|�|s|sssSs|Sd��K
+$$
+
+$4;K;4D44;;SS[��|||ls���|���������������d[ddd[[ddddlslldllldlllssslsss�sssldSSddd[[S;;KSdllllldllllllsddss|S�K,4S
+
+
+
+$4,$
+$,4;;;K;;K[[lldddddss|�������l���|�|llsllldlllllllllldllsdd[Sddd|slldllS4;;D;;D;DKDDdsllllls|||SD[����$D4$
+
+
+
+
+
+,
+
+
+
+,,,,,D4,44;;;;d[l[SdlSss[S[dlslsdlldlldlsslllldslsslSDDD;;4$$4$4,4dK;4D;444;[SKDK[||��|�|�d4S���;;
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+,,$
+,4DSK4DSSKSK;SKKSKlldlldlslssllssssls4
+,,$$,,$,d[
+;S444,$,DDDD4$Kl|�����d4S���s[
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+,
+
+
+$$$,;KK;DDKDDddddddddddlslssddddK$
+$,,$4;4;DDK[S
+$$$$,$,4;KD;4Kl||�|��d
+;[[$
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+,$$$,4DKD4dddldddddllsslllddldS;,44DKDDDKS[[dS$,4,$,4K[K;Dd|||||||S
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+$$$
+
+
+
+ddllllllldld[ls||s||s|sl[SSSS[[lsssdD;DD;DDD;DDDSS[s|����|s[$
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+llldddldd[[[SSS[llls|���|lsdddlssllldSSSKSS[ddd[dl|��|��|ss[D4,$$
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ddd[d[[dddd[SKSKSdll|sssssssslsssss|s[[[dlldlddddll|s||||ssl[K;,$
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+[dd[[dddddd[dldlddddlllsssss|||s|sssssllsssssslllllsssssssd[[K;44$
+
+
+4
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+[[KS[[[dddddllllllssslsllss||sss||���||||||||sls|ssssls|ssdSKDD;;44$4
+
+Dd�l
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+[S;DS[ddll��|dlslss|s|||||||||��|||||s||||||sslsss|sssllllldd[SSDS;$,$$$DS|s
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+S[[SS[dlKK|�[lllssss||||�|s|||||�|���|���||||sslss|ss||ss||ssslsd[SSK;;444DDDD;4,,$
+$$
+
+
+
+
+
+
+
+
+
+dddddd[;,D[Ddss|||||||||�|||||��|||l����|||ssssssssss|�||sss|||||s|ld[[[[[[SSKDDDDD4,$$$,,,,$
+
+
+
+
+
+
+
+l[d[SSD;;4SSK[ls||||||||||||||||ssss;s����|sllllllssssss||�||||����|slllssllld[[SKSSSKD;4$$$$$,,44DKKDK;
+
+4;SKKKSSDDKSdllss|||||��|||�s|�|||sl4l��|�|l��lllsslssss||||���������ss||||sslddd[[[[SSSSKKK;4,$$,4;KS[[4DK;4,,
+,K[[[[d[[[ddlssssls|ssss|s|�||llslllK;|�|lKd��[lddll[||�||���������������|slsldllllddd[d[[d[[[SKD;,$$,,,4;4;DKS[[[KK,ld[ddddddddllllsssssssssssK[�sKD;d|d;4sl;4�|SSKDS[Sl||�������������||��|ssslsssllslllddddddlld[[SD;,$$$$$,,,,4;;KS[[,[[dlllddldlllsss|sllsslssSD4���[l���|[4DK,|KKD;KK[ls���������������||�|sss|lllssllsssssllllllldld[[SKDD4$$$$$,4DK[DS[ddddlddlllssslllssssss[$;DK||[ls�����[D,
+DdSDD[ls|������������������|||slllddlsss|sssssss|sslllddd[[[SD4$$$$$4D;S[dddddddldlllssssslsssl;
+,44Dd[l�����dD
+
+4DKKl||��������������������||sslld[dllss|s||sssssllllllld[SD;4,$$$
+$$,SSS[[[[dddddddlllssssllsd;
+DSK[��|dK[S;$,Sl|���������������������|ssslldddddllssssslllllllllldd[SD;;;44444;[d;4$$
\ No newline at end of file
diff --git a/jasper-1.900.1-6ct/data/images/goldenears_gray.ras b/jasper-1.900.1-6ct/data/images/goldenears_gray.ras
new file mode 100644
index 0000000..f12b6c8
Binary files /dev/null and b/jasper-1.900.1-6ct/data/images/goldenears_gray.ras differ
diff --git a/jasper-1.900.1-6ct/data/images/small_16x1.pnm b/jasper-1.900.1-6ct/data/images/small_16x1.pnm
new file mode 100644
index 0000000..989d815
Binary files /dev/null and b/jasper-1.900.1-6ct/data/images/small_16x1.pnm differ
diff --git a/jasper-1.900.1-6ct/data/images/small_1x1.pnm b/jasper-1.900.1-6ct/data/images/small_1x1.pnm
new file mode 100644
index 0000000..43a6c4e
--- /dev/null
+++ b/jasper-1.900.1-6ct/data/images/small_1x1.pnm
@@ -0,0 +1,4 @@
+P5
+1 1
+255
+�
\ No newline at end of file
diff --git a/jasper-1.900.1-6ct/data/images/stawamuschief.pnm b/jasper-1.900.1-6ct/data/images/stawamuschief.pnm
new file mode 100644
index 0000000..2b04d6a
--- /dev/null
+++ b/jasper-1.900.1-6ct/data/images/stawamuschief.pnm
@@ -0,0 +1,4 @@
+P6
+199 149
+255
+o��m��s��k��l��i��t��t��v��t��v��z��y��z��}�‡�~��{��~��{��{���傢傤戢儦儤肧脩懧臨芩錨鋫釬茫鋭莬鐪쐫쏮뒯ꏱ덱폲푯퓮��푱��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������t��r��t��t��r��t��y��v��y��z��}�����ဤ�~�〦℥䃧冧凨利努捫抭狭菮摭珮琯蓮鑰鐱锰镱ꓲꓱ [...]
>=>{np��������������������{��}�����{������x��x������������������������xtstpuuoskloekm`dfifgphiwqo}xr��u�������������������{��z��~��yvustru������������������������er�nv����������������������������������������������������}sqxsr]afNYeS[`nsojjlY^eJU_]iiouqRZ_�����������������æ��������|�yejiV`bS[\Y`f����������yw�����Ƭ�������������������������������������Ʒ�Ǘ��w�����������������������|�����w��fmsOT\C at PGLU";A at DNAFQ?>G7R]JQ]NUcRVbSoxn����������������������������������������������������������� [...]
\ No newline at end of file
diff --git a/jasper-1.900.1-6ct/data/images/stawamuschief_gray.pnm b/jasper-1.900.1-6ct/data/images/stawamuschief_gray.pnm
new file mode 100644
index 0000000..d856042
--- /dev/null
+++ b/jasper-1.900.1-6ct/data/images/stawamuschief_gray.pnm
@@ -0,0 +1,4 @@
+P5
+199 149
+255
+���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������û�������� [...]
\ No newline at end of file
diff --git a/jasper-1.900.1-6ct/data/images/test.pnm b/jasper-1.900.1-6ct/data/images/test.pnm
new file mode 100644
index 0000000..3552e16
--- /dev/null
+++ b/jasper-1.900.1-6ct/data/images/test.pnm
@@ -0,0 +1,11 @@
+P2
+8 8
+4095
+0000 1024 2048 3072 3072 2048 1024 0000
+0000 1024 2048 3072 3072 2048 1024 0000
+0000 1024 2048 3072 3072 2048 1024 0000
+0000 1024 2048 3072 3072 2048 1024 0000
+0000 1024 2048 3072 3072 2048 1024 0000
+0000 1024 2048 3072 3072 2048 1024 0000
+0000 1024 2048 3072 3072 2048 1024 0000
+0000 1024 2048 3072 3072 2048 1024 0000
diff --git a/jasper-1.900.1-6ct/doc/Changes_for_gcc4 warnings.txt b/jasper-1.900.1-6ct/doc/Changes_for_gcc4 warnings.txt
new file mode 100644
index 0000000..0733842
--- /dev/null
+++ b/jasper-1.900.1-6ct/doc/Changes_for_gcc4 warnings.txt
@@ -0,0 +1,59 @@
+Changes for gcc4 warnings.+++++++++++++++++++++++
+jas_debug.c
+was:
+ fprintf(out, "%04x:", i);
+to:
+ fprintf(out, "%04x:", (unsigned int)i);
+
+bmp_dec.c
+jas_cm.c
+jas_getopt.c
+jas_image.c
+jpc_t1dec.c
+jpg_dummy.c
+mif_cod.c
+pnm_dec.c
+added:
+#include "jasper/jas_debug.h"
+
+jas_cm.c
+jasper.c
+added:
+#include <jasper/jas_debug.h>
+
+jpc_tsfb.c
+int jpc_tsfb_analyze2(jpc_tsfb_t *tsfb, int *a, int xstart, int ystart,
+ int width, int height, int stride, int numlvls)
+moved to before:
+int jpc_tsfb_analyze(jpc_tsfb_t *tsfb, jas_seq2d_t *a)
+
+int jpc_tsfb_synthesize2(jpc_tsfb_t *tsfb, int *a, int xstart, int ystart,
+ int width, int height, int stride, int numlvls)
+moved to before:
+int jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *a)
+
+jpc_enc.c
+commented out the Local prototype and the Code as unused:
+static int jpc_calcssexp(jpc_fix_t stepsize);
+static int jpc_calcssmant(jpc_fix_t stepsize);
+
+for 64 bit warnings
+jpc_mqdec.c
+from:
+ fprintf(out, "CTX = %d, ", mqdec->curctx - mqdec->ctxs);
+ fprintf(out, "IND %d, MPS %d, QEVAL %x\n", *mqdec->curctx -
+ jpc_mqstates, (*mqdec->curctx)->mps, (*mqdec->curctx)->qeval);
+to:
+ fprintf(out, "CTX = %d, ", (int)(mqdec->curctx - mqdec->ctxs));
+ fprintf(out, "IND %d, MPS %d, QEVAL %x\n", (int)(*mqdec->curctx -
+ jpc_mqstates), (*mqdec->curctx)->mps, (*mqdec->curctx)->qeval);
+
+jpc_mqenc.c
+from:
+ fprintf(out, "IND = %02d, MPS = %d, QEVAL = %04x\n",
+ *mqenc->curctx - jpc_mqstates, (*mqenc->curctx)->mps,
+ (*mqenc->curctx)->qeval);
+to:
+ fprintf(out, "IND = %02d, MPS = %d, QEVAL = %04x\n",
+ (int)(*mqenc->curctx - jpc_mqstates), (*mqenc->curctx)->mps,
+ (*mqenc->curctx)->qeval);
diff --git a/jasper-1.900.1-6ct/doc/Changes_for_jpeg-6c.txt b/jasper-1.900.1-6ct/doc/Changes_for_jpeg-6c.txt
new file mode 100644
index 0000000..65d5ba8
--- /dev/null
+++ b/jasper-1.900.1-6ct/doc/Changes_for_jpeg-6c.txt
@@ -0,0 +1,118 @@
+Multi-bitwidth jpeg-6c with lossless changes+++++++++++++++++++++
+jpg_dec.c
+line 141 from:
+ int num_scanlines;
+to:
+ int num_scanlines, byte_width;
+
+add at line 181:
+ if (cinfo.data_precision > 8) byte_width = 2;/* 12 or 16 */
+ else byte_width = 1;/* 8 */
+
+line 183 from:
+ cinfo.output_width * cinfo.output_components, (JDIMENSION) 1);
+to:
+ cinfo.output_width * cinfo.output_components * byte_width, (JDIMENSION) 1);
+
+line 245 from:
+ cmptparm.prec = 8;
+to:
+ cmptparm.prec = cinfo->data_precision;
+add at line 312:
+ JSAMPLE16 *bufptr16;
+
+add at line 316:
+ bool wide = FALSE;
+
+add at line 322:
+ if (cinfo->data_precision > 8) wide = TRUE;
+
+
+line 326 from:
+ for (x = 0; x < width; ++x) {
+ jas_matrix_set(dinfo->data, 0, x, GETJSAMPLE(*bufptr));
+ bufptr += cinfo->output_components;
+ }
+to:
+ for (cmptno = 0; cmptno < cinfo->output_components; ++cmptno) {
+ width = jas_image_cmptwidth(dinfo->image, cmptno);
+ if (wide) {
+ bufptr16 = (dinfo->buffer[0]) + cmptno;
+ for (x = 0; x < width; ++x) {
+ jas_matrix_set(dinfo->data, 0, x, GETJSAMPLE16(*bufptr16));
+ bufptr16 += cinfo->output_components;
+ }
+ } else {
+ bufptr = (dinfo->buffer[0]) + cmptno;
+ for (x = 0; x < width; ++x) {
+ jas_matrix_set(dinfo->data, 0, x, GETJSAMPLE(*bufptr));
+ bufptr += cinfo->output_components;
+ }
+ }
+
+
+jpg_ecn.c -----------------------------------------
+line 108 from:
+typedef struct {
+ int qual;
+} jpg_encopts_t;
+
+typedef enum {
+ OPT_QUAL
+} jpg_optid_t;
+
+jas_taginfo_t jpg_opttab[] = {
+ {OPT_QUAL, "quality"},
+ {-1, 0}
+to:
+typedef struct {
+ int qual;
+ bool lossless;
+} jpg_encopts_t;
+
+typedef enum {
+ OPT_QUAL,
+ LOSSLESS
+} jpg_optid_t;
+
+jas_taginfo_t jpg_opttab[] = {
+ {OPT_QUAL, "quality"},
+ {LOSSLESS, "lossless"},
+ {-1, 0}
+
+add at line 214:
+ uint_fast8_t prec;
+ uint byte_width;
+
+line 277 from:
+ jas_image_cmptprec(image, enc->cmpts[cmptno]) != 8 ||
+to:
+/* jas_image_cmptprec(image, enc->cmpts[cmptno]) != 8 ||*/
+add at line 282:
+ prec = jas_image_cmptprec(image, enc->cmpts[cmptno]);
+ if ( prec != 8 && prec != 12 && prec != 16) {
+ jas_eprintf("error: The JPG encoder cannot handle an image with a %d bit width.\n", prec);
+ goto error;
+ }
+add at line 304:
+ cinfo.data_precision = prec;
+ cinfo.data_precision_other = prec;
+ if (prec > 8) byte_width = 2; /* 12 or 16 */
+ else byte_width = 1; /* 8 */
+ cinfo.lossless = encopts.lossless;
+ if (prec == 16) cinfo.lossless = TRUE;
+
+line 317 from:
+ JPOOL_IMAGE, (JDIMENSION) width * cinfo.input_components,
+to:
+ JPOOL_IMAGE, (JDIMENSION) width * cinfo.input_components * byte_width,
+
+add at line 392:
+ encopts->lossless = FALSE;
+
+add at line 411:
+ case LOSSLESS:
+ encopts->lossless = TRUE;
+ encopts->qual = -1;
+ break;
+
diff --git a/jasper-1.900.1-6ct/doc/README b/jasper-1.900.1-6ct/doc/README
new file mode 100644
index 0000000..ded5edd
--- /dev/null
+++ b/jasper-1.900.1-6ct/doc/README
@@ -0,0 +1,8 @@
+This directory contains documentation related to the JasPer software.
+
+jasper.pdf
+ JasPer Software Reference Manual
+
+jpeg2000.pdf
+ A detailed technical tutorial on the JPEG-2000 standard.
+
diff --git a/jasper-1.900.1-6ct/jasper.spec.in b/jasper-1.900.1-6ct/jasper.spec.in
new file mode 100644
index 0000000..9c8f642
--- /dev/null
+++ b/jasper-1.900.1-6ct/jasper.spec.in
@@ -0,0 +1,101 @@
+# Note that this is NOT a relocatable package
+%define package_name jasper
+%define ver @JAS_VERSION@
+%define prefix /usr
+%define datadir %{prefix}/share
+%define release @JAS_RPM_RELEASE@
+
+Summary: JasPer
+Name: %{package_name}
+Version: %{ver}
+Release: %{release}
+Copyright: Modified BSD
+Group: Development/Libraries
+
+# FIXME:
+Source: http://www.ece.uvic.ca/~mdadams/jasper/software/jasper-@JAS_VERSION@.tar.gz
+
+BuildRoot: /var/tmp/%{package_name}-%{version}-root
+Requires: libjpeg
+BuildRequires: libjpeg-devel
+URL: http://www.ece.uvic.ca/~mdadams/jasper/
+
+%description
+JasPer is a collection
+of software (i.e., a library and application programs) for the coding
+and manipulation of images. This software can handle image data in a
+variety of formats. One such format supported by JasPer is the JPEG-2000
+format defined in ISO/IEC 15444-1:2000.
+
+%package devel
+Summary: Include Files and Documentation
+Group: Development/Libraries
+Requires: %{package_name} = %{ver}
+
+%description devel
+JasPer is a collection
+of software (i.e., a library and application programs) for the coding
+and manipulation of images. This software can handle image data in a
+variety of formats. One such format supported by JasPer is the JPEG-2000
+code stream format defined in ISO/IEC 15444-1:2000.
+
+%prep
+%setup
+
+./configure --prefix=/usr --enable-shared
+
+
+# build
+%build
+
+#if [ "$SMP" != "" ]; then
+# (make "MAKE=make -k -j $SMP"; exit 0)
+# make
+#else
+ make
+#fi
+
+
+# install
+%install
+rm -rf $RPM_BUILD_ROOT
+
+make prefix=$RPM_BUILD_ROOT%{prefix} install
+
+
+# clean
+%clean
+rm -rf $RPM_BUILD_ROOT
+
+
+%post -p /sbin/ldconfig
+
+%postun -p /sbin/ldconfig
+
+
+# files main package
+%files
+%defattr(-, root, root)
+
+%doc README LICENSE ChangeLog
+
+%{prefix}/bin/*
+%{prefix}/lib/lib*.so.*
+
+# files devel package
+%files devel
+%defattr(-, root, root)
+
+# no API docs yet :(
+# %doc doc/html/*
+
+%{prefix}/include/jasper/*
+%{prefix}/lib/lib*.so
+%{prefix}/lib/lib*.a
+%{prefix}/lib/lib*.la
+
+%changelog
+
+* Fri Oct 25 2002 Alexander D. Karaivanov <adk at medical-insight.com>
+
+ - spec file created
diff --git a/jasper-1.900.1-6ct/jasperlib.c b/jasper-1.900.1-6ct/jasperlib.c
new file mode 100644
index 0000000..4154803
--- /dev/null
+++ b/jasper-1.900.1-6ct/jasperlib.c
@@ -0,0 +1,72 @@
+// This is an amalgamation of the jasper library modified by bcb
+// this amalgamation was done by mvh 20100117
+// mvh 20100119: simplified and works with unchanged jasper-1.900.1-6ct
+
+#include <stddef.h> // first inclusion avoids compile error later
+
+#include "base/jas_cm.c"
+#include "base/jas_debug.c"
+#include "base/jas_getopt.c"
+#include "base/jas_icc.c"
+#include "base/jas_iccdata.c"
+#include "base/jas_image.c"
+#include "base/jas_init.c"
+#include "base/jas_malloc.c"
+#include "base/jas_seq.c"
+#include "base/jas_stream.c"
+#include "base/jas_string.c"
+#include "base/jas_tmr.c"
+#include "base/jas_tvp.c"
+#include "base/jas_version.c"
+
+#include "bmp/bmp_cod.c"
+#include "bmp/bmp_dec.c"
+#include "bmp/bmp_enc.c"
+
+#include "jp2/jp2_cod.c"
+#include "jp2/jp2_dec.c"
+#include "jp2/jp2_enc.c"
+
+#include "jpc/jpc_bs.c"
+#include "jpc/jpc_cs.c"
+#define OPT_DEBUG OPTx_DEBUG // symbol is double
+#include "jpc/jpc_dec.c"
+#undef OPT_DEBUG
+#include "jpc/jpc_enc.c"
+#include "jpc/jpc_math.c"
+#include "jpc/jpc_mct.c"
+#include "jpc/jpc_mqcod.c"
+#include "jpc/jpc_mqdec.c"
+#include "jpc/jpc_mqenc.c"
+#include "jpc/jpc_qmfb.c"
+#include "jpc/jpc_t1cod.c"
+#include "jpc/jpc_t1dec.c"
+#include "jpc/jpc_t1enc.c"
+#include "jpc/jpc_t2cod.c"
+#include "jpc/jpc_t2dec.c"
+#include "jpc/jpc_t2enc.c"
+#include "jpc/jpc_tagtree.c"
+#include "jpc/jpc_tsfb.c"
+#include "jpc/jpc_util.c"
+
+#include "jpg/jpg_val.c"
+#ifdef HAVE_LIBJPEG
+# include "jpg/jpg_dec.c"
+# include "jpg/jpg_enc.c"
+#else
+# include "jpg/jpg_dummy.c"
+#endif
+
+#include "mif/mif_cod.c"
+
+#include "pgx/pgx_cod.c"
+#include "pgx/pgx_dec.c"
+#include "pgx/pgx_enc.c"
+
+#include "pnm/pnm_cod.c"
+#include "pnm/pnm_dec.c"
+#include "pnm/pnm_enc.c"
+
+#include "ras/ras_cod.c"
+#include "ras/ras_dec.c"
+#include "ras/ras_enc.c"
diff --git a/jasper-1.900.1-6ct/src/Makefile.am b/jasper-1.900.1-6ct/src/Makefile.am
new file mode 100644
index 0000000..d13b988
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/Makefile.am
@@ -0,0 +1,61 @@
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+EXTRA_DIST = README
+
+SUBDIRS = libjasper appl msvc
diff --git a/jasper-1.900.1-6ct/src/Makefile.in b/jasper-1.900.1-6ct/src/Makefile.in
new file mode 100644
index 0000000..0c191e2
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/Makefile.in
@@ -0,0 +1,550 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src
+DIST_COMMON = README $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+SOURCES =
+DIST_SOURCES =
+RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
+ html-recursive info-recursive install-data-recursive \
+ install-exec-recursive install-info-recursive \
+ install-recursive installcheck-recursive installdirs-recursive \
+ pdf-recursive ps-recursive uninstall-info-recursive \
+ uninstall-recursive
+ETAGS = etags
+CTAGS = ctags
+DIST_SUBDIRS = $(SUBDIRS)
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+EXTRA_DIST = README
+SUBDIRS = libjasper appl msvc
+all: all-recursive
+
+.SUFFIXES:
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+
+# This directory's subdirectories are mostly independent; you can cd
+# into them and run `make' without going through this Makefile.
+# To change the values of `make' variables: instead of editing Makefiles,
+# (1) if the variable is set in `config.status', edit `config.status'
+# (which will cause the Makefiles to be regenerated when you run `make');
+# (2) otherwise, pass the desired values on the `make' command line.
+$(RECURSIVE_TARGETS):
+ @failcom='exit 1'; \
+ for f in x $$MAKEFLAGS; do \
+ case $$f in \
+ *=* | --[!k]*);; \
+ *k*) failcom='fail=yes';; \
+ esac; \
+ done; \
+ dot_seen=no; \
+ target=`echo $@ | sed s/-recursive//`; \
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ echo "Making $$target in $$subdir"; \
+ if test "$$subdir" = "."; then \
+ dot_seen=yes; \
+ local_target="$$target-am"; \
+ else \
+ local_target="$$target"; \
+ fi; \
+ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+ || eval $$failcom; \
+ done; \
+ if test "$$dot_seen" = "no"; then \
+ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
+ fi; test -z "$$fail"
+
+mostlyclean-recursive clean-recursive distclean-recursive \
+maintainer-clean-recursive:
+ @failcom='exit 1'; \
+ for f in x $$MAKEFLAGS; do \
+ case $$f in \
+ *=* | --[!k]*);; \
+ *k*) failcom='fail=yes';; \
+ esac; \
+ done; \
+ dot_seen=no; \
+ case "$@" in \
+ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
+ *) list='$(SUBDIRS)' ;; \
+ esac; \
+ rev=''; for subdir in $$list; do \
+ if test "$$subdir" = "."; then :; else \
+ rev="$$subdir $$rev"; \
+ fi; \
+ done; \
+ rev="$$rev ."; \
+ target=`echo $@ | sed s/-recursive//`; \
+ for subdir in $$rev; do \
+ echo "Making $$target in $$subdir"; \
+ if test "$$subdir" = "."; then \
+ local_target="$$target-am"; \
+ else \
+ local_target="$$target"; \
+ fi; \
+ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+ || eval $$failcom; \
+ done && test -z "$$fail"
+tags-recursive:
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
+ done
+ctags-recursive:
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
+ done
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
+ include_option=--etags-include; \
+ empty_fix=.; \
+ else \
+ include_option=--include; \
+ empty_fix=; \
+ fi; \
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ if test "$$subdir" = .; then :; else \
+ test ! -f $$subdir/TAGS || \
+ tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \
+ fi; \
+ done; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+ list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
+ if test "$$subdir" = .; then :; else \
+ test -d "$(distdir)/$$subdir" \
+ || $(mkdir_p) "$(distdir)/$$subdir" \
+ || exit 1; \
+ distdir=`$(am__cd) $(distdir) && pwd`; \
+ top_distdir=`$(am__cd) $(top_distdir) && pwd`; \
+ (cd $$subdir && \
+ $(MAKE) $(AM_MAKEFLAGS) \
+ top_distdir="$$top_distdir" \
+ distdir="$$distdir/$$subdir" \
+ distdir) \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-recursive
+all-am: Makefile
+installdirs: installdirs-recursive
+installdirs-am:
+install: install-recursive
+install-exec: install-exec-recursive
+install-data: install-data-recursive
+uninstall: uninstall-recursive
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-recursive
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-recursive
+
+clean-am: clean-generic clean-libtool mostlyclean-am
+
+distclean: distclean-recursive
+ -rm -f Makefile
+distclean-am: clean-am distclean-generic distclean-libtool \
+ distclean-tags
+
+dvi: dvi-recursive
+
+dvi-am:
+
+html: html-recursive
+
+info: info-recursive
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-recursive
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-recursive
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-recursive
+
+mostlyclean-am: mostlyclean-generic mostlyclean-libtool
+
+pdf: pdf-recursive
+
+pdf-am:
+
+ps: ps-recursive
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+uninstall-info: uninstall-info-recursive
+
+.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am check check-am \
+ clean clean-generic clean-libtool clean-recursive ctags \
+ ctags-recursive distclean distclean-generic distclean-libtool \
+ distclean-recursive distclean-tags distdir dvi dvi-am html \
+ html-am info info-am install install-am install-data \
+ install-data-am install-exec install-exec-am install-info \
+ install-info-am install-man install-strip installcheck \
+ installcheck-am installdirs installdirs-am maintainer-clean \
+ maintainer-clean-generic maintainer-clean-recursive \
+ mostlyclean mostlyclean-generic mostlyclean-libtool \
+ mostlyclean-recursive pdf pdf-am ps ps-am tags tags-recursive \
+ uninstall uninstall-am uninstall-info-am
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/README b/jasper-1.900.1-6ct/src/README
new file mode 100644
index 0000000..faf38c3
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/README
@@ -0,0 +1 @@
+This directory hierarchy contains the source code for JasPer.
diff --git a/jasper-1.900.1-6ct/src/appl/Makefile.am b/jasper-1.900.1-6ct/src/appl/Makefile.am
new file mode 100644
index 0000000..c1f7ff8
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/appl/Makefile.am
@@ -0,0 +1,91 @@
+# Copyright (c) 2001-2003 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+if HAVE_OPENGL
+BIN_JIV = jiv
+EXTRA_JIV =
+else
+BIN_JIV =
+EXTRA_JIV = jiv
+endif
+
+bin_PROGRAMS = jasper $(BIN_JIV) imgcmp imginfo tmrdemo
+#bin_PROGRAMS = jasper $(BIN_JIV) imgcmp imginfo tmrdemo dummy dummy2
+EXTRA_PROGRAMS = $(EXTRA_JIV) dummy dummy2
+
+jasper_SOURCES = jasper.c
+imgcmp_SOURCES = imgcmp.c
+imginfo_SOURCES = imginfo.c
+dummy_SOURCES = dummy.c
+dummy2_SOURCES = dummy2.c
+tmrdemo_SOURCES = tmrdemo.c
+jiv_SOURCES = jiv.c
+man_MANS = imgcmp.1 imginfo.1 jasper.1 jiv.1
+EXTRA_DIST = $(man_MANS)
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
+
+MYLDFLAGS = ../libjasper/libjasper.la
+jasper_LDADD = $(MYLDFLAGS)
+imgcmp_LDADD = $(MYLDFLAGS)
+imginfo_LDADD = $(MYLDFLAGS)
+jiv_LDADD = $(MYLDFLAGS) $(OPENGL_LIBS)
+dummy_LDADD = $(MYLDFLAGS)
+dummy2_LDADD = $(MYLDFLAGS)
+tmrdemo_LDADD = $(MYLDFLAGS)
+
diff --git a/jasper-1.900.1-6ct/src/appl/Makefile.in b/jasper-1.900.1-6ct/src/appl/Makefile.in
new file mode 100644
index 0000000..1798996
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/appl/Makefile.in
@@ -0,0 +1,649 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2003 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+bin_PROGRAMS = jasper$(EXEEXT) $(am__EXEEXT_2) imgcmp$(EXEEXT) \
+ imginfo$(EXEEXT) tmrdemo$(EXEEXT)
+EXTRA_PROGRAMS = $(am__EXEEXT_1) dummy$(EXEEXT) dummy2$(EXEEXT)
+subdir = src/appl
+DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+ at HAVE_OPENGL_FALSE@am__EXEEXT_1 = jiv$(EXEEXT)
+ at HAVE_OPENGL_TRUE@am__EXEEXT_2 = jiv$(EXEEXT)
+am__installdirs = "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)"
+binPROGRAMS_INSTALL = $(INSTALL_PROGRAM)
+PROGRAMS = $(bin_PROGRAMS)
+am_dummy_OBJECTS = dummy.$(OBJEXT)
+dummy_OBJECTS = $(am_dummy_OBJECTS)
+am__DEPENDENCIES_1 = ../libjasper/libjasper.la
+dummy_DEPENDENCIES = $(am__DEPENDENCIES_1)
+am_dummy2_OBJECTS = dummy2.$(OBJEXT)
+dummy2_OBJECTS = $(am_dummy2_OBJECTS)
+dummy2_DEPENDENCIES = $(am__DEPENDENCIES_1)
+am_imgcmp_OBJECTS = imgcmp.$(OBJEXT)
+imgcmp_OBJECTS = $(am_imgcmp_OBJECTS)
+imgcmp_DEPENDENCIES = $(am__DEPENDENCIES_1)
+am_imginfo_OBJECTS = imginfo.$(OBJEXT)
+imginfo_OBJECTS = $(am_imginfo_OBJECTS)
+imginfo_DEPENDENCIES = $(am__DEPENDENCIES_1)
+am_jasper_OBJECTS = jasper.$(OBJEXT)
+jasper_OBJECTS = $(am_jasper_OBJECTS)
+jasper_DEPENDENCIES = $(am__DEPENDENCIES_1)
+am_jiv_OBJECTS = jiv.$(OBJEXT)
+jiv_OBJECTS = $(am_jiv_OBJECTS)
+am__DEPENDENCIES_2 =
+jiv_DEPENDENCIES = $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_2)
+am_tmrdemo_OBJECTS = tmrdemo.$(OBJEXT)
+tmrdemo_OBJECTS = $(am_tmrdemo_OBJECTS)
+tmrdemo_DEPENDENCIES = $(am__DEPENDENCIES_1)
+DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/src/libjasper/include/jasper
+depcomp = $(SHELL) $(top_srcdir)/acaux/depcomp
+am__depfiles_maybe = depfiles
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LTCOMPILE = $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) \
+ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+ $(AM_CFLAGS) $(CFLAGS)
+CCLD = $(CC)
+LINK = $(LIBTOOL) --tag=CC --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+ $(AM_LDFLAGS) $(LDFLAGS) -o $@
+SOURCES = $(dummy_SOURCES) $(dummy2_SOURCES) $(imgcmp_SOURCES) \
+ $(imginfo_SOURCES) $(jasper_SOURCES) $(jiv_SOURCES) \
+ $(tmrdemo_SOURCES)
+DIST_SOURCES = $(dummy_SOURCES) $(dummy2_SOURCES) $(imgcmp_SOURCES) \
+ $(imginfo_SOURCES) $(jasper_SOURCES) $(jiv_SOURCES) \
+ $(tmrdemo_SOURCES)
+man1dir = $(mandir)/man1
+NROFF = nroff
+MANS = $(man_MANS)
+ETAGS = etags
+CTAGS = ctags
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+ at HAVE_OPENGL_FALSE@BIN_JIV =
+ at HAVE_OPENGL_TRUE@BIN_JIV = jiv
+ at HAVE_OPENGL_FALSE@EXTRA_JIV = jiv
+ at HAVE_OPENGL_TRUE@EXTRA_JIV =
+jasper_SOURCES = jasper.c
+imgcmp_SOURCES = imgcmp.c
+imginfo_SOURCES = imginfo.c
+dummy_SOURCES = dummy.c
+dummy2_SOURCES = dummy2.c
+tmrdemo_SOURCES = tmrdemo.c
+jiv_SOURCES = jiv.c
+man_MANS = imgcmp.1 imginfo.1 jasper.1 jiv.1
+EXTRA_DIST = $(man_MANS)
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
+MYLDFLAGS = ../libjasper/libjasper.la
+jasper_LDADD = $(MYLDFLAGS)
+imgcmp_LDADD = $(MYLDFLAGS)
+imginfo_LDADD = $(MYLDFLAGS)
+jiv_LDADD = $(MYLDFLAGS) $(OPENGL_LIBS)
+dummy_LDADD = $(MYLDFLAGS)
+dummy2_LDADD = $(MYLDFLAGS)
+tmrdemo_LDADD = $(MYLDFLAGS)
+all: all-am
+
+.SUFFIXES:
+.SUFFIXES: .c .lo .o .obj
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/appl/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/appl/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+install-binPROGRAMS: $(bin_PROGRAMS)
+ @$(NORMAL_INSTALL)
+ test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)"
+ @list='$(bin_PROGRAMS)'; for p in $$list; do \
+ p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \
+ if test -f $$p \
+ || test -f $$p1 \
+ ; then \
+ f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
+ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
+ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
+ else :; fi; \
+ done
+
+uninstall-binPROGRAMS:
+ @$(NORMAL_UNINSTALL)
+ @list='$(bin_PROGRAMS)'; for p in $$list; do \
+ f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \
+ echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
+ rm -f "$(DESTDIR)$(bindir)/$$f"; \
+ done
+
+clean-binPROGRAMS:
+ @list='$(bin_PROGRAMS)'; for p in $$list; do \
+ f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \
+ echo " rm -f $$p $$f"; \
+ rm -f $$p $$f ; \
+ done
+dummy$(EXEEXT): $(dummy_OBJECTS) $(dummy_DEPENDENCIES)
+ @rm -f dummy$(EXEEXT)
+ $(LINK) $(dummy_LDFLAGS) $(dummy_OBJECTS) $(dummy_LDADD) $(LIBS)
+dummy2$(EXEEXT): $(dummy2_OBJECTS) $(dummy2_DEPENDENCIES)
+ @rm -f dummy2$(EXEEXT)
+ $(LINK) $(dummy2_LDFLAGS) $(dummy2_OBJECTS) $(dummy2_LDADD) $(LIBS)
+imgcmp$(EXEEXT): $(imgcmp_OBJECTS) $(imgcmp_DEPENDENCIES)
+ @rm -f imgcmp$(EXEEXT)
+ $(LINK) $(imgcmp_LDFLAGS) $(imgcmp_OBJECTS) $(imgcmp_LDADD) $(LIBS)
+imginfo$(EXEEXT): $(imginfo_OBJECTS) $(imginfo_DEPENDENCIES)
+ @rm -f imginfo$(EXEEXT)
+ $(LINK) $(imginfo_LDFLAGS) $(imginfo_OBJECTS) $(imginfo_LDADD) $(LIBS)
+jasper$(EXEEXT): $(jasper_OBJECTS) $(jasper_DEPENDENCIES)
+ @rm -f jasper$(EXEEXT)
+ $(LINK) $(jasper_LDFLAGS) $(jasper_OBJECTS) $(jasper_LDADD) $(LIBS)
+jiv$(EXEEXT): $(jiv_OBJECTS) $(jiv_DEPENDENCIES)
+ @rm -f jiv$(EXEEXT)
+ $(LINK) $(jiv_LDFLAGS) $(jiv_OBJECTS) $(jiv_LDADD) $(LIBS)
+tmrdemo$(EXEEXT): $(tmrdemo_OBJECTS) $(tmrdemo_DEPENDENCIES)
+ @rm -f tmrdemo$(EXEEXT)
+ $(LINK) $(tmrdemo_LDFLAGS) $(tmrdemo_OBJECTS) $(tmrdemo_LDADD) $(LIBS)
+
+mostlyclean-compile:
+ -rm -f *.$(OBJEXT)
+
+distclean-compile:
+ -rm -f *.tab.c
+
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/dummy.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/dummy2.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/imgcmp.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/imginfo.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jasper.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jiv.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/tmrdemo.Po at am__quote@
+
+.c.o:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c $<
+
+.c.obj:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
+
+.c.lo:
+ at am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $<
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+install-man1: $(man1_MANS) $(man_MANS)
+ @$(NORMAL_INSTALL)
+ test -z "$(man1dir)" || $(mkdir_p) "$(DESTDIR)$(man1dir)"
+ @list='$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
+ l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
+ for i in $$l2; do \
+ case "$$i" in \
+ *.1*) list="$$list $$i" ;; \
+ esac; \
+ done; \
+ for i in $$list; do \
+ if test -f $(srcdir)/$$i; then file=$(srcdir)/$$i; \
+ else file=$$i; fi; \
+ ext=`echo $$i | sed -e 's/^.*\\.//'`; \
+ case "$$ext" in \
+ 1*) ;; \
+ *) ext='1' ;; \
+ esac; \
+ inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
+ inst=`echo $$inst | sed -e 's/^.*\///'`; \
+ inst=`echo $$inst | sed '$(transform)'`.$$ext; \
+ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
+ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \
+ done
+uninstall-man1:
+ @$(NORMAL_UNINSTALL)
+ @list='$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
+ l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
+ for i in $$l2; do \
+ case "$$i" in \
+ *.1*) list="$$list $$i" ;; \
+ esac; \
+ done; \
+ for i in $$list; do \
+ ext=`echo $$i | sed -e 's/^.*\\.//'`; \
+ case "$$ext" in \
+ 1*) ;; \
+ *) ext='1' ;; \
+ esac; \
+ inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
+ inst=`echo $$inst | sed -e 's/^.*\///'`; \
+ inst=`echo $$inst | sed '$(transform)'`.$$ext; \
+ echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \
+ rm -f "$(DESTDIR)$(man1dir)/$$inst"; \
+ done
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-am
+all-am: Makefile $(PROGRAMS) $(MANS)
+installdirs:
+ for dir in "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)"; do \
+ test -z "$$dir" || $(mkdir_p) "$$dir"; \
+ done
+install: install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-am
+
+clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am
+
+distclean: distclean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+distclean-am: clean-am distclean-compile distclean-generic \
+ distclean-libtool distclean-tags
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+info: info-am
+
+info-am:
+
+install-data-am: install-man
+
+install-exec-am: install-binPROGRAMS
+
+install-info: install-info-am
+
+install-man: install-man1
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-compile mostlyclean-generic \
+ mostlyclean-libtool
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-binPROGRAMS uninstall-info-am uninstall-man
+
+uninstall-man: uninstall-man1
+
+.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \
+ clean-generic clean-libtool ctags distclean distclean-compile \
+ distclean-generic distclean-libtool distclean-tags distdir dvi \
+ dvi-am html html-am info info-am install install-am \
+ install-binPROGRAMS install-data install-data-am install-exec \
+ install-exec-am install-info install-info-am install-man \
+ install-man1 install-strip installcheck installcheck-am \
+ installdirs maintainer-clean maintainer-clean-generic \
+ mostlyclean mostlyclean-compile mostlyclean-generic \
+ mostlyclean-libtool pdf pdf-am ps ps-am tags uninstall \
+ uninstall-am uninstall-binPROGRAMS uninstall-info-am \
+ uninstall-man uninstall-man1
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/appl/dummy.c b/jasper-1.900.1-6ct/src/appl/dummy.c
new file mode 100644
index 0000000..e69de29
diff --git a/jasper-1.900.1-6ct/src/appl/dummy2.c b/jasper-1.900.1-6ct/src/appl/dummy2.c
new file mode 100644
index 0000000..acfd275
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/appl/dummy2.c
@@ -0,0 +1,65 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <jasper.h>
+
+#define FAILED 2
+
+int main(int argc, char **argv)
+{
+ char *refpath;
+ FILE *reffile;
+ char *othpath;
+ FILE *othfile;
+ int c;
+ jas_seq2d_t *x;
+ jas_seq2d_t *y;
+
+ refpath = 0;
+ othpath = 0;
+
+ while ((c = getopt(argc, argv, "f:F:")) != EOF) {
+ switch (c) {
+ case 'f':
+ refpath = optarg;
+ break;
+ case 'F':
+ othpath = optarg;
+ break;
+ }
+ }
+
+ if (!refpath || !othpath) {
+ fprintf(stderr, "usage: %s -f reffile -F othfile\n", argv[0]);
+ exit(FAILED);
+ }
+
+ if (!(reffile = fopen(refpath, "r"))) {
+ fprintf(stderr, "cannot open %s\n", refpath);
+ exit(FAILED);
+ }
+ if (!(othfile = fopen(othpath, "r"))) {
+ fprintf(stderr, "cannot open %s\n", othpath);
+ exit(FAILED);
+ }
+
+ if (!(x = jas_seq2d_input(reffile))) {
+ fprintf(stderr, "cannot input reference\n");
+ exit(FAILED);
+ }
+ if (!(y = jas_seq2d_input(othfile))) {
+ fprintf(stderr, "cannot input other\n");
+ exit(FAILED);
+ }
+
+ if (!jas_matrix_cmp(x, y)) {
+ fprintf(stderr, "equal\n");
+ exit(0);
+ } else {
+ fprintf(stderr, "not equal\n");
+ exit(1);
+ }
+
+ exit(FAILED);
+
+}
+
diff --git a/jasper-1.900.1-6ct/src/appl/imgcmp.1 b/jasper-1.900.1-6ct/src/appl/imgcmp.1
new file mode 100644
index 0000000..efc65d4
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/appl/imgcmp.1
@@ -0,0 +1,24 @@
+.TH imgcmp 1 "20 June 2004" "Version 1.701.0" "JasPer Manual"
+
+.SH NAME
+imgcmp \- Image comparison utility
+
+.SH SYNOPSIS
+.B imgcmp
+.RI [ options ]
+
+.SH DESCRIPTION
+The
+.B imgcmp
+command compares two images of the same geometry with respect to a given
+metric.
+Please use the \-\-help command
+line switch and the JasPer Software Reference Manual for more information.
+
+.SH SEE ALSO
+.IR jasper (1)
+
+.SH AUTHOR
+Michael D. Adams <mdadams at ieee.org>
+This manpage was initially written by Roland Stigge <stigge at antcom.de> for
+the Debian Project.
diff --git a/jasper-1.900.1-6ct/src/appl/imgcmp.c b/jasper-1.900.1-6ct/src/appl/imgcmp.c
new file mode 100644
index 0000000..255b581
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/appl/imgcmp.c
@@ -0,0 +1,576 @@
+/*
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Image Comparison Program
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+#include <float.h>
+#include <assert.h>
+
+#include <jasper/jasper.h>
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+typedef enum {
+ OPT_HELP,
+ OPT_VERSION,
+ OPT_VERBOSE,
+ OPT_ORIG,
+ OPT_RECON,
+ OPT_METRIC,
+ OPT_MAXONLY,
+ OPT_MINONLY,
+ OPT_DIFFIMAGE
+} optid_t;
+
+typedef enum {
+ metricid_none = 0,
+ metricid_equal,
+ metricid_psnr,
+ metricid_mse,
+ metricid_rmse,
+ metricid_pae,
+ metricid_mae
+} metricid_t;
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+double getdistortion(jas_matrix_t *orig, jas_matrix_t *recon, int depth, int metric);
+double pae(jas_matrix_t *x, jas_matrix_t *y);
+double msen(jas_matrix_t *x, jas_matrix_t *y, int n);
+double psnr(jas_matrix_t *x, jas_matrix_t *y, int depth);
+jas_image_t *makediffimage(jas_matrix_t *origdata, jas_matrix_t *recondata);
+void usage(void);
+void cmdinfo(void);
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static jas_taginfo_t metrictab[] = {
+ {metricid_mse, "mse"},
+ {metricid_pae, "pae"},
+ {metricid_rmse, "rmse"},
+ {metricid_psnr, "psnr"},
+ {metricid_mae, "mae"},
+ {metricid_equal, "equal"},
+ {-1, 0}
+};
+
+static jas_opt_t opts[] = {
+ {OPT_HELP, "help", 0},
+ {OPT_VERSION, "version", 0},
+ {OPT_VERBOSE, "verbose", 0},
+ {OPT_ORIG, "f", JAS_OPT_HASARG},
+ {OPT_RECON, "F", JAS_OPT_HASARG},
+ {OPT_METRIC, "m", JAS_OPT_HASARG},
+ {OPT_MAXONLY, "max", 0},
+ {OPT_MINONLY, "min", 0},
+ {OPT_DIFFIMAGE, "d", JAS_OPT_HASARG},
+ {-1, 0, 0}
+};
+
+static char *cmdname = 0;
+
+/******************************************************************************\
+* Main program.
+\******************************************************************************/
+
+int main(int argc, char **argv)
+{
+ char *origpath;
+ char *reconpath;
+ int verbose;
+ char *metricname;
+ int metric;
+
+ int id;
+ jas_image_t *origimage;
+ jas_image_t *reconimage;
+ jas_matrix_t *origdata;
+ jas_matrix_t *recondata;
+ jas_image_t *diffimage;
+ jas_stream_t *diffstream;
+ int width;
+ int height;
+ int depth;
+ int numcomps;
+ double d;
+ double maxdist;
+ double mindist;
+ int compno;
+ jas_stream_t *origstream;
+ jas_stream_t *reconstream;
+ char *diffpath;
+ int maxonly;
+ int minonly;
+ int fmtid;
+
+ verbose = 0;
+ origpath = 0;
+ reconpath = 0;
+ metricname = 0;
+ metric = metricid_none;
+ diffpath = 0;
+ maxonly = 0;
+ minonly = 0;
+
+ if (jas_init()) {
+ abort();
+ }
+
+ cmdname = argv[0];
+
+ /* Parse the command line options. */
+ while ((id = jas_getopt(argc, argv, opts)) >= 0) {
+ switch (id) {
+ case OPT_MAXONLY:
+ maxonly = 1;
+ break;
+ case OPT_MINONLY:
+ minonly = 1;
+ break;
+ case OPT_METRIC:
+ metricname = jas_optarg;
+ break;
+ case OPT_ORIG:
+ origpath = jas_optarg;
+ break;
+ case OPT_RECON:
+ reconpath = jas_optarg;
+ break;
+ case OPT_VERBOSE:
+ verbose = 1;
+ break;
+ case OPT_DIFFIMAGE:
+ diffpath = jas_optarg;
+ break;
+ case OPT_VERSION:
+ printf("%s\n", JAS_VERSION);
+ exit(EXIT_SUCCESS);
+ break;
+ case OPT_HELP:
+ default:
+ usage();
+ break;
+ }
+ }
+
+ if (verbose) {
+ cmdinfo();
+ }
+
+ /* Ensure that files are given for both the original and reconstructed
+ images. */
+ if (!origpath || !reconpath) {
+ usage();
+ }
+
+ /* If a metric was specified, process it. */
+ if (metricname) {
+ if ((metric = (jas_taginfo_nonull(jas_taginfos_lookup(metrictab,
+ metricname))->id)) < 0) {
+ usage();
+ }
+ }
+
+ /* Open the original image file. */
+ if (!(origstream = jas_stream_fopen(origpath, "rb"))) {
+ fprintf(stderr, "cannot open %s\n", origpath);
+ return EXIT_FAILURE;
+ }
+
+ /* Open the reconstructed image file. */
+ if (!(reconstream = jas_stream_fopen(reconpath, "rb"))) {
+ fprintf(stderr, "cannot open %s\n", reconpath);
+ return EXIT_FAILURE;
+ }
+
+ /* Decode the original image. */
+ if (!(origimage = jas_image_decode(origstream, -1, 0))) {
+ fprintf(stderr, "cannot load original image\n");
+ return EXIT_FAILURE;
+ }
+
+ /* Decoder the reconstructed image. */
+ if (!(reconimage = jas_image_decode(reconstream, -1, 0))) {
+ fprintf(stderr, "cannot load reconstructed image\n");
+ return EXIT_FAILURE;
+ }
+
+ /* Close the original image file. */
+ jas_stream_close(origstream);
+
+ /* Close the reconstructed image file. */
+ jas_stream_close(reconstream);
+
+ /* Ensure that both images have the same number of components. */
+ numcomps = jas_image_numcmpts(origimage);
+ if (jas_image_numcmpts(reconimage) != numcomps) {
+ fprintf(stderr, "number of components differ\n");
+ return EXIT_FAILURE;
+ }
+
+ /* Compute the difference for each component. */
+ maxdist = 0;
+ mindist = FLT_MAX;
+ for (compno = 0; compno < numcomps; ++compno) {
+ width = jas_image_cmptwidth(origimage, compno);
+ height = jas_image_cmptheight(origimage, compno);
+ depth = jas_image_cmptprec(origimage, compno);
+ if (jas_image_cmptwidth(reconimage, compno) != width ||
+ jas_image_cmptheight(reconimage, compno) != height) {
+ fprintf(stderr, "image dimensions differ\n");
+ return EXIT_FAILURE;
+ }
+ if (jas_image_cmptprec(reconimage, compno) != depth) {
+ fprintf(stderr, "precisions differ\n");
+ return EXIT_FAILURE;
+ }
+
+ if (!(origdata = jas_matrix_create(height, width))) {
+ fprintf(stderr, "internal error\n");
+ return EXIT_FAILURE;
+ }
+ if (!(recondata = jas_matrix_create(height, width))) {
+ fprintf(stderr, "internal error\n");
+ return EXIT_FAILURE;
+ }
+ if (jas_image_readcmpt(origimage, compno, 0, 0, width, height,
+ origdata)) {
+ fprintf(stderr, "cannot read component data\n");
+ return EXIT_FAILURE;
+ }
+ if (jas_image_readcmpt(reconimage, compno, 0, 0, width, height,
+ recondata)) {
+ fprintf(stderr, "cannot read component data\n");
+ return EXIT_FAILURE;
+ }
+
+ if (diffpath) {
+ if (!(diffstream = jas_stream_fopen(diffpath, "rwb"))) {
+ fprintf(stderr, "cannot open diff stream\n");
+ return EXIT_FAILURE;
+ }
+ if (!(diffimage = makediffimage(origdata, recondata))) {
+ fprintf(stderr, "cannot make diff image\n");
+ return EXIT_FAILURE;
+ }
+ fmtid = jas_image_strtofmt("pnm");
+ if (jas_image_encode(diffimage, diffstream, fmtid, 0)) {
+ fprintf(stderr, "cannot save\n");
+ return EXIT_FAILURE;
+ }
+ jas_stream_close(diffstream);
+ jas_image_destroy(diffimage);
+ }
+
+ if (metric != metricid_none) {
+ d = getdistortion(origdata, recondata, depth, metric);
+ if (d > maxdist) {
+ maxdist = d;
+ }
+ if (d < mindist) {
+ mindist = d;
+ }
+ if (!maxonly && !minonly) {
+ if (metric == metricid_pae || metric == metricid_equal) {
+ printf("%ld\n", (long) ceil(d));
+ } else {
+ printf("%f\n", d);
+ }
+ }
+ }
+ jas_matrix_destroy(origdata);
+ jas_matrix_destroy(recondata);
+ }
+
+ if (metric != metricid_none && (maxonly || minonly)) {
+ if (maxonly) {
+ d = maxdist;
+ } else if (minonly) {
+ d = mindist;
+ } else {
+ abort();
+ }
+
+ if (metric == metricid_pae || metric == metricid_equal) {
+ printf("%ld\n", (long) ceil(d));
+ } else {
+ printf("%f\n", d);
+ }
+ }
+
+ jas_image_destroy(origimage);
+ jas_image_destroy(reconimage);
+ jas_image_clearfmts();
+
+ return EXIT_SUCCESS;
+}
+
+/******************************************************************************\
+* Distortion metric computation functions.
+\******************************************************************************/
+
+double getdistortion(jas_matrix_t *orig, jas_matrix_t *recon, int depth, int metric)
+{
+ double d;
+
+ switch (metric) {
+ case metricid_psnr:
+ default:
+ d = psnr(orig, recon, depth);
+ break;
+ case metricid_mae:
+ d = msen(orig, recon, 1);
+ break;
+ case metricid_mse:
+ d = msen(orig, recon, 2);
+ break;
+ case metricid_rmse:
+ d = sqrt(msen(orig, recon, 2));
+ break;
+ case metricid_pae:
+ d = pae(orig, recon);
+ break;
+ case metricid_equal:
+ d = (pae(orig, recon) == 0) ? 0 : 1;
+ break;
+ }
+ return d;
+}
+
+/* Compute peak absolute error. */
+
+double pae(jas_matrix_t *x, jas_matrix_t *y)
+{
+ double s;
+ double d;
+ int i;
+ int j;
+
+ s = 0.0;
+ for (i = 0; i < jas_matrix_numrows(x); i++) {
+ for (j = 0; j < jas_matrix_numcols(x); j++) {
+ d = abs(jas_matrix_get(y, i, j) - jas_matrix_get(x, i, j));
+ if (d > s) {
+ s = d;
+ }
+ }
+ }
+
+ return s;
+}
+
+/* Compute either mean-squared error or mean-absolute error. */
+
+double msen(jas_matrix_t *x, jas_matrix_t *y, int n)
+{
+ double s;
+ double d;
+ int i;
+ int j;
+
+ s = 0.0;
+ for (i = 0; i < jas_matrix_numrows(x); i++) {
+ for (j = 0; j < jas_matrix_numcols(x); j++) {
+ d = jas_matrix_get(y, i, j) - jas_matrix_get(x, i, j);
+ if (n == 1) {
+ s += fabs(d);
+ } else if (n == 2) {
+ s += d * d;
+ } else {
+ abort();
+ }
+ }
+ }
+
+ return s / ((double) jas_matrix_numrows(x) * jas_matrix_numcols(x));
+}
+
+/* Compute peak signal-to-noise ratio. */
+
+double psnr(jas_matrix_t *x, jas_matrix_t *y, int depth)
+{
+ double m;
+ double p;
+ m = msen(x, y, 2);
+ p = ((1 << depth) - 1);
+ return 20.0 * log10(p / sqrt(m));
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+jas_image_t *makediffimage(jas_matrix_t *origdata, jas_matrix_t *recondata)
+{
+ jas_image_t *diffimage;
+ jas_matrix_t *diffdata[3];
+ int width;
+ int height;
+ int i;
+ int j;
+ int k;
+ jas_image_cmptparm_t compparms[3];
+ jas_seqent_t a;
+ jas_seqent_t b;
+
+ width = jas_matrix_numcols(origdata);
+ height = jas_matrix_numrows(origdata);
+
+ for (i = 0; i < 3; ++i) {
+ compparms[i].tlx = 0;
+ compparms[i].tly = 0;
+ compparms[i].hstep = 1;
+ compparms[i].vstep = 1;
+ compparms[i].width = width;
+ compparms[i].height = height;
+ compparms[i].prec = 8;
+ compparms[i].sgnd = false;
+ }
+ if (!(diffimage = jas_image_create(3, compparms, JAS_CLRSPC_SRGB))) {
+ abort();
+ }
+
+ for (i = 0; i < 3; ++i) {
+ if (!(diffdata[i] = jas_matrix_create(height, width))) {
+ fprintf(stderr, "internal error\n");
+ return 0;
+ }
+ }
+
+ for (j = 0; j < height; ++j) {
+ for (k = 0; k < width; ++k) {
+ a = jas_matrix_get(origdata, j, k);
+ b = jas_matrix_get(recondata, j, k);
+ if (a > b) {
+ jas_matrix_set(diffdata[0], j, k, 255);
+ jas_matrix_set(diffdata[1], j, k, 0);
+ jas_matrix_set(diffdata[2], j, k, 0);
+ } else if (a < b) {
+ jas_matrix_set(diffdata[0], j, k, 0);
+ jas_matrix_set(diffdata[1], j, k, 255);
+ jas_matrix_set(diffdata[2], j, k, 0);
+ } else {
+ jas_matrix_set(diffdata[0], j, k, a);
+ jas_matrix_set(diffdata[1], j, k, a);
+ jas_matrix_set(diffdata[2], j, k, a);
+ }
+ }
+ }
+
+ for (i = 0; i < 3; ++i) {
+ if (jas_image_writecmpt(diffimage, i, 0, 0, width, height, diffdata[i])) {
+ return 0;
+ }
+ }
+
+ return diffimage;
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+void cmdinfo()
+{
+ fprintf(stderr, "Image Comparison Utility (Version %s).\n",
+ JAS_VERSION);
+ fprintf(stderr,
+ "Copyright (c) 2001 Michael David Adams.\n"
+ "All rights reserved.\n"
+ );
+}
+
+void usage()
+{
+ cmdinfo();
+ fprintf(stderr, "usage:\n");
+ fprintf(stderr,"%s ", cmdname);
+ fprintf(stderr,
+ "-f reference_image_file -F other_image_file [-m metric]\n"
+ );
+ fprintf(stderr,
+ "The metric argument may assume one of the following values:\n"
+ " psnr .... peak signal to noise ratio\n"
+ " mse ..... mean squared error\n"
+ " rmse .... root mean squared error\n"
+ " pae ..... peak absolute error\n"
+ " mae ..... mean absolute error\n"
+ " equal ... equality (boolean)\n"
+ );
+ exit(EXIT_FAILURE);
+}
diff --git a/jasper-1.900.1-6ct/src/appl/imginfo.1 b/jasper-1.900.1-6ct/src/appl/imginfo.1
new file mode 100644
index 0000000..34ae656
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/appl/imginfo.1
@@ -0,0 +1,23 @@
+.TH imginfo 1 "20 June 2004" "Version 1.701.0" "JasPer Manual"
+
+.SH NAME
+imginfo \- Image information utility
+
+.SH SYNOPSIS
+.B imginfo
+.RI [ options ]
+
+.SH DESCRIPTION
+The
+.B imginfo
+command displays information about an image.
+Please use the \-\-help command
+line switch and the JasPer Software Reference Manual for more information.
+
+.SH SEE ALSO
+.IR jasper (1)
+
+.SH AUTHOR
+Michael D. Adams <mdadams at ieee.org>
+This manpage was initially written by Roland Stigge <stigge at antcom.de> for
+the Debian Project.
diff --git a/jasper-1.900.1-6ct/src/appl/imginfo.c b/jasper-1.900.1-6ct/src/appl/imginfo.c
new file mode 100644
index 0000000..8af19e9
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/appl/imginfo.c
@@ -0,0 +1,223 @@
+/*
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Image Information Program
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+#include <float.h>
+#include <assert.h>
+
+#include <jasper/jasper.h>
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+typedef enum {
+ OPT_HELP,
+ OPT_VERSION,
+ OPT_VERBOSE,
+ OPT_INFILE
+} optid_t;
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void usage(void);
+static void cmdinfo(void);
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static jas_opt_t opts[] = {
+ {OPT_HELP, "help", 0},
+ {OPT_VERSION, "version", 0},
+ {OPT_VERBOSE, "verbose", 0},
+ {OPT_INFILE, "f", JAS_OPT_HASARG},
+ {-1, 0, 0}
+};
+
+static char *cmdname = 0;
+
+/******************************************************************************\
+* Main program.
+\******************************************************************************/
+
+int main(int argc, char **argv)
+{
+ int fmtid;
+ int id;
+ char *infile;
+ jas_stream_t *instream;
+ jas_image_t *image;
+ int width;
+ int height;
+ int depth;
+ int numcmpts;
+ int verbose;
+ char *fmtname;
+
+ if (jas_init()) {
+ abort();
+ }
+
+ cmdname = argv[0];
+
+ infile = 0;
+ verbose = 0;
+
+ /* Parse the command line options. */
+ while ((id = jas_getopt(argc, argv, opts)) >= 0) {
+ switch (id) {
+ case OPT_VERBOSE:
+ verbose = 1;
+ break;
+ case OPT_VERSION:
+ printf("%s\n", JAS_VERSION);
+ exit(EXIT_SUCCESS);
+ break;
+ case OPT_INFILE:
+ infile = jas_optarg;
+ break;
+ case OPT_HELP:
+ default:
+ usage();
+ break;
+ }
+ }
+
+ /* Open the image file. */
+ if (infile) {
+ /* The image is to be read from a file. */
+ if (!(instream = jas_stream_fopen(infile, "rb"))) {
+ fprintf(stderr, "cannot open input image file %s\n", infile);
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ /* The image is to be read from standard input. */
+ if (!(instream = jas_stream_fdopen(0, "rb"))) {
+ fprintf(stderr, "cannot open standard input\n");
+ exit(EXIT_FAILURE);
+ }
+ }
+
+ if ((fmtid = jas_image_getfmt(instream)) < 0) {
+ fprintf(stderr, "unknown image format\n");
+ }
+
+ /* Decode the image. */
+ if (!(image = jas_image_decode(instream, fmtid, 0))) {
+ fprintf(stderr, "cannot load image\n");
+ return EXIT_FAILURE;
+ }
+
+ /* Close the image file. */
+ jas_stream_close(instream);
+
+ numcmpts = jas_image_numcmpts(image);
+ width = jas_image_cmptwidth(image, 0);
+ height = jas_image_cmptheight(image, 0);
+ depth = jas_image_cmptprec(image, 0);
+ if (!(fmtname = jas_image_fmttostr(fmtid))) {
+ abort();
+ }
+ printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image));
+
+ jas_image_destroy(image);
+ jas_image_clearfmts();
+
+ return EXIT_SUCCESS;
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void cmdinfo()
+{
+ fprintf(stderr, "Image Information Utility (Version %s).\n",
+ JAS_VERSION);
+ fprintf(stderr,
+ "Copyright (c) 2001 Michael David Adams.\n"
+ "All rights reserved.\n"
+ );
+}
+
+static void usage()
+{
+ cmdinfo();
+ fprintf(stderr, "usage:\n");
+ fprintf(stderr,"%s ", cmdname);
+ fprintf(stderr, "[-f image_file]\n");
+ exit(EXIT_FAILURE);
+}
diff --git a/jasper-1.900.1-6ct/src/appl/jasper.1 b/jasper-1.900.1-6ct/src/appl/jasper.1
new file mode 100644
index 0000000..f0f74a1
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/appl/jasper.1
@@ -0,0 +1,19 @@
+.TH jasper 1 "20 June 2004" "Version 1.701.0" "JasPer Manual"
+
+.SH NAME
+jasper \- File format converter specialized in JPEG-2000 encoding
+
+.SH SYNOPSIS
+.B jasper
+.RI [ options ]
+
+.SH DESCRIPTION
+The
+.B jasper
+command converts to and from JPEG-2000 files. Please use the \-\-help command
+line switch and the JasPer Software Reference Manual for more information.
+
+.SH AUTHOR
+Michael D. Adams <mdadams at ieee.org>
+This manpage was initially written by Roland Stigge <stigge at antcom.de> for
+the Debian Project.
diff --git a/jasper-1.900.1-6ct/src/appl/jasper.c b/jasper-1.900.1-6ct/src/appl/jasper.c
new file mode 100644
index 0000000..6900029
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/appl/jasper.c
@@ -0,0 +1,555 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JasPer Transcoder Program
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <time.h>
+
+#include <jasper/jasper.h>
+#include <jasper/jas_debug.h>
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+#define OPTSMAX 4096
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* Encoder command line options. */
+
+typedef struct {
+
+ char *infile;
+ /* The input image file. */
+
+ int infmt;
+ /* The input image file format. */
+
+ char *inopts;
+ char inoptsbuf[OPTSMAX + 1];
+
+ char *outfile;
+ /* The output image file. */
+
+ int outfmt;
+
+ char *outopts;
+ char outoptsbuf[OPTSMAX + 1];
+
+ int verbose;
+ /* Verbose mode. */
+
+ int debug;
+
+ int version;
+
+ int_fast32_t cmptno;
+
+ int srgb;
+
+} cmdopts_t;
+
+/******************************************************************************\
+* Local prototypes.
+\******************************************************************************/
+
+cmdopts_t *cmdopts_parse(int argc, char **argv);
+void cmdopts_destroy(cmdopts_t *cmdopts);
+void cmdusage(void);
+void badusage(void);
+void cmdinfo(void);
+int addopt(char *optstr, int maxlen, char *s);
+
+/******************************************************************************\
+* Global data.
+\******************************************************************************/
+
+char *cmdname = "";
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+int main(int argc, char **argv)
+{
+ jas_image_t *image;
+ cmdopts_t *cmdopts;
+ jas_stream_t *in;
+ jas_stream_t *out;
+ jas_tmr_t dectmr;
+ jas_tmr_t enctmr;
+ double dectime;
+ double enctime;
+ int_fast16_t numcmpts;
+ int i;
+
+ /* Determine the base name of this command. */
+ if ((cmdname = strrchr(argv[0], '/'))) {
+ ++cmdname;
+ } else {
+ cmdname = argv[0];
+ }
+
+ if (jas_init()) {
+ abort();
+ }
+
+ /* Parse the command line options. */
+ if (!(cmdopts = cmdopts_parse(argc, argv))) {
+ fprintf(stderr, "error: cannot parse command line\n");
+ exit(EXIT_FAILURE);
+ }
+
+ if (cmdopts->version) {
+ printf("%s\n", JAS_VERSION);
+ fprintf(stderr, "libjasper %s\n", jas_getversion());
+ exit(EXIT_SUCCESS);
+ }
+
+ jas_setdbglevel(cmdopts->debug);
+
+ if (cmdopts->verbose) {
+ cmdinfo();
+ }
+
+ /* Open the input image file. */
+ if (cmdopts->infile) {
+ /* The input image is to be read from a file. */
+ if (!(in = jas_stream_fopen(cmdopts->infile, "rb"))) {
+ fprintf(stderr, "error: cannot open input image file %s\n",
+ cmdopts->infile);
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ /* The input image is to be read from standard input. */
+ if (!(in = jas_stream_fdopen(0, "rb"))) {
+ fprintf(stderr, "error: cannot open standard input\n");
+ exit(EXIT_FAILURE);
+ }
+ }
+
+ /* Open the output image file. */
+ if (cmdopts->outfile) {
+ /* The output image is to be written to a file. */
+ if (!(out = jas_stream_fopen(cmdopts->outfile, "w+b"))) {
+ fprintf(stderr, "error: cannot open output image file %s\n",
+ cmdopts->outfile);
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ /* The output image is to be written to standard output. */
+ if (!(out = jas_stream_fdopen(1, "w+b"))) {
+ fprintf(stderr, "error: cannot open standard output\n");
+ exit(EXIT_FAILURE);
+ }
+ }
+
+ if (cmdopts->infmt < 0) {
+ if ((cmdopts->infmt = jas_image_getfmt(in)) < 0) {
+ fprintf(stderr, "error: input image has unknown format\n");
+ exit(EXIT_FAILURE);
+ }
+ }
+
+ /* Get the input image data. */
+ jas_tmr_start(&dectmr);
+ if (!(image = jas_image_decode(in, cmdopts->infmt, cmdopts->inopts))) {
+ fprintf(stderr, "error: cannot load image data\n");
+ exit(EXIT_FAILURE);
+ }
+ jas_tmr_stop(&dectmr);
+ dectime = jas_tmr_get(&dectmr);
+
+ /* If requested, throw away all of the components except one.
+ Why might this be desirable? It is a hack, really.
+ None of the image formats other than the JPEG-2000 ones support
+ images with two, four, five, or more components. This hack
+ allows such images to be decoded with the non-JPEG-2000 decoders,
+ one component at a time. */
+ numcmpts = jas_image_numcmpts(image);
+ if (cmdopts->cmptno >= 0 && cmdopts->cmptno < numcmpts) {
+ for (i = numcmpts - 1; i >= 0; --i) {
+ if (i != cmdopts->cmptno) {
+ jas_image_delcmpt(image, i);
+ }
+ }
+ }
+
+ if (cmdopts->srgb) {
+ jas_image_t *newimage;
+ jas_cmprof_t *outprof;
+ jas_eprintf("forcing conversion to sRGB\n");
+ if (!(outprof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB))) {
+ jas_eprintf("cannot create sRGB profile\n");
+ exit(EXIT_FAILURE);
+ }
+ if (!(newimage = jas_image_chclrspc(image, outprof, JAS_CMXFORM_INTENT_PER))) {
+ jas_eprintf("cannot convert to sRGB\n");
+ exit(EXIT_FAILURE);
+ }
+ jas_image_destroy(image);
+ jas_cmprof_destroy(outprof);
+ image = newimage;
+ }
+
+ /* Generate the output image data. */
+ jas_tmr_start(&enctmr);
+ if (jas_image_encode(image, out, cmdopts->outfmt, cmdopts->outopts)) {
+ fprintf(stderr, "error: cannot encode image\n");
+ exit(EXIT_FAILURE);
+ }
+ jas_stream_flush(out);
+ jas_tmr_stop(&enctmr);
+ enctime = jas_tmr_get(&enctmr);
+
+ if (cmdopts->verbose) {
+ fprintf(stderr, "decoding time = %f\n", dectime);
+ fprintf(stderr, "encoding time = %f\n", enctime);
+ }
+
+ /* If this fails, we don't care. */
+ (void) jas_stream_close(in);
+
+ /* Close the output image stream. */
+ if (jas_stream_close(out)) {
+ fprintf(stderr, "error: cannot close output image file\n");
+ exit(EXIT_FAILURE);
+ }
+
+ cmdopts_destroy(cmdopts);
+ jas_image_destroy(image);
+ jas_image_clearfmts();
+
+ /* Success at last! :-) */
+ return EXIT_SUCCESS;
+}
+
+cmdopts_t *cmdopts_parse(int argc, char **argv)
+{
+
+ typedef enum {
+ CMDOPT_HELP = 0,
+ CMDOPT_VERBOSE,
+ CMDOPT_INFILE,
+ CMDOPT_INFMT,
+ CMDOPT_INOPT,
+ CMDOPT_OUTFILE,
+ CMDOPT_OUTFMT,
+ CMDOPT_OUTOPT,
+ CMDOPT_VERSION,
+ CMDOPT_DEBUG,
+ CMDOPT_CMPTNO,
+ CMDOPT_SRGB
+ } cmdoptid_t;
+
+ static jas_opt_t cmdoptions[] = {
+ {CMDOPT_HELP, "help", 0},
+ {CMDOPT_VERBOSE, "verbose", 0},
+ {CMDOPT_INFILE, "input", JAS_OPT_HASARG},
+ {CMDOPT_INFILE, "f", JAS_OPT_HASARG},
+ {CMDOPT_INFMT, "input-format", JAS_OPT_HASARG},
+ {CMDOPT_INFMT, "t", JAS_OPT_HASARG},
+ {CMDOPT_INOPT, "input-option", JAS_OPT_HASARG},
+ {CMDOPT_INOPT, "o", JAS_OPT_HASARG},
+ {CMDOPT_OUTFILE, "output", JAS_OPT_HASARG},
+ {CMDOPT_OUTFILE, "F", JAS_OPT_HASARG},
+ {CMDOPT_OUTFMT, "output-format", JAS_OPT_HASARG},
+ {CMDOPT_OUTFMT, "T", JAS_OPT_HASARG},
+ {CMDOPT_OUTOPT, "output-option", JAS_OPT_HASARG},
+ {CMDOPT_OUTOPT, "O", JAS_OPT_HASARG},
+ {CMDOPT_VERSION, "version", 0},
+ {CMDOPT_DEBUG, "debug-level", JAS_OPT_HASARG},
+ {CMDOPT_CMPTNO, "cmptno", JAS_OPT_HASARG},
+ {CMDOPT_SRGB, "force-srgb", 0},
+ {CMDOPT_SRGB, "S", 0},
+ {-1, 0, 0}
+ };
+
+ cmdopts_t *cmdopts;
+ int c;
+
+ if (!(cmdopts = malloc(sizeof(cmdopts_t)))) {
+ fprintf(stderr, "error: insufficient memory\n");
+ exit(EXIT_FAILURE);
+ }
+
+ cmdopts->infile = 0;
+ cmdopts->infmt = -1;
+ cmdopts->inopts = 0;
+ cmdopts->inoptsbuf[0] = '\0';
+ cmdopts->outfile = 0;
+ cmdopts->outfmt = -1;
+ cmdopts->outopts = 0;
+ cmdopts->outoptsbuf[0] = '\0';
+ cmdopts->verbose = 0;
+ cmdopts->version = 0;
+ cmdopts->cmptno = -1;
+ cmdopts->debug = 0;
+ cmdopts->srgb = 0;
+
+ while ((c = jas_getopt(argc, argv, cmdoptions)) != EOF) {
+ switch (c) {
+ case CMDOPT_HELP:
+ cmdusage();
+ break;
+ case CMDOPT_VERBOSE:
+ cmdopts->verbose = 1;
+ break;
+ case CMDOPT_VERSION:
+ cmdopts->version = 1;
+ break;
+ case CMDOPT_DEBUG:
+ cmdopts->debug = atoi(jas_optarg);
+ break;
+ case CMDOPT_INFILE:
+ cmdopts->infile = jas_optarg;
+ break;
+ case CMDOPT_INFMT:
+ if ((cmdopts->infmt = jas_image_strtofmt(jas_optarg)) < 0) {
+ fprintf(stderr, "warning: ignoring invalid input format %s\n",
+ jas_optarg);
+ cmdopts->infmt = -1;
+ }
+ break;
+ case CMDOPT_INOPT:
+ addopt(cmdopts->inoptsbuf, OPTSMAX, jas_optarg);
+ cmdopts->inopts = cmdopts->inoptsbuf;
+ break;
+ case CMDOPT_OUTFILE:
+ cmdopts->outfile = jas_optarg;
+ break;
+ case CMDOPT_OUTFMT:
+ if ((cmdopts->outfmt = jas_image_strtofmt(jas_optarg)) < 0) {
+ fprintf(stderr, "error: invalid output format %s\n", jas_optarg);
+ badusage();
+ }
+ break;
+ case CMDOPT_OUTOPT:
+ addopt(cmdopts->outoptsbuf, OPTSMAX, jas_optarg);
+ cmdopts->outopts = cmdopts->outoptsbuf;
+ break;
+ case CMDOPT_CMPTNO:
+ cmdopts->cmptno = atoi(jas_optarg);
+ break;
+ case CMDOPT_SRGB:
+ cmdopts->srgb = 1;
+ break;
+ default:
+ badusage();
+ break;
+ }
+ }
+
+ while (jas_optind < argc) {
+ fprintf(stderr,
+ "warning: ignoring bogus command line argument %s\n",
+ argv[jas_optind]);
+ ++jas_optind;
+ }
+
+ if (cmdopts->version) {
+ goto done;
+ }
+
+ if (cmdopts->outfmt < 0 && cmdopts->outfile) {
+ if ((cmdopts->outfmt = jas_image_fmtfromname(cmdopts->outfile)) < 0) {
+ fprintf(stderr,
+ "error: cannot guess image format from output file name\n");
+ }
+ }
+
+ if (cmdopts->outfmt < 0) {
+ fprintf(stderr, "error: no output format specified\n");
+ badusage();
+ }
+
+done:
+ return cmdopts;
+}
+
+void cmdopts_destroy(cmdopts_t *cmdopts)
+{
+ free(cmdopts);
+}
+
+int addopt(char *optstr, int maxlen, char *s)
+{
+ int n;
+ int m;
+
+ n = strlen(optstr);
+ m = n + strlen(s) + 1;
+ if (m > maxlen) {
+ return 1;
+ }
+ if (n > 0) {
+ strcat(optstr, "\n");
+ }
+ strcat(optstr, s);
+ return 0;
+}
+
+void cmdinfo()
+{
+ fprintf(stderr, "JasPer Transcoder (Version %s).\n",
+ JAS_VERSION);
+ fprintf(stderr, "%s\n", JAS_COPYRIGHT);
+ fprintf(stderr, "%s\n", JAS_NOTES);
+}
+
+static char *helpinfo[] = {
+"The following options are supported:\n",
+" --help Print this help information and exit.\n",
+" --version Print version information and exit.\n",
+" --verbose Enable verbose mode.\n",
+" --debug-level $lev Set the debug level to $lev.\n",
+" --input $file Read the input image from the file named $file\n",
+" instead of standard input.\n",
+" --input-format $fmt Specify the format of the input image as $fmt.\n",
+" (See below for the list of supported formats.)\n",
+" --input-option $opt Provide the option $opt to the decoder.\n",
+" --output $file Write the output image to the file named $file\n",
+" instead of standard output.\n",
+" --output-format $fmt Specify the format of the output image as $fmt.\n",
+" (See below for the list of supported formats.)\n",
+" --output-option $opt Provide the option $opt to the encoder.\n",
+" --force-srgb Force conversion to the sRGB color space.\n",
+"Some of the above option names can be abbreviated as follows:\n",
+" --input = -f, --input-format = -t, --input-option = -o,\n",
+" --output = -F, --output-format = -T, --output-option = -O\n",
+0
+};
+
+void cmdusage()
+{
+ int fmtid;
+ jas_image_fmtinfo_t *fmtinfo;
+ char *s;
+ int i;
+ cmdinfo();
+ fprintf(stderr, "usage: %s [options]\n", cmdname);
+ for (i = 0, s = helpinfo[i]; s; ++i, s = helpinfo[i]) {
+ fprintf(stderr, "%s", s);
+ }
+ fprintf(stderr, "The following formats are supported:\n");
+ for (fmtid = 0;; ++fmtid) {
+ if (!(fmtinfo = jas_image_lookupfmtbyid(fmtid))) {
+ break;
+ }
+ fprintf(stderr, " %-5s %s\n", fmtinfo->name,
+ fmtinfo->desc);
+ }
+ exit(EXIT_FAILURE);
+}
+
+void badusage()
+{
+ fprintf(stderr,
+ "For more information on how to use this command, type:\n");
+ fprintf(stderr, " %s --help\n", cmdname);
+ exit(EXIT_FAILURE);
+}
+
+#if 0
+jas_image_t *converttosrgb(jas_image_t *inimage)
+{
+ jas_image_t *outimage;
+ jas_cmpixmap_t inpixmap;
+ jas_cmpixmap_t outpixmap;
+ jas_cmcmptfmt_t incmptfmts[16];
+ jas_cmcmptfmt_t outcmptfmts[16];
+
+ outprof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB);
+ assert(outprof);
+ xform = jas_cmxform_create(jas_image_cmprof(inimage), outprof, 0, JAS_CMXFORM_FWD, JAS_CMXFORM_INTENT_PER, 0);
+ assert(xform);
+
+ inpixmap.numcmpts = jas_image_numcmpts(oldimage);
+ outpixmap.numcmpts = 3;
+ for (i = 0; i < inpixmap.numcmpts; ++i) {
+ inpixmap.cmptfmts[i] = &incmptfmts[i];
+ }
+ for (i = 0; i < outpixmap.numcmpts; ++i)
+ outpixmap.cmptfmts[i] = &outcmptfmts[i];
+ if (jas_cmxform_apply(xform, &inpixmap, &outpixmap))
+ abort();
+
+ jas_xform_destroy(xform);
+ jas_cmprof_destroy(outprof);
+ return 0;
+}
+#endif
diff --git a/jasper-1.900.1-6ct/src/appl/jiv.1 b/jasper-1.900.1-6ct/src/appl/jiv.1
new file mode 100644
index 0000000..2c067f5
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/appl/jiv.1
@@ -0,0 +1,24 @@
+.TH jiv 1 "20 June 2004" "Version 1.701.0" "JasPer Manual"
+
+.SH NAME
+jiv \- Image display utility
+
+.SH SYNOPSIS
+.B jiv
+.RI [ options ]
+.RI [ file ... ]
+
+.SH DESCRIPTION
+The
+.B jiv
+command displays a JPEG-2000 image on an X display. Use the arrow keys for
+scrolling and < and > for zooming. Please use the \-\-help command line switch
+and the JasPer Software Reference Manual for more information.
+
+.SH SEE ALSO
+.IR jasper (1)
+
+.SH AUTHOR
+Michael D. Adams <mdadams at ieee.org>
+This manpage was initially written by Roland Stigge <stigge at antcom.de> for
+the Debian Project.
diff --git a/jasper-1.900.1-6ct/src/appl/jiv.c b/jasper-1.900.1-6ct/src/appl/jiv.c
new file mode 100644
index 0000000..a88f4d4
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/appl/jiv.c
@@ -0,0 +1,1086 @@
+/*
+ * Copyright (c) 2002-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+#include <jasper/jasper.h>
+#include <GL/glut.h>
+#include <stdlib.h>
+#include <math.h>
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+#define MAXCMPTS 256
+#define BIGPANAMOUNT 0.90
+#define SMALLPANAMOUNT 0.05
+#define BIGZOOMAMOUNT 2.0
+#define SMALLZOOMAMOUNT 1.41421356237310
+
+#define min(x, y) (((x) < (y)) ? (x) : (y))
+#define max(x, y) (((x) > (y)) ? (x) : (y))
+
+typedef struct {
+
+ /* The number of image files to view. */
+ int numfiles;
+
+ /* The names of the image files. */
+ char **filenames;
+
+ /* The title for the window. */
+ char *title;
+
+ /* The time to wait before advancing to the next image (in ms). */
+ int tmout;
+
+ /* Loop indefinitely over all images. */
+ int loop;
+
+ int verbose;
+
+} cmdopts_t;
+
+typedef struct {
+
+ int width;
+
+ int height;
+
+ GLshort *data;
+
+} pixmap_t;
+
+typedef struct {
+
+ /* The index of the current image file. */
+ int filenum;
+
+ /* The image. */
+ jas_image_t *image;
+ jas_image_t *altimage;
+
+ float botleftx;
+ float botlefty;
+ float toprightx;
+ float toprighty;
+
+ int viewportwidth;
+ int viewportheight;
+
+ /* The image for display. */
+ pixmap_t vp;
+
+ /* The active timer ID. */
+ int activetmid;
+
+ /* The next available timer ID. */
+ int nexttmid;
+
+ int monomode;
+
+ int cmptno;
+
+} gs_t;
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void displayfunc(void);
+static void reshapefunc(int w, int h);
+static void keyboardfunc(unsigned char key, int x, int y);
+static void specialfunc(int key, int x, int y);
+static void timerfunc(int value);
+
+static void usage(void);
+static void nextimage(void);
+static void previmage(void);
+static void nextcmpt(void);
+static void prevcmpt(void);
+static int loadimage(void);
+static void unloadimage(void);
+static int jas_image_render2(jas_image_t *image, int cmptno, float vtlx, float vtly,
+ float vsx, float vsy, int vw, int vh, GLshort *vdata);
+static int jas_image_render(jas_image_t *image, float vtlx, float vtly,
+ float vsx, float vsy, int vw, int vh, GLshort *vdata);
+
+static void dumpstate(void);
+static int pixmap_resize(pixmap_t *p, int w, int h);
+static void pixmap_clear(pixmap_t *p);
+static void cmdinfo(void);
+
+static void cleanupandexit(int);
+static void init(void);
+
+static void zoom(float sx, float sy);
+static void pan(float dx, float dy);
+static void panzoom(float dx, float dy, float sx, float sy);
+static void render(void);
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+jas_opt_t opts[] = {
+ {'V', "version", 0},
+ {'v', "v", 0},
+ {'h', "help", 0},
+ {'w', "wait", JAS_OPT_HASARG},
+ {'l', "loop", 0},
+ {'t', "title", JAS_OPT_HASARG},
+ {-1, 0, 0}
+};
+
+char *cmdname = 0;
+cmdopts_t cmdopts;
+gs_t gs;
+jas_stream_t *streamin = 0;
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+int main(int argc, char **argv)
+{
+ int c;
+
+ init();
+
+ /* Determine the base name of this command. */
+ if ((cmdname = strrchr(argv[0], '/'))) {
+ ++cmdname;
+ } else {
+ cmdname = argv[0];
+ }
+
+ /* Initialize the JasPer library. */
+ if (jas_init()) {
+ abort();
+ }
+
+ glutInit(&argc, argv);
+ glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
+ glutCreateWindow(cmdname);
+ glutReshapeFunc(reshapefunc);
+ glutDisplayFunc(displayfunc);
+ glutSpecialFunc(specialfunc);
+ glutKeyboardFunc(keyboardfunc);
+
+ cmdopts.numfiles = 0;
+ cmdopts.filenames = 0;
+ cmdopts.title = 0;
+ cmdopts.tmout = 0;
+ cmdopts.loop = 0;
+ cmdopts.verbose = 0;
+
+ while ((c = jas_getopt(argc, argv, opts)) != EOF) {
+ switch (c) {
+ case 'w':
+ cmdopts.tmout = atof(jas_optarg) * 1000;
+ break;
+ case 'l':
+ cmdopts.loop = 1;
+ break;
+ case 't':
+ cmdopts.title = jas_optarg;
+ break;
+ case 'v':
+ cmdopts.verbose = 1;
+ break;
+ case 'V':
+ printf("%s\n", JAS_VERSION);
+ fprintf(stderr, "libjasper %s\n", jas_getversion());
+ cleanupandexit(EXIT_SUCCESS);
+ break;
+ default:
+ case 'h':
+ usage();
+ break;
+ }
+ }
+
+ if (jas_optind < argc) {
+ /* The images are to be read from one or more explicitly named
+ files. */
+ cmdopts.numfiles = argc - jas_optind;
+ cmdopts.filenames = &argv[jas_optind];
+ } else {
+ /* The images are to be read from standard input. */
+ static char *null = 0;
+ cmdopts.filenames = &null;
+ cmdopts.numfiles = 1;
+ }
+
+ streamin = jas_stream_fdopen(0, "rb");
+
+ /* Load the next image. */
+ nextimage();
+
+ /* Start the GLUT main event handler loop. */
+ glutMainLoop();
+
+ return EXIT_SUCCESS;
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void cmdinfo()
+{
+ fprintf(stderr, "JasPer Image Viewer (Version %s).\n",
+ JAS_VERSION);
+ fprintf(stderr, "Copyright (c) 2002-2003 Michael David Adams.\n"
+ "All rights reserved.\n");
+ fprintf(stderr, "%s\n", JAS_NOTES);
+}
+
+static char *helpinfo[] = {
+"The following options are supported:\n",
+" --help Print this help information and exit.\n",
+" --version Print version information and exit.\n",
+" --loop Loop indefinitely through images.\n",
+" --wait N Advance to next image after N seconds.\n",
+0
+};
+
+static void usage()
+{
+ char *s;
+ int i;
+ cmdinfo();
+ fprintf(stderr, "usage: %s [options] [file1 file2 ...]\n", cmdname);
+ for (i = 0, s = helpinfo[i]; s; ++i, s = helpinfo[i]) {
+ fprintf(stderr, "%s", s);
+ }
+ cleanupandexit(EXIT_FAILURE);
+}
+
+/******************************************************************************\
+* GLUT Callback Functions
+\******************************************************************************/
+
+/* Display callback function. */
+
+static void displayfunc()
+{
+
+ float w;
+ float h;
+ int regbotleftx;
+ int regbotlefty;
+ int regtoprightx;
+ int regtoprighty;
+ int regtoprightwidth;
+ int regtoprightheight;
+ int regwidth;
+ int regheight;
+ float x;
+ float y;
+ float xx;
+ float yy;
+
+ if (cmdopts.verbose) {
+ fprintf(stderr, "displayfunc()\n");
+ }
+
+ regbotleftx = max(ceil(gs.botleftx), 0);
+ regbotlefty = max(ceil(gs.botlefty), 0);
+ regtoprightx = min(gs.vp.width, floor(gs.toprightx));
+ regtoprighty = min(gs.vp.height, floor(gs.toprighty));
+ regwidth = regtoprightx - regbotleftx;
+ regheight = regtoprighty - regbotlefty;
+ w = gs.toprightx - gs.botleftx;
+ h = gs.toprighty - gs.botlefty;
+ x = (regbotleftx - gs.botleftx) / w;
+ y = (regbotlefty - gs.botlefty) / h;
+ xx = (regtoprightx - gs.botleftx) / w;
+ yy = (regtoprighty - gs.botlefty) / h;
+
+ assert(regwidth > 0);
+ assert(regheight > 0);
+ assert(abs(((double) regheight / regwidth) - ((double) gs.viewportheight / gs.viewportwidth)) < 1e-5);
+
+ glClear(GL_COLOR_BUFFER_BIT);
+ glPixelStorei(GL_UNPACK_ALIGNMENT, sizeof(GLshort));
+ glPixelStorei(GL_UNPACK_ROW_LENGTH, gs.vp.width);
+ glPixelStorei(GL_UNPACK_SKIP_PIXELS, regbotleftx);
+ glPixelStorei(GL_UNPACK_SKIP_ROWS, regbotlefty);
+ glRasterPos2f(x * gs.viewportwidth, y * gs.viewportheight);
+ glPixelZoom((xx - x) * ((double) gs.viewportwidth) / regwidth, (yy - y) * ((double) gs.viewportheight) / regheight);
+ glDrawPixels(regwidth, regheight, GL_RGBA, GL_UNSIGNED_SHORT,
+ gs.vp.data);
+ glFlush();
+ glutSwapBuffers();
+
+}
+
+/* Reshape callback function. */
+
+static void reshapefunc(int w, int h)
+{
+ if (cmdopts.verbose) {
+ fprintf(stderr, "reshapefunc(%d, %d)\n", w, h);
+ dumpstate();
+ }
+
+ glViewport(0, 0, w, h);
+ glMatrixMode(GL_PROJECTION);
+ glLoadIdentity();
+ gluOrtho2D(0, w, 0, h);
+ glMatrixMode(GL_MODELVIEW);
+ glLoadIdentity();
+ glTranslatef(0, 0, 0);
+ glRasterPos2i(0, 0);
+
+ zoom((double) gs.viewportwidth / w, (double) gs.viewportheight / h);
+ gs.viewportwidth = w;
+ gs.viewportheight = h;
+
+}
+
+/* Keyboard callback function. */
+
+static void keyboardfunc(unsigned char key, int x, int y)
+{
+ if (cmdopts.verbose) {
+ fprintf(stderr, "keyboardfunc(%d, %d, %d)\n", key, x, y);
+ }
+
+ switch (key) {
+ case ' ':
+ nextimage();
+ break;
+ case '\b':
+ previmage();
+ break;
+ case '>':
+ zoom(BIGZOOMAMOUNT, BIGZOOMAMOUNT);
+ glutPostRedisplay();
+ break;
+ case '.':
+ zoom(SMALLZOOMAMOUNT, SMALLZOOMAMOUNT);
+ glutPostRedisplay();
+ break;
+ case '<':
+ zoom(1.0 / BIGZOOMAMOUNT, 1.0 / BIGZOOMAMOUNT);
+ glutPostRedisplay();
+ break;
+ case ',':
+ zoom(1.0 / SMALLZOOMAMOUNT, 1.0 / SMALLZOOMAMOUNT);
+ glutPostRedisplay();
+ break;
+ case 'c':
+ nextcmpt();
+ break;
+ case 'C':
+ prevcmpt();
+ break;
+ case 'h':
+ fprintf(stderr, "h help\n");
+ fprintf(stderr, "> zoom in (large)\n");
+ fprintf(stderr, ", zoom in (small)\n");
+ fprintf(stderr, "< zoom out (large)\n");
+ fprintf(stderr, ". zoom out (small)\n");
+ fprintf(stderr, "down arrow pan down\n");
+ fprintf(stderr, "up arrow pan up\n");
+ fprintf(stderr, "left arrow pan left\n");
+ fprintf(stderr, "right arrow pan right\n");
+ fprintf(stderr, "space next image\n");
+ fprintf(stderr, "backspace previous image\n");
+ fprintf(stderr, "q quit\n");
+ break;
+ case 'q':
+ cleanupandexit(EXIT_SUCCESS);
+ break;
+ }
+}
+
+/* Special keyboard callback function. */
+
+static void specialfunc(int key, int x, int y)
+{
+ if (cmdopts.verbose) {
+ fprintf(stderr, "specialfunc(%d, %d, %d)\n", key, x, y);
+ }
+
+ switch (key) {
+ case GLUT_KEY_UP:
+ {
+ float panamount;
+ panamount = (glutGetModifiers() & GLUT_ACTIVE_SHIFT) ?
+ BIGPANAMOUNT : SMALLPANAMOUNT;
+ pan(0.0, panamount * (gs.toprighty - gs.botlefty));
+ glutPostRedisplay();
+ }
+ break;
+ case GLUT_KEY_DOWN:
+ {
+ float panamount;
+ panamount = (glutGetModifiers() & GLUT_ACTIVE_SHIFT) ?
+ BIGPANAMOUNT : SMALLPANAMOUNT;
+ pan(0.0, -panamount * (gs.toprighty - gs.botlefty));
+ glutPostRedisplay();
+ }
+ break;
+ case GLUT_KEY_LEFT:
+ {
+ float panamount;
+ panamount = (glutGetModifiers() & GLUT_ACTIVE_SHIFT) ?
+ BIGPANAMOUNT : SMALLPANAMOUNT;
+ pan(-panamount * (gs.toprightx - gs.botleftx), 0.0);
+ glutPostRedisplay();
+ }
+ break;
+ case GLUT_KEY_RIGHT:
+ {
+ float panamount;
+ panamount = (glutGetModifiers() & GLUT_ACTIVE_SHIFT) ?
+ BIGPANAMOUNT : SMALLPANAMOUNT;
+ pan(panamount * (gs.toprightx - gs.botleftx), 0.0);
+ glutPostRedisplay();
+ }
+ break;
+ default:
+ break;
+ }
+}
+
+/* Timer callback function. */
+
+static void timerfunc(int value)
+{
+ if (cmdopts.verbose) {
+ fprintf(stderr, "timerfunc(%d)\n", value);
+ }
+ if (value == gs.activetmid) {
+ nextimage();
+ }
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void zoom(float sx, float sy)
+{
+ panzoom(0, 0, sx, sy);
+}
+
+static void pan(float dx, float dy)
+{
+ panzoom(dx, dy, 1.0, 1.0);
+}
+
+static void panzoom(float dx, float dy, float sx, float sy)
+{
+ float w;
+ float h;
+ float cx;
+ float cy;
+ int reginh;
+ int reginv;
+
+ reginh = (gs.botleftx >= 0 && gs.toprightx <= gs.vp.width);
+ reginv = (gs.botlefty >= 0 && gs.toprighty <= gs.vp.height);
+
+ if (cmdopts.verbose) {
+ fprintf(stderr, "start of panzoom\n");
+ dumpstate();
+ fprintf(stderr, "reginh=%d reginv=%d\n", reginh, reginv);
+ }
+
+ if (dx || dy) {
+ gs.botleftx += dx;
+ gs.botlefty += dy;
+ gs.toprightx += dx;
+ gs.toprighty += dy;
+ }
+
+ if (sx != 1.0 || sy != 1.0) {
+ cx = (gs.botleftx + gs.toprightx) / 2.0;
+ cy = (gs.botlefty + gs.toprighty) / 2.0;
+ w = gs.toprightx - gs.botleftx;
+ h = gs.toprighty - gs.botlefty;
+ gs.botleftx = cx - 0.5 * w / sx;
+ gs.botlefty = cy - 0.5 * h / sy;
+ gs.toprightx = cx + 0.5 * w / sx;
+ gs.toprighty = cy + 0.5 * h / sy;
+ }
+
+ if (reginh) {
+ if (gs.botleftx < 0) {
+ dx = -gs.botleftx;
+ gs.botleftx += dx;
+ gs.toprightx += dx;
+ } else if (gs.toprightx > gs.vp.width) {
+ dx = gs.vp.width - gs.toprightx;
+ gs.botleftx += dx;
+ gs.toprightx += dx;
+ }
+ }
+ if (gs.botleftx < 0 || gs.toprightx > gs.vp.width) {
+ float w;
+ w = gs.toprightx - gs.botleftx;
+ gs.botleftx = 0.5 * gs.vp.width - 0.5 * w;
+ gs.toprightx = 0.5 * gs.vp.width + 0.5 * w;
+ }
+
+ if (reginv) {
+ if (gs.botlefty < 0) {
+ dy = -gs.botlefty;
+ gs.botlefty += dy;
+ gs.toprighty += dy;
+ } else if (gs.toprighty > gs.vp.height) {
+ dy = gs.vp.height - gs.toprighty;
+ gs.botlefty += dy;
+ gs.toprighty += dy;
+ }
+ }
+ if (gs.botlefty < 0 || gs.toprighty > gs.vp.height) {
+ float h;
+ h = gs.toprighty - gs.botlefty;
+ gs.botlefty = 0.5 * gs.vp.height - 0.5 * h;
+ gs.toprighty = 0.5 * gs.vp.height + 0.5 * h;
+ }
+
+ if (cmdopts.verbose) {
+ fprintf(stderr, "end of panzoom\n");
+ dumpstate();
+ }
+}
+
+static void nextcmpt()
+{
+ if (gs.monomode) {
+ if (gs.cmptno == jas_image_numcmpts(gs.image) - 1) {
+ if (gs.altimage) {
+ gs.monomode = 0;
+ } else {
+ gs.cmptno = 0;
+ }
+ } else {
+ ++gs.cmptno;
+ }
+ } else {
+ gs.monomode = 1;
+ gs.cmptno = 0;
+ }
+ render();
+ glutPostRedisplay();
+}
+
+static void prevcmpt()
+{
+ if (gs.monomode) {
+ if (!gs.cmptno) {
+ gs.monomode = 0;
+ } else {
+ --gs.cmptno;
+ }
+ } else {
+ gs.monomode = 1;
+ gs.cmptno = jas_image_numcmpts(gs.image) - 1;
+ }
+ render();
+ glutPostRedisplay();
+}
+
+static void nextimage()
+{
+ int n;
+ unloadimage();
+ for (n = cmdopts.numfiles; n > 0; --n) {
+ ++gs.filenum;
+ if (gs.filenum >= cmdopts.numfiles) {
+ if (cmdopts.loop) {
+ gs.filenum = 0;
+ } else {
+ cleanupandexit(EXIT_SUCCESS);
+ }
+ }
+ if (!loadimage()) {
+ return;
+ }
+ fprintf(stderr, "cannot load image\n");
+ }
+ cleanupandexit(EXIT_SUCCESS);
+}
+
+static void previmage()
+{
+ int n;
+ unloadimage();
+ for (n = cmdopts.numfiles; n > 0; --n) {
+ --gs.filenum;
+ if (gs.filenum < 0) {
+ if (cmdopts.loop) {
+ gs.filenum = cmdopts.numfiles - 1;
+ } else {
+ cleanupandexit(EXIT_SUCCESS);
+ }
+ }
+ if (!loadimage()) {
+ return;
+ }
+ }
+ cleanupandexit(EXIT_SUCCESS);
+}
+
+static int loadimage()
+{
+ int reshapeflag;
+ jas_stream_t *in;
+ int scrnwidth;
+ int scrnheight;
+ int vh;
+ int vw;
+ char *pathname;
+ jas_cmprof_t *outprof;
+
+ assert(!gs.image);
+ assert(!gs.altimage);
+
+ gs.image = 0;
+ gs.altimage = 0;
+
+ pathname = cmdopts.filenames[gs.filenum];
+
+ if (pathname && pathname[0] != '\0') {
+ if (cmdopts.verbose) {
+ fprintf(stderr, "opening file %s\n", pathname);
+ }
+ /* The input image is to be read from a file. */
+ if (!(in = jas_stream_fopen(pathname, "rb"))) {
+ fprintf(stderr, "error: cannot open file %s\n", pathname);
+ goto error;
+ }
+ } else {
+ /* The input image is to be read from standard input. */
+ in = streamin;
+ }
+
+ if (cmdopts.verbose) {
+ fprintf(stderr, "decoding image\n");
+ }
+
+ /* Get the input image data. */
+ if (!(gs.image = jas_image_decode(in, -1, 0))) {
+ fprintf(stderr, "error: cannot load image data\n");
+ goto error;
+ }
+
+ /* Close the input stream. */
+ if (in != streamin) {
+ jas_stream_close(in);
+ }
+
+ if (cmdopts.verbose) {
+ fprintf(stderr, "creating color profile\n");
+ }
+
+ if (!(outprof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB)))
+ goto error;
+ if (!(gs.altimage = jas_image_chclrspc(gs.image, outprof, JAS_CMXFORM_INTENT_PER)))
+ goto error;
+
+ vw = jas_image_width(gs.image);
+ vh = jas_image_height(gs.image);
+
+ gs.botleftx = jas_image_tlx(gs.image);
+ gs.botlefty = jas_image_tly(gs.image);
+ gs.toprightx = jas_image_brx(gs.image);
+ gs.toprighty = jas_image_bry(gs.image);
+ if (gs.altimage) {
+ gs.monomode = 0;
+ } else {
+ gs.monomode = 1;
+ gs.cmptno = 0;
+ }
+
+
+ if (cmdopts.verbose) {
+ fprintf(stderr, "num of components %d\n", jas_image_numcmpts(gs.image));
+ fprintf(stderr, "dimensions %d %d\n", jas_image_width(gs.image), jas_image_height(gs.image));
+ }
+
+ gs.viewportwidth = vw;
+ gs.viewportheight = vh;
+ pixmap_resize(&gs.vp, vw, vh);
+ if (cmdopts.verbose) {
+ fprintf(stderr, "preparing image for viewing\n");
+ }
+ render();
+ if (cmdopts.verbose) {
+ fprintf(stderr, "done preparing image for viewing\n");
+ }
+
+ if (vw != glutGet(GLUT_WINDOW_WIDTH) ||
+ vh != glutGet(GLUT_WINDOW_HEIGHT)) {
+ glutReshapeWindow(vw, vh);
+ }
+ if (cmdopts.title) {
+ glutSetWindowTitle(cmdopts.title);
+ } else {
+ glutSetWindowTitle((pathname && pathname[0] != '\0') ? pathname :
+ "stdin");
+ }
+ /* If we reshaped the window, GLUT will automatically invoke both
+ the reshape and display callback (in this order). Therefore, we
+ only need to explicitly force the display callback to be invoked
+ if the window was not reshaped. */
+ glutPostRedisplay();
+
+ if (cmdopts.tmout != 0) {
+ glutTimerFunc(cmdopts.tmout, timerfunc, gs.nexttmid);
+ gs.activetmid = gs.nexttmid;
+ ++gs.nexttmid;
+ }
+
+ return 0;
+
+error:
+ unloadimage();
+ return -1;
+}
+
+static void unloadimage()
+{
+ if (gs.image) {
+ jas_image_destroy(gs.image);
+ gs.image = 0;
+ }
+ if (gs.altimage) {
+ jas_image_destroy(gs.altimage);
+ gs.altimage = 0;
+ }
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void pixmap_clear(pixmap_t *p)
+{
+ memset(p->data, 0, 4 * p->width * p->height * sizeof(GLshort));
+}
+
+static int pixmap_resize(pixmap_t *p, int w, int h)
+{
+ p->width = w;
+ p->height = h;
+ if (!(p->data = realloc(p->data, w * h * 4 * sizeof(GLshort)))) {
+ return -1;
+ }
+ return 0;
+}
+
+static void dumpstate()
+{
+ printf("blx=%f bly=%f trx=%f try=%f\n", gs.botleftx, gs.botlefty, gs.toprightx, gs.toprighty);
+}
+
+#define vctocc(i, co, cs, vo, vs) \
+ (((vo) + (i) * (vs) - (co)) / (cs))
+
+static int jas_image_render(jas_image_t *image, float vtlx, float vtly,
+ float vsx, float vsy, int vw, int vh, GLshort *vdata)
+{
+ int i;
+ int j;
+ int k;
+ int x;
+ int y;
+ int v[3];
+ GLshort *vdatap;
+ int cmptlut[3];
+ int width;
+ int height;
+ int hs;
+ int vs;
+ int tlx;
+ int tly;
+
+ if ((cmptlut[0] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R))) < 0 ||
+ (cmptlut[1] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G))) < 0 ||
+ (cmptlut[2] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))) < 0)
+ goto error;
+ width = jas_image_cmptwidth(image, cmptlut[0]);
+ height = jas_image_cmptheight(image, cmptlut[0]);
+ tlx = jas_image_cmpttlx(image, cmptlut[0]);
+ tly = jas_image_cmpttly(image, cmptlut[0]);
+ vs = jas_image_cmptvstep(image, cmptlut[0]);
+ hs = jas_image_cmpthstep(image, cmptlut[0]);
+ for (i = 1; i < 3; ++i) {
+ if (jas_image_cmptwidth(image, cmptlut[i]) != width ||
+ jas_image_cmptheight(image, cmptlut[i]) != height)
+ goto error;
+ }
+ for (i = 0; i < vh; ++i) {
+ vdatap = &vdata[(vh - 1 - i) * (4 * vw)];
+ for (j = 0; j < vw; ++j) {
+ x = vctocc(j, tlx, hs, vtlx, vsx);
+ y = vctocc(i, tly, vs, vtly, vsy);
+ if (x >= 0 && x < width && y >= 0 && y < height) {
+ for (k = 0; k < 3; ++k) {
+ v[k] = jas_image_readcmptsample(image, cmptlut[k], x, y);
+ v[k] <<= 16 - jas_image_cmptprec(image, cmptlut[k]);
+ if (v[k] < 0) {
+ v[k] = 0;
+ } else if (v[k] > 65535) {
+ v[k] = 65535;
+ }
+ }
+ } else {
+ v[0] = 0;
+ v[1] = 0;
+ v[2] = 0;
+ }
+ *vdatap++ = v[0];
+ *vdatap++ = v[1];
+ *vdatap++ = v[2];
+ *vdatap++ = 0;
+ }
+ }
+ return 0;
+error:
+ return -1;
+}
+
+static int jas_image_render2(jas_image_t *image, int cmptno, float vtlx,
+ float vtly, float vsx, float vsy, int vw, int vh, GLshort *vdata)
+{
+ int i;
+ int j;
+ int x;
+ int y;
+ int v;
+ GLshort *vdatap;
+
+ if (cmptno < 0 || cmptno >= image->numcmpts_) {
+ fprintf(stderr, "bad parameter\n");
+ goto error;
+ }
+ for (i = 0; i < vh; ++i) {
+ vdatap = &vdata[(vh - 1 - i) * (4 * vw)];
+ for (j = 0; j < vw; ++j) {
+ x = vctocc(j, jas_image_cmpttlx(image, cmptno), jas_image_cmpthstep(image, cmptno), vtlx, vsx);
+ y = vctocc(i, jas_image_cmpttly(image, cmptno), jas_image_cmptvstep(image, cmptno), vtly, vsy);
+ v = (x >= 0 && x < jas_image_cmptwidth(image, cmptno) && y >=0 && y < jas_image_cmptheight(image, cmptno)) ? jas_image_readcmptsample(image, cmptno, x, y) : 0;
+ v <<= 16 - jas_image_cmptprec(image, cmptno);
+ if (v < 0) {
+ v = 0;
+ } else if (v > 65535) {
+ v = 65535;
+ }
+ *vdatap++ = v;
+ *vdatap++ = v;
+ *vdatap++ = v;
+ *vdatap++ = 0;
+ }
+ }
+ return 0;
+error:
+ return -1;
+}
+
+
+static void render()
+{
+ float vtlx;
+ float vtly;
+
+ vtlx = gs.botleftx;
+ vtly = gs.toprighty;
+ if (cmdopts.verbose) {
+// fprintf(stderr, "vtlx=%f, vtly=%f, vsx=%f, vsy=%f\n",
+// vtlx, vtly, gs.sx, gs.sy);
+ }
+
+ if (gs.monomode) {
+ if (cmdopts.verbose) {
+ fprintf(stderr, "component %d\n", gs.cmptno);
+ }
+ jas_image_render2(gs.image, gs.cmptno, 0.0, 0.0,
+ 1.0, 1.0, gs.vp.width, gs.vp.height, gs.vp.data);
+ } else {
+ if (cmdopts.verbose) {
+ fprintf(stderr, "color\n");
+ }
+ jas_image_render(gs.altimage, 0.0, 0.0, 1.0, 1.0,
+ gs.vp.width, gs.vp.height, gs.vp.data);
+ }
+
+}
+
+#if 0
+
+#define vctocc(i, co, cs, vo, vs) \
+ (((vo) + (i) * (vs) - (co)) / (cs))
+
+static void drawview(jas_image_t *image, float vtlx, float vtly,
+ float sx, float sy, pixmap_t *p)
+{
+ int i;
+ int j;
+ int k;
+ int red;
+ int grn;
+ int blu;
+ int lum;
+ GLshort *datap;
+ int x;
+ int y;
+ int *cmptlut;
+ int numcmpts;
+ int v[4];
+ int u[4];
+ int color;
+
+ cmptlut = gs.cmptlut;
+ switch (jas_image_colorspace(gs.image)) {
+ case JAS_IMAGE_CS_RGB:
+ case JAS_IMAGE_CS_YCBCR:
+ color = 1;
+ numcmpts = 3;
+ break;
+ case JAS_IMAGE_CS_GRAY:
+ default:
+ numcmpts = 1;
+ color = 0;
+ break;
+ }
+
+ for (i = 0; i < p->height; ++i) {
+ datap = &p->data[(p->height - 1 - i) * (4 * p->width)];
+ for (j = 0; j < p->width; ++j) {
+ if (!gs.monomode && color) {
+ for (k = 0; k < numcmpts; ++k) {
+ x = vctocc(j, jas_image_cmpttlx(gs.image, cmptlut[k]), jas_image_cmpthstep(gs.image, cmptlut[k]), vtlx, sx);
+ y = vctocc(i, jas_image_cmpttly(gs.image, cmptlut[k]), jas_image_cmptvstep(gs.image, cmptlut[k]), vtly, sy);
+ v[k] = (x >= 0 && x < jas_image_cmptwidth(gs.image, cmptlut[k]) && y >=0 && y < jas_image_cmptheight(gs.image, cmptlut[k])) ? jas_matrix_get(gs.cmpts[cmptlut[k]], y, x) : 0;
+ v[k] <<= 16 - jas_image_cmptprec(gs.image, cmptlut[k]);
+ }
+ switch (jas_image_colorspace(gs.image)) {
+ case JAS_IMAGE_CS_RGB:
+ break;
+ case JAS_IMAGE_CS_YCBCR:
+ u[0] = (1/1.772) * (v[0] + 1.402 * v[2]);
+ u[1] = (1/1.772) * (v[0] - 0.34413 * v[1] - 0.71414 * v[2]);
+ u[2] = (1/1.772) * (v[0] + 1.772 * v[1]);
+ v[0] = u[0];
+ v[1] = u[1];
+ v[2] = u[2];
+ break;
+ }
+ } else {
+ x = vctocc(j, jas_image_cmpttlx(gs.image, gs.cmptno), jas_image_cmpthstep(gs.image, gs.cmptno), vtlx, sx);
+ y = vctocc(i, jas_image_cmpttly(gs.image, gs.cmptno), jas_image_cmptvstep(gs.image, gs.cmptno), vtly, sy);
+ v[0] = (x >= 0 && x < jas_image_cmptwidth(gs.image, gs.cmptno) && y >=0 && y < jas_image_cmptheight(gs.image, gs.cmptno)) ? jas_matrix_get(gs.cmpts[gs.cmptno], y, x) : 0;
+ v[0] <<= 16 - jas_image_cmptprec(gs.image, gs.cmptno);
+ v[1] = v[0];
+ v[2] = v[0];
+ v[3] = 0;
+ }
+
+for (k = 0; k < 3; ++k) {
+ if (v[k] < 0) {
+ v[k] = 0;
+ } else if (v[k] > 65535) {
+ v[k] = 65535;
+ }
+}
+
+ *datap++ = v[0];
+ *datap++ = v[1];
+ *datap++ = v[2];
+ *datap++ = 0;
+ }
+ }
+}
+
+#endif
+
+static void cleanupandexit(int status)
+{
+ unloadimage();
+ exit(status);
+}
+
+static void init()
+{
+ gs.filenum = -1;
+ gs.image = 0;
+ gs.altimage = 0;
+ gs.nexttmid = 0;
+ gs.vp.width = 0;
+ gs.vp.height = 0;
+ gs.vp.data = 0;
+ gs.viewportwidth = -1;
+ gs.viewportheight = -1;
+}
diff --git a/jasper-1.900.1-6ct/src/appl/tmrdemo.c b/jasper-1.900.1-6ct/src/appl/tmrdemo.c
new file mode 100644
index 0000000..ec9d984
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/appl/tmrdemo.c
@@ -0,0 +1,52 @@
+#include <jasper/jasper.h>
+
+int main(int argc, char **argv)
+{
+ int i;
+ jas_tmr_t tmr;
+ jas_tmr_t dummytmr;
+ double t;
+ int numiters;
+
+ if (argc < 2) {
+ fprintf(stderr, "bad usage :P\n");
+ exit(1);
+ }
+
+ numiters = atoi(argv[1]);
+
+ jas_tmr_start(&tmr);
+ for (i = numiters; i > 0; --i) {
+ jas_tmr_start(&dummytmr);
+ }
+ jas_tmr_stop(&tmr);
+ t = jas_tmr_get(&tmr);
+ t /= numiters;
+ printf("jas_tmr_start %.3f us\n", t * 1e6);
+
+ jas_tmr_start(&tmr);
+ for (i = numiters; i > 0; --i) {
+ jas_tmr_stop(&dummytmr);
+ }
+ jas_tmr_stop(&tmr);
+ t = jas_tmr_get(&tmr);
+ t /= numiters;
+ printf("jas_tmr_stop %.3f us\n", t * 1e6);
+
+ t = 0;
+ for (i = numiters; i > 0; --i) {
+ jas_tmr_start(&tmr);
+ jas_tmr_stop(&tmr);
+ t += jas_tmr_get(&tmr);
+ }
+ t /= numiters;
+ printf("zero time %.3f us\n", t * 1e6);
+
+ jas_tmr_start(&tmr);
+ sleep(1);
+ jas_tmr_stop(&tmr);
+ t = jas_tmr_get(&tmr);
+ printf("time delay %.8f s\n", t);
+
+ exit(0);
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/Makefile.am b/jasper-1.900.1-6ct/src/libjasper/Makefile.am
new file mode 100644
index 0000000..5023a3b
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/Makefile.am
@@ -0,0 +1,89 @@
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+EXTRA_DIST = README
+
+SUBDIRS = \
+ include \
+ base \
+ bmp \
+ jp2 \
+ jpc \
+ jpg \
+ mif \
+ pgx \
+ pnm \
+ ras
+
+lib_LTLIBRARIES = libjasper.la
+libjasper_la_SOURCES = dummy.c
+libjasper_la_LIBADD = \
+ base/libbase.la \
+ bmp/libbmp.la \
+ jp2/libjp2.la \
+ jpc/libjpc.la \
+ jpg/libjpg.la \
+ mif/libmif.la \
+ pgx/libpgx.la \
+ pnm/libpnm.la \
+ ras/libras.la
+
+# -release $(LT_RELEASE)
+libjasper_la_LDFLAGS = \
+ -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE)
+
diff --git a/jasper-1.900.1-6ct/src/libjasper/Makefile.in b/jasper-1.900.1-6ct/src/libjasper/Makefile.in
new file mode 100644
index 0000000..89f66ab
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/Makefile.in
@@ -0,0 +1,673 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src/libjasper
+DIST_COMMON = README $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj = case $$p in \
+ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+ *) f=$$p;; \
+ esac;
+am__strip_dir = `echo $$p | sed -e 's|^.*/||'`;
+am__installdirs = "$(DESTDIR)$(libdir)"
+libLTLIBRARIES_INSTALL = $(INSTALL)
+LTLIBRARIES = $(lib_LTLIBRARIES)
+libjasper_la_DEPENDENCIES = base/libbase.la bmp/libbmp.la \
+ jp2/libjp2.la jpc/libjpc.la jpg/libjpg.la mif/libmif.la \
+ pgx/libpgx.la pnm/libpnm.la ras/libras.la
+am_libjasper_la_OBJECTS = dummy.lo
+libjasper_la_OBJECTS = $(am_libjasper_la_OBJECTS)
+DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/src/libjasper/include/jasper
+depcomp = $(SHELL) $(top_srcdir)/acaux/depcomp
+am__depfiles_maybe = depfiles
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LTCOMPILE = $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) \
+ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+ $(AM_CFLAGS) $(CFLAGS)
+CCLD = $(CC)
+LINK = $(LIBTOOL) --tag=CC --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+ $(AM_LDFLAGS) $(LDFLAGS) -o $@
+SOURCES = $(libjasper_la_SOURCES)
+DIST_SOURCES = $(libjasper_la_SOURCES)
+RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
+ html-recursive info-recursive install-data-recursive \
+ install-exec-recursive install-info-recursive \
+ install-recursive installcheck-recursive installdirs-recursive \
+ pdf-recursive ps-recursive uninstall-info-recursive \
+ uninstall-recursive
+ETAGS = etags
+CTAGS = ctags
+DIST_SUBDIRS = $(SUBDIRS)
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+EXTRA_DIST = README
+SUBDIRS = \
+ include \
+ base \
+ bmp \
+ jp2 \
+ jpc \
+ jpg \
+ mif \
+ pgx \
+ pnm \
+ ras
+
+lib_LTLIBRARIES = libjasper.la
+libjasper_la_SOURCES = dummy.c
+libjasper_la_LIBADD = \
+ base/libbase.la \
+ bmp/libbmp.la \
+ jp2/libjp2.la \
+ jpc/libjpc.la \
+ jpg/libjpg.la \
+ mif/libmif.la \
+ pgx/libpgx.la \
+ pnm/libpnm.la \
+ ras/libras.la
+
+
+# -release $(LT_RELEASE)
+libjasper_la_LDFLAGS = \
+ -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE)
+
+all: all-recursive
+
+.SUFFIXES:
+.SUFFIXES: .c .lo .o .obj
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libjasper/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/libjasper/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+install-libLTLIBRARIES: $(lib_LTLIBRARIES)
+ @$(NORMAL_INSTALL)
+ test -z "$(libdir)" || $(mkdir_p) "$(DESTDIR)$(libdir)"
+ @list='$(lib_LTLIBRARIES)'; for p in $$list; do \
+ if test -f $$p; then \
+ f=$(am__strip_dir) \
+ echo " $(LIBTOOL) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \
+ $(LIBTOOL) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \
+ else :; fi; \
+ done
+
+uninstall-libLTLIBRARIES:
+ @$(NORMAL_UNINSTALL)
+ @set -x; list='$(lib_LTLIBRARIES)'; for p in $$list; do \
+ p=$(am__strip_dir) \
+ echo " $(LIBTOOL) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \
+ $(LIBTOOL) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \
+ done
+
+clean-libLTLIBRARIES:
+ -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES)
+ @list='$(lib_LTLIBRARIES)'; for p in $$list; do \
+ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
+ test "$$dir" != "$$p" || dir=.; \
+ echo "rm -f \"$${dir}/so_locations\""; \
+ rm -f "$${dir}/so_locations"; \
+ done
+libjasper.la: $(libjasper_la_OBJECTS) $(libjasper_la_DEPENDENCIES)
+ $(LINK) -rpath $(libdir) $(libjasper_la_LDFLAGS) $(libjasper_la_OBJECTS) $(libjasper_la_LIBADD) $(LIBS)
+
+mostlyclean-compile:
+ -rm -f *.$(OBJEXT)
+
+distclean-compile:
+ -rm -f *.tab.c
+
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/dummy.Plo at am__quote@
+
+.c.o:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c $<
+
+.c.obj:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
+
+.c.lo:
+ at am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $<
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+
+# This directory's subdirectories are mostly independent; you can cd
+# into them and run `make' without going through this Makefile.
+# To change the values of `make' variables: instead of editing Makefiles,
+# (1) if the variable is set in `config.status', edit `config.status'
+# (which will cause the Makefiles to be regenerated when you run `make');
+# (2) otherwise, pass the desired values on the `make' command line.
+$(RECURSIVE_TARGETS):
+ @failcom='exit 1'; \
+ for f in x $$MAKEFLAGS; do \
+ case $$f in \
+ *=* | --[!k]*);; \
+ *k*) failcom='fail=yes';; \
+ esac; \
+ done; \
+ dot_seen=no; \
+ target=`echo $@ | sed s/-recursive//`; \
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ echo "Making $$target in $$subdir"; \
+ if test "$$subdir" = "."; then \
+ dot_seen=yes; \
+ local_target="$$target-am"; \
+ else \
+ local_target="$$target"; \
+ fi; \
+ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+ || eval $$failcom; \
+ done; \
+ if test "$$dot_seen" = "no"; then \
+ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
+ fi; test -z "$$fail"
+
+mostlyclean-recursive clean-recursive distclean-recursive \
+maintainer-clean-recursive:
+ @failcom='exit 1'; \
+ for f in x $$MAKEFLAGS; do \
+ case $$f in \
+ *=* | --[!k]*);; \
+ *k*) failcom='fail=yes';; \
+ esac; \
+ done; \
+ dot_seen=no; \
+ case "$@" in \
+ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
+ *) list='$(SUBDIRS)' ;; \
+ esac; \
+ rev=''; for subdir in $$list; do \
+ if test "$$subdir" = "."; then :; else \
+ rev="$$subdir $$rev"; \
+ fi; \
+ done; \
+ rev="$$rev ."; \
+ target=`echo $@ | sed s/-recursive//`; \
+ for subdir in $$rev; do \
+ echo "Making $$target in $$subdir"; \
+ if test "$$subdir" = "."; then \
+ local_target="$$target-am"; \
+ else \
+ local_target="$$target"; \
+ fi; \
+ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+ || eval $$failcom; \
+ done && test -z "$$fail"
+tags-recursive:
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
+ done
+ctags-recursive:
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
+ done
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
+ include_option=--etags-include; \
+ empty_fix=.; \
+ else \
+ include_option=--include; \
+ empty_fix=; \
+ fi; \
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ if test "$$subdir" = .; then :; else \
+ test ! -f $$subdir/TAGS || \
+ tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \
+ fi; \
+ done; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+ list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
+ if test "$$subdir" = .; then :; else \
+ test -d "$(distdir)/$$subdir" \
+ || $(mkdir_p) "$(distdir)/$$subdir" \
+ || exit 1; \
+ distdir=`$(am__cd) $(distdir) && pwd`; \
+ top_distdir=`$(am__cd) $(top_distdir) && pwd`; \
+ (cd $$subdir && \
+ $(MAKE) $(AM_MAKEFLAGS) \
+ top_distdir="$$top_distdir" \
+ distdir="$$distdir/$$subdir" \
+ distdir) \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-recursive
+all-am: Makefile $(LTLIBRARIES)
+installdirs: installdirs-recursive
+installdirs-am:
+ for dir in "$(DESTDIR)$(libdir)"; do \
+ test -z "$$dir" || $(mkdir_p) "$$dir"; \
+ done
+install: install-recursive
+install-exec: install-exec-recursive
+install-data: install-data-recursive
+uninstall: uninstall-recursive
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-recursive
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-recursive
+
+clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \
+ mostlyclean-am
+
+distclean: distclean-recursive
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+distclean-am: clean-am distclean-compile distclean-generic \
+ distclean-libtool distclean-tags
+
+dvi: dvi-recursive
+
+dvi-am:
+
+html: html-recursive
+
+info: info-recursive
+
+info-am:
+
+install-data-am:
+
+install-exec-am: install-libLTLIBRARIES
+
+install-info: install-info-recursive
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-recursive
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-recursive
+
+mostlyclean-am: mostlyclean-compile mostlyclean-generic \
+ mostlyclean-libtool
+
+pdf: pdf-recursive
+
+pdf-am:
+
+ps: ps-recursive
+
+ps-am:
+
+uninstall-am: uninstall-info-am uninstall-libLTLIBRARIES
+
+uninstall-info: uninstall-info-recursive
+
+.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am check check-am \
+ clean clean-generic clean-libLTLIBRARIES clean-libtool \
+ clean-recursive ctags ctags-recursive distclean \
+ distclean-compile distclean-generic distclean-libtool \
+ distclean-recursive distclean-tags distdir dvi dvi-am html \
+ html-am info info-am install install-am install-data \
+ install-data-am install-exec install-exec-am install-info \
+ install-info-am install-libLTLIBRARIES install-man \
+ install-strip installcheck installcheck-am installdirs \
+ installdirs-am maintainer-clean maintainer-clean-generic \
+ maintainer-clean-recursive mostlyclean mostlyclean-compile \
+ mostlyclean-generic mostlyclean-libtool mostlyclean-recursive \
+ pdf pdf-am ps ps-am tags tags-recursive uninstall uninstall-am \
+ uninstall-info-am uninstall-libLTLIBRARIES
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/libjasper/Obsolete/20100119/amake.bat b/jasper-1.900.1-6ct/src/libjasper/Obsolete/20100119/amake.bat
new file mode 100644
index 0000000..a6f5c31
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/Obsolete/20100119/amake.bat
@@ -0,0 +1,6 @@
+set path=c:\lang\ms8amd64\bin
+set include=c:\lang\ms8amd64\include;\quirt\comps\exe\dgate;\quirt\comps\dll\cqdicom
+set lib=c:\lang\ms8amd64\lib
+
+cl -Iinclude -DJAS_WIN_MSVC_BUILD -MD -O2 -c jasperlib.c
+copy jasperlib.obj \quirt\comps\exe\dgate\ms8amd64
diff --git a/jasper-1.900.1-6ct/src/libjasper/Obsolete/20100119/jasperlib.c b/jasper-1.900.1-6ct/src/libjasper/Obsolete/20100119/jasperlib.c
new file mode 100644
index 0000000..5fb1323
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/Obsolete/20100119/jasperlib.c
@@ -0,0 +1,104 @@
+// This is an amalgation of the jasper library by mvh 20100117
+
+#include "include/jasper/jasper.h"
+
+#include "base/jas_cm.c"
+#include "base/jas_debug.c"
+#include "base/jas_getopt.c"
+#include "base/jas_icc.c"
+#include "base/jas_iccdata.c"
+#include "base/jas_image.c"
+#include "base/jas_init.c"
+#include "base/jas_malloc.c"
+#include "base/jas_seq.c"
+#include "base/jas_stream.c"
+#include "base/jas_string.c"
+#include "base/jas_tmr.c"
+#include "base/jas_tvp.c"
+#include "base/jas_version.c"
+
+#include "bmp/bmp_cod.h"
+#include "bmp/bmp_enc.h"
+#include "bmp/bmp_cod.c"
+#include "bmp/bmp_dec.c"
+#include "bmp/bmp_enc.c"
+
+#include "jp2/jp2_cod.h"
+#include "jp2/jp2_dec.h"
+#include "jp2/jp2_cod.c"
+#include "jp2/jp2_dec.c"
+#include "jp2/jp2_enc.c"
+
+#include "jpc/jpc_bs.h"
+#include "jpc/jpc_cod.h"
+#include "jpc/jpc_cs.h"
+#include "jpc/jpc_dec.h"
+#include "jpc/jpc_enc.h"
+#include "jpc/jpc_fix.h"
+#include "jpc/jpc_flt.h"
+#include "jpc/jpc_math.h"
+#include "jpc/jpc_mct.h"
+#include "jpc/jpc_mqcod.h"
+#include "jpc/jpc_mqdec.h"
+#include "jpc/jpc_mqenc.h"
+#include "jpc/jpc_qmfb.h"
+#include "jpc/jpc_t1cod.h"
+#include "jpc/jpc_t1dec.h"
+#include "jpc/jpc_t1enc.h"
+#include "jpc/jpc_t2cod.h"
+#include "jpc/jpc_t2dec.h"
+#include "jpc/jpc_t2enc.h"
+#include "jpc/jpc_tagtree.h"
+#include "jpc/jpc_tsfb.h"
+#include "jpc/jpc_util.h"
+
+#include "jpc/jpc_bs.c"
+#include "jpc/jpc_cs.c"
+#include "jpc/jpc_dec.c" // had to change OPT_DEBUG to OPTx_DEBUG because of name clash
+#include "jpc/jpc_enc.c"
+#include "jpc/jpc_math.c"
+#include "jpc/jpc_mct.c"
+#include "jpc/jpc_mqcod.c"
+#include "jpc/jpc_mqdec.c"
+#include "jpc/jpc_mqenc.c"
+#include "jpc/jpc_qmfb.c"
+#include "jpc/jpc_t1cod.c"
+#include "jpc/jpc_t1dec.c"
+#include "jpc/jpc_t1enc.c"
+#include "jpc/jpc_t2cod.c"
+#include "jpc/jpc_t2dec.c"
+#include "jpc/jpc_t2enc.c"
+#include "jpc/jpc_tagtree.c"
+#include "jpc/jpc_tsfb.c"
+#include "jpc/jpc_util.c"
+
+#include "jpg/jpg_cod.h"
+#include "jpg/jpg_enc.h"
+//#include "jpg/jpg_jpeglib.h"
+
+//#include "jpg/jpg_dec.c"
+//#include "jpg/jpg_enc.c"
+#include "jpg/jpg_dummy.c"
+#include "jpg/jpg_val.c"
+
+#include "mif/mif_cod.h"
+#include "mif/mif_cod.c"
+
+#include "pgx/pgx_cod.h"
+#include "pgx/pgx_enc.h"
+#include "pgx/pgx_cod.c"
+#include "pgx/pgx_dec.c"
+#include "pgx/pgx_enc.c"
+
+#include "pnm/pnm_cod.h"
+#include "pnm/pnm_enc.h"
+#include "pnm/pnm_cod.c"
+#include "pnm/pnm_dec.c"
+#include "pnm/pnm_enc.c"
+
+#include "ras/ras_cod.h"
+#include "ras/ras_enc.h"
+#include "ras/ras_cod.c"
+#include "ras/ras_dec.c"
+#include "ras/ras_enc.c"
+
diff --git a/jasper-1.900.1-6ct/src/libjasper/README b/jasper-1.900.1-6ct/src/libjasper/README
new file mode 100644
index 0000000..4b79616
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/README
@@ -0,0 +1,2 @@
+This directory hierarchy contains the source code for the JasPer library
+(i.e., libjasper).
diff --git a/jasper-1.900.1-6ct/src/libjasper/base/Makefile.am b/jasper-1.900.1-6ct/src/libjasper/base/Makefile.am
new file mode 100644
index 0000000..8bdb67b
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/Makefile.am
@@ -0,0 +1,76 @@
+# Copyright (c) 2001-2003 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+noinst_LTLIBRARIES = libbase.la
+libbase_la_SOURCES = \
+ jas_cm.c \
+ jas_debug.c \
+ jas_getopt.c \
+ jas_image.c \
+ jas_icc.c \
+ jas_iccdata.c \
+ jas_init.c \
+ jas_malloc.c \
+ jas_seq.c \
+ jas_stream.c \
+ jas_string.c \
+ jas_tmr.c \
+ jas_tvp.c \
+ jas_version.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
diff --git a/jasper-1.900.1-6ct/src/libjasper/base/Makefile.in b/jasper-1.900.1-6ct/src/libjasper/base/Makefile.in
new file mode 100644
index 0000000..abb299d
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/Makefile.in
@@ -0,0 +1,533 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2003 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src/libjasper/base
+DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+LTLIBRARIES = $(noinst_LTLIBRARIES)
+libbase_la_LIBADD =
+am_libbase_la_OBJECTS = jas_cm.lo jas_debug.lo jas_getopt.lo \
+ jas_image.lo jas_icc.lo jas_iccdata.lo jas_init.lo \
+ jas_malloc.lo jas_seq.lo jas_stream.lo jas_string.lo \
+ jas_tmr.lo jas_tvp.lo jas_version.lo
+libbase_la_OBJECTS = $(am_libbase_la_OBJECTS)
+DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/src/libjasper/include/jasper
+depcomp = $(SHELL) $(top_srcdir)/acaux/depcomp
+am__depfiles_maybe = depfiles
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LTCOMPILE = $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) \
+ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+ $(AM_CFLAGS) $(CFLAGS)
+CCLD = $(CC)
+LINK = $(LIBTOOL) --tag=CC --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+ $(AM_LDFLAGS) $(LDFLAGS) -o $@
+SOURCES = $(libbase_la_SOURCES)
+DIST_SOURCES = $(libbase_la_SOURCES)
+ETAGS = etags
+CTAGS = ctags
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+noinst_LTLIBRARIES = libbase.la
+libbase_la_SOURCES = \
+ jas_cm.c \
+ jas_debug.c \
+ jas_getopt.c \
+ jas_image.c \
+ jas_icc.c \
+ jas_iccdata.c \
+ jas_init.c \
+ jas_malloc.c \
+ jas_seq.c \
+ jas_stream.c \
+ jas_string.c \
+ jas_tmr.c \
+ jas_tvp.c \
+ jas_version.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
+all: all-am
+
+.SUFFIXES:
+.SUFFIXES: .c .lo .o .obj
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libjasper/base/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/libjasper/base/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+clean-noinstLTLIBRARIES:
+ -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
+ @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \
+ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
+ test "$$dir" != "$$p" || dir=.; \
+ echo "rm -f \"$${dir}/so_locations\""; \
+ rm -f "$${dir}/so_locations"; \
+ done
+libbase.la: $(libbase_la_OBJECTS) $(libbase_la_DEPENDENCIES)
+ $(LINK) $(libbase_la_LDFLAGS) $(libbase_la_OBJECTS) $(libbase_la_LIBADD) $(LIBS)
+
+mostlyclean-compile:
+ -rm -f *.$(OBJEXT)
+
+distclean-compile:
+ -rm -f *.tab.c
+
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_cm.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_debug.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_getopt.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_icc.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_iccdata.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_image.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_init.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_malloc.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_seq.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_stream.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_string.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_tmr.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_tvp.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jas_version.Plo at am__quote@
+
+.c.o:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c $<
+
+.c.obj:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
+
+.c.lo:
+ at am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $<
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-am
+all-am: Makefile $(LTLIBRARIES)
+installdirs:
+install: install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-am
+
+clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \
+ mostlyclean-am
+
+distclean: distclean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+distclean-am: clean-am distclean-compile distclean-generic \
+ distclean-libtool distclean-tags
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+info: info-am
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-am
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-compile mostlyclean-generic \
+ mostlyclean-libtool
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
+ clean-libtool clean-noinstLTLIBRARIES ctags distclean \
+ distclean-compile distclean-generic distclean-libtool \
+ distclean-tags distdir dvi dvi-am html html-am info info-am \
+ install install-am install-data install-data-am install-exec \
+ install-exec-am install-info install-info-am install-man \
+ install-strip installcheck installcheck-am installdirs \
+ maintainer-clean maintainer-clean-generic mostlyclean \
+ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
+ pdf pdf-am ps ps-am tags uninstall uninstall-am \
+ uninstall-info-am
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/libjasper/base/jas_cm.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_cm.c
new file mode 100644
index 0000000..9b41750
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_cm.c
@@ -0,0 +1,1283 @@
+/*
+ * Copyright (c) 2002-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Color Management
+ *
+ * $Id$
+ */
+
+#include <jasper/jas_config.h>
+#include <math.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <jasper/jas_cm.h>
+#include <jasper/jas_icc.h>
+#include <jasper/jas_init.h>
+#include <jasper/jas_stream.h>
+#include <jasper/jas_malloc.h>
+#include <jasper/jas_math.h>
+#include <jasper/jas_debug.h>
+
+static jas_cmprof_t *jas_cmprof_create(void);
+static void jas_cmshapmatlut_cleanup(jas_cmshapmatlut_t *);
+static jas_cmreal_t jas_cmshapmatlut_lookup(jas_cmshapmatlut_t *lut, jas_cmreal_t x);
+
+static void jas_cmpxform_destroy(jas_cmpxform_t *pxform);
+static jas_cmpxform_t *jas_cmpxform_copy(jas_cmpxform_t *pxform);
+
+static void jas_cmshapmat_destroy(jas_cmpxform_t *pxform);
+static int jas_cmshapmat_apply(jas_cmpxform_t *pxform, jas_cmreal_t *in,
+ jas_cmreal_t *out, int cnt);
+
+static int jas_cmputint(long **bufptr, int sgnd, int prec, long val);
+static int jas_cmgetint(long **bufptr, int sgnd, int prec, long *val);
+static int jas_cmpxformseq_append(jas_cmpxformseq_t *pxformseq,
+ jas_cmpxformseq_t *othpxformseq);
+static int jas_cmpxformseq_appendcnvt(jas_cmpxformseq_t *pxformseq,
+ int, int);
+static int jas_cmpxformseq_resize(jas_cmpxformseq_t *pxformseq, int n);
+
+static int mono(jas_iccprof_t *prof, int op, jas_cmpxformseq_t **pxformseq);
+static int triclr(jas_iccprof_t *prof, int op, jas_cmpxformseq_t **retpxformseq);
+
+static void jas_cmpxformseq_destroy(jas_cmpxformseq_t *pxformseq);
+static int jas_cmpxformseq_delete(jas_cmpxformseq_t *pxformseq, int i);
+static jas_cmpxformseq_t *jas_cmpxformseq_create(void);
+static jas_cmpxformseq_t *jas_cmpxformseq_copy(jas_cmpxformseq_t *pxformseq);
+static int jas_cmshapmat_invmat(jas_cmreal_t out[3][4], jas_cmreal_t in[3][4]);
+static int jas_cmpxformseq_insertpxform(jas_cmpxformseq_t *pxformseq,
+ int i, jas_cmpxform_t *pxform);
+
+#define SEQFWD(intent) (intent)
+#define SEQREV(intent) (4 + (intent))
+#define SEQSIM(intent) (8 + (intent))
+#define SEQGAM 12
+
+#define fwdpxformseq(prof, intent) \
+ (((prof)->pxformseqs[SEQFWD(intent)]) ? \
+ ((prof)->pxformseqs[SEQFWD(intent)]) : \
+ ((prof)->pxformseqs[SEQFWD(0)]))
+
+#define revpxformseq(prof, intent) \
+ (((prof)->pxformseqs[SEQREV(intent)]) ? \
+ ((prof)->pxformseqs[SEQREV(intent)]) : \
+ ((prof)->pxformseqs[SEQREV(0)]))
+
+#define simpxformseq(prof, intent) \
+ (((prof)->pxformseqs[SEQSIM(intent)]) ? \
+ ((prof)->pxformseqs[SEQSIM(intent)]) : \
+ ((prof)->pxformseqs[SEQSIM(0)]))
+
+#define gampxformseq(prof) ((prof)->pxformseqs[SEQGAM])
+
+static int icctoclrspc(int iccclrspc, int refflag);
+static jas_cmpxform_t *jas_cmpxform_create0(void);
+static jas_cmpxform_t *jas_cmpxform_createshapmat(void);
+static void jas_cmshapmatlut_init(jas_cmshapmatlut_t *lut);
+static int jas_cmshapmatlut_set(jas_cmshapmatlut_t *lut, jas_icccurv_t *curv);
+
+static jas_cmpxformops_t shapmat_ops = {jas_cmshapmat_destroy, jas_cmshapmat_apply, 0};
+static jas_cmprof_t *jas_cmprof_createsycc(void);
+
+/******************************************************************************\
+* Color profile class.
+\******************************************************************************/
+
+jas_cmprof_t *jas_cmprof_createfromclrspc(int clrspc)
+{
+ jas_iccprof_t *iccprof;
+ jas_cmprof_t *prof;
+
+ iccprof = 0;
+ prof = 0;
+ switch (clrspc) {
+ case JAS_CLRSPC_SYCBCR:
+ if (!(prof = jas_cmprof_createsycc()))
+ goto error;
+ break;
+ default:
+ if (!(iccprof = jas_iccprof_createfromclrspc(clrspc)))
+ goto error;
+ if (!(prof = jas_cmprof_createfromiccprof(iccprof)))
+ goto error;
+ jas_iccprof_destroy(iccprof);
+ iccprof = 0;
+ if (!jas_clrspc_isgeneric(clrspc))
+ prof->clrspc = clrspc;
+ break;
+ }
+ return prof;
+error:
+ if (iccprof)
+ jas_iccprof_destroy(iccprof);
+ return 0;
+}
+
+static jas_cmprof_t *jas_cmprof_createsycc()
+{
+ jas_cmprof_t *prof;
+ jas_cmpxform_t *fwdpxform;
+ jas_cmpxform_t *revpxform;
+ jas_cmshapmat_t *fwdshapmat;
+ jas_cmshapmat_t *revshapmat;
+ int i;
+ int j;
+
+ if (!(prof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB)))
+ goto error;
+ prof->clrspc = JAS_CLRSPC_SYCBCR;
+ assert(prof->numchans == 3 && prof->numrefchans == 3);
+ assert(prof->refclrspc == JAS_CLRSPC_CIEXYZ);
+ if (!(fwdpxform = jas_cmpxform_createshapmat()))
+ goto error;
+ fwdpxform->numinchans = 3;
+ fwdpxform->numoutchans = 3;
+ fwdshapmat = &fwdpxform->data.shapmat;
+ fwdshapmat->mono = 0;
+ fwdshapmat->order = 0;
+ fwdshapmat->useluts = 0;
+ fwdshapmat->usemat = 1;
+ fwdshapmat->mat[0][0] = 1.0;
+ fwdshapmat->mat[0][1] = 0.0;
+ fwdshapmat->mat[0][2] = 1.402;
+ fwdshapmat->mat[1][0] = 1.0;
+ fwdshapmat->mat[1][1] = -0.34413;
+ fwdshapmat->mat[1][2] = -0.71414;
+ fwdshapmat->mat[2][0] = 1.0;
+ fwdshapmat->mat[2][1] = 1.772;
+ fwdshapmat->mat[2][2] = 0.0;
+ fwdshapmat->mat[0][3] = -0.5 * (1.402);
+ fwdshapmat->mat[1][3] = -0.5 * (-0.34413 - 0.71414);
+ fwdshapmat->mat[2][3] = -0.5 * (1.772);
+ if (!(revpxform = jas_cmpxform_createshapmat()))
+ goto error;
+ revpxform->numinchans = 3;
+ revpxform->numoutchans = 3;
+ revshapmat = &revpxform->data.shapmat;
+ revshapmat->mono = 0;
+ revshapmat->order = 1;
+ revshapmat->useluts = 0;
+ revshapmat->usemat = 1;
+ jas_cmshapmat_invmat(revshapmat->mat, fwdshapmat->mat);
+
+ for (i = 0; i < JAS_CMXFORM_NUMINTENTS; ++i) {
+ j = SEQFWD(i);
+ if (prof->pxformseqs[j]) {
+ if (jas_cmpxformseq_insertpxform(prof->pxformseqs[j], 0,
+ fwdpxform))
+ goto error;
+ }
+ j = SEQREV(i);
+ if (prof->pxformseqs[j]) {
+ if (jas_cmpxformseq_insertpxform(prof->pxformseqs[j],
+ -1, revpxform))
+ goto error;
+ }
+ }
+
+ jas_cmpxform_destroy(fwdpxform);
+ jas_cmpxform_destroy(revpxform);
+ return prof;
+error:
+ return 0;
+}
+
+jas_cmprof_t *jas_cmprof_createfromiccprof(jas_iccprof_t *iccprof)
+{
+ jas_cmprof_t *prof;
+ jas_icchdr_t icchdr;
+ jas_cmpxformseq_t *fwdpxformseq;
+ jas_cmpxformseq_t *revpxformseq;
+
+ prof = 0;
+ fwdpxformseq = 0;
+ revpxformseq = 0;
+
+ if (!(prof = jas_cmprof_create()))
+ goto error;
+ jas_iccprof_gethdr(iccprof, &icchdr);
+ if (!(prof->iccprof = jas_iccprof_copy(iccprof)))
+ goto error;
+ prof->clrspc = icctoclrspc(icchdr.colorspc, 0);
+ prof->refclrspc = icctoclrspc(icchdr.refcolorspc, 1);
+ prof->numchans = jas_clrspc_numchans(prof->clrspc);
+ prof->numrefchans = jas_clrspc_numchans(prof->refclrspc);
+
+ if (prof->numchans == 1) {
+ if (mono(prof->iccprof, 0, &fwdpxformseq))
+ goto error;
+ if (mono(prof->iccprof, 1, &revpxformseq))
+ goto error;
+ } else if (prof->numchans == 3) {
+ if (triclr(prof->iccprof, 0, &fwdpxformseq))
+ goto error;
+ if (triclr(prof->iccprof, 1, &revpxformseq))
+ goto error;
+ }
+ prof->pxformseqs[SEQFWD(0)] = fwdpxformseq;
+ prof->pxformseqs[SEQREV(0)] = revpxformseq;
+
+#if 0
+ if (prof->numchans > 1) {
+ lut(prof->iccprof, 0, PER, &pxformseq);
+ pxformseqs_set(prof, SEQFWD(PER), pxformseq);
+ lut(prof->iccprof, 1, PER, &pxformseq);
+ pxformseqs_set(prof, SEQREV(PER), pxformseq);
+ lut(prof->iccprof, 0, CLR, &pxformseq);
+ pxformseqs_set(prof, SEQREV(CLR), pxformseq);
+ lut(prof->iccprof, 1, CLR, &pxformseq);
+ pxformseqs_set(prof, SEQREV(CLR), pxformseq);
+ lut(prof->iccprof, 0, SAT, &pxformseq);
+ pxformseqs_set(prof, SEQREV(SAT), pxformseq);
+ lut(prof->iccprof, 1, SAT, &pxformseq);
+ pxformseqs_set(prof, SEQREV(SAT), pxformseq);
+ }
+#endif
+
+ return prof;
+
+error:
+ if (fwdpxformseq) {
+ jas_cmpxformseq_destroy(fwdpxformseq);
+ }
+ if (revpxformseq) {
+ jas_cmpxformseq_destroy(revpxformseq);
+ }
+ if (prof) {
+ jas_cmprof_destroy(prof);
+ }
+
+ return 0;
+}
+
+static jas_cmprof_t *jas_cmprof_create()
+{
+ int i;
+ jas_cmprof_t *prof;
+ if (!(prof = jas_malloc(sizeof(jas_cmprof_t))))
+ return 0;
+ memset(prof, 0, sizeof(jas_cmprof_t));
+ prof->iccprof = 0;
+ for (i = 0; i < JAS_CMPROF_NUMPXFORMSEQS; ++i)
+ prof->pxformseqs[i] = 0;
+ return prof;
+}
+
+void jas_cmprof_destroy(jas_cmprof_t *prof)
+{
+ int i;
+ for (i = 0; i < JAS_CMPROF_NUMPXFORMSEQS; ++i) {
+ if (prof->pxformseqs[i]) {
+ jas_cmpxformseq_destroy(prof->pxformseqs[i]);
+ prof->pxformseqs[i] = 0;
+ }
+ }
+ if (prof->iccprof)
+ jas_iccprof_destroy(prof->iccprof);
+ jas_free(prof);
+}
+
+jas_cmprof_t *jas_cmprof_copy(jas_cmprof_t *prof)
+{
+ jas_cmprof_t *newprof;
+ int i;
+
+ if (!(newprof = jas_cmprof_create()))
+ goto error;
+ newprof->clrspc = prof->clrspc;
+ newprof->numchans = prof->numchans;
+ newprof->refclrspc = prof->refclrspc;
+ newprof->numrefchans = prof->numrefchans;
+ newprof->iccprof = jas_iccprof_copy(prof->iccprof);
+ for (i = 0; i < JAS_CMPROF_NUMPXFORMSEQS; ++i) {
+ if (prof->pxformseqs[i]) {
+ if (!(newprof->pxformseqs[i] = jas_cmpxformseq_copy(prof->pxformseqs[i])))
+ goto error;
+ }
+ }
+ return newprof;
+error:
+ return 0;
+}
+
+/******************************************************************************\
+* Transform class.
+\******************************************************************************/
+
+jas_cmxform_t *jas_cmxform_create(jas_cmprof_t *inprof, jas_cmprof_t *outprof,
+ jas_cmprof_t *prfprof, int op, int intent, int optimize)
+{
+ jas_cmxform_t *xform;
+ jas_cmpxformseq_t *inpxformseq;
+ jas_cmpxformseq_t *outpxformseq;
+ jas_cmpxformseq_t *altoutpxformseq;
+ jas_cmpxformseq_t *prfpxformseq;
+ int prfintent;
+
+ /* Avoid compiler warnings about unused parameters. */
+ optimize = 0;
+
+ prfintent = intent;
+
+ if (!(xform = jas_malloc(sizeof(jas_cmxform_t))))
+ goto error;
+ if (!(xform->pxformseq = jas_cmpxformseq_create()))
+ goto error;
+
+ switch (op) {
+ case JAS_CMXFORM_OP_FWD:
+ inpxformseq = fwdpxformseq(inprof, intent);
+ outpxformseq = revpxformseq(outprof, intent);
+ if (!inpxformseq || !outpxformseq)
+ goto error;
+ if (jas_cmpxformseq_append(xform->pxformseq, inpxformseq) ||
+ jas_cmpxformseq_appendcnvt(xform->pxformseq,
+ inprof->refclrspc, outprof->refclrspc) ||
+ jas_cmpxformseq_append(xform->pxformseq, outpxformseq))
+ goto error;
+ xform->numinchans = jas_clrspc_numchans(inprof->clrspc);
+ xform->numoutchans = jas_clrspc_numchans(outprof->clrspc);
+ break;
+ case JAS_CMXFORM_OP_REV:
+ outpxformseq = fwdpxformseq(outprof, intent);
+ inpxformseq = revpxformseq(inprof, intent);
+ if (!outpxformseq || !inpxformseq)
+ goto error;
+ if (jas_cmpxformseq_append(xform->pxformseq, outpxformseq) ||
+ jas_cmpxformseq_appendcnvt(xform->pxformseq,
+ outprof->refclrspc, inprof->refclrspc) ||
+ jas_cmpxformseq_append(xform->pxformseq, inpxformseq))
+ goto error;
+ xform->numinchans = jas_clrspc_numchans(outprof->clrspc);
+ xform->numoutchans = jas_clrspc_numchans(inprof->clrspc);
+ break;
+ case JAS_CMXFORM_OP_PROOF:
+ assert(prfprof);
+ inpxformseq = fwdpxformseq(inprof, intent);
+ prfpxformseq = fwdpxformseq(prfprof, prfintent);
+ if (!inpxformseq || !prfpxformseq)
+ goto error;
+ outpxformseq = simpxformseq(outprof, intent);
+ altoutpxformseq = 0;
+ if (!outpxformseq) {
+ outpxformseq = revpxformseq(outprof, intent);
+ altoutpxformseq = fwdpxformseq(outprof, intent);
+ if (!outpxformseq || !altoutpxformseq)
+ goto error;
+ }
+ if (jas_cmpxformseq_append(xform->pxformseq, inpxformseq) ||
+ jas_cmpxformseq_appendcnvt(xform->pxformseq,
+ inprof->refclrspc, outprof->refclrspc))
+ goto error;
+ if (altoutpxformseq) {
+ if (jas_cmpxformseq_append(xform->pxformseq, outpxformseq) ||
+ jas_cmpxformseq_append(xform->pxformseq, altoutpxformseq))
+ goto error;
+ } else {
+ if (jas_cmpxformseq_append(xform->pxformseq, outpxformseq))
+ goto error;
+ }
+ if (jas_cmpxformseq_appendcnvt(xform->pxformseq,
+ outprof->refclrspc, inprof->refclrspc) ||
+ jas_cmpxformseq_append(xform->pxformseq, prfpxformseq))
+ goto error;
+ xform->numinchans = jas_clrspc_numchans(inprof->clrspc);
+ xform->numoutchans = jas_clrspc_numchans(prfprof->clrspc);
+ break;
+ case JAS_CMXFORM_OP_GAMUT:
+ inpxformseq = fwdpxformseq(inprof, intent);
+ outpxformseq = gampxformseq(outprof);
+ if (!inpxformseq || !outpxformseq)
+ goto error;
+ if (jas_cmpxformseq_append(xform->pxformseq, inpxformseq) ||
+ jas_cmpxformseq_appendcnvt(xform->pxformseq,
+ inprof->refclrspc, outprof->refclrspc) ||
+ jas_cmpxformseq_append(xform->pxformseq, outpxformseq))
+ goto error;
+ xform->numinchans = jas_clrspc_numchans(inprof->clrspc);
+ xform->numoutchans = 1;
+ break;
+ }
+ return xform;
+error:
+ return 0;
+}
+
+#define APPLYBUFSIZ 2048
+int jas_cmxform_apply(jas_cmxform_t *xform, jas_cmpixmap_t *in, jas_cmpixmap_t *out)
+{
+ jas_cmcmptfmt_t *fmt;
+ jas_cmreal_t buf[2][APPLYBUFSIZ];
+ jas_cmpxformseq_t *pxformseq;
+ int i;
+ int j;
+ int width;
+ int height;
+ int total;
+ int n;
+ jas_cmreal_t *inbuf;
+ jas_cmreal_t *outbuf;
+ jas_cmpxform_t *pxform;
+ long *dataptr;
+ int maxchans;
+ int bufmax;
+ int m;
+ int bias;
+ jas_cmreal_t scale;
+ long v;
+ jas_cmreal_t *bufptr;
+
+ if (xform->numinchans > in->numcmpts || xform->numoutchans > out->numcmpts)
+ goto error;
+
+ fmt = &in->cmptfmts[0];
+ width = fmt->width;
+ height = fmt->height;
+ for (i = 1; i < xform->numinchans; ++i) {
+ fmt = &in->cmptfmts[i];
+ if (fmt->width != width || fmt->height != height) {
+ goto error;
+ }
+ }
+ for (i = 0; i < xform->numoutchans; ++i) {
+ fmt = &out->cmptfmts[i];
+ if (fmt->width != width || fmt->height != height) {
+ goto error;
+ }
+ }
+
+ maxchans = 0;
+ pxformseq = xform->pxformseq;
+ for (i = 0; i < pxformseq->numpxforms; ++i) {
+ pxform = pxformseq->pxforms[i];
+ if (pxform->numinchans > maxchans) {
+ maxchans = pxform->numinchans;
+ }
+ if (pxform->numoutchans > maxchans) {
+ maxchans = pxform->numoutchans;
+ }
+ }
+ bufmax = APPLYBUFSIZ / maxchans;
+ assert(bufmax > 0);
+
+ total = width * height;
+ n = 0;
+ while (n < total) {
+
+ inbuf = &buf[0][0];
+ m = JAS_MIN(total - n, bufmax);
+
+ for (i = 0; i < xform->numinchans; ++i) {
+ fmt = &in->cmptfmts[i];
+ scale = (double)((1 << fmt->prec) - 1);
+ bias = fmt->sgnd ? (1 << (fmt->prec - 1)) : 0;
+ dataptr = &fmt->buf[n];
+ bufptr = &inbuf[i];
+ for (j = 0; j < m; ++j) {
+ if (jas_cmgetint(&dataptr, fmt->sgnd, fmt->prec, &v))
+ goto error;
+ *bufptr = (v - bias) / scale;
+ bufptr += xform->numinchans;
+ }
+ }
+
+ inbuf = &buf[0][0];
+ outbuf = inbuf;
+ for (i = 0; i < pxformseq->numpxforms; ++i) {
+ pxform = pxformseq->pxforms[i];
+ if (pxform->numoutchans > pxform->numinchans) {
+ outbuf = (inbuf == &buf[0][0]) ? &buf[1][0] : &buf[0][0];
+ } else {
+ outbuf = inbuf;
+ }
+ if ((*pxform->ops->apply)(pxform, inbuf, outbuf, m))
+ goto error;
+ inbuf = outbuf;
+ }
+
+ for (i = 0; i < xform->numoutchans; ++i) {
+ fmt = &out->cmptfmts[i];
+ scale = (double)((1 << fmt->prec) - 1);
+ bias = fmt->sgnd ? (1 << (fmt->prec - 1)) : 0;
+ bufptr = &outbuf[i];
+ dataptr = &fmt->buf[n];
+ for (j = 0; j < m; ++j) {
+ v = (*bufptr) * scale + bias;
+ bufptr += xform->numoutchans;
+ if (jas_cmputint(&dataptr, fmt->sgnd, fmt->prec, v))
+ goto error;
+ }
+ }
+
+ n += m;
+ }
+
+ return 0;
+error:
+ return -1;
+}
+
+void jas_cmxform_destroy(jas_cmxform_t *xform)
+{
+ if (xform->pxformseq)
+ jas_cmpxformseq_destroy(xform->pxformseq);
+ jas_free(xform);
+}
+
+/******************************************************************************\
+* Primitive transform sequence class.
+\******************************************************************************/
+
+static jas_cmpxformseq_t *jas_cmpxformseq_create()
+{
+ jas_cmpxformseq_t *pxformseq;
+ pxformseq = 0;
+ if (!(pxformseq = jas_malloc(sizeof(jas_cmpxformseq_t))))
+ goto error;
+ pxformseq->pxforms = 0;
+ pxformseq->numpxforms = 0;
+ pxformseq->maxpxforms = 0;
+ if (jas_cmpxformseq_resize(pxformseq, 16))
+ goto error;
+ return pxformseq;
+error:
+ if (pxformseq)
+ jas_cmpxformseq_destroy(pxformseq);
+ return 0;
+}
+
+static jas_cmpxformseq_t *jas_cmpxformseq_copy(jas_cmpxformseq_t *pxformseq)
+{
+ jas_cmpxformseq_t *newpxformseq;
+
+ if (!(newpxformseq = jas_cmpxformseq_create()))
+ goto error;
+ if (jas_cmpxformseq_append(newpxformseq, pxformseq))
+ goto error;
+ return newpxformseq;
+error:
+ return 0;
+}
+
+static void jas_cmpxformseq_destroy(jas_cmpxformseq_t *pxformseq)
+{
+ while (pxformseq->numpxforms > 0)
+ jas_cmpxformseq_delete(pxformseq, pxformseq->numpxforms - 1);
+ if (pxformseq->pxforms)
+ jas_free(pxformseq->pxforms);
+ jas_free(pxformseq);
+}
+
+static int jas_cmpxformseq_delete(jas_cmpxformseq_t *pxformseq, int i)
+{
+ assert(i >= 0 && i < pxformseq->numpxforms);
+ if (i != pxformseq->numpxforms - 1)
+ abort();
+ jas_cmpxform_destroy(pxformseq->pxforms[i]);
+ pxformseq->pxforms[i] = 0;
+ --pxformseq->numpxforms;
+ return 0;
+}
+
+static int jas_cmpxformseq_appendcnvt(jas_cmpxformseq_t *pxformseq,
+ int dstclrspc, int srcclrspc)
+{
+ if (dstclrspc == srcclrspc)
+ return 0;
+ abort();
+ /* Avoid compiler warnings about unused parameters. */
+ pxformseq = 0;
+ return -1;
+}
+
+static int jas_cmpxformseq_insertpxform(jas_cmpxformseq_t *pxformseq,
+ int i, jas_cmpxform_t *pxform)
+{
+ jas_cmpxform_t *tmppxform;
+ int n;
+ if (i < 0)
+ i = pxformseq->numpxforms;
+ assert(i >= 0 && i <= pxformseq->numpxforms);
+ if (pxformseq->numpxforms >= pxformseq->maxpxforms) {
+ if (jas_cmpxformseq_resize(pxformseq, pxformseq->numpxforms +
+ 16))
+ goto error;
+ }
+ assert(pxformseq->numpxforms < pxformseq->maxpxforms);
+ if (!(tmppxform = jas_cmpxform_copy(pxform)))
+ goto error;
+ n = pxformseq->numpxforms - i;
+ if (n > 0) {
+ memmove(&pxformseq->pxforms[i + 1], &pxformseq->pxforms[i],
+ n * sizeof(jas_cmpxform_t *));
+ }
+ pxformseq->pxforms[i] = tmppxform;
+ ++pxformseq->numpxforms;
+ return 0;
+error:
+ return -1;
+}
+
+static int jas_cmpxformseq_append(jas_cmpxformseq_t *pxformseq,
+ jas_cmpxformseq_t *othpxformseq)
+{
+ int n;
+ int i;
+ jas_cmpxform_t *pxform;
+ jas_cmpxform_t *othpxform;
+ n = pxformseq->numpxforms + othpxformseq->numpxforms;
+ if (n > pxformseq->maxpxforms) {
+ if (jas_cmpxformseq_resize(pxformseq, n))
+ goto error;
+ }
+ for (i = 0; i < othpxformseq->numpxforms; ++i) {
+ othpxform = othpxformseq->pxforms[i];
+ if (!(pxform = jas_cmpxform_copy(othpxform)))
+ goto error;
+ pxformseq->pxforms[pxformseq->numpxforms] = pxform;
+ ++pxformseq->numpxforms;
+ }
+ return 0;
+error:
+ return -1;
+}
+
+static int jas_cmpxformseq_resize(jas_cmpxformseq_t *pxformseq, int n)
+{
+ jas_cmpxform_t **p;
+ assert(n >= pxformseq->numpxforms);
+ p = (!pxformseq->pxforms) ? jas_malloc(n * sizeof(jas_cmpxform_t *)) :
+ jas_realloc(pxformseq->pxforms, n * sizeof(jas_cmpxform_t *));
+ if (!p) {
+ return -1;
+ }
+ pxformseq->pxforms = p;
+ pxformseq->maxpxforms = n;
+ return 0;
+}
+
+/******************************************************************************\
+* Primitive transform class.
+\******************************************************************************/
+
+static jas_cmpxform_t *jas_cmpxform_create0()
+{
+ jas_cmpxform_t *pxform;
+ if (!(pxform = jas_malloc(sizeof(jas_cmpxform_t))))
+ return 0;
+ memset(pxform, 0, sizeof(jas_cmpxform_t));
+ pxform->refcnt = 0;
+ pxform->ops = 0;
+ return pxform;
+}
+
+static void jas_cmpxform_destroy(jas_cmpxform_t *pxform)
+{
+ if (--pxform->refcnt <= 0) {
+ (*pxform->ops->destroy)(pxform);
+ jas_free(pxform);
+ }
+}
+
+static jas_cmpxform_t *jas_cmpxform_copy(jas_cmpxform_t *pxform)
+{
+ ++pxform->refcnt;
+ return pxform;
+}
+
+/******************************************************************************\
+* Shaper matrix class.
+\******************************************************************************/
+
+static jas_cmpxform_t *jas_cmpxform_createshapmat()
+{
+ int i;
+ int j;
+ jas_cmpxform_t *pxform;
+ jas_cmshapmat_t *shapmat;
+ if (!(pxform = jas_cmpxform_create0()))
+ return 0;
+ pxform->ops = &shapmat_ops;
+ shapmat = &pxform->data.shapmat;
+ shapmat->mono = 0;
+ shapmat->order = 0;
+ shapmat->useluts = 0;
+ shapmat->usemat = 0;
+ for (i = 0; i < 3; ++i)
+ jas_cmshapmatlut_init(&shapmat->luts[i]);
+ for (i = 0; i < 3; ++i) {
+ for (j = 0; j < 4; ++j)
+ shapmat->mat[i][j] = 0.0;
+ }
+ ++pxform->refcnt;
+ return pxform;
+}
+
+static void jas_cmshapmat_destroy(jas_cmpxform_t *pxform)
+{
+ jas_cmshapmat_t *shapmat = &pxform->data.shapmat;
+ int i;
+ for (i = 0; i < 3; ++i)
+ jas_cmshapmatlut_cleanup(&shapmat->luts[i]);
+}
+
+static int jas_cmshapmat_apply(jas_cmpxform_t *pxform, jas_cmreal_t *in,
+ jas_cmreal_t *out, int cnt)
+{
+ jas_cmshapmat_t *shapmat = &pxform->data.shapmat;
+ jas_cmreal_t *src;
+ jas_cmreal_t *dst;
+ jas_cmreal_t a0;
+ jas_cmreal_t a1;
+ jas_cmreal_t a2;
+ jas_cmreal_t b0;
+ jas_cmreal_t b1;
+ jas_cmreal_t b2;
+ src = in;
+ dst = out;
+ if (!shapmat->mono) {
+ while (--cnt >= 0) {
+ a0 = *src++;
+ a1 = *src++;
+ a2 = *src++;
+ if (!shapmat->order && shapmat->useluts) {
+ a0 = jas_cmshapmatlut_lookup(&shapmat->luts[0], a0);
+ a1 = jas_cmshapmatlut_lookup(&shapmat->luts[1], a1);
+ a2 = jas_cmshapmatlut_lookup(&shapmat->luts[2], a2);
+ }
+ if (shapmat->usemat) {
+ b0 = shapmat->mat[0][0] * a0
+ + shapmat->mat[0][1] * a1
+ + shapmat->mat[0][2] * a2
+ + shapmat->mat[0][3];
+ b1 = shapmat->mat[1][0] * a0
+ + shapmat->mat[1][1] * a1
+ + shapmat->mat[1][2] * a2
+ + shapmat->mat[1][3];
+ b2 = shapmat->mat[2][0] * a0
+ + shapmat->mat[2][1] * a1
+ + shapmat->mat[2][2] * a2
+ + shapmat->mat[2][3];
+ a0 = b0;
+ a1 = b1;
+ a2 = b2;
+ }
+ if (shapmat->order && shapmat->useluts) {
+ a0 = jas_cmshapmatlut_lookup(&shapmat->luts[0], a0);
+ a1 = jas_cmshapmatlut_lookup(&shapmat->luts[1], a1);
+ a2 = jas_cmshapmatlut_lookup(&shapmat->luts[2], a2);
+ }
+ *dst++ = a0;
+ *dst++ = a1;
+ *dst++ = a2;
+ }
+ } else {
+ if (!shapmat->order) {
+ while (--cnt >= 0) {
+ a0 = *src++;
+ if (shapmat->useluts)
+ a0 = jas_cmshapmatlut_lookup(&shapmat->luts[0], a0);
+ a2 = a0 * shapmat->mat[2][0];
+ a1 = a0 * shapmat->mat[1][0];
+ a0 = a0 * shapmat->mat[0][0];
+ *dst++ = a0;
+ *dst++ = a1;
+ *dst++ = a2;
+ }
+ } else {
+assert(0);
+ while (--cnt >= 0) {
+ a0 = *src++;
+ src++;
+ src++;
+ a0 = a0 * shapmat->mat[0][0];
+ if (shapmat->useluts)
+ a0 = jas_cmshapmatlut_lookup(&shapmat->luts[0], a0);
+ *dst++ = a0;
+ }
+ }
+ }
+
+ return 0;
+}
+
+static void jas_cmshapmatlut_init(jas_cmshapmatlut_t *lut)
+{
+ lut->data = 0;
+ lut->size = 0;
+}
+
+static void jas_cmshapmatlut_cleanup(jas_cmshapmatlut_t *lut)
+{
+ if (lut->data) {
+ jas_free(lut->data);
+ lut->data = 0;
+ }
+ lut->size = 0;
+}
+
+static double gammafn(double x, double gamma)
+{
+ if (x == 0.0)
+ return 0.0;
+ return pow(x, gamma);
+}
+
+static int jas_cmshapmatlut_set(jas_cmshapmatlut_t *lut, jas_icccurv_t *curv)
+{
+ jas_cmreal_t gamma;
+ int i;
+ gamma = 0;
+ jas_cmshapmatlut_cleanup(lut);
+ if (curv->numents == 0) {
+ lut->size = 2;
+ if (!(lut->data = jas_malloc(lut->size * sizeof(jas_cmreal_t))))
+ goto error;
+ lut->data[0] = 0.0;
+ lut->data[1] = 1.0;
+ } else if (curv->numents == 1) {
+ lut->size = 256;
+ if (!(lut->data = jas_malloc(lut->size * sizeof(jas_cmreal_t))))
+ goto error;
+ gamma = curv->ents[0] / 256.0;
+ for (i = 0; i < lut->size; ++i) {
+ lut->data[i] = gammafn(i / (double) (lut->size - 1), gamma);
+ }
+ } else {
+ lut->size = curv->numents;
+ if (!(lut->data = jas_malloc(lut->size * sizeof(jas_cmreal_t))))
+ goto error;
+ for (i = 0; i < lut->size; ++i) {
+ lut->data[i] = curv->ents[i] / 65535.0;
+ }
+ }
+ return 0;
+error:
+ return -1;
+}
+
+static jas_cmreal_t jas_cmshapmatlut_lookup(jas_cmshapmatlut_t *lut, jas_cmreal_t x)
+{
+ jas_cmreal_t t;
+ int lo;
+ int hi;
+ t = x * (lut->size - 1);
+ lo = floor(t);
+ if (lo < 0)
+ return lut->data[0];
+ hi = ceil(t);
+ if (hi >= lut->size)
+ return lut->data[lut->size - 1];
+ return lut->data[lo] + (t - lo) * (lut->data[hi] - lut->data[lo]);
+}
+
+static int jas_cmshapmatlut_invert(jas_cmshapmatlut_t *invlut,
+ jas_cmshapmatlut_t *lut, int n)
+{
+ int i;
+ int j;
+ int k;
+ jas_cmreal_t ax;
+ jas_cmreal_t ay;
+ jas_cmreal_t bx;
+ jas_cmreal_t by;
+ jas_cmreal_t sx;
+ jas_cmreal_t sy;
+ assert(n >= 2);
+ if (invlut->data) {
+ jas_free(invlut->data);
+ invlut->data = 0;
+ }
+ /* The sample values should be nondecreasing. */
+ for (i = 1; i < lut->size; ++i) {
+ if (lut->data[i - 1] > lut->data[i]) {
+ assert(0);
+ return -1;
+ }
+ }
+ if (!(invlut->data = jas_malloc(n * sizeof(jas_cmreal_t))))
+ return -1;
+ invlut->size = n;
+ for (i = 0; i < invlut->size; ++i) {
+ sy = ((double) i) / (invlut->size - 1);
+ sx = 1.0;
+ for (j = 0; j < lut->size; ++j) {
+ ay = lut->data[j];
+ if (sy == ay) {
+ for (k = j + 1; k < lut->size; ++k) {
+ by = lut->data[k];
+ if (by != sy)
+ break;
+#if 0
+assert(0);
+#endif
+ }
+ if (k < lut->size) {
+ --k;
+ ax = ((double) j) / (lut->size - 1);
+ bx = ((double) k) / (lut->size - 1);
+ sx = (ax + bx) / 2.0;
+ }
+ break;
+ }
+ if (j < lut->size - 1) {
+ by = lut->data[j + 1];
+ if (sy > ay && sy < by) {
+ ax = ((double) j) / (lut->size - 1);
+ bx = ((double) j + 1) / (lut->size - 1);
+ sx = ax +
+ (sy - ay) / (by - ay) * (bx - ax);
+ break;
+ }
+ }
+ }
+ invlut->data[i] = sx;
+ }
+#if 0
+for (i=0;i<lut->size;++i)
+ jas_eprintf("lut[%d]=%f ", i, lut->data[i]);
+for (i=0;i<invlut->size;++i)
+ jas_eprintf("invlut[%d]=%f ", i, invlut->data[i]);
+#endif
+ return 0;
+}
+
+static int jas_cmshapmat_invmat(jas_cmreal_t out[3][4], jas_cmreal_t in[3][4])
+{
+ jas_cmreal_t d;
+ d = in[0][0] * (in[1][1] * in[2][2] - in[1][2] * in[2][1])
+ - in[0][1] * (in[1][0] * in[2][2] - in[1][2] * in[2][0])
+ + in[0][2] * (in[1][0] * in[2][1] - in[1][1] * in[2][0]);
+#if 0
+jas_eprintf("delta=%f\n", d);
+#endif
+ if (JAS_ABS(d) < 1e-6)
+ return -1;
+ out[0][0] = (in[1][1] * in[2][2] - in[1][2] * in[2][1]) / d;
+ out[1][0] = -(in[1][0] * in[2][2] - in[1][2] * in[2][0]) / d;
+ out[2][0] = (in[1][0] * in[2][1] - in[1][1] * in[2][0]) / d;
+ out[0][1] = -(in[0][1] * in[2][2] - in[0][2] * in[2][1]) / d;
+ out[1][1] = (in[0][0] * in[2][2] - in[0][2] * in[2][0]) / d;
+ out[2][1] = -(in[0][0] * in[2][1] - in[0][1] * in[2][0]) / d;
+ out[0][2] = (in[0][1] * in[1][2] - in[0][2] * in[1][1]) / d;
+ out[1][2] = -(in[0][0] * in[1][2] - in[1][0] * in[0][2]) / d;
+ out[2][2] = (in[0][0] * in[1][1] - in[0][1] * in[1][0]) / d;
+ out[0][3] = -in[0][3];
+ out[1][3] = -in[1][3];
+ out[2][3] = -in[2][3];
+#if 0
+jas_eprintf("[ %f %f %f %f ]\n[ %f %f %f %f ]\n[ %f %f %f %f ]\n",
+in[0][0], in[0][1], in[0][2], in[0][3],
+in[1][0], in[1][1], in[1][2], in[1][3],
+in[2][0], in[2][1], in[2][2], in[2][3]);
+jas_eprintf("[ %f %f %f %f ]\n[ %f %f %f %f ]\n[ %f %f %f %f ]\n",
+out[0][0], out[0][1], out[0][2], out[0][3],
+out[1][0], out[1][1], out[1][2], out[1][3],
+out[2][0], out[2][1], out[2][2], out[2][3]);
+#endif
+ return 0;
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static int icctoclrspc(int iccclrspc, int refflag)
+{
+ if (refflag) {
+ switch (iccclrspc) {
+ case JAS_ICC_COLORSPC_XYZ:
+ return JAS_CLRSPC_CIEXYZ;
+ case JAS_ICC_COLORSPC_LAB:
+ return JAS_CLRSPC_CIELAB;
+ default:
+ abort();
+ break;
+ }
+ } else {
+ switch (iccclrspc) {
+ case JAS_ICC_COLORSPC_YCBCR:
+ return JAS_CLRSPC_GENYCBCR;
+ case JAS_ICC_COLORSPC_RGB:
+ return JAS_CLRSPC_GENRGB;
+ case JAS_ICC_COLORSPC_GRAY:
+ return JAS_CLRSPC_GENGRAY;
+ default:
+ abort();
+ break;
+ }
+ }
+}
+
+static int mono(jas_iccprof_t *iccprof, int op, jas_cmpxformseq_t **retpxformseq)
+{
+ jas_iccattrval_t *graytrc;
+ jas_cmshapmat_t *shapmat;
+ jas_cmpxform_t *pxform;
+ jas_cmpxformseq_t *pxformseq;
+ jas_cmshapmatlut_t lut;
+
+ jas_cmshapmatlut_init(&lut);
+ if (!(graytrc = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_GRYTRC)) ||
+ graytrc->type != JAS_ICC_TYPE_CURV)
+ goto error;
+ if (!(pxform = jas_cmpxform_createshapmat()))
+ goto error;
+ shapmat = &pxform->data.shapmat;
+ if (!(pxformseq = jas_cmpxformseq_create()))
+ goto error;
+ if (jas_cmpxformseq_insertpxform(pxformseq, -1, pxform))
+ goto error;
+
+ pxform->numinchans = 1;
+ pxform->numoutchans = 3;
+
+ shapmat->mono = 1;
+ shapmat->useluts = 1;
+ shapmat->usemat = 1;
+ if (!op) {
+ shapmat->order = 0;
+ shapmat->mat[0][0] = 0.9642;
+ shapmat->mat[1][0] = 1.0;
+ shapmat->mat[2][0] = 0.8249;
+ if (jas_cmshapmatlut_set(&shapmat->luts[0], &graytrc->data.curv))
+ goto error;
+ } else {
+ shapmat->order = 1;
+ shapmat->mat[0][0] = 1.0 / 0.9642;
+ shapmat->mat[1][0] = 1.0;
+ shapmat->mat[2][0] = 1.0 / 0.8249;
+ jas_cmshapmatlut_init(&lut);
+ if (jas_cmshapmatlut_set(&lut, &graytrc->data.curv))
+ goto error;
+ if (jas_cmshapmatlut_invert(&shapmat->luts[0], &lut, lut.size))
+ goto error;
+ jas_cmshapmatlut_cleanup(&lut);
+ }
+ jas_iccattrval_destroy(graytrc);
+ jas_cmpxform_destroy(pxform);
+ *retpxformseq = pxformseq;
+ return 0;
+error:
+ return -1;
+}
+
+static int triclr(jas_iccprof_t *iccprof, int op, jas_cmpxformseq_t **retpxformseq)
+{
+ int i;
+ jas_iccattrval_t *trcs[3];
+ jas_iccattrval_t *cols[3];
+ jas_cmshapmat_t *shapmat;
+ jas_cmpxform_t *pxform;
+ jas_cmpxformseq_t *pxformseq;
+ jas_cmreal_t mat[3][4];
+ jas_cmshapmatlut_t lut;
+
+ pxform = 0;
+ pxformseq = 0;
+ for (i = 0; i < 3; ++i) {
+ trcs[i] = 0;
+ cols[i] = 0;
+ }
+ jas_cmshapmatlut_init(&lut);
+
+ if (!(trcs[0] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_REDTRC)) ||
+ !(trcs[1] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_GRNTRC)) ||
+ !(trcs[2] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_BLUTRC)) ||
+ !(cols[0] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_REDMATCOL)) ||
+ !(cols[1] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_GRNMATCOL)) ||
+ !(cols[2] = jas_iccprof_getattr(iccprof, JAS_ICC_TAG_BLUMATCOL)))
+ goto error;
+ for (i = 0; i < 3; ++i) {
+ if (trcs[i]->type != JAS_ICC_TYPE_CURV ||
+ cols[i]->type != JAS_ICC_TYPE_XYZ)
+ goto error;
+ }
+ if (!(pxform = jas_cmpxform_createshapmat()))
+ goto error;
+ pxform->numinchans = 3;
+ pxform->numoutchans = 3;
+ shapmat = &pxform->data.shapmat;
+ if (!(pxformseq = jas_cmpxformseq_create()))
+ goto error;
+ if (jas_cmpxformseq_insertpxform(pxformseq, -1, pxform))
+ goto error;
+ shapmat->mono = 0;
+ shapmat->useluts = 1;
+ shapmat->usemat = 1;
+ if (!op) {
+ shapmat->order = 0;
+ for (i = 0; i < 3; ++i) {
+ shapmat->mat[0][i] = cols[i]->data.xyz.x / 65536.0;
+ shapmat->mat[1][i] = cols[i]->data.xyz.y / 65536.0;
+ shapmat->mat[2][i] = cols[i]->data.xyz.z / 65536.0;
+ }
+ for (i = 0; i < 3; ++i)
+ shapmat->mat[i][3] = 0.0;
+ for (i = 0; i < 3; ++i) {
+ if (jas_cmshapmatlut_set(&shapmat->luts[i], &trcs[i]->data.curv))
+ goto error;
+ }
+ } else {
+ shapmat->order = 1;
+ for (i = 0; i < 3; ++i) {
+ mat[0][i] = cols[i]->data.xyz.x / 65536.0;
+ mat[1][i] = cols[i]->data.xyz.y / 65536.0;
+ mat[2][i] = cols[i]->data.xyz.z / 65536.0;
+ }
+ for (i = 0; i < 3; ++i)
+ mat[i][3] = 0.0;
+ if (jas_cmshapmat_invmat(shapmat->mat, mat))
+ goto error;
+ for (i = 0; i < 3; ++i) {
+ jas_cmshapmatlut_init(&lut);
+ if (jas_cmshapmatlut_set(&lut, &trcs[i]->data.curv))
+ goto error;
+ if (jas_cmshapmatlut_invert(&shapmat->luts[i], &lut, lut.size))
+ goto error;
+ jas_cmshapmatlut_cleanup(&lut);
+ }
+ }
+ for (i = 0; i < 3; ++i) {
+ jas_iccattrval_destroy(trcs[i]);
+ jas_iccattrval_destroy(cols[i]);
+ }
+ jas_cmpxform_destroy(pxform);
+ *retpxformseq = pxformseq;
+ return 0;
+
+error:
+
+ for (i = 0; i < 3; ++i) {
+ if (trcs[i]) {
+ jas_iccattrval_destroy(trcs[i]);
+ }
+ if (cols[i]) {
+ jas_iccattrval_destroy(cols[i]);
+ }
+ }
+ if (pxformseq) {
+ jas_cmpxformseq_destroy(pxformseq);
+ }
+ if (pxform) {
+ jas_cmpxform_destroy(pxform);
+ }
+
+ return -1;
+}
+
+static int jas_cmgetint(long **bufptr, int sgnd, int prec, long *val)
+{
+ long v;
+ int m;
+ v = **bufptr;
+ if (sgnd) {
+ m = (1 << (prec - 1));
+ if (v < -m || v >= m)
+ return -1;
+ } else {
+ if (v < 0 || v >= (1 << prec))
+ return -1;
+ }
+ ++(*bufptr);
+ *val = v;
+ return 0;
+}
+
+static int jas_cmputint(long **bufptr, int sgnd, int prec, long val)
+{
+ int m;
+ if (sgnd) {
+ m = (1 << (prec - 1));
+ if (val < -m || val >= m)
+ return -1;
+ } else {
+ if (val < 0 || val >= (1 << prec))
+ return -1;
+ }
+ **bufptr = val;
+ ++(*bufptr);
+ return 0;
+}
+
+int jas_clrspc_numchans(int clrspc)
+{
+ switch (jas_clrspc_fam(clrspc)) {
+ case JAS_CLRSPC_FAM_XYZ:
+ case JAS_CLRSPC_FAM_LAB:
+ case JAS_CLRSPC_FAM_RGB:
+ case JAS_CLRSPC_FAM_YCBCR:
+ return 3;
+ break;
+ case JAS_CLRSPC_FAM_GRAY:
+ return 1;
+ break;
+ default:
+ abort();
+ break;
+ }
+}
+
+jas_iccprof_t *jas_iccprof_createfromcmprof(jas_cmprof_t *prof)
+{
+ return jas_iccprof_copy(prof->iccprof);
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/base/jas_debug.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_debug.c
new file mode 100644
index 0000000..433a800
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_debug.c
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdarg.h>
+#include <stdio.h>
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_debug.h"
+
+/******************************************************************************\
+* Local data.
+\******************************************************************************/
+
+static int jas_dbglevel = 0;
+/* The debug level. */
+
+/******************************************************************************\
+* Code for getting/setting the debug level.
+\******************************************************************************/
+
+/* Set the library debug level. */
+int jas_setdbglevel(int dbglevel)
+{
+ int olddbglevel;
+
+ /* Save the old debug level. */
+ olddbglevel = jas_dbglevel;
+
+ /* Change the debug level. */
+ jas_dbglevel = dbglevel;
+
+ /* Return the old debug level. */
+ return olddbglevel;
+}
+
+/* Get the library debug level. */
+int jas_getdbglevel()
+{
+ return jas_dbglevel;
+}
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+/* Perform formatted output to standard error. */
+int jas_eprintf(const char *fmt, ...)
+{
+ int ret;
+ va_list ap;
+
+ va_start(ap, fmt);
+ ret = vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ return ret;
+}
+
+/* Dump memory to a stream. */
+int jas_memdump(FILE *out, void *data, size_t len)
+{
+ size_t i;
+ size_t j;
+ uchar *dp;
+ dp = data;
+ for (i = 0; i < len; i += 16) {
+ fprintf(out, "%04x:", (unsigned int)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/jasper-1.900.1-6ct/src/libjasper/base/jas_getopt.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_getopt.c
new file mode 100644
index 0000000..9c9724a
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_getopt.c
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) 1999-2000, Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Command Line Option Parsing Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <string.h>
+
+#include "jasper/jas_getopt.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+
+/******************************************************************************\
+* Global data.
+\******************************************************************************/
+
+int jas_optind = 0;
+int jas_opterr = 1;
+char *jas_optarg = 0;
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+static jas_opt_t *jas_optlookup(jas_opt_t *opts, char *name)
+{
+ jas_opt_t *opt;
+
+ 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;
+
+ 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) {
+ jas_eprintf("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) {
+ jas_eprintf("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) {
+ jas_eprintf("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/jasper-1.900.1-6ct/src/libjasper/base/jas_icc.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_icc.c
new file mode 100644
index 0000000..e5a0a2e
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_icc.c
@@ -0,0 +1,1722 @@
+/*
+ * Copyright (c) 2002-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#include <assert.h>
+#include <jasper/jas_config.h>
+#include <jasper/jas_types.h>
+#include <jasper/jas_malloc.h>
+#include <jasper/jas_debug.h>
+#include <jasper/jas_icc.h>
+#include <jasper/jas_cm.h>
+#include <jasper/jas_stream.h>
+#include <jasper/jas_string.h>
+
+#include <stdlib.h>
+#include <ctype.h>
+
+#define jas_iccputuint8(out, val) jas_iccputuint(out, 1, val)
+#define jas_iccputuint16(out, val) jas_iccputuint(out, 2, val)
+#define jas_iccputsint32(out, val) jas_iccputsint(out, 4, val)
+#define jas_iccputuint32(out, val) jas_iccputuint(out, 4, val)
+#define jas_iccputuint64(out, val) jas_iccputuint(out, 8, val)
+
+static jas_iccattrval_t *jas_iccattrval_create0(void);
+
+static int jas_iccgetuint(jas_stream_t *in, int n, ulonglong *val);
+static int jas_iccgetuint8(jas_stream_t *in, jas_iccuint8_t *val);
+static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val);
+static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val);
+static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val);
+static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val);
+static int jas_iccputuint(jas_stream_t *out, int n, ulonglong val);
+static int jas_iccputsint(jas_stream_t *out, int n, longlong val);
+static jas_iccprof_t *jas_iccprof_create(void);
+static int jas_iccprof_readhdr(jas_stream_t *in, jas_icchdr_t *hdr);
+static int jas_iccprof_writehdr(jas_stream_t *out, jas_icchdr_t *hdr);
+static int jas_iccprof_gettagtab(jas_stream_t *in, jas_icctagtab_t *tagtab);
+static void jas_iccprof_sorttagtab(jas_icctagtab_t *tagtab);
+static int jas_iccattrtab_lookup(jas_iccattrtab_t *attrtab, jas_iccuint32_t name);
+static jas_iccattrtab_t *jas_iccattrtab_copy(jas_iccattrtab_t *attrtab);
+static jas_iccattrvalinfo_t *jas_iccattrvalinfo_lookup(jas_iccsig_t name);
+static int jas_iccgettime(jas_stream_t *in, jas_icctime_t *time);
+static int jas_iccgetxyz(jas_stream_t *in, jas_iccxyz_t *xyz);
+static int jas_icctagtabent_cmp(const void *src, const void *dst);
+
+static void jas_icccurv_destroy(jas_iccattrval_t *attrval);
+static int jas_icccurv_copy(jas_iccattrval_t *attrval,
+ jas_iccattrval_t *othattrval);
+static int jas_icccurv_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+ int cnt);
+static int jas_icccurv_getsize(jas_iccattrval_t *attrval);
+static int jas_icccurv_output(jas_iccattrval_t *attrval, jas_stream_t *out);
+static void jas_icccurv_dump(jas_iccattrval_t *attrval, FILE *out);
+
+static void jas_icctxtdesc_destroy(jas_iccattrval_t *attrval);
+static int jas_icctxtdesc_copy(jas_iccattrval_t *attrval,
+ jas_iccattrval_t *othattrval);
+static int jas_icctxtdesc_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+ int cnt);
+static int jas_icctxtdesc_getsize(jas_iccattrval_t *attrval);
+static int jas_icctxtdesc_output(jas_iccattrval_t *attrval, jas_stream_t *out);
+static void jas_icctxtdesc_dump(jas_iccattrval_t *attrval, FILE *out);
+
+static void jas_icctxt_destroy(jas_iccattrval_t *attrval);
+static int jas_icctxt_copy(jas_iccattrval_t *attrval,
+ jas_iccattrval_t *othattrval);
+static int jas_icctxt_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+ int cnt);
+static int jas_icctxt_getsize(jas_iccattrval_t *attrval);
+static int jas_icctxt_output(jas_iccattrval_t *attrval, jas_stream_t *out);
+static void jas_icctxt_dump(jas_iccattrval_t *attrval, FILE *out);
+
+static int jas_iccxyz_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+ int cnt);
+static int jas_iccxyz_getsize(jas_iccattrval_t *attrval);
+static int jas_iccxyz_output(jas_iccattrval_t *attrval, jas_stream_t *out);
+static void jas_iccxyz_dump(jas_iccattrval_t *attrval, FILE *out);
+
+static jas_iccattrtab_t *jas_iccattrtab_create(void);
+static void jas_iccattrtab_destroy(jas_iccattrtab_t *tab);
+static int jas_iccattrtab_resize(jas_iccattrtab_t *tab, int maxents);
+static int jas_iccattrtab_add(jas_iccattrtab_t *attrtab, int i,
+ jas_iccuint32_t name, jas_iccattrval_t *val);
+static int jas_iccattrtab_replace(jas_iccattrtab_t *attrtab, int i,
+ jas_iccuint32_t name, jas_iccattrval_t *val);
+static void jas_iccattrtab_delete(jas_iccattrtab_t *attrtab, int i);
+static long jas_iccpadtomult(long x, long y);
+static int jas_iccattrtab_get(jas_iccattrtab_t *attrtab, int i,
+ jas_iccattrname_t *name, jas_iccattrval_t **val);
+static int jas_iccprof_puttagtab(jas_stream_t *out, jas_icctagtab_t *tagtab);
+
+static void jas_icclut16_destroy(jas_iccattrval_t *attrval);
+static int jas_icclut16_copy(jas_iccattrval_t *attrval,
+ jas_iccattrval_t *othattrval);
+static int jas_icclut16_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+ int cnt);
+static int jas_icclut16_getsize(jas_iccattrval_t *attrval);
+static int jas_icclut16_output(jas_iccattrval_t *attrval, jas_stream_t *out);
+static void jas_icclut16_dump(jas_iccattrval_t *attrval, FILE *out);
+
+static void jas_icclut8_destroy(jas_iccattrval_t *attrval);
+static int jas_icclut8_copy(jas_iccattrval_t *attrval,
+ jas_iccattrval_t *othattrval);
+static int jas_icclut8_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+ int cnt);
+static int jas_icclut8_getsize(jas_iccattrval_t *attrval);
+static int jas_icclut8_output(jas_iccattrval_t *attrval, jas_stream_t *out);
+static void jas_icclut8_dump(jas_iccattrval_t *attrval, FILE *out);
+
+static int jas_iccputtime(jas_stream_t *out, jas_icctime_t *ctime);
+static int jas_iccputxyz(jas_stream_t *out, jas_iccxyz_t *xyz);
+
+static long jas_iccpowi(int x, int n);
+
+static char *jas_iccsigtostr(int sig, char *buf);
+
+
+jas_iccattrvalinfo_t jas_iccattrvalinfos[] = {
+ {JAS_ICC_TYPE_CURV, {jas_icccurv_destroy, jas_icccurv_copy,
+ jas_icccurv_input, jas_icccurv_output, jas_icccurv_getsize,
+ jas_icccurv_dump}},
+ {JAS_ICC_TYPE_XYZ, {0, 0, jas_iccxyz_input, jas_iccxyz_output,
+ jas_iccxyz_getsize, jas_iccxyz_dump}},
+ {JAS_ICC_TYPE_TXTDESC, {jas_icctxtdesc_destroy,
+ jas_icctxtdesc_copy, jas_icctxtdesc_input, jas_icctxtdesc_output,
+ jas_icctxtdesc_getsize, jas_icctxtdesc_dump}},
+ {JAS_ICC_TYPE_TXT, {jas_icctxt_destroy, jas_icctxt_copy,
+ jas_icctxt_input, jas_icctxt_output, jas_icctxt_getsize,
+ jas_icctxt_dump}},
+ {JAS_ICC_TYPE_LUT8, {jas_icclut8_destroy, jas_icclut8_copy,
+ jas_icclut8_input, jas_icclut8_output, jas_icclut8_getsize,
+ jas_icclut8_dump}},
+ {JAS_ICC_TYPE_LUT16, {jas_icclut16_destroy, jas_icclut16_copy,
+ jas_icclut16_input, jas_icclut16_output, jas_icclut16_getsize,
+ jas_icclut16_dump}},
+ {0, {0, 0, 0, 0, 0, 0}}
+};
+
+typedef struct {
+ jas_iccuint32_t tag;
+ char *name;
+} jas_icctaginfo_t;
+
+/******************************************************************************\
+* profile class
+\******************************************************************************/
+
+static jas_iccprof_t *jas_iccprof_create()
+{
+ jas_iccprof_t *prof;
+ prof = 0;
+ if (!(prof = jas_malloc(sizeof(jas_iccprof_t)))) {
+ goto error;
+ }
+ if (!(prof->attrtab = jas_iccattrtab_create()))
+ goto error;
+ memset(&prof->hdr, 0, sizeof(jas_icchdr_t));
+ prof->tagtab.numents = 0;
+ prof->tagtab.ents = 0;
+ return prof;
+error:
+ if (prof)
+ jas_iccprof_destroy(prof);
+ return 0;
+}
+
+jas_iccprof_t *jas_iccprof_copy(jas_iccprof_t *prof)
+{
+ jas_iccprof_t *newprof;
+ newprof = 0;
+ if (!(newprof = jas_iccprof_create()))
+ goto error;
+ newprof->hdr = prof->hdr;
+ newprof->tagtab.numents = 0;
+ newprof->tagtab.ents = 0;
+ assert(newprof->attrtab);
+ jas_iccattrtab_destroy(newprof->attrtab);
+ if (!(newprof->attrtab = jas_iccattrtab_copy(prof->attrtab)))
+ goto error;
+ return newprof;
+error:
+ if (newprof)
+ jas_iccprof_destroy(newprof);
+ return 0;
+}
+
+void jas_iccprof_destroy(jas_iccprof_t *prof)
+{
+ if (prof->attrtab)
+ jas_iccattrtab_destroy(prof->attrtab);
+ if (prof->tagtab.ents)
+ jas_free(prof->tagtab.ents);
+ jas_free(prof);
+}
+
+void jas_iccprof_dump(jas_iccprof_t *prof, FILE *out)
+{
+ jas_iccattrtab_dump(prof->attrtab, out);
+}
+
+jas_iccprof_t *jas_iccprof_load(jas_stream_t *in)
+{
+ jas_iccprof_t *prof;
+ int numtags;
+ long curoff;
+ long reloff;
+ long prevoff;
+ jas_iccsig_t type;
+ jas_iccattrval_t *attrval;
+ jas_iccattrval_t *prevattrval;
+ jas_icctagtabent_t *tagtabent;
+ jas_iccattrvalinfo_t *attrvalinfo;
+ int i;
+ int len;
+
+ prof = 0;
+ attrval = 0;
+
+ if (!(prof = jas_iccprof_create())) {
+ goto error;
+ }
+
+ if (jas_iccprof_readhdr(in, &prof->hdr)) {
+ jas_eprintf("cannot get header\n");
+ goto error;
+ }
+ if (jas_iccprof_gettagtab(in, &prof->tagtab)) {
+ jas_eprintf("cannot get tab table\n");
+ goto error;
+ }
+ jas_iccprof_sorttagtab(&prof->tagtab);
+
+ numtags = prof->tagtab.numents;
+ curoff = JAS_ICC_HDRLEN + 4 + 12 * numtags;
+ prevoff = 0;
+ prevattrval = 0;
+ for (i = 0; i < numtags; ++i) {
+ tagtabent = &prof->tagtab.ents[i];
+ if (tagtabent->off == JAS_CAST(jas_iccuint32_t, prevoff)) {
+ if (prevattrval) {
+ if (!(attrval = jas_iccattrval_clone(prevattrval)))
+ goto error;
+ if (jas_iccprof_setattr(prof, tagtabent->tag, attrval))
+ goto error;
+ jas_iccattrval_destroy(attrval);
+ } else {
+#if 0
+ jas_eprintf("warning: skipping unknown tag type\n");
+#endif
+ }
+ continue;
+ }
+ reloff = tagtabent->off - curoff;
+ if (reloff > 0) {
+ if (jas_stream_gobble(in, reloff) != reloff)
+ goto error;
+ curoff += reloff;
+ } else if (reloff < 0) {
+ /* This should never happen since we read the tagged
+ element data in a single pass. */
+ abort();
+ }
+ prevoff = curoff;
+ if (jas_iccgetuint32(in, &type)) {
+ goto error;
+ }
+ if (jas_stream_gobble(in, 4) != 4) {
+ goto error;
+ }
+ curoff += 8;
+ if (!(attrvalinfo = jas_iccattrvalinfo_lookup(type))) {
+#if 0
+ jas_eprintf("warning: skipping unknown tag type\n");
+#endif
+ prevattrval = 0;
+ continue;
+ }
+ if (!(attrval = jas_iccattrval_create(type))) {
+ goto error;
+ }
+ len = tagtabent->len - 8;
+ if ((*attrval->ops->input)(attrval, in, len)) {
+ goto error;
+ }
+ curoff += len;
+ if (jas_iccprof_setattr(prof, tagtabent->tag, attrval)) {
+ goto error;
+ }
+ prevattrval = attrval; /* This is correct, but slimey. */
+ jas_iccattrval_destroy(attrval);
+ attrval = 0;
+ }
+
+ return prof;
+
+error:
+ if (prof)
+ jas_iccprof_destroy(prof);
+ if (attrval)
+ jas_iccattrval_destroy(attrval);
+ return 0;
+}
+
+int jas_iccprof_save(jas_iccprof_t *prof, jas_stream_t *out)
+{
+ long curoff;
+ long reloff;
+ long newoff;
+ int i;
+ int j;
+ jas_icctagtabent_t *tagtabent;
+ jas_icctagtabent_t *sharedtagtabent;
+ jas_icctagtabent_t *tmptagtabent;
+ jas_iccuint32_t attrname;
+ jas_iccattrval_t *attrval;
+ jas_icctagtab_t *tagtab;
+
+ tagtab = &prof->tagtab;
+ if (!(tagtab->ents = jas_malloc(prof->attrtab->numattrs *
+ sizeof(jas_icctagtabent_t))))
+ goto error;
+ tagtab->numents = prof->attrtab->numattrs;
+ curoff = JAS_ICC_HDRLEN + 4 + 12 * tagtab->numents;
+ for (i = 0; i < JAS_CAST(int, tagtab->numents); ++i) {
+ tagtabent = &tagtab->ents[i];
+ if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval))
+ goto error;
+ assert(attrval->ops->output);
+ tagtabent->tag = attrname;
+ tagtabent->data = &attrval->data;
+ sharedtagtabent = 0;
+ for (j = 0; j < i; ++j) {
+ tmptagtabent = &tagtab->ents[j];
+ if (tagtabent->data == tmptagtabent->data) {
+ sharedtagtabent = tmptagtabent;
+ break;
+ }
+ }
+ if (sharedtagtabent) {
+ tagtabent->off = sharedtagtabent->off;
+ tagtabent->len = sharedtagtabent->len;
+ tagtabent->first = sharedtagtabent;
+ } else {
+ tagtabent->off = curoff;
+ tagtabent->len = (*attrval->ops->getsize)(attrval) + 8;
+ tagtabent->first = 0;
+ if (i < JAS_CAST(int, tagtab->numents - 1)) {
+ curoff = jas_iccpadtomult(curoff + tagtabent->len, 4);
+ } else {
+ curoff += tagtabent->len;
+ }
+ }
+ jas_iccattrval_destroy(attrval);
+ }
+ prof->hdr.size = curoff;
+ if (jas_iccprof_writehdr(out, &prof->hdr))
+ goto error;
+ if (jas_iccprof_puttagtab(out, &prof->tagtab))
+ goto error;
+ curoff = JAS_ICC_HDRLEN + 4 + 12 * tagtab->numents;
+ for (i = 0; i < JAS_CAST(int, tagtab->numents);) {
+ tagtabent = &tagtab->ents[i];
+ assert(curoff == JAS_CAST(long, tagtabent->off));
+ if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval))
+ goto error;
+ if (jas_iccputuint32(out, attrval->type) || jas_stream_pad(out,
+ 4, 0) != 4)
+ goto error;
+ if ((*attrval->ops->output)(attrval, out))
+ goto error;
+ jas_iccattrval_destroy(attrval);
+ curoff += tagtabent->len;
+ ++i;
+ while (i < JAS_CAST(int, tagtab->numents) &&
+ tagtab->ents[i].first)
+ ++i;
+ newoff = (i < JAS_CAST(int, tagtab->numents)) ?
+ tagtab->ents[i].off : prof->hdr.size;
+ reloff = newoff - curoff;
+ assert(reloff >= 0);
+ if (reloff > 0) {
+ if (jas_stream_pad(out, reloff, 0) != reloff)
+ goto error;
+ curoff += reloff;
+ }
+ }
+ return 0;
+error:
+ /* XXX - need to free some resources here */
+ return -1;
+}
+
+static int jas_iccprof_writehdr(jas_stream_t *out, jas_icchdr_t *hdr)
+{
+ if (jas_iccputuint32(out, hdr->size) ||
+ jas_iccputuint32(out, hdr->cmmtype) ||
+ jas_iccputuint32(out, hdr->version) ||
+ jas_iccputuint32(out, hdr->clas) ||
+ jas_iccputuint32(out, hdr->colorspc) ||
+ jas_iccputuint32(out, hdr->refcolorspc) ||
+ jas_iccputtime(out, &hdr->ctime) ||
+ jas_iccputuint32(out, hdr->magic) ||
+ jas_iccputuint32(out, hdr->platform) ||
+ jas_iccputuint32(out, hdr->flags) ||
+ jas_iccputuint32(out, hdr->maker) ||
+ jas_iccputuint32(out, hdr->model) ||
+ jas_iccputuint64(out, hdr->attr) ||
+ jas_iccputuint32(out, hdr->intent) ||
+ jas_iccputxyz(out, &hdr->illum) ||
+ jas_iccputuint32(out, hdr->creator) ||
+ jas_stream_pad(out, 44, 0) != 44)
+ return -1;
+ return 0;
+}
+
+static int jas_iccprof_puttagtab(jas_stream_t *out, jas_icctagtab_t *tagtab)
+{
+ int i;
+ jas_icctagtabent_t *tagtabent;
+ if (jas_iccputuint32(out, tagtab->numents))
+ goto error;
+ for (i = 0; i < JAS_CAST(int, tagtab->numents); ++i) {
+ tagtabent = &tagtab->ents[i];
+ if (jas_iccputuint32(out, tagtabent->tag) ||
+ jas_iccputuint32(out, tagtabent->off) ||
+ jas_iccputuint32(out, tagtabent->len))
+ goto error;
+ }
+ return 0;
+error:
+ return -1;
+}
+
+static int jas_iccprof_readhdr(jas_stream_t *in, jas_icchdr_t *hdr)
+{
+ if (jas_iccgetuint32(in, &hdr->size) ||
+ jas_iccgetuint32(in, &hdr->cmmtype) ||
+ jas_iccgetuint32(in, &hdr->version) ||
+ jas_iccgetuint32(in, &hdr->clas) ||
+ jas_iccgetuint32(in, &hdr->colorspc) ||
+ jas_iccgetuint32(in, &hdr->refcolorspc) ||
+ jas_iccgettime(in, &hdr->ctime) ||
+ jas_iccgetuint32(in, &hdr->magic) ||
+ jas_iccgetuint32(in, &hdr->platform) ||
+ jas_iccgetuint32(in, &hdr->flags) ||
+ jas_iccgetuint32(in, &hdr->maker) ||
+ jas_iccgetuint32(in, &hdr->model) ||
+ jas_iccgetuint64(in, &hdr->attr) ||
+ jas_iccgetuint32(in, &hdr->intent) ||
+ jas_iccgetxyz(in, &hdr->illum) ||
+ jas_iccgetuint32(in, &hdr->creator) ||
+ jas_stream_gobble(in, 44) != 44)
+ return -1;
+ return 0;
+}
+
+static int jas_iccprof_gettagtab(jas_stream_t *in, jas_icctagtab_t *tagtab)
+{
+ int i;
+ jas_icctagtabent_t *tagtabent;
+
+ if (tagtab->ents) {
+ jas_free(tagtab->ents);
+ tagtab->ents = 0;
+ }
+ if (jas_iccgetuint32(in, &tagtab->numents))
+ goto error;
+ if (!(tagtab->ents = jas_malloc(tagtab->numents *
+ sizeof(jas_icctagtabent_t))))
+ goto error;
+ tagtabent = tagtab->ents;
+ for (i = 0; i < JAS_CAST(long, tagtab->numents); ++i) {
+ if (jas_iccgetuint32(in, &tagtabent->tag) ||
+ jas_iccgetuint32(in, &tagtabent->off) ||
+ jas_iccgetuint32(in, &tagtabent->len))
+ goto error;
+ ++tagtabent;
+ }
+ return 0;
+error:
+ if (tagtab->ents) {
+ jas_free(tagtab->ents);
+ tagtab->ents = 0;
+ }
+ return -1;
+}
+
+jas_iccattrval_t *jas_iccprof_getattr(jas_iccprof_t *prof,
+ jas_iccattrname_t name)
+{
+ int i;
+ jas_iccattrval_t *attrval;
+ if ((i = jas_iccattrtab_lookup(prof->attrtab, name)) < 0)
+ goto error;
+ if (!(attrval = jas_iccattrval_clone(prof->attrtab->attrs[i].val)))
+ goto error;
+ return attrval;
+error:
+ return 0;
+}
+
+int jas_iccprof_setattr(jas_iccprof_t *prof, jas_iccattrname_t name,
+ jas_iccattrval_t *val)
+{
+ int i;
+ if ((i = jas_iccattrtab_lookup(prof->attrtab, name)) >= 0) {
+ if (val) {
+ if (jas_iccattrtab_replace(prof->attrtab, i, name, val))
+ goto error;
+ } else {
+ jas_iccattrtab_delete(prof->attrtab, i);
+ }
+ } else {
+ if (val) {
+ if (jas_iccattrtab_add(prof->attrtab, -1, name, val))
+ goto error;
+ } else {
+ /* NOP */
+ }
+ }
+ return 0;
+error:
+ return -1;
+}
+
+int jas_iccprof_gethdr(jas_iccprof_t *prof, jas_icchdr_t *hdr)
+{
+ *hdr = prof->hdr;
+ return 0;
+}
+
+int jas_iccprof_sethdr(jas_iccprof_t *prof, jas_icchdr_t *hdr)
+{
+ prof->hdr = *hdr;
+ return 0;
+}
+
+static void jas_iccprof_sorttagtab(jas_icctagtab_t *tagtab)
+{
+ qsort(tagtab->ents, tagtab->numents, sizeof(jas_icctagtabent_t),
+ jas_icctagtabent_cmp);
+}
+
+static int jas_icctagtabent_cmp(const void *src, const void *dst)
+{
+ jas_icctagtabent_t *srctagtabent = JAS_CAST(jas_icctagtabent_t *, src);
+ jas_icctagtabent_t *dsttagtabent = JAS_CAST(jas_icctagtabent_t *, dst);
+ if (srctagtabent->off > dsttagtabent->off) {
+ return 1;
+ } else if (srctagtabent->off < dsttagtabent->off) {
+ return -1;
+ }
+ return 0;
+}
+
+static jas_iccattrvalinfo_t *jas_iccattrvalinfo_lookup(jas_iccsig_t type)
+{
+ jas_iccattrvalinfo_t *info;
+ info = jas_iccattrvalinfos;
+ for (info = jas_iccattrvalinfos; info->type; ++info) {
+ if (info->type == type) {
+ return info;
+ }
+ }
+ return 0;
+}
+
+static int jas_iccgettime(jas_stream_t *in, jas_icctime_t *time)
+{
+ if (jas_iccgetuint16(in, &time->year) ||
+ jas_iccgetuint16(in, &time->month) ||
+ jas_iccgetuint16(in, &time->day) ||
+ jas_iccgetuint16(in, &time->hour) ||
+ jas_iccgetuint16(in, &time->min) ||
+ jas_iccgetuint16(in, &time->sec)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jas_iccgetxyz(jas_stream_t *in, jas_iccxyz_t *xyz)
+{
+ if (jas_iccgetsint32(in, &xyz->x) ||
+ jas_iccgetsint32(in, &xyz->y) ||
+ jas_iccgetsint32(in, &xyz->z)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jas_iccputtime(jas_stream_t *out, jas_icctime_t *time)
+{
+ jas_iccputuint16(out, time->year);
+ jas_iccputuint16(out, time->month);
+ jas_iccputuint16(out, time->day);
+ jas_iccputuint16(out, time->hour);
+ jas_iccputuint16(out, time->min);
+ jas_iccputuint16(out, time->sec);
+ return 0;
+}
+
+static int jas_iccputxyz(jas_stream_t *out, jas_iccxyz_t *xyz)
+{
+ jas_iccputuint32(out, xyz->x);
+ jas_iccputuint32(out, xyz->y);
+ jas_iccputuint32(out, xyz->z);
+ return 0;
+}
+
+/******************************************************************************\
+* attribute table class
+\******************************************************************************/
+
+static jas_iccattrtab_t *jas_iccattrtab_create()
+{
+ jas_iccattrtab_t *tab;
+ tab = 0;
+ if (!(tab = jas_malloc(sizeof(jas_iccattrtab_t))))
+ goto error;
+ tab->maxattrs = 0;
+ tab->numattrs = 0;
+ tab->attrs = 0;
+ if (jas_iccattrtab_resize(tab, 32))
+ goto error;
+ return tab;
+error:
+ if (tab)
+ jas_iccattrtab_destroy(tab);
+ return 0;
+}
+
+static jas_iccattrtab_t *jas_iccattrtab_copy(jas_iccattrtab_t *attrtab)
+{
+ jas_iccattrtab_t *newattrtab;
+ int i;
+ if (!(newattrtab = jas_iccattrtab_create()))
+ goto error;
+ for (i = 0; i < attrtab->numattrs; ++i) {
+ if (jas_iccattrtab_add(newattrtab, i, attrtab->attrs[i].name,
+ attrtab->attrs[i].val))
+ goto error;
+ }
+ return newattrtab;
+error:
+ return 0;
+}
+
+static void jas_iccattrtab_destroy(jas_iccattrtab_t *tab)
+{
+ if (tab->attrs) {
+ while (tab->numattrs > 0) {
+ jas_iccattrtab_delete(tab, 0);
+ }
+ jas_free(tab->attrs);
+ }
+ jas_free(tab);
+}
+
+void jas_iccattrtab_dump(jas_iccattrtab_t *attrtab, FILE *out)
+{
+ int i;
+ jas_iccattr_t *attr;
+ jas_iccattrval_t *attrval;
+ jas_iccattrvalinfo_t *info;
+ char buf[16];
+ fprintf(out, "numattrs=%d\n", attrtab->numattrs);
+ fprintf(out, "---\n");
+ for (i = 0; i < attrtab->numattrs; ++i) {
+ attr = &attrtab->attrs[i];
+ attrval = attr->val;
+ info = jas_iccattrvalinfo_lookup(attrval->type);
+ if (!info) abort();
+ fprintf(out, "attrno=%d; attrname=\"%s\"(0x%08x); attrtype=\"%s\"(0x%08x)\n",
+ i,
+ jas_iccsigtostr(attr->name, &buf[0]),
+ attr->name,
+ jas_iccsigtostr(attrval->type, &buf[8]),
+ attrval->type
+ );
+ jas_iccattrval_dump(attrval, out);
+ fprintf(out, "---\n");
+ }
+}
+
+static int jas_iccattrtab_resize(jas_iccattrtab_t *tab, int maxents)
+{
+ jas_iccattr_t *newattrs;
+ assert(maxents >= tab->numattrs);
+ newattrs = tab->attrs ? jas_realloc(tab->attrs, maxents *
+ sizeof(jas_iccattr_t)) : jas_malloc(maxents * sizeof(jas_iccattr_t));
+ if (!newattrs)
+ return -1;
+ tab->attrs = newattrs;
+ tab->maxattrs = maxents;
+ return 0;
+}
+
+static int jas_iccattrtab_add(jas_iccattrtab_t *attrtab, int i,
+ jas_iccuint32_t name, jas_iccattrval_t *val)
+{
+ int n;
+ jas_iccattr_t *attr;
+ jas_iccattrval_t *tmpattrval;
+ tmpattrval = 0;
+ if (i < 0) {
+ i = attrtab->numattrs;
+ }
+ assert(i >= 0 && i <= attrtab->numattrs);
+ if (attrtab->numattrs >= attrtab->maxattrs) {
+ if (jas_iccattrtab_resize(attrtab, attrtab->numattrs + 32)) {
+ goto error;
+ }
+ }
+ if (!(tmpattrval = jas_iccattrval_clone(val)))
+ goto error;
+ n = attrtab->numattrs - i;
+ if (n > 0)
+ memmove(&attrtab->attrs[i + 1], &attrtab->attrs[i],
+ n * sizeof(jas_iccattr_t));
+ attr = &attrtab->attrs[i];
+ attr->name = name;
+ attr->val = tmpattrval;
+ ++attrtab->numattrs;
+ return 0;
+error:
+ if (tmpattrval)
+ jas_iccattrval_destroy(tmpattrval);
+ return -1;
+}
+
+static int jas_iccattrtab_replace(jas_iccattrtab_t *attrtab, int i,
+ jas_iccuint32_t name, jas_iccattrval_t *val)
+{
+ jas_iccattrval_t *newval;
+ jas_iccattr_t *attr;
+ if (!(newval = jas_iccattrval_clone(val)))
+ goto error;
+ attr = &attrtab->attrs[i];
+ jas_iccattrval_destroy(attr->val);
+ attr->name = name;
+ attr->val = newval;
+ return 0;
+error:
+ return -1;
+}
+
+static void jas_iccattrtab_delete(jas_iccattrtab_t *attrtab, int i)
+{
+ int n;
+ jas_iccattrval_destroy(attrtab->attrs[i].val);
+ if ((n = attrtab->numattrs - i - 1) > 0)
+ memmove(&attrtab->attrs[i], &attrtab->attrs[i + 1],
+ n * sizeof(jas_iccattr_t));
+ --attrtab->numattrs;
+}
+
+static int jas_iccattrtab_get(jas_iccattrtab_t *attrtab, int i,
+ jas_iccattrname_t *name, jas_iccattrval_t **val)
+{
+ jas_iccattr_t *attr;
+ if (i < 0 || i >= attrtab->numattrs)
+ goto error;
+ attr = &attrtab->attrs[i];
+ *name = attr->name;
+ if (!(*val = jas_iccattrval_clone(attr->val)))
+ goto error;
+ return 0;
+error:
+ return -1;
+}
+
+static int jas_iccattrtab_lookup(jas_iccattrtab_t *attrtab,
+ jas_iccuint32_t name)
+{
+ int i;
+ jas_iccattr_t *attr;
+ for (i = 0; i < attrtab->numattrs; ++i) {
+ attr = &attrtab->attrs[i];
+ if (attr->name == name)
+ return i;
+ }
+ return -1;
+}
+
+/******************************************************************************\
+* attribute value class
+\******************************************************************************/
+
+jas_iccattrval_t *jas_iccattrval_create(jas_iccuint32_t type)
+{
+ jas_iccattrval_t *attrval;
+ jas_iccattrvalinfo_t *info;
+
+ if (!(info = jas_iccattrvalinfo_lookup(type)))
+ goto error;
+ if (!(attrval = jas_iccattrval_create0()))
+ goto error;
+ attrval->ops = &info->ops;
+ attrval->type = type;
+ ++attrval->refcnt;
+ memset(&attrval->data, 0, sizeof(attrval->data));
+ return attrval;
+error:
+ return 0;
+}
+
+jas_iccattrval_t *jas_iccattrval_clone(jas_iccattrval_t *attrval)
+{
+ ++attrval->refcnt;
+ return attrval;
+}
+
+void jas_iccattrval_destroy(jas_iccattrval_t *attrval)
+{
+#if 0
+jas_eprintf("refcnt=%d\n", attrval->refcnt);
+#endif
+ if (--attrval->refcnt <= 0) {
+ if (attrval->ops->destroy)
+ (*attrval->ops->destroy)(attrval);
+ jas_free(attrval);
+ }
+}
+
+void jas_iccattrval_dump(jas_iccattrval_t *attrval, FILE *out)
+{
+ char buf[8];
+ jas_iccsigtostr(attrval->type, buf);
+ fprintf(out, "refcnt = %d; type = 0x%08x %s\n", attrval->refcnt,
+ attrval->type, jas_iccsigtostr(attrval->type, &buf[0]));
+ if (attrval->ops->dump) {
+ (*attrval->ops->dump)(attrval, out);
+ }
+}
+
+int jas_iccattrval_allowmodify(jas_iccattrval_t **attrvalx)
+{
+ jas_iccattrval_t *newattrval;
+ jas_iccattrval_t *attrval = *attrvalx;
+ newattrval = 0;
+ if (attrval->refcnt > 1) {
+ if (!(newattrval = jas_iccattrval_create0()))
+ goto error;
+ newattrval->ops = attrval->ops;
+ newattrval->type = attrval->type;
+ ++newattrval->refcnt;
+ if (newattrval->ops->copy) {
+ if ((*newattrval->ops->copy)(newattrval, attrval))
+ goto error;
+ } else {
+ memcpy(&newattrval->data, &attrval->data,
+ sizeof(newattrval->data));
+ }
+ *attrvalx = newattrval;
+ }
+ return 0;
+error:
+ if (newattrval) {
+ jas_free(newattrval);
+ }
+ return -1;
+}
+
+static jas_iccattrval_t *jas_iccattrval_create0()
+{
+ jas_iccattrval_t *attrval;
+ if (!(attrval = jas_malloc(sizeof(jas_iccattrval_t))))
+ return 0;
+ memset(attrval, 0, sizeof(jas_iccattrval_t));
+ attrval->refcnt = 0;
+ attrval->ops = 0;
+ attrval->type = 0;
+ return attrval;
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static int jas_iccxyz_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+ int len)
+{
+ if (len != 4 * 3) abort();
+ return jas_iccgetxyz(in, &attrval->data.xyz);
+}
+
+static int jas_iccxyz_output(jas_iccattrval_t *attrval, jas_stream_t *out)
+{
+ jas_iccxyz_t *xyz = &attrval->data.xyz;
+ if (jas_iccputuint32(out, xyz->x) ||
+ jas_iccputuint32(out, xyz->y) ||
+ jas_iccputuint32(out, xyz->z))
+ return -1;
+ return 0;
+}
+
+static int jas_iccxyz_getsize(jas_iccattrval_t *attrval)
+{
+ /* Avoid compiler warnings about unused parameters. */
+ attrval = 0;
+
+ return 12;
+}
+
+static void jas_iccxyz_dump(jas_iccattrval_t *attrval, FILE *out)
+{
+ jas_iccxyz_t *xyz = &attrval->data.xyz;
+ fprintf(out, "(%f, %f, %f)\n", xyz->x / 65536.0, xyz->y / 65536.0, xyz->z / 65536.0);
+}
+
+/******************************************************************************\
+* attribute table class
+\******************************************************************************/
+
+static void jas_icccurv_destroy(jas_iccattrval_t *attrval)
+{
+ jas_icccurv_t *curv = &attrval->data.curv;
+ if (curv->ents)
+ jas_free(curv->ents);
+}
+
+static int jas_icccurv_copy(jas_iccattrval_t *attrval,
+ jas_iccattrval_t *othattrval)
+{
+ /* Avoid compiler warnings about unused parameters. */
+ attrval = 0;
+ othattrval = 0;
+
+ /* Not yet implemented. */
+ abort();
+ return -1;
+}
+
+static int jas_icccurv_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+ int cnt)
+{
+ jas_icccurv_t *curv = &attrval->data.curv;
+ unsigned int i;
+
+ curv->numents = 0;
+ curv->ents = 0;
+
+ if (jas_iccgetuint32(in, &curv->numents))
+ goto error;
+ if (!(curv->ents = jas_malloc(curv->numents * sizeof(jas_iccuint16_t))))
+ goto error;
+ for (i = 0; i < curv->numents; ++i) {
+ if (jas_iccgetuint16(in, &curv->ents[i]))
+ goto error;
+ }
+
+ if (JAS_CAST(int, 4 + 2 * curv->numents) != cnt)
+ goto error;
+ return 0;
+
+error:
+ jas_icccurv_destroy(attrval);
+ return -1;
+}
+
+static int jas_icccurv_getsize(jas_iccattrval_t *attrval)
+{
+ jas_icccurv_t *curv = &attrval->data.curv;
+ return 4 + 2 * curv->numents;
+}
+
+static int jas_icccurv_output(jas_iccattrval_t *attrval, jas_stream_t *out)
+{
+ jas_icccurv_t *curv = &attrval->data.curv;
+ unsigned int i;
+
+ if (jas_iccputuint32(out, curv->numents))
+ goto error;
+ for (i = 0; i < curv->numents; ++i) {
+ if (jas_iccputuint16(out, curv->ents[i]))
+ goto error;
+ }
+ return 0;
+error:
+ return -1;
+}
+
+static void jas_icccurv_dump(jas_iccattrval_t *attrval, FILE *out)
+{
+ int i;
+ jas_icccurv_t *curv = &attrval->data.curv;
+ fprintf(out, "number of entires = %d\n", curv->numents);
+ if (curv->numents == 1) {
+ fprintf(out, "gamma = %f\n", curv->ents[0] / 256.0);
+ } else {
+ for (i = 0; i < JAS_CAST(int, curv->numents); ++i) {
+ if (i < 3 || i >= JAS_CAST(int, curv->numents) - 3) {
+ fprintf(out, "entry[%d] = %f\n", i, curv->ents[i] / 65535.0);
+ }
+ }
+ }
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void jas_icctxtdesc_destroy(jas_iccattrval_t *attrval)
+{
+ jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
+ if (txtdesc->ascdata)
+ jas_free(txtdesc->ascdata);
+ if (txtdesc->ucdata)
+ jas_free(txtdesc->ucdata);
+}
+
+static int jas_icctxtdesc_copy(jas_iccattrval_t *attrval,
+ jas_iccattrval_t *othattrval)
+{
+ jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
+
+ /* Avoid compiler warnings about unused parameters. */
+ attrval = 0;
+ othattrval = 0;
+ txtdesc = 0;
+
+ /* Not yet implemented. */
+ abort();
+ return -1;
+}
+
+static int jas_icctxtdesc_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+ int cnt)
+{
+ int n;
+ int c;
+ jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
+ txtdesc->ascdata = 0;
+ txtdesc->ucdata = 0;
+ if (jas_iccgetuint32(in, &txtdesc->asclen))
+ goto error;
+ if (!(txtdesc->ascdata = jas_malloc(txtdesc->asclen)))
+ goto error;
+ if (jas_stream_read(in, txtdesc->ascdata, txtdesc->asclen) !=
+ JAS_CAST(int, txtdesc->asclen))
+ goto error;
+ txtdesc->ascdata[txtdesc->asclen - 1] = '\0';
+ if (jas_iccgetuint32(in, &txtdesc->uclangcode) ||
+ jas_iccgetuint32(in, &txtdesc->uclen))
+ goto error;
+ if (!(txtdesc->ucdata = jas_malloc(txtdesc->uclen * 2)))
+ goto error;
+ if (jas_stream_read(in, txtdesc->ucdata, txtdesc->uclen * 2) !=
+ JAS_CAST(int, txtdesc->uclen * 2))
+ goto error;
+ if (jas_iccgetuint16(in, &txtdesc->sccode))
+ goto error;
+ if ((c = jas_stream_getc(in)) == EOF)
+ goto error;
+ txtdesc->maclen = c;
+ if (jas_stream_read(in, txtdesc->macdata, 67) != 67)
+ goto error;
+ txtdesc->asclen = strlen(txtdesc->ascdata) + 1;
+#define WORKAROUND_BAD_PROFILES
+#ifdef WORKAROUND_BAD_PROFILES
+ n = txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67;
+ if (n > cnt) {
+ return -1;
+ }
+ if (n < cnt) {
+ if (jas_stream_gobble(in, cnt - n) != cnt - n)
+ goto error;
+ }
+#else
+ if (txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67 != cnt)
+ return -1;
+#endif
+ return 0;
+error:
+ jas_icctxtdesc_destroy(attrval);
+ return -1;
+}
+
+static int jas_icctxtdesc_getsize(jas_iccattrval_t *attrval)
+{
+ jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
+ return strlen(txtdesc->ascdata) + 1 + txtdesc->uclen * 2 + 15 + 67;
+}
+
+static int jas_icctxtdesc_output(jas_iccattrval_t *attrval, jas_stream_t *out)
+{
+ jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
+ if (jas_iccputuint32(out, txtdesc->asclen) ||
+ jas_stream_puts(out, txtdesc->ascdata) ||
+ jas_stream_putc(out, 0) == EOF ||
+ jas_iccputuint32(out, txtdesc->uclangcode) ||
+ jas_iccputuint32(out, txtdesc->uclen) ||
+ jas_stream_write(out, txtdesc->ucdata, txtdesc->uclen * 2) != JAS_CAST(int, txtdesc->uclen * 2) ||
+ jas_iccputuint16(out, txtdesc->sccode) ||
+ jas_stream_putc(out, txtdesc->maclen) == EOF)
+ goto error;
+ if (txtdesc->maclen > 0) {
+ if (jas_stream_write(out, txtdesc->macdata, 67) != 67)
+ goto error;
+ } else {
+ if (jas_stream_pad(out, 67, 0) != 67)
+ goto error;
+ }
+ return 0;
+error:
+ return -1;
+}
+
+static void jas_icctxtdesc_dump(jas_iccattrval_t *attrval, FILE *out)
+{
+ jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
+ fprintf(out, "ascii = \"%s\"\n", txtdesc->ascdata);
+ fprintf(out, "uclangcode = %d; uclen = %d\n", txtdesc->uclangcode,
+ txtdesc->uclen);
+ fprintf(out, "sccode = %d\n", txtdesc->sccode);
+ fprintf(out, "maclen = %d\n", txtdesc->maclen);
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void jas_icctxt_destroy(jas_iccattrval_t *attrval)
+{
+ jas_icctxt_t *txt = &attrval->data.txt;
+ if (txt->string)
+ jas_free(txt->string);
+}
+
+static int jas_icctxt_copy(jas_iccattrval_t *attrval,
+ jas_iccattrval_t *othattrval)
+{
+ jas_icctxt_t *txt = &attrval->data.txt;
+ jas_icctxt_t *othtxt = &othattrval->data.txt;
+ if (!(txt->string = jas_strdup(othtxt->string)))
+ return -1;
+ return 0;
+}
+
+static int jas_icctxt_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+ int cnt)
+{
+ jas_icctxt_t *txt = &attrval->data.txt;
+ txt->string = 0;
+ if (!(txt->string = jas_malloc(cnt)))
+ goto error;
+ if (jas_stream_read(in, txt->string, cnt) != cnt)
+ goto error;
+ txt->string[cnt - 1] = '\0';
+ if (JAS_CAST(int, strlen(txt->string)) + 1 != cnt)
+ goto error;
+ return 0;
+error:
+ if (txt->string)
+ jas_free(txt->string);
+ return -1;
+}
+
+static int jas_icctxt_getsize(jas_iccattrval_t *attrval)
+{
+ jas_icctxt_t *txt = &attrval->data.txt;
+ return strlen(txt->string) + 1;
+}
+
+static int jas_icctxt_output(jas_iccattrval_t *attrval, jas_stream_t *out)
+{
+ jas_icctxt_t *txt = &attrval->data.txt;
+ if (jas_stream_puts(out, txt->string) ||
+ jas_stream_putc(out, 0) == EOF)
+ return -1;
+ return 0;
+}
+
+static void jas_icctxt_dump(jas_iccattrval_t *attrval, FILE *out)
+{
+ jas_icctxt_t *txt = &attrval->data.txt;
+ fprintf(out, "string = \"%s\"\n", txt->string);
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void jas_icclut8_destroy(jas_iccattrval_t *attrval)
+{
+ jas_icclut8_t *lut8 = &attrval->data.lut8;
+ if (lut8->clut)
+ jas_free(lut8->clut);
+ if (lut8->intabs)
+ jas_free(lut8->intabs);
+ if (lut8->intabsbuf)
+ jas_free(lut8->intabsbuf);
+ if (lut8->outtabs)
+ jas_free(lut8->outtabs);
+ if (lut8->outtabsbuf)
+ jas_free(lut8->outtabsbuf);
+}
+
+static int jas_icclut8_copy(jas_iccattrval_t *attrval,
+ jas_iccattrval_t *othattrval)
+{
+ jas_icclut8_t *lut8 = &attrval->data.lut8;
+ /* Avoid compiler warnings about unused parameters. */
+ attrval = 0;
+ othattrval = 0;
+ lut8 = 0;
+ abort();
+ return -1;
+}
+
+static int jas_icclut8_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+ int cnt)
+{
+ int i;
+ int j;
+ int clutsize;
+ jas_icclut8_t *lut8 = &attrval->data.lut8;
+ lut8->clut = 0;
+ lut8->intabs = 0;
+ lut8->intabsbuf = 0;
+ lut8->outtabs = 0;
+ lut8->outtabsbuf = 0;
+ if (jas_iccgetuint8(in, &lut8->numinchans) ||
+ jas_iccgetuint8(in, &lut8->numoutchans) ||
+ jas_iccgetuint8(in, &lut8->clutlen) ||
+ jas_stream_getc(in) == EOF)
+ goto error;
+ for (i = 0; i < 3; ++i) {
+ for (j = 0; j < 3; ++j) {
+ if (jas_iccgetsint32(in, &lut8->e[i][j]))
+ goto error;
+ }
+ }
+ if (jas_iccgetuint16(in, &lut8->numintabents) ||
+ jas_iccgetuint16(in, &lut8->numouttabents))
+ goto error;
+ clutsize = jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans;
+ if (!(lut8->clut = jas_malloc(clutsize * sizeof(jas_iccuint8_t))) ||
+ !(lut8->intabsbuf = jas_malloc(lut8->numinchans *
+ lut8->numintabents * sizeof(jas_iccuint8_t))) ||
+ !(lut8->intabs = jas_malloc(lut8->numinchans *
+ sizeof(jas_iccuint8_t *))))
+ goto error;
+ for (i = 0; i < lut8->numinchans; ++i)
+ lut8->intabs[i] = &lut8->intabsbuf[i * lut8->numintabents];
+ if (!(lut8->outtabsbuf = jas_malloc(lut8->numoutchans *
+ lut8->numouttabents * sizeof(jas_iccuint8_t))) ||
+ !(lut8->outtabs = jas_malloc(lut8->numoutchans *
+ sizeof(jas_iccuint8_t *))))
+ goto error;
+ for (i = 0; i < lut8->numoutchans; ++i)
+ lut8->outtabs[i] = &lut8->outtabsbuf[i * lut8->numouttabents];
+ for (i = 0; i < lut8->numinchans; ++i) {
+ for (j = 0; j < JAS_CAST(int, lut8->numintabents); ++j) {
+ if (jas_iccgetuint8(in, &lut8->intabs[i][j]))
+ goto error;
+ }
+ }
+ for (i = 0; i < lut8->numoutchans; ++i) {
+ for (j = 0; j < JAS_CAST(int, lut8->numouttabents); ++j) {
+ if (jas_iccgetuint8(in, &lut8->outtabs[i][j]))
+ goto error;
+ }
+ }
+ for (i = 0; i < clutsize; ++i) {
+ if (jas_iccgetuint8(in, &lut8->clut[i]))
+ goto error;
+ }
+ if (JAS_CAST(int, 44 + lut8->numinchans * lut8->numintabents +
+ lut8->numoutchans * lut8->numouttabents +
+ jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans) !=
+ cnt)
+ goto error;
+ return 0;
+error:
+ jas_icclut8_destroy(attrval);
+ return -1;
+}
+
+static int jas_icclut8_getsize(jas_iccattrval_t *attrval)
+{
+ jas_icclut8_t *lut8 = &attrval->data.lut8;
+ return 44 + lut8->numinchans * lut8->numintabents +
+ lut8->numoutchans * lut8->numouttabents +
+ jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans;
+}
+
+static int jas_icclut8_output(jas_iccattrval_t *attrval, jas_stream_t *out)
+{
+ jas_icclut8_t *lut8 = &attrval->data.lut8;
+ int i;
+ int j;
+ int n;
+ lut8->clut = 0;
+ lut8->intabs = 0;
+ lut8->intabsbuf = 0;
+ lut8->outtabs = 0;
+ lut8->outtabsbuf = 0;
+ if (jas_stream_putc(out, lut8->numinchans) == EOF ||
+ jas_stream_putc(out, lut8->numoutchans) == EOF ||
+ jas_stream_putc(out, lut8->clutlen) == EOF ||
+ jas_stream_putc(out, 0) == EOF)
+ goto error;
+ for (i = 0; i < 3; ++i) {
+ for (j = 0; j < 3; ++j) {
+ if (jas_iccputsint32(out, lut8->e[i][j]))
+ goto error;
+ }
+ }
+ if (jas_iccputuint16(out, lut8->numintabents) ||
+ jas_iccputuint16(out, lut8->numouttabents))
+ goto error;
+ n = lut8->numinchans * lut8->numintabents;
+ for (i = 0; i < n; ++i) {
+ if (jas_iccputuint8(out, lut8->intabsbuf[i]))
+ goto error;
+ }
+ n = lut8->numoutchans * lut8->numouttabents;
+ for (i = 0; i < n; ++i) {
+ if (jas_iccputuint8(out, lut8->outtabsbuf[i]))
+ goto error;
+ }
+ n = jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans;
+ for (i = 0; i < n; ++i) {
+ if (jas_iccputuint8(out, lut8->clut[i]))
+ goto error;
+ }
+ return 0;
+error:
+ return -1;
+}
+
+static void jas_icclut8_dump(jas_iccattrval_t *attrval, FILE *out)
+{
+ jas_icclut8_t *lut8 = &attrval->data.lut8;
+ int i;
+ int j;
+ fprintf(out, "numinchans=%d, numoutchans=%d, clutlen=%d\n",
+ lut8->numinchans, lut8->numoutchans, lut8->clutlen);
+ for (i = 0; i < 3; ++i) {
+ for (j = 0; j < 3; ++j) {
+ fprintf(out, "e[%d][%d]=%f ", i, j, lut8->e[i][j] / 65536.0);
+ }
+ fprintf(out, "\n");
+ }
+ fprintf(out, "numintabents=%d, numouttabents=%d\n",
+ lut8->numintabents, lut8->numouttabents);
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static void jas_icclut16_destroy(jas_iccattrval_t *attrval)
+{
+ jas_icclut16_t *lut16 = &attrval->data.lut16;
+ if (lut16->clut)
+ jas_free(lut16->clut);
+ if (lut16->intabs)
+ jas_free(lut16->intabs);
+ if (lut16->intabsbuf)
+ jas_free(lut16->intabsbuf);
+ if (lut16->outtabs)
+ jas_free(lut16->outtabs);
+ if (lut16->outtabsbuf)
+ jas_free(lut16->outtabsbuf);
+}
+
+static int jas_icclut16_copy(jas_iccattrval_t *attrval,
+ jas_iccattrval_t *othattrval)
+{
+ /* Avoid compiler warnings about unused parameters. */
+ attrval = 0;
+ othattrval = 0;
+ /* Not yet implemented. */
+ abort();
+ return -1;
+}
+
+static int jas_icclut16_input(jas_iccattrval_t *attrval, jas_stream_t *in,
+ int cnt)
+{
+ int i;
+ int j;
+ int clutsize;
+ jas_icclut16_t *lut16 = &attrval->data.lut16;
+ lut16->clut = 0;
+ lut16->intabs = 0;
+ lut16->intabsbuf = 0;
+ lut16->outtabs = 0;
+ lut16->outtabsbuf = 0;
+ if (jas_iccgetuint8(in, &lut16->numinchans) ||
+ jas_iccgetuint8(in, &lut16->numoutchans) ||
+ jas_iccgetuint8(in, &lut16->clutlen) ||
+ jas_stream_getc(in) == EOF)
+ goto error;
+ for (i = 0; i < 3; ++i) {
+ for (j = 0; j < 3; ++j) {
+ if (jas_iccgetsint32(in, &lut16->e[i][j]))
+ goto error;
+ }
+ }
+ if (jas_iccgetuint16(in, &lut16->numintabents) ||
+ jas_iccgetuint16(in, &lut16->numouttabents))
+ goto error;
+ clutsize = jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans;
+ if (!(lut16->clut = jas_malloc(clutsize * sizeof(jas_iccuint16_t))) ||
+ !(lut16->intabsbuf = jas_malloc(lut16->numinchans *
+ lut16->numintabents * sizeof(jas_iccuint16_t))) ||
+ !(lut16->intabs = jas_malloc(lut16->numinchans *
+ sizeof(jas_iccuint16_t *))))
+ goto error;
+ for (i = 0; i < lut16->numinchans; ++i)
+ lut16->intabs[i] = &lut16->intabsbuf[i * lut16->numintabents];
+ if (!(lut16->outtabsbuf = jas_malloc(lut16->numoutchans *
+ lut16->numouttabents * sizeof(jas_iccuint16_t))) ||
+ !(lut16->outtabs = jas_malloc(lut16->numoutchans *
+ sizeof(jas_iccuint16_t *))))
+ goto error;
+ for (i = 0; i < lut16->numoutchans; ++i)
+ lut16->outtabs[i] = &lut16->outtabsbuf[i * lut16->numouttabents];
+ for (i = 0; i < lut16->numinchans; ++i) {
+ for (j = 0; j < JAS_CAST(int, lut16->numintabents); ++j) {
+ if (jas_iccgetuint16(in, &lut16->intabs[i][j]))
+ goto error;
+ }
+ }
+ for (i = 0; i < lut16->numoutchans; ++i) {
+ for (j = 0; j < JAS_CAST(int, lut16->numouttabents); ++j) {
+ if (jas_iccgetuint16(in, &lut16->outtabs[i][j]))
+ goto error;
+ }
+ }
+ for (i = 0; i < clutsize; ++i) {
+ if (jas_iccgetuint16(in, &lut16->clut[i]))
+ goto error;
+ }
+ if (JAS_CAST(int, 44 + 2 * (lut16->numinchans * lut16->numintabents +
+ lut16->numoutchans * lut16->numouttabents +
+ jas_iccpowi(lut16->clutlen, lut16->numinchans) *
+ lut16->numoutchans)) != cnt)
+ goto error;
+ return 0;
+error:
+ jas_icclut16_destroy(attrval);
+ return -1;
+}
+
+static int jas_icclut16_getsize(jas_iccattrval_t *attrval)
+{
+ jas_icclut16_t *lut16 = &attrval->data.lut16;
+ return 44 + 2 * (lut16->numinchans * lut16->numintabents +
+ lut16->numoutchans * lut16->numouttabents +
+ jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans);
+}
+
+static int jas_icclut16_output(jas_iccattrval_t *attrval, jas_stream_t *out)
+{
+ jas_icclut16_t *lut16 = &attrval->data.lut16;
+ int i;
+ int j;
+ int n;
+ if (jas_stream_putc(out, lut16->numinchans) == EOF ||
+ jas_stream_putc(out, lut16->numoutchans) == EOF ||
+ jas_stream_putc(out, lut16->clutlen) == EOF ||
+ jas_stream_putc(out, 0) == EOF)
+ goto error;
+ for (i = 0; i < 3; ++i) {
+ for (j = 0; j < 3; ++j) {
+ if (jas_iccputsint32(out, lut16->e[i][j]))
+ goto error;
+ }
+ }
+ if (jas_iccputuint16(out, lut16->numintabents) ||
+ jas_iccputuint16(out, lut16->numouttabents))
+ goto error;
+ n = lut16->numinchans * lut16->numintabents;
+ for (i = 0; i < n; ++i) {
+ if (jas_iccputuint16(out, lut16->intabsbuf[i]))
+ goto error;
+ }
+ n = lut16->numoutchans * lut16->numouttabents;
+ for (i = 0; i < n; ++i) {
+ if (jas_iccputuint16(out, lut16->outtabsbuf[i]))
+ goto error;
+ }
+ n = jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans;
+ for (i = 0; i < n; ++i) {
+ if (jas_iccputuint16(out, lut16->clut[i]))
+ goto error;
+ }
+ return 0;
+error:
+ return -1;
+}
+
+static void jas_icclut16_dump(jas_iccattrval_t *attrval, FILE *out)
+{
+ jas_icclut16_t *lut16 = &attrval->data.lut16;
+ int i;
+ int j;
+ fprintf(out, "numinchans=%d, numoutchans=%d, clutlen=%d\n",
+ lut16->numinchans, lut16->numoutchans, lut16->clutlen);
+ for (i = 0; i < 3; ++i) {
+ for (j = 0; j < 3; ++j) {
+ fprintf(out, "e[%d][%d]=%f ", i, j, lut16->e[i][j] / 65536.0);
+ }
+ fprintf(out, "\n");
+ }
+ fprintf(out, "numintabents=%d, numouttabents=%d\n",
+ lut16->numintabents, lut16->numouttabents);
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static int jas_iccgetuint(jas_stream_t *in, int n, ulonglong *val)
+{
+ int i;
+ int c;
+ ulonglong v;
+ v = 0;
+ for (i = n; i > 0; --i) {
+ if ((c = jas_stream_getc(in)) == EOF)
+ return -1;
+ v = (v << 8) | c;
+ }
+ *val = v;
+ return 0;
+}
+
+static int jas_iccgetuint8(jas_stream_t *in, jas_iccuint8_t *val)
+{
+ int c;
+ if ((c = jas_stream_getc(in)) == EOF)
+ return -1;
+ *val = c;
+ return 0;
+}
+
+static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val)
+{
+ ulonglong tmp;
+ if (jas_iccgetuint(in, 2, &tmp))
+ return -1;
+ *val = tmp;
+ return 0;
+}
+
+static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val)
+{
+ ulonglong tmp;
+ if (jas_iccgetuint(in, 4, &tmp))
+ return -1;
+ *val = (tmp & 0x80000000) ? (-JAS_CAST(longlong, (((~tmp) &
+ 0x7fffffff) + 1))) : JAS_CAST(longlong, tmp);
+ return 0;
+}
+
+static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val)
+{
+ ulonglong tmp;
+ if (jas_iccgetuint(in, 4, &tmp))
+ return -1;
+ *val = tmp;
+ return 0;
+}
+
+static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val)
+{
+ ulonglong tmp;
+ if (jas_iccgetuint(in, 8, &tmp))
+ return -1;
+ *val = tmp;
+ return 0;
+}
+
+static int jas_iccputuint(jas_stream_t *out, int n, ulonglong val)
+{
+ int i;
+ int c;
+ for (i = n; i > 0; --i) {
+ c = (val >> (8 * (i - 1))) & 0xff;
+ if (jas_stream_putc(out, c) == EOF)
+ return -1;
+ }
+ return 0;
+}
+
+static int jas_iccputsint(jas_stream_t *out, int n, longlong val)
+{
+ ulonglong tmp;
+ tmp = (val < 0) ? (abort(), 0) : val;
+ return jas_iccputuint(out, n, tmp);
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static char *jas_iccsigtostr(int sig, char *buf)
+{
+ int n;
+ int c;
+ char *bufptr;
+ bufptr = buf;
+ for (n = 4; n > 0; --n) {
+ c = (sig >> 24) & 0xff;
+ if (isalpha(c) || isdigit(c)) {
+ *bufptr++ = c;
+ }
+ sig <<= 8;
+ }
+ *bufptr = '\0';
+ return buf;
+}
+
+static long jas_iccpadtomult(long x, long y)
+{
+ return ((x + y - 1) / y) * y;
+}
+
+static long jas_iccpowi(int x, int n)
+{
+ long y;
+ y = 1;
+ while (--n >= 0)
+ y *= x;
+ return y;
+}
+
+
+jas_iccprof_t *jas_iccprof_createfrombuf(uchar *buf, int len)
+{
+ jas_stream_t *in;
+ jas_iccprof_t *prof;
+ if (!(in = jas_stream_memopen(JAS_CAST(char *, buf), len)))
+ goto error;
+ if (!(prof = jas_iccprof_load(in)))
+ goto error;
+ jas_stream_close(in);
+ return prof;
+error:
+ return 0;
+}
+
+jas_iccprof_t *jas_iccprof_createfromclrspc(int clrspc)
+{
+ jas_iccprof_t *prof;
+ switch (clrspc) {
+ case JAS_CLRSPC_SRGB:
+ prof = jas_iccprof_createfrombuf(jas_iccprofdata_srgb,
+ jas_iccprofdata_srgblen);
+ break;
+ case JAS_CLRSPC_SGRAY:
+ prof = jas_iccprof_createfrombuf(jas_iccprofdata_sgray,
+ jas_iccprofdata_sgraylen);
+ break;
+ default:
+ prof = 0;
+ break;
+ }
+ return prof;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/base/jas_iccdata.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_iccdata.c
new file mode 100644
index 0000000..bf68bf0
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_iccdata.c
@@ -0,0 +1,517 @@
+/*
+ * Copyright (c) 2002-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#include <jasper/jas_config.h>
+#include <jasper/jas_types.h>
+
+uchar jas_iccprofdata_srgb[] =
+{
+ 0x00, 0x00, 0x0c, 0x48, 0x4c, 0x69, 0x6e, 0x6f,
+ 0x02, 0x10, 0x00, 0x00, 0x6d, 0x6e, 0x74, 0x72,
+ 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20,
+ 0x07, 0xce, 0x00, 0x02, 0x00, 0x09, 0x00, 0x06,
+ 0x00, 0x31, 0x00, 0x00, 0x61, 0x63, 0x73, 0x70,
+ 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00,
+ 0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6,
+ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d,
+ 0x48, 0x50, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x11, 0x63, 0x70, 0x72, 0x74,
+ 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x33,
+ 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x84,
+ 0x00, 0x00, 0x00, 0x6c, 0x77, 0x74, 0x70, 0x74,
+ 0x00, 0x00, 0x01, 0xf0, 0x00, 0x00, 0x00, 0x14,
+ 0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x02, 0x04,
+ 0x00, 0x00, 0x00, 0x14, 0x72, 0x58, 0x59, 0x5a,
+ 0x00, 0x00, 0x02, 0x18, 0x00, 0x00, 0x00, 0x14,
+ 0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x02, 0x2c,
+ 0x00, 0x00, 0x00, 0x14, 0x62, 0x58, 0x59, 0x5a,
+ 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x00, 0x14,
+ 0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54,
+ 0x00, 0x00, 0x00, 0x70, 0x64, 0x6d, 0x64, 0x64,
+ 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88,
+ 0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x4c,
+ 0x00, 0x00, 0x00, 0x86, 0x76, 0x69, 0x65, 0x77,
+ 0x00, 0x00, 0x03, 0xd4, 0x00, 0x00, 0x00, 0x24,
+ 0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xf8,
+ 0x00, 0x00, 0x00, 0x14, 0x6d, 0x65, 0x61, 0x73,
+ 0x00, 0x00, 0x04, 0x0c, 0x00, 0x00, 0x00, 0x24,
+ 0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x04, 0x30,
+ 0x00, 0x00, 0x00, 0x0c, 0x72, 0x54, 0x52, 0x43,
+ 0x00, 0x00, 0x04, 0x3c, 0x00, 0x00, 0x08, 0x0c,
+ 0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x3c,
+ 0x00, 0x00, 0x08, 0x0c, 0x62, 0x54, 0x52, 0x43,
+ 0x00, 0x00, 0x04, 0x3c, 0x00, 0x00, 0x08, 0x0c,
+ 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00,
+ 0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68,
+ 0x74, 0x20, 0x28, 0x63, 0x29, 0x20, 0x31, 0x39,
+ 0x39, 0x38, 0x20, 0x48, 0x65, 0x77, 0x6c, 0x65,
+ 0x74, 0x74, 0x2d, 0x50, 0x61, 0x63, 0x6b, 0x61,
+ 0x72, 0x64, 0x20, 0x43, 0x6f, 0x6d, 0x70, 0x61,
+ 0x6e, 0x79, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12,
+ 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43,
+ 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e,
+ 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x12, 0x73, 0x52, 0x47,
+ 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39,
+ 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00,
+ 0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x6f, 0xa2, 0x00, 0x00, 0x38, 0xf5,
+ 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x99,
+ 0x00, 0x00, 0xb7, 0x85, 0x00, 0x00, 0x18, 0xda,
+ 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x24, 0xa0, 0x00, 0x00, 0x0f, 0x84,
+ 0x00, 0x00, 0xb6, 0xcf, 0x64, 0x65, 0x73, 0x63,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16,
+ 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70,
+ 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69,
+ 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74,
+ 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e,
+ 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e,
+ 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36,
+ 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65,
+ 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47,
+ 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72,
+ 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d,
+ 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39,
+ 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44,
+ 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52,
+ 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75,
+ 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20,
+ 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c,
+ 0x52, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63,
+ 0x65, 0x20, 0x56, 0x69, 0x65, 0x77, 0x69, 0x6e,
+ 0x67, 0x20, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74,
+ 0x69, 0x6f, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x49,
+ 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d,
+ 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x52,
+ 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65,
+ 0x20, 0x56, 0x69, 0x65, 0x77, 0x69, 0x6e, 0x67,
+ 0x20, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69,
+ 0x6f, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x49, 0x45,
+ 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32,
+ 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x76, 0x69, 0x65, 0x77,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0xfe,
+ 0x00, 0x14, 0x5f, 0x2e, 0x00, 0x10, 0xcf, 0x14,
+ 0x00, 0x03, 0xed, 0xcc, 0x00, 0x04, 0x13, 0x0b,
+ 0x00, 0x03, 0x5c, 0x9e, 0x00, 0x00, 0x00, 0x01,
+ 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x4c, 0x09, 0x56, 0x00, 0x50, 0x00, 0x00,
+ 0x00, 0x57, 0x1f, 0xe7, 0x6d, 0x65, 0x61, 0x73,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02,
+ 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00,
+ 0x43, 0x52, 0x54, 0x20, 0x63, 0x75, 0x72, 0x76,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
+ 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f,
+ 0x00, 0x14, 0x00, 0x19, 0x00, 0x1e, 0x00, 0x23,
+ 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37,
+ 0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a,
+ 0x00, 0x4f, 0x00, 0x54, 0x00, 0x59, 0x00, 0x5e,
+ 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72,
+ 0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86,
+ 0x00, 0x8b, 0x00, 0x90, 0x00, 0x95, 0x00, 0x9a,
+ 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae,
+ 0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1,
+ 0x00, 0xc6, 0x00, 0xcb, 0x00, 0xd0, 0x00, 0xd5,
+ 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb,
+ 0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01,
+ 0x01, 0x07, 0x01, 0x0d, 0x01, 0x13, 0x01, 0x19,
+ 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32,
+ 0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c,
+ 0x01, 0x52, 0x01, 0x59, 0x01, 0x60, 0x01, 0x67,
+ 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83,
+ 0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1,
+ 0x01, 0xa9, 0x01, 0xb1, 0x01, 0xb9, 0x01, 0xc1,
+ 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1,
+ 0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03,
+ 0x02, 0x0c, 0x02, 0x14, 0x02, 0x1d, 0x02, 0x26,
+ 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b,
+ 0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71,
+ 0x02, 0x7a, 0x02, 0x84, 0x02, 0x8e, 0x02, 0x98,
+ 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1,
+ 0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb,
+ 0x02, 0xf5, 0x03, 0x00, 0x03, 0x0b, 0x03, 0x16,
+ 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43,
+ 0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72,
+ 0x03, 0x7e, 0x03, 0x8a, 0x03, 0x96, 0x03, 0xa2,
+ 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3,
+ 0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06,
+ 0x04, 0x13, 0x04, 0x20, 0x04, 0x2d, 0x04, 0x3b,
+ 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71,
+ 0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8,
+ 0x04, 0xb6, 0x04, 0xc4, 0x04, 0xd3, 0x04, 0xe1,
+ 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c,
+ 0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58,
+ 0x05, 0x67, 0x05, 0x77, 0x05, 0x86, 0x05, 0x96,
+ 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5,
+ 0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16,
+ 0x06, 0x27, 0x06, 0x37, 0x06, 0x48, 0x06, 0x59,
+ 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d,
+ 0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3,
+ 0x06, 0xf5, 0x07, 0x07, 0x07, 0x19, 0x07, 0x2b,
+ 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74,
+ 0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf,
+ 0x07, 0xd2, 0x07, 0xe5, 0x07, 0xf8, 0x08, 0x0b,
+ 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a,
+ 0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa,
+ 0x08, 0xbe, 0x08, 0xd2, 0x08, 0xe7, 0x08, 0xfb,
+ 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f,
+ 0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4,
+ 0x09, 0xba, 0x09, 0xcf, 0x09, 0xe5, 0x09, 0xfb,
+ 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54,
+ 0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae,
+ 0x0a, 0xc5, 0x0a, 0xdc, 0x0a, 0xf3, 0x0b, 0x0b,
+ 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69,
+ 0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8,
+ 0x0b, 0xe1, 0x0b, 0xf9, 0x0c, 0x12, 0x0c, 0x2a,
+ 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e,
+ 0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3,
+ 0x0d, 0x0d, 0x0d, 0x26, 0x0d, 0x40, 0x0d, 0x5a,
+ 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3,
+ 0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e,
+ 0x0e, 0x49, 0x0e, 0x64, 0x0e, 0x7f, 0x0e, 0x9b,
+ 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09,
+ 0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a,
+ 0x0f, 0x96, 0x0f, 0xb3, 0x0f, 0xcf, 0x0f, 0xec,
+ 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61,
+ 0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7,
+ 0x10, 0xf5, 0x11, 0x13, 0x11, 0x31, 0x11, 0x4f,
+ 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9,
+ 0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45,
+ 0x12, 0x64, 0x12, 0x84, 0x12, 0xa3, 0x12, 0xc3,
+ 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43,
+ 0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5,
+ 0x13, 0xe5, 0x14, 0x06, 0x14, 0x27, 0x14, 0x49,
+ 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce,
+ 0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56,
+ 0x15, 0x78, 0x15, 0x9b, 0x15, 0xbd, 0x15, 0xe0,
+ 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c,
+ 0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa,
+ 0x17, 0x1d, 0x17, 0x41, 0x17, 0x65, 0x17, 0x89,
+ 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b,
+ 0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf,
+ 0x18, 0xd5, 0x18, 0xfa, 0x19, 0x20, 0x19, 0x45,
+ 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd,
+ 0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77,
+ 0x1a, 0x9e, 0x1a, 0xc5, 0x1a, 0xec, 0x1b, 0x14,
+ 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2,
+ 0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52,
+ 0x1c, 0x7b, 0x1c, 0xa3, 0x1c, 0xcc, 0x1c, 0xf5,
+ 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99,
+ 0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40,
+ 0x1e, 0x6a, 0x1e, 0x94, 0x1e, 0xbe, 0x1e, 0xe9,
+ 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94,
+ 0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41,
+ 0x20, 0x6c, 0x20, 0x98, 0x20, 0xc4, 0x20, 0xf0,
+ 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1,
+ 0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55,
+ 0x22, 0x82, 0x22, 0xaf, 0x22, 0xdd, 0x23, 0x0a,
+ 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2,
+ 0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c,
+ 0x24, 0xab, 0x24, 0xda, 0x25, 0x09, 0x25, 0x38,
+ 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7,
+ 0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7,
+ 0x26, 0xe8, 0x27, 0x18, 0x27, 0x49, 0x27, 0x7a,
+ 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f,
+ 0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06,
+ 0x29, 0x38, 0x29, 0x6b, 0x29, 0x9d, 0x29, 0xd0,
+ 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b,
+ 0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69,
+ 0x2b, 0x9d, 0x2b, 0xd1, 0x2c, 0x05, 0x2c, 0x39,
+ 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c,
+ 0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1,
+ 0x2e, 0x16, 0x2e, 0x4c, 0x2e, 0x82, 0x2e, 0xb7,
+ 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91,
+ 0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c,
+ 0x30, 0xa4, 0x30, 0xdb, 0x31, 0x12, 0x31, 0x4a,
+ 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a,
+ 0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d,
+ 0x33, 0x46, 0x33, 0x7f, 0x33, 0xb8, 0x33, 0xf1,
+ 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8,
+ 0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2,
+ 0x35, 0xfd, 0x36, 0x37, 0x36, 0x72, 0x36, 0xae,
+ 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c,
+ 0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c,
+ 0x38, 0xc8, 0x39, 0x05, 0x39, 0x42, 0x39, 0x7f,
+ 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74,
+ 0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b,
+ 0x3b, 0xaa, 0x3b, 0xe8, 0x3c, 0x27, 0x3c, 0x65,
+ 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61,
+ 0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60,
+ 0x3e, 0xa0, 0x3e, 0xe0, 0x3f, 0x21, 0x3f, 0x61,
+ 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64,
+ 0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a,
+ 0x41, 0xac, 0x41, 0xee, 0x42, 0x30, 0x42, 0x72,
+ 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d,
+ 0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a,
+ 0x44, 0xce, 0x45, 0x12, 0x45, 0x55, 0x45, 0x9a,
+ 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab,
+ 0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0,
+ 0x48, 0x05, 0x48, 0x4b, 0x48, 0x91, 0x48, 0xd7,
+ 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0,
+ 0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c,
+ 0x4b, 0x53, 0x4b, 0x9a, 0x4b, 0xe2, 0x4c, 0x2a,
+ 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a,
+ 0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e,
+ 0x4e, 0xb7, 0x4f, 0x00, 0x4f, 0x49, 0x4f, 0x93,
+ 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb,
+ 0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6,
+ 0x52, 0x31, 0x52, 0x7c, 0x52, 0xc7, 0x53, 0x13,
+ 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42,
+ 0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75,
+ 0x55, 0xc2, 0x56, 0x0f, 0x56, 0x5c, 0x56, 0xa9,
+ 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0,
+ 0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a,
+ 0x59, 0x69, 0x59, 0xb8, 0x5a, 0x07, 0x5a, 0x56,
+ 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95,
+ 0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6,
+ 0x5d, 0x27, 0x5d, 0x78, 0x5d, 0xc9, 0x5e, 0x1a,
+ 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61,
+ 0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa,
+ 0x60, 0xfc, 0x61, 0x4f, 0x61, 0xa2, 0x61, 0xf5,
+ 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43,
+ 0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94,
+ 0x64, 0xe9, 0x65, 0x3d, 0x65, 0x92, 0x65, 0xe7,
+ 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d,
+ 0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96,
+ 0x68, 0xec, 0x69, 0x43, 0x69, 0x9a, 0x69, 0xf1,
+ 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f,
+ 0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf,
+ 0x6d, 0x08, 0x6d, 0x60, 0x6d, 0xb9, 0x6e, 0x12,
+ 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78,
+ 0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0,
+ 0x71, 0x3a, 0x71, 0x95, 0x71, 0xf0, 0x72, 0x4b,
+ 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8,
+ 0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28,
+ 0x75, 0x85, 0x75, 0xe1, 0x76, 0x3e, 0x76, 0x9b,
+ 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11,
+ 0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89,
+ 0x79, 0xe7, 0x7a, 0x46, 0x7a, 0xa5, 0x7b, 0x04,
+ 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81,
+ 0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01,
+ 0x7e, 0x62, 0x7e, 0xc2, 0x7f, 0x23, 0x7f, 0x84,
+ 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a,
+ 0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92,
+ 0x82, 0xf4, 0x83, 0x57, 0x83, 0xba, 0x84, 0x1d,
+ 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab,
+ 0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b,
+ 0x87, 0x9f, 0x88, 0x04, 0x88, 0x69, 0x88, 0xce,
+ 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64,
+ 0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc,
+ 0x8c, 0x63, 0x8c, 0xca, 0x8d, 0x31, 0x8d, 0x98,
+ 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36,
+ 0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6,
+ 0x91, 0x3f, 0x91, 0xa8, 0x92, 0x11, 0x92, 0x7a,
+ 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20,
+ 0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9,
+ 0x96, 0x34, 0x96, 0x9f, 0x97, 0x0a, 0x97, 0x75,
+ 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24,
+ 0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5,
+ 0x9b, 0x42, 0x9b, 0xaf, 0x9c, 0x1c, 0x9c, 0x89,
+ 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40,
+ 0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa,
+ 0xa0, 0x69, 0xa0, 0xd8, 0xa1, 0x47, 0xa1, 0xb6,
+ 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76,
+ 0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38,
+ 0xa5, 0xa9, 0xa6, 0x1a, 0xa6, 0x8b, 0xa6, 0xfd,
+ 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4,
+ 0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f,
+ 0xab, 0x02, 0xab, 0x75, 0xab, 0xe9, 0xac, 0x5c,
+ 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d,
+ 0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00,
+ 0xb0, 0x75, 0xb0, 0xea, 0xb1, 0x60, 0xb1, 0xd6,
+ 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae,
+ 0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a,
+ 0xb6, 0x01, 0xb6, 0x79, 0xb6, 0xf0, 0xb7, 0x68,
+ 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a,
+ 0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e,
+ 0xbb, 0xa7, 0xbc, 0x21, 0xbc, 0x9b, 0xbd, 0x15,
+ 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff,
+ 0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec,
+ 0xc1, 0x67, 0xc1, 0xe3, 0xc2, 0x5f, 0xc2, 0xdb,
+ 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce,
+ 0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3,
+ 0xc7, 0x41, 0xc7, 0xbf, 0xc8, 0x3d, 0xc8, 0xbc,
+ 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7,
+ 0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5,
+ 0xcd, 0x35, 0xcd, 0xb5, 0xce, 0x36, 0xce, 0xb6,
+ 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba,
+ 0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1,
+ 0xd3, 0x44, 0xd3, 0xc6, 0xd4, 0x49, 0xd4, 0xcb,
+ 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8,
+ 0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8,
+ 0xd9, 0x6c, 0xd9, 0xf1, 0xda, 0x76, 0xda, 0xfb,
+ 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10,
+ 0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29,
+ 0xdf, 0xaf, 0xe0, 0x36, 0xe0, 0xbd, 0xe1, 0x44,
+ 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63,
+ 0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84,
+ 0xe6, 0x0d, 0xe6, 0x96, 0xe7, 0x1f, 0xe7, 0xa9,
+ 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0,
+ 0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb,
+ 0xec, 0x86, 0xed, 0x11, 0xed, 0x9c, 0xee, 0x28,
+ 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58,
+ 0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c,
+ 0xf3, 0x19, 0xf3, 0xa7, 0xf4, 0x34, 0xf4, 0xc2,
+ 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb,
+ 0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38,
+ 0xf9, 0xc7, 0xfa, 0x57, 0xfa, 0xe7, 0xfb, 0x77,
+ 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba,
+ 0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff
+};
+
+int jas_iccprofdata_srgblen = sizeof(jas_iccprofdata_srgb);
+
+uchar jas_iccprofdata_sgray[] = {
+ 0x00, 0x00, 0x01, 0x8a, 0x00, 0x00, 0x00, 0x00,
+ 0x02, 0x20, 0x00, 0x00, 0x73, 0x63, 0x6e, 0x72,
+ 0x47, 0x52, 0x41, 0x59, 0x58, 0x59, 0x5a, 0x20,
+ 0x07, 0xd3, 0x00, 0x01, 0x00, 0x1f, 0x00, 0x0d,
+ 0x00, 0x35, 0x00, 0x21, 0x61, 0x63, 0x73, 0x70,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
+ 0x4b, 0x4f, 0x44, 0x41, 0x73, 0x47, 0x72, 0x79,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6,
+ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d,
+ 0x4a, 0x50, 0x45, 0x47, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x04, 0x64, 0x65, 0x73, 0x63,
+ 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, 0x86,
+ 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0x3c,
+ 0x00, 0x00, 0x00, 0x2b, 0x77, 0x74, 0x70, 0x74,
+ 0x00, 0x00, 0x01, 0x68, 0x00, 0x00, 0x00, 0x14,
+ 0x6b, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0x7c,
+ 0x00, 0x00, 0x00, 0x0e, 0x64, 0x65, 0x73, 0x63,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c,
+ 0x52, 0x65, 0x73, 0x74, 0x72, 0x69, 0x63, 0x74,
+ 0x65, 0x64, 0x20, 0x49, 0x43, 0x43, 0x20, 0x70,
+ 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x64,
+ 0x65, 0x73, 0x63, 0x72, 0x69, 0x62, 0x69, 0x6e,
+ 0x67, 0x20, 0x73, 0x52, 0x47, 0x42, 0x2d, 0x67,
+ 0x72, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74,
+ 0x00, 0x00, 0x00, 0x00, 0x43, 0x6f, 0x70, 0x79,
+ 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x32, 0x30,
+ 0x30, 0x33, 0x20, 0x73, 0x52, 0x47, 0x42, 0x2d,
+ 0x67, 0x72, 0x65, 0x79, 0x20, 0x52, 0x65, 0x66,
+ 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x00, 0x00,
+ 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0xf3, 0x54, 0x00, 0x01, 0x00, 0x00,
+ 0x00, 0x01, 0x16, 0xcf, 0x63, 0x75, 0x72, 0x76,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
+ 0x01, 0xcd
+};
+
+int jas_iccprofdata_sgraylen = sizeof(jas_iccprofdata_sgray);
diff --git a/jasper-1.900.1-6ct/src/libjasper/base/jas_image.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_image.c
new file mode 100644
index 0000000..4b7ac7d
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_image.c
@@ -0,0 +1,1446 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Image Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "jasper/jas_math.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_string.h"
+#include "jasper/jas_debug.h"
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+#define FLOORDIV(x, y) ((x) / (y))
+
+/******************************************************************************\
+* Local prototypes.
+\******************************************************************************/
+
+static jas_image_cmpt_t *jas_image_cmpt_create0(void);
+static void jas_image_cmpt_destroy(jas_image_cmpt_t *cmpt);
+static jas_image_cmpt_t *jas_image_cmpt_create(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);
+static void jas_image_setbbox(jas_image_t *image);
+static jas_image_cmpt_t *jas_image_cmpt_copy(jas_image_cmpt_t *cmpt);
+static int jas_image_growcmpts(jas_image_t *image, int maxcmpts);
+static uint_fast32_t inttobits(jas_seqent_t v, int prec, bool sgnd);
+static jas_seqent_t bitstoint(uint_fast32_t v, int prec, bool sgnd);
+static int putint(jas_stream_t *out, int sgnd, int prec, long val);
+static int getint(jas_stream_t *in, int sgnd, int prec, long *val);
+static void jas_image_calcbbox2(jas_image_t *image, jas_image_coord_t *tlx,
+ jas_image_coord_t *tly, jas_image_coord_t *brx, jas_image_coord_t *bry);
+static long uptomult(long x, long y);
+static long downtomult(long x, long y);
+static long convert(long val, int oldsgnd, int oldprec, int newsgnd,
+ int newprec);
+static void jas_image_calcbbox2(jas_image_t *image, jas_image_coord_t *tlx,
+ jas_image_coord_t *tly, jas_image_coord_t *brx, jas_image_coord_t *bry);
+
+/******************************************************************************\
+* Global data.
+\******************************************************************************/
+
+static int jas_image_numfmts = 0;
+static jas_image_fmtinfo_t jas_image_fmtinfos[JAS_IMAGE_MAXFMTS];
+
+/******************************************************************************\
+* Create and destroy operations.
+\******************************************************************************/
+
+jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms,
+ int clrspc)
+{
+ jas_image_t *image;
+ uint_fast32_t rawsize;
+ uint_fast32_t inmem;
+ int cmptno;
+ jas_image_cmptparm_t *cmptparm;
+
+ if (!(image = jas_image_create0())) {
+ return 0;
+ }
+
+ image->clrspc_ = clrspc;
+ 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;
+
+ if (!(image = jas_malloc(sizeof(jas_image_t)))) {
+ return 0;
+ }
+
+ image->tlx_ = 0;
+ image->tly_ = 0;
+ image->brx_ = 0;
+ image->bry_ = 0;
+ image->clrspc_ = JAS_CLRSPC_UNKNOWN;
+ image->numcmpts_ = 0;
+ image->maxcmpts_ = 0;
+ image->cmpts_ = 0;
+ image->inmem_ = true;
+ image->cmprof_ = 0;
+
+ return image;
+}
+
+jas_image_t *jas_image_copy(jas_image_t *image)
+{
+ jas_image_t *newimage;
+ 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_;
+ }
+
+ jas_image_setbbox(newimage);
+
+ if (image->cmprof_) {
+ if (!(newimage->cmprof_ = jas_cmprof_copy(image->cmprof_)))
+ goto error;
+ }
+
+ return newimage;
+error:
+ if (newimage) {
+ jas_image_destroy(newimage);
+ }
+ return 0;
+}
+
+static jas_image_cmpt_t *jas_image_cmpt_create0()
+{
+ jas_image_cmpt_t *cmpt;
+ if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
+ return 0;
+ }
+ memset(cmpt, 0, sizeof(jas_image_cmpt_t));
+ cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
+ return cmpt;
+}
+
+static jas_image_cmpt_t *jas_image_cmpt_copy(jas_image_cmpt_t *cmpt)
+{
+ jas_image_cmpt_t *newcmpt;
+
+ if (!(newcmpt = jas_image_cmpt_create0())) {
+ return 0;
+ }
+ newcmpt->tlx_ = cmpt->tlx_;
+ newcmpt->tly_ = cmpt->tly_;
+ newcmpt->hstep_ = cmpt->hstep_;
+ newcmpt->vstep_ = cmpt->vstep_;
+ newcmpt->width_ = cmpt->width_;
+ newcmpt->height_ = cmpt->height_;
+ newcmpt->prec_ = cmpt->prec_;
+ newcmpt->sgnd_ = cmpt->sgnd_;
+ newcmpt->cps_ = cmpt->cps_;
+ newcmpt->type_ = cmpt->type_;
+ if (!(newcmpt->stream_ = jas_stream_memopen(0, 0))) {
+ 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;
+
+ 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_);
+ }
+ if (image->cmprof_)
+ jas_cmprof_destroy(image->cmprof_);
+ 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->type_ = JAS_IMAGE_CT_UNKNOWN;
+ cmpt->tlx_ = tlx;
+ cmpt->tly_ = tly;
+ cmpt->hstep_ = hstep;
+ cmpt->vstep_ = vstep;
+ cmpt->width_ = width;
+ cmpt->height_ = height;
+ cmpt->prec_ = depth;
+ cmpt->sgnd_ = sgnd;
+ cmpt->stream_ = 0;
+ cmpt->cps_ = (depth + 7) / 8;
+
+ 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);
+}
+
+/******************************************************************************\
+* Load and save operations.
+\******************************************************************************/
+
+jas_image_t *jas_image_decode(jas_stream_t *in, int fmt, char *optstr)
+{
+ jas_image_fmtinfo_t *fmtinfo;
+ jas_image_t *image;
+
+ image = 0;
+
+ /* If possible, try to determine the format of the input data. */
+ if (fmt < 0) {
+ if ((fmt = jas_image_getfmt(in)) < 0)
+ goto error;
+ }
+
+ /* Is it possible to decode an image represented in this format? */
+ if (!(fmtinfo = jas_image_lookupfmtbyid(fmt)))
+ goto error;
+ if (!fmtinfo->ops.decode)
+ goto error;
+
+ /* Decode the image. */
+ if (!(image = (*fmtinfo->ops.decode)(in, optstr)))
+ goto error;
+
+ /* Create a color profile if needed. */
+ if (!jas_clrspc_isunknown(image->clrspc_) &&
+ !jas_clrspc_isgeneric(image->clrspc_) && !image->cmprof_) {
+ if (!(image->cmprof_ =
+ jas_cmprof_createfromclrspc(jas_image_clrspc(image))))
+ goto error;
+ }
+
+ return image;
+error:
+ if (image)
+ jas_image_destroy(image);
+ return 0;
+}
+
+int jas_image_encode(jas_image_t *image, jas_stream_t *out, int fmt, 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);
+}
+
+/******************************************************************************\
+* Component read and write operations.
+\******************************************************************************/
+
+int jas_image_readcmpt(jas_image_t *image, int cmptno, jas_image_coord_t x,
+ jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height,
+ jas_matrix_t *data)
+{
+ jas_image_cmpt_t *cmpt;
+ jas_image_coord_t i;
+ jas_image_coord_t j;
+ int k;
+ jas_seqent_t v;
+ int c;
+ jas_seqent_t *dr;
+ jas_seqent_t *d;
+ int drs;
+
+ if (cmptno < 0 || 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;
+}
+
+int jas_image_writecmpt(jas_image_t *image, int cmptno, jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width,
+ jas_image_coord_t height, jas_matrix_t *data)
+{
+ jas_image_cmpt_t *cmpt;
+ jas_image_coord_t i;
+ jas_image_coord_t j;
+ jas_seqent_t *d;
+ jas_seqent_t *dr;
+ int drs;
+ jas_seqent_t v;
+ int k;
+ int c;
+
+ if (cmptno < 0 || 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;
+}
+
+/******************************************************************************\
+* File format operations.
+\******************************************************************************/
+
+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, char *name, char *ext, 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;
+}
+
+int jas_image_strtofmt(char *name)
+{
+ 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;
+}
+
+int jas_image_getfmt(jas_stream_t *in)
+{
+ jas_image_fmtinfo_t *fmtinfo;
+ int found;
+ int i;
+
+ /* Check for data in each of the supported formats. */
+ 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;
+}
+
+/******************************************************************************\
+* Miscellaneous operations.
+\******************************************************************************/
+
+uint_fast32_t jas_image_rawsize(jas_image_t *image)
+{
+ uint_fast32_t rawsize;
+ int cmptno;
+ jas_image_cmpt_t *cmpt;
+
+ rawsize = 0;
+ for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
+ cmpt = image->cmpts_[cmptno];
+ rawsize += (cmpt->width_ * cmpt->height_ * cmpt->prec_ +
+ 7) / 8;
+ }
+ return rawsize;
+}
+
+void jas_image_delcmpt(jas_image_t *image, int cmptno)
+{
+ if (cmptno >= image->numcmpts_) {
+ return;
+ }
+ jas_image_cmpt_destroy(image->cmpts_[cmptno]);
+ if (cmptno < image->numcmpts_) {
+ memmove(&image->cmpts_[cmptno], &image->cmpts_[cmptno + 1],
+ (image->numcmpts_ - 1 - cmptno) * sizeof(jas_image_cmpt_t *));
+ }
+ --image->numcmpts_;
+
+ jas_image_setbbox(image);
+}
+
+int jas_image_addcmpt(jas_image_t *image, int cmptno,
+ jas_image_cmptparm_t *cmptparm)
+{
+ jas_image_cmpt_t *newcmpt;
+ if (cmptno < 0)
+ cmptno = image->numcmpts_;
+ assert(cmptno >= 0 && 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;
+
+ 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;
+
+ for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) {
+ if (!strcmp(fmtinfo->name, name)) {
+ return fmtinfo;
+ }
+ }
+ return 0;
+}
+
+
+
+
+
+static uint_fast32_t inttobits(jas_seqent_t v, int prec, bool sgnd)
+{
+ uint_fast32_t ret;
+ ret = ((sgnd && v < 0) ? ((1 << prec) + v) : v) & JAS_ONES(prec);
+ return ret;
+}
+
+static jas_seqent_t bitstoint(uint_fast32_t v, int prec, bool sgnd)
+{
+ jas_seqent_t ret;
+ v &= JAS_ONES(prec);
+ ret = (sgnd && (v & (1 << (prec - 1)))) ? (v - (1 << prec)) : v;
+ return ret;
+}
+
+static void jas_image_setbbox(jas_image_t *image)
+{
+ jas_image_cmpt_t *cmpt;
+ int 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;
+
+ 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;
+}
+
+void jas_image_dump(jas_image_t *image, FILE *out)
+{
+ long buf[1024];
+ int cmptno;
+ int n;
+ int i;
+ int width;
+ int height;
+ jas_image_cmpt_t *cmpt;
+ for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
+ cmpt = image->cmpts_[cmptno];
+ fprintf(out, "prec=%d, sgnd=%d, cmpttype=%d\n", cmpt->prec_,
+ cmpt->sgnd_, cmpt->type_);
+ width = jas_image_cmptwidth(image, cmptno);
+ height = jas_image_cmptheight(image, cmptno);
+ n = JAS_MIN(16, width);
+ if (jas_image_readcmpt2(image, cmptno, 0, 0, n, 1, buf)) {
+ abort();
+ }
+ for (i = 0; i < n; ++i) {
+ fprintf(out, " f(%d,%d)=%ld", i, 0, buf[i]);
+ }
+ fprintf(out, "\n");
+ if (jas_image_readcmpt2(image, cmptno, width - n, height - 1, n, 1, buf)) {
+ abort();
+ }
+ for (i = 0; i < n; ++i) {
+ fprintf(out, " f(%d,%d)=%ld", width - n + i, height - 1, buf[i]);
+ }
+ fprintf(out, "\n");
+ }
+}
+
+int jas_image_depalettize(jas_image_t *image, 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 (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;
+
+ 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_);
+}
+
+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;
+
+ 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;
+ }
+}
+
+int jas_image_getcmptbytype(jas_image_t *image, int ctype)
+{
+ int cmptno;
+
+ for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
+ if (image->cmpts_[cmptno]->type_ == ctype) {
+ return cmptno;
+ }
+ }
+ return -1;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+/***********************************************/
+/***********************************************/
+/***********************************************/
+/***********************************************/
+
+int jas_image_readcmpt2(jas_image_t *image, int cmptno, jas_image_coord_t x,
+ jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height,
+ long *buf)
+{
+ jas_image_cmpt_t *cmpt;
+ jas_image_coord_t i;
+ jas_image_coord_t j;
+ long v;
+ long *bufptr;
+
+ if (cmptno < 0 || cmptno >= image->numcmpts_)
+ goto error;
+ cmpt = image->cmpts_[cmptno];
+ if (x < 0 || x >= cmpt->width_ || y < 0 || y >= cmpt->height_ ||
+ width < 0 || height < 0 || x + width > cmpt->width_ ||
+ y + height > cmpt->height_)
+ goto error;
+
+ bufptr = buf;
+ for (i = 0; i < height; ++i) {
+ if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x)
+ * cmpt->cps_, SEEK_SET) < 0)
+ goto error;
+ for (j = 0; j < width; ++j) {
+ if (getint(cmpt->stream_, cmpt->sgnd_, cmpt->prec_, &v))
+ goto error;
+ *bufptr++ = v;
+ }
+ }
+
+ return 0;
+error:
+ return -1;
+}
+
+int jas_image_writecmpt2(jas_image_t *image, int cmptno, jas_image_coord_t x,
+ jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height,
+ long *buf)
+{
+ jas_image_cmpt_t *cmpt;
+ jas_image_coord_t i;
+ jas_image_coord_t j;
+ long v;
+ long *bufptr;
+
+ if (cmptno < 0 || cmptno >= image->numcmpts_)
+ goto error;
+ cmpt = image->cmpts_[cmptno];
+ if (x < 0 || x >= cmpt->width_ || y < 0 || y >= cmpt->height_ ||
+ width < 0 || height < 0 || x + width > cmpt->width_ ||
+ y + height > cmpt->height_)
+ goto error;
+
+ bufptr = buf;
+ for (i = 0; i < height; ++i) {
+ if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x)
+ * cmpt->cps_, SEEK_SET) < 0)
+ goto error;
+ for (j = 0; j < width; ++j) {
+ v = *bufptr++;
+ if (putint(cmpt->stream_, cmpt->sgnd_, cmpt->prec_, v))
+ goto error;
+ }
+ }
+
+ return 0;
+error:
+ return -1;
+}
+
+int jas_image_sampcmpt(jas_image_t *image, int cmptno, int newcmptno,
+ jas_image_coord_t ho, jas_image_coord_t vo, jas_image_coord_t hs,
+ jas_image_coord_t vs, int sgnd, int prec)
+{
+ jas_image_cmpt_t *oldcmpt;
+ jas_image_cmpt_t *newcmpt;
+ int width;
+ int height;
+ jas_image_coord_t tlx;
+ jas_image_coord_t tly;
+ jas_image_coord_t brx;
+ jas_image_coord_t bry;
+ int i;
+ int j;
+ jas_image_cmptparm_t cmptparm;
+ jas_image_coord_t ax;
+ jas_image_coord_t ay;
+ jas_image_coord_t bx;
+ jas_image_coord_t by;
+ jas_image_coord_t d0;
+ jas_image_coord_t d1;
+ jas_image_coord_t d2;
+ jas_image_coord_t d3;
+ jas_image_coord_t oldx;
+ jas_image_coord_t oldy;
+ jas_image_coord_t x;
+ jas_image_coord_t y;
+ long v;
+ jas_image_coord_t cmptbrx;
+ jas_image_coord_t cmptbry;
+
+ assert(cmptno >= 0 && cmptno < image->numcmpts_);
+ oldcmpt = image->cmpts_[cmptno];
+ assert(oldcmpt->tlx_ == 0 && oldcmpt->tly_ == 0);
+ jas_image_calcbbox2(image, &tlx, &tly, &brx, &bry);
+ width = FLOORDIV(brx - ho + hs, hs);
+ height = FLOORDIV(bry - vo + vs, vs);
+ cmptparm.tlx = ho;
+ cmptparm.tly = vo;
+ cmptparm.hstep = hs;
+ cmptparm.vstep = vs;
+ cmptparm.width = width;
+ cmptparm.height = height;
+ cmptparm.prec = prec;
+ cmptparm.sgnd = sgnd;
+ if (jas_image_addcmpt(image, newcmptno, &cmptparm))
+ goto error;
+cmptbrx = oldcmpt->tlx_ + (oldcmpt->width_ - 1) * oldcmpt->hstep_;
+cmptbry = oldcmpt->tly_ + (oldcmpt->height_ - 1) * oldcmpt->vstep_;
+ newcmpt = image->cmpts_[newcmptno];
+ jas_stream_rewind(newcmpt->stream_);
+ for (i = 0; i < height; ++i) {
+ y = newcmpt->tly_ + newcmpt->vstep_ * i;
+ for (j = 0; j < width; ++j) {
+ x = newcmpt->tlx_ + newcmpt->hstep_ * j;
+ ax = downtomult(x - oldcmpt->tlx_, oldcmpt->hstep_) + oldcmpt->tlx_;
+ ay = downtomult(y - oldcmpt->tly_, oldcmpt->vstep_) + oldcmpt->tly_;
+ bx = uptomult(x - oldcmpt->tlx_, oldcmpt->hstep_) + oldcmpt->tlx_;
+ if (bx > cmptbrx)
+ bx = cmptbrx;
+ by = uptomult(y - oldcmpt->tly_, oldcmpt->vstep_) + oldcmpt->tly_;
+ if (by > cmptbry)
+ by = cmptbry;
+ d0 = (ax - x) * (ax - x) + (ay - y) * (ay - y);
+ d1 = (bx - x) * (bx - x) + (ay - y) * (ay - y);
+ d2 = (bx - x) * (bx - x) + (by - y) * (by - y);
+ d3 = (ax - x) * (ax - x) + (by - y) * (by - y);
+ if (d0 <= d1 && d0 <= d2 && d0 <= d3) {
+ oldx = (ax - oldcmpt->tlx_) / oldcmpt->hstep_;
+ oldy = (ay - oldcmpt->tly_) / oldcmpt->vstep_;
+ } else if (d1 <= d0 && d1 <= d2 && d1 <= d3) {
+ oldx = (bx - oldcmpt->tlx_) / oldcmpt->hstep_;
+ oldy = (ay - oldcmpt->tly_) / oldcmpt->vstep_;
+ } else if (d2 <= d0 && d2 <= d1 && d1 <= d3) {
+ oldx = (bx - oldcmpt->tlx_) / oldcmpt->hstep_;
+ oldy = (by - oldcmpt->tly_) / oldcmpt->vstep_;
+ } else {
+ oldx = (ax - oldcmpt->tlx_) / oldcmpt->hstep_;
+ oldy = (by - oldcmpt->tly_) / oldcmpt->vstep_;
+ }
+ assert(oldx >= 0 && oldx < oldcmpt->width_ &&
+ oldy >= 0 && oldy < oldcmpt->height_);
+ if (jas_stream_seek(oldcmpt->stream_, oldcmpt->cps_ *
+ (oldy * oldcmpt->width_ + oldx), SEEK_SET) < 0)
+ goto error;
+ if (getint(oldcmpt->stream_, oldcmpt->sgnd_,
+ oldcmpt->prec_, &v))
+ goto error;
+ if (newcmpt->prec_ != oldcmpt->prec_ ||
+ newcmpt->sgnd_ != oldcmpt->sgnd_) {
+ v = convert(v, oldcmpt->sgnd_, oldcmpt->prec_,
+ newcmpt->sgnd_, newcmpt->prec_);
+ }
+ if (putint(newcmpt->stream_, newcmpt->sgnd_,
+ newcmpt->prec_, v))
+ goto error;
+ }
+ }
+ return 0;
+error:
+ return -1;
+}
+
+int jas_image_ishomosamp(jas_image_t *image)
+{
+ jas_image_coord_t hstep;
+ jas_image_coord_t vstep;
+ int result;
+ int i;
+ hstep = jas_image_cmpthstep(image, 0);
+ vstep = jas_image_cmptvstep(image, 0);
+ result = 1;
+ for (i = 0; i < image->numcmpts_; ++i) {
+ if (jas_image_cmpthstep(image, i) != hstep ||
+ jas_image_cmptvstep(image, i) != vstep) {
+ result = 0;
+ break;
+ }
+ }
+ return result;
+}
+
+/* Note: This function defines a bounding box differently. */
+static void jas_image_calcbbox2(jas_image_t *image, jas_image_coord_t *tlx,
+ jas_image_coord_t *tly, jas_image_coord_t *brx, jas_image_coord_t *bry)
+{
+ jas_image_cmpt_t *cmpt;
+ jas_image_coord_t tmptlx;
+ jas_image_coord_t tmptly;
+ jas_image_coord_t tmpbrx;
+ jas_image_coord_t tmpbry;
+ jas_image_coord_t t;
+ int i;
+ if (image->numcmpts_ > 0) {
+ cmpt = image->cmpts_[0];
+ tmptlx = cmpt->tlx_;
+ tmptly = cmpt->tly_;
+ tmpbrx = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1);
+ tmpbry = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1);
+ for (i = 0; i < image->numcmpts_; ++i) {
+ cmpt = image->cmpts_[i];
+ if (cmpt->tlx_ < tmptlx)
+ tmptlx = cmpt->tlx_;
+ if (cmpt->tly_ < tmptly)
+ tmptly = cmpt->tly_;
+ t = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1);
+ if (t > tmpbrx)
+ tmpbrx = t;
+ t = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1);
+ if (t > tmpbry)
+ tmpbry = t;
+ }
+ } else {
+ tmptlx = 0;
+ tmptly = 0;
+ tmpbrx = -1;
+ tmpbry = -1;
+ }
+ *tlx = tmptlx;
+ *tly = tmptly;
+ *brx = tmpbrx;
+ *bry = tmpbry;
+}
+
+
+
+static int getint(jas_stream_t *in, int sgnd, int prec, long *val)
+{
+ long v;
+ int n;
+ int c;
+ n = (prec + 7) / 8;
+ v = 0;
+ while (--n >= 0) {
+ if ((c = jas_stream_getc(in)) == EOF)
+ return -1;
+ v = (v << 8) | c;
+ }
+ v &= ((1 << prec) - 1);
+ if (sgnd) {
+ /* XXX - Do something here. */
+ abort();
+ } else {
+ *val = v;
+ }
+ return 0;
+}
+
+static int putint(jas_stream_t *out, int sgnd, int prec, long val)
+{
+ int n;
+ int c;
+ if (sgnd) {
+ /* XXX - Do something here. */
+ abort();
+ }
+ val &= (1 << prec) - 1;
+ n = (prec + 7) / 8;
+ while (--n >= 0) {
+ c = (val >> (n * 8)) & 0xff;
+ if (jas_stream_putc(out, c) != c)
+ return -1;
+ }
+ return 0;
+}
+
+static long convert(long val, int oldsgnd, int oldprec, int newsgnd,
+ int newprec)
+{
+ if (newsgnd != oldsgnd) {
+ }
+ if (newprec != oldprec) {
+ if (newprec > oldprec) {
+ val <<= newprec - oldprec;
+ } else if (oldprec > newprec) {
+ val >>= oldprec - newprec;
+ }
+ }
+ return val;
+}
+
+static long downtomult(long x, long y)
+{
+ assert(x >= 0);
+ return (x / y) * y;
+}
+
+static long uptomult(long x, long y)
+{
+ assert(x >= 0);
+ return ((x + y - 1) / y) * y;
+}
+
+jas_image_t *jas_image_chclrspc(jas_image_t *image, jas_cmprof_t *outprof,
+ int intent)
+{
+ jas_image_t *inimage;
+ int minhstep;
+ int minvstep;
+ int i;
+ int j;
+ int k;
+ int n;
+ int hstep;
+ int vstep;
+ int numinauxchans;
+ int numoutauxchans;
+ int numinclrchans;
+ int numoutclrchans;
+ int prec;
+ jas_image_t *outimage;
+ int cmpttype;
+ int numoutchans;
+ jas_cmprof_t *inprof;
+ jas_cmprof_t *tmpprof;
+ jas_image_cmptparm_t cmptparm;
+ int width;
+ int height;
+ jas_cmxform_t *xform;
+ jas_cmpixmap_t inpixmap;
+ jas_cmpixmap_t outpixmap;
+ jas_cmcmptfmt_t *incmptfmts;
+ jas_cmcmptfmt_t *outcmptfmts;
+
+#if 0
+jas_eprintf("IMAGE\n");
+jas_image_dump(image, stderr);
+#endif
+
+ if (!(inimage = jas_image_copy(image)))
+ goto error;
+ image = 0;
+
+ if (!jas_image_ishomosamp(inimage)) {
+ minhstep = jas_image_cmpthstep(inimage, 0);
+ minvstep = jas_image_cmptvstep(inimage, 0);
+ for (i = 1; i < jas_image_numcmpts(inimage); ++i) {
+ hstep = jas_image_cmpthstep(inimage, i);
+ vstep = jas_image_cmptvstep(inimage, i);
+ if (hstep < minhstep)
+ minhstep = hstep;
+ if (vstep < minvstep)
+ minvstep = vstep;
+ }
+ n = jas_image_numcmpts(inimage);
+ for (i = 0; i < n; ++i) {
+ cmpttype = jas_image_cmpttype(inimage, i);
+ if (jas_image_sampcmpt(inimage, i, i + 1, 0, 0, minhstep, minvstep, jas_image_cmptsgnd(inimage, i), jas_image_cmptprec(inimage, i)))
+ goto error;
+ jas_image_setcmpttype(inimage, i + 1, cmpttype);
+ jas_image_delcmpt(inimage, i);
+ }
+ }
+
+ width = jas_image_cmptwidth(inimage, 0);
+ height = jas_image_cmptheight(inimage, 0);
+ hstep = jas_image_cmpthstep(inimage, 0);
+ vstep = jas_image_cmptvstep(inimage, 0);
+
+ inprof = jas_image_cmprof(inimage);
+ assert(inprof);
+ numinclrchans = jas_clrspc_numchans(jas_cmprof_clrspc(inprof));
+ numinauxchans = jas_image_numcmpts(inimage) - numinclrchans;
+ numoutclrchans = jas_clrspc_numchans(jas_cmprof_clrspc(outprof));
+ numoutauxchans = 0;
+ numoutchans = numoutclrchans + numoutauxchans;
+ prec = 8;
+
+ if (!(outimage = jas_image_create0()))
+ goto error;
+
+ /* Create a component for each of the colorants. */
+ for (i = 0; i < numoutclrchans; ++i) {
+ cmptparm.tlx = 0;
+ cmptparm.tly = 0;
+ cmptparm.hstep = hstep;
+ cmptparm.vstep = vstep;
+ cmptparm.width = width;
+ cmptparm.height = height;
+ cmptparm.prec = prec;
+ cmptparm.sgnd = 0;
+ if (jas_image_addcmpt(outimage, -1, &cmptparm))
+ goto error;
+ jas_image_setcmpttype(outimage, i, JAS_IMAGE_CT_COLOR(i));
+ }
+#if 0
+ /* Copy the auxiliary components without modification. */
+ for (i = 0; i < jas_image_numcmpts(inimage); ++i) {
+ if (!ISCOLOR(jas_image_cmpttype(inimage, i))) {
+ jas_image_copycmpt(outimage, -1, inimage, i);
+/* XXX - need to specify laydown of component on ref. grid */
+ }
+ }
+#endif
+
+ if (!(tmpprof = jas_cmprof_copy(outprof)))
+ goto error;
+ assert(!jas_image_cmprof(outimage));
+ jas_image_setcmprof(outimage, tmpprof);
+ tmpprof = 0;
+ jas_image_setclrspc(outimage, jas_cmprof_clrspc(outprof));
+
+ if (!(xform = jas_cmxform_create(inprof, outprof, 0, JAS_CMXFORM_OP_FWD, intent, 0)))
+ goto error;
+
+ inpixmap.numcmpts = numinclrchans;
+ incmptfmts = malloc(numinclrchans * sizeof(jas_cmcmptfmt_t));
+ assert(incmptfmts);
+ inpixmap.cmptfmts = incmptfmts;
+ for (i = 0; i < numinclrchans; ++i) {
+ j = jas_image_getcmptbytype(inimage, JAS_IMAGE_CT_COLOR(i));
+ assert(j >= 0);
+ if (!(incmptfmts[i].buf = malloc(width * sizeof(long))))
+ goto error;
+ incmptfmts[i].prec = jas_image_cmptprec(inimage, j);
+ incmptfmts[i].sgnd = jas_image_cmptsgnd(inimage, j);
+ incmptfmts[i].width = width;
+ incmptfmts[i].height = 1;
+ }
+
+ outpixmap.numcmpts = numoutclrchans;
+ outcmptfmts = malloc(numoutclrchans * sizeof(jas_cmcmptfmt_t));
+ assert(outcmptfmts);
+ outpixmap.cmptfmts = outcmptfmts;
+
+ for (i = 0; i < numoutclrchans; ++i) {
+ j = jas_image_getcmptbytype(outimage, JAS_IMAGE_CT_COLOR(i));
+ assert(j >= 0);
+ if (!(outcmptfmts[i].buf = malloc(width * sizeof(long))))
+ goto error;
+ outcmptfmts[i].prec = jas_image_cmptprec(outimage, j);
+ outcmptfmts[i].sgnd = jas_image_cmptsgnd(outimage, j);
+ outcmptfmts[i].width = width;
+ outcmptfmts[i].height = 1;
+ }
+
+ for (i = 0; i < height; ++i) {
+ for (j = 0; j < numinclrchans; ++j) {
+ k = jas_image_getcmptbytype(inimage, JAS_IMAGE_CT_COLOR(j));
+ if (jas_image_readcmpt2(inimage, k, 0, i, width, 1, incmptfmts[j].buf))
+ goto error;
+ }
+ jas_cmxform_apply(xform, &inpixmap, &outpixmap);
+ for (j = 0; j < numoutclrchans; ++j) {
+ k = jas_image_getcmptbytype(outimage, JAS_IMAGE_CT_COLOR(j));
+ if (jas_image_writecmpt2(outimage, k, 0, i, width, 1, outcmptfmts[j].buf))
+ goto error;
+ }
+ }
+
+ for (i = 0; i < numoutclrchans; ++i)
+ jas_free(outcmptfmts[i].buf);
+ jas_free(outcmptfmts);
+ for (i = 0; i < numinclrchans; ++i)
+ jas_free(incmptfmts[i].buf);
+ jas_free(incmptfmts);
+ jas_cmxform_destroy(xform);
+ jas_image_destroy(inimage);
+
+#if 0
+jas_eprintf("INIMAGE\n");
+jas_image_dump(inimage, stderr);
+jas_eprintf("OUTIMAGE\n");
+jas_image_dump(outimage, stderr);
+#endif
+ return outimage;
+error:
+ return 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/base/jas_init.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_init.c
new file mode 100644
index 0000000..898616b
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_init.c
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_init.h"
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+/* Initialize the image format table. */
+int jas_init()
+{
+ jas_image_fmtops_t fmtops;
+ int fmtid;
+
+ 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;
+#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;
+#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;
+#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;
+#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;
+#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;
+#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;
+#endif
+
+ /* We must not register the JasPer library exit handler until after
+ at least one memory allocation is performed. This is desirable
+ as it ensures that the JasPer exit handler is called before the
+ debug memory allocator exit handler. */
+ atexit(jas_cleanup);
+
+ return 0;
+}
+
+void jas_cleanup()
+{
+ jas_image_clearfmts();
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/base/jas_malloc.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_malloc.c
new file mode 100644
index 0000000..13f7bc8
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_malloc.c
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Memory Allocator
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+
+/* We need the prototype for memset. */
+#include <string.h>
+
+#include "jasper/jas_malloc.h"
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+#if defined(DEBUG_MEMALLOC)
+#include "../../../local/src/memalloc.c"
+#endif
+
+#if !defined(DEBUG_MEMALLOC)
+
+#define MEMALLOC_ALIGNMENT 32
+#define MEMALLOC_ALIGN2
+#undef MEMALLOC_ALIGN2
+
+void *jas_malloc(size_t size)
+{
+#if defined(MEMALLOC_ALIGN2)
+ void *ptr;
+abort();
+ if (posix_memalign(&ptr, MEMALLOC_ALIGNMENT, size)) {
+ return 0;
+ }
+ return ptr;
+#endif
+ return malloc(size);
+}
+
+void jas_free(void *ptr)
+{
+ free(ptr);
+}
+
+void *jas_realloc(void *ptr, size_t 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;
+}
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/base/jas_seq.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_seq.c
new file mode 100644
index 0000000..16e1778
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_seq.c
@@ -0,0 +1,454 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Sequence/Matrix Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdlib.h>
+#include <assert.h>
+#include <math.h>
+
+#include "jasper/jas_seq.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+
+/******************************************************************************\
+* Constructors and destructors.
+\******************************************************************************/
+
+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 *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;
+}
+
+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);
+}
+
+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 *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;
+}
+
+/******************************************************************************\
+* Bind operations.
+\******************************************************************************/
+
+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);
+}
+
+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_;
+}
+
+/******************************************************************************\
+* Arithmetic operations.
+\******************************************************************************/
+
+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;
+}
+
+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));
+ }
+ }
+}
+
+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;
+ }
+ }
+ }
+}
+
+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;
+ }
+ }
+}
+
+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;
+ }
+ }
+}
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+int jas_matrix_resize(jas_matrix_t *matrix, int numrows, int numcols)
+{
+ int size;
+ int i;
+
+ size = numrows * numcols;
+ if (size > matrix->datasize_ || numrows > matrix->maxrows_) {
+ return -1;
+ }
+
+ matrix->numrows_ = numrows;
+ matrix->numcols_ = numcols;
+
+ for (i = 0; i < numrows; ++i) {
+ matrix->rows_[i] = &matrix->data_[numcols * i];
+ }
+
+ return 0;
+}
+
+void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val)
+{
+ 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_seq2d_input(FILE *in)
+{
+ jas_matrix_t *matrix;
+ int i;
+ int j;
+ long x;
+ int numrows;
+ int numcols;
+ int xoff;
+ int yoff;
+
+ if (fscanf(in, "%d %d", &xoff, &yoff) != 2)
+ return 0;
+ if (fscanf(in, "%d %d", &numcols, &numrows) != 2)
+ return 0;
+ if (!(matrix = jas_seq2d_create(xoff, yoff, xoff + numcols, yoff + numrows)))
+ return 0;
+
+ if (jas_matrix_numrows(matrix) != numrows || jas_matrix_numcols(matrix) != numcols) {
+ abort();
+ }
+
+ /* 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;
+}
+
+int jas_seq2d_output(jas_matrix_t *matrix, FILE *out)
+{
+#define MAXLINELEN 80
+ int i;
+ int j;
+ jas_seqent_t x;
+ char buf[MAXLINELEN + 1];
+ char sbuf[MAXLINELEN + 1];
+ int n;
+
+ fprintf(out, "%d %d\n", jas_seq2d_xstart(matrix),
+ jas_seq2d_ystart(matrix));
+ fprintf(out, "%d %d\n", jas_matrix_numcols(matrix),
+ jas_matrix_numrows(matrix));
+
+ buf[0] = '\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);
+ sprintf(sbuf, "%s%4ld", (strlen(buf) > 0) ? " " : "",
+ JAS_CAST(long, x));
+ n = strlen(buf);
+ if (n + strlen(sbuf) > MAXLINELEN) {
+ fputs(buf, out);
+ fputs("\n", out);
+ buf[0] = '\0';
+ }
+ strcat(buf, sbuf);
+ if (j == jas_matrix_numcols(matrix) - 1) {
+ fputs(buf, out);
+ fputs("\n", out);
+ buf[0] = '\0';
+ }
+ }
+ }
+ fputs(buf, out);
+
+ return 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/base/jas_stream.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_stream.c
new file mode 100644
index 0000000..9a88556
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_stream.c
@@ -0,0 +1,1150 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * I/O Stream Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+#if defined(HAVE_FCNTL_H)
+#include <fcntl.h>
+#endif
+#include <stdlib.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <ctype.h>
+#if defined(HAVE_UNISTD_H)
+#include <unistd.h>
+#endif
+#if defined(WIN32) || defined(HAVE_IO_H)
+#include <io.h>
+#endif
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+
+/******************************************************************************\
+* Local function prototypes.
+\******************************************************************************/
+
+static int jas_strtoopenmode(const char *s);
+static void jas_stream_destroy(jas_stream_t *stream);
+static jas_stream_t *jas_stream_create(void);
+static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf,
+ int bufsize);
+
+static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt);
+static int mem_write(jas_stream_obj_t *obj, char *buf, int cnt);
+static long mem_seek(jas_stream_obj_t *obj, long offset, int origin);
+static int mem_close(jas_stream_obj_t *obj);
+
+static int sfile_read(jas_stream_obj_t *obj, char *buf, int cnt);
+static int sfile_write(jas_stream_obj_t *obj, char *buf, int cnt);
+static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin);
+static int sfile_close(jas_stream_obj_t *obj);
+
+static int file_read(jas_stream_obj_t *obj, char *buf, int cnt);
+static int file_write(jas_stream_obj_t *obj, char *buf, int cnt);
+static long file_seek(jas_stream_obj_t *obj, long offset, int origin);
+static int file_close(jas_stream_obj_t *obj);
+
+/******************************************************************************\
+* Local data.
+\******************************************************************************/
+
+static jas_stream_ops_t jas_stream_fileops = {
+ file_read,
+ file_write,
+ file_seek,
+ file_close
+};
+
+static jas_stream_ops_t jas_stream_sfileops = {
+ sfile_read,
+ sfile_write,
+ sfile_seek,
+ sfile_close
+};
+
+static jas_stream_ops_t jas_stream_memops = {
+ mem_read,
+ mem_write,
+ mem_seek,
+ mem_close
+};
+
+/******************************************************************************\
+* Code for opening and closing streams.
+\******************************************************************************/
+
+static jas_stream_t *jas_stream_create()
+{
+ jas_stream_t *stream;
+
+ if (!(stream = jas_malloc(sizeof(jas_stream_t)))) {
+ return 0;
+ }
+ stream->openmode_ = 0;
+ stream->bufmode_ = 0;
+ stream->flags_ = 0;
+ stream->bufbase_ = 0;
+ stream->bufstart_ = 0;
+ stream->bufsize_ = 0;
+ stream->ptr_ = 0;
+ stream->cnt_ = 0;
+ stream->ops_ = 0;
+ stream->obj_ = 0;
+ stream->rwcnt_ = 0;
+ stream->rwlimit_ = -1;
+
+ return stream;
+}
+
+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 *jas_stream_fopen(const char *filename, const char *mode)
+{
+ jas_stream_t *stream;
+ jas_stream_fileobj_t *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(jas_stream_fileobj_t)))) {
+ jas_stream_destroy(stream);
+ return 0;
+ }
+ obj->fd = -1;
+ obj->flags = 0;
+ obj->pathname[0] = '\0';
+ stream->obj_ = (void *) obj;
+
+ /* Select the operations for a file stream object. */
+ stream->ops_ = &jas_stream_fileops;
+
+ /* Open the underlying file. */
+ if ((obj->fd = 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;
+
+ /* Eliminate compiler warning about unused variable. */
+ path = 0;
+
+ /* 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;
+ jas_stream_fileobj_t *obj;
+
+ if (!(stream = jas_stream_create())) {
+ return 0;
+ }
+
+ /* A temporary file stream is always opened for both reading and
+ writing in binary mode. */
+ stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY;
+
+ /* Allocate memory for the underlying temporary file object. */
+ if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) {
+ jas_stream_destroy(stream);
+ return 0;
+ }
+ obj->fd = -1;
+ obj->flags = 0;
+ obj->pathname[0] = '\0';
+ stream->obj_ = obj;
+
+ /* Choose a file name. */
+ tmpnam(obj->pathname);
+
+ /* Open the underlying file. */
+ if ((obj->fd = open(obj->pathname, O_CREAT | O_EXCL | O_RDWR | O_TRUNC | O_BINARY,
+ JAS_STREAM_PERMS)) < 0) {
+ jas_stream_destroy(stream);
+ return 0;
+ }
+
+ /* Unlink the file so that it will disappear if the program
+ terminates abnormally. */
+ /* Under UNIX, one can unlink an open file and continue to do I/O
+ on it. Not all operating systems support this functionality, however.
+ For example, under Microsoft Windows the unlink operation will fail,
+ since the file is open. */
+ if (unlink(obj->pathname)) {
+ /* We will try unlinking the file again after it is closed. */
+ obj->flags |= JAS_STREAM_FILEOBJ_DELONCLOSE;
+ }
+
+ /* Use full buffering. */
+ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
+
+ stream->ops_ = &jas_stream_fileops;
+
+ return stream;
+}
+
+jas_stream_t *jas_stream_fdopen(int fd, const char *mode)
+{
+ jas_stream_t *stream;
+ jas_stream_fileobj_t *obj;
+
+ /* Allocate a stream object. */
+ if (!(stream = jas_stream_create())) {
+ return 0;
+ }
+
+ /* Parse the mode string. */
+ stream->openmode_ = jas_strtoopenmode(mode);
+
+#if defined(WIN32)
+ /* Argh!!! Someone ought to banish text mode (i.e., O_TEXT) to the
+ greatest depths of purgatory! */
+ /* Ensure that the file descriptor is in binary mode, if the caller
+ has specified the binary mode flag. Arguably, the caller ought to
+ take care of this, but text mode is a ugly wart anyways, so we save
+ the caller some grief by handling this within the stream library. */
+ /* This ugliness is mainly for the benefit of those who run the
+ JasPer software under Windows from shells that insist on opening
+ files in text mode. For example, in the Cygwin environment,
+ shells often open files in text mode when I/O redirection is
+ used. Grr... */
+ if (stream->openmode_ & JAS_STREAM_BINARY) {
+ setmode(fd, O_BINARY);
+ }
+#endif
+
+ /* Allocate space for the underlying file stream object. */
+ if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) {
+ jas_stream_destroy(stream);
+ return 0;
+ }
+ obj->fd = fd;
+ obj->flags = 0;
+ obj->pathname[0] = '\0';
+ stream->obj_ = (void *) obj;
+
+ /* Do not close the underlying file descriptor when the stream is
+ closed. */
+ obj->flags |= JAS_STREAM_FILEOBJ_NOCLOSE;
+
+ /* By default, use full buffering for this type of stream. */
+ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0);
+
+ /* Select the operations for a file stream object. */
+ stream->ops_ = &jas_stream_fileops;
+
+ return stream;
+}
+
+static void jas_stream_destroy(jas_stream_t *stream)
+{
+ /* 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);
+
+ /* Close the underlying stream object. */
+ (*stream->ops_->close_)(stream->obj_);
+
+ jas_stream_destroy(stream);
+
+ return 0;
+}
+
+/******************************************************************************\
+* Code for reading and writing streams.
+\******************************************************************************/
+
+int jas_stream_getc_func(jas_stream_t *stream)
+{
+ assert(stream->ptr_ - stream->bufbase_ <= stream->bufsize_ +
+ JAS_STREAM_MAXPUTBACK);
+ return jas_stream_getc_macro(stream);
+}
+
+int jas_stream_putc_func(jas_stream_t *stream, int c)
+{
+ assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_);
+ return jas_stream_putc_macro(stream, c);
+}
+
+int jas_stream_ungetc(jas_stream_t *stream, int c)
+{
+ if (!stream->ptr_ || stream->ptr_ == stream->bufbase_) {
+ return -1;
+ }
+
+ /* Reset the EOF indicator (since we now have at least one character
+ to read). */
+ stream->flags_ &= ~JAS_STREAM_EOF;
+
+ --stream->rwcnt_;
+ --stream->ptr_;
+ ++stream->cnt_;
+ *stream->ptr_ = c;
+ return 0;
+}
+
+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 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;
+ }
+
+ return n;
+}
+
+/* Note: This function uses a fixed size buffer. Therefore, it cannot
+ handle invocations that will produce more output than can be held
+ by the buffer. */
+int jas_stream_printf(jas_stream_t *stream, const char *fmt, ...)
+{
+ va_list ap;
+ char buf[4096];
+ int ret;
+
+ va_start(ap, fmt);
+ ret = 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;
+}
+
+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 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 jas_stream_pad(jas_stream_t *stream, int n, int c)
+{
+ int m;
+ m = n;
+ for (m = n; m > 0; --m) {
+ if (jas_stream_putc(stream, c) == EOF)
+ return n - m;
+ }
+ return n;
+}
+
+/******************************************************************************\
+* Code for getting and setting the stream position.
+\******************************************************************************/
+
+int jas_stream_isseekable(jas_stream_t *stream)
+{
+ if (stream->ops_ == &jas_stream_memops) {
+ return 1;
+ } else if (stream->ops_ == &jas_stream_fileops) {
+ if ((*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR) < 0) {
+ return 0;
+ }
+ return 1;
+ } else {
+ return 0;
+ }
+}
+
+int jas_stream_rewind(jas_stream_t *stream)
+{
+ 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 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;
+}
+
+/******************************************************************************\
+* Buffer initialization code.
+\******************************************************************************/
+
+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(uchar *, buf);
+ stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK;
+ }
+ } else {
+ /* The unbuffered mode is being employed. */
+ /* A buffer should not have been supplied by the caller. */
+ assert(!buf);
+ /* Use a trivial one-character buffer. */
+ stream->bufbase_ = stream->tinybuf_;
+ stream->bufsize_ = 1;
+ }
+ stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK];
+ stream->ptr_ = stream->bufstart_;
+ stream->cnt_ = 0;
+ stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK;
+}
+
+/******************************************************************************\
+* Buffer filling and flushing code.
+\******************************************************************************/
+
+int jas_stream_flush(jas_stream_t *stream)
+{
+ if (stream->bufmode_ & JAS_STREAM_RDBUF) {
+ return 0;
+ }
+ return jas_stream_flushbuf(stream, EOF);
+}
+
+int jas_stream_fillbuf(jas_stream_t *stream, int getflag)
+{
+ int c;
+
+ /* The stream must not be in an error or EOF state. */
+ if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) {
+ return EOF;
+ }
+
+ /* The stream must be open for reading. */
+ if ((stream->openmode_ & JAS_STREAM_READ) == 0) {
+ return EOF;
+ }
+
+ /* Make a half-hearted attempt to confirm that the buffer is not
+ currently being used for writing. This check is not intended
+ to be foolproof! */
+ assert((stream->bufmode_ & JAS_STREAM_WRBUF) == 0);
+
+ assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_);
+
+ /* Mark the buffer as being used for reading. */
+ stream->bufmode_ |= JAS_STREAM_RDBUF;
+
+ /* Read new data into the buffer. */
+ stream->ptr_ = stream->bufstart_;
+ if ((stream->cnt_ = (*stream->ops_->read_)(stream->obj_,
+ (char *) stream->bufstart_, stream->bufsize_)) <= 0) {
+ if (stream->cnt_ < 0) {
+ stream->flags_ |= JAS_STREAM_ERR;
+ } else {
+ stream->flags_ |= JAS_STREAM_EOF;
+ }
+ stream->cnt_ = 0;
+ return EOF;
+ }
+
+ assert(stream->cnt_ > 0);
+ /* Get or peek at the first character in the buffer. */
+ c = (getflag) ? jas_stream_getc2(stream) : (*stream->ptr_);
+
+ return c;
+}
+
+int jas_stream_flushbuf(jas_stream_t *stream, int c)
+{
+ int len;
+ int n;
+
+ /* The stream should not be in an error or EOF state. */
+ if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) {
+ return EOF;
+ }
+
+ /* The stream must be open for writing. */
+ if ((stream->openmode_ & (JAS_STREAM_WRITE | JAS_STREAM_APPEND)) == 0) {
+ return EOF;
+ }
+
+ /* The buffer should not currently be in use for reading. */
+ assert(!(stream->bufmode_ & JAS_STREAM_RDBUF));
+
+ /* Note: Do not use the quantity stream->cnt to determine the number
+ of characters in the buffer! Depending on how this function was
+ called, the stream->cnt value may be "off-by-one". */
+ len = stream->ptr_ - stream->bufstart_;
+ if (len > 0) {
+ n = (*stream->ops_->write_)(stream->obj_, (char *)
+ stream->bufstart_, len);
+ if (n != len) {
+ stream->flags_ |= JAS_STREAM_ERR;
+ return EOF;
+ }
+ }
+ stream->cnt_ = stream->bufsize_;
+ stream->ptr_ = stream->bufstart_;
+
+ stream->bufmode_ |= JAS_STREAM_WRBUF;
+
+ if (c != EOF) {
+ assert(stream->cnt_ > 0);
+ return jas_stream_putc2(stream, c);
+ }
+
+ return 0;
+}
+
+/******************************************************************************\
+* Miscellaneous code.
+\******************************************************************************/
+
+static int jas_strtoopenmode(const char *s)
+{
+ int openmode = 0;
+ while (*s != '\0') {
+ switch (*s) {
+ case 'r':
+ openmode |= JAS_STREAM_READ;
+ break;
+ case 'w':
+ openmode |= JAS_STREAM_WRITE | JAS_STREAM_CREATE;
+ break;
+ case 'b':
+ openmode |= JAS_STREAM_BINARY;
+ break;
+ case 'a':
+ openmode |= JAS_STREAM_APPEND;
+ break;
+ case '+':
+ openmode |= JAS_STREAM_READ | JAS_STREAM_WRITE;
+ break;
+ default:
+ break;
+ }
+ ++s;
+ }
+ return openmode;
+}
+
+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 occured
+ (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;
+
+ 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;
+}
+
+long jas_stream_length(jas_stream_t *stream)
+{
+ long oldpos;
+ long pos;
+ if ((oldpos = jas_stream_tell(stream)) < 0) {
+ return -1;
+ }
+ if (jas_stream_seek(stream, 0, SEEK_END) < 0) {
+ return -1;
+ }
+ if ((pos = jas_stream_tell(stream)) < 0) {
+ return -1;
+ }
+ if (jas_stream_seek(stream, oldpos, SEEK_SET) < 0) {
+ return -1;
+ }
+ return pos;
+}
+
+/******************************************************************************\
+* Memory stream object.
+\******************************************************************************/
+
+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;
+}
+
+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;
+}
+
+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_;
+ }
+assert(ret == cnt);
+ 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_;
+}
+
+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;
+}
+
+/******************************************************************************\
+* File stream object.
+\******************************************************************************/
+
+static int file_read(jas_stream_obj_t *obj, char *buf, int cnt)
+{
+ jas_stream_fileobj_t *fileobj = JAS_CAST(jas_stream_fileobj_t *, obj);
+ return read(fileobj->fd, buf, cnt);
+}
+
+static int file_write(jas_stream_obj_t *obj, char *buf, int cnt)
+{
+ jas_stream_fileobj_t *fileobj = JAS_CAST(jas_stream_fileobj_t *, obj);
+ return write(fileobj->fd, buf, cnt);
+}
+
+static long file_seek(jas_stream_obj_t *obj, long offset, int origin)
+{
+ jas_stream_fileobj_t *fileobj = JAS_CAST(jas_stream_fileobj_t *, obj);
+ return lseek(fileobj->fd, offset, origin);
+}
+
+static int file_close(jas_stream_obj_t *obj)
+{
+ jas_stream_fileobj_t *fileobj = JAS_CAST(jas_stream_fileobj_t *, obj);
+ int ret;
+ ret = close(fileobj->fd);
+ if (fileobj->flags & JAS_STREAM_FILEOBJ_DELONCLOSE) {
+ unlink(fileobj->pathname);
+ }
+ jas_free(fileobj);
+ return ret;
+}
+
+/******************************************************************************\
+* Stdio file stream object.
+\******************************************************************************/
+
+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);
+}
+
+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);
+}
+
+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);
+}
+
+static int sfile_close(jas_stream_obj_t *obj)
+{
+ FILE *fp;
+ fp = JAS_CAST(FILE *, obj);
+ return fclose(fp);
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/base/jas_string.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_string.c
new file mode 100644
index 0000000..f3306b9
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_string.c
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * String Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+#include <string.h>
+
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_string.h"
+
+/******************************************************************************\
+* Miscellaneous Functions
+\******************************************************************************/
+
+/* This function is equivalent to the popular but non-standard (and
+ not-always-available) strdup function. */
+
+char *jas_strdup(const char *s)
+{
+ 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/jasper-1.900.1-6ct/src/libjasper/base/jas_tmr.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_tmr.c
new file mode 100644
index 0000000..babb9fd
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_tmr.c
@@ -0,0 +1,149 @@
+/*
+ * Copyright (c) 2004 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Timing Routines
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+
+#include "jasper/jas_tmr.h"
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+#if defined(HAVE_GETTIMEOFDAY)
+
+void jas_tmr_start(jas_tmr_t *tmr)
+{
+ if (gettimeofday(&tmr->start, 0)) {
+ abort();
+ }
+}
+
+void jas_tmr_stop(jas_tmr_t *tmr)
+{
+ if (gettimeofday(&tmr->stop, 0)) {
+ abort();
+ }
+}
+
+double jas_tmr_get(jas_tmr_t *tmr)
+{
+ double t0;
+ double t1;
+ t0 = ((double) tmr->start.tv_sec) + ((double) tmr->start.tv_usec) / 1e6;
+ t1 = ((double) tmr->stop.tv_sec) + ((double) tmr->stop.tv_usec) / 1e6;
+ return t1 - t0;
+}
+
+#elif defined(HAVE_GETRUSAGE)
+
+void jas_tmr_start(jas_tmr_t *tmr)
+{
+ if (getrusage(RUSAGE_SELF, &tmr->start) < 0) {
+ abort();
+ }
+}
+
+void jas_tmr_stop(jas_tmr_t *tmr)
+{
+ if (getrusage(RUSAGE_SELF, &tmr->stop) < 0) {
+ abort();
+ }
+}
+
+double jas_tmr_get(jas_tmr_t *tmr)
+{
+ double t;
+ t = ((tmr->stop.ru_utime.tv_sec * 1e6 + tmr->stop.ru_utime.tv_usec) -
+ (tmr->start.ru_utime.tv_sec * 1e6 + tmr->start.ru_utime.tv_usec)) / 1e6;
+ t += ((tmr->stop.ru_stime.tv_sec * 1e6 + tmr->stop.ru_stime.tv_usec) -
+ (tmr->start.ru_stime.tv_sec * 1e6 + tmr->start.ru_stime.tv_usec)) / 1e6;
+ return t;
+}
+
+#else
+
+void jas_tmr_start(jas_tmr_t *tmr)
+{
+}
+
+void jas_tmr_stop(jas_tmr_t *tmr)
+{
+}
+
+double jas_tmr_get(jas_tmr_t *tmr)
+{
+ return 0.0;
+}
+
+#endif
+
diff --git a/jasper-1.900.1-6ct/src/libjasper/base/jas_tvp.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_tvp.c
new file mode 100644
index 0000000..c005acf
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_tvp.c
@@ -0,0 +1,237 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tag-Value Parser Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+#include <stdio.h>
+#include <ctype.h>
+#include <stdlib.h>
+
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_string.h"
+#include "jasper/jas_tvp.h"
+
+/******************************************************************************\
+* Macros.
+\******************************************************************************/
+
+/* Is the specified character valid for a tag name? */
+#define JAS_TVP_ISTAG(x) \
+ (isalpha(x) || (x) == '_' || isdigit(x))
+
+/******************************************************************************\
+* Code for creating and destroying a tag-value parser.
+\******************************************************************************/
+
+jas_tvparser_t *jas_tvparser_create(const char *s)
+{
+ jas_tvparser_t *tvp;
+ if (!(tvp = jas_malloc(sizeof(jas_tvparser_t)))) {
+ return 0;
+ }
+ if (!(tvp->buf = jas_strdup(s))) {
+ jas_tvparser_destroy(tvp);
+ return 0;
+ }
+ tvp->pos = tvp->buf;
+ tvp->tag = 0;
+ tvp->val = 0;
+ return tvp;
+}
+
+void jas_tvparser_destroy(jas_tvparser_t *tvp)
+{
+ if (tvp->buf) {
+ jas_free(tvp->buf);
+ }
+ jas_free(tvp);
+}
+
+/******************************************************************************\
+* Main parsing code.
+\******************************************************************************/
+
+/* Get the next tag-value pair. */
+int jas_tvparser_next(jas_tvparser_t *tvp)
+{
+ char *p;
+ char *tag;
+ char *val;
+
+ /* Skip any leading whitespace. */
+ p = tvp->pos;
+ while (*p != '\0' && isspace(*p)) {
+ ++p;
+ }
+
+ /* Has the end of the input data been reached? */
+ if (*p == '\0') {
+ /* No more tags are present. */
+ tvp->pos = p;
+ return 1;
+ }
+
+ /* Does the tag name begin with a valid character? */
+ if (!JAS_TVP_ISTAG(*p)) {
+ return -1;
+ }
+
+ /* Remember where the tag name begins. */
+ tag = 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;
+ }
+
+ /* 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';
+
+ val = p;
+ while (*p != '\0' && !isspace(*p)) {
+ ++p;
+ }
+
+ if (*p != '\0') {
+ *p++ = '\0';
+ }
+
+ tvp->pos = p;
+ tvp->tag = tag;
+ tvp->val = val;
+
+ return 0;
+}
+
+/******************************************************************************\
+* Code for querying the current tag/value.
+\******************************************************************************/
+
+/* Get the current tag. */
+char *jas_tvparser_gettag(jas_tvparser_t *tvp)
+{
+ return tvp->tag;
+}
+
+/* Get the current value. */
+char *jas_tvparser_getval(jas_tvparser_t *tvp)
+{
+ return tvp->val;
+}
+
+/******************************************************************************\
+* Miscellaneous code.
+\******************************************************************************/
+
+/* 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;
+}
+
+/* This function is simply for convenience. */
+/* One can avoid testing for the special case of a null pointer, by
+ using this function. This function never returns a null pointer. */
+jas_taginfo_t *jas_taginfo_nonull(jas_taginfo_t *taginfo)
+{
+ static jas_taginfo_t invalidtaginfo = {
+ -1, 0
+ };
+
+ return taginfo ? taginfo : &invalidtaginfo;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/base/jas_version.c b/jasper-1.900.1-6ct/src/libjasper/base/jas_version.c
new file mode 100644
index 0000000..f56f253
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/base/jas_version.c
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#include "jasper/jas_version.h"
+
+const char *jas_getversion()
+{
+ return JAS_VERSION;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/bmp/Makefile.am b/jasper-1.900.1-6ct/src/libjasper/bmp/Makefile.am
new file mode 100644
index 0000000..d70855a
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/bmp/Makefile.am
@@ -0,0 +1,67 @@
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+noinst_LTLIBRARIES = libbmp.la
+libbmp_la_SOURCES = \
+ bmp_cod.h \
+ bmp_enc.h \
+ bmp_cod.c \
+ bmp_dec.c \
+ bmp_enc.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
diff --git a/jasper-1.900.1-6ct/src/libjasper/bmp/Makefile.in b/jasper-1.900.1-6ct/src/libjasper/bmp/Makefile.in
new file mode 100644
index 0000000..a8297a6
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/bmp/Makefile.in
@@ -0,0 +1,510 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src/libjasper/bmp
+DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+LTLIBRARIES = $(noinst_LTLIBRARIES)
+libbmp_la_LIBADD =
+am_libbmp_la_OBJECTS = bmp_cod.lo bmp_dec.lo bmp_enc.lo
+libbmp_la_OBJECTS = $(am_libbmp_la_OBJECTS)
+DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/src/libjasper/include/jasper
+depcomp = $(SHELL) $(top_srcdir)/acaux/depcomp
+am__depfiles_maybe = depfiles
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LTCOMPILE = $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) \
+ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+ $(AM_CFLAGS) $(CFLAGS)
+CCLD = $(CC)
+LINK = $(LIBTOOL) --tag=CC --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+ $(AM_LDFLAGS) $(LDFLAGS) -o $@
+SOURCES = $(libbmp_la_SOURCES)
+DIST_SOURCES = $(libbmp_la_SOURCES)
+ETAGS = etags
+CTAGS = ctags
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+noinst_LTLIBRARIES = libbmp.la
+libbmp_la_SOURCES = \
+ bmp_cod.h \
+ bmp_enc.h \
+ bmp_cod.c \
+ bmp_dec.c \
+ bmp_enc.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
+all: all-am
+
+.SUFFIXES:
+.SUFFIXES: .c .lo .o .obj
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libjasper/bmp/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/libjasper/bmp/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+clean-noinstLTLIBRARIES:
+ -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
+ @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \
+ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
+ test "$$dir" != "$$p" || dir=.; \
+ echo "rm -f \"$${dir}/so_locations\""; \
+ rm -f "$${dir}/so_locations"; \
+ done
+libbmp.la: $(libbmp_la_OBJECTS) $(libbmp_la_DEPENDENCIES)
+ $(LINK) $(libbmp_la_LDFLAGS) $(libbmp_la_OBJECTS) $(libbmp_la_LIBADD) $(LIBS)
+
+mostlyclean-compile:
+ -rm -f *.$(OBJEXT)
+
+distclean-compile:
+ -rm -f *.tab.c
+
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/bmp_cod.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/bmp_dec.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/bmp_enc.Plo at am__quote@
+
+.c.o:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c $<
+
+.c.obj:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
+
+.c.lo:
+ at am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $<
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-am
+all-am: Makefile $(LTLIBRARIES)
+installdirs:
+install: install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-am
+
+clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \
+ mostlyclean-am
+
+distclean: distclean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+distclean-am: clean-am distclean-compile distclean-generic \
+ distclean-libtool distclean-tags
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+info: info-am
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-am
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-compile mostlyclean-generic \
+ mostlyclean-libtool
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
+ clean-libtool clean-noinstLTLIBRARIES ctags distclean \
+ distclean-compile distclean-generic distclean-libtool \
+ distclean-tags distdir dvi dvi-am html html-am info info-am \
+ install install-am install-data install-data-am install-exec \
+ install-exec-am install-info install-info-am install-man \
+ install-strip installcheck installcheck-am installdirs \
+ maintainer-clean maintainer-clean-generic mostlyclean \
+ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
+ pdf pdf-am ps ps-am tags uninstall uninstall-am \
+ uninstall-info-am
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_cod.c b/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_cod.c
new file mode 100644
index 0000000..4e84ecc
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_cod.c
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Windows Bitmap File Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_malloc.h"
+
+#include "bmp_cod.h"
+
+/******************************************************************************\
+* Constructors and destructors.
+\******************************************************************************/
+
+bmp_info_t *bmp_info_create()
+{
+ bmp_info_t *info;
+ if (!(info = jas_malloc(sizeof(bmp_info_t)))) {
+ return 0;
+ }
+ info->palents = 0;
+ return info;
+}
+
+void bmp_info_destroy(bmp_info_t *info)
+{
+ if (info->palents) {
+ jas_free(info->palents);
+ }
+ jas_free(info);
+}
+
+/******************************************************************************\
+* Miscellaneous functions.
+\******************************************************************************/
+
+int bmp_isgrayscalepal(bmp_palent_t *palents, int numpalents)
+{
+ bmp_palent_t *palent;
+ int i;
+
+ for (i = numpalents, palent = palents; i > 0; --i, ++palent) {
+ if (palent->red != palent->grn || palent->red != palent->blu) {
+ return 0;
+ }
+ }
+ return 1;
+}
+
+int bmp_numcmpts(bmp_info_t *info)
+{
+ int numcmpts;
+
+ if (info->depth == 24) {
+ numcmpts = 3;
+ } else if (info->depth == 8) {
+ numcmpts = bmp_isgrayscalepal(info->palents, info->numcolors) ?
+ 1 : 3;
+ } else {
+ numcmpts = 0;
+ abort();
+ }
+ return numcmpts;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_cod.h b/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_cod.h
new file mode 100644
index 0000000..beaaf30
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_cod.h
@@ -0,0 +1,215 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Windows Bitmap File Library
+ *
+ * $Id$
+ */
+
+#ifndef BMP_COD_H
+#define BMP_COD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+
+/******************************************************************************\
+* Constants and macros.
+\******************************************************************************/
+
+#define BMP_MAGIC 0x4d42
+/* The signature for a BMP file. */
+
+#define BMP_HDRLEN 14
+/* The nominal header length. */
+
+#define BMP_INFOLEN 40
+/* The nominal info length. */
+
+#define BMP_PALLEN(info) ((info)->numcolors * 4)
+/* The length of the palette. */
+
+#define BMP_HASPAL(info) ((info)->numcolors > 0)
+/* Is this a palettized image? */
+
+/* Encoding types. */
+#define BMP_ENC_RGB 0 /* No special encoding. */
+#define BMP_ENC_RLE8 1 /* Run length encoding. */
+#define BMP_ENC_RLE4 2 /* Run length encoding. */
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* BMP header. */
+typedef struct {
+
+ int_fast16_t magic;
+ /* The signature (a.k.a. the magic number). */
+
+ int_fast32_t siz;
+ /* The size of the file in 32-bit words. */
+
+ int_fast16_t reserved1;
+ /* Ask Bill Gates what this is all about. */
+
+ int_fast16_t reserved2;
+ /* Ditto. */
+
+ int_fast32_t off;
+ /* The offset of the bitmap data from the bitmap file header in bytes. */
+
+} bmp_hdr_t;
+
+/* Palette entry. */
+typedef struct {
+
+ int_fast16_t red;
+ /* The red component. */
+
+ int_fast16_t grn;
+ /* The green component. */
+
+ int_fast16_t blu;
+ /* The blue component. */
+
+ int_fast16_t res;
+ /* Reserved. */
+
+} bmp_palent_t;
+
+/* BMP info. */
+typedef struct {
+
+ int_fast32_t len;
+ /* The length of the bitmap information header in bytes. */
+
+ int_fast32_t width;
+ /* The width of the bitmap in pixels. */
+
+ int_fast32_t height;
+ /* The height of the bitmap in pixels. */
+
+ int_fast8_t topdown;
+ /* The bitmap data is specified in top-down order. */
+
+ int_fast16_t numplanes;
+ /* The number of planes. This must be set to a value of one. */
+
+ int_fast16_t depth;
+ /* The number of bits per pixel. */
+
+ int_fast32_t enctype;
+ /* The type of compression used. */
+
+ int_fast32_t siz;
+ /* The size of the image in bytes. */
+
+ int_fast32_t hres;
+ /* The horizontal resolution in pixels/metre. */
+
+ int_fast32_t vres;
+ /* The vertical resolution in pixels/metre. */
+
+ int_fast32_t numcolors;
+ /* The number of color indices used by the bitmap. */
+
+ int_fast32_t mincolors;
+ /* The number of color indices important for displaying the bitmap. */
+
+ bmp_palent_t *palents;
+ /* The colors should be listed in order of importance. */
+
+} bmp_info_t;
+
+/******************************************************************************\
+* Functions and macros.
+\******************************************************************************/
+
+#define bmp_issupported(hdr, info) \
+ ((hdr)->magic == BMP_MAGIC && !(hdr)->reserved1 && \
+ !(hdr)->reserved2 && (info)->numplanes == 1 && \
+ ((info)->depth == 8 || (info)->depth == 24) && \
+ (info)->enctype == BMP_ENC_RGB)
+/* Is this type of BMP file supported? */
+
+#define bmp_haspal(info) \
+ ((info)->depth == 8)
+/* Is there a palette? */
+
+int bmp_numcmpts(bmp_info_t *info);
+/* Get the number of components. */
+
+bmp_info_t *bmp_info_create(void);
+/* Create BMP information. */
+
+void bmp_info_destroy(bmp_info_t *info);
+/* Destroy BMP information. */
+
+int bmp_isgrayscalepal(bmp_palent_t *palents, int numpalents);
+/* Does the specified palette correspond to a grayscale image? */
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_dec.c b/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_dec.c
new file mode 100644
index 0000000..88dc968
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_dec.c
@@ -0,0 +1,464 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Windows Bitmap File Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.h"
+
+#include "bmp_cod.h"
+
+/******************************************************************************\
+* Local prototypes.
+\******************************************************************************/
+
+static int bmp_gethdr(jas_stream_t *in, bmp_hdr_t *hdr);
+static bmp_info_t *bmp_getinfo(jas_stream_t *in);
+static int bmp_getdata(jas_stream_t *in, bmp_info_t *info, jas_image_t *image);
+static int bmp_getint16(jas_stream_t *in, int_fast16_t *val);
+static int bmp_getint32(jas_stream_t *in, int_fast32_t *val);
+static int bmp_gobble(jas_stream_t *in, long n);
+
+/******************************************************************************\
+* Interface functions.
+\******************************************************************************/
+
+jas_image_t *bmp_decode(jas_stream_t *in, char *optstr)
+{
+ jas_image_t *image;
+ bmp_hdr_t hdr;
+ bmp_info_t *info;
+ uint_fast16_t cmptno;
+ jas_image_cmptparm_t cmptparms[3];
+ jas_image_cmptparm_t *cmptparm;
+ uint_fast16_t numcmpts;
+ long n;
+
+ if (optstr) {
+ jas_eprintf("warning: ignoring BMP decoder options\n");
+ }
+
+ jas_eprintf(
+ "THE BMP FORMAT IS NOT FULLY SUPPORTED!\n"
+ "THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n"
+ "IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n"
+ "TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n"
+ );
+
+ /* Read the bitmap header. */
+ if (bmp_gethdr(in, &hdr)) {
+ jas_eprintf("cannot get header\n");
+ return 0;
+ }
+
+ /* Read the bitmap information. */
+ if (!(info = bmp_getinfo(in))) {
+ jas_eprintf("cannot get info\n");
+ return 0;
+ }
+
+ /* Ensure that we support this type of BMP file. */
+ if (!bmp_issupported(&hdr, info)) {
+ jas_eprintf("error: unsupported BMP encoding\n");
+ bmp_info_destroy(info);
+ return 0;
+ }
+
+ /* Skip over any useless data between the end of the palette
+ and start of the bitmap data. */
+ if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) {
+ jas_eprintf("error: possibly bad bitmap offset?\n");
+ return 0;
+ }
+ if (n > 0) {
+ jas_eprintf("skipping unknown data in BMP file\n");
+ if (bmp_gobble(in, n)) {
+ bmp_info_destroy(info);
+ return 0;
+ }
+ }
+
+ /* Get the number of components. */
+ numcmpts = bmp_numcmpts(info);
+
+ for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
+ ++cmptparm) {
+ cmptparm->tlx = 0;
+ cmptparm->tly = 0;
+ cmptparm->hstep = 1;
+ cmptparm->vstep = 1;
+ cmptparm->width = info->width;
+ cmptparm->height = info->height;
+ cmptparm->prec = 8;
+ cmptparm->sgnd = false;
+ }
+
+ /* Create image object. */
+ if (!(image = jas_image_create(numcmpts, cmptparms,
+ JAS_CLRSPC_UNKNOWN))) {
+ bmp_info_destroy(info);
+ return 0;
+ }
+
+ if (numcmpts == 3) {
+ jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
+ jas_image_setcmpttype(image, 0,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
+ jas_image_setcmpttype(image, 1,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
+ jas_image_setcmpttype(image, 2,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
+ } else {
+ jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
+ jas_image_setcmpttype(image, 0,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
+ }
+
+ /* Read the bitmap data. */
+ if (bmp_getdata(in, info, image)) {
+ bmp_info_destroy(info);
+ jas_image_destroy(image);
+ return 0;
+ }
+
+ bmp_info_destroy(info);
+
+ return image;
+}
+
+int bmp_validate(jas_stream_t *in)
+{
+ int n;
+ int i;
+ uchar buf[2];
+
+ assert(JAS_STREAM_MAXPUTBACK >= 2);
+
+ /* Read the first two characters that constitute the signature. */
+ if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) {
+ return -1;
+ }
+ /* Put the characters read back onto the stream. */
+ for (i = n - 1; i >= 0; --i) {
+ if (jas_stream_ungetc(in, buf[i]) == EOF) {
+ return -1;
+ }
+ }
+ /* Did we read enough characters? */
+ if (n < 2) {
+ return -1;
+ }
+ /* Is the signature correct for the BMP format? */
+ if (buf[0] == (BMP_MAGIC & 0xff) && buf[1] == (BMP_MAGIC >> 8)) {
+ return 0;
+ }
+ return -1;
+}
+
+/******************************************************************************\
+* Code for aggregate types.
+\******************************************************************************/
+
+static int bmp_gethdr(jas_stream_t *in, bmp_hdr_t *hdr)
+{
+ if (bmp_getint16(in, &hdr->magic) || hdr->magic != BMP_MAGIC ||
+ bmp_getint32(in, &hdr->siz) || bmp_getint16(in, &hdr->reserved1) ||
+ bmp_getint16(in, &hdr->reserved2) || bmp_getint32(in, &hdr->off)) {
+ return -1;
+ }
+ return 0;
+}
+
+static bmp_info_t *bmp_getinfo(jas_stream_t *in)
+{
+ bmp_info_t *info;
+ int i;
+ bmp_palent_t *palent;
+
+ if (!(info = bmp_info_create())) {
+ return 0;
+ }
+
+ if (bmp_getint32(in, &info->len) || info->len != 40 ||
+ bmp_getint32(in, &info->width) || bmp_getint32(in, &info->height) ||
+ bmp_getint16(in, &info->numplanes) ||
+ bmp_getint16(in, &info->depth) || bmp_getint32(in, &info->enctype) ||
+ bmp_getint32(in, &info->siz) ||
+ bmp_getint32(in, &info->hres) || bmp_getint32(in, &info->vres) ||
+ bmp_getint32(in, &info->numcolors) ||
+ bmp_getint32(in, &info->mincolors)) {
+ bmp_info_destroy(info);
+ return 0;
+ }
+
+ if (info->height < 0) {
+ info->topdown = 1;
+ info->height = -info->height;
+ } else {
+ info->topdown = 0;
+ }
+
+ if (info->width <= 0 || info->height <= 0 || info->numplanes <= 0 ||
+ info->depth <= 0 || info->numcolors < 0 || info->mincolors < 0) {
+ bmp_info_destroy(info);
+ return 0;
+ }
+
+ if (info->enctype != BMP_ENC_RGB) {
+ jas_eprintf("unsupported BMP encoding\n");
+ bmp_info_destroy(info);
+ return 0;
+ }
+
+ if (info->numcolors > 0) {
+ if (!(info->palents = jas_malloc(info->numcolors *
+ sizeof(bmp_palent_t)))) {
+ bmp_info_destroy(info);
+ return 0;
+ }
+ } else {
+ info->palents = 0;
+ }
+
+ for (i = 0; i < info->numcolors; ++i) {
+ palent = &info->palents[i];
+ if ((palent->blu = jas_stream_getc(in)) == EOF ||
+ (palent->grn = jas_stream_getc(in)) == EOF ||
+ (palent->red = jas_stream_getc(in)) == EOF ||
+ (palent->res = jas_stream_getc(in)) == EOF) {
+ bmp_info_destroy(info);
+ return 0;
+ }
+ }
+
+ return info;
+}
+
+static int bmp_getdata(jas_stream_t *in, bmp_info_t *info, jas_image_t *image)
+{
+ int i;
+ int j;
+ int y;
+ jas_matrix_t *cmpts[3];
+ int numpad;
+ int red;
+ int grn;
+ int blu;
+ int ret;
+ int numcmpts;
+ int cmptno;
+ int ind;
+ bmp_palent_t *palent;
+ int mxind;
+ int haspal;
+
+ assert(info->depth == 8 || info->depth == 24);
+ assert(info->enctype == BMP_ENC_RGB);
+
+ numcmpts = bmp_numcmpts(info);
+ haspal = bmp_haspal(info);
+
+ ret = 0;
+ for (i = 0; i < numcmpts; ++i) {
+ cmpts[i] = 0;
+ }
+
+ /* Create temporary matrices to hold component data. */
+ for (i = 0; i < numcmpts; ++i) {
+ if (!(cmpts[i] = jas_matrix_create(1, info->width))) {
+ ret = -1;
+ goto bmp_getdata_done;
+ }
+ }
+
+ /* Calculate number of padding bytes per row of image data. */
+ numpad = (numcmpts * info->width) % 4;
+ if (numpad) {
+ numpad = 4 - numpad;
+ }
+
+ mxind = (1 << info->depth) - 1;
+ for (i = 0; i < info->height; ++i) {
+ for (j = 0; j < info->width; ++j) {
+ if (haspal) {
+ if ((ind = jas_stream_getc(in)) == EOF) {
+ ret = -1;
+ goto bmp_getdata_done;
+ }
+ if (ind > mxind) {
+ ret = -1;
+ goto bmp_getdata_done;
+ }
+ if (ind < info->numcolors) {
+ palent = &info->palents[ind];
+ red = palent->red;
+ grn = palent->grn;
+ blu = palent->blu;
+ } else {
+ red = ind;
+ grn = ind;
+ blu = ind;
+ }
+ } else {
+ if ((blu = jas_stream_getc(in)) == EOF ||
+ (grn = jas_stream_getc(in)) == EOF ||
+ (red = jas_stream_getc(in)) == EOF) {
+ ret = -1;
+ goto bmp_getdata_done;
+ }
+ }
+ if (numcmpts == 3) {
+ jas_matrix_setv(cmpts[0], j, red);
+ jas_matrix_setv(cmpts[1], j, grn);
+ jas_matrix_setv(cmpts[2], j, blu);
+ } else {
+ jas_matrix_setv(cmpts[0], j, red);
+ }
+ }
+ for (j = numpad; j > 0; --j) {
+ if (jas_stream_getc(in) == EOF) {
+ ret = -1;
+ goto bmp_getdata_done;
+ }
+ }
+ for (cmptno = 0; cmptno < numcmpts; ++cmptno) {
+ y = info->topdown ? i : (info->height - 1 - i);
+ if (jas_image_writecmpt(image, cmptno, 0, y, info->width,
+ 1, cmpts[cmptno])) {
+ ret = -1;
+ goto bmp_getdata_done;
+ }
+ }
+ }
+
+bmp_getdata_done:
+ /* Destroy the temporary matrices. */
+ for (i = 0; i < numcmpts; ++i) {
+ if (cmpts[i]) {
+ jas_matrix_destroy(cmpts[i]);
+ }
+ }
+
+ return ret;
+}
+
+/******************************************************************************\
+* Code for primitive types.
+\******************************************************************************/
+
+static int bmp_getint16(jas_stream_t *in, int_fast16_t *val)
+{
+ int lo;
+ int hi;
+ if ((lo = jas_stream_getc(in)) == EOF || (hi = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ if (val) {
+ *val = (hi << 8) | lo;
+ }
+ return 0;
+}
+
+static int bmp_getint32(jas_stream_t *in, int_fast32_t *val)
+{
+ int n;
+ uint_fast32_t v;
+ int c;
+ for (n = 4, v = 0;;) {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v |= (c << 24);
+ if (--n <= 0) {
+ break;
+ }
+ v >>= 8;
+ }
+ if (val) {
+ *val = v;
+ }
+ return 0;
+}
+
+static int bmp_gobble(jas_stream_t *in, long n)
+{
+ while (--n >= 0) {
+ if (jas_stream_getc(in) == EOF) {
+ return -1;
+ }
+ }
+ return 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_enc.c b/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_enc.c
new file mode 100644
index 0000000..26c658c
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_enc.c
@@ -0,0 +1,395 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Windows Bitmap File Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_debug.h"
+
+#include "bmp_enc.h"
+#include "bmp_cod.h"
+
+/******************************************************************************\
+* Local prototypes.
+\******************************************************************************/
+
+static int bmp_puthdr(jas_stream_t *out, bmp_hdr_t *hdr);
+static int bmp_putinfo(jas_stream_t *out, bmp_info_t *info);
+static int bmp_putdata(jas_stream_t *out, bmp_info_t *info, jas_image_t *image, int *cmpts);
+static int bmp_putint16(jas_stream_t *in, int_fast16_t val);
+static int bmp_putint32(jas_stream_t *out, int_fast32_t val);
+
+/******************************************************************************\
+* Interface functions.
+\******************************************************************************/
+
+int bmp_encode(jas_image_t *image, jas_stream_t *out, char *optstr)
+{
+ jas_image_coord_t width;
+ jas_image_coord_t height;
+ int depth;
+ int cmptno;
+ bmp_hdr_t hdr;
+ bmp_info_t *info;
+ int_fast32_t datalen;
+ int numpad;
+ bmp_enc_t encbuf;
+ bmp_enc_t *enc = &encbuf;
+ jas_clrspc_t clrspc;
+
+ if (optstr) {
+ jas_eprintf("warning: ignoring BMP encoder options\n");
+ }
+
+ clrspc = jas_image_clrspc(image);
+ switch (jas_clrspc_fam(clrspc)) {
+ case JAS_CLRSPC_FAM_RGB:
+ if (clrspc != JAS_CLRSPC_SRGB)
+ jas_eprintf("warning: inaccurate color\n");
+ break;
+ case JAS_CLRSPC_FAM_GRAY:
+ if (clrspc != JAS_CLRSPC_SGRAY)
+ jas_eprintf("warning: inaccurate color\n");
+ break;
+ default:
+ jas_eprintf("error: BMP format does not support color space\n");
+ return -1;
+ break;
+ }
+
+ switch (jas_clrspc_fam(clrspc)) {
+ case JAS_CLRSPC_FAM_RGB:
+ enc->numcmpts = 3;
+ if ((enc->cmpts[0] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R))) < 0 ||
+ (enc->cmpts[1] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G))) < 0 ||
+ (enc->cmpts[2] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))) < 0) {
+ jas_eprintf("error: missing color component\n");
+ return -1;
+ }
+ break;
+ case JAS_CLRSPC_FAM_GRAY:
+ enc->numcmpts = 1;
+ if ((enc->cmpts[0] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y))) < 0) {
+ jas_eprintf("error: missing color component\n");
+ return -1;
+ }
+ break;
+ default:
+ abort();
+ break;
+ }
+
+ width = jas_image_cmptwidth(image, enc->cmpts[0]);
+ height = jas_image_cmptheight(image, enc->cmpts[0]);
+ depth = jas_image_cmptprec(image, enc->cmpts[0]);
+
+ /* Check to ensure that the image to be saved can actually be represented
+ using the BMP format. */
+ for (cmptno = 0; cmptno < enc->numcmpts; ++cmptno) {
+ if (jas_image_cmptwidth(image, enc->cmpts[cmptno]) != width ||
+ jas_image_cmptheight(image, enc->cmpts[cmptno]) != height ||
+ jas_image_cmptprec(image, enc->cmpts[cmptno]) != depth ||
+ jas_image_cmptsgnd(image, enc->cmpts[cmptno]) != false ||
+ jas_image_cmpttlx(image, enc->cmpts[cmptno]) != 0 ||
+ jas_image_cmpttly(image, enc->cmpts[cmptno]) != 0) {
+ jas_eprintf("The BMP format cannot be used to represent an image with this geometry.\n");
+ return -1;
+ }
+ }
+
+ /* The component depths must be 1, 4, or 8. */
+ if (depth != 1 && depth != 4 && depth != 8) {
+ return -1;
+ }
+
+ numpad = (width * enc->numcmpts) % 4;
+ if (numpad) {
+ numpad = 4 - numpad;
+ }
+ datalen = (enc->numcmpts * width + numpad) * height;
+
+ if (!(info = bmp_info_create())) {
+ return -1;
+ }
+ info->len = BMP_INFOLEN;
+ info->width = width;
+ info->height = height;
+ info->numplanes = 1;
+ info->depth = enc->numcmpts * depth;
+ info->enctype = BMP_ENC_RGB;
+ info->siz = datalen;
+ info->hres = 0;
+ info->vres = 0;
+ info->numcolors = (enc->numcmpts == 1) ? 256 : 0;
+ info->mincolors = 0;
+
+ hdr.magic = BMP_MAGIC;
+ hdr.siz = BMP_HDRLEN + BMP_INFOLEN + 0 + datalen;
+ hdr.off = BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info);
+
+ /* Write the bitmap header. */
+ if (bmp_puthdr(out, &hdr)) {
+ return -1;
+ }
+
+ /* Write the bitmap information. */
+ if (bmp_putinfo(out, info)) {
+ return -1;
+ }
+
+ /* Write the bitmap data. */
+ if (bmp_putdata(out, info, image, enc->cmpts)) {
+ return -1;
+ }
+
+ bmp_info_destroy(info);
+
+ return 0;
+}
+
+/******************************************************************************\
+* Code for aggregate types.
+\******************************************************************************/
+
+static int bmp_puthdr(jas_stream_t *out, bmp_hdr_t *hdr)
+{
+ assert(hdr->magic == BMP_MAGIC);
+ if (bmp_putint16(out, hdr->magic) || bmp_putint32(out, hdr->siz) ||
+ bmp_putint32(out, 0) || bmp_putint32(out, hdr->off)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int bmp_putinfo(jas_stream_t *out, bmp_info_t *info)
+{
+ int i;
+
+ info->len = 40;
+ if (bmp_putint32(out, info->len) ||
+ bmp_putint32(out, info->width) ||
+ bmp_putint32(out, info->height) ||
+ bmp_putint16(out, info->numplanes) ||
+ bmp_putint16(out, info->depth) ||
+ bmp_putint32(out, info->enctype) ||
+ bmp_putint32(out, info->siz) ||
+ bmp_putint32(out, info->hres) ||
+ bmp_putint32(out, info->vres) ||
+ bmp_putint32(out, info->numcolors) ||
+ bmp_putint32(out, info->mincolors)) {
+ return -1;
+ }
+
+ for (i = 0; i < info->numcolors; ++i)
+ {
+ if (jas_stream_putc(out, i) == EOF ||
+ jas_stream_putc(out, i) == EOF ||
+ jas_stream_putc(out, i) == EOF ||
+ jas_stream_putc(out, 0) == EOF)
+ {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int bmp_putdata(jas_stream_t *out, bmp_info_t *info, jas_image_t *image,
+ int *cmpts)
+{
+ int i;
+ int j;
+ jas_matrix_t *bufs[3];
+ int numpad;
+ unsigned char red;
+ unsigned char grn;
+ unsigned char blu;
+ int ret;
+ int numcmpts;
+ int v;
+ int cmptno;
+
+ numcmpts = (info->depth == 24) ? 3:1;
+
+ /* We do not support palettized images. */
+ if (BMP_HASPAL(info) && numcmpts == 3) {
+ jas_eprintf("no palettized image support for BMP format\n");
+ return -1;
+ }
+
+ ret = 0;
+ for (i = 0; i < numcmpts; ++i) {
+ bufs[i] = 0;
+ }
+
+ /* Create temporary matrices to hold component data. */
+ for (i = 0; i < numcmpts; ++i) {
+ if (!(bufs[i] = jas_matrix_create(1, info->width))) {
+ ret = -1;
+ goto bmp_putdata_done;
+ }
+ }
+
+ /* Calculate number of padding bytes per row of image data. */
+ numpad = (numcmpts * info->width) % 4;
+ if (numpad) {
+ numpad = 4 - numpad;
+ }
+
+ /* Put the image data. */
+ for (i = info->height - 1; i >= 0; --i) {
+ for (cmptno = 0; cmptno < numcmpts; ++cmptno) {
+ if (jas_image_readcmpt(image, cmptno, 0, i, info->width,
+ 1, bufs[cmpts[cmptno]])) {
+ ret = -1;
+ goto bmp_putdata_done;
+ }
+ }
+ for (j = 0; j < info->width; ++j) {
+ if (numcmpts == 3) {
+ red = (jas_matrix_getv(bufs[0], j));
+ grn = (jas_matrix_getv(bufs[1], j));
+ blu = (jas_matrix_getv(bufs[2], j));
+ if (jas_stream_putc(out, blu) == EOF ||
+ jas_stream_putc(out, grn) == EOF ||
+ jas_stream_putc(out, red) == EOF) {
+ ret = -1;
+ goto bmp_putdata_done;
+ }
+ } else if (numcmpts == 1) {
+ v = (jas_matrix_getv(bufs[cmpts[0]], j));
+ if (jas_stream_putc(out, v) == EOF) {
+ ret = -1;
+ goto bmp_putdata_done;
+ }
+ } else {
+ abort();
+ }
+ }
+ for (j = numpad; j > 0; --j) {
+ if (jas_stream_putc(out, 0) == EOF) {
+ ret = -1;
+ goto bmp_putdata_done;
+ }
+ }
+ }
+
+bmp_putdata_done:
+ /* Destroy the temporary matrices. */
+ for (i = 0; i < numcmpts; ++i) {
+ if (bufs[i]) {
+ jas_matrix_destroy(bufs[i]);
+ }
+ }
+
+ return ret;
+}
+
+/******************************************************************************\
+* Code for primitive types.
+\******************************************************************************/
+
+static int bmp_putint16(jas_stream_t *in, int_fast16_t val)
+{
+ if (jas_stream_putc(in, val & 0xff) == EOF || jas_stream_putc(in, (val >> 8) &
+ 0xff) == EOF) {
+ return -1;
+ }
+ return 0;
+}
+
+static int bmp_putint32(jas_stream_t *out, int_fast32_t val)
+{
+ int n;
+ int_fast32_t v;
+
+ /* This code needs to be changed if we want to handle negative values. */
+ assert(val >= 0);
+ v = val;
+ for (n = 4;;) {
+ if (jas_stream_putc(out, v & 0xff) == EOF) {
+ return -1;
+ }
+ if (--n <= 0) {
+ break;
+ }
+ v >>= 8;
+ }
+ return 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_enc.h b/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_enc.h
new file mode 100644
index 0000000..f37e504
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/bmp/bmp_enc.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef BMP_ENC_H
+#define BMP_ENC_H
+
+typedef struct {
+
+ int numcmpts;
+ int cmpts[4];
+
+} bmp_enc_t;
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/dummy.c b/jasper-1.900.1-6ct/src/libjasper/dummy.c
new file mode 100644
index 0000000..9344920
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/dummy.c
@@ -0,0 +1,3 @@
+/* This source file only exists to keep libtool happy. */
+
+char jas_dummy;
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/Makefile.am b/jasper-1.900.1-6ct/src/libjasper/include/Makefile.am
new file mode 100644
index 0000000..bdca0c9
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/Makefile.am
@@ -0,0 +1,59 @@
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+SUBDIRS = jasper
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/Makefile.in b/jasper-1.900.1-6ct/src/libjasper/include/Makefile.in
new file mode 100644
index 0000000..4c860a0
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/Makefile.in
@@ -0,0 +1,549 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src/libjasper/include
+DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+SOURCES =
+DIST_SOURCES =
+RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
+ html-recursive info-recursive install-data-recursive \
+ install-exec-recursive install-info-recursive \
+ install-recursive installcheck-recursive installdirs-recursive \
+ pdf-recursive ps-recursive uninstall-info-recursive \
+ uninstall-recursive
+ETAGS = etags
+CTAGS = ctags
+DIST_SUBDIRS = $(SUBDIRS)
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+SUBDIRS = jasper
+all: all-recursive
+
+.SUFFIXES:
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libjasper/include/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/libjasper/include/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+
+# This directory's subdirectories are mostly independent; you can cd
+# into them and run `make' without going through this Makefile.
+# To change the values of `make' variables: instead of editing Makefiles,
+# (1) if the variable is set in `config.status', edit `config.status'
+# (which will cause the Makefiles to be regenerated when you run `make');
+# (2) otherwise, pass the desired values on the `make' command line.
+$(RECURSIVE_TARGETS):
+ @failcom='exit 1'; \
+ for f in x $$MAKEFLAGS; do \
+ case $$f in \
+ *=* | --[!k]*);; \
+ *k*) failcom='fail=yes';; \
+ esac; \
+ done; \
+ dot_seen=no; \
+ target=`echo $@ | sed s/-recursive//`; \
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ echo "Making $$target in $$subdir"; \
+ if test "$$subdir" = "."; then \
+ dot_seen=yes; \
+ local_target="$$target-am"; \
+ else \
+ local_target="$$target"; \
+ fi; \
+ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+ || eval $$failcom; \
+ done; \
+ if test "$$dot_seen" = "no"; then \
+ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
+ fi; test -z "$$fail"
+
+mostlyclean-recursive clean-recursive distclean-recursive \
+maintainer-clean-recursive:
+ @failcom='exit 1'; \
+ for f in x $$MAKEFLAGS; do \
+ case $$f in \
+ *=* | --[!k]*);; \
+ *k*) failcom='fail=yes';; \
+ esac; \
+ done; \
+ dot_seen=no; \
+ case "$@" in \
+ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
+ *) list='$(SUBDIRS)' ;; \
+ esac; \
+ rev=''; for subdir in $$list; do \
+ if test "$$subdir" = "."; then :; else \
+ rev="$$subdir $$rev"; \
+ fi; \
+ done; \
+ rev="$$rev ."; \
+ target=`echo $@ | sed s/-recursive//`; \
+ for subdir in $$rev; do \
+ echo "Making $$target in $$subdir"; \
+ if test "$$subdir" = "."; then \
+ local_target="$$target-am"; \
+ else \
+ local_target="$$target"; \
+ fi; \
+ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+ || eval $$failcom; \
+ done && test -z "$$fail"
+tags-recursive:
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
+ done
+ctags-recursive:
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
+ done
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
+ include_option=--etags-include; \
+ empty_fix=.; \
+ else \
+ include_option=--include; \
+ empty_fix=; \
+ fi; \
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ if test "$$subdir" = .; then :; else \
+ test ! -f $$subdir/TAGS || \
+ tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \
+ fi; \
+ done; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+ list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
+ if test "$$subdir" = .; then :; else \
+ test -d "$(distdir)/$$subdir" \
+ || $(mkdir_p) "$(distdir)/$$subdir" \
+ || exit 1; \
+ distdir=`$(am__cd) $(distdir) && pwd`; \
+ top_distdir=`$(am__cd) $(top_distdir) && pwd`; \
+ (cd $$subdir && \
+ $(MAKE) $(AM_MAKEFLAGS) \
+ top_distdir="$$top_distdir" \
+ distdir="$$distdir/$$subdir" \
+ distdir) \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-recursive
+all-am: Makefile
+installdirs: installdirs-recursive
+installdirs-am:
+install: install-recursive
+install-exec: install-exec-recursive
+install-data: install-data-recursive
+uninstall: uninstall-recursive
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-recursive
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-recursive
+
+clean-am: clean-generic clean-libtool mostlyclean-am
+
+distclean: distclean-recursive
+ -rm -f Makefile
+distclean-am: clean-am distclean-generic distclean-libtool \
+ distclean-tags
+
+dvi: dvi-recursive
+
+dvi-am:
+
+html: html-recursive
+
+info: info-recursive
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-recursive
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-recursive
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-recursive
+
+mostlyclean-am: mostlyclean-generic mostlyclean-libtool
+
+pdf: pdf-recursive
+
+pdf-am:
+
+ps: ps-recursive
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+uninstall-info: uninstall-info-recursive
+
+.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am check check-am \
+ clean clean-generic clean-libtool clean-recursive ctags \
+ ctags-recursive distclean distclean-generic distclean-libtool \
+ distclean-recursive distclean-tags distdir dvi dvi-am html \
+ html-am info info-am install install-am install-data \
+ install-data-am install-exec install-exec-am install-info \
+ install-info-am install-man install-strip installcheck \
+ installcheck-am installdirs installdirs-am maintainer-clean \
+ maintainer-clean-generic maintainer-clean-recursive \
+ mostlyclean mostlyclean-generic mostlyclean-libtool \
+ mostlyclean-recursive pdf pdf-am ps ps-am tags tags-recursive \
+ uninstall uninstall-am uninstall-info-am
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/Makefile.am b/jasper-1.900.1-6ct/src/libjasper/include/jasper/Makefile.am
new file mode 100644
index 0000000..1e490ff
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/Makefile.am
@@ -0,0 +1,80 @@
+# Copyright (c) 2001-2003 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+libjasperincludedir = $(includedir)/jasper
+
+libjasperinclude_HEADERS = \
+ jasper.h \
+ jas_config.h \
+ jas_config2.h \
+ jas_cm.h \
+ jas_fix.h \
+ jas_debug.h \
+ jas_getopt.h \
+ jas_icc.h \
+ jas_image.h \
+ jas_init.h \
+ jas_malloc.h \
+ jas_math.h \
+ jas_seq.h \
+ jas_stream.h \
+ jas_string.h \
+ jas_tmr.h \
+ jas_tvp.h \
+ jas_types.h \
+ jas_version.h
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/Makefile.in b/jasper-1.900.1-6ct/src/libjasper/include/jasper/Makefile.in
new file mode 100644
index 0000000..c165de6
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/Makefile.in
@@ -0,0 +1,508 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2003 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../../../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src/libjasper/include/jasper
+DIST_COMMON = $(libjasperinclude_HEADERS) $(srcdir)/Makefile.am \
+ $(srcdir)/Makefile.in $(srcdir)/jas_config.h.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = jas_config.h
+CONFIG_CLEAN_FILES =
+SOURCES =
+DIST_SOURCES =
+am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj = case $$p in \
+ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+ *) f=$$p;; \
+ esac;
+am__strip_dir = `echo $$p | sed -e 's|^.*/||'`;
+am__installdirs = "$(DESTDIR)$(libjasperincludedir)"
+libjasperincludeHEADERS_INSTALL = $(INSTALL_HEADER)
+HEADERS = $(libjasperinclude_HEADERS)
+ETAGS = etags
+CTAGS = ctags
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+libjasperincludedir = $(includedir)/jasper
+libjasperinclude_HEADERS = \
+ jasper.h \
+ jas_config.h \
+ jas_config2.h \
+ jas_cm.h \
+ jas_fix.h \
+ jas_debug.h \
+ jas_getopt.h \
+ jas_icc.h \
+ jas_image.h \
+ jas_init.h \
+ jas_malloc.h \
+ jas_math.h \
+ jas_seq.h \
+ jas_stream.h \
+ jas_string.h \
+ jas_tmr.h \
+ jas_tvp.h \
+ jas_types.h \
+ jas_version.h
+
+all: jas_config.h
+ $(MAKE) $(AM_MAKEFLAGS) all-am
+
+.SUFFIXES:
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libjasper/include/jasper/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/libjasper/include/jasper/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+jas_config.h: stamp-h1
+ @if test ! -f $@; then \
+ rm -f stamp-h1; \
+ $(MAKE) stamp-h1; \
+ else :; fi
+
+stamp-h1: $(srcdir)/jas_config.h.in $(top_builddir)/config.status
+ @rm -f stamp-h1
+ cd $(top_builddir) && $(SHELL) ./config.status src/libjasper/include/jasper/jas_config.h
+$(srcdir)/jas_config.h.in: $(am__configure_deps)
+ cd $(top_srcdir) && $(AUTOHEADER)
+ rm -f stamp-h1
+ touch $@
+
+distclean-hdr:
+ -rm -f jas_config.h stamp-h1
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+install-libjasperincludeHEADERS: $(libjasperinclude_HEADERS)
+ @$(NORMAL_INSTALL)
+ test -z "$(libjasperincludedir)" || $(mkdir_p) "$(DESTDIR)$(libjasperincludedir)"
+ @list='$(libjasperinclude_HEADERS)'; for p in $$list; do \
+ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
+ f=$(am__strip_dir) \
+ echo " $(libjasperincludeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(libjasperincludedir)/$$f'"; \
+ $(libjasperincludeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(libjasperincludedir)/$$f"; \
+ done
+
+uninstall-libjasperincludeHEADERS:
+ @$(NORMAL_UNINSTALL)
+ @list='$(libjasperinclude_HEADERS)'; for p in $$list; do \
+ f=$(am__strip_dir) \
+ echo " rm -f '$(DESTDIR)$(libjasperincludedir)/$$f'"; \
+ rm -f "$(DESTDIR)$(libjasperincludedir)/$$f"; \
+ done
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: $(HEADERS) $(SOURCES) jas_config.h.in $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) jas_config.h.in $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: $(HEADERS) $(SOURCES) jas_config.h.in $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) jas_config.h.in $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-am
+all-am: Makefile $(HEADERS) jas_config.h
+installdirs:
+ for dir in "$(DESTDIR)$(libjasperincludedir)"; do \
+ test -z "$$dir" || $(mkdir_p) "$$dir"; \
+ done
+install: install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-am
+
+clean-am: clean-generic clean-libtool mostlyclean-am
+
+distclean: distclean-am
+ -rm -f Makefile
+distclean-am: clean-am distclean-generic distclean-hdr \
+ distclean-libtool distclean-tags
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+info: info-am
+
+info-am:
+
+install-data-am: install-libjasperincludeHEADERS
+
+install-exec-am:
+
+install-info: install-info-am
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-generic mostlyclean-libtool
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-info-am uninstall-libjasperincludeHEADERS
+
+.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
+ clean-libtool ctags distclean distclean-generic distclean-hdr \
+ distclean-libtool distclean-tags distdir dvi dvi-am html \
+ html-am info info-am install install-am install-data \
+ install-data-am install-exec install-exec-am install-info \
+ install-info-am install-libjasperincludeHEADERS install-man \
+ install-strip installcheck installcheck-am installdirs \
+ maintainer-clean maintainer-clean-generic mostlyclean \
+ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
+ tags uninstall uninstall-am uninstall-info-am \
+ uninstall-libjasperincludeHEADERS
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_cm.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_cm.h
new file mode 100644
index 0000000..d5cd22e
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_cm.h
@@ -0,0 +1,266 @@
+/*
+ * Copyright (c) 2002-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Color Management
+ *
+ * $Id$
+ */
+
+#ifndef JAS_CM_H
+#define JAS_CM_H
+
+#include <jasper/jas_config.h>
+#include <jasper/jas_icc.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef int jas_clrspc_t;
+
+/* transform operations */
+#define JAS_CMXFORM_OP_FWD 0
+#define JAS_CMXFORM_OP_REV 1
+#define JAS_CMXFORM_OP_PROOF 2
+#define JAS_CMXFORM_OP_GAMUT 3
+
+/* rendering intents */
+#define JAS_CMXFORM_INTENT_PER 0
+#define JAS_CMXFORM_INTENT_RELCLR 1
+#define JAS_CMXFORM_INTENT_ABSCLR 2
+#define JAS_CMXFORM_INTENT_SAT 3
+#define JAS_CMXFORM_NUMINTENTS 4
+
+#define JAS_CMXFORM_OPTM_SPEED 0
+#define JAS_CMXFORM_OPTM_SIZE 1
+#define JAS_CMXFORM_OPTM_ACC 2
+
+
+#define jas_clrspc_create(fam, mbr) (((fam) << 8) | (mbr))
+#define jas_clrspc_fam(clrspc) ((clrspc) >> 8)
+#define jas_clrspc_mbr(clrspc) ((clrspc) & 0xff)
+#define jas_clrspc_isgeneric(clrspc) (!jas_clrspc_mbr(clrspc))
+#define jas_clrspc_isunknown(clrspc) ((clrspc) & JAS_CLRSPC_UNKNOWNMASK)
+
+#define JAS_CLRSPC_UNKNOWNMASK 0x4000
+
+/* color space families */
+#define JAS_CLRSPC_FAM_UNKNOWN 0
+#define JAS_CLRSPC_FAM_XYZ 1
+#define JAS_CLRSPC_FAM_LAB 2
+#define JAS_CLRSPC_FAM_GRAY 3
+#define JAS_CLRSPC_FAM_RGB 4
+#define JAS_CLRSPC_FAM_YCBCR 5
+
+/* specific color spaces */
+#define JAS_CLRSPC_UNKNOWN JAS_CLRSPC_UNKNOWNMASK
+#define JAS_CLRSPC_CIEXYZ jas_clrspc_create(JAS_CLRSPC_FAM_XYZ, 1)
+#define JAS_CLRSPC_CIELAB jas_clrspc_create(JAS_CLRSPC_FAM_LAB, 1)
+#define JAS_CLRSPC_SGRAY jas_clrspc_create(JAS_CLRSPC_FAM_GRAY, 1)
+#define JAS_CLRSPC_SRGB jas_clrspc_create(JAS_CLRSPC_FAM_RGB, 1)
+#define JAS_CLRSPC_SYCBCR jas_clrspc_create(JAS_CLRSPC_FAM_YCBCR, 1)
+
+/* generic color spaces */
+#define JAS_CLRSPC_GENRGB jas_clrspc_create(JAS_CLRSPC_FAM_RGB, 0)
+#define JAS_CLRSPC_GENGRAY jas_clrspc_create(JAS_CLRSPC_FAM_GRAY, 0)
+#define JAS_CLRSPC_GENYCBCR jas_clrspc_create(JAS_CLRSPC_FAM_YCBCR, 0)
+
+#define JAS_CLRSPC_CHANIND_YCBCR_Y 0
+#define JAS_CLRSPC_CHANIND_YCBCR_CB 1
+#define JAS_CLRSPC_CHANIND_YCBCR_CR 2
+
+#define JAS_CLRSPC_CHANIND_RGB_R 0
+#define JAS_CLRSPC_CHANIND_RGB_G 1
+#define JAS_CLRSPC_CHANIND_RGB_B 2
+
+#define JAS_CLRSPC_CHANIND_GRAY_Y 0
+
+typedef double jas_cmreal_t;
+
+struct jas_cmpxform_s;
+
+typedef struct {
+ long *buf;
+ int prec;
+ int sgnd;
+ int width;
+ int height;
+} jas_cmcmptfmt_t;
+
+typedef struct {
+ int numcmpts;
+ jas_cmcmptfmt_t *cmptfmts;
+} jas_cmpixmap_t;
+
+typedef struct {
+ void (*destroy)(struct jas_cmpxform_s *pxform);
+ int (*apply)(struct jas_cmpxform_s *pxform, jas_cmreal_t *in, jas_cmreal_t *out, int cnt);
+ void (*dump)(struct jas_cmpxform_s *pxform);
+} jas_cmpxformops_t;
+
+typedef struct {
+ jas_cmreal_t *data;
+ int size;
+} jas_cmshapmatlut_t;
+
+typedef struct {
+ int mono;
+ int order;
+ int useluts;
+ int usemat;
+ jas_cmshapmatlut_t luts[3];
+ jas_cmreal_t mat[3][4];
+} jas_cmshapmat_t;
+
+typedef struct {
+ int order;
+} jas_cmshaplut_t;
+
+typedef struct {
+ int inclrspc;
+ int outclrspc;
+} jas_cmclrspcconv_t;
+
+#define jas_align_t double
+
+typedef struct jas_cmpxform_s {
+ int refcnt;
+ jas_cmpxformops_t *ops;
+ int numinchans;
+ int numoutchans;
+ union {
+ jas_align_t dummy;
+ jas_cmshapmat_t shapmat;
+ jas_cmshaplut_t shaplut;
+ jas_cmclrspcconv_t clrspcconv;
+ } data;
+} jas_cmpxform_t;
+
+typedef struct {
+ int numpxforms;
+ int maxpxforms;
+ jas_cmpxform_t **pxforms;
+} jas_cmpxformseq_t;
+
+typedef struct {
+ int numinchans;
+ int numoutchans;
+ jas_cmpxformseq_t *pxformseq;
+} jas_cmxform_t;
+
+#define JAS_CMPROF_TYPE_DEV 1
+#define JAS_CMPROF_TYPE_CLRSPC 2
+
+#define JAS_CMPROF_NUMPXFORMSEQS 13
+
+typedef struct {
+ int clrspc;
+ int numchans;
+ int refclrspc;
+ int numrefchans;
+ jas_iccprof_t *iccprof;
+ jas_cmpxformseq_t *pxformseqs[JAS_CMPROF_NUMPXFORMSEQS];
+} jas_cmprof_t;
+
+/* Create a profile. */
+
+/* Destroy a profile. */
+void jas_cmprof_destroy(jas_cmprof_t *prof);
+
+#if 0
+typedef int_fast32_t jas_cmattrname_t;
+typedef int_fast32_t jas_cmattrval_t;
+typedef int_fast32_t jas_cmattrtype_t;
+/* Load a profile. */
+int jas_cmprof_load(jas_cmprof_t *prof, jas_stream_t *in, int fmt);
+/* Save a profile. */
+int jas_cmprof_save(jas_cmprof_t *prof, jas_stream_t *out, int fmt);
+/* Set an attribute of a profile. */
+int jas_cm_prof_setattr(jas_cm_prof_t *prof, jas_cm_attrname_t name, void *val);
+/* Get an attribute of a profile. */
+void *jas_cm_prof_getattr(jas_cm_prof_t *prof, jas_cm_attrname_t name);
+#endif
+
+jas_cmxform_t *jas_cmxform_create(jas_cmprof_t *inprof, jas_cmprof_t *outprof,
+ jas_cmprof_t *proofprof, int op, int intent, int optimize);
+
+void jas_cmxform_destroy(jas_cmxform_t *xform);
+
+/* Apply a transform to data. */
+int jas_cmxform_apply(jas_cmxform_t *xform, jas_cmpixmap_t *in,
+ jas_cmpixmap_t *out);
+
+int jas_cxform_optimize(jas_cmxform_t *xform, int optimize);
+
+int jas_clrspc_numchans(int clrspc);
+jas_cmprof_t *jas_cmprof_createfromiccprof(jas_iccprof_t *iccprof);
+jas_cmprof_t *jas_cmprof_createfromclrspc(int clrspc);
+jas_iccprof_t *jas_iccprof_createfromcmprof(jas_cmprof_t *prof);
+
+#define jas_cmprof_clrspc(prof) ((prof)->clrspc)
+jas_cmprof_t *jas_cmprof_copy(jas_cmprof_t *prof);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_config.h.in b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_config.h.in
new file mode 100644
index 0000000..a7375de
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_config.h.in
@@ -0,0 +1,172 @@
+/* src/libjasper/include/jasper/jas_config.h.in. Generated from configure.ac by autoheader. */
+
+
+/* Avoid problems due to multiple inclusion. */
+#ifndef JAS_CONFIG_H
+#define JAS_CONFIG_H
+
+/* This preprocessor symbol identifies the version of JasPer. */
+#undef JAS_VERSION
+/* If configure is being used, this symbol will be defined automatically
+ at this point in the configuration header file. */
+
+/* The preprocessor symbol JAS_WIN_MSVC_BUILD should not be defined
+ unless the JasPer software is being built under Microsoft Windows
+ using Microsoft Visual C. */
+#if !defined(JAS_WIN_MSVC_BUILD)
+/* A configure-based build is being used. */
+
+
+
+/* Extra debugging support */
+#undef DEBUG
+
+/* Debugging memory allocator */
+#undef DEBUG_MEMALLOC
+
+/* Debugging overflow detection */
+#undef DEBUG_OVERFLOW
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#undef HAVE_DLFCN_H
+
+/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */
+#undef HAVE_DOPRNT
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#undef HAVE_FCNTL_H
+
+/* Define to 1 if you have the `getrusage' function. */
+#undef HAVE_GETRUSAGE
+
+/* Define to 1 if you have the `gettimeofday' function. */
+#undef HAVE_GETTIMEOFDAY
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#undef HAVE_INTTYPES_H
+
+/* Define to 1 if you have the <io.h> header file. */
+#undef HAVE_IO_H
+
+/* Define to 1 if you have the `m' library (-lm). */
+#undef HAVE_LIBM
+
+/* Define to 1 if you have the <limits.h> header file. */
+#undef HAVE_LIMITS_H
+
+/* Define to 1 if you have the <memory.h> header file. */
+#undef HAVE_MEMORY_H
+
+/* Define to 1 if you have the <stdbool.h> header file. */
+#undef HAVE_STDBOOL_H
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#undef HAVE_STDDEF_H
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#undef HAVE_STDINT_H
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#undef HAVE_STDLIB_H
+
+/* Define to 1 if you have the <strings.h> header file. */
+#undef HAVE_STRINGS_H
+
+/* Define to 1 if you have the <string.h> header file. */
+#undef HAVE_STRING_H
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#undef HAVE_SYS_STAT_H
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#undef HAVE_SYS_TIME_H
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#undef HAVE_SYS_TYPES_H
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#undef HAVE_UNISTD_H
+
+/* Have variable length arrays */
+#undef HAVE_VLA
+
+/* Define to 1 if you have the `vprintf' function. */
+#undef HAVE_VPRINTF
+
+/* Define to 1 if you have the <windows.h> header file. */
+#undef HAVE_WINDOWS_H
+
+/* JasPer configure */
+#undef JAS_CONFIGURE
+
+/* JasPer version */
+#undef JAS_VERSION
+
+/* Name of package */
+#undef PACKAGE
+
+/* Define to the address where bug reports for this package should be sent. */
+#undef PACKAGE_BUGREPORT
+
+/* Define to the full name of this package. */
+#undef PACKAGE_NAME
+
+/* Define to the full name and version of this package. */
+#undef PACKAGE_STRING
+
+/* Define to the one symbol short name of this package. */
+#undef PACKAGE_TARNAME
+
+/* Define to the version of this package. */
+#undef PACKAGE_VERSION
+
+/* Define to 1 if you have the ANSI C header files. */
+#undef STDC_HEADERS
+
+/* Version number of package */
+#undef VERSION
+
+/* Define to 1 if the X Window System is missing or not being used. */
+#undef X_DISPLAY_MISSING
+
+/* Define to empty if `const' does not conform to ANSI C. */
+#undef const
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+ calls it, or to nothing if 'inline' is not supported under any name. */
+#ifndef __cplusplus
+#undef inline
+#endif
+
+/* Define to `long long' if <sys/types.h> does not define. */
+#undef longlong
+
+/* Define to `unsigned' if <sys/types.h> does not define. */
+#undef size_t
+
+/* Define to `int' if <sys/types.h> does not define. */
+#undef ssize_t
+
+/* Define to `unsigned char' if <sys/types.h> does not define. */
+#undef uchar
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+#undef uint
+
+/* Define to `unsigned long' if <sys/types.h> does not define. */
+#undef ulong
+
+/* Define to `unsigned long long' if <sys/types.h> does not define. */
+#undef ulonglong
+
+/* Define to `unsigned short' if <sys/types.h> does not define. */
+#undef ushort
+
+
+#else
+/* A configure-based build is not being used. */
+#include <jasper/jas_config2.h>
+#endif
+
+#endif
+
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_config2.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_config2.h
new file mode 100644
index 0000000..78e8b91
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_config2.h
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2002-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef JAS_CONFIG2_H
+#define JAS_CONFIG2_H
+
+/*
+ * Configuration for Microsoft Windows and Microsoft Visual C.
+ *
+ * We are not using a configure-based build.
+ * Try to compensate for this here, by specifying the preprocessor symbols
+ * normally defined by configure.
+ */
+
+#define uchar unsigned char
+#define ushort unsigned short
+#define uint unsigned int
+#define ulong unsigned long
+#define longlong long long
+#define ulonglong unsigned long long
+/*#define ssize_t int*/
+
+#define HAVE_FCNTL_H 1
+#define HAVE_LIMITS_H 1
+#define HAVE_IO_H 1
+#define HAVE_WINDOWS_H 1
+#define HAVE_SYS_TYPES_H 1
+#define HAVE_STDLIB_H 1
+#define HAVE_STDDEF_H 1
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_debug.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_debug.h
new file mode 100644
index 0000000..014614b
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_debug.h
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Debugging-Related Code
+ *
+ * $Id$
+ */
+
+#ifndef JAS_DEBUG_H
+#define JAS_DEBUG_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+
+#include <jasper/jas_config.h>
+#include "jasper/jas_types.h"
+#include "jasper/jas_debug.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Macros and functions.
+\******************************************************************************/
+
+/* Output debugging information to standard error provided that the debug
+ level is set sufficiently high. */
+#if defined(DEBUG)
+#define JAS_DBGLOG(n, x) \
+ ((jas_getdbglevel() >= (n)) ? (jas_eprintf x) : 0)
+#else
+#define JAS_DBGLOG(n, x)
+#endif
+
+/* Get the library debug level. */
+int jas_getdbglevel(void);
+
+/* Set the library debug level. */
+int jas_setdbglevel(int dbglevel);
+
+/* Perform formatted output to standard error. */
+int jas_eprintf(const char *fmt, ...);
+
+/* Dump memory to a stream. */
+int jas_memdump(FILE *out, void *data, size_t len);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_fix.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_fix.h
new file mode 100644
index 0000000..f91ce25
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_fix.h
@@ -0,0 +1,358 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Fixed-Point Number Class
+ *
+ * $Id$
+ */
+
+#ifndef JAS_FIX_H
+#define JAS_FIX_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+
+#include <jasper/jas_config.h>
+#include <jasper/jas_types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* The representation of the value zero. */
+#define JAS_FIX_ZERO(fix_t, fracbits) \
+ JAS_CAST(fix_t, 0)
+
+/* The representation of the value one. */
+#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))
+
+/******************************************************************************\
+* Conversion operations.
+\******************************************************************************/
+
+/* Convert an int to a fixed-point number. */
+#define JAS_INTTOFIX(fix_t, fracbits, x) \
+ JAS_CAST(fix_t, (x) << (fracbits))
+
+/* Convert a fixed-point number to an int. */
+#define JAS_FIXTOINT(fix_t, fracbits, x) \
+ JAS_CAST(int, (x) >> (fracbits))
+
+/* Convert a fixed-point number to a double. */
+#define JAS_FIXTODBL(fix_t, fracbits, x) \
+ (JAS_CAST(double, x) / (JAS_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))))
+
+/******************************************************************************\
+* Basic arithmetic operations.
+* All other arithmetic operations are synthesized from these basic operations.
+* There are three macros for each type of arithmetic operation.
+* One macro always performs overflow/underflow checking, one never performs
+* overflow/underflow checking, and one is generic with its behavior
+* depending on compile-time flags.
+* Only the generic macros should be invoked directly by application code.
+\******************************************************************************/
+
+/* Calculate the sum of two fixed-point numbers. */
+#if !defined(DEBUG_OVERFLOW)
+#define JAS_FIX_ADD JAS_FIX_ADD_FAST
+#else
+#define JAS_FIX_ADD JAS_FIX_ADD_OFLOW
+#endif
+
+/* Calculate the sum of two fixed-point numbers without overflow checking. */
+#define JAS_FIX_ADD_FAST(fix_t, fracbits, x, y) ((x) + (y))
+
+/* Calculate the sum of two fixed-point numbers with overflow checking. */
+#define JAS_FIX_ADD_OFLOW(fix_t, fracbits, x, y) \
+ ((x) >= 0) ? \
+ (((y) >= 0) ? ((x) + (y) >= 0 || JAS_FIX_OFLOW(), (x) + (y)) : \
+ ((x) + (y))) : \
+ (((y) >= 0) ? ((x) + (y)) : ((x) + (y) < 0 || JAS_FIX_OFLOW(), \
+ (x) + (y)))
+
+/* Calculate the product of two fixed-point numbers. */
+#if !defined(DEBUG_OVERFLOW)
+#define JAS_FIX_MUL JAS_FIX_MUL_FAST
+#else
+#define JAS_FIX_MUL JAS_FIX_MUL_OFLOW
+#endif
+
+/* Calculate the product of two fixed-point numbers without overflow
+ checking. */
+#define JAS_FIX_MUL_FAST(fix_t, fracbits, bigfix_t, x, y) \
+ JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y)) >> \
+ (fracbits))
+
+/* Calculate the product of two fixed-point numbers with overflow
+ checking. */
+#define JAS_FIX_MUL_OFLOW(fix_t, fracbits, bigfix_t, x, y) \
+ ((JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> (fracbits)) == \
+ JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> \
+ (fracbits))) ? \
+ JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) * JAS_CAST(bigfix_t, y) >> \
+ (fracbits))) : JAS_FIX_OFLOW())
+
+/* Calculate the product of a fixed-point number and an int. */
+#if !defined(DEBUG_OVERFLOW)
+#define JAS_FIX_MULBYINT JAS_FIX_MULBYINT_FAST
+#else
+#define JAS_FIX_MULBYINT JAS_FIX_MULBYINT_OFLOW
+#endif
+
+/* Calculate the product of a fixed-point number and an int without overflow
+ checking. */
+#define JAS_FIX_MULBYINT_FAST(fix_t, fracbits, x, y) \
+ JAS_CAST(fix_t, ((x) * (y)))
+
+/* Calculate the product of a fixed-point number and an int with overflow
+ checking. */
+#define JAS_FIX_MULBYINT_OFLOW(fix_t, fracbits, x, y) \
+ JAS_FIX_MULBYINT_FAST(fix_t, fracbits, x, y)
+
+/* Calculate the quotient of two fixed-point numbers. */
+#if !defined(DEBUG_OVERFLOW)
+#define JAS_FIX_DIV JAS_FIX_DIV_FAST
+#else
+#define JAS_FIX_DIV JAS_FIX_DIV_UFLOW
+#endif
+
+/* Calculate the quotient of two fixed-point numbers without underflow
+ checking. */
+#define JAS_FIX_DIV_FAST(fix_t, fracbits, bigfix_t, x, y) \
+ JAS_CAST(fix_t, (JAS_CAST(bigfix_t, x) << (fracbits)) / (y))
+
+/* Calculate the quotient of two fixed-point numbers with underflow
+ checking. */
+#define JAS_FIX_DIV_UFLOW(fix_t, fracbits, bigfix_t, x, y) \
+ JAS_FIX_DIV_FAST(fix_t, fracbits, bigfix_t, x, y)
+
+/* Negate a fixed-point number. */
+#if !defined(DEBUG_OVERFLOW)
+#define JAS_FIX_NEG JAS_FIX_NEG_FAST
+#else
+#define JAS_FIX_NEG JAS_FIX_NEG_OFLOW
+#endif
+
+/* Negate a fixed-point number without overflow checking. */
+#define JAS_FIX_NEG_FAST(fix_t, fracbits, x) \
+ (-(x))
+
+/* Negate a fixed-point number with overflow checking. */
+/* Yes, overflow is actually possible for two's complement representations,
+ although highly unlikely to occur. */
+#define JAS_FIX_NEG_OFLOW(fix_t, fracbits, x) \
+ (((x) < 0) ? (-(x) > 0 || JAS_FIX_OFLOW(), -(x)) : (-(x)))
+
+/* Perform an arithmetic shift left of a fixed-point number. */
+#if !defined(DEBUG_OVERFLOW)
+#define JAS_FIX_ASL JAS_FIX_ASL_FAST
+#else
+#define JAS_FIX_ASL JAS_FIX_ASL_OFLOW
+#endif
+
+/* Perform an arithmetic shift left of a fixed-point number without overflow
+ checking. */
+#define JAS_FIX_ASL_FAST(fix_t, fracbits, x, n) \
+ ((x) << (n))
+
+/* Perform an arithmetic shift left of a fixed-point number with overflow
+ checking. */
+#define JAS_FIX_ASL_OFLOW(fix_t, fracbits, x, n) \
+ ((((x) << (n)) >> (n)) == (x) || JAS_FIX_OFLOW(), (x) << (n))
+
+/* Perform an arithmetic shift right of a fixed-point number. */
+#if !defined(DEBUG_OVERFLOW)
+#define JAS_FIX_ASR JAS_FIX_ASR_FAST
+#else
+#define JAS_FIX_ASR JAS_FIX_ASR_UFLOW
+#endif
+
+/* Perform an arithmetic shift right of a fixed-point number without underflow
+ checking. */
+#define JAS_FIX_ASR_FAST(fix_t, fracbits, x, n) \
+ ((x) >> (n))
+
+/* Perform an arithmetic shift right of a fixed-point number with underflow
+ checking. */
+#define JAS_FIX_ASR_UFLOW(fix_t, fracbits, x, n) \
+ JAS_FIX_ASR_FAST(fix_t, fracbits, x, n)
+
+/******************************************************************************\
+* Other basic arithmetic operations.
+\******************************************************************************/
+
+/* Calculate the difference between two fixed-point numbers. */
+#define JAS_FIX_SUB(fix_t, fracbits, x, y) \
+ JAS_FIX_ADD(fix_t, fracbits, x, JAS_FIX_NEG(fix_t, fracbits, y))
+
+/* Add one fixed-point number to another. */
+#define JAS_FIX_PLUSEQ(fix_t, fracbits, x, y) \
+ ((x) = JAS_FIX_ADD(fix_t, fracbits, x, y))
+
+/* Subtract one fixed-point number from another. */
+#define JAS_FIX_MINUSEQ(fix_t, fracbits, x, y) \
+ ((x) = JAS_FIX_SUB(fix_t, fracbits, x, y))
+
+/* Multiply one fixed-point number by another. */
+#define JAS_FIX_MULEQ(fix_t, fracbits, bigfix_t, x, y) \
+ ((x) = JAS_FIX_MUL(fix_t, fracbits, bigfix_t, x, y))
+
+/******************************************************************************\
+* Miscellaneous operations.
+\******************************************************************************/
+
+/* Calculate the absolute value of a fixed-point number. */
+#define JAS_FIX_ABS(fix_t, fracbits, x) \
+ (((x) >= 0) ? (x) : (JAS_FIX_NEG(fix_t, fracbits, x)))
+
+/* Is a fixed-point number an integer? */
+#define JAS_FIX_ISINT(fix_t, fracbits, x) \
+ (JAS_FIX_FLOOR(fix_t, fracbits, x) == (x))
+
+/* Get the sign of a fixed-point number. */
+#define JAS_FIX_SGN(fix_t, fracbits, x) \
+ ((x) >= 0 ? 1 : (-1))
+
+/******************************************************************************\
+* Relational operations.
+\******************************************************************************/
+
+/* Compare two fixed-point numbers. */
+#define JAS_FIX_CMP(fix_t, fracbits, x, y) \
+ ((x) > (y) ? 1 : (((x) == (y)) ? 0 : (-1)))
+
+/* Less than. */
+#define JAS_FIX_LT(fix_t, fracbits, x, y) \
+ ((x) < (y))
+
+/* Less than or equal. */
+#define JAS_FIX_LTE(fix_t, fracbits, x, y) \
+ ((x) <= (y))
+
+/* Greater than. */
+#define JAS_FIX_GT(fix_t, fracbits, x, y) \
+ ((x) > (y))
+
+/* Greater than or equal. */
+#define JAS_FIX_GTE(fix_t, fracbits, x, y) \
+ ((x) >= (y))
+
+/******************************************************************************\
+* Rounding functions.
+\******************************************************************************/
+
+/* Round a fixed-point number to the nearest integer. */
+#define JAS_FIX_ROUND(fix_t, fracbits, x) \
+ (((x) < 0) ? JAS_FIX_FLOOR(fix_t, fracbits, JAS_FIX_ADD(fix_t, fracbits, \
+ (x), JAS_FIX_HALF(fix_t, fracbits))) : \
+ JAS_FIX_NEG(fix_t, fracbits, JAS_FIX_FLOOR(fix_t, fracbits, \
+ JAS_FIX_ADD(fix_t, fracbits, (-(x)), JAS_FIX_HALF(fix_t, fracbits)))))
+
+/* Round a fixed-point number to the nearest integer in the direction of
+ negative infinity (i.e., the floor function). */
+#define JAS_FIX_FLOOR(fix_t, fracbits, x) \
+ ((x) & (~((JAS_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))
+
+/******************************************************************************\
+* The below macros are for internal library use only. Do not invoke them
+* directly in application code.
+\******************************************************************************/
+
+/* Handle overflow. */
+#define JAS_FIX_OFLOW() \
+ jas_eprintf("overflow error: file %s, line %d\n", __FILE__, __LINE__)
+
+/* Handle underflow. */
+#define JAS_FIX_UFLOW() \
+ jas_eprintf("underflow error: file %s, line %d\n", __FILE__, __LINE__)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_getopt.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_getopt.h
new file mode 100644
index 0000000..3c7b205
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_getopt.h
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Command Line Option Parsing Code
+ *
+ * $Id$
+ */
+
+#ifndef JAS_GETOPT_H
+#define JAS_GETOPT_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <jasper/jas_config.h>
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+#define JAS_GETOPT_EOF (-1)
+#define JAS_GETOPT_ERR '?'
+
+/* option flags. */
+#define JAS_OPT_HASARG 0x01 /* option has argument */
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* Command line option type. */
+typedef struct {
+
+ int id;
+ /* The unique identifier for this option. */
+
+ char *name;
+ /* The name of this option. */
+
+ int flags;
+ /* option flags. */
+
+} jas_opt_t;
+
+/******************************************************************************\
+* External data.
+\******************************************************************************/
+
+/* The current option index. */
+extern int jas_optind;
+
+/* The current option argument. */
+extern char *jas_optarg;
+
+/* The debug level. */
+extern int jas_opterr;
+
+/******************************************************************************\
+* Prototypes.
+\******************************************************************************/
+
+/* Get the next option. */
+int jas_getopt(int argc, char **argv, jas_opt_t *opts);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_icc.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_icc.h
new file mode 100644
index 0000000..616a572
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_icc.h
@@ -0,0 +1,407 @@
+/*
+ * Copyright (c) 2002-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef JAS_ICC_H
+#define JAS_ICC_H
+
+#include <jasper/jas_config.h>
+#include <jasper/jas_types.h>
+#include <jasper/jas_stream.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Profile file signature. */
+#define JAS_ICC_MAGIC 0x61637370
+
+#define JAS_ICC_HDRLEN 128
+
+/* Profile/device class signatures. */
+#define JAS_ICC_CLAS_IN 0x73636e72 /* input device */
+#define JAS_ICC_CLAS_DPY 0x6d6e7472 /* display device */
+#define JAS_ICC_CLAS_OUT 0x70727472 /* output device */
+#define JAS_ICC_CLAS_LNK 0x6c696e6b /* device link */
+#define JAS_ICC_CLAS_CNV 0x73706163 /* color space conversion */
+#define JAS_ICC_CLAS_ABS 0x61627374 /* abstract */
+#define JAS_ICC_CLAS_NAM 0x6e6d636c /* named color */
+
+/* Color space signatures. */
+#define JAS_ICC_COLORSPC_XYZ 0x58595a20 /* XYZ */
+#define JAS_ICC_COLORSPC_LAB 0x4c616220 /* LAB */
+#define JAS_ICC_COLORSPC_LUV 0x4c757620 /* LUV */
+#define JAS_ICC_COLORSPC_YCBCR 0x59436272 /* YCbCr */
+#define JAS_ICC_COLORSPC_YXY 0x59787920 /* Yxy */
+#define JAS_ICC_COLORSPC_RGB 0x52474220 /* RGB */
+#define JAS_ICC_COLORSPC_GRAY 0x47524159 /* Gray */
+#define JAS_ICC_COLORSPC_HSV 0x48535620 /* HSV */
+#define JAS_ICC_COLORSPC_HLS 0x484c5320 /* HLS */
+#define JAS_ICC_COLORSPC_CMYK 0x434d594b /* CMYK */
+#define JAS_ICC_COLORSPC_CMY 0x434d5920 /* CMY */
+#define JAS_ICC_COLORSPC_2 0x32434c52 /* 2 channel color */
+#define JAS_ICC_COLORSPC_3 0x33434c52 /* 3 channel color */
+#define JAS_ICC_COLORSPC_4 0x34434c52 /* 4 channel color */
+#define JAS_ICC_COLORSPC_5 0x35434c52 /* 5 channel color */
+#define JAS_ICC_COLORSPC_6 0x36434c52 /* 6 channel color */
+#define JAS_ICC_COLORSPC_7 0x37434c52 /* 7 channel color */
+#define JAS_ICC_COLORSPC_8 0x38434c52 /* 8 channel color */
+#define JAS_ICC_COLORSPC_9 0x39434c52 /* 9 channel color */
+#define JAS_ICC_COLORSPC_10 0x41434c52 /* 10 channel color */
+#define JAS_ICC_COLORSPC_11 0x42434c52 /* 11 channel color */
+#define JAS_ICC_COLORSPC_12 0x43434c52 /* 12 channel color */
+#define JAS_ICC_COLORSPC_13 0x44434c52 /* 13 channel color */
+#define JAS_ICC_COLORSPC_14 0x45434c52 /* 14 channel color */
+#define JAS_ICC_COLORSPC_15 0x46434c52 /* 15 channel color */
+
+/* Profile connection color space (PCS) signatures. */
+#define JAS_ICC_REFCOLORSPC_XYZ 0x58595a20 /* CIE XYZ */
+#define JAS_ICC_REFCOLORSPC_LAB 0x4c616220 /* CIE Lab */
+
+/* Primary platform signatures. */
+#define JAS_ICC_PLATFORM_APPL 0x4150504c /* Apple Computer */
+#define JAS_ICC_PLATFORM_MSFT 0x4d534654 /* Microsoft */
+#define JAS_ICC_PLATFORM_SGI 0x53474920 /* Silicon Graphics */
+#define JAS_ICC_PLATFORM_SUNW 0x53554e57 /* Sun Microsystems */
+#define JAS_ICC_PLATFORM_TGNT 0x54474e54 /* Taligent */
+
+/* Profile flags. */
+#define JAS_ICC_FLAGS_EMBED 0x01 /* embedded */
+#define JAS_ICC_FLAGS_NOSEP 0x02 /* no separate use */
+
+/* Attributes. */
+#define JAS_ICC_ATTR_TRANS 0x01 /* transparent */
+#define JAS_ICC_ATTR_MATTE 0x02 /* matte */
+
+/* Rendering intents. */
+#define JAS_ICC_INTENT_PER 0 /* perceptual */
+#define JAS_ICC_INTENT_REL 1 /* relative colorimetric */
+#define JAS_ICC_INTENT_SAT 2 /* saturation */
+#define JAS_ICC_INTENT_ABS 3 /* absolute colorimetric */
+
+/* Tag signatures. */
+#define JAS_ICC_TAG_ATOB0 0x41324230 /* */
+#define JAS_ICC_TAG_ATOB1 0x41324231 /* */
+#define JAS_ICC_TAG_ATOB2 0x41324232 /* */
+#define JAS_ICC_TAG_BLUMATCOL 0x6258595a /* */
+#define JAS_ICC_TAG_BLUTRC 0x62545243 /* */
+#define JAS_ICC_TAG_BTOA0 0x42324130 /* */
+#define JAS_ICC_TAG_BTOA1 0x42324131 /* */
+#define JAS_ICC_TAG_BTOA2 0x42324132 /* */
+#define JAS_ICC_TAG_CALTIME 0x63616c74 /* */
+#define JAS_ICC_TAG_CHARTARGET 0x74617267 /* */
+#define JAS_ICC_TAG_CPYRT 0x63707274 /* */
+#define JAS_ICC_TAG_CRDINFO 0x63726469 /* */
+#define JAS_ICC_TAG_DEVMAKERDESC 0x646d6e64 /* */
+#define JAS_ICC_TAG_DEVMODELDESC 0x646d6464 /* */
+#define JAS_ICC_TAG_DEVSET 0x64657673 /* */
+#define JAS_ICC_TAG_GAMUT 0x67616d74 /* */
+#define JAS_ICC_TAG_GRYTRC 0x6b545243 /* */
+#define JAS_ICC_TAG_GRNMATCOL 0x6758595a /* */
+#define JAS_ICC_TAG_GRNTRC 0x67545243 /* */
+#define JAS_ICC_TAG_LUM 0x6c756d69 /* */
+#define JAS_ICC_TAG_MEASURE 0x6d656173 /* */
+#define JAS_ICC_TAG_MEDIABLKPT 0x626b7074 /* */
+#define JAS_ICC_TAG_MEDIAWHIPT 0x77747074 /* */
+#define JAS_ICC_TAG_NAMCOLR 0x6e636f6c /* */
+#define JAS_ICC_TAG_NAMCOLR2 0x6e636c32 /* */
+#define JAS_ICC_TAG_OUTRESP 0x72657370 /* */
+#define JAS_ICC_TAG_PREVIEW0 0x70726530 /* */
+#define JAS_ICC_TAG_PREVIEW1 0x70726531 /* */
+#define JAS_ICC_TAG_PREVIEW2 0x70726532 /* */
+#define JAS_ICC_TAG_PROFDESC 0x64657363 /* */
+#define JAS_ICC_TAG_PROFSEQDESC 0x70736571 /* */
+#define JAS_ICC_TAG_PSDCRD0 0x70736430 /* */
+#define JAS_ICC_TAG_PSCRDD1 0x70736431 /* */
+#define JAS_ICC_TAG_PSCRDD2 0x70736432 /* */
+#define JAS_ICC_TAG_PSCRDD3 0x70736433 /* */
+#define JAS_ICC_TAG_PS2CSA 0x70733273 /* */
+#define JAS_ICC_TAG_PS2RENINTENT 0x70733269 /* */
+#define JAS_ICC_TAG_REDMATCOL 0x7258595a /* */
+#define JAS_ICC_TAG_REDTRC 0x72545243 /* */
+#define JAS_ICC_TAG_SCRNGDES 0x73637264 /* */
+#define JAS_ICC_TAG_SCRNG 0x7363726e /* */
+#define JAS_ICC_TAG_TECH 0x74656368 /* */
+#define JAS_ICC_TAG_UCRBG 0x62666420 /* */
+#define JAS_ICC_TAG_VIEWCONDDESC 0x76756564 /* */
+#define JAS_ICC_TAG_VIEWCOND 0x76696577 /* */
+
+/* Type signatures. */
+#define JAS_ICC_TYPE_CRDINFO 0x63726469 /* CRD information */
+#define JAS_ICC_TYPE_CURV 0x63757276 /* curve */
+#define JAS_ICC_TYPE_DATA 0x64617461 /* data */
+#define JAS_ICC_TYPE_TIME 0x6474696d /* date/time */
+#define JAS_ICC_TYPE_DEVSET 0x64657673 /* device settings */
+#define JAS_ICC_TYPE_LUT16 0x6d667432 /* */
+#define JAS_ICC_TYPE_LUT8 0x6d667431 /* */
+#define JAS_ICC_TYPE_MEASURE 0x6d656173 /* */
+#define JAS_ICC_TYPE_NAMCOLR 0x6e636f6c /* */
+#define JAS_ICC_TYPE_NAMCOLR2 0x6e636c32 /* */
+#define JAS_ICC_TYPE_PROFSEQDESC 0x70736571 /* profile sequence description */
+#define JAS_ICC_TYPE_RESPCURVSET16 0x72637332 /* response curve set 16 */
+#define JAS_ICC_TYPE_SF32 0x73663332 /* signed 32-bit fixed-point */
+#define JAS_ICC_TYPE_SCRNG 0x7363726e /* screening */
+#define JAS_ICC_TYPE_SIG 0x73696720 /* signature */
+#define JAS_ICC_TYPE_TXTDESC 0x64657363 /* text description */
+#define JAS_ICC_TYPE_TXT 0x74657874 /* text */
+#define JAS_ICC_TYPE_UF32 0x75663332 /* unsigned 32-bit fixed-point */
+#define JAS_ICC_TYPE_UCRBG 0x62666420 /* */
+#define JAS_ICC_TYPE_UI16 0x75693136 /* */
+#define JAS_ICC_TYPE_UI32 0x75693332 /* */
+#define JAS_ICC_TYPE_UI8 0x75693038 /* */
+#define JAS_ICC_TYPE_UI64 0x75693634 /* */
+#define JAS_ICC_TYPE_VIEWCOND 0x76696577 /* */
+#define JAS_ICC_TYPE_XYZ 0x58595a20 /* XYZ */
+
+typedef uint_fast8_t jas_iccuint8_t;
+typedef uint_fast16_t jas_iccuint16_t;
+typedef uint_fast32_t jas_iccuint32_t;
+typedef int_fast32_t jas_iccsint32_t;
+typedef int_fast32_t jas_iccs15fixed16_t;
+typedef uint_fast32_t jas_iccu16fixed16_t;
+typedef uint_fast64_t jas_iccuint64_t;
+typedef uint_fast32_t jas_iccsig_t;
+
+typedef jas_iccsig_t jas_icctagsig_t;
+typedef jas_iccsig_t jas_icctagtype_t;
+typedef jas_iccsig_t jas_iccattrname_t;
+
+/* Date/time type. */
+typedef struct {
+ jas_iccuint16_t year;
+ jas_iccuint16_t month;
+ jas_iccuint16_t day;
+ jas_iccuint16_t hour;
+ jas_iccuint16_t min;
+ jas_iccuint16_t sec;
+} jas_icctime_t;
+
+/* XYZ type. */
+typedef struct {
+ jas_iccs15fixed16_t x;
+ jas_iccs15fixed16_t y;
+ jas_iccs15fixed16_t z;
+} jas_iccxyz_t;
+
+/* Curve type. */
+typedef struct {
+ jas_iccuint32_t numents;
+ jas_iccuint16_t *ents;
+} jas_icccurv_t;
+
+/* Text description type. */
+typedef struct {
+ jas_iccuint32_t asclen;
+ char *ascdata; /* ASCII invariant description */
+ jas_iccuint32_t uclangcode; /* Unicode language code */
+ jas_iccuint32_t uclen; /* Unicode localizable description count */
+ uchar *ucdata; /* Unicode localizable description */
+ jas_iccuint16_t sccode; /* ScriptCode code */
+ jas_iccuint8_t maclen; /* Localizable Macintosh description count */
+ uchar macdata[69]; /* Localizable Macintosh description */
+} jas_icctxtdesc_t;
+
+/* Text type. */
+typedef struct {
+ char *string; /* ASCII character string */
+} jas_icctxt_t;
+
+typedef struct {
+ jas_iccuint8_t numinchans;
+ jas_iccuint8_t numoutchans;
+ jas_iccsint32_t e[3][3];
+ jas_iccuint8_t clutlen;
+ jas_iccuint8_t *clut;
+ jas_iccuint16_t numintabents;
+ jas_iccuint8_t **intabs;
+ jas_iccuint8_t *intabsbuf;
+ jas_iccuint16_t numouttabents;
+ jas_iccuint8_t **outtabs;
+ jas_iccuint8_t *outtabsbuf;
+} jas_icclut8_t;
+
+typedef struct {
+ jas_iccuint8_t numinchans;
+ jas_iccuint8_t numoutchans;
+ jas_iccsint32_t e[3][3];
+ jas_iccuint8_t clutlen;
+ jas_iccuint16_t *clut;
+ jas_iccuint16_t numintabents;
+ jas_iccuint16_t **intabs;
+ jas_iccuint16_t *intabsbuf;
+ jas_iccuint16_t numouttabents;
+ jas_iccuint16_t **outtabs;
+ jas_iccuint16_t *outtabsbuf;
+} jas_icclut16_t;
+
+struct jas_iccattrval_s;
+
+typedef struct {
+ void (*destroy)(struct jas_iccattrval_s *);
+ int (*copy)(struct jas_iccattrval_s *, struct jas_iccattrval_s *);
+ int (*input)(struct jas_iccattrval_s *, jas_stream_t *, int);
+ int (*output)(struct jas_iccattrval_s *, jas_stream_t *);
+ int (*getsize)(struct jas_iccattrval_s *);
+ void (*dump)(struct jas_iccattrval_s *, FILE *);
+} jas_iccattrvalops_t;
+
+/* Attribute value type (type and value information). */
+typedef struct jas_iccattrval_s {
+ int refcnt; /* reference count */
+ jas_iccsig_t type; /* type */
+ jas_iccattrvalops_t *ops; /* type-dependent operations */
+ union {
+ jas_iccxyz_t xyz;
+ jas_icccurv_t curv;
+ jas_icctxtdesc_t txtdesc;
+ jas_icctxt_t txt;
+ jas_icclut8_t lut8;
+ jas_icclut16_t lut16;
+ } data; /* value */
+} jas_iccattrval_t;
+
+/* Header type. */
+typedef struct {
+ jas_iccuint32_t size; /* profile size */
+ jas_iccsig_t cmmtype; /* CMM type signature */
+ jas_iccuint32_t version; /* profile version */
+ jas_iccsig_t clas; /* profile/device class signature */
+ jas_iccsig_t colorspc; /* color space of data */
+ jas_iccsig_t refcolorspc; /* profile connection space */
+ jas_icctime_t ctime; /* creation time */
+ jas_iccsig_t magic; /* profile file signature */
+ jas_iccsig_t platform; /* primary platform */
+ jas_iccuint32_t flags; /* profile flags */
+ jas_iccsig_t maker; /* device manufacturer signature */
+ jas_iccsig_t model; /* device model signature */
+ jas_iccuint64_t attr; /* device setup attributes */
+ jas_iccsig_t intent; /* rendering intent */
+ jas_iccxyz_t illum; /* illuminant */
+ jas_iccsig_t creator; /* profile creator signature */
+} jas_icchdr_t;
+
+typedef struct {
+ jas_iccsig_t name;
+ jas_iccattrval_t *val;
+} jas_iccattr_t;
+
+typedef struct {
+ int numattrs;
+ int maxattrs;
+ jas_iccattr_t *attrs;
+} jas_iccattrtab_t;
+
+typedef struct jas_icctagtabent_s {
+ jas_iccuint32_t tag;
+ jas_iccuint32_t off;
+ jas_iccuint32_t len;
+ void *data;
+ struct jas_icctagtabent_s *first;
+} jas_icctagtabent_t;
+
+typedef struct {
+ jas_iccuint32_t numents;
+ jas_icctagtabent_t *ents;
+} jas_icctagtab_t;
+
+/* ICC profile type. */
+typedef struct {
+ jas_icchdr_t hdr;
+ jas_icctagtab_t tagtab;
+ jas_iccattrtab_t *attrtab;
+} jas_iccprof_t;
+
+typedef struct {
+ jas_iccuint32_t type;
+ jas_iccattrvalops_t ops;
+} jas_iccattrvalinfo_t;
+
+jas_iccprof_t *jas_iccprof_load(jas_stream_t *in);
+int jas_iccprof_save(jas_iccprof_t *prof, jas_stream_t *out);
+void jas_iccprof_destroy(jas_iccprof_t *prof);
+jas_iccattrval_t *jas_iccprof_getattr(jas_iccprof_t *prof,
+ jas_iccattrname_t name);
+int jas_iccprof_setattr(jas_iccprof_t *prof, jas_iccattrname_t name,
+ jas_iccattrval_t *val);
+void jas_iccprof_dump(jas_iccprof_t *prof, FILE *out);
+jas_iccprof_t *jas_iccprof_copy(jas_iccprof_t *prof);
+int jas_iccprof_gethdr(jas_iccprof_t *prof, jas_icchdr_t *hdr);
+int jas_iccprof_sethdr(jas_iccprof_t *prof, jas_icchdr_t *hdr);
+
+void jas_iccattrval_destroy(jas_iccattrval_t *attrval);
+void jas_iccattrval_dump(jas_iccattrval_t *attrval, FILE *out);
+int jas_iccattrval_allowmodify(jas_iccattrval_t **attrval);
+jas_iccattrval_t *jas_iccattrval_clone(jas_iccattrval_t *attrval);
+jas_iccattrval_t *jas_iccattrval_create(jas_iccuint32_t type);
+
+void jas_iccattrtab_dump(jas_iccattrtab_t *attrtab, FILE *out);
+
+extern uchar jas_iccprofdata_srgb[];
+extern int jas_iccprofdata_srgblen;
+extern uchar jas_iccprofdata_sgray[];
+extern int jas_iccprofdata_sgraylen;
+jas_iccprof_t *jas_iccprof_createfrombuf(uchar *buf, int len);
+jas_iccprof_t *jas_iccprof_createfromclrspc(int clrspc);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_image.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_image.h
new file mode 100644
index 0000000..3ccb749
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_image.h
@@ -0,0 +1,564 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Image Class
+ *
+ * $Id$
+ */
+
+#ifndef JAS_IMAGE_H
+#define JAS_IMAGE_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <jasper/jas_config.h>
+#include <jasper/jas_stream.h>
+#include <jasper/jas_seq.h>
+#include <jasper/jas_cm.h>
+#include <stdio.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/*
+ * Miscellaneous constants.
+ */
+
+/* The threshold at which image data is no longer stored in memory. */
+#define JAS_IMAGE_INMEMTHRESH (16 * 1024 * 1024)
+
+/*
+ * Component types
+ */
+
+#define JAS_IMAGE_CT_UNKNOWN 0x10000
+#define JAS_IMAGE_CT_COLOR(n) ((n) & 0x7fff)
+#define JAS_IMAGE_CT_OPACITY 0x08000
+
+#define JAS_IMAGE_CT_RGB_R 0
+#define JAS_IMAGE_CT_RGB_G 1
+#define JAS_IMAGE_CT_RGB_B 2
+
+#define JAS_IMAGE_CT_YCBCR_Y 0
+#define JAS_IMAGE_CT_YCBCR_CB 1
+#define JAS_IMAGE_CT_YCBCR_CR 2
+
+#define JAS_IMAGE_CT_GRAY_Y 0
+
+/******************************************************************************\
+* Simple types.
+\******************************************************************************/
+
+/* Image coordinate. */
+typedef int_fast32_t jas_image_coord_t;
+
+/* Color space (e.g., RGB, YCbCr). */
+typedef int_fast16_t jas_image_colorspc_t;
+
+/* Component type (e.g., color, opacity). */
+typedef int_fast32_t jas_image_cmpttype_t;
+
+/* Component sample data format (e.g., real/integer, signedness, precision). */
+typedef int_fast16_t jas_image_smpltype_t;
+
+/******************************************************************************\
+* Image class and supporting classes.
+\******************************************************************************/
+
+/* Image component class. */
+
+typedef struct {
+
+ jas_image_coord_t tlx_;
+ /* The x-coordinate of the top-left corner of the component. */
+
+ jas_image_coord_t tly_;
+ /* The y-coordinate of the top-left corner of the component. */
+
+ jas_image_coord_t hstep_;
+ /* The horizontal sampling period in units of the reference grid. */
+
+ jas_image_coord_t vstep_;
+ /* The vertical sampling period in units of the reference grid. */
+
+ jas_image_coord_t width_;
+ /* The component width in samples. */
+
+ jas_image_coord_t height_;
+ /* The component height in samples. */
+
+#ifdef FIX_ME
+ int smpltype_;
+#else
+ int prec_;
+ /* The precision of the sample data (i.e., the number of bits per
+ sample). If the samples are signed values, this quantity
+ includes the sign bit. */
+
+ int sgnd_;
+ /* The signedness of the sample data. */
+#endif
+
+ jas_stream_t *stream_;
+ /* The stream containing the component data. */
+
+ int cps_;
+ /* The number of characters per sample in the stream. */
+
+ jas_image_cmpttype_t type_;
+ /* The type of component (e.g., opacity, red, green, blue, luma). */
+
+} jas_image_cmpt_t;
+
+/* Image class. */
+
+typedef struct {
+
+ jas_image_coord_t tlx_;
+ /* The x-coordinate of the top-left corner of the image bounding box. */
+
+ jas_image_coord_t tly_;
+ /* The y-coordinate of the top-left corner of the image bounding box. */
+
+ jas_image_coord_t brx_;
+ /* The x-coordinate of the bottom-right corner of the image bounding
+ box (plus one). */
+
+ jas_image_coord_t bry_;
+ /* The y-coordinate of the bottom-right corner of the image bounding
+ box (plus one). */
+
+ int numcmpts_;
+ /* The number of components. */
+
+ int maxcmpts_;
+ /* The maximum number of components that this image can have (i.e., the
+ allocated size of the components array). */
+
+ jas_image_cmpt_t **cmpts_;
+ /* Per-component information. */
+
+ jas_clrspc_t clrspc_;
+
+ jas_cmprof_t *cmprof_;
+
+ bool inmem_;
+
+} jas_image_t;
+
+/* Component parameters class. */
+/* This data type exists solely/mainly for the purposes of the
+ jas_image_create function. */
+
+typedef struct {
+
+ jas_image_coord_t tlx;
+ /* The x-coordinate of the top-left corner of the component. */
+
+ jas_image_coord_t tly;
+ /* The y-coordinate of the top-left corner of the component. */
+
+ jas_image_coord_t hstep;
+ /* The horizontal sampling period in units of the reference grid. */
+
+ jas_image_coord_t vstep;
+ /* The vertical sampling period in units of the reference grid. */
+
+ jas_image_coord_t width;
+ /* The width of the component in samples. */
+
+ jas_image_coord_t height;
+ /* The height of the component in samples. */
+
+#ifdef FIX_ME
+ int smpltype;
+#else
+ int prec;
+ /* The precision of the component sample data. */
+
+ int sgnd;
+ /* The signedness of the component sample data. */
+#endif
+
+} jas_image_cmptparm_t;
+
+/******************************************************************************\
+* File format related classes.
+\******************************************************************************/
+
+#define JAS_IMAGE_MAXFMTS 32
+/* The maximum number of image data formats supported. */
+
+/* Image format-dependent operations. */
+
+typedef struct {
+
+ jas_image_t *(*decode)(jas_stream_t *in, char *opts);
+ /* 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 (*validate)(jas_stream_t *in);
+ /* Determine if stream data is in a particular format. */
+
+} jas_image_fmtops_t;
+
+/* Image format information. */
+
+typedef struct {
+
+ int id;
+ /* The ID for this format. */
+
+ char *name;
+ /* The name by which this format is identified. */
+
+ char *ext;
+ /* The file name extension associated with this format. */
+
+ char *desc;
+ /* A brief description of the format. */
+
+ jas_image_fmtops_t ops;
+ /* The operations for this format. */
+
+} jas_image_fmtinfo_t;
+
+/******************************************************************************\
+* Image operations.
+\******************************************************************************/
+
+/* Create an image. */
+jas_image_t *jas_image_create(int numcmpts,
+ jas_image_cmptparm_t *cmptparms, jas_clrspc_t clrspc);
+
+/* Create an "empty" image. */
+jas_image_t *jas_image_create0(void);
+
+/* Clone an image. */
+jas_image_t *jas_image_copy(jas_image_t *image);
+
+/* Deallocate any resources associated with an image. */
+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_)
+
+/* Get the height of the image in units of the image reference grid. */
+#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_)
+
+/* 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_)
+
+/* 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_)
+
+/* 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_)
+
+/* Get the number of image components. */
+#define jas_image_numcmpts(image) \
+ ((image)->numcmpts_)
+
+/* Get the color model used by the image. */
+#define jas_image_clrspc(image) \
+ ((image)->clrspc_)
+
+/* Set the color model for an image. */
+#define jas_image_setclrspc(image, clrspc) \
+ ((image)->clrspc_ = (clrspc))
+
+#define jas_image_cmpttype(image, cmptno) \
+ ((image)->cmpts_[(cmptno)]->type_)
+#define jas_image_setcmpttype(image, cmptno, type) \
+ ((image)->cmpts_[(cmptno)]->type_ = (type))
+
+/* Get the width of a component. */
+#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_)
+
+/* Get the signedness of the sample data for a component. */
+#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_)
+
+/* Get the horizontal subsampling factor for a component. */
+#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_)
+
+/* Get the x-coordinate of the top-left corner of a component. */
+#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_)
+
+/* 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_)
+
+/* 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_)
+
+/* Get the raw size of an image (i.e., the nominal size of the image without
+ any compression. */
+uint_fast32_t jas_image_rawsize(jas_image_t *image);
+
+/* Create an image from a stream in some specified format. */
+jas_image_t *jas_image_decode(jas_stream_t *in, int fmt, char *optstr);
+
+/* Write an image to a stream in a specified format. */
+int jas_image_encode(jas_image_t *image, jas_stream_t *out, int fmt,
+ char *optstr);
+
+/* Read a rectangular region of an image component. */
+/* The position and size of the rectangular region to be read is specified
+relative to the component's coordinate system. */
+int jas_image_readcmpt(jas_image_t *image, int cmptno,
+ jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height,
+ jas_matrix_t *data);
+
+/* Write a rectangular region of an image component. */
+int jas_image_writecmpt(jas_image_t *image, int cmptno,
+ jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height,
+ jas_matrix_t *data);
+
+/* Delete a component from an image. */
+void jas_image_delcmpt(jas_image_t *image, int cmptno);
+
+/* Add a component to an image. */
+int jas_image_addcmpt(jas_image_t *image, int cmptno,
+ jas_image_cmptparm_t *cmptparm);
+
+/* Copy a component from one image to another. */
+int jas_image_copycmpt(jas_image_t *dstimage, int dstcmptno,
+ jas_image_t *srcimage, int srccmptno);
+
+#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_))
+
+int jas_image_depalettize(jas_image_t *image, int cmptno, int numlutents,
+ int_fast32_t *lutents, int dtype, int newcmptno);
+
+int jas_image_readcmptsample(jas_image_t *image, int cmptno, int x, int y);
+void jas_image_writecmptsample(jas_image_t *image, int cmptno, int x, int y,
+ int_fast32_t v);
+
+int jas_image_getcmptbytype(jas_image_t *image, int ctype);
+
+/******************************************************************************\
+* Image format-related operations.
+\******************************************************************************/
+
+/* Clear the table of image formats. */
+void jas_image_clearfmts(void);
+
+/* Add entry to table of image formats. */
+int jas_image_addfmt(int id, char *name, char *ext, char *desc,
+ jas_image_fmtops_t *ops);
+
+/* Get the ID for the image format with the specified name. */
+int jas_image_strtofmt(char *s);
+
+/* Get the name of the image format with the specified ID. */
+char *jas_image_fmttostr(int fmt);
+
+/* Lookup image format information by the format ID. */
+jas_image_fmtinfo_t *jas_image_lookupfmtbyid(int id);
+
+/* Lookup image format information by the format name. */
+jas_image_fmtinfo_t *jas_image_lookupfmtbyname(const char *name);
+
+/* Guess the format of an image file based on its name. */
+int jas_image_fmtfromname(char *filename);
+
+/* Get the format of image data in a stream. */
+int jas_image_getfmt(jas_stream_t *in);
+
+
+#define jas_image_cmprof(image) ((image)->cmprof_)
+int jas_image_ishomosamp(jas_image_t *image);
+int jas_image_sampcmpt(jas_image_t *image, int cmptno, int newcmptno,
+ jas_image_coord_t ho, jas_image_coord_t vo, jas_image_coord_t hs,
+ jas_image_coord_t vs, int sgnd, int prec);
+int jas_image_writecmpt2(jas_image_t *image, int cmptno, jas_image_coord_t x,
+ jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height,
+ long *buf);
+int jas_image_readcmpt2(jas_image_t *image, int cmptno, jas_image_coord_t x,
+ jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height,
+ long *buf);
+
+#define jas_image_setcmprof(image, cmprof) ((image)->cmprof_ = cmprof)
+jas_image_t *jas_image_chclrspc(jas_image_t *image, jas_cmprof_t *outprof,
+ int intent);
+void jas_image_dump(jas_image_t *image, FILE *out);
+
+/******************************************************************************\
+* Image format-dependent operations.
+\******************************************************************************/
+
+#if !defined(EXCLUDE_JPG_SUPPORT)
+/* Format-dependent operations for JPG support. */
+jas_image_t *jpg_decode(jas_stream_t *in, char *optstr);
+int jpg_encode(jas_image_t *image, jas_stream_t *out, char *optstr);
+int jpg_validate(jas_stream_t *in);
+#endif
+
+#if !defined(EXCLUDE_MIF_SUPPORT)
+/* Format-dependent operations for MIF support. */
+jas_image_t *mif_decode(jas_stream_t *in, char *optstr);
+int mif_encode(jas_image_t *image, jas_stream_t *out, char *optstr);
+int mif_validate(jas_stream_t *in);
+#endif
+
+#if !defined(EXCLUDE_PNM_SUPPORT)
+/* Format-dependent operations for PNM support. */
+jas_image_t *pnm_decode(jas_stream_t *in, char *optstr);
+int pnm_encode(jas_image_t *image, jas_stream_t *out, char *optstr);
+int pnm_validate(jas_stream_t *in);
+#endif
+
+#if !defined(EXCLUDE_RAS_SUPPORT)
+/* Format-dependent operations for Sun Rasterfile support. */
+jas_image_t *ras_decode(jas_stream_t *in, char *optstr);
+int ras_encode(jas_image_t *image, jas_stream_t *out, char *optstr);
+int ras_validate(jas_stream_t *in);
+#endif
+
+#if !defined(EXCLUDE_BMP_SUPPORT)
+/* Format-dependent operations for BMP support. */
+jas_image_t *bmp_decode(jas_stream_t *in, char *optstr);
+int bmp_encode(jas_image_t *image, jas_stream_t *out, char *optstr);
+int bmp_validate(jas_stream_t *in);
+#endif
+
+#if !defined(EXCLUDE_JP2_SUPPORT)
+/* Format-dependent operations for JP2 support. */
+jas_image_t *jp2_decode(jas_stream_t *in, char *optstr);
+int jp2_encode(jas_image_t *image, jas_stream_t *out, char *optstr);
+int jp2_validate(jas_stream_t *in);
+#endif
+
+#if !defined(EXCLUDE_JPC_SUPPORT)
+/* Format-dependent operations for JPEG-2000 code stream support. */
+jas_image_t *jpc_decode(jas_stream_t *in, char *optstr);
+int jpc_encode(jas_image_t *image, jas_stream_t *out, char *optstr);
+int jpc_validate(jas_stream_t *in);
+#endif
+
+#if !defined(EXCLUDE_PGX_SUPPORT)
+/* Format-dependent operations for PGX support. */
+jas_image_t *pgx_decode(jas_stream_t *in, char *optstr);
+int pgx_encode(jas_image_t *image, jas_stream_t *out, char *optstr);
+int pgx_validate(jas_stream_t *in);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_init.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_init.h
new file mode 100644
index 0000000..10301e9
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_init.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef JAS_INIT_H
+#define JAS_INIT_H
+
+#include <jasper/jas_config.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+int jas_init(void);
+
+void jas_cleanup(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_malloc.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_malloc.h
new file mode 100644
index 0000000..f2a8f8b
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_malloc.h
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Memory Allocator
+ *
+ * $Id$
+ */
+
+#ifndef JAS_MALLOC_H
+#define JAS_MALLOC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <jasper/jas_config.h>
+
+#include <stdlib.h>
+#include <stdio.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Hack follows...
+\******************************************************************************/
+
+#if defined(DEBUG_MEMALLOC)
+/* 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
+#endif
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+#if !defined(DEBUG_MEMALLOC)
+
+/* Allocate memory. */
+void *jas_malloc(size_t size);
+
+/* Free memory. */
+void jas_free(void *ptr);
+
+/* Resize a block of allocated memory. */
+void *jas_realloc(void *ptr, size_t size);
+
+/* Allocate a block of memory and initialize the contents to zero. */
+void *jas_calloc(size_t nmemb, size_t size);
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_math.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_math.h
new file mode 100644
index 0000000..fc8010f
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_math.h
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Math-Related Code
+ *
+ * $Id$
+ */
+
+#ifndef JAS_MATH_H
+#define JAS_MATH_H
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+#include <jasper/jas_config.h>
+
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Macros
+\******************************************************************************/
+
+/* Compute the absolute value. */
+#define JAS_ABS(x) \
+ (((x) >= 0) ? (x) : (-(x)))
+
+/* Compute the minimum of two values. */
+#define JAS_MIN(x, y) \
+ (((x) < (y)) ? (x) : (y))
+
+/* Compute the maximum of two values. */
+#define JAS_MAX(x, y) \
+ (((x) > (y)) ? (x) : (y))
+
+/* Compute the remainder from division (where division is defined such
+ that the remainder is always nonnegative). */
+#define JAS_MOD(x, y) \
+ (((x) < 0) ? (((-x) % (y)) ? ((y) - ((-(x)) % (y))) : (0)) : ((x) % (y)))
+
+/* Compute the integer with the specified number of least significant bits
+ set to one. */
+#define JAS_ONES(n) \
+ ((1 << (n)) - 1)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_seq.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_seq.h
new file mode 100644
index 0000000..91fe31e
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_seq.h
@@ -0,0 +1,301 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Sequence/Matrix Library
+ *
+ * $Id$
+ */
+
+#ifndef JAS_SEQ_H
+#define JAS_SEQ_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <jasper/jas_config.h>
+
+#include <jasper/jas_stream.h>
+#include <jasper/jas_types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* This matrix is a reference to another matrix. */
+#define JAS_MATRIX_REF 0x0001
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* An element in a sequence. */
+typedef int_fast32_t jas_seqent_t;
+
+/* An element in a matrix. */
+typedef int_fast32_t jas_matent_t;
+
+/* Matrix. */
+
+typedef struct {
+
+ /* Additional state information. */
+ int flags_;
+
+ /* The starting horizontal index. */
+ int_fast32_t xstart_;
+
+ /* The starting vertical index. */
+ int_fast32_t ystart_;
+
+ /* The ending horizontal index. */
+ int_fast32_t xend_;
+
+ /* The ending vertical index. */
+ int_fast32_t yend_;
+
+ /* The number of rows in the matrix. */
+ int_fast32_t numrows_;
+
+ /* The number of columns in the matrix. */
+ int_fast32_t numcols_;
+
+ /* Pointers to the start of each row. */
+ jas_seqent_t **rows_;
+
+ /* The allocated size of the rows array. */
+ int_fast32_t maxrows_;
+
+ /* The matrix data buffer. */
+ jas_seqent_t *data_;
+
+ /* The allocated size of the data array. */
+ int_fast32_t datasize_;
+
+} jas_matrix_t;
+
+typedef jas_matrix_t jas_seq2d_t;
+typedef jas_matrix_t jas_seq_t;
+
+/******************************************************************************\
+* Functions/macros for matrix class.
+\******************************************************************************/
+
+/* Get the number of rows. */
+#define jas_matrix_numrows(matrix) \
+ ((matrix)->numrows_)
+
+/* Get the number of columns. */
+#define jas_matrix_numcols(matrix) \
+ ((matrix)->numcols_)
+
+/* Get a matrix element. */
+#define jas_matrix_get(matrix, i, j) \
+ ((matrix)->rows_[i][j])
+
+/* Set a matrix element. */
+#define jas_matrix_set(matrix, 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]))
+
+/* 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)))
+
+/* Get the address of an element in a matrix. */
+#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_length(matrix) \
+ (max((matrix)->numrows_, (matrix)->numcols_))
+
+/* Create a matrix with the specified dimensions. */
+jas_matrix_t *jas_matrix_create(int numrows, int numcols);
+
+/* Destroy a matrix. */
+void jas_matrix_destroy(jas_matrix_t *matrix);
+
+/* Resize a matrix. The previous contents of the matrix are lost. */
+int jas_matrix_resize(jas_matrix_t *matrix, int numrows, int numcols);
+
+int jas_matrix_output(jas_matrix_t *matrix, FILE *out);
+
+/* Create a matrix that references part of another matrix. */
+void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0, int c0,
+ int r1, int c1);
+
+/* Create a matrix that is a reference to a row of another matrix. */
+#define jas_matrix_bindrow(mat0, mat1, r) \
+ (jas_matrix_bindsub((mat0), (mat1), (r), 0, (r), (mat1)->numcols_ - 1))
+
+/* Create a matrix that is a reference to a column of another matrix. */
+#define jas_matrix_bindcol(mat0, mat1, c) \
+ (jas_matrix_bindsub((mat0), (mat1), 0, (c), (mat1)->numrows_ - 1, (c)))
+
+/* Clip the values of matrix elements to the specified range. */
+void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval,
+ jas_seqent_t maxval);
+
+/* Arithmetic shift left of all elements in a matrix. */
+void jas_matrix_asl(jas_matrix_t *matrix, int n);
+
+/* Arithmetic shift right of all elements in a matrix. */
+void jas_matrix_asr(jas_matrix_t *matrix, int n);
+
+/* Almost-but-not-quite arithmetic shift right of all elements in a matrix. */
+void jas_matrix_divpow2(jas_matrix_t *matrix, int n);
+
+/* Set all elements of a matrix to the specified value. */
+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))
+
+/* The spacing between columns of a matrix. */
+#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);
+
+jas_matrix_t *jas_matrix_copy(jas_matrix_t *x);
+
+jas_matrix_t *jas_matrix_input(FILE *);
+
+/******************************************************************************\
+* Functions/macros for 2-D sequence class.
+\******************************************************************************/
+
+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_)
+
+void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, int xstart,
+ int ystart, int xend, int yend);
+
+/******************************************************************************\
+* Functions/macros for 1-D sequence class.
+\******************************************************************************/
+
+#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_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_)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_stream.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_stream.h
new file mode 100644
index 0000000..651bea9
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_stream.h
@@ -0,0 +1,464 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * I/O Stream Class
+ *
+ * $Id$
+ */
+
+#ifndef JAS_STREAM_H
+#define JAS_STREAM_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <jasper/jas_config.h>
+
+#include <stdio.h>
+#if defined(HAVE_FCNTL_H)
+#include <fcntl.h>
+#endif
+#include <string.h>
+#if defined(HAVE_UNISTD_H)
+#include <unistd.h>
+#endif
+#include <jasper/jas_types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* On most UNIX systems, we probably need to define O_BINARY ourselves. */
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
+/*
+ * Stream open flags.
+ */
+
+/* The stream was opened for reading. */
+#define JAS_STREAM_READ 0x0001
+/* The stream was opened for writing. */
+#define JAS_STREAM_WRITE 0x0002
+/* The stream was opened for appending. */
+#define JAS_STREAM_APPEND 0x0004
+/* The stream was opened in binary mode. */
+#define JAS_STREAM_BINARY 0x0008
+/* The stream should be created/truncated. */
+#define JAS_STREAM_CREATE 0x0010
+
+
+/*
+ * Stream buffering flags.
+ */
+
+/* The stream is unbuffered. */
+#define JAS_STREAM_UNBUF 0x0000
+/* The stream is line buffered. */
+#define JAS_STREAM_LINEBUF 0x0001
+/* The stream is fully buffered. */
+#define JAS_STREAM_FULLBUF 0x0002
+/* The buffering mode mask. */
+#define JAS_STREAM_BUFMODEMASK 0x000f
+
+/* The memory associated with the buffer needs to be deallocated when the
+ stream is destroyed. */
+#define JAS_STREAM_FREEBUF 0x0008
+/* The buffer is currently being used for reading. */
+#define JAS_STREAM_RDBUF 0x0010
+/* The buffer is currently being used for writing. */
+#define JAS_STREAM_WRBUF 0x0020
+
+/*
+ * Stream error flags.
+ */
+
+/* The end-of-file has been encountered (on reading). */
+#define JAS_STREAM_EOF 0x0001
+/* An I/O error has been encountered on the stream. */
+#define JAS_STREAM_ERR 0x0002
+/* The read/write limit has been exceeded. */
+#define JAS_STREAM_RWLIMIT 0x0004
+/* The error mask. */
+#define JAS_STREAM_ERRMASK \
+ (JAS_STREAM_EOF | JAS_STREAM_ERR | JAS_STREAM_RWLIMIT)
+
+/*
+ * Other miscellaneous constants.
+ */
+
+/* The default buffer size (for fully-buffered operation). */
+#define JAS_STREAM_BUFSIZE 8192
+/* The default permission mask for file creation. */
+#define JAS_STREAM_PERMS 0666
+
+/* The maximum number of characters that can always be put back on a stream. */
+#define JAS_STREAM_MAXPUTBACK 16
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/*
+ * Generic file object.
+ */
+
+typedef void jas_stream_obj_t;
+
+/*
+ * Generic file object operations.
+ */
+
+typedef struct {
+
+ /* Read characters from a file object. */
+ int (*read_)(jas_stream_obj_t *obj, char *buf, 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);
+
+ /* Close a file object. */
+ int (*close_)(jas_stream_obj_t *obj);
+
+} jas_stream_ops_t;
+
+/*
+ * Stream object.
+ */
+
+typedef struct {
+
+ /* The mode in which the stream was opened. */
+ int openmode_;
+
+ /* The buffering mode. */
+ int bufmode_;
+
+ /* The stream status. */
+ int flags_;
+
+ /* The start of the buffer area to use for reading/writing. */
+ uchar *bufbase_;
+
+ /* The start of the buffer area excluding the extra initial space for
+ character putback. */
+ uchar *bufstart_;
+
+ /* The buffer size. */
+ int bufsize_;
+
+ /* The current position in the buffer. */
+ uchar *ptr_;
+
+ /* The number of characters that must be read/written before
+ the buffer needs to be filled/flushed. */
+ int cnt_;
+
+ /* A trivial buffer to be used for unbuffered operation. */
+ uchar tinybuf_[JAS_STREAM_MAXPUTBACK + 1];
+
+ /* The operations for the underlying stream file object. */
+ jas_stream_ops_t *ops_;
+
+ /* The underlying stream file object. */
+ jas_stream_obj_t *obj_;
+
+ /* The number of characters read/written. */
+ long rwcnt_;
+
+ /* The maximum number of characters that may be read/written. */
+ long rwlimit_;
+
+} jas_stream_t;
+
+/*
+ * Regular file object.
+ */
+
+/*
+ * File descriptor file object.
+ */
+typedef struct {
+ int fd;
+ int flags;
+ char pathname[L_tmpnam + 1];
+} jas_stream_fileobj_t;
+
+#define JAS_STREAM_FILEOBJ_DELONCLOSE 0x01
+#define JAS_STREAM_FILEOBJ_NOCLOSE 0x02
+
+/*
+ * Memory file object.
+ */
+
+typedef struct {
+
+ /* The data associated with this file. */
+ uchar *buf_;
+
+ /* The allocated size of the buffer for holding file data. */
+ int bufsize_;
+
+ /* The length of the file. */
+ int_fast32_t len_;
+
+ /* The seek position. */
+ int_fast32_t pos_;
+
+ /* Is the buffer growable? */
+ int growable_;
+
+ /* Was the buffer allocated internally? */
+ int myalloc_;
+
+} jas_stream_memobj_t;
+
+/******************************************************************************\
+* Macros/functions for opening and closing streams.
+\******************************************************************************/
+
+/* Open a file as a stream. */
+jas_stream_t *jas_stream_fopen(const char *filename, const char *mode);
+
+/* Open a memory buffer as a stream. */
+jas_stream_t *jas_stream_memopen(char *buf, int bufsize);
+
+/* Open a file descriptor as a stream. */
+jas_stream_t *jas_stream_fdopen(int fd, const char *mode);
+
+/* Open a stdio stream as a stream. */
+jas_stream_t *jas_stream_freopen(const char *path, const char *mode, FILE *fp);
+
+/* Open a temporary file as a stream. */
+jas_stream_t *jas_stream_tmpfile(void);
+
+/* Close a stream. */
+int jas_stream_close(jas_stream_t *stream);
+
+/******************************************************************************\
+* Macros/functions for getting/setting the stream state.
+\******************************************************************************/
+
+/* Get the EOF indicator for a stream. */
+#define jas_stream_eof(stream) \
+ (((stream)->flags_ & JAS_STREAM_EOF) != 0)
+
+/* Get the error indicator for a stream. */
+#define jas_stream_error(stream) \
+ (((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))
+
+/* Get the read/write limit for a stream. */
+#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_)
+
+/* Set the read/write count for a stream. */
+long jas_stream_setrwcount(jas_stream_t *stream, long rwcnt);
+
+/******************************************************************************\
+* Macros/functions for I/O.
+\******************************************************************************/
+
+/* Read a character from a stream. */
+#if defined(DEBUG)
+#define jas_stream_getc(stream) jas_stream_getc_func(stream)
+#else
+#define jas_stream_getc(stream) jas_stream_getc_macro(stream)
+#endif
+
+/* Write a character to a stream. */
+#if defined(DEBUG)
+#define jas_stream_putc(stream, c) jas_stream_putc_func(stream, c)
+#else
+#define jas_stream_putc(stream, c) jas_stream_putc_macro(stream, c)
+#endif
+
+/* Read characters from a stream into a buffer. */
+int jas_stream_read(jas_stream_t *stream, void *buf, int cnt);
+
+/* Write characters from a buffer to a stream. */
+int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt);
+
+/* Write formatted output to a stream. */
+int jas_stream_printf(jas_stream_t *stream, const char *fmt, ...);
+
+/* Write a string to a stream. */
+int jas_stream_puts(jas_stream_t *stream, const char *s);
+
+/* Read a line of input from a stream. */
+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_)))
+
+/* Put a character back on a stream. */
+int jas_stream_ungetc(jas_stream_t *stream, int c);
+
+/******************************************************************************\
+* Macros/functions for getting/setting the stream position.
+\******************************************************************************/
+
+/* Is it possible to seek on this stream? */
+int jas_stream_isseekable(jas_stream_t *stream);
+
+/* Set the current position within the stream. */
+long jas_stream_seek(jas_stream_t *stream, long offset, int origin);
+
+/* Get the current position within the stream. */
+long jas_stream_tell(jas_stream_t *stream);
+
+/* Seek to the beginning of a stream. */
+int jas_stream_rewind(jas_stream_t *stream);
+
+/******************************************************************************\
+* Macros/functions for flushing.
+\******************************************************************************/
+
+/* Flush any pending output to a stream. */
+int jas_stream_flush(jas_stream_t *stream);
+
+/******************************************************************************\
+* Miscellaneous macros/functions.
+\******************************************************************************/
+
+/* Copy data from one stream to another. */
+int jas_stream_copy(jas_stream_t *dst, jas_stream_t *src, int n);
+
+/* Display stream contents (for debugging purposes). */
+int jas_stream_display(jas_stream_t *stream, FILE *fp, int n);
+
+/* Consume (i.e., discard) characters from stream. */
+int jas_stream_gobble(jas_stream_t *stream, int n);
+
+/* Write a character multiple times to a stream. */
+int jas_stream_pad(jas_stream_t *stream, int n, int c);
+
+/* Get the size of the file associated with the specified stream.
+ The specified stream must be seekable. */
+long jas_stream_length(jas_stream_t *stream);
+
+/******************************************************************************\
+* Internal functions.
+\******************************************************************************/
+
+/* The following functions are for internal use only! If you call them
+directly, you will die a horrible, miserable, and painful death! */
+
+/* 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)
+#define jas_stream_getc2(stream) \
+ ((--(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)
+#define jas_stream_putc2(stream, c) \
+ (((stream)->bufmode_ |= JAS_STREAM_WRBUF, --(stream)->cnt_ < 0) ? \
+ jas_stream_flushbuf((stream), (uchar)(c)) : \
+ (++(stream)->rwcnt_, (int)(*(stream)->ptr_++ = (c))))
+
+/* These prototypes need to be here for the sake of the stream_getc and
+stream_putc macros. */
+int jas_stream_fillbuf(jas_stream_t *stream, int getflag);
+int jas_stream_flushbuf(jas_stream_t *stream, int c);
+int jas_stream_getc_func(jas_stream_t *stream);
+int jas_stream_putc_func(jas_stream_t *stream, int c);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_string.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_string.h
new file mode 100644
index 0000000..f217da2
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_string.h
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * String Library
+ *
+ * $Id$
+ */
+
+#ifndef JAS_STRING_H
+#define JAS_STRING_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <jasper/jas_config.h>
+#include <string.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Copy a string (a la strdup). */
+char *jas_strdup(const char *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_tmr.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_tmr.h
new file mode 100644
index 0000000..837f2bf
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_tmr.h
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2004 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef JAS_TMR_H
+#define JAS_TMR_H
+
+#include<time.h>
+#include <jasper/jas_config.h>
+#if defined(HAVE_SYS_TIME_H)
+#include <sys/time.h>
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(HAVE_GETTIMEOFDAY)
+
+typedef struct {
+ struct timeval start;
+ struct timeval stop;
+} jas_tmr_t;
+
+#elif defined(HAVE_GETRUSAGE)
+
+typedef struct {
+ struct rusage start;
+ struct rusage stop;
+} jas_tmr_t;
+
+#else
+
+typedef int jas_tmr_t;
+
+#endif
+
+void jas_tmr_start(jas_tmr_t *tmr);
+void jas_tmr_stop(jas_tmr_t *tmr);
+double jas_tmr_get(jas_tmr_t *tmr);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_tvp.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_tvp.h
new file mode 100644
index 0000000..ae4f933
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_tvp.h
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tag/Value Parser
+ *
+ * $Id$
+ */
+
+#ifndef JAS_TVP_H
+#define JAS_TVP_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <jasper/jas_config.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* Tag information type. */
+
+typedef struct {
+
+ int id;
+ /* The ID for the tag. */
+
+ char *name;
+ /* The name of the tag. */
+
+} jas_taginfo_t;
+
+/* Tag-value parser type. */
+
+typedef struct {
+
+ char *buf;
+ /* The parsing buffer. */
+
+ char *tag;
+ /* The current tag name. */
+
+ char *val;
+ /* The current value. */
+
+ char *pos;
+ /* The current position in the parsing buffer. */
+
+} jas_tvparser_t;
+
+/******************************************************************************\
+* Tag information functions.
+\******************************************************************************/
+
+/* Lookup a tag by name. */
+jas_taginfo_t *jas_taginfos_lookup(jas_taginfo_t *taginfos, const char *name);
+
+/* This function returns a pointer to the specified taginfo object if it
+ exists (i.e., the pointer is nonnull); otherwise, a pointer to a dummy
+ object is returned. This is useful in some situations to avoid checking
+ for a null pointer. */
+jas_taginfo_t *jas_taginfo_nonull(jas_taginfo_t *taginfo);
+
+/******************************************************************************\
+* Tag-value parser functions.
+\******************************************************************************/
+
+/* Create a tag-value parser for the specified string. */
+jas_tvparser_t *jas_tvparser_create(const char *s);
+
+/* Destroy a tag-value parser. */
+void jas_tvparser_destroy(jas_tvparser_t *tvparser);
+
+/* Get the next tag-value pair. */
+int jas_tvparser_next(jas_tvparser_t *tvparser);
+
+/* Get the tag name for the current tag-value pair. */
+char *jas_tvparser_gettag(jas_tvparser_t *tvparser);
+
+/* Get the value for the current tag-value pair. */
+char *jas_tvparser_getval(jas_tvparser_t *tvparser);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_types.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_types.h
new file mode 100644
index 0000000..1acef11
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_types.h
@@ -0,0 +1,228 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Primitive Types
+ *
+ * $Id$
+ */
+
+#ifndef JAS_TYPES_H
+#define JAS_TYPES_H
+
+#include <jasper/jas_config.h>
+
+#if !defined(JAS_CONFIGURE)
+
+#if defined(WIN32) || defined(HAVE_WINDOWS_H)
+/*
+ We are dealing with Microsoft Windows and most likely Microsoft
+ Visual C (MSVC). (Heaven help us.) Sadly, MSVC does not correctly
+ define some of the standard types specified in ISO/IEC 9899:1999.
+ In particular, it does not define the "long long" and "unsigned long
+ long" types. So, we work around this problem by using the "INT64"
+ and "UINT64" types that are defined in the header file "windows.h".
+ */
+#include <windows.h>
+#undef longlong
+#define longlong INT64
+#undef ulonglong
+#define ulonglong UINT64
+#endif
+
+#endif
+
+#if defined(HAVE_STDLIB_H)
+#undef false
+#undef true
+#include <stdlib.h>
+#endif
+#if defined(HAVE_STDDEF_H)
+#include <stddef.h>
+#endif
+#if defined(HAVE_SYS_TYPES_H)
+#include <sys/types.h>
+#endif
+
+#ifndef __cplusplus
+#if defined(HAVE_STDBOOL_H)
+/*
+ * The C language implementation does correctly provide the standard header
+ * file "stdbool.h".
+ */
+#include <stdbool.h>
+#else
+
+/*
+ * The C language implementation does not provide the standard header file
+ * "stdbool.h" as required by ISO/IEC 9899:1999. Try to compensate for this
+ * braindamage below.
+ */
+#if !defined(bool)
+#define bool int
+#endif
+#if !defined(true)
+#define true 1
+#endif
+#if !defined(false)
+#define false 0
+#endif
+#endif
+
+#endif
+
+#if defined(HAVE_STDINT_H)
+/*
+ * The C language implementation does correctly provide the standard header
+ * file "stdint.h".
+ */
+#include <stdint.h>
+#else
+/*
+ * The C language implementation does not provide the standard header file
+ * "stdint.h" as required by ISO/IEC 9899:1999. Try to compensate for this
+ * braindamage below.
+ */
+#include <limits.h>
+/**********/
+#if !defined(INT_FAST8_MIN)
+typedef signed char int_fast8_t;
+#define INT_FAST8_MIN (-127)
+#define INT_FAST8_MAX 128
+#endif
+/**********/
+#if !defined(UINT_FAST8_MAX)
+typedef unsigned char uint_fast8_t;
+#define UINT_FAST8_MAX 255
+#endif
+/**********/
+#if !defined(INT_FAST16_MIN)
+typedef short int_fast16_t;
+#define INT_FAST16_MIN SHRT_MIN
+#define INT_FAST16_MAX SHRT_MAX
+#endif
+/**********/
+#if !defined(UINT_FAST16_MAX)
+typedef unsigned short uint_fast16_t;
+#define UINT_FAST16_MAX USHRT_MAX
+#endif
+/**********/
+#if !defined(INT_FAST32_MIN)
+typedef int int_fast32_t;
+#define INT_FAST32_MIN INT_MIN
+#define INT_FAST32_MAX INT_MAX
+#endif
+/**********/
+#if !defined(UINT_FAST32_MAX)
+typedef unsigned int uint_fast32_t;
+#define UINT_FAST32_MAX UINT_MAX
+#endif
+/**********/
+#if !defined(INT_FAST64_MIN)
+typedef longlong int_fast64_t;
+#define INT_FAST64_MIN LLONG_MIN
+#define INT_FAST64_MAX LLONG_MAX
+#endif
+/**********/
+#if !defined(UINT_FAST64_MAX)
+typedef ulonglong uint_fast64_t;
+#define UINT_FAST64_MAX ULLONG_MAX
+#endif
+/**********/
+#endif
+
+/* Hopefully, these macro definitions will fix more problems than they cause. */
+#if !defined(uchar)
+#define uchar unsigned char
+#endif
+#if !defined(ushort)
+#define ushort unsigned short
+#endif
+#if !defined(uint)
+#define uint unsigned int
+#endif
+#if !defined(ulong)
+#define ulong unsigned long
+#endif
+#if !defined(longlong)
+#define longlong long long
+#endif
+#if !defined(ulonglong)
+#define ulonglong unsigned long long
+#endif
+
+/* The below macro is intended to be used for type casts. By using this
+ macro, type casts can be easily located in the source code with
+ tools like "grep". */
+#define JAS_CAST(t, e) \
+ ((t) (e))
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_version.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_version.h
new file mode 100644
index 0000000..14da7a0
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jas_version.h
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef JAS_VERSION_H
+#define JAS_VERSION_H
+
+#include <jasper/jas_config.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************\
+* Constants and types.
+\******************************************************************************/
+
+#if !defined(JAS_VERSION)
+/* The version information below should match that specified in
+ the "configure.in" file! */
+#define JAS_VERSION "unknown"
+#endif
+
+#define JAS_COPYRIGHT \
+ "Copyright (c) 2001-2006 Michael David Adams.\n" \
+ "Copyright (c) 1999-2000 Image Power, Inc. and the University of\n" \
+ " British Columbia.\n" \
+ "All rights reserved.\n"
+
+#define JAS_NOTES \
+ "For more information about this software, please visit the following\n" \
+ "web sites/pages:\n" \
+ " http://www.ece.uvic.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 at yahoogroups.com\n" \
+ "To be added to the (unmoderated) JasPer software discussion\n" \
+ "mailing list, send an email to:\n" \
+ " jasper-discussion-subscribe at yahoogroups.com\n" \
+ "Please send any bug reports to:\n" \
+ " mdadams at ieee.org\n"
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+const char *jas_getversion(void);
+/* Get the version information for the JasPer library. */
+/* Note: Since libjasper can be built as a shared library, the version
+ returned by this function may not necessarily correspond to JAS_VERSION. */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/include/jasper/jasper.h b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jasper.h
new file mode 100644
index 0000000..eb74ba0
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/include/jasper/jasper.h
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef JAS_JASPER_H
+#define JAS_JASPER_H
+
+#include <jasper/jas_config.h>
+#include <jasper/jas_types.h>
+#include <jasper/jas_version.h>
+
+#include <jasper/jas_init.h>
+#include <jasper/jas_cm.h>
+#include <jasper/jas_icc.h>
+#include <jasper/jas_fix.h>
+#include <jasper/jas_debug.h>
+#include <jasper/jas_getopt.h>
+#include <jasper/jas_image.h>
+#include <jasper/jas_icc.h>
+#include <jasper/jas_math.h>
+#include <jasper/jas_malloc.h>
+#include <jasper/jas_seq.h>
+#include <jasper/jas_stream.h>
+#include <jasper/jas_string.h>
+#include <jasper/jas_tmr.h>
+#include <jasper/jas_tvp.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jp2/Makefile.am b/jasper-1.900.1-6ct/src/libjasper/jp2/Makefile.am
new file mode 100644
index 0000000..4887961
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jp2/Makefile.am
@@ -0,0 +1,67 @@
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+noinst_LTLIBRARIES = libjp2.la
+libjp2_la_SOURCES = \
+ jp2_cod.h \
+ jp2_dec.h \
+ jp2_cod.c \
+ jp2_dec.c \
+ jp2_enc.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
diff --git a/jasper-1.900.1-6ct/src/libjasper/jp2/Makefile.in b/jasper-1.900.1-6ct/src/libjasper/jp2/Makefile.in
new file mode 100644
index 0000000..fec1638
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jp2/Makefile.in
@@ -0,0 +1,510 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src/libjasper/jp2
+DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+LTLIBRARIES = $(noinst_LTLIBRARIES)
+libjp2_la_LIBADD =
+am_libjp2_la_OBJECTS = jp2_cod.lo jp2_dec.lo jp2_enc.lo
+libjp2_la_OBJECTS = $(am_libjp2_la_OBJECTS)
+DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/src/libjasper/include/jasper
+depcomp = $(SHELL) $(top_srcdir)/acaux/depcomp
+am__depfiles_maybe = depfiles
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LTCOMPILE = $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) \
+ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+ $(AM_CFLAGS) $(CFLAGS)
+CCLD = $(CC)
+LINK = $(LIBTOOL) --tag=CC --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+ $(AM_LDFLAGS) $(LDFLAGS) -o $@
+SOURCES = $(libjp2_la_SOURCES)
+DIST_SOURCES = $(libjp2_la_SOURCES)
+ETAGS = etags
+CTAGS = ctags
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+noinst_LTLIBRARIES = libjp2.la
+libjp2_la_SOURCES = \
+ jp2_cod.h \
+ jp2_dec.h \
+ jp2_cod.c \
+ jp2_dec.c \
+ jp2_enc.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
+all: all-am
+
+.SUFFIXES:
+.SUFFIXES: .c .lo .o .obj
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libjasper/jp2/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/libjasper/jp2/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+clean-noinstLTLIBRARIES:
+ -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
+ @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \
+ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
+ test "$$dir" != "$$p" || dir=.; \
+ echo "rm -f \"$${dir}/so_locations\""; \
+ rm -f "$${dir}/so_locations"; \
+ done
+libjp2.la: $(libjp2_la_OBJECTS) $(libjp2_la_DEPENDENCIES)
+ $(LINK) $(libjp2_la_LDFLAGS) $(libjp2_la_OBJECTS) $(libjp2_la_LIBADD) $(LIBS)
+
+mostlyclean-compile:
+ -rm -f *.$(OBJEXT)
+
+distclean-compile:
+ -rm -f *.tab.c
+
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jp2_cod.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jp2_dec.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jp2_enc.Plo at am__quote@
+
+.c.o:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c $<
+
+.c.obj:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
+
+.c.lo:
+ at am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $<
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-am
+all-am: Makefile $(LTLIBRARIES)
+installdirs:
+install: install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-am
+
+clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \
+ mostlyclean-am
+
+distclean: distclean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+distclean-am: clean-am distclean-compile distclean-generic \
+ distclean-libtool distclean-tags
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+info: info-am
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-am
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-compile mostlyclean-generic \
+ mostlyclean-libtool
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
+ clean-libtool clean-noinstLTLIBRARIES ctags distclean \
+ distclean-compile distclean-generic distclean-libtool \
+ distclean-tags distdir dvi dvi-am html html-am info info-am \
+ install install-am install-data install-data-am install-exec \
+ install-exec-am install-info install-info-am install-man \
+ install-strip installcheck installcheck-am installdirs \
+ maintainer-clean maintainer-clean-generic mostlyclean \
+ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
+ pdf pdf-am ps ps-am tags uninstall uninstall-am \
+ uninstall-info-am
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_cod.c b/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_cod.c
new file mode 100644
index 0000000..83cecb1
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_cod.c
@@ -0,0 +1,921 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JP2 Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include "jasper/jas_stream.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.h"
+
+#include "jp2_cod.h"
+
+/******************************************************************************\
+* Function prototypes.
+\******************************************************************************/
+
+#define ONES(n) ((1 << (n)) - 1)
+
+jp2_boxinfo_t *jp2_boxinfolookup(int type);
+
+static int jp2_getuint8(jas_stream_t *in, uint_fast8_t *val);
+static int jp2_getuint16(jas_stream_t *in, uint_fast16_t *val);
+static int jp2_getuint32(jas_stream_t *in, uint_fast32_t *val);
+static int jp2_getuint64(jas_stream_t *in, uint_fast64_t *val);
+static int jp2_putuint8(jas_stream_t *out, uint_fast8_t val);
+static int jp2_putuint16(jas_stream_t *out, uint_fast16_t val);
+static int jp2_putuint32(jas_stream_t *out, uint_fast32_t val);
+static int jp2_putuint64(jas_stream_t *out, uint_fast64_t val);
+
+static int jp2_getint(jas_stream_t *in, int s, int n, int_fast32_t *val);
+
+jp2_box_t *jp2_box_get(jas_stream_t *in);
+void jp2_box_dump(jp2_box_t *box, FILE *out);
+
+static int jp2_jp_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_jp_putdata(jp2_box_t *box, jas_stream_t *out);
+static int jp2_ftyp_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_ftyp_putdata(jp2_box_t *box, jas_stream_t *out);
+static int jp2_ihdr_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_ihdr_putdata(jp2_box_t *box, jas_stream_t *out);
+static void jp2_bpcc_destroy(jp2_box_t *box);
+static int jp2_bpcc_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_bpcc_putdata(jp2_box_t *box, jas_stream_t *out);
+static int jp2_colr_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_colr_putdata(jp2_box_t *box, jas_stream_t *out);
+static void jp2_colr_dumpdata(jp2_box_t *box, FILE *out);
+static void jp2_colr_destroy(jp2_box_t *box);
+static void jp2_cdef_destroy(jp2_box_t *box);
+static int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_cdef_putdata(jp2_box_t *box, jas_stream_t *out);
+static void jp2_cdef_dumpdata(jp2_box_t *box, FILE *out);
+static void jp2_cmap_destroy(jp2_box_t *box);
+static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_cmap_putdata(jp2_box_t *box, jas_stream_t *out);
+static void jp2_cmap_dumpdata(jp2_box_t *box, FILE *out);
+static void jp2_pclr_destroy(jp2_box_t *box);
+static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in);
+static int jp2_pclr_putdata(jp2_box_t *box, jas_stream_t *out);
+static void jp2_pclr_dumpdata(jp2_box_t *box, FILE *out);
+
+/******************************************************************************\
+* Local data.
+\******************************************************************************/
+
+jp2_boxinfo_t jp2_boxinfos[] = {
+ {JP2_BOX_JP, "JP", 0,
+ {0, 0, jp2_jp_getdata, jp2_jp_putdata, 0}},
+ {JP2_BOX_FTYP, "FTYP", 0,
+ {0, 0, jp2_ftyp_getdata, jp2_ftyp_putdata, 0}},
+ {JP2_BOX_JP2H, "JP2H", JP2_BOX_SUPER,
+ {0, 0, 0, 0, 0}},
+ {JP2_BOX_IHDR, "IHDR", 0,
+ {0, 0, jp2_ihdr_getdata, jp2_ihdr_putdata, 0}},
+ {JP2_BOX_BPCC, "BPCC", 0,
+ {0, jp2_bpcc_destroy, jp2_bpcc_getdata, jp2_bpcc_putdata, 0}},
+ {JP2_BOX_COLR, "COLR", 0,
+ {0, jp2_colr_destroy, jp2_colr_getdata, jp2_colr_putdata, jp2_colr_dumpdata}},
+ {JP2_BOX_PCLR, "PCLR", 0,
+ {0, jp2_pclr_destroy, jp2_pclr_getdata, jp2_pclr_putdata, jp2_pclr_dumpdata}},
+ {JP2_BOX_CMAP, "CMAP", 0,
+ {0, jp2_cmap_destroy, jp2_cmap_getdata, jp2_cmap_putdata, jp2_cmap_dumpdata}},
+ {JP2_BOX_CDEF, "CDEF", 0,
+ {0, jp2_cdef_destroy, jp2_cdef_getdata, jp2_cdef_putdata, jp2_cdef_dumpdata}},
+ {JP2_BOX_RES, "RES", JP2_BOX_SUPER,
+ {0, 0, 0, 0, 0}},
+ {JP2_BOX_RESC, "RESC", 0,
+ {0, 0, 0, 0, 0}},
+ {JP2_BOX_RESD, "RESD", 0,
+ {0, 0, 0, 0, 0}},
+ {JP2_BOX_JP2C, "JP2C", JP2_BOX_NODATA,
+ {0, 0, 0, 0, 0}},
+ {JP2_BOX_JP2I, "JP2I", 0,
+ {0, 0, 0, 0, 0}},
+ {JP2_BOX_XML, "XML", 0,
+ {0, 0, 0, 0, 0}},
+ {JP2_BOX_UUID, "UUID", 0,
+ {0, 0, 0, 0, 0}},
+ {JP2_BOX_UINF, "UINF", JP2_BOX_SUPER,
+ {0, 0, 0, 0, 0}},
+ {JP2_BOX_ULST, "ULST", 0,
+ {0, 0, 0, 0, 0}},
+ {JP2_BOX_URL, "URL", 0,
+ {0, 0, 0, 0, 0}},
+ {0, 0, 0, {0, 0, 0, 0, 0}},
+};
+
+jp2_boxinfo_t jp2_boxinfo_unk = {
+ 0, "Unknown", 0, {0, 0, 0, 0, 0}
+};
+
+/******************************************************************************\
+* Box constructor.
+\******************************************************************************/
+
+jp2_box_t *jp2_box_create(int type)
+{
+ jp2_box_t *box;
+ jp2_boxinfo_t *boxinfo;
+
+ if (!(box = jas_malloc(sizeof(jp2_box_t)))) {
+ return 0;
+ }
+ memset(box, 0, sizeof(jp2_box_t));
+ box->type = type;
+ box->len = 0;
+ if (!(boxinfo = jp2_boxinfolookup(type))) {
+ return 0;
+ }
+ box->info = boxinfo;
+ box->ops = &boxinfo->ops;
+ return box;
+}
+
+/******************************************************************************\
+* Box destructor.
+\******************************************************************************/
+
+void jp2_box_destroy(jp2_box_t *box)
+{
+ if (box->ops->destroy) {
+ (*box->ops->destroy)(box);
+ }
+ jas_free(box);
+}
+
+static void jp2_bpcc_destroy(jp2_box_t *box)
+{
+ jp2_bpcc_t *bpcc = &box->data.bpcc;
+ if (bpcc->bpcs) {
+ jas_free(bpcc->bpcs);
+ bpcc->bpcs = 0;
+ }
+}
+
+static void jp2_cdef_destroy(jp2_box_t *box)
+{
+ jp2_cdef_t *cdef = &box->data.cdef;
+ if (cdef->ents) {
+ jas_free(cdef->ents);
+ cdef->ents = 0;
+ }
+}
+
+/******************************************************************************\
+* Box input.
+\******************************************************************************/
+
+jp2_box_t *jp2_box_get(jas_stream_t *in)
+{
+ jp2_box_t *box;
+ jp2_boxinfo_t *boxinfo;
+ jas_stream_t *tmpstream;
+ uint_fast32_t len;
+ uint_fast64_t extlen;
+ bool dataflag;
+
+ box = 0;
+ tmpstream = 0;
+
+ if (!(box = jas_malloc(sizeof(jp2_box_t)))) {
+ goto error;
+ }
+ box->ops = &jp2_boxinfo_unk.ops;
+ if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) {
+ goto error;
+ }
+ boxinfo = jp2_boxinfolookup(box->type);
+ box->info = boxinfo;
+ box->ops = &boxinfo->ops;
+ box->len = len;
+ if (box->len == 1) {
+ if (jp2_getuint64(in, &extlen)) {
+ goto error;
+ }
+ if (extlen > 0xffffffffUL) {
+ jas_eprintf("warning: cannot handle large 64-bit box length\n");
+ extlen = 0xffffffffUL;
+ }
+ box->len = extlen;
+ box->datalen = extlen - JP2_BOX_HDRLEN(true);
+ } else {
+ box->datalen = box->len - JP2_BOX_HDRLEN(false);
+ }
+ if (box->len != 0 && box->len < 8) {
+ goto error;
+ }
+
+ dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
+
+ if (dataflag) {
+ if (!(tmpstream = jas_stream_memopen(0, 0))) {
+ goto error;
+ }
+ if (jas_stream_copy(tmpstream, in, box->datalen)) {
+ jas_eprintf("cannot copy box data\n");
+ goto error;
+ }
+ jas_stream_rewind(tmpstream);
+
+ if (box->ops->getdata) {
+ if ((*box->ops->getdata)(box, tmpstream)) {
+ jas_eprintf("cannot parse box data\n");
+ goto error;
+ }
+ }
+ jas_stream_close(tmpstream);
+ }
+
+ if (jas_getdbglevel() >= 1) {
+ jp2_box_dump(box, stderr);
+ }
+
+ return box;
+ abort();
+
+error:
+ if (box) {
+ jp2_box_destroy(box);
+ }
+ if (tmpstream) {
+ jas_stream_close(tmpstream);
+ }
+ return 0;
+}
+
+void jp2_box_dump(jp2_box_t *box, FILE *out)
+{
+ jp2_boxinfo_t *boxinfo;
+ boxinfo = jp2_boxinfolookup(box->type);
+ assert(boxinfo);
+
+ fprintf(out, "JP2 box: ");
+ fprintf(out, "type=%c%s%c (0x%08x); length=%d\n", '"', boxinfo->name,
+ '"', box->type, box->len);
+ if (box->ops->dumpdata) {
+ (*box->ops->dumpdata)(box, out);
+ }
+}
+
+static int jp2_jp_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+ jp2_jp_t *jp = &box->data.jp;
+ if (jp2_getuint32(in, &jp->magic)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jp2_ftyp_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+ jp2_ftyp_t *ftyp = &box->data.ftyp;
+ unsigned int i;
+ if (jp2_getuint32(in, &ftyp->majver) || jp2_getuint32(in, &ftyp->minver)) {
+ return -1;
+ }
+ ftyp->numcompatcodes = (box->datalen - 8) / 4;
+ if (ftyp->numcompatcodes > JP2_FTYP_MAXCOMPATCODES) {
+ return -1;
+ }
+ for (i = 0; i < ftyp->numcompatcodes; ++i) {
+ if (jp2_getuint32(in, &ftyp->compatcodes[i])) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static int jp2_ihdr_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+ jp2_ihdr_t *ihdr = &box->data.ihdr;
+ if (jp2_getuint32(in, &ihdr->height) || jp2_getuint32(in, &ihdr->width) ||
+ jp2_getuint16(in, &ihdr->numcmpts) || jp2_getuint8(in, &ihdr->bpc) ||
+ jp2_getuint8(in, &ihdr->comptype) || jp2_getuint8(in, &ihdr->csunk) ||
+ jp2_getuint8(in, &ihdr->ipr)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jp2_bpcc_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+ jp2_bpcc_t *bpcc = &box->data.bpcc;
+ unsigned int i;
+ bpcc->numcmpts = box->datalen;
+ if (!(bpcc->bpcs = jas_malloc(bpcc->numcmpts * sizeof(uint_fast8_t)))) {
+ return -1;
+ }
+ for (i = 0; i < bpcc->numcmpts; ++i) {
+ if (jp2_getuint8(in, &bpcc->bpcs[i])) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static void jp2_colr_dumpdata(jp2_box_t *box, FILE *out)
+{
+ jp2_colr_t *colr = &box->data.colr;
+ fprintf(out, "method=%d; pri=%d; approx=%d\n", (int)colr->method, (int)colr->pri, (int)colr->approx);
+ switch (colr->method) {
+ case JP2_COLR_ENUM:
+ fprintf(out, "csid=%d\n", (int)colr->csid);
+ break;
+ case JP2_COLR_ICC:
+ jas_memdump(out, colr->iccp, colr->iccplen);
+ break;
+ }
+}
+
+static int jp2_colr_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+ jp2_colr_t *colr = &box->data.colr;
+ colr->csid = 0;
+ colr->iccp = 0;
+ colr->iccplen = 0;
+
+ if (jp2_getuint8(in, &colr->method) || jp2_getuint8(in, &colr->pri) ||
+ jp2_getuint8(in, &colr->approx)) {
+ return -1;
+ }
+ switch (colr->method) {
+ case JP2_COLR_ENUM:
+ if (jp2_getuint32(in, &colr->csid)) {
+ return -1;
+ }
+ break;
+ case JP2_COLR_ICC:
+ colr->iccplen = box->datalen - 3;
+ if (!(colr->iccp = jas_malloc(colr->iccplen * sizeof(uint_fast8_t)))) {
+ return -1;
+ }
+ if (jas_stream_read(in, colr->iccp, colr->iccplen) != colr->iccplen) {
+ return -1;
+ }
+ break;
+ }
+ return 0;
+}
+
+static void jp2_cdef_dumpdata(jp2_box_t *box, FILE *out)
+{
+ jp2_cdef_t *cdef = &box->data.cdef;
+ unsigned int i;
+ for (i = 0; i < cdef->numchans; ++i) {
+ fprintf(out, "channo=%d; type=%d; assoc=%d\n",
+ cdef->ents[i].channo, cdef->ents[i].type, cdef->ents[i].assoc);
+ }
+}
+
+static void jp2_colr_destroy(jp2_box_t *box)
+{
+ jp2_colr_t *colr = &box->data.colr;
+ if (colr->iccp) {
+ jas_free(colr->iccp);
+ }
+}
+
+static int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+ jp2_cdef_t *cdef = &box->data.cdef;
+ jp2_cdefchan_t *chan;
+ unsigned int channo;
+ if (jp2_getuint16(in, &cdef->numchans)) {
+ return -1;
+ }
+ if (!(cdef->ents = jas_malloc(cdef->numchans * sizeof(jp2_cdefchan_t)))) {
+ return -1;
+ }
+ for (channo = 0; channo < cdef->numchans; ++channo) {
+ chan = &cdef->ents[channo];
+ if (jp2_getuint16(in, &chan->channo) || jp2_getuint16(in, &chan->type) ||
+ jp2_getuint16(in, &chan->assoc)) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Box output.
+\******************************************************************************/
+
+int jp2_box_put(jp2_box_t *box, jas_stream_t *out)
+{
+ jas_stream_t *tmpstream;
+ bool extlen;
+ bool dataflag;
+
+ tmpstream = 0;
+
+ dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
+
+ if (dataflag) {
+ tmpstream = jas_stream_memopen(0, 0);
+ if (box->ops->putdata) {
+ if ((*box->ops->putdata)(box, tmpstream)) {
+ goto error;
+ }
+ }
+ box->len = jas_stream_tell(tmpstream) + JP2_BOX_HDRLEN(false);
+ jas_stream_rewind(tmpstream);
+ }
+ extlen = (box->len >= (((uint_fast64_t)1) << 32)) != 0;
+ if (jp2_putuint32(out, extlen ? 1 : box->len)) {
+ goto error;
+ }
+ if (jp2_putuint32(out, box->type)) {
+ goto error;
+ }
+ if (extlen) {
+ if (jp2_putuint64(out, box->len)) {
+ goto error;
+ }
+ }
+
+ if (dataflag) {
+ if (jas_stream_copy(out, tmpstream, box->len - JP2_BOX_HDRLEN(false))) {
+ goto error;
+ }
+ jas_stream_close(tmpstream);
+ }
+
+ return 0;
+ abort();
+
+error:
+
+ if (tmpstream) {
+ jas_stream_close(tmpstream);
+ }
+ return -1;
+}
+
+static int jp2_jp_putdata(jp2_box_t *box, jas_stream_t *out)
+{
+ jp2_jp_t *jp = &box->data.jp;
+ if (jp2_putuint32(out, jp->magic)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jp2_ftyp_putdata(jp2_box_t *box, jas_stream_t *out)
+{
+ jp2_ftyp_t *ftyp = &box->data.ftyp;
+ unsigned int i;
+ if (jp2_putuint32(out, ftyp->majver) || jp2_putuint32(out, ftyp->minver)) {
+ return -1;
+ }
+ for (i = 0; i < ftyp->numcompatcodes; ++i) {
+ if (jp2_putuint32(out, ftyp->compatcodes[i])) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static int jp2_ihdr_putdata(jp2_box_t *box, jas_stream_t *out)
+{
+ jp2_ihdr_t *ihdr = &box->data.ihdr;
+ if (jp2_putuint32(out, ihdr->height) || jp2_putuint32(out, ihdr->width) ||
+ jp2_putuint16(out, ihdr->numcmpts) || jp2_putuint8(out, ihdr->bpc) ||
+ jp2_putuint8(out, ihdr->comptype) || jp2_putuint8(out, ihdr->csunk) ||
+ jp2_putuint8(out, ihdr->ipr)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jp2_bpcc_putdata(jp2_box_t *box, jas_stream_t *out)
+{
+ jp2_bpcc_t *bpcc = &box->data.bpcc;
+ unsigned int i;
+ for (i = 0; i < bpcc->numcmpts; ++i) {
+ if (jp2_putuint8(out, bpcc->bpcs[i])) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static int jp2_colr_putdata(jp2_box_t *box, jas_stream_t *out)
+{
+ jp2_colr_t *colr = &box->data.colr;
+ if (jp2_putuint8(out, colr->method) || jp2_putuint8(out, colr->pri) ||
+ jp2_putuint8(out, colr->approx)) {
+ return -1;
+ }
+ switch (colr->method) {
+ case JP2_COLR_ENUM:
+ if (jp2_putuint32(out, colr->csid)) {
+ return -1;
+ }
+ break;
+ case JP2_COLR_ICC:
+ if (jas_stream_write(out, colr->iccp,
+ JAS_CAST(int, colr->iccplen)) != JAS_CAST(int, colr->iccplen))
+ return -1;
+ break;
+ }
+ return 0;
+}
+
+static int jp2_cdef_putdata(jp2_box_t *box, jas_stream_t *out)
+{
+ jp2_cdef_t *cdef = &box->data.cdef;
+ unsigned int i;
+ jp2_cdefchan_t *ent;
+
+ if (jp2_putuint16(out, cdef->numchans)) {
+ return -1;
+ }
+
+ for (i = 0; i < cdef->numchans; ++i) {
+ ent = &cdef->ents[i];
+ if (jp2_putuint16(out, ent->channo) ||
+ jp2_putuint16(out, ent->type) ||
+ jp2_putuint16(out, ent->assoc)) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Input operations for primitive types.
+\******************************************************************************/
+
+static int jp2_getuint8(jas_stream_t *in, uint_fast8_t *val)
+{
+ int c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ if (val) {
+ *val = c;
+ }
+ return 0;
+}
+
+static int jp2_getuint16(jas_stream_t *in, uint_fast16_t *val)
+{
+ uint_fast16_t v;
+ int c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = (v << 8) | c;
+ if (val) {
+ *val = v;
+ }
+ return 0;
+}
+
+static int jp2_getuint32(jas_stream_t *in, uint_fast32_t *val)
+{
+ uint_fast32_t v;
+ int c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = (v << 8) | c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = (v << 8) | c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = (v << 8) | c;
+ if (val) {
+ *val = v;
+ }
+ return 0;
+}
+
+static int jp2_getuint64(jas_stream_t *in, uint_fast64_t *val)
+{
+ uint_fast64_t tmpval;
+ int i;
+ int c;
+
+ tmpval = 0;
+ for (i = 0; i < 8; ++i) {
+ tmpval <<= 8;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ tmpval |= (c & 0xff);
+ }
+ *val = tmpval;
+
+ return 0;
+}
+
+/******************************************************************************\
+* Output operations for primitive types.
+\******************************************************************************/
+
+static int jp2_putuint8(jas_stream_t *out, uint_fast8_t val)
+{
+ if (jas_stream_putc(out, val & 0xff) == EOF) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jp2_putuint16(jas_stream_t *out, uint_fast16_t val)
+{
+ if (jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
+ jas_stream_putc(out, val & 0xff) == EOF) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jp2_putuint32(jas_stream_t *out, uint_fast32_t val)
+{
+ if (jas_stream_putc(out, (val >> 24) & 0xff) == EOF ||
+ jas_stream_putc(out, (val >> 16) & 0xff) == EOF ||
+ jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
+ jas_stream_putc(out, val & 0xff) == EOF) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jp2_putuint64(jas_stream_t *out, uint_fast64_t val)
+{
+ if (jp2_putuint32(out, (val >> 32) & 0xffffffffUL) ||
+ jp2_putuint32(out, val & 0xffffffffUL)) {
+ return -1;
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Miscellaneous code.
+\******************************************************************************/
+
+jp2_boxinfo_t *jp2_boxinfolookup(int type)
+{
+ jp2_boxinfo_t *boxinfo;
+ for (boxinfo = jp2_boxinfos; boxinfo->name; ++boxinfo) {
+ if (boxinfo->type == type) {
+ return boxinfo;
+ }
+ }
+ return &jp2_boxinfo_unk;
+}
+
+
+
+
+
+static void jp2_cmap_destroy(jp2_box_t *box)
+{
+ jp2_cmap_t *cmap = &box->data.cmap;
+ if (cmap->ents) {
+ jas_free(cmap->ents);
+ }
+}
+
+static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+ jp2_cmap_t *cmap = &box->data.cmap;
+ jp2_cmapent_t *ent;
+ unsigned int i;
+
+ cmap->numchans = (box->datalen) / 4;
+ if (!(cmap->ents = jas_malloc(cmap->numchans * sizeof(jp2_cmapent_t)))) {
+ return -1;
+ }
+ for (i = 0; i < cmap->numchans; ++i) {
+ ent = &cmap->ents[i];
+ if (jp2_getuint16(in, &ent->cmptno) ||
+ jp2_getuint8(in, &ent->map) ||
+ jp2_getuint8(in, &ent->pcol)) {
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int jp2_cmap_putdata(jp2_box_t *box, jas_stream_t *out)
+{
+ /* Eliminate compiler warning about unused variables. */
+ box = 0;
+ out = 0;
+
+ return -1;
+}
+
+static void jp2_cmap_dumpdata(jp2_box_t *box, FILE *out)
+{
+ jp2_cmap_t *cmap = &box->data.cmap;
+ unsigned int i;
+ jp2_cmapent_t *ent;
+ fprintf(out, "numchans = %d\n", (int) cmap->numchans);
+ for (i = 0; i < cmap->numchans; ++i) {
+ ent = &cmap->ents[i];
+ fprintf(out, "cmptno=%d; map=%d; pcol=%d\n",
+ (int) ent->cmptno, (int) ent->map, (int) ent->pcol);
+ }
+}
+
+static void jp2_pclr_destroy(jp2_box_t *box)
+{
+ jp2_pclr_t *pclr = &box->data.pclr;
+ if (pclr->lutdata) {
+ jas_free(pclr->lutdata);
+ }
+ if (pclr->bpc)
+ jas_free(pclr->bpc);
+}
+
+static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in)
+{
+ jp2_pclr_t *pclr = &box->data.pclr;
+ int lutsize;
+ unsigned int i;
+ unsigned int j;
+ int_fast32_t x;
+
+ pclr->lutdata = 0;
+
+ if (jp2_getuint16(in, &pclr->numlutents) ||
+ jp2_getuint8(in, &pclr->numchans)) {
+ return -1;
+ }
+ lutsize = pclr->numlutents * pclr->numchans;
+ if (!(pclr->lutdata = jas_malloc(lutsize * sizeof(int_fast32_t)))) {
+ return -1;
+ }
+ if (!(pclr->bpc = jas_malloc(pclr->numchans * sizeof(uint_fast8_t)))) {
+ return -1;
+ }
+ for (i = 0; i < pclr->numchans; ++i) {
+ if (jp2_getuint8(in, &pclr->bpc[i])) {
+ return -1;
+ }
+ }
+ for (i = 0; i < pclr->numlutents; ++i) {
+ for (j = 0; j < pclr->numchans; ++j) {
+ if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0,
+ (pclr->bpc[j] & 0x7f) + 1, &x)) {
+ return -1;
+ }
+ pclr->lutdata[i * pclr->numchans + j] = x;
+ }
+ }
+ return 0;
+}
+
+static int jp2_pclr_putdata(jp2_box_t *box, jas_stream_t *out)
+{
+#if 0
+ jp2_pclr_t *pclr = &box->data.pclr;
+#endif
+/* Eliminate warning about unused variable. */
+box = 0;
+out = 0;
+ return -1;
+}
+
+static void jp2_pclr_dumpdata(jp2_box_t *box, FILE *out)
+{
+ jp2_pclr_t *pclr = &box->data.pclr;
+ unsigned int i;
+ int j;
+ fprintf(out, "numents=%d; numchans=%d\n", (int) pclr->numlutents,
+ (int) pclr->numchans);
+ for (i = 0; i < pclr->numlutents; ++i) {
+ for (j = 0; j < pclr->numchans; ++j) {
+ fprintf(out, "LUT[%d][%d]=%d\n", i, j, pclr->lutdata[i * pclr->numchans + j]);
+ }
+ }
+}
+
+static int jp2_getint(jas_stream_t *in, int s, int n, int_fast32_t *val)
+{
+ int c;
+ int i;
+ uint_fast32_t v;
+ int m;
+
+ m = (n + 7) / 8;
+
+ v = 0;
+ for (i = 0; i < m; ++i) {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = (v << 8) | c;
+ }
+ v &= ONES(n);
+ if (s) {
+ int sb;
+ sb = v & (1 << (8 * m - 1));
+ *val = ((~v) + 1) & ONES(8 * m);
+ if (sb) {
+ *val = -*val;
+ }
+ } else {
+ *val = v;
+ }
+
+ return 0;
+}
+
+jp2_cdefchan_t *jp2_cdef_lookup(jp2_cdef_t *cdef, int channo)
+{
+ unsigned int i;
+ jp2_cdefchan_t *cdefent;
+ for (i = 0; i < cdef->numchans; ++i) {
+ cdefent = &cdef->ents[i];
+ if (cdefent->channo == JAS_CAST(unsigned int, channo)) {
+ return cdefent;
+ }
+ }
+ return 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_cod.h b/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_cod.h
new file mode 100644
index 0000000..70e1ffb
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_cod.h
@@ -0,0 +1,304 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JP2 Library
+ *
+ * $Id$
+ */
+
+#ifndef JP2_COD_H
+#define JP2_COD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+
+/******************************************************************************\
+* Macros.
+\******************************************************************************/
+
+#define JP2_SPTOBPC(s, p) \
+ ((((p) - 1) & 0x7f) | (((s) & 1) << 7))
+
+/******************************************************************************\
+* Box class.
+\******************************************************************************/
+
+#define JP2_BOX_HDRLEN(ext) ((ext) ? 16 : 8)
+
+/* Box types. */
+#define JP2_BOX_JP 0x6a502020 /* Signature */
+#define JP2_BOX_FTYP 0x66747970 /* File Type */
+#define JP2_BOX_JP2H 0x6a703268 /* JP2 Header */
+#define JP2_BOX_IHDR 0x69686472 /* Image Header */
+#define JP2_BOX_BPCC 0x62706363 /* Bits Per Component */
+#define JP2_BOX_COLR 0x636f6c72 /* Color Specification */
+#define JP2_BOX_PCLR 0x70636c72 /* Palette */
+#define JP2_BOX_CMAP 0x636d6170 /* Component Mapping */
+#define JP2_BOX_CDEF 0x63646566 /* Channel Definition */
+#define JP2_BOX_RES 0x72657320 /* Resolution */
+#define JP2_BOX_RESC 0x72657363 /* Capture Resolution */
+#define JP2_BOX_RESD 0x72657364 /* Default Display Resolution */
+#define JP2_BOX_JP2C 0x6a703263 /* Contiguous Code Stream */
+#define JP2_BOX_JP2I 0x6a703269 /* Intellectual Property */
+#define JP2_BOX_XML 0x786d6c20 /* XML */
+#define JP2_BOX_UUID 0x75756964 /* UUID */
+#define JP2_BOX_UINF 0x75696e66 /* UUID Info */
+#define JP2_BOX_ULST 0x75637374 /* UUID List */
+#define JP2_BOX_URL 0x75726c20 /* URL */
+
+#define JP2_BOX_SUPER 0x01
+#define JP2_BOX_NODATA 0x02
+
+/* JP box data. */
+
+#define JP2_JP_MAGIC 0x0d0a870a
+#define JP2_JP_LEN 12
+
+typedef struct {
+ uint_fast32_t magic;
+} jp2_jp_t;
+
+/* FTYP box data. */
+
+#define JP2_FTYP_MAXCOMPATCODES 32
+#define JP2_FTYP_MAJVER 0x6a703220
+#define JP2_FTYP_MINVER 0
+#define JP2_FTYP_COMPATCODE JP2_FTYP_MAJVER
+
+typedef struct {
+ uint_fast32_t majver;
+ uint_fast32_t minver;
+ uint_fast32_t numcompatcodes;
+ uint_fast32_t compatcodes[JP2_FTYP_MAXCOMPATCODES];
+} jp2_ftyp_t;
+
+/* IHDR box data. */
+
+#define JP2_IHDR_COMPTYPE 7
+#define JP2_IHDR_BPCNULL 255
+
+typedef struct {
+ uint_fast32_t width;
+ uint_fast32_t height;
+ uint_fast16_t numcmpts;
+ uint_fast8_t bpc;
+ uint_fast8_t comptype;
+ uint_fast8_t csunk;
+ uint_fast8_t ipr;
+} jp2_ihdr_t;
+
+/* BPCC box data. */
+
+typedef struct {
+ uint_fast16_t numcmpts;
+ uint_fast8_t *bpcs;
+} jp2_bpcc_t;
+
+/* COLR box data. */
+
+#define JP2_COLR_ENUM 1
+#define JP2_COLR_ICC 2
+#define JP2_COLR_PRI 0
+
+#define JP2_COLR_SRGB 16
+#define JP2_COLR_SGRAY 17
+#define JP2_COLR_SYCC 18
+
+typedef struct {
+ uint_fast8_t method;
+ uint_fast8_t pri;
+ uint_fast8_t approx;
+ uint_fast32_t csid;
+ uint_fast8_t *iccp;
+ 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;
+} jp2_pclr_t;
+
+/* CDEF box per-channel data. */
+
+#define JP2_CDEF_RGB_R 1
+#define JP2_CDEF_RGB_G 2
+#define JP2_CDEF_RGB_B 3
+
+#define JP2_CDEF_YCBCR_Y 1
+#define JP2_CDEF_YCBCR_CB 2
+#define JP2_CDEF_YCBCR_CR 3
+
+#define JP2_CDEF_GRAY_Y 1
+
+#define JP2_CDEF_TYPE_COLOR 0
+#define JP2_CDEF_TYPE_OPACITY 1
+#define JP2_CDEF_TYPE_UNSPEC 65535
+#define JP2_CDEF_ASOC_ALL 0
+#define JP2_CDEF_ASOC_NONE 65535
+
+typedef struct {
+ uint_fast16_t channo;
+ uint_fast16_t type;
+ uint_fast16_t assoc;
+} jp2_cdefchan_t;
+
+/* CDEF box data. */
+
+typedef struct {
+ uint_fast16_t numchans;
+ jp2_cdefchan_t *ents;
+} jp2_cdef_t;
+
+typedef struct {
+ uint_fast16_t cmptno;
+ uint_fast8_t map;
+ uint_fast8_t pcol;
+} jp2_cmapent_t;
+
+typedef struct {
+ uint_fast16_t numchans;
+ jp2_cmapent_t *ents;
+} jp2_cmap_t;
+
+#define JP2_CMAP_DIRECT 0
+#define JP2_CMAP_PALETTE 1
+
+/* Generic box. */
+
+struct jp2_boxops_s;
+typedef struct {
+
+ struct jp2_boxops_s *ops;
+ struct jp2_boxinfo_s *info;
+
+ uint_fast32_t type;
+
+ /* The length of the box including the (variable-length) header. */
+ uint_fast32_t len;
+
+ /* The length of the box data. */
+ uint_fast32_t datalen;
+
+ union {
+ jp2_jp_t jp;
+ jp2_ftyp_t ftyp;
+ jp2_ihdr_t ihdr;
+ jp2_bpcc_t bpcc;
+ jp2_colr_t colr;
+ jp2_pclr_t pclr;
+ jp2_cdef_t cdef;
+ jp2_cmap_t cmap;
+ } data;
+
+} jp2_box_t;
+
+typedef struct jp2_boxops_s {
+ void (*init)(jp2_box_t *box);
+ void (*destroy)(jp2_box_t *box);
+ int (*getdata)(jp2_box_t *box, jas_stream_t *in);
+ int (*putdata)(jp2_box_t *box, jas_stream_t *out);
+ void (*dumpdata)(jp2_box_t *box, FILE *out);
+} jp2_boxops_t;
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+typedef struct jp2_boxinfo_s {
+ int type;
+ char *name;
+ int flags;
+ jp2_boxops_t ops;
+} jp2_boxinfo_t;
+
+/******************************************************************************\
+* Box class.
+\******************************************************************************/
+
+jp2_box_t *jp2_box_create(int type);
+void jp2_box_destroy(jp2_box_t *box);
+jp2_box_t *jp2_box_get(jas_stream_t *in);
+int jp2_box_put(jp2_box_t *box, jas_stream_t *out);
+
+#define JP2_DTYPETOBPC(dtype) \
+ ((JAS_IMAGE_CDT_GETSGND(dtype) << 7) | (JAS_IMAGE_CDT_GETPREC(dtype) - 1))
+#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
+
+jp2_cdefchan_t *jp2_cdef_lookup(jp2_cdef_t *cdef, int channo);
+
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_dec.c b/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_dec.c
new file mode 100644
index 0000000..65772de
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_dec.c
@@ -0,0 +1,603 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JP2 Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_image.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_version.h"
+
+#include "jp2_cod.h"
+#include "jp2_dec.h"
+
+#define JP2_VALIDATELEN (JAS_MIN(JP2_JP_LEN + 16, JAS_STREAM_MAXPUTBACK))
+
+static jp2_dec_t *jp2_dec_create(void);
+static void jp2_dec_destroy(jp2_dec_t *dec);
+static int jp2_getcs(jp2_colr_t *colr);
+static int fromiccpcs(int cs);
+static int jp2_getct(int colorspace, int type, int assoc);
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+jas_image_t *jp2_decode(jas_stream_t *in, char *optstr)
+{
+ jp2_box_t *box;
+ int found;
+ jas_image_t *image;
+ jp2_dec_t *dec;
+ bool samedtype;
+ int dtype;
+ unsigned int i;
+ jp2_cmap_t *cmapd;
+ jp2_pclr_t *pclrd;
+ jp2_cdef_t *cdefd;
+ unsigned int channo;
+ int newcmptno;
+ int_fast32_t *lutents;
+#if 0
+ jp2_cdefchan_t *cdefent;
+ int cmptno;
+#endif
+ jp2_cmapent_t *cmapent;
+ jas_icchdr_t icchdr;
+ jas_iccprof_t *iccprof;
+
+ dec = 0;
+ box = 0;
+ image = 0;
+
+ if (!(dec = jp2_dec_create())) {
+ goto error;
+ }
+
+ /* Get the first box. This should be a JP box. */
+ if (!(box = jp2_box_get(in))) {
+ jas_eprintf("error: cannot get box\n");
+ goto error;
+ }
+ if (box->type != JP2_BOX_JP) {
+ jas_eprintf("error: expecting signature box\n");
+ goto error;
+ }
+ if (box->data.jp.magic != JP2_JP_MAGIC) {
+ jas_eprintf("incorrect magic number\n");
+ goto error;
+ }
+ jp2_box_destroy(box);
+ box = 0;
+
+ /* Get the second box. This should be a FTYP box. */
+ if (!(box = jp2_box_get(in))) {
+ goto error;
+ }
+ if (box->type != JP2_BOX_FTYP) {
+ jas_eprintf("expecting file type box\n");
+ goto error;
+ }
+ jp2_box_destroy(box);
+ box = 0;
+
+ /* Get more boxes... */
+ found = 0;
+ while ((box = jp2_box_get(in))) {
+ if (jas_getdbglevel() >= 1) {
+ jas_eprintf("box type %s\n", box->info->name);
+ }
+ switch (box->type) {
+ case JP2_BOX_JP2C:
+ found = 1;
+ break;
+ case JP2_BOX_IHDR:
+ if (!dec->ihdr) {
+ dec->ihdr = box;
+ box = 0;
+ }
+ break;
+ case JP2_BOX_BPCC:
+ if (!dec->bpcc) {
+ dec->bpcc = box;
+ box = 0;
+ }
+ break;
+ case JP2_BOX_CDEF:
+ if (!dec->cdef) {
+ dec->cdef = box;
+ box = 0;
+ }
+ break;
+ case JP2_BOX_PCLR:
+ if (!dec->pclr) {
+ dec->pclr = box;
+ box = 0;
+ }
+ break;
+ case JP2_BOX_CMAP:
+ if (!dec->cmap) {
+ dec->cmap = box;
+ box = 0;
+ }
+ break;
+ case JP2_BOX_COLR:
+ if (!dec->colr) {
+ dec->colr = box;
+ box = 0;
+ }
+ break;
+ }
+ if (box) {
+ jp2_box_destroy(box);
+ box = 0;
+ }
+ if (found) {
+ break;
+ }
+ }
+
+ if (!found) {
+ jas_eprintf("error: no code stream found\n");
+ goto error;
+ }
+
+ if (!(dec->image = jpc_decode(in, optstr))) {
+ jas_eprintf("error: cannot decode code stream\n");
+ goto error;
+ }
+
+ /* An IHDR box must be present. */
+ if (!dec->ihdr) {
+ jas_eprintf("error: missing IHDR box\n");
+ goto error;
+ }
+
+ /* Does the number of components indicated in the IHDR box match
+ the value specified in the code stream? */
+ if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(uint, jas_image_numcmpts(dec->image))) {
+ jas_eprintf("warning: number of components mismatch\n");
+ }
+
+ /* At least one component must be present. */
+ if (!jas_image_numcmpts(dec->image)) {
+ jas_eprintf("error: no components\n");
+ goto error;
+ }
+
+ /* Determine if all components have the same data type. */
+ samedtype = true;
+ dtype = jas_image_cmptdtype(dec->image, 0);
+ for (i = 1; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
+ if (jas_image_cmptdtype(dec->image, i) != dtype) {
+ samedtype = false;
+ break;
+ }
+ }
+
+ /* Is the component data type indicated in the IHDR box consistent
+ with the data in the code stream? */
+ if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) ||
+ (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) {
+ jas_eprintf("warning: component data type mismatch\n");
+ }
+
+ /* Is the compression type supported? */
+ if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {
+ jas_eprintf("error: unsupported compression type\n");
+ goto error;
+ }
+
+ if (dec->bpcc) {
+ /* Is the number of components indicated in the BPCC box
+ consistent with the code stream data? */
+ if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(uint, jas_image_numcmpts(
+ dec->image))) {
+ jas_eprintf("warning: number of components mismatch\n");
+ }
+ /* Is the component data type information indicated in the BPCC
+ box consistent with the code stream data? */
+ if (!samedtype) {
+ for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
+ if (jas_image_cmptdtype(dec->image, i) != JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {
+ jas_eprintf("warning: component data type mismatch\n");
+ }
+ }
+ } else {
+ jas_eprintf("warning: superfluous BPCC box\n");
+ }
+ }
+
+ /* A COLR box must be present. */
+ if (!dec->colr) {
+ jas_eprintf("error: no COLR box\n");
+ goto error;
+ }
+
+ switch (dec->colr->data.colr.method) {
+ case JP2_COLR_ENUM:
+ jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr));
+ break;
+ case JP2_COLR_ICC:
+ iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp,
+ dec->colr->data.colr.iccplen);
+ assert(iccprof);
+ jas_iccprof_gethdr(iccprof, &icchdr);
+ jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc);
+ jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));
+ dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);
+ assert(dec->image->cmprof_);
+ jas_iccprof_destroy(iccprof);
+ break;
+ }
+
+ /* If a CMAP box is present, a PCLR box must also be present. */
+ if (dec->cmap && !dec->pclr) {
+ jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n");
+ jp2_box_destroy(dec->cmap);
+ dec->cmap = 0;
+ }
+
+ /* If a CMAP box is not present, a PCLR box must not be present. */
+ if (!dec->cmap && dec->pclr) {
+ jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n");
+ jp2_box_destroy(dec->pclr);
+ dec->pclr = 0;
+ }
+
+ /* Determine the number of channels (which is essentially the number
+ of components after any palette mappings have been applied). */
+ dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : JAS_CAST(uint, jas_image_numcmpts(dec->image));
+
+ /* Perform a basic sanity check on the CMAP box if present. */
+ if (dec->cmap) {
+ for (i = 0; i < dec->numchans; ++i) {
+ /* Is the component number reasonable? */
+ if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(uint, jas_image_numcmpts(dec->image))) {
+ jas_eprintf("error: invalid component number in CMAP box\n");
+ goto error;
+ }
+ /* Is the LUT index reasonable? */
+ if (dec->cmap->data.cmap.ents[i].pcol >= dec->pclr->data.pclr.numchans) {
+ jas_eprintf("error: invalid CMAP LUT index\n");
+ goto error;
+ }
+ }
+ }
+
+ /* Allocate space for the channel-number to component-number LUT. */
+ if (!(dec->chantocmptlut = jas_malloc(dec->numchans * sizeof(uint_fast16_t)))) {
+ jas_eprintf("error: no memory\n");
+ goto error;
+ }
+
+ if (!dec->cmap) {
+ for (i = 0; i < dec->numchans; ++i) {
+ dec->chantocmptlut[i] = i;
+ }
+ } else {
+ cmapd = &dec->cmap->data.cmap;
+ pclrd = &dec->pclr->data.pclr;
+ cdefd = &dec->cdef->data.cdef;
+ for (channo = 0; channo < cmapd->numchans; ++channo) {
+ cmapent = &cmapd->ents[channo];
+ if (cmapent->map == JP2_CMAP_DIRECT) {
+ dec->chantocmptlut[channo] = channo;
+ } else if (cmapent->map == JP2_CMAP_PALETTE) {
+ lutents = jas_malloc(pclrd->numlutents * sizeof(int_fast32_t));
+ for (i = 0; i < pclrd->numlutents; ++i) {
+ lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];
+ }
+ newcmptno = jas_image_numcmpts(dec->image);
+ jas_image_depalettize(dec->image, cmapent->cmptno, pclrd->numlutents, lutents, JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);
+ dec->chantocmptlut[channo] = newcmptno;
+ jas_free(lutents);
+#if 0
+ if (dec->cdef) {
+ cdefent = jp2_cdef_lookup(cdefd, channo);
+ if (!cdefent) {
+ abort();
+ }
+ jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc));
+ } else {
+ jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1));
+ }
+#endif
+ }
+ }
+ }
+
+ /* Mark all components as being of unknown type. */
+
+ for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
+ jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN);
+ }
+
+ /* Determine the type of each component. */
+ if (dec->cdef) {
+ for (i = 0; i < dec->numchans; ++i) {
+ jas_image_setcmpttype(dec->image,
+ dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo],
+ jp2_getct(jas_image_clrspc(dec->image),
+ dec->cdef->data.cdef.ents[i].type, dec->cdef->data.cdef.ents[i].assoc));
+ }
+ } else {
+ for (i = 0; i < dec->numchans; ++i) {
+ jas_image_setcmpttype(dec->image, dec->chantocmptlut[i],
+ jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));
+ }
+ }
+
+ /* Delete any components that are not of interest. */
+ for (i = jas_image_numcmpts(dec->image); i > 0; --i) {
+ if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) {
+ jas_image_delcmpt(dec->image, i - 1);
+ }
+ }
+
+ /* Ensure that some components survived. */
+ if (!jas_image_numcmpts(dec->image)) {
+ jas_eprintf("error: no components\n");
+ goto error;
+ }
+#if 0
+jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image));
+#endif
+
+ /* Prevent the image from being destroyed later. */
+ image = dec->image;
+ dec->image = 0;
+
+ jp2_dec_destroy(dec);
+
+ return image;
+
+error:
+ if (box) {
+ jp2_box_destroy(box);
+ }
+ if (dec) {
+ jp2_dec_destroy(dec);
+ }
+ return 0;
+}
+
+int jp2_validate(jas_stream_t *in)
+{
+ char buf[JP2_VALIDATELEN];
+ int i;
+ int n;
+#if 0
+ jas_stream_t *tmpstream;
+ jp2_box_t *box;
+#endif
+
+ assert(JAS_STREAM_MAXPUTBACK >= JP2_VALIDATELEN);
+
+ /* Read the validation data (i.e., the data used for detecting
+ the format). */
+ if ((n = jas_stream_read(in, buf, JP2_VALIDATELEN)) < 0) {
+ return -1;
+ }
+
+ /* Put the validation data back onto the stream, so that the
+ stream position will not be changed. */
+ for (i = n - 1; i >= 0; --i) {
+ if (jas_stream_ungetc(in, buf[i]) == EOF) {
+ return -1;
+ }
+ }
+
+ /* Did we read enough data? */
+ if (n < JP2_VALIDATELEN) {
+ return -1;
+ }
+
+ /* Is the box type correct? */
+ if (((buf[4] << 24) | (buf[5] << 16) | (buf[6] << 8) | buf[7]) !=
+ JP2_BOX_JP)
+ {
+ return -1;
+ }
+
+ return 0;
+}
+
+static jp2_dec_t *jp2_dec_create(void)
+{
+ jp2_dec_t *dec;
+
+ if (!(dec = jas_malloc(sizeof(jp2_dec_t)))) {
+ return 0;
+ }
+ dec->ihdr = 0;
+ dec->bpcc = 0;
+ dec->cdef = 0;
+ dec->pclr = 0;
+ dec->image = 0;
+ dec->chantocmptlut = 0;
+ dec->cmap = 0;
+ dec->colr = 0;
+ return dec;
+}
+
+static void jp2_dec_destroy(jp2_dec_t *dec)
+{
+ if (dec->ihdr) {
+ jp2_box_destroy(dec->ihdr);
+ }
+ if (dec->bpcc) {
+ jp2_box_destroy(dec->bpcc);
+ }
+ if (dec->cdef) {
+ jp2_box_destroy(dec->cdef);
+ }
+ if (dec->pclr) {
+ jp2_box_destroy(dec->pclr);
+ }
+ if (dec->image) {
+ jas_image_destroy(dec->image);
+ }
+ if (dec->cmap) {
+ jp2_box_destroy(dec->cmap);
+ }
+ if (dec->colr) {
+ jp2_box_destroy(dec->colr);
+ }
+ if (dec->chantocmptlut) {
+ jas_free(dec->chantocmptlut);
+ }
+ jas_free(dec);
+}
+
+static int jp2_getct(int colorspace, int type, int assoc)
+{
+ if (type == 1 && assoc == 0) {
+ return JAS_IMAGE_CT_OPACITY;
+ }
+ if (type == 0 && assoc >= 1 && assoc <= 65534) {
+ switch (colorspace) {
+ case JAS_CLRSPC_FAM_RGB:
+ switch (assoc) {
+ case JP2_CDEF_RGB_R:
+ return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R);
+ break;
+ case JP2_CDEF_RGB_G:
+ return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G);
+ break;
+ case JP2_CDEF_RGB_B:
+ return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B);
+ break;
+ }
+ break;
+ case JAS_CLRSPC_FAM_YCBCR:
+ switch (assoc) {
+ case JP2_CDEF_YCBCR_Y:
+ return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y);
+ break;
+ case JP2_CDEF_YCBCR_CB:
+ return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB);
+ break;
+ case JP2_CDEF_YCBCR_CR:
+ return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR);
+ break;
+ }
+ break;
+ case JAS_CLRSPC_FAM_GRAY:
+ switch (assoc) {
+ case JP2_CDEF_GRAY_Y:
+ return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y);
+ break;
+ }
+ break;
+ default:
+ return JAS_IMAGE_CT_COLOR(assoc - 1);
+ break;
+ }
+ }
+ return JAS_IMAGE_CT_UNKNOWN;
+}
+
+static int jp2_getcs(jp2_colr_t *colr)
+{
+ if (colr->method == JP2_COLR_ENUM) {
+ switch (colr->csid) {
+ case JP2_COLR_SRGB:
+ return JAS_CLRSPC_SRGB;
+ break;
+ case JP2_COLR_SYCC:
+ return JAS_CLRSPC_SYCBCR;
+ break;
+ case JP2_COLR_SGRAY:
+ return JAS_CLRSPC_SGRAY;
+ break;
+ }
+ }
+ return JAS_CLRSPC_UNKNOWN;
+}
+
+static int fromiccpcs(int cs)
+{
+ switch (cs) {
+ case ICC_CS_RGB:
+ return JAS_CLRSPC_GENRGB;
+ break;
+ case ICC_CS_YCBCR:
+ return JAS_CLRSPC_GENYCBCR;
+ break;
+ case ICC_CS_GRAY:
+ return JAS_CLRSPC_GENGRAY;
+ break;
+ }
+ return JAS_CLRSPC_UNKNOWN;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_dec.h b/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_dec.h
new file mode 100644
index 0000000..1cb95a2
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_dec.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef JP2_DEC_H
+#define JP2_DEC_H
+
+#include "jasper/jas_image.h"
+#include "jasper/jas_stream.h"
+#include "jp2_cod.h"
+
+typedef struct {
+
+ jp2_box_t *pclr;
+ jp2_box_t *cdef;
+ jp2_box_t *ihdr;
+ jp2_box_t *bpcc;
+ jp2_box_t *cmap;
+ jp2_box_t *colr;
+ jas_image_t *image;
+ uint_fast16_t numchans;
+ uint_fast16_t *chantocmptlut;
+
+} jp2_dec_t;
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_enc.c b/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_enc.c
new file mode 100644
index 0000000..9e1e1fc
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jp2/jp2_enc.c
@@ -0,0 +1,436 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JP2 Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_cm.h"
+#include "jasper/jas_icc.h"
+#include "jp2_cod.h"
+
+static uint_fast32_t jp2_gettypeasoc(int colorspace, int ctype);
+static int clrspctojp2(jas_clrspc_t clrspc);
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+int jp2_encode(jas_image_t *image, jas_stream_t *out, 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;
+jas_iccprof_t *iccprof;
+jas_stream_t *iccstream;
+int pos;
+int needcdef;
+int prec;
+int sgnd;
+
+ box = 0;
+ tmpstream = 0;
+
+ allcmptssame = 1;
+ sgnd = jas_image_cmptsgnd(image, 0);
+ prec = jas_image_cmptprec(image, 0);
+ for (i = 1; i < jas_image_numcmpts(image); ++i) {
+ if (jas_image_cmptsgnd(image, i) != sgnd ||
+ jas_image_cmptprec(image, i) != prec) {
+ allcmptssame = 0;
+ break;
+ }
+ }
+
+ /* Output the signature box. */
+
+ if (!(box = jp2_box_create(JP2_BOX_JP))) {
+ 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);
+ 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;
+ switch (jas_image_clrspc(image)) {
+ case JAS_CLRSPC_SRGB:
+ case JAS_CLRSPC_SYCBCR:
+ case JAS_CLRSPC_SGRAY:
+ colr->method = JP2_COLR_ENUM;
+ colr->csid = clrspctojp2(jas_image_clrspc(image));
+ colr->pri = JP2_COLR_PRI;
+ colr->approx = 0;
+ break;
+ default:
+ colr->method = JP2_COLR_ICC;
+ colr->pri = JP2_COLR_PRI;
+ colr->approx = 0;
+ iccprof = jas_iccprof_createfromcmprof(jas_image_cmprof(image));
+ assert(iccprof);
+ iccstream = jas_stream_memopen(0, 0);
+ assert(iccstream);
+ if (jas_iccprof_save(iccprof, iccstream))
+ abort();
+ if ((pos = jas_stream_tell(iccstream)) < 0)
+ abort();
+ colr->iccplen = pos;
+ colr->iccp = jas_malloc(pos);
+ assert(colr->iccp);
+ jas_stream_rewind(iccstream);
+ if (jas_stream_read(iccstream, colr->iccp, colr->iccplen) != colr->iccplen)
+ abort();
+ jas_stream_close(iccstream);
+ jas_iccprof_destroy(iccprof);
+ break;
+ }
+ if (jp2_box_put(box, tmpstream)) {
+ goto error;
+ }
+ jp2_box_destroy(box);
+ box = 0;
+
+ needcdef = 1;
+ switch (jas_clrspc_fam(jas_image_clrspc(image))) {
+ case JAS_CLRSPC_FAM_RGB:
+ if (jas_image_cmpttype(image, 0) ==
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R) &&
+ jas_image_cmpttype(image, 1) ==
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G) &&
+ jas_image_cmpttype(image, 2) ==
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))
+ needcdef = 0;
+ break;
+ case JAS_CLRSPC_FAM_YCBCR:
+ if (jas_image_cmpttype(image, 0) ==
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y) &&
+ jas_image_cmpttype(image, 1) ==
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB) &&
+ jas_image_cmpttype(image, 2) ==
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR))
+ needcdef = 0;
+ break;
+ case JAS_CLRSPC_FAM_GRAY:
+ if (jas_image_cmpttype(image, 0) ==
+ JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y))
+ needcdef = 0;
+ break;
+ default:
+ abort();
+ break;
+ }
+
+ if (needcdef) {
+ 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_clrspc(image), jas_image_cmpttype(image, i));
+ cdefchanent->type = typeasoc >> 16;
+ cdefchanent->assoc = typeasoc & 0x7fff;
+ }
+ if (jp2_box_put(box, tmpstream)) {
+ goto error;
+ }
+ 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(false);
+ 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;
+}
+
+static uint_fast32_t jp2_gettypeasoc(int colorspace, int ctype)
+{
+ int type;
+ int asoc;
+
+ if (ctype & JAS_IMAGE_CT_OPACITY) {
+ type = JP2_CDEF_TYPE_OPACITY;
+ asoc = JP2_CDEF_ASOC_ALL;
+ goto done;
+ }
+
+ type = JP2_CDEF_TYPE_UNSPEC;
+ asoc = JP2_CDEF_ASOC_NONE;
+ switch (jas_clrspc_fam(colorspace)) {
+ case JAS_CLRSPC_FAM_RGB:
+ switch (JAS_IMAGE_CT_COLOR(ctype)) {
+ case JAS_IMAGE_CT_RGB_R:
+ type = JP2_CDEF_TYPE_COLOR;
+ asoc = JP2_CDEF_RGB_R;
+ break;
+ case JAS_IMAGE_CT_RGB_G:
+ type = JP2_CDEF_TYPE_COLOR;
+ asoc = JP2_CDEF_RGB_G;
+ break;
+ case JAS_IMAGE_CT_RGB_B:
+ type = JP2_CDEF_TYPE_COLOR;
+ asoc = JP2_CDEF_RGB_B;
+ break;
+ }
+ break;
+ case JAS_CLRSPC_FAM_YCBCR:
+ switch (JAS_IMAGE_CT_COLOR(ctype)) {
+ case JAS_IMAGE_CT_YCBCR_Y:
+ type = JP2_CDEF_TYPE_COLOR;
+ asoc = JP2_CDEF_YCBCR_Y;
+ break;
+ case JAS_IMAGE_CT_YCBCR_CB:
+ type = JP2_CDEF_TYPE_COLOR;
+ asoc = JP2_CDEF_YCBCR_CB;
+ break;
+ case JAS_IMAGE_CT_YCBCR_CR:
+ type = JP2_CDEF_TYPE_COLOR;
+ asoc = JP2_CDEF_YCBCR_CR;
+ break;
+ }
+ break;
+ case JAS_CLRSPC_FAM_GRAY:
+ type = JP2_CDEF_TYPE_COLOR;
+ asoc = JP2_CDEF_GRAY_Y;
+ break;
+ }
+
+done:
+ return (type << 16) | asoc;
+}
+
+static int clrspctojp2(jas_clrspc_t clrspc)
+{
+ switch (clrspc) {
+ case JAS_CLRSPC_SRGB:
+ return JP2_COLR_SRGB;
+ case JAS_CLRSPC_SYCBCR:
+ return JP2_COLR_SYCC;
+ case JAS_CLRSPC_SGRAY:
+ return JP2_COLR_SGRAY;
+ default:
+ abort();
+ break;
+ }
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/Makefile.am b/jasper-1.900.1-6ct/src/libjasper/jpc/Makefile.am
new file mode 100644
index 0000000..41a9bbf
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/Makefile.am
@@ -0,0 +1,105 @@
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+# AM_CFLAGS = -funroll-loops
+
+noinst_LTLIBRARIES = libjpc.la
+libjpc_la_SOURCES = \
+ jpc_bs.h \
+ jpc_cod.h \
+ jpc_cs.h \
+ jpc_dec.h \
+ jpc_enc.h \
+ jpc_fix.h \
+ jpc_flt.h \
+ jpc_math.h \
+ jpc_mct.h \
+ jpc_mqcod.h \
+ jpc_mqdec.h \
+ jpc_mqenc.h \
+ jpc_qmfb.h \
+ jpc_tagtree.h \
+ jpc_t1cod.h \
+ jpc_t1dec.h \
+ jpc_t1enc.h \
+ jpc_tsfb.h \
+ jpc_t2cod.h \
+ jpc_t2dec.h \
+ jpc_t2enc.h \
+ jpc_util.h \
+ jpc_bs.c \
+ jpc_cs.c \
+ jpc_dec.c \
+ jpc_enc.c \
+ jpc_math.c \
+ jpc_mct.c \
+ jpc_mqcod.c \
+ jpc_mqdec.c \
+ jpc_mqenc.c \
+ jpc_qmfb.c \
+ jpc_tagtree.c \
+ jpc_t1cod.c \
+ jpc_t1dec.c \
+ jpc_t1enc.c \
+ jpc_tsfb.c \
+ jpc_t2cod.c \
+ jpc_t2dec.c \
+ jpc_t2enc.c \
+ jpc_util.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/Makefile.in b/jasper-1.900.1-6ct/src/libjasper/jpc/Makefile.in
new file mode 100644
index 0000000..b628494
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/Makefile.in
@@ -0,0 +1,568 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+# AM_CFLAGS = -funroll-loops
+
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src/libjasper/jpc
+DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+LTLIBRARIES = $(noinst_LTLIBRARIES)
+libjpc_la_LIBADD =
+am_libjpc_la_OBJECTS = jpc_bs.lo jpc_cs.lo jpc_dec.lo jpc_enc.lo \
+ jpc_math.lo jpc_mct.lo jpc_mqcod.lo jpc_mqdec.lo jpc_mqenc.lo \
+ jpc_qmfb.lo jpc_tagtree.lo jpc_t1cod.lo jpc_t1dec.lo \
+ jpc_t1enc.lo jpc_tsfb.lo jpc_t2cod.lo jpc_t2dec.lo \
+ jpc_t2enc.lo jpc_util.lo
+libjpc_la_OBJECTS = $(am_libjpc_la_OBJECTS)
+DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/src/libjasper/include/jasper
+depcomp = $(SHELL) $(top_srcdir)/acaux/depcomp
+am__depfiles_maybe = depfiles
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LTCOMPILE = $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) \
+ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+ $(AM_CFLAGS) $(CFLAGS)
+CCLD = $(CC)
+LINK = $(LIBTOOL) --tag=CC --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+ $(AM_LDFLAGS) $(LDFLAGS) -o $@
+SOURCES = $(libjpc_la_SOURCES)
+DIST_SOURCES = $(libjpc_la_SOURCES)
+ETAGS = etags
+CTAGS = ctags
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+noinst_LTLIBRARIES = libjpc.la
+libjpc_la_SOURCES = \
+ jpc_bs.h \
+ jpc_cod.h \
+ jpc_cs.h \
+ jpc_dec.h \
+ jpc_enc.h \
+ jpc_fix.h \
+ jpc_flt.h \
+ jpc_math.h \
+ jpc_mct.h \
+ jpc_mqcod.h \
+ jpc_mqdec.h \
+ jpc_mqenc.h \
+ jpc_qmfb.h \
+ jpc_tagtree.h \
+ jpc_t1cod.h \
+ jpc_t1dec.h \
+ jpc_t1enc.h \
+ jpc_tsfb.h \
+ jpc_t2cod.h \
+ jpc_t2dec.h \
+ jpc_t2enc.h \
+ jpc_util.h \
+ jpc_bs.c \
+ jpc_cs.c \
+ jpc_dec.c \
+ jpc_enc.c \
+ jpc_math.c \
+ jpc_mct.c \
+ jpc_mqcod.c \
+ jpc_mqdec.c \
+ jpc_mqenc.c \
+ jpc_qmfb.c \
+ jpc_tagtree.c \
+ jpc_t1cod.c \
+ jpc_t1dec.c \
+ jpc_t1enc.c \
+ jpc_tsfb.c \
+ jpc_t2cod.c \
+ jpc_t2dec.c \
+ jpc_t2enc.c \
+ jpc_util.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
+all: all-am
+
+.SUFFIXES:
+.SUFFIXES: .c .lo .o .obj
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libjasper/jpc/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/libjasper/jpc/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+clean-noinstLTLIBRARIES:
+ -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
+ @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \
+ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
+ test "$$dir" != "$$p" || dir=.; \
+ echo "rm -f \"$${dir}/so_locations\""; \
+ rm -f "$${dir}/so_locations"; \
+ done
+libjpc.la: $(libjpc_la_OBJECTS) $(libjpc_la_DEPENDENCIES)
+ $(LINK) $(libjpc_la_LDFLAGS) $(libjpc_la_OBJECTS) $(libjpc_la_LIBADD) $(LIBS)
+
+mostlyclean-compile:
+ -rm -f *.$(OBJEXT)
+
+distclean-compile:
+ -rm -f *.tab.c
+
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_bs.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_cs.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_dec.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_enc.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_math.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_mct.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_mqcod.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_mqdec.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_mqenc.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_qmfb.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_t1cod.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_t1dec.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_t1enc.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_t2cod.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_t2dec.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_t2enc.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_tagtree.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_tsfb.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpc_util.Plo at am__quote@
+
+.c.o:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c $<
+
+.c.obj:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
+
+.c.lo:
+ at am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $<
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-am
+all-am: Makefile $(LTLIBRARIES)
+installdirs:
+install: install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-am
+
+clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \
+ mostlyclean-am
+
+distclean: distclean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+distclean-am: clean-am distclean-compile distclean-generic \
+ distclean-libtool distclean-tags
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+info: info-am
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-am
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-compile mostlyclean-generic \
+ mostlyclean-libtool
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
+ clean-libtool clean-noinstLTLIBRARIES ctags distclean \
+ distclean-compile distclean-generic distclean-libtool \
+ distclean-tags distdir dvi dvi-am html html-am info info-am \
+ install install-am install-data install-data-am install-exec \
+ install-exec-am install-info install-info-am install-man \
+ install-strip installcheck installcheck-am installdirs \
+ maintainer-clean maintainer-clean-generic mostlyclean \
+ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
+ pdf pdf-am ps ps-am tags uninstall uninstall-am \
+ uninstall-info-am
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_bs.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_bs.c
new file mode 100644
index 0000000..c3dd466
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_bs.c
@@ -0,0 +1,440 @@
+/*
+ * Copyright (c) 1999-2000, Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Bit Stream Class
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+
+#include "jpc_bs.h"
+
+/******************************************************************************\
+* Local function prototypes.
+\******************************************************************************/
+
+static jpc_bitstream_t *jpc_bitstream_alloc(void);
+
+/******************************************************************************\
+* Code for opening and closing bit streams.
+\******************************************************************************/
+
+/* Open a bit stream from a stream. */
+jpc_bitstream_t *jpc_bitstream_sopen(jas_stream_t *stream, char *mode)
+{
+ jpc_bitstream_t *bitstream;
+
+ /* Ensure that the open mode is valid. */
+#if 1
+/* This causes a string literal too long error (with c99 pedantic mode). */
+ assert(!strcmp(mode, "r") || !strcmp(mode, "w") || !strcmp(mode, "r+")
+ || !strcmp(mode, "w+"));
+#endif
+
+ if (!(bitstream = jpc_bitstream_alloc())) {
+ return 0;
+ }
+
+ /* By default, do not close the underlying (character) stream, upon
+ the close of the bit stream. */
+ bitstream->flags_ = JPC_BITSTREAM_NOCLOSE;
+
+ bitstream->stream_ = stream;
+ bitstream->openmode_ = (mode[0] == 'w') ? JPC_BITSTREAM_WRITE :
+ JPC_BITSTREAM_READ;
+
+ /* Mark the data buffer as empty. */
+ bitstream->cnt_ = (bitstream->openmode_ == JPC_BITSTREAM_READ) ? 0 : 8;
+ bitstream->buf_ = 0;
+
+ return bitstream;
+}
+
+/* Close a bit stream. */
+int jpc_bitstream_close(jpc_bitstream_t *bitstream)
+{
+ int ret = 0;
+
+ /* Align to the next byte boundary while considering the effects of
+ bit stuffing. */
+ if (jpc_bitstream_align(bitstream)) {
+ ret = -1;
+ }
+
+ /* If necessary, close the underlying (character) stream. */
+ if (!(bitstream->flags_ & JPC_BITSTREAM_NOCLOSE) && bitstream->stream_) {
+ if (jas_stream_close(bitstream->stream_)) {
+ ret = -1;
+ }
+ bitstream->stream_ = 0;
+ }
+
+ jas_free(bitstream);
+ return ret;
+}
+
+/* Allocate a new bit stream. */
+static jpc_bitstream_t *jpc_bitstream_alloc()
+{
+ jpc_bitstream_t *bitstream;
+
+ /* Allocate memory for the new bit stream object. */
+ if (!(bitstream = jas_malloc(sizeof(jpc_bitstream_t)))) {
+ return 0;
+ }
+ /* Initialize all of the data members. */
+ bitstream->stream_ = 0;
+ bitstream->cnt_ = 0;
+ bitstream->flags_ = 0;
+ bitstream->openmode_ = 0;
+
+ return bitstream;
+}
+
+/******************************************************************************\
+* Code for reading/writing from/to bit streams.
+\******************************************************************************/
+
+/* Get a bit from a bit stream. */
+int jpc_bitstream_getbit_func(jpc_bitstream_t *bitstream)
+{
+ int ret;
+ JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func(%p)\n", bitstream));
+ ret = jpc_bitstream_getbit_macro(bitstream);
+ JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func -> %d\n", ret));
+ return ret;
+}
+
+/* Put a bit to a bit stream. */
+int jpc_bitstream_putbit_func(jpc_bitstream_t *bitstream, int b)
+{
+ int ret;
+ JAS_DBGLOG(1000, ("jpc_bitstream_putbit_func(%p, %d)\n", bitstream, b));
+ ret = jpc_bitstream_putbit_macro(bitstream, b);
+ JAS_DBGLOG(1000, ("jpc_bitstream_putbit_func() -> %d\n", ret));
+ return ret;
+}
+
+/* Get one or more bits from a bit stream. */
+long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n)
+{
+ long v;
+ int u;
+
+ /* We can reliably get at most 31 bits since ISO/IEC 9899 only
+ guarantees that a long can represent values up to 2^31-1. */
+ assert(n >= 0 && n < 32);
+
+ /* 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;
+}
+
+/******************************************************************************\
+* Code for buffer filling and flushing.
+\******************************************************************************/
+
+/* Fill the buffer for a bit stream. */
+int jpc_bitstream_fillbuf(jpc_bitstream_t *bitstream)
+{
+ int c;
+ /* Note: The count has already been decremented by the caller. */
+ assert(bitstream->openmode_ & JPC_BITSTREAM_READ);
+ assert(bitstream->cnt_ <= 0);
+
+ if (bitstream->flags_ & JPC_BITSTREAM_ERR) {
+ bitstream->cnt_ = 0;
+ return -1;
+ }
+
+ if (bitstream->flags_ & JPC_BITSTREAM_EOF) {
+ bitstream->buf_ = 0x7f;
+ bitstream->cnt_ = 7;
+ return 1;
+ }
+
+ bitstream->buf_ = (bitstream->buf_ << 8) & 0xffff;
+ if ((c = jas_stream_getc((bitstream)->stream_)) == EOF) {
+ bitstream->flags_ |= JPC_BITSTREAM_EOF;
+ return 1;
+ }
+ bitstream->cnt_ = (bitstream->buf_ == 0xff00) ? 6 : 7;
+ bitstream->buf_ |= c & ((1 << (bitstream->cnt_ + 1)) - 1);
+ return (bitstream->buf_ >> bitstream->cnt_) & 1;
+}
+
+
+/******************************************************************************\
+* Code related to flushing.
+\******************************************************************************/
+
+/* Does the bit stream need to be aligned to a byte boundary (considering
+ the effects of bit stuffing)? */
+int jpc_bitstream_needalign(jpc_bitstream_t *bitstream)
+{
+ if (bitstream->openmode_ & JPC_BITSTREAM_READ) {
+ /* The bit stream is open for reading. */
+ /* If there are any bits buffered for reading, or the
+ previous byte forced a stuffed bit, alignment is
+ required. */
+ if ((bitstream->cnt_ < 8 && bitstream->cnt_ > 0) ||
+ ((bitstream->buf_ >> 8) & 0xff) == 0xff) {
+ return 1;
+ }
+ } else if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
+ /* The bit stream is open for writing. */
+ /* If there are any bits buffered for writing, or the
+ previous byte forced a stuffed bit, alignment is
+ required. */
+ if ((bitstream->cnt_ < 8 && bitstream->cnt_ >= 0) ||
+ ((bitstream->buf_ >> 8) & 0xff) == 0xff) {
+ return 1;
+ }
+ } else {
+ /* This should not happen. Famous last words, eh? :-) */
+ assert(0);
+ return -1;
+ }
+ return 0;
+}
+
+/* How many additional bytes would be output if we align the bit stream? */
+int jpc_bitstream_pending(jpc_bitstream_t *bitstream)
+{
+ if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
+ /* The bit stream is being used for writing. */
+#if 1
+ /* XXX - Is this really correct? Check someday... */
+ if (bitstream->cnt_ < 8) {
+ return 1;
+ }
+#else
+ if (bitstream->cnt_ < 8) {
+ if (((bitstream->buf_ >> 8) & 0xff) == 0xff) {
+ return 2;
+ }
+ return 1;
+ }
+#endif
+ return 0;
+ } else {
+ /* This operation should not be invoked on a bit stream that
+ is being used for reading. */
+ return -1;
+ }
+}
+
+/* Align the bit stream to a byte boundary. */
+int jpc_bitstream_align(jpc_bitstream_t *bitstream)
+{
+ int ret;
+ if (bitstream->openmode_ & JPC_BITSTREAM_READ) {
+ ret = jpc_bitstream_inalign(bitstream, 0, 0);
+ } else if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
+ ret = jpc_bitstream_outalign(bitstream, 0);
+ } else {
+ abort();
+ }
+ return ret;
+}
+
+/* Align a bit stream in the input case. */
+int jpc_bitstream_inalign(jpc_bitstream_t *bitstream, int fillmask,
+ int filldata)
+{
+ int n;
+ int v;
+ int u;
+ int numfill;
+ int m;
+
+ numfill = 7;
+ m = 0;
+ v = 0;
+ if (bitstream->cnt_ > 0) {
+ n = bitstream->cnt_;
+ } else if (!bitstream->cnt_) {
+ n = ((bitstream->buf_ & 0xff) == 0xff) ? 7 : 0;
+ } else {
+ n = 0;
+ }
+ if (n > 0) {
+ if ((u = jpc_bitstream_getbits(bitstream, n)) < 0) {
+ return -1;
+ }
+ m += n;
+ v = (v << n) | u;
+ }
+ if ((bitstream->buf_ & 0xff) == 0xff) {
+ if ((u = jpc_bitstream_getbits(bitstream, 7)) < 0) {
+ return -1;
+ }
+ v = (v << 7) | u;
+ m += 7;
+ }
+ if (m > numfill) {
+ v >>= m - numfill;
+ } else {
+ filldata >>= numfill - m;
+ fillmask >>= numfill - m;
+ }
+ if (((~(v ^ filldata)) & fillmask) != fillmask) {
+ /* The actual fill pattern does not match the expected one. */
+ return 1;
+ }
+
+ return 0;
+}
+
+/* Align a bit stream in the output case. */
+int jpc_bitstream_outalign(jpc_bitstream_t *bitstream, int filldata)
+{
+ int n;
+ int v;
+
+ /* Ensure that this bit stream is open for writing. */
+ assert(bitstream->openmode_ & JPC_BITSTREAM_WRITE);
+
+ /* Ensure that the first bit of fill data is zero. */
+ /* Note: The first bit of fill data must be zero. If this were not
+ the case, the fill data itself could cause further bit stuffing to
+ be required (which would cause numerous complications). */
+ assert(!(filldata & (~0x3f)));
+
+ if (!bitstream->cnt_) {
+ if ((bitstream->buf_ & 0xff) == 0xff) {
+ n = 7;
+ v = filldata;
+ } else {
+ n = 0;
+ v = 0;
+ }
+ } else if (bitstream->cnt_ > 0 && bitstream->cnt_ < 8) {
+ n = bitstream->cnt_;
+ v = filldata >> (7 - n);
+ } else {
+ 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/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_bs.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_bs.h
new file mode 100644
index 0000000..3cebafa
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_bs.h
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Bit Stream Class
+ *
+ * $Id$
+ */
+
+#ifndef JPC_BS_H
+#define JPC_BS_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_stream.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/*
+ * Bit stream open mode flags.
+ */
+
+/* Bit stream open for reading. */
+#define JPC_BITSTREAM_READ 0x01
+/* Bit stream open for writing. */
+#define JPC_BITSTREAM_WRITE 0x02
+
+/*
+ * Bit stream flags.
+ */
+
+/* Do not close underlying character stream. */
+#define JPC_BITSTREAM_NOCLOSE 0x01
+/* End of file has been reached while reading. */
+#define JPC_BITSTREAM_EOF 0x02
+/* An I/O error has occured. */
+#define JPC_BITSTREAM_ERR 0x04
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* Bit stream class. */
+
+typedef struct {
+
+ /* Some miscellaneous flags. */
+ int flags_;
+
+ /* The input/output buffer. */
+ uint_fast16_t buf_;
+
+ /* The number of bits remaining in the byte being read/written. */
+ int cnt_;
+
+ /* The underlying stream associated with this bit stream. */
+ jas_stream_t *stream_;
+
+ /* The mode in which this bit stream was opened. */
+ int openmode_;
+
+} jpc_bitstream_t;
+
+/******************************************************************************\
+* Functions/macros for opening and closing bit streams..
+\******************************************************************************/
+
+/* Open a stream as a bit stream. */
+jpc_bitstream_t *jpc_bitstream_sopen(jas_stream_t *stream, char *mode);
+
+/* Close a bit stream. */
+int jpc_bitstream_close(jpc_bitstream_t *bitstream);
+
+/******************************************************************************\
+* Functions/macros for reading from and writing to bit streams..
+\******************************************************************************/
+
+/* Read a bit from a bit stream. */
+#if defined(DEBUG)
+#define jpc_bitstream_getbit(bitstream) \
+ jpc_bitstream_getbit_func(bitstream)
+#else
+#define jpc_bitstream_getbit(bitstream) \
+ jpc_bitstream_getbit_macro(bitstream)
+#endif
+
+/* Write a bit to a bit stream. */
+#if defined(DEBUG)
+#define jpc_bitstream_putbit(bitstream, v) \
+ jpc_bitstream_putbit_func(bitstream, v)
+#else
+#define jpc_bitstream_putbit(bitstream, v) \
+ jpc_bitstream_putbit_macro(bitstream, v)
+#endif
+
+/* Read one or more bits from a bit stream. */
+long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n);
+
+/* Write one or more bits to a bit stream. */
+int jpc_bitstream_putbits(jpc_bitstream_t *bitstream, int n, long v);
+
+/******************************************************************************\
+* Functions/macros for flushing and aligning bit streams.
+\******************************************************************************/
+
+/* Align the current position within the bit stream to the next byte
+ boundary. */
+int jpc_bitstream_align(jpc_bitstream_t *bitstream);
+
+/* Align the current position in the bit stream with the next byte boundary,
+ ensuring that certain bits consumed in the process match a particular
+ pattern. */
+int jpc_bitstream_inalign(jpc_bitstream_t *bitstream, int fillmask,
+ int filldata);
+
+/* Align the current position in the bit stream with the next byte boundary,
+ writing bits from the specified pattern (if necessary) in the process. */
+int jpc_bitstream_outalign(jpc_bitstream_t *bitstream, int filldata);
+
+/* Check if a bit stream needs alignment. */
+int jpc_bitstream_needalign(jpc_bitstream_t *bitstream);
+
+/* How many additional bytes would be output if the bit stream was aligned? */
+int jpc_bitstream_pending(jpc_bitstream_t *bitstream);
+
+/******************************************************************************\
+* Functions/macros for querying state information for bit streams.
+\******************************************************************************/
+
+/* Has EOF been encountered on a bit stream? */
+#define jpc_bitstream_eof(bitstream) \
+ ((bitstream)->flags_ & JPC_BITSTREAM_EOF)
+
+/******************************************************************************\
+* Internals.
+\******************************************************************************/
+
+/* DO NOT DIRECTLY INVOKE ANY OF THE MACROS OR FUNCTIONS BELOW. THEY ARE
+ FOR INTERNAL USE ONLY. */
+
+int jpc_bitstream_getbit_func(jpc_bitstream_t *bitstream);
+
+int jpc_bitstream_putbit_func(jpc_bitstream_t *bitstream, int v);
+
+int jpc_bitstream_fillbuf(jpc_bitstream_t *bitstream);
+
+#define jpc_bitstream_getbit_macro(bitstream) \
+ (assert((bitstream)->openmode_ & JPC_BITSTREAM_READ), \
+ (--(bitstream)->cnt_ >= 0) ? \
+ ((int)(((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))
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_cod.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_cod.h
new file mode 100644
index 0000000..32e1124
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_cod.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef JPC_COD_H
+#define JPC_COD_H
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* The nominal word size used by this implementation. */
+#define JPC_PREC 32
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_cs.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_cs.c
new file mode 100644
index 0000000..f076571
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_cs.c
@@ -0,0 +1,1644 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JPEG-2000 Code Stream Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdlib.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.h"
+
+#include "jpc_cs.h"
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* Marker segment table entry. */
+typedef struct {
+ int id;
+ char *name;
+ jpc_msops_t ops;
+} jpc_mstabent_t;
+
+/******************************************************************************\
+* Local prototypes.
+\******************************************************************************/
+
+static jpc_mstabent_t *jpc_mstab_lookup(int id);
+
+static int jpc_poc_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_poc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_poc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static void jpc_poc_destroyparms(jpc_ms_t *ms);
+
+static int jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_sot_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_cod_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_coc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_qcd_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_qcc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_rgn_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_sop_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_ppt_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+static int jpc_com_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+
+static int jpc_sot_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_siz_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_cod_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_coc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_qcd_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_qcc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_rgn_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_unk_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_sop_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_ppt_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_crg_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+static int jpc_com_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+
+static int jpc_sot_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_siz_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_cod_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_coc_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_qcc_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_rgn_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_unk_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_sop_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_ppm_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_ppt_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_crg_dumpparms(jpc_ms_t *ms, FILE *out);
+static int jpc_com_dumpparms(jpc_ms_t *ms, FILE *out);
+
+static void jpc_siz_destroyparms(jpc_ms_t *ms);
+static void jpc_qcd_destroyparms(jpc_ms_t *ms);
+static void jpc_qcc_destroyparms(jpc_ms_t *ms);
+static void jpc_cod_destroyparms(jpc_ms_t *ms);
+static void jpc_coc_destroyparms(jpc_ms_t *ms);
+static void jpc_unk_destroyparms(jpc_ms_t *ms);
+static void jpc_ppm_destroyparms(jpc_ms_t *ms);
+static void jpc_ppt_destroyparms(jpc_ms_t *ms);
+static void jpc_crg_destroyparms(jpc_ms_t *ms);
+static void jpc_com_destroyparms(jpc_ms_t *ms);
+
+static void jpc_qcx_destroycompparms(jpc_qcxcp_t *compparms);
+static int jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
+ jas_stream_t *in, uint_fast16_t len);
+static int jpc_qcx_putcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
+ jas_stream_t *out);
+static void jpc_cox_destroycompparms(jpc_coxcp_t *compparms);
+static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
+ jas_stream_t *in, int prtflag, jpc_coxcp_t *compparms);
+static int jpc_cox_putcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
+ jas_stream_t *out, int prtflag, jpc_coxcp_t *compparms);
+
+/******************************************************************************\
+* Global data.
+\******************************************************************************/
+
+static jpc_mstabent_t jpc_mstab[] = {
+ {JPC_MS_SOC, "SOC", {0, 0, 0, 0}},
+ {JPC_MS_SOT, "SOT", {0, jpc_sot_getparms, jpc_sot_putparms,
+ jpc_sot_dumpparms}},
+ {JPC_MS_SOD, "SOD", {0, 0, 0, 0}},
+ {JPC_MS_EOC, "EOC", {0, 0, 0, 0}},
+ {JPC_MS_SIZ, "SIZ", {jpc_siz_destroyparms, jpc_siz_getparms,
+ jpc_siz_putparms, jpc_siz_dumpparms}},
+ {JPC_MS_COD, "COD", {jpc_cod_destroyparms, jpc_cod_getparms,
+ jpc_cod_putparms, jpc_cod_dumpparms}},
+ {JPC_MS_COC, "COC", {jpc_coc_destroyparms, jpc_coc_getparms,
+ jpc_coc_putparms, jpc_coc_dumpparms}},
+ {JPC_MS_RGN, "RGN", {0, jpc_rgn_getparms, jpc_rgn_putparms,
+ jpc_rgn_dumpparms}},
+ {JPC_MS_QCD, "QCD", {jpc_qcd_destroyparms, jpc_qcd_getparms,
+ jpc_qcd_putparms, jpc_qcd_dumpparms}},
+ {JPC_MS_QCC, "QCC", {jpc_qcc_destroyparms, jpc_qcc_getparms,
+ jpc_qcc_putparms, jpc_qcc_dumpparms}},
+ {JPC_MS_POC, "POC", {jpc_poc_destroyparms, jpc_poc_getparms,
+ jpc_poc_putparms, jpc_poc_dumpparms}},
+ {JPC_MS_TLM, "TLM", {0, jpc_unk_getparms, jpc_unk_putparms, 0}},
+ {JPC_MS_PLM, "PLM", {0, jpc_unk_getparms, jpc_unk_putparms, 0}},
+ {JPC_MS_PPM, "PPM", {jpc_ppm_destroyparms, jpc_ppm_getparms,
+ jpc_ppm_putparms, jpc_ppm_dumpparms}},
+ {JPC_MS_PPT, "PPT", {jpc_ppt_destroyparms, jpc_ppt_getparms,
+ jpc_ppt_putparms, jpc_ppt_dumpparms}},
+ {JPC_MS_SOP, "SOP", {0, jpc_sop_getparms, jpc_sop_putparms,
+ jpc_sop_dumpparms}},
+ {JPC_MS_EPH, "EPH", {0, 0, 0, 0}},
+ {JPC_MS_CRG, "CRG", {0, jpc_crg_getparms, jpc_crg_putparms,
+ jpc_crg_dumpparms}},
+ {JPC_MS_COM, "COM", {jpc_com_destroyparms, jpc_com_getparms,
+ jpc_com_putparms, jpc_com_dumpparms}},
+ {-1, "UNKNOWN", {jpc_unk_destroyparms, jpc_unk_getparms,
+ jpc_unk_putparms, jpc_unk_dumpparms}}
+};
+
+/******************************************************************************\
+* Code stream manipulation functions.
+\******************************************************************************/
+
+/* Create a code stream state object. */
+jpc_cstate_t *jpc_cstate_create()
+{
+ jpc_cstate_t *cstate;
+ if (!(cstate = jas_malloc(sizeof(jpc_cstate_t)))) {
+ return 0;
+ }
+ cstate->numcomps = 0;
+ return cstate;
+}
+
+/* Destroy a code stream state object. */
+void jpc_cstate_destroy(jpc_cstate_t *cstate)
+{
+ jas_free(cstate);
+}
+
+/* Read a marker segment from a stream. */
+jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate)
+{
+ jpc_ms_t *ms;
+ jpc_mstabent_t *mstabent;
+ jas_stream_t *tmpstream;
+
+ if (!(ms = jpc_ms_create(0))) {
+ return 0;
+ }
+
+ /* Get the marker type. */
+ if (jpc_getuint16(in, &ms->id) || ms->id < JPC_MS_MIN ||
+ ms->id > JPC_MS_MAX) {
+ jpc_ms_destroy(ms);
+ return 0;
+ }
+
+ mstabent = jpc_mstab_lookup(ms->id);
+ ms->ops = &mstabent->ops;
+
+ /* Get the marker segment length and parameters if present. */
+ /* Note: It is tacitly assumed that a marker segment cannot have
+ parameters unless it has a length field. That is, there cannot
+ be a parameters field without a length field and vice versa. */
+ if (JPC_MS_HASPARMS(ms->id)) {
+ /* Get the length of the marker segment. */
+ if (jpc_getuint16(in, &ms->len) || ms->len < 3) {
+ jpc_ms_destroy(ms);
+ return 0;
+ }
+ /* Calculate the length of the marker segment parameters. */
+ ms->len -= 2;
+ /* Create and prepare a temporary memory stream from which to
+ read the marker segment parameters. */
+ /* Note: This approach provides a simple way of ensuring that
+ we never read beyond the end of the marker segment (even if
+ the marker segment length is errantly set too small). */
+ if (!(tmpstream = jas_stream_memopen(0, 0))) {
+ jpc_ms_destroy(ms);
+ return 0;
+ }
+ if (jas_stream_copy(tmpstream, in, ms->len) ||
+ jas_stream_seek(tmpstream, 0, SEEK_SET) < 0) {
+ jas_stream_close(tmpstream);
+ jpc_ms_destroy(ms);
+ return 0;
+ }
+ /* Get the marker segment parameters. */
+ if ((*ms->ops->getparms)(ms, cstate, tmpstream)) {
+ ms->ops = 0;
+ jpc_ms_destroy(ms);
+ jas_stream_close(tmpstream);
+ return 0;
+ }
+
+ if (jas_getdbglevel() > 0) {
+ jpc_ms_dump(ms, stderr);
+ }
+
+ if (JAS_CAST(ulong, jas_stream_tell(tmpstream)) != ms->len) {
+ jas_eprintf("warning: trailing garbage in marker segment (%ld bytes)\n",
+ ms->len - jas_stream_tell(tmpstream));
+ }
+
+ /* Close the temporary stream. */
+ jas_stream_close(tmpstream);
+
+ } else {
+ /* There are no marker segment parameters. */
+ ms->len = 0;
+
+ if (jas_getdbglevel() > 0) {
+ jpc_ms_dump(ms, stderr);
+ }
+ }
+
+ /* Update the code stream state information based on the type of
+ marker segment read. */
+ /* Note: This is a bit of a hack, but I'm not going to define another
+ type of virtual function for this one special case. */
+ if (ms->id == JPC_MS_SIZ) {
+ cstate->numcomps = ms->parms.siz.numcomps;
+ }
+
+ return ms;
+}
+
+/* Write a marker segment to a stream. */
+int jpc_putms(jas_stream_t *out, jpc_cstate_t *cstate, jpc_ms_t *ms)
+{
+ jas_stream_t *tmpstream;
+ int len;
+
+ /* Output the marker segment type. */
+ if (jpc_putuint16(out, ms->id)) {
+ return -1;
+ }
+
+ /* Output the marker segment length and parameters if necessary. */
+ if (ms->ops->putparms) {
+ /* Create a temporary stream in which to buffer the
+ parameter data. */
+ if (!(tmpstream = jas_stream_memopen(0, 0))) {
+ return -1;
+ }
+ if ((*ms->ops->putparms)(ms, cstate, tmpstream)) {
+ jas_stream_close(tmpstream);
+ return -1;
+ }
+ /* Get the number of bytes of parameter data written. */
+ if ((len = jas_stream_tell(tmpstream)) < 0) {
+ jas_stream_close(tmpstream);
+ return -1;
+ }
+ ms->len = len;
+ /* Write the marker segment length and parameter data to
+ the output stream. */
+ if (jas_stream_seek(tmpstream, 0, SEEK_SET) < 0 ||
+ jpc_putuint16(out, ms->len + 2) ||
+ jas_stream_copy(out, tmpstream, ms->len) < 0) {
+ jas_stream_close(tmpstream);
+ return -1;
+ }
+ /* Close the temporary stream. */
+ jas_stream_close(tmpstream);
+ }
+
+ /* This is a bit of a hack, but I'm not going to define another
+ type of virtual function for this one special case. */
+ if (ms->id == JPC_MS_SIZ) {
+ cstate->numcomps = ms->parms.siz.numcomps;
+ }
+
+ if (jas_getdbglevel() > 0) {
+ jpc_ms_dump(ms, stderr);
+ }
+
+ return 0;
+}
+
+/******************************************************************************\
+* Marker segment operations.
+\******************************************************************************/
+
+/* Create a marker segment of the specified type. */
+jpc_ms_t *jpc_ms_create(int type)
+{
+ jpc_ms_t *ms;
+ jpc_mstabent_t *mstabent;
+
+ if (!(ms = jas_malloc(sizeof(jpc_ms_t)))) {
+ return 0;
+ }
+ ms->id = type;
+ ms->len = 0;
+ mstabent = jpc_mstab_lookup(ms->id);
+ ms->ops = &mstabent->ops;
+ memset(&ms->parms, 0, sizeof(jpc_msparms_t));
+ return ms;
+}
+
+/* Destroy a marker segment. */
+void jpc_ms_destroy(jpc_ms_t *ms)
+{
+ if (ms->ops && ms->ops->destroyparms) {
+ (*ms->ops->destroyparms)(ms);
+ }
+ jas_free(ms);
+}
+
+/* Dump a marker segment to a stream for debugging. */
+void jpc_ms_dump(jpc_ms_t *ms, FILE *out)
+{
+ jpc_mstabent_t *mstabent;
+ mstabent = jpc_mstab_lookup(ms->id);
+ fprintf(out, "type = 0x%04x (%s);", ms->id, mstabent->name);
+ if (JPC_MS_HASPARMS(ms->id)) {
+ fprintf(out, " len = %d;", ms->len + 2);
+ if (ms->ops->dumpparms) {
+ (*ms->ops->dumpparms)(ms, out);
+ } else {
+ fprintf(out, "\n");
+ }
+ } else {
+ fprintf(out, "\n");
+ }
+}
+
+/******************************************************************************\
+* SOT marker segment operations.
+\******************************************************************************/
+
+static int jpc_sot_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+ jpc_sot_t *sot = &ms->parms.sot;
+
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+
+ if (jpc_getuint16(in, &sot->tileno) ||
+ jpc_getuint32(in, &sot->len) ||
+ jpc_getuint8(in, &sot->partno) ||
+ jpc_getuint8(in, &sot->numparts)) {
+ return -1;
+ }
+ if (jas_stream_eof(in)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_sot_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ jpc_sot_t *sot = &ms->parms.sot;
+
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+
+ if (jpc_putuint16(out, sot->tileno) ||
+ jpc_putuint32(out, sot->len) ||
+ jpc_putuint8(out, sot->partno) ||
+ jpc_putuint8(out, sot->numparts)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_sot_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ jpc_sot_t *sot = &ms->parms.sot;
+ fprintf(out, "tileno = %d; len = %d; partno = %d; numparts = %d\n",
+ sot->tileno, sot->len, sot->partno, sot->numparts);
+ return 0;
+}
+
+/******************************************************************************\
+* SIZ marker segment operations.
+\******************************************************************************/
+
+static void jpc_siz_destroyparms(jpc_ms_t *ms)
+{
+ jpc_siz_t *siz = &ms->parms.siz;
+ if (siz->comps) {
+ jas_free(siz->comps);
+ }
+}
+
+static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
+ jas_stream_t *in)
+{
+ jpc_siz_t *siz = &ms->parms.siz;
+ unsigned int i;
+ uint_fast8_t tmp;
+
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+
+ if (jpc_getuint16(in, &siz->caps) ||
+ jpc_getuint32(in, &siz->width) ||
+ jpc_getuint32(in, &siz->height) ||
+ jpc_getuint32(in, &siz->xoff) ||
+ jpc_getuint32(in, &siz->yoff) ||
+ jpc_getuint32(in, &siz->tilewidth) ||
+ jpc_getuint32(in, &siz->tileheight) ||
+ jpc_getuint32(in, &siz->tilexoff) ||
+ jpc_getuint32(in, &siz->tileyoff) ||
+ jpc_getuint16(in, &siz->numcomps)) {
+ return -1;
+ }
+ if (!siz->width || !siz->height || !siz->tilewidth ||
+ !siz->tileheight || !siz->numcomps) {
+ return -1;
+ }
+ if (!(siz->comps = jas_malloc(siz->numcomps * sizeof(jpc_sizcomp_t)))) {
+ return -1;
+ }
+ for (i = 0; i < siz->numcomps; ++i) {
+ if (jpc_getuint8(in, &tmp) ||
+ jpc_getuint8(in, &siz->comps[i].hsamp) ||
+ jpc_getuint8(in, &siz->comps[i].vsamp)) {
+ jas_free(siz->comps);
+ return -1;
+ }
+ siz->comps[i].sgnd = (tmp >> 7) & 1;
+ siz->comps[i].prec = (tmp & 0x7f) + 1;
+ }
+ if (jas_stream_eof(in)) {
+ jas_free(siz->comps);
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_siz_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ jpc_siz_t *siz = &ms->parms.siz;
+ unsigned int i;
+
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+
+ assert(siz->width && siz->height && siz->tilewidth &&
+ siz->tileheight && siz->numcomps);
+ if (jpc_putuint16(out, siz->caps) ||
+ jpc_putuint32(out, siz->width) ||
+ jpc_putuint32(out, siz->height) ||
+ jpc_putuint32(out, siz->xoff) ||
+ jpc_putuint32(out, siz->yoff) ||
+ jpc_putuint32(out, siz->tilewidth) ||
+ jpc_putuint32(out, siz->tileheight) ||
+ jpc_putuint32(out, siz->tilexoff) ||
+ jpc_putuint32(out, siz->tileyoff) ||
+ jpc_putuint16(out, siz->numcomps)) {
+ return -1;
+ }
+ for (i = 0; i < siz->numcomps; ++i) {
+ if (jpc_putuint8(out, ((siz->comps[i].sgnd & 1) << 7) |
+ ((siz->comps[i].prec - 1) & 0x7f)) ||
+ jpc_putuint8(out, siz->comps[i].hsamp) ||
+ jpc_putuint8(out, siz->comps[i].vsamp)) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static int jpc_siz_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ jpc_siz_t *siz = &ms->parms.siz;
+ unsigned int i;
+ fprintf(out, "caps = 0x%02x;\n", siz->caps);
+ fprintf(out, "width = %d; height = %d; xoff = %d; yoff = %d;\n",
+ siz->width, siz->height, siz->xoff, siz->yoff);
+ fprintf(out, "tilewidth = %d; tileheight = %d; tilexoff = %d; "
+ "tileyoff = %d;\n", siz->tilewidth, siz->tileheight, siz->tilexoff,
+ siz->tileyoff);
+ for (i = 0; i < siz->numcomps; ++i) {
+ fprintf(out, "prec[%d] = %d; sgnd[%d] = %d; hsamp[%d] = %d; "
+ "vsamp[%d] = %d\n", i, siz->comps[i].prec, i,
+ siz->comps[i].sgnd, i, siz->comps[i].hsamp, i,
+ siz->comps[i].vsamp);
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* COD marker segment operations.
+\******************************************************************************/
+
+static void jpc_cod_destroyparms(jpc_ms_t *ms)
+{
+ jpc_cod_t *cod = &ms->parms.cod;
+ jpc_cox_destroycompparms(&cod->compparms);
+}
+
+static int jpc_cod_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+ jpc_cod_t *cod = &ms->parms.cod;
+ if (jpc_getuint8(in, &cod->csty)) {
+ return -1;
+ }
+ if (jpc_getuint8(in, &cod->prg) ||
+ jpc_getuint16(in, &cod->numlyrs) ||
+ jpc_getuint8(in, &cod->mctrans)) {
+ return -1;
+ }
+ if (jpc_cox_getcompparms(ms, cstate, in,
+ (cod->csty & JPC_COX_PRT) != 0, &cod->compparms)) {
+ return -1;
+ }
+ if (jas_stream_eof(in)) {
+ jpc_cod_destroyparms(ms);
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_cod_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ jpc_cod_t *cod = &ms->parms.cod;
+ assert(cod->numlyrs > 0 && cod->compparms.numdlvls <= 32);
+ assert(cod->compparms.numdlvls == cod->compparms.numrlvls - 1);
+ if (jpc_putuint8(out, cod->compparms.csty) ||
+ jpc_putuint8(out, cod->prg) ||
+ jpc_putuint16(out, cod->numlyrs) ||
+ jpc_putuint8(out, cod->mctrans)) {
+ return -1;
+ }
+ if (jpc_cox_putcompparms(ms, cstate, out,
+ (cod->csty & JPC_COX_PRT) != 0, &cod->compparms)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_cod_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ jpc_cod_t *cod = &ms->parms.cod;
+ int i;
+ fprintf(out, "csty = 0x%02x;\n", cod->compparms.csty);
+ fprintf(out, "numdlvls = %d; qmfbid = %d; mctrans = %d\n",
+ cod->compparms.numdlvls, cod->compparms.qmfbid, cod->mctrans);
+ fprintf(out, "prg = %d; numlyrs = %d;\n",
+ cod->prg, cod->numlyrs);
+ fprintf(out, "cblkwidthval = %d; cblkheightval = %d; "
+ "cblksty = 0x%02x;\n", cod->compparms.cblkwidthval, cod->compparms.cblkheightval,
+ cod->compparms.cblksty);
+ if (cod->csty & JPC_COX_PRT) {
+ for (i = 0; i < cod->compparms.numrlvls; ++i) {
+ jas_eprintf("prcwidth[%d] = %d, prcheight[%d] = %d\n",
+ i, cod->compparms.rlvls[i].parwidthval,
+ i, cod->compparms.rlvls[i].parheightval);
+ }
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* COC marker segment operations.
+\******************************************************************************/
+
+static void jpc_coc_destroyparms(jpc_ms_t *ms)
+{
+ jpc_coc_t *coc = &ms->parms.coc;
+ jpc_cox_destroycompparms(&coc->compparms);
+}
+
+static int jpc_coc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+ jpc_coc_t *coc = &ms->parms.coc;
+ uint_fast8_t tmp;
+ if (cstate->numcomps <= 256) {
+ if (jpc_getuint8(in, &tmp)) {
+ return -1;
+ }
+ coc->compno = tmp;
+ } else {
+ if (jpc_getuint16(in, &coc->compno)) {
+ return -1;
+ }
+ }
+ if (jpc_getuint8(in, &coc->compparms.csty)) {
+ return -1;
+ }
+ if (jpc_cox_getcompparms(ms, cstate, in,
+ (coc->compparms.csty & JPC_COX_PRT) != 0, &coc->compparms)) {
+ return -1;
+ }
+ if (jas_stream_eof(in)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_coc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ jpc_coc_t *coc = &ms->parms.coc;
+ assert(coc->compparms.numdlvls <= 32);
+ if (cstate->numcomps <= 256) {
+ if (jpc_putuint8(out, coc->compno)) {
+ return -1;
+ }
+ } else {
+ if (jpc_putuint16(out, coc->compno)) {
+ return -1;
+ }
+ }
+ if (jpc_putuint8(out, coc->compparms.csty)) {
+ return -1;
+ }
+ if (jpc_cox_putcompparms(ms, cstate, out,
+ (coc->compparms.csty & JPC_COX_PRT) != 0, &coc->compparms)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_coc_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ jpc_coc_t *coc = &ms->parms.coc;
+ fprintf(out, "compno = %d; csty = 0x%02x; numdlvls = %d;\n",
+ coc->compno, coc->compparms.csty, coc->compparms.numdlvls);
+ fprintf(out, "cblkwidthval = %d; cblkheightval = %d; "
+ "cblksty = 0x%02x; qmfbid = %d;\n", coc->compparms.cblkwidthval,
+ coc->compparms.cblkheightval, coc->compparms.cblksty, coc->compparms.qmfbid);
+ return 0;
+}
+/******************************************************************************\
+* COD/COC marker segment operation helper functions.
+\******************************************************************************/
+
+static void jpc_cox_destroycompparms(jpc_coxcp_t *compparms)
+{
+ /* Eliminate compiler warning about unused variables. */
+ compparms = 0;
+}
+
+static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
+ jas_stream_t *in, int prtflag, jpc_coxcp_t *compparms)
+{
+ uint_fast8_t tmp;
+ int i;
+
+ /* Eliminate compiler warning about unused variables. */
+ ms = 0;
+ cstate = 0;
+
+ if (jpc_getuint8(in, &compparms->numdlvls) ||
+ jpc_getuint8(in, &compparms->cblkwidthval) ||
+ jpc_getuint8(in, &compparms->cblkheightval) ||
+ jpc_getuint8(in, &compparms->cblksty) ||
+ jpc_getuint8(in, &compparms->qmfbid)) {
+ return -1;
+ }
+ compparms->numrlvls = compparms->numdlvls + 1;
+ if (prtflag) {
+ for (i = 0; i < compparms->numrlvls; ++i) {
+ if (jpc_getuint8(in, &tmp)) {
+ jpc_cox_destroycompparms(compparms);
+ return -1;
+ }
+ compparms->rlvls[i].parwidthval = tmp & 0xf;
+ compparms->rlvls[i].parheightval = (tmp >> 4) & 0xf;
+ }
+/* Sigh. This bit should be in the same field in both COC and COD mrk segs. */
+compparms->csty |= JPC_COX_PRT;
+ } else {
+ }
+ if (jas_stream_eof(in)) {
+ jpc_cox_destroycompparms(compparms);
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_cox_putcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
+ jas_stream_t *out, int prtflag, jpc_coxcp_t *compparms)
+{
+ int i;
+ assert(compparms->numdlvls <= 32);
+
+ /* Eliminate compiler warning about unused variables. */
+ ms = 0;
+ cstate = 0;
+
+ if (jpc_putuint8(out, compparms->numdlvls) ||
+ jpc_putuint8(out, compparms->cblkwidthval) ||
+ jpc_putuint8(out, compparms->cblkheightval) ||
+ jpc_putuint8(out, compparms->cblksty) ||
+ jpc_putuint8(out, compparms->qmfbid)) {
+ return -1;
+ }
+ if (prtflag) {
+ for (i = 0; i < compparms->numrlvls; ++i) {
+ if (jpc_putuint8(out,
+ ((compparms->rlvls[i].parheightval & 0xf) << 4) |
+ (compparms->rlvls[i].parwidthval & 0xf))) {
+ return -1;
+ }
+ }
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* RGN marker segment operations.
+\******************************************************************************/
+
+static int jpc_rgn_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+ jpc_rgn_t *rgn = &ms->parms.rgn;
+ uint_fast8_t tmp;
+ if (cstate->numcomps <= 256) {
+ if (jpc_getuint8(in, &tmp)) {
+ return -1;
+ }
+ rgn->compno = tmp;
+ } else {
+ if (jpc_getuint16(in, &rgn->compno)) {
+ return -1;
+ }
+ }
+ if (jpc_getuint8(in, &rgn->roisty) ||
+ jpc_getuint8(in, &rgn->roishift)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_rgn_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ jpc_rgn_t *rgn = &ms->parms.rgn;
+ if (cstate->numcomps <= 256) {
+ if (jpc_putuint8(out, rgn->compno)) {
+ return -1;
+ }
+ } else {
+ if (jpc_putuint16(out, rgn->compno)) {
+ return -1;
+ }
+ }
+ if (jpc_putuint8(out, rgn->roisty) ||
+ jpc_putuint8(out, rgn->roishift)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_rgn_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ jpc_rgn_t *rgn = &ms->parms.rgn;
+ fprintf(out, "compno = %d; roisty = %d; roishift = %d\n",
+ rgn->compno, rgn->roisty, rgn->roishift);
+ return 0;
+}
+
+/******************************************************************************\
+* QCD marker segment operations.
+\******************************************************************************/
+
+static void jpc_qcd_destroyparms(jpc_ms_t *ms)
+{
+ jpc_qcd_t *qcd = &ms->parms.qcd;
+ jpc_qcx_destroycompparms(&qcd->compparms);
+}
+
+static int jpc_qcd_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+ jpc_qcxcp_t *compparms = &ms->parms.qcd.compparms;
+ return jpc_qcx_getcompparms(compparms, cstate, in, ms->len);
+}
+
+static int jpc_qcd_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ jpc_qcxcp_t *compparms = &ms->parms.qcd.compparms;
+ return jpc_qcx_putcompparms(compparms, cstate, out);
+}
+
+static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ jpc_qcd_t *qcd = &ms->parms.qcd;
+ int i;
+ fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n",
+ (int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes);
+ for (i = 0; i < qcd->compparms.numstepsizes; ++i) {
+ fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
+ i, (unsigned) JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i]),
+ i, (unsigned) JPC_QCX_GETMANT(qcd->compparms.stepsizes[i]));
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* QCC marker segment operations.
+\******************************************************************************/
+
+static void jpc_qcc_destroyparms(jpc_ms_t *ms)
+{
+ jpc_qcc_t *qcc = &ms->parms.qcc;
+ jpc_qcx_destroycompparms(&qcc->compparms);
+}
+
+static int jpc_qcc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+ jpc_qcc_t *qcc = &ms->parms.qcc;
+ uint_fast8_t tmp;
+ int len;
+ len = ms->len;
+ if (cstate->numcomps <= 256) {
+ jpc_getuint8(in, &tmp);
+ qcc->compno = tmp;
+ --len;
+ } else {
+ jpc_getuint16(in, &qcc->compno);
+ len -= 2;
+ }
+ if (jpc_qcx_getcompparms(&qcc->compparms, cstate, in, len)) {
+ return -1;
+ }
+ if (jas_stream_eof(in)) {
+ jpc_qcc_destroyparms(ms);
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_qcc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ jpc_qcc_t *qcc = &ms->parms.qcc;
+ if (cstate->numcomps <= 256) {
+ jpc_putuint8(out, qcc->compno);
+ } else {
+ jpc_putuint16(out, qcc->compno);
+ }
+ if (jpc_qcx_putcompparms(&qcc->compparms, cstate, out)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_qcc_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ jpc_qcc_t *qcc = &ms->parms.qcc;
+ int i;
+ fprintf(out, "compno = %d; qntsty = %d; numguard = %d; "
+ "numstepsizes = %d\n", qcc->compno, qcc->compparms.qntsty, qcc->compparms.numguard,
+ qcc->compparms.numstepsizes);
+ for (i = 0; i < qcc->compparms.numstepsizes; ++i) {
+ fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
+ i, (unsigned) JPC_QCX_GETEXPN(qcc->compparms.stepsizes[i]),
+ i, (unsigned) JPC_QCX_GETMANT(qcc->compparms.stepsizes[i]));
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* QCD/QCC marker segment helper functions.
+\******************************************************************************/
+
+static void jpc_qcx_destroycompparms(jpc_qcxcp_t *compparms)
+{
+ if (compparms->stepsizes) {
+ jas_free(compparms->stepsizes);
+ }
+}
+
+static int jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
+ jas_stream_t *in, uint_fast16_t len)
+{
+ uint_fast8_t tmp;
+ int n;
+ int i;
+
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+
+ n = 0;
+ jpc_getuint8(in, &tmp);
+ ++n;
+ compparms->qntsty = tmp & 0x1f;
+ compparms->numguard = (tmp >> 5) & 7;
+ switch (compparms->qntsty) {
+ case JPC_QCX_SIQNT:
+ compparms->numstepsizes = 1;
+ break;
+ case JPC_QCX_NOQNT:
+ compparms->numstepsizes = (len - n);
+ break;
+ case JPC_QCX_SEQNT:
+ /* XXX - this is a hack */
+ compparms->numstepsizes = (len - n) / 2;
+ break;
+ }
+ if (compparms->numstepsizes > 0) {
+ compparms->stepsizes = jas_malloc(compparms->numstepsizes *
+ sizeof(uint_fast16_t));
+ assert(compparms->stepsizes);
+ for (i = 0; i < compparms->numstepsizes; ++i) {
+ if (compparms->qntsty == JPC_QCX_NOQNT) {
+ jpc_getuint8(in, &tmp);
+ compparms->stepsizes[i] = JPC_QCX_EXPN(tmp >> 3);
+ } else {
+ jpc_getuint16(in, &compparms->stepsizes[i]);
+ }
+ }
+ } else {
+ compparms->stepsizes = 0;
+ }
+ if (jas_stream_error(in) || jas_stream_eof(in)) {
+ jpc_qcx_destroycompparms(compparms);
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_qcx_putcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
+ jas_stream_t *out)
+{
+ int i;
+
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+
+ jpc_putuint8(out, ((compparms->numguard & 7) << 5) | compparms->qntsty);
+ for (i = 0; i < compparms->numstepsizes; ++i) {
+ if (compparms->qntsty == JPC_QCX_NOQNT) {
+ jpc_putuint8(out, JPC_QCX_GETEXPN(
+ compparms->stepsizes[i]) << 3);
+ } else {
+ jpc_putuint16(out, compparms->stepsizes[i]);
+ }
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* SOP marker segment operations.
+\******************************************************************************/
+
+static int jpc_sop_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+ jpc_sop_t *sop = &ms->parms.sop;
+
+ /* Eliminate compiler warning about unused variable. */
+ cstate = 0;
+
+ if (jpc_getuint16(in, &sop->seqno)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_sop_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ jpc_sop_t *sop = &ms->parms.sop;
+
+ /* Eliminate compiler warning about unused variable. */
+ cstate = 0;
+
+ if (jpc_putuint16(out, sop->seqno)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_sop_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ jpc_sop_t *sop = &ms->parms.sop;
+ fprintf(out, "seqno = %d;\n", sop->seqno);
+ return 0;
+}
+
+/******************************************************************************\
+* PPM marker segment operations.
+\******************************************************************************/
+
+static void jpc_ppm_destroyparms(jpc_ms_t *ms)
+{
+ jpc_ppm_t *ppm = &ms->parms.ppm;
+ if (ppm->data) {
+ jas_free(ppm->data);
+ }
+}
+
+static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+ jpc_ppm_t *ppm = &ms->parms.ppm;
+
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+
+ ppm->data = 0;
+
+ if (ms->len < 1) {
+ goto error;
+ }
+ if (jpc_getuint8(in, &ppm->ind)) {
+ goto error;
+ }
+
+ ppm->len = ms->len - 1;
+ if (ppm->len > 0) {
+ if (!(ppm->data = jas_malloc(ppm->len * sizeof(unsigned char)))) {
+ goto error;
+ }
+ if (JAS_CAST(uint, jas_stream_read(in, ppm->data, ppm->len)) != ppm->len) {
+ goto error;
+ }
+ } else {
+ ppm->data = 0;
+ }
+ return 0;
+
+error:
+ jpc_ppm_destroyparms(ms);
+ return -1;
+}
+
+static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ jpc_ppm_t *ppm = &ms->parms.ppm;
+
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+
+ if (JAS_CAST(uint, jas_stream_write(out, (char *) ppm->data, ppm->len)) != ppm->len) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_ppm_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ jpc_ppm_t *ppm = &ms->parms.ppm;
+ fprintf(out, "ind=%d; len = %d;\n", ppm->ind, ppm->len);
+ if (ppm->len > 0) {
+ fprintf(out, "data =\n");
+ jas_memdump(out, ppm->data, ppm->len);
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* PPT marker segment operations.
+\******************************************************************************/
+
+static void jpc_ppt_destroyparms(jpc_ms_t *ms)
+{
+ jpc_ppt_t *ppt = &ms->parms.ppt;
+ if (ppt->data) {
+ jas_free(ppt->data);
+ }
+}
+
+static int jpc_ppt_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+ jpc_ppt_t *ppt = &ms->parms.ppt;
+
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+
+ ppt->data = 0;
+
+ if (ms->len < 1) {
+ goto error;
+ }
+ if (jpc_getuint8(in, &ppt->ind)) {
+ goto error;
+ }
+ ppt->len = ms->len - 1;
+ if (ppt->len > 0) {
+ if (!(ppt->data = jas_malloc(ppt->len * sizeof(unsigned char)))) {
+ goto error;
+ }
+ if (jas_stream_read(in, (char *) ppt->data, ppt->len) != JAS_CAST(int, ppt->len)) {
+ goto error;
+ }
+ } else {
+ ppt->data = 0;
+ }
+ return 0;
+
+error:
+ jpc_ppt_destroyparms(ms);
+ return -1;
+}
+
+static int jpc_ppt_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ jpc_ppt_t *ppt = &ms->parms.ppt;
+
+ /* Eliminate compiler warning about unused variable. */
+ cstate = 0;
+
+ if (jpc_putuint8(out, ppt->ind)) {
+ return -1;
+ }
+ if (jas_stream_write(out, (char *) ppt->data, ppt->len) != JAS_CAST(int, ppt->len)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_ppt_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ jpc_ppt_t *ppt = &ms->parms.ppt;
+ fprintf(out, "ind=%d; len = %d;\n", ppt->ind, ppt->len);
+ if (ppt->len > 0) {
+ fprintf(out, "data =\n");
+ jas_memdump(out, ppt->data, ppt->len);
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* POC marker segment operations.
+\******************************************************************************/
+
+static void jpc_poc_destroyparms(jpc_ms_t *ms)
+{
+ jpc_poc_t *poc = &ms->parms.poc;
+ if (poc->pchgs) {
+ jas_free(poc->pchgs);
+ }
+}
+
+static int jpc_poc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+ jpc_poc_t *poc = &ms->parms.poc;
+ jpc_pocpchg_t *pchg;
+ int pchgno;
+ uint_fast8_t tmp;
+ poc->numpchgs = (cstate->numcomps > 256) ? (ms->len / 9) :
+ (ms->len / 7);
+ if (!(poc->pchgs = jas_malloc(poc->numpchgs * sizeof(jpc_pocpchg_t)))) {
+ goto error;
+ }
+ for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; ++pchgno,
+ ++pchg) {
+ if (jpc_getuint8(in, &pchg->rlvlnostart)) {
+ goto error;
+ }
+ if (cstate->numcomps > 256) {
+ if (jpc_getuint16(in, &pchg->compnostart)) {
+ goto error;
+ }
+ } else {
+ if (jpc_getuint8(in, &tmp)) {
+ goto error;
+ };
+ pchg->compnostart = tmp;
+ }
+ if (jpc_getuint16(in, &pchg->lyrnoend) ||
+ jpc_getuint8(in, &pchg->rlvlnoend)) {
+ goto error;
+ }
+ if (cstate->numcomps > 256) {
+ if (jpc_getuint16(in, &pchg->compnoend)) {
+ goto error;
+ }
+ } else {
+ if (jpc_getuint8(in, &tmp)) {
+ goto error;
+ }
+ pchg->compnoend = tmp;
+ }
+ if (jpc_getuint8(in, &pchg->prgord)) {
+ goto error;
+ }
+ if (pchg->rlvlnostart > pchg->rlvlnoend ||
+ pchg->compnostart > pchg->compnoend) {
+ goto error;
+ }
+ }
+ return 0;
+
+error:
+ jpc_poc_destroyparms(ms);
+ return -1;
+}
+
+static int jpc_poc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ jpc_poc_t *poc = &ms->parms.poc;
+ jpc_pocpchg_t *pchg;
+ int pchgno;
+ for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; ++pchgno,
+ ++pchg) {
+ if (jpc_putuint8(out, pchg->rlvlnostart) ||
+ ((cstate->numcomps > 256) ?
+ jpc_putuint16(out, pchg->compnostart) :
+ jpc_putuint8(out, pchg->compnostart)) ||
+ jpc_putuint16(out, pchg->lyrnoend) ||
+ jpc_putuint8(out, pchg->rlvlnoend) ||
+ ((cstate->numcomps > 256) ?
+ jpc_putuint16(out, pchg->compnoend) :
+ jpc_putuint8(out, pchg->compnoend)) ||
+ jpc_putuint8(out, pchg->prgord)) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static int jpc_poc_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ jpc_poc_t *poc = &ms->parms.poc;
+ jpc_pocpchg_t *pchg;
+ int pchgno;
+ for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs;
+ ++pchgno, ++pchg) {
+ fprintf(out, "po[%d] = %d; ", pchgno, pchg->prgord);
+ fprintf(out, "cs[%d] = %d; ce[%d] = %d; ",
+ pchgno, pchg->compnostart, pchgno, pchg->compnoend);
+ fprintf(out, "rs[%d] = %d; re[%d] = %d; ",
+ pchgno, pchg->rlvlnostart, pchgno, pchg->rlvlnoend);
+ fprintf(out, "le[%d] = %d\n", pchgno, pchg->lyrnoend);
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* CRG marker segment operations.
+\******************************************************************************/
+
+static void jpc_crg_destroyparms(jpc_ms_t *ms)
+{
+ jpc_crg_t *crg = &ms->parms.crg;
+ if (crg->comps) {
+ jas_free(crg->comps);
+ }
+}
+
+static int jpc_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+ jpc_crg_t *crg = &ms->parms.crg;
+ jpc_crgcomp_t *comp;
+ uint_fast16_t compno;
+ crg->numcomps = cstate->numcomps;
+ if (!(crg->comps = jas_malloc(cstate->numcomps * sizeof(uint_fast16_t)))) {
+ return -1;
+ }
+ for (compno = 0, comp = crg->comps; compno < cstate->numcomps;
+ ++compno, ++comp) {
+ if (jpc_getuint16(in, &comp->hoff) ||
+ jpc_getuint16(in, &comp->voff)) {
+ jpc_crg_destroyparms(ms);
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static int jpc_crg_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ jpc_crg_t *crg = &ms->parms.crg;
+ int compno;
+ jpc_crgcomp_t *comp;
+
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+
+ for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno,
+ ++comp) {
+ if (jpc_putuint16(out, comp->hoff) ||
+ jpc_putuint16(out, comp->voff)) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static int jpc_crg_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ jpc_crg_t *crg = &ms->parms.crg;
+ int compno;
+ jpc_crgcomp_t *comp;
+ for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno,
+ ++comp) {
+ fprintf(out, "hoff[%d] = %d; voff[%d] = %d\n", compno,
+ comp->hoff, compno, comp->voff);
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Operations for COM marker segment.
+\******************************************************************************/
+
+static void jpc_com_destroyparms(jpc_ms_t *ms)
+{
+ jpc_com_t *com = &ms->parms.com;
+ if (com->data) {
+ jas_free(com->data);
+ }
+}
+
+static int jpc_com_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+ jpc_com_t *com = &ms->parms.com;
+
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+
+ if (jpc_getuint16(in, &com->regid)) {
+ return -1;
+ }
+ com->len = ms->len - 2;
+ if (com->len > 0) {
+ if (!(com->data = jas_malloc(com->len))) {
+ return -1;
+ }
+ if (jas_stream_read(in, com->data, com->len) != JAS_CAST(int, com->len)) {
+ return -1;
+ }
+ } else {
+ com->data = 0;
+ }
+ return 0;
+}
+
+static int jpc_com_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ jpc_com_t *com = &ms->parms.com;
+
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+
+ if (jpc_putuint16(out, com->regid)) {
+ return -1;
+ }
+ if (jas_stream_write(out, com->data, com->len) != JAS_CAST(int, com->len)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_com_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ jpc_com_t *com = &ms->parms.com;
+ unsigned int i;
+ int printable;
+ fprintf(out, "regid = %d;\n", com->regid);
+ printable = 1;
+ for (i = 0; i < com->len; ++i) {
+ if (!isprint(com->data[i])) {
+ printable = 0;
+ break;
+ }
+ }
+ if (printable) {
+ fprintf(out, "data = ");
+ fwrite(com->data, sizeof(char), com->len, out);
+ fprintf(out, "\n");
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Operations for unknown types of marker segments.
+\******************************************************************************/
+
+static void jpc_unk_destroyparms(jpc_ms_t *ms)
+{
+ jpc_unk_t *unk = &ms->parms.unk;
+ if (unk->data) {
+ jas_free(unk->data);
+ }
+}
+
+static int jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
+{
+ jpc_unk_t *unk = &ms->parms.unk;
+
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+
+ if (ms->len > 0) {
+ if (!(unk->data = jas_malloc(ms->len * sizeof(unsigned char)))) {
+ return -1;
+ }
+ if (jas_stream_read(in, (char *) unk->data, ms->len) != JAS_CAST(int, ms->len)) {
+ jas_free(unk->data);
+ return -1;
+ }
+ unk->len = ms->len;
+ } else {
+ unk->data = 0;
+ unk->len = 0;
+ }
+ return 0;
+}
+
+static int jpc_unk_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
+{
+ /* Eliminate compiler warning about unused variables. */
+ cstate = 0;
+ ms = 0;
+ out = 0;
+
+ /* If this function is called, we are trying to write an unsupported
+ type of marker segment. Return with an error indication. */
+ return -1;
+}
+
+static int jpc_unk_dumpparms(jpc_ms_t *ms, FILE *out)
+{
+ unsigned int i;
+ jpc_unk_t *unk = &ms->parms.unk;
+ for (i = 0; i < unk->len; ++i) {
+ fprintf(out, "%02x ", unk->data[i]);
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Primitive I/O operations.
+\******************************************************************************/
+
+int jpc_getuint8(jas_stream_t *in, uint_fast8_t *val)
+{
+ int c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ if (val) {
+ *val = c;
+ }
+ return 0;
+}
+
+int jpc_putuint8(jas_stream_t *out, uint_fast8_t val)
+{
+ if (jas_stream_putc(out, val & 0xff) == EOF) {
+ return -1;
+ }
+ return 0;
+}
+
+int jpc_getuint16(jas_stream_t *in, uint_fast16_t *val)
+{
+ uint_fast16_t v;
+ int c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = (v << 8) | c;
+ if (val) {
+ *val = v;
+ }
+ return 0;
+}
+
+int jpc_putuint16(jas_stream_t *out, uint_fast16_t val)
+{
+ if (jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
+ jas_stream_putc(out, val & 0xff) == EOF) {
+ return -1;
+ }
+ return 0;
+}
+
+int jpc_getuint32(jas_stream_t *in, uint_fast32_t *val)
+{
+ uint_fast32_t v;
+ int c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = (v << 8) | c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = (v << 8) | c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = (v << 8) | c;
+ if (val) {
+ *val = v;
+ }
+ return 0;
+}
+
+int jpc_putuint32(jas_stream_t *out, uint_fast32_t val)
+{
+ if (jas_stream_putc(out, (val >> 24) & 0xff) == EOF ||
+ jas_stream_putc(out, (val >> 16) & 0xff) == EOF ||
+ jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
+ jas_stream_putc(out, val & 0xff) == EOF) {
+ return -1;
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Miscellany
+\******************************************************************************/
+
+static jpc_mstabent_t *jpc_mstab_lookup(int id)
+{
+ jpc_mstabent_t *mstabent;
+ for (mstabent = jpc_mstab;; ++mstabent) {
+ if (mstabent->id == id || mstabent->id < 0) {
+ return mstabent;
+ }
+ }
+ assert(0);
+ return 0;
+}
+
+int jpc_validate(jas_stream_t *in)
+{
+ int n;
+ int i;
+ unsigned char buf[2];
+
+ assert(JAS_STREAM_MAXPUTBACK >= 2);
+
+ if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) {
+ return -1;
+ }
+ for (i = n - 1; i >= 0; --i) {
+ if (jas_stream_ungetc(in, buf[i]) == EOF) {
+ return -1;
+ }
+ }
+ if (n < 2) {
+ return -1;
+ }
+ if (buf[0] == (JPC_MS_SOC >> 8) && buf[1] == (JPC_MS_SOC & 0xff)) {
+ return 0;
+ }
+ return -1;
+}
+
+int jpc_getdata(jas_stream_t *in, jas_stream_t *out, long len)
+{
+ return jas_stream_copy(out, in, len);
+}
+
+int jpc_putdata(jas_stream_t *out, jas_stream_t *in, long len)
+{
+ return jas_stream_copy(out, in, len);
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_cs.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_cs.h
new file mode 100644
index 0000000..311986f
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_cs.h
@@ -0,0 +1,763 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JPEG-2000 Code Stream Library
+ *
+ * $Id$
+ */
+
+#ifndef JPC_CS_H
+#define JPC_CS_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_image.h"
+#include "jasper/jas_stream.h"
+
+#include "jpc_cod.h"
+
+/******************************************************************************\
+* Constants and Types.
+\******************************************************************************/
+
+/* The maximum number of resolution levels. */
+#define JPC_MAXRLVLS 33
+
+/* The maximum number of bands. */
+#define JPC_MAXBANDS (3 * JPC_MAXRLVLS + 1)
+
+/* The maximum number of layers. */
+#define JPC_MAXLYRS 16384
+
+/**************************************\
+* Code stream.
+\**************************************/
+
+/*
+ * Code stream states.
+ */
+
+/* Initial. */
+#define JPC_CS_INIT 0
+/* Main header. */
+#define JPC_CS_MHDR 1
+/* Tile-part header. */
+#define JPC_CS_THDR 2
+/* Main trailer. */
+#define JPC_CS_MTLR 3
+/* Tile-part data. */
+#define JPC_CS_TDATA 4
+
+/*
+ * Unfortunately, the code stream syntax was not designed in such a way that
+ * any given marker segment can be correctly decoded without additional state
+ * derived from previously decoded marker segments.
+ * For example, a RGN/COC/QCC marker segment cannot be decoded unless the
+ * number of components is known.
+ */
+
+/*
+ * Code stream state information.
+ */
+
+typedef struct {
+
+ /* The number of components. */
+ uint_fast16_t numcomps;
+
+} jpc_cstate_t;
+
+/**************************************\
+* SOT marker segment parameters.
+\**************************************/
+
+typedef struct {
+
+ /* The tile number. */
+ uint_fast16_t tileno;
+
+ /* The combined length of the marker segment and its auxilary data
+ (i.e., packet data). */
+ uint_fast32_t len;
+
+ /* The tile-part instance. */
+ uint_fast8_t partno;
+
+ /* The number of tile-parts. */
+ uint_fast8_t numparts;
+
+} jpc_sot_t;
+
+/**************************************\
+* SIZ marker segment parameters.
+\**************************************/
+
+/* Per component information. */
+
+typedef struct {
+
+ /* The precision of the samples. */
+ uint_fast8_t prec;
+
+ /* The signedness of the samples. */
+ uint_fast8_t sgnd;
+
+ /* The horizontal separation of samples with respect to the reference
+ grid. */
+ uint_fast8_t hsamp;
+
+ /* The vertical separation of samples with respect to the reference
+ grid. */
+ uint_fast8_t vsamp;
+
+} jpc_sizcomp_t;
+
+/* SIZ marker segment parameters. */
+
+typedef struct {
+
+ /* The code stream capabilities. */
+ uint_fast16_t caps;
+
+ /* The width of the image in units of the reference grid. */
+ uint_fast32_t width;
+
+ /* The height of the image in units of the reference grid. */
+ uint_fast32_t height;
+
+ /* The horizontal offset from the origin of the reference grid to the
+ left side of the image area. */
+ uint_fast32_t xoff;
+
+ /* The vertical offset from the origin of the reference grid to the
+ top side of the image area. */
+ uint_fast32_t yoff;
+
+ /* The nominal width of a tile in units of the reference grid. */
+ uint_fast32_t tilewidth;
+
+ /* The nominal height of a tile in units of the reference grid. */
+ uint_fast32_t tileheight;
+
+ /* The horizontal offset from the origin of the reference grid to the
+ left side of the first tile. */
+ uint_fast32_t tilexoff;
+
+ /* The vertical offset from the origin of the reference grid to the
+ top side of the first tile. */
+ uint_fast32_t tileyoff;
+
+ /* The number of components. */
+ uint_fast16_t numcomps;
+
+ /* The per-component information. */
+ jpc_sizcomp_t *comps;
+
+} jpc_siz_t;
+
+/**************************************\
+* COD marker segment parameters.
+\**************************************/
+
+/*
+ * Coding style constants.
+ */
+
+/* Precincts may be used. */
+#define JPC_COX_PRT 0x01
+/* SOP marker segments may be used. */
+#define JPC_COD_SOP 0x02
+/* EPH marker segments may be used. */
+#define JPC_COD_EPH 0x04
+
+/*
+ * Progression order constants.
+ */
+
+/* Layer-resolution-component-precinct progressive
+ (i.e., progressive by fidelity). */
+#define JPC_COD_LRCPPRG 0
+/* Resolution-layer-component-precinct progressive
+ (i.e., progressive by resolution). */
+#define JPC_COD_RLCPPRG 1
+/* Resolution-precinct-component-layer progressive. */
+#define JPC_COD_RPCLPRG 2
+/* Precinct-component-resolution-layer progressive. */
+#define JPC_COD_PCRLPRG 3
+/* Component-position-resolution-layer progressive. */
+#define JPC_COD_CPRLPRG 4
+
+/*
+ * Code block style constants.
+ */
+
+#define JPC_COX_LAZY 0x01 /* Selective arithmetic coding bypass. */
+#define JPC_COX_RESET 0x02 /* Reset context probabilities. */
+#define JPC_COX_TERMALL 0x04 /* Terminate all coding passes. */
+#define JPC_COX_VSC 0x08 /* Vertical stripe causal context formation. */
+#define JPC_COX_PTERM 0x10 /* Predictable termination. */
+#define JPC_COX_SEGSYM 0x20 /* Use segmentation symbols. */
+
+/* Transform constants. */
+#define JPC_COX_INS 0x00 /* Irreversible 9/7. */
+#define JPC_COX_RFT 0x01 /* Reversible 5/3. */
+
+/* Multicomponent transform constants. */
+#define JPC_COD_NOMCT 0x00 /* No multicomponent transform. */
+#define JPC_COD_MCT 0x01 /* Multicomponent transform. */
+
+/* Get the code block size value from the code block size exponent. */
+#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)
+
+/* Per resolution-level information. */
+
+typedef struct {
+
+ /* The packet partition width. */
+ uint_fast8_t parwidthval;
+
+ /* The packet partition height. */
+ uint_fast8_t parheightval;
+
+} jpc_coxrlvl_t;
+
+/* Per component information. */
+
+typedef struct {
+
+ /* The coding style. */
+ uint_fast8_t csty;
+
+ /* The number of decomposition levels. */
+ uint_fast8_t numdlvls;
+
+ /* The nominal code block width specifier. */
+ uint_fast8_t cblkwidthval;
+
+ /* The nominal code block height specifier. */
+ uint_fast8_t cblkheightval;
+
+ /* The style of coding passes. */
+ uint_fast8_t cblksty;
+
+ /* The QMFB employed. */
+ uint_fast8_t qmfbid;
+
+ /* The number of resolution levels. */
+ int numrlvls;
+
+ /* The per-resolution-level information. */
+ jpc_coxrlvl_t rlvls[JPC_MAXRLVLS];
+
+} jpc_coxcp_t;
+
+/* COD marker segment parameters. */
+
+typedef struct {
+
+ /* The general coding style. */
+ uint_fast8_t csty;
+
+ /* The progression order. */
+ uint_fast8_t prg;
+
+ /* The number of layers. */
+ uint_fast16_t numlyrs;
+
+ /* The multicomponent transform. */
+ uint_fast8_t mctrans;
+
+ /* Component-related parameters. */
+ jpc_coxcp_t compparms;
+
+} jpc_cod_t;
+
+/* COC marker segment parameters. */
+
+typedef struct {
+
+ /* The component number. */
+ uint_fast16_t compno;
+
+ /* Component-related parameters. */
+ jpc_coxcp_t compparms;
+
+} jpc_coc_t;
+
+/**************************************\
+* RGN marker segment parameters.
+\**************************************/
+
+/* The maxshift ROI style. */
+#define JPC_RGN_MAXSHIFT 0x00
+
+typedef struct {
+
+ /* The component to which the marker applies. */
+ uint_fast16_t compno;
+
+ /* The ROI style. */
+ uint_fast8_t roisty;
+
+ /* The ROI shift value. */
+ uint_fast8_t roishift;
+
+} jpc_rgn_t;
+
+/**************************************\
+* QCD/QCC marker segment parameters.
+\**************************************/
+
+/*
+ * Quantization style constants.
+ */
+
+#define JPC_QCX_NOQNT 0 /* No quantization. */
+#define JPC_QCX_SIQNT 1 /* Scalar quantization, implicit. */
+#define JPC_QCX_SEQNT 2 /* Scalar quantization, explicit. */
+
+/*
+ * Stepsize manipulation macros.
+ */
+
+#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 number of step sizes. */
+ int numstepsizes;
+
+ /* The step sizes. */
+ uint_fast16_t *stepsizes;
+
+ /* The number of guard bits. */
+ uint_fast8_t numguard;
+
+} jpc_qcxcp_t;
+
+/* QCC marker segment parameters. */
+
+typedef struct {
+
+ /* The component associated with this marker segment. */
+ uint_fast16_t compno;
+
+ /* The parameters. */
+ jpc_qcxcp_t compparms;
+
+} jpc_qcc_t;
+
+/* QCD marker segment parameters. */
+
+typedef struct {
+
+ /* The parameters. */
+ jpc_qcxcp_t compparms;
+
+} jpc_qcd_t;
+
+/**************************************\
+* POD marker segment parameters.
+\**************************************/
+
+typedef struct {
+
+ /* The progression order. */
+ uint_fast8_t prgord;
+
+ /* The lower bound (inclusive) on the resolution level for the
+ progression order volume. */
+ uint_fast8_t rlvlnostart;
+
+ /* The upper bound (exclusive) on the resolution level for the
+ progression order volume. */
+ uint_fast8_t rlvlnoend;
+
+ /* The lower bound (inclusive) on the component for the progression
+ order volume. */
+ uint_fast16_t compnostart;
+
+ /* The upper bound (exclusive) on the component for the progression
+ order volume. */
+ uint_fast16_t compnoend;
+
+ /* The upper bound (exclusive) on the layer for the progression
+ order volume. */
+ uint_fast16_t lyrnoend;
+
+} jpc_pocpchg_t;
+
+/* An alias for the above type. */
+typedef jpc_pocpchg_t jpc_pchg_t;
+
+/* POC marker segment parameters. */
+
+typedef struct {
+
+ /* The number of progression order changes. */
+ int numpchgs;
+
+ /* The per-progression-order-change information. */
+ jpc_pocpchg_t *pchgs;
+
+} jpc_poc_t;
+
+/**************************************\
+* PPM/PPT marker segment parameters.
+\**************************************/
+
+/* PPM marker segment parameters. */
+
+typedef struct {
+
+ /* The index. */
+ uint_fast8_t ind;
+
+ /* The length. */
+ uint_fast16_t len;
+
+ /* The data. */
+ uchar *data;
+
+} jpc_ppm_t;
+
+/* PPT marker segment parameters. */
+
+typedef struct {
+
+ /* The index. */
+ uint_fast8_t ind;
+
+ /* The length. */
+ uint_fast32_t len;
+
+ /* The data. */
+ unsigned char *data;
+
+} jpc_ppt_t;
+
+/**************************************\
+* COM marker segment parameters.
+\**************************************/
+
+/*
+ * Registration IDs.
+ */
+
+#define JPC_COM_BIN 0x00
+#define JPC_COM_LATIN 0x01
+
+typedef struct {
+
+ /* The registration ID. */
+ uint_fast16_t regid;
+
+ /* The length of the data in bytes. */
+ uint_fast16_t len;
+
+ /* The data. */
+ uchar *data;
+
+} jpc_com_t;
+
+/**************************************\
+* SOP marker segment parameters.
+\**************************************/
+
+typedef struct {
+
+ /* The sequence number. */
+ uint_fast16_t seqno;
+
+} jpc_sop_t;
+
+/**************************************\
+* CRG marker segment parameters.
+\**************************************/
+
+/* Per component information. */
+
+typedef struct {
+
+ /* The horizontal offset. */
+ uint_fast16_t hoff;
+
+ /* The vertical offset. */
+ uint_fast16_t voff;
+
+} jpc_crgcomp_t;
+
+typedef struct {
+
+ /* The number of components. */
+ int numcomps;
+
+ /* Per component information. */
+ jpc_crgcomp_t *comps;
+
+} jpc_crg_t;
+
+/**************************************\
+* Marker segment parameters for unknown marker type.
+\**************************************/
+
+typedef struct {
+
+ /* The data. */
+ uchar *data;
+
+ /* The length. */
+ uint_fast16_t len;
+
+} jpc_unk_t;
+
+/**************************************\
+* Generic marker segment parameters.
+\**************************************/
+
+typedef union {
+ int soc; /* unused */
+ jpc_sot_t sot;
+ int sod; /* unused */
+ int eoc; /* unused */
+ jpc_siz_t siz;
+ jpc_cod_t cod;
+ jpc_coc_t coc;
+ jpc_rgn_t rgn;
+ jpc_qcd_t qcd;
+ jpc_qcc_t qcc;
+ jpc_poc_t poc;
+ /* jpc_plm_t plm; */
+ /* jpc_plt_t plt; */
+ jpc_ppm_t ppm;
+ jpc_ppt_t ppt;
+ jpc_sop_t sop;
+ int eph; /* unused */
+ jpc_com_t com;
+ jpc_crg_t crg;
+ jpc_unk_t unk;
+} jpc_msparms_t;
+
+/**************************************\
+* Marker segment.
+\**************************************/
+
+/* Marker segment IDs. */
+
+/* The smallest valid marker value. */
+#define JPC_MS_MIN 0xff00
+
+/* The largest valid marker value. */
+#define JPC_MS_MAX 0xffff
+
+/* The minimum marker value that cannot occur within packet data. */
+#define JPC_MS_INMIN 0xff80
+/* The maximum marker value that cannot occur within packet data. */
+#define JPC_MS_INMAX 0xffff
+
+/* Delimiting marker segments. */
+#define JPC_MS_SOC 0xff4f /* Start of code stream (SOC). */
+#define JPC_MS_SOT 0xff90 /* Start of tile-part (SOT). */
+#define JPC_MS_SOD 0xff93 /* Start of data (SOD). */
+#define JPC_MS_EOC 0xffd9 /* End of code stream (EOC). */
+
+/* Fixed information marker segments. */
+#define JPC_MS_SIZ 0xff51 /* Image and tile size (SIZ). */
+
+/* Functional marker segments. */
+#define JPC_MS_COD 0xff52 /* Coding style default (COD). */
+#define JPC_MS_COC 0xff53 /* Coding style component (COC). */
+#define JPC_MS_RGN 0xff5e /* Region of interest (RGN). */
+#define JPC_MS_QCD 0xff5c /* Quantization default (QCD). */
+#define JPC_MS_QCC 0xff5d /* Quantization component (QCC). */
+#define JPC_MS_POC 0xff5f /* Progression order default (POC). */
+
+/* Pointer marker segments. */
+#define JPC_MS_TLM 0xff55 /* Tile-part lengths, main header (TLM). */
+#define JPC_MS_PLM 0xff57 /* Packet length, main header (PLM). */
+#define JPC_MS_PLT 0xff58 /* Packet length, tile-part header (PLT). */
+#define JPC_MS_PPM 0xff60 /* Packed packet headers, main header (PPM). */
+#define JPC_MS_PPT 0xff61 /* Packet packet headers, tile-part header (PPT). */
+
+/* In bit stream marker segments. */
+#define JPC_MS_SOP 0xff91 /* Start of packet (SOP). */
+#define JPC_MS_EPH 0xff92 /* End of packet header (EPH). */
+
+/* Informational marker segments. */
+#define JPC_MS_CRG 0xff63 /* Component registration (CRG). */
+#define JPC_MS_COM 0xff64 /* Comment (COM). */
+
+/* Forward declaration. */
+struct jpc_msops_s;
+
+/* Generic marker segment class. */
+
+typedef struct {
+
+ /* The type of marker segment. */
+ uint_fast16_t id;
+
+ /* The length of the marker segment. */
+ uint_fast16_t len;
+
+ /* The starting offset within the stream. */
+ uint_fast32_t off;
+
+ /* The parameters of the marker segment. */
+ jpc_msparms_t parms;
+
+ /* The marker segment operations. */
+ struct jpc_msops_s *ops;
+
+} jpc_ms_t;
+
+/* Marker segment operations (which depend on the marker segment type). */
+
+typedef struct jpc_msops_s {
+
+ /* Destroy the marker segment parameters. */
+ void (*destroyparms)(jpc_ms_t *ms);
+
+ /* Get the marker segment parameters from a stream. */
+ int (*getparms)(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
+
+ /* Put the marker segment parameters to a stream. */
+ int (*putparms)(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
+
+ /* Dump the marker segment parameters (for debugging). */
+ int (*dumpparms)(jpc_ms_t *ms, FILE *out);
+
+} jpc_msops_t;
+
+/******************************************************************************\
+* Macros/Functions.
+\******************************************************************************/
+
+/* Create a code-stream state object. */
+jpc_cstate_t *jpc_cstate_create(void);
+
+/* Destroy a code-stream state object. */
+void jpc_cstate_destroy(jpc_cstate_t *cstate);
+
+/* Create a marker segment. */
+jpc_ms_t *jpc_ms_create(int type);
+
+/* Destroy a marker segment. */
+void jpc_ms_destroy(jpc_ms_t *ms);
+
+/* Does a marker segment have parameters? */
+#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)
+
+/* Read a marker segment from a stream. */
+jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate);
+
+/* Write a marker segment to a stream. */
+int jpc_putms(jas_stream_t *out, jpc_cstate_t *cstate, jpc_ms_t *ms);
+
+/* Copy code stream data from one stream to another. */
+int jpc_getdata(jas_stream_t *in, jas_stream_t *out, long n);
+
+/* Copy code stream data from one stream to another. */
+int jpc_putdata(jas_stream_t *out, jas_stream_t *in, long n);
+
+/* Dump a marker segment (for debugging). */
+void jpc_ms_dump(jpc_ms_t *ms, FILE *out);
+
+/* Read a 8-bit unsigned integer from a stream. */
+int jpc_getuint8(jas_stream_t *in, uint_fast8_t *val);
+
+/* Read a 16-bit unsigned integer from a stream. */
+int jpc_getuint16(jas_stream_t *in, uint_fast16_t *val);
+
+/* Read a 32-bit unsigned integer from a stream. */
+int jpc_getuint32(jas_stream_t *in, uint_fast32_t *val);
+
+/* Write a 8-bit unsigned integer to a stream. */
+int jpc_putuint8(jas_stream_t *out, uint_fast8_t val);
+
+/* Write a 16-bit unsigned integer to a stream. */
+int jpc_putuint16(jas_stream_t *out, uint_fast16_t val);
+
+/* Write a 32-bit unsigned integer to a stream. */
+int jpc_putuint32(jas_stream_t *out, uint_fast32_t val);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_dec.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_dec.c
new file mode 100644
index 0000000..fa72a0e
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_dec.c
@@ -0,0 +1,2305 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_tvp.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.h"
+
+#include "jpc_fix.h"
+#include "jpc_dec.h"
+#include "jpc_cs.h"
+#include "jpc_mct.h"
+#include "jpc_t2dec.h"
+#include "jpc_t1dec.h"
+#include "jpc_math.h"
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+#define JPC_MHSOC 0x0001
+ /* In the main header, expecting a SOC marker segment. */
+#define JPC_MHSIZ 0x0002
+ /* In the main header, expecting a SIZ marker segment. */
+#define JPC_MH 0x0004
+ /* In the main header, expecting "other" marker segments. */
+#define JPC_TPHSOT 0x0008
+ /* In a tile-part header, expecting a SOT marker segment. */
+#define JPC_TPH 0x0010
+ /* In a tile-part header, expecting "other" marker segments. */
+#define JPC_MT 0x0020
+ /* In the main trailer. */
+
+typedef struct {
+
+ uint_fast16_t id;
+ /* The marker segment type. */
+
+ int validstates;
+ /* The states in which this type of marker segment can be
+ validly encountered. */
+
+ int (*action)(jpc_dec_t *dec, jpc_ms_t *ms);
+ /* The action to take upon encountering this type of marker segment. */
+
+} jpc_dec_mstabent_t;
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+/* COD/COC parameters have been specified. */
+#define JPC_CSET 0x0001
+/* QCD/QCC parameters have been specified. */
+#define JPC_QSET 0x0002
+/* COD/COC parameters set from a COC marker segment. */
+#define JPC_COC 0x0004
+/* QCD/QCC parameters set from a QCC marker segment. */
+#define JPC_QCC 0x0008
+
+/******************************************************************************\
+* Local function prototypes.
+\******************************************************************************/
+
+static int jpc_dec_dump(jpc_dec_t *dec, FILE *out);
+
+jpc_ppxstab_t *jpc_ppxstab_create(void);
+void jpc_ppxstab_destroy(jpc_ppxstab_t *tab);
+int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents);
+int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent);
+jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab);
+int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab);
+jpc_ppxstabent_t *jpc_ppxstabent_create(void);
+void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent);
+
+int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist);
+jpc_streamlist_t *jpc_streamlist_create(void);
+int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno,
+ jas_stream_t *stream);
+jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno);
+void jpc_streamlist_destroy(jpc_streamlist_t *streamlist);
+jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno);
+
+static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp);
+static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps);
+static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp);
+static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp);
+static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod);
+static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc);
+static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
+ jpc_coxcp_t *compparms, int flags);
+static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd);
+static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc);
+static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
+ jpc_qcxcp_t *compparms, int flags);
+static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn);
+static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp);
+static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp);
+static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset);
+static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc);
+
+static int jpc_dec_decode(jpc_dec_t *dec);
+static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in);
+static void jpc_dec_destroy(jpc_dec_t *dec);
+static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize);
+static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps);
+static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits);
+static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile);
+static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile);
+static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile);
+static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms);
+static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts);
+
+static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id);
+
+/******************************************************************************\
+* Global data.
+\******************************************************************************/
+
+jpc_dec_mstabent_t jpc_dec_mstab[] = {
+ {JPC_MS_SOC, JPC_MHSOC, jpc_dec_process_soc},
+ {JPC_MS_SOT, JPC_MH | JPC_TPHSOT, jpc_dec_process_sot},
+ {JPC_MS_SOD, JPC_TPH, jpc_dec_process_sod},
+ {JPC_MS_EOC, JPC_TPHSOT, jpc_dec_process_eoc},
+ {JPC_MS_SIZ, JPC_MHSIZ, jpc_dec_process_siz},
+ {JPC_MS_COD, JPC_MH | JPC_TPH, jpc_dec_process_cod},
+ {JPC_MS_COC, JPC_MH | JPC_TPH, jpc_dec_process_coc},
+ {JPC_MS_RGN, JPC_MH | JPC_TPH, jpc_dec_process_rgn},
+ {JPC_MS_QCD, JPC_MH | JPC_TPH, jpc_dec_process_qcd},
+ {JPC_MS_QCC, JPC_MH | JPC_TPH, jpc_dec_process_qcc},
+ {JPC_MS_POC, JPC_MH | JPC_TPH, jpc_dec_process_poc},
+ {JPC_MS_TLM, JPC_MH, 0},
+ {JPC_MS_PLM, JPC_MH, 0},
+ {JPC_MS_PLT, JPC_TPH, 0},
+ {JPC_MS_PPM, JPC_MH, jpc_dec_process_ppm},
+ {JPC_MS_PPT, JPC_TPH, jpc_dec_process_ppt},
+ {JPC_MS_SOP, 0, 0},
+ {JPC_MS_CRG, JPC_MH, jpc_dec_process_crg},
+ {JPC_MS_COM, JPC_MH | JPC_TPH, jpc_dec_process_com},
+ {0, JPC_MH | JPC_TPH, jpc_dec_process_unk}
+};
+
+/******************************************************************************\
+* The main entry point for the JPEG-2000 decoder.
+\******************************************************************************/
+
+jas_image_t *jpc_decode(jas_stream_t *in, char *optstr)
+{
+ jpc_dec_importopts_t opts;
+ jpc_dec_t *dec;
+ jas_image_t *image;
+
+ dec = 0;
+
+ if (jpc_dec_parseopts(optstr, &opts)) {
+ goto error;
+ }
+
+ jpc_initluts();
+
+ if (!(dec = jpc_dec_create(&opts, in))) {
+ goto error;
+ }
+
+ /* Do most of the work. */
+ if (jpc_dec_decode(dec)) {
+ goto error;
+ }
+
+ if (jas_image_numcmpts(dec->image) >= 3) {
+ jas_image_setclrspc(dec->image, JAS_CLRSPC_SRGB);
+ jas_image_setcmpttype(dec->image, 0,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
+ jas_image_setcmpttype(dec->image, 1,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
+ jas_image_setcmpttype(dec->image, 2,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
+ } else {
+ jas_image_setclrspc(dec->image, JAS_CLRSPC_SGRAY);
+ jas_image_setcmpttype(dec->image, 0,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
+ }
+
+ /* Save the return value. */
+ image = dec->image;
+
+ /* Stop the image from being discarded. */
+ dec->image = 0;
+
+ /* Destroy decoder. */
+ jpc_dec_destroy(dec);
+
+ return image;
+
+error:
+ if (dec) {
+ jpc_dec_destroy(dec);
+ }
+ return 0;
+}
+
+typedef enum {
+ OPT_MAXLYRS,
+ OPT_MAXPKTS,
+ OPT_DEBUG
+} optid_t;
+
+jas_taginfo_t decopts[] = {
+ {OPT_MAXLYRS, "maxlyrs"},
+ {OPT_MAXPKTS, "maxpkts"},
+ {OPT_DEBUG, "debug"},
+ {-1, 0}
+};
+
+static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts)
+{
+ jas_tvparser_t *tvp;
+
+ opts->debug = 0;
+ opts->maxlyrs = JPC_MAXLYRS;
+ opts->maxpkts = -1;
+
+ if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
+ return -1;
+ }
+
+ while (!jas_tvparser_next(tvp)) {
+ switch (jas_taginfo_nonull(jas_taginfos_lookup(decopts,
+ jas_tvparser_gettag(tvp)))->id) {
+ case OPT_MAXLYRS:
+ opts->maxlyrs = atoi(jas_tvparser_getval(tvp));
+ break;
+ case OPT_DEBUG:
+ opts->debug = atoi(jas_tvparser_getval(tvp));
+ break;
+ case OPT_MAXPKTS:
+ opts->maxpkts = atoi(jas_tvparser_getval(tvp));
+ break;
+ default:
+ jas_eprintf("warning: ignoring invalid option %s\n",
+ jas_tvparser_gettag(tvp));
+ break;
+ }
+ }
+
+ jas_tvparser_destroy(tvp);
+
+ return 0;
+}
+
+/******************************************************************************\
+* Code for table-driven code stream decoder.
+\******************************************************************************/
+
+static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id)
+{
+ jpc_dec_mstabent_t *mstabent;
+ for (mstabent = jpc_dec_mstab; mstabent->id != 0; ++mstabent) {
+ if (mstabent->id == id) {
+ break;
+ }
+ }
+ return mstabent;
+}
+
+static int jpc_dec_decode(jpc_dec_t *dec)
+{
+ jpc_ms_t *ms;
+ jpc_dec_mstabent_t *mstabent;
+ int ret;
+ jpc_cstate_t *cstate;
+
+ if (!(cstate = jpc_cstate_create())) {
+ return -1;
+ }
+ dec->cstate = cstate;
+
+ /* Initially, we should expect to encounter a SOC marker segment. */
+ dec->state = JPC_MHSOC;
+
+ for (;;) {
+
+ /* Get the next marker segment in the code stream. */
+ if (!(ms = jpc_getms(dec->in, cstate))) {
+ jas_eprintf("cannot get marker segment\n");
+ return -1;
+ }
+
+ mstabent = jpc_dec_mstab_lookup(ms->id);
+ assert(mstabent);
+
+ /* Ensure that this type of marker segment is permitted
+ at this point in the code stream. */
+ if (!(dec->state & mstabent->validstates)) {
+ jas_eprintf("unexpected marker segment type\n");
+ jpc_ms_destroy(ms);
+ return -1;
+ }
+
+ /* Process the marker segment. */
+ if (mstabent->action) {
+ ret = (*mstabent->action)(dec, ms);
+ } else {
+ /* No explicit action is required. */
+ ret = 0;
+ }
+
+ /* Destroy the marker segment. */
+ jpc_ms_destroy(ms);
+
+ if (ret < 0) {
+ return -1;
+ } else if (ret > 0) {
+ break;
+ }
+
+ }
+
+ return 0;
+}
+
+static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ int cmptno;
+ jpc_dec_cmpt_t *cmpt;
+ jpc_crg_t *crg;
+
+ crg = &ms->parms.crg;
+ for (cmptno = 0, cmpt = dec->cmpts; cmptno < dec->numcomps; ++cmptno,
+ ++cmpt) {
+ /* Ignore the information in the CRG marker segment for now.
+ This information serves no useful purpose for decoding anyhow.
+ Some other parts of the code need to be changed if these lines
+ are uncommented.
+ cmpt->hsubstep = crg->comps[cmptno].hoff;
+ cmpt->vsubstep = crg->comps[cmptno].voff;
+ */
+ }
+ return 0;
+}
+
+static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ /* Eliminate warnings about unused variables. */
+ ms = 0;
+
+ /* We should expect to encounter a SIZ marker segment next. */
+ dec->state = JPC_MHSIZ;
+
+ return 0;
+}
+
+static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ jpc_dec_tile_t *tile;
+ jpc_sot_t *sot = &ms->parms.sot;
+ jas_image_cmptparm_t *compinfos;
+ jas_image_cmptparm_t *compinfo;
+ jpc_dec_cmpt_t *cmpt;
+ int cmptno;
+
+ if (dec->state == JPC_MH) {
+
+ compinfos = jas_malloc(dec->numcomps * sizeof(jas_image_cmptparm_t));
+ assert(compinfos);
+ for (cmptno = 0, cmpt = dec->cmpts, compinfo = compinfos;
+ cmptno < dec->numcomps; ++cmptno, ++cmpt, ++compinfo) {
+ compinfo->tlx = 0;
+ compinfo->tly = 0;
+ compinfo->prec = cmpt->prec;
+ compinfo->sgnd = cmpt->sgnd;
+ compinfo->width = cmpt->width;
+ compinfo->height = cmpt->height;
+ compinfo->hstep = cmpt->hstep;
+ compinfo->vstep = cmpt->vstep;
+ }
+
+ if (!(dec->image = jas_image_create(dec->numcomps, compinfos,
+ JAS_CLRSPC_UNKNOWN))) {
+ return -1;
+ }
+ jas_free(compinfos);
+
+ /* Is the packet header information stored in PPM marker segments in
+ the main header? */
+ if (dec->ppmstab) {
+ /* Convert the PPM marker segment data into a collection of streams
+ (one stream per tile-part). */
+ if (!(dec->pkthdrstreams = jpc_ppmstabtostreams(dec->ppmstab))) {
+ abort();
+ }
+ jpc_ppxstab_destroy(dec->ppmstab);
+ dec->ppmstab = 0;
+ }
+ }
+
+ if (sot->len > 0) {
+ dec->curtileendoff = jas_stream_getrwcount(dec->in) - ms->len -
+ 4 + sot->len;
+ } else {
+ dec->curtileendoff = 0;
+ }
+
+ if (JAS_CAST(int, sot->tileno) > dec->numtiles) {
+ jas_eprintf("invalid tile number in SOT marker segment\n");
+ return -1;
+ }
+ /* Set the current tile. */
+ dec->curtile = &dec->tiles[sot->tileno];
+ tile = dec->curtile;
+ /* Ensure that this is the expected part number. */
+ if (sot->partno != tile->partno) {
+ return -1;
+ }
+ if (tile->numparts > 0 && sot->partno >= tile->numparts) {
+ return -1;
+ }
+ if (!tile->numparts && sot->numparts > 0) {
+ tile->numparts = sot->numparts;
+ }
+
+ tile->pptstab = 0;
+
+ switch (tile->state) {
+ case JPC_TILE_INIT:
+ /* This is the first tile-part for this tile. */
+ tile->state = JPC_TILE_ACTIVE;
+ assert(!tile->cp);
+ if (!(tile->cp = jpc_dec_cp_copy(dec->cp))) {
+ return -1;
+ }
+ jpc_dec_cp_resetflags(dec->cp);
+ break;
+ default:
+ if (sot->numparts == sot->partno - 1) {
+ tile->state = JPC_TILE_ACTIVELAST;
+ }
+ break;
+ }
+
+ /* Note: We do not increment the expected tile-part number until
+ all processing for this tile-part is complete. */
+
+ /* We should expect to encounter other tile-part header marker
+ segments next. */
+ dec->state = JPC_TPH;
+
+ return 0;
+}
+
+static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ jpc_dec_tile_t *tile;
+ int pos;
+
+ /* Eliminate compiler warnings about unused variables. */
+ ms = 0;
+
+ if (!(tile = dec->curtile)) {
+ return -1;
+ }
+
+ if (!tile->partno) {
+ if (!jpc_dec_cp_isvalid(tile->cp)) {
+ return -1;
+ }
+ jpc_dec_cp_prepare(tile->cp);
+ if (jpc_dec_tileinit(dec, tile)) {
+ return -1;
+ }
+ }
+
+ /* Are packet headers stored in the main header or tile-part header? */
+ if (dec->pkthdrstreams) {
+ /* Get the stream containing the packet header data for this
+ tile-part. */
+ if (!(tile->pkthdrstream = jpc_streamlist_remove(dec->pkthdrstreams, 0))) {
+ return -1;
+ }
+ }
+
+ if (tile->pptstab) {
+ if (!tile->pkthdrstream) {
+ if (!(tile->pkthdrstream = jas_stream_memopen(0, 0))) {
+ return -1;
+ }
+ }
+ pos = jas_stream_tell(tile->pkthdrstream);
+ jas_stream_seek(tile->pkthdrstream, 0, SEEK_END);
+ if (jpc_pptstabwrite(tile->pkthdrstream, tile->pptstab)) {
+ return -1;
+ }
+ jas_stream_seek(tile->pkthdrstream, pos, SEEK_SET);
+ jpc_ppxstab_destroy(tile->pptstab);
+ tile->pptstab = 0;
+ }
+
+ if (jas_getdbglevel() >= 10) {
+ jpc_dec_dump(dec, stderr);
+ }
+
+ if (jpc_dec_decodepkts(dec, (tile->pkthdrstream) ? tile->pkthdrstream :
+ dec->in, dec->in)) {
+ jas_eprintf("jpc_dec_decodepkts failed\n");
+ return -1;
+ }
+
+ /* Gobble any unconsumed tile data. */
+ if (dec->curtileendoff > 0) {
+ long curoff;
+ uint_fast32_t n;
+ curoff = jas_stream_getrwcount(dec->in);
+ if (curoff < dec->curtileendoff) {
+ n = dec->curtileendoff - curoff;
+ jas_eprintf("warning: ignoring trailing garbage (%lu bytes)\n",
+ (unsigned long) n);
+
+ while (n-- > 0) {
+ if (jas_stream_getc(dec->in) == EOF) {
+ jas_eprintf("read error\n");
+ return -1;
+ }
+ }
+ } else if (curoff > dec->curtileendoff) {
+ jas_eprintf("warning: not enough tile data (%lu bytes)\n",
+ (unsigned long) curoff - dec->curtileendoff);
+ }
+
+ }
+
+ if (tile->numparts > 0 && tile->partno == tile->numparts - 1) {
+ if (jpc_dec_tiledecode(dec, tile)) {
+ return -1;
+ }
+ jpc_dec_tilefini(dec, tile);
+ }
+
+ dec->curtile = 0;
+
+ /* Increment the expected tile-part number. */
+ ++tile->partno;
+
+ /* We should expect to encounter a SOT marker segment next. */
+ dec->state = JPC_TPHSOT;
+
+ return 0;
+}
+
+static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile)
+{
+ jpc_dec_tcomp_t *tcomp;
+ int compno;
+ int rlvlno;
+ jpc_dec_rlvl_t *rlvl;
+ jpc_dec_band_t *band;
+ jpc_dec_prc_t *prc;
+ int bndno;
+ jpc_tsfb_band_t *bnd;
+ int bandno;
+ jpc_dec_ccp_t *ccp;
+ int prccnt;
+ jpc_dec_cblk_t *cblk;
+ int cblkcnt;
+ uint_fast32_t tlprcxstart;
+ uint_fast32_t tlprcystart;
+ uint_fast32_t brprcxend;
+ uint_fast32_t brprcyend;
+ uint_fast32_t tlcbgxstart;
+ uint_fast32_t tlcbgystart;
+ uint_fast32_t brcbgxend;
+ uint_fast32_t brcbgyend;
+ uint_fast32_t cbgxstart;
+ uint_fast32_t cbgystart;
+ uint_fast32_t cbgxend;
+ uint_fast32_t cbgyend;
+ uint_fast32_t tlcblkxstart;
+ uint_fast32_t tlcblkystart;
+ uint_fast32_t brcblkxend;
+ uint_fast32_t brcblkyend;
+ uint_fast32_t cblkxstart;
+ uint_fast32_t cblkystart;
+ uint_fast32_t cblkxend;
+ uint_fast32_t cblkyend;
+ uint_fast32_t tmpxstart;
+ uint_fast32_t tmpystart;
+ uint_fast32_t tmpxend;
+ uint_fast32_t tmpyend;
+ jpc_dec_cp_t *cp;
+ jpc_tsfb_band_t bnds[64];
+ jpc_pchg_t *pchg;
+ int pchgno;
+ jpc_dec_cmpt_t *cmpt;
+
+ cp = tile->cp;
+ tile->realmode = 0;
+ if (cp->mctid == JPC_MCT_ICT) {
+ tile->realmode = 1;
+ }
+
+ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
+ dec->numcomps; ++compno, ++tcomp, ++cmpt) {
+ ccp = &tile->cp->ccps[compno];
+ if (ccp->qmfbid == JPC_COX_INS) {
+ tile->realmode = 1;
+ }
+ tcomp->numrlvls = ccp->numrlvls;
+ if (!(tcomp->rlvls = jas_malloc(tcomp->numrlvls *
+ sizeof(jpc_dec_rlvl_t)))) {
+ return -1;
+ }
+ if (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart,
+ cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep),
+ JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend,
+ cmpt->vstep)))) {
+ return -1;
+ }
+ if (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid,
+ tcomp->numrlvls - 1))) {
+ return -1;
+ }
+{
+ jpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data), jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data), jas_seq2d_yend(tcomp->data), bnds);
+}
+ for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
+ ++rlvlno, ++rlvl) {
+rlvl->bands = 0;
+ rlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart,
+ tcomp->numrlvls - 1 - rlvlno);
+ rlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart,
+ tcomp->numrlvls - 1 - rlvlno);
+ rlvl->xend = JPC_CEILDIVPOW2(tcomp->xend,
+ tcomp->numrlvls - 1 - rlvlno);
+ rlvl->yend = JPC_CEILDIVPOW2(tcomp->yend,
+ tcomp->numrlvls - 1 - rlvlno);
+ rlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno];
+ rlvl->prcheightexpn = ccp->prcheightexpns[rlvlno];
+ tlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart,
+ rlvl->prcwidthexpn) << rlvl->prcwidthexpn;
+ tlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart,
+ rlvl->prcheightexpn) << rlvl->prcheightexpn;
+ brprcxend = JPC_CEILDIVPOW2(rlvl->xend,
+ rlvl->prcwidthexpn) << rlvl->prcwidthexpn;
+ brprcyend = JPC_CEILDIVPOW2(rlvl->yend,
+ rlvl->prcheightexpn) << rlvl->prcheightexpn;
+ rlvl->numhprcs = (brprcxend - tlprcxstart) >>
+ rlvl->prcwidthexpn;
+ rlvl->numvprcs = (brprcyend - tlprcystart) >>
+ rlvl->prcheightexpn;
+ rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs;
+
+ if (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) {
+ rlvl->bands = 0;
+ rlvl->numprcs = 0;
+ rlvl->numhprcs = 0;
+ rlvl->numvprcs = 0;
+ continue;
+ }
+ if (!rlvlno) {
+ tlcbgxstart = tlprcxstart;
+ tlcbgystart = tlprcystart;
+ brcbgxend = brprcxend;
+ brcbgyend = brprcyend;
+ rlvl->cbgwidthexpn = rlvl->prcwidthexpn;
+ rlvl->cbgheightexpn = rlvl->prcheightexpn;
+ } else {
+ tlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1);
+ tlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1);
+ brcbgxend = JPC_CEILDIVPOW2(brprcxend, 1);
+ brcbgyend = JPC_CEILDIVPOW2(brprcyend, 1);
+ rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1;
+ rlvl->cbgheightexpn = rlvl->prcheightexpn - 1;
+ }
+ rlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn,
+ rlvl->cbgwidthexpn);
+ rlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn,
+ rlvl->cbgheightexpn);
+
+ rlvl->numbands = (!rlvlno) ? 1 : 3;
+ if (!(rlvl->bands = jas_malloc(rlvl->numbands *
+ sizeof(jpc_dec_band_t)))) {
+ return -1;
+ }
+ for (bandno = 0, band = rlvl->bands;
+ bandno < rlvl->numbands; ++bandno, ++band) {
+ bndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) +
+ bandno + 1);
+ bnd = &bnds[bndno];
+
+ band->orient = bnd->orient;
+ band->stepsize = ccp->stepsizes[bndno];
+ band->analgain = JPC_NOMINALGAIN(ccp->qmfbid,
+ tcomp->numrlvls - 1, rlvlno, band->orient);
+ band->absstepsize = jpc_calcabsstepsize(band->stepsize,
+ cmpt->prec + band->analgain);
+ band->numbps = ccp->numguardbits +
+ JPC_QCX_GETEXPN(band->stepsize) - 1;
+ band->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ?
+ (JPC_PREC - 1 - band->numbps) : ccp->roishift;
+ band->data = 0;
+ band->prcs = 0;
+ if (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) {
+ continue;
+ }
+ if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) {
+ return -1;
+ }
+ jas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart, bnd->locystart, bnd->locxend, bnd->locyend);
+ jas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart);
+
+ assert(rlvl->numprcs);
+
+ if (!(band->prcs = jas_malloc(rlvl->numprcs * sizeof(jpc_dec_prc_t)))) {
+ return -1;
+ }
+
+/************************************************/
+ cbgxstart = tlcbgxstart;
+ cbgystart = tlcbgystart;
+ for (prccnt = rlvl->numprcs, prc = band->prcs;
+ prccnt > 0; --prccnt, ++prc) {
+ cbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn);
+ cbgyend = cbgystart + (1 << rlvl->cbgheightexpn);
+ prc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t, jas_seq2d_xstart(band->data)));
+ prc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t, jas_seq2d_ystart(band->data)));
+ prc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t, jas_seq2d_xend(band->data)));
+ prc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t, jas_seq2d_yend(band->data)));
+ if (prc->xend > prc->xstart && prc->yend > prc->ystart) {
+ tlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart,
+ rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn;
+ tlcblkystart = JPC_FLOORDIVPOW2(prc->ystart,
+ rlvl->cblkheightexpn) << rlvl->cblkheightexpn;
+ brcblkxend = JPC_CEILDIVPOW2(prc->xend,
+ rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn;
+ brcblkyend = JPC_CEILDIVPOW2(prc->yend,
+ rlvl->cblkheightexpn) << rlvl->cblkheightexpn;
+ prc->numhcblks = (brcblkxend - tlcblkxstart) >>
+ rlvl->cblkwidthexpn;
+ prc->numvcblks = (brcblkyend - tlcblkystart) >>
+ rlvl->cblkheightexpn;
+ prc->numcblks = prc->numhcblks * prc->numvcblks;
+ assert(prc->numcblks > 0);
+
+ if (!(prc->incltagtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) {
+ return -1;
+ }
+ if (!(prc->numimsbstagtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) {
+ return -1;
+ }
+ if (!(prc->cblks = jas_malloc(prc->numcblks * sizeof(jpc_dec_cblk_t)))) {
+ return -1;
+ }
+
+ cblkxstart = cbgxstart;
+ cblkystart = cbgystart;
+ for (cblkcnt = prc->numcblks, cblk = prc->cblks; cblkcnt > 0;) {
+ cblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn);
+ cblkyend = cblkystart + (1 << rlvl->cblkheightexpn);
+ tmpxstart = JAS_MAX(cblkxstart, prc->xstart);
+ tmpystart = JAS_MAX(cblkystart, prc->ystart);
+ tmpxend = JAS_MIN(cblkxend, prc->xend);
+ tmpyend = JAS_MIN(cblkyend, prc->yend);
+ if (tmpxend > tmpxstart && tmpyend > tmpystart) {
+ cblk->firstpassno = -1;
+ cblk->mqdec = 0;
+ cblk->nulldec = 0;
+ cblk->flags = 0;
+ cblk->numpasses = 0;
+ cblk->segs.head = 0;
+ cblk->segs.tail = 0;
+ cblk->curseg = 0;
+ cblk->numimsbs = 0;
+ cblk->numlenbits = 3;
+ cblk->flags = 0;
+ if (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) {
+ return -1;
+ }
+ jas_seq2d_bindsub(cblk->data, band->data, tmpxstart, tmpystart, tmpxend, tmpyend);
+ ++cblk;
+ --cblkcnt;
+ }
+ cblkxstart += 1 << rlvl->cblkwidthexpn;
+ if (cblkxstart >= cbgxend) {
+ cblkxstart = cbgxstart;
+ cblkystart += 1 << rlvl->cblkheightexpn;
+ }
+ }
+
+ } else {
+ prc->cblks = 0;
+ prc->incltagtree = 0;
+ prc->numimsbstagtree = 0;
+ }
+ cbgxstart += 1 << rlvl->cbgwidthexpn;
+ if (cbgxstart >= brcbgxend) {
+ cbgxstart = tlcbgxstart;
+ cbgystart += 1 << rlvl->cbgheightexpn;
+ }
+
+ }
+/********************************************/
+ }
+ }
+ }
+
+if (!(tile->pi = jpc_dec_pi_create(dec, tile)))
+{
+ return -1;
+}
+
+ for (pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist);
+ ++pchgno) {
+ pchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno));
+ assert(pchg);
+ jpc_pi_addpchg(tile->pi, pchg);
+ }
+ jpc_pi_init(tile->pi);
+
+ return 0;
+}
+
+static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile)
+{
+ jpc_dec_tcomp_t *tcomp;
+ int compno;
+ int bandno;
+ int rlvlno;
+ jpc_dec_band_t *band;
+ jpc_dec_rlvl_t *rlvl;
+ int prcno;
+ jpc_dec_prc_t *prc;
+ jpc_dec_seg_t *seg;
+ jpc_dec_cblk_t *cblk;
+ int cblkno;
+
+if (tile->tcomps) {
+
+ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
+ ++compno, ++tcomp) {
+ for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
+ ++rlvlno, ++rlvl) {
+if (!rlvl->bands) {
+ continue;
+}
+ for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) {
+if (band->prcs) {
+ for (prcno = 0, prc = band->prcs; prcno <
+ rlvl->numprcs; ++prcno, ++prc) {
+if (!prc->cblks) {
+ continue;
+}
+ for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) {
+
+ while (cblk->segs.head) {
+ seg = cblk->segs.head;
+ jpc_seglist_remove(&cblk->segs, seg);
+ jpc_seg_destroy(seg);
+ }
+ jas_matrix_destroy(cblk->data);
+ if (cblk->mqdec) {
+ jpc_mqdec_destroy(cblk->mqdec);
+ }
+ if (cblk->nulldec) {
+ jpc_bitstream_close(cblk->nulldec);
+ }
+ if (cblk->flags) {
+ jas_matrix_destroy(cblk->flags);
+ }
+ }
+ if (prc->incltagtree) {
+ jpc_tagtree_destroy(prc->incltagtree);
+ }
+ if (prc->numimsbstagtree) {
+ jpc_tagtree_destroy(prc->numimsbstagtree);
+ }
+ if (prc->cblks) {
+ jas_free(prc->cblks);
+ }
+ }
+}
+ if (band->data) {
+ jas_matrix_destroy(band->data);
+ }
+ if (band->prcs) {
+ jas_free(band->prcs);
+ }
+ }
+ if (rlvl->bands) {
+ jas_free(rlvl->bands);
+ }
+ }
+ if (tcomp->rlvls) {
+ jas_free(tcomp->rlvls);
+ }
+ if (tcomp->data) {
+ jas_matrix_destroy(tcomp->data);
+ }
+ if (tcomp->tsfb) {
+ jpc_tsfb_destroy(tcomp->tsfb);
+ }
+ }
+}
+ if (tile->cp) {
+ jpc_dec_cp_destroy(tile->cp);
+ tile->cp = 0;
+ }
+ if (tile->tcomps) {
+ jas_free(tile->tcomps);
+ tile->tcomps = 0;
+ }
+ if (tile->pi) {
+ jpc_pi_destroy(tile->pi);
+ tile->pi = 0;
+ }
+ if (tile->pkthdrstream) {
+ jas_stream_close(tile->pkthdrstream);
+ tile->pkthdrstream = 0;
+ }
+ if (tile->pptstab) {
+ jpc_ppxstab_destroy(tile->pptstab);
+ tile->pptstab = 0;
+ }
+
+ tile->state = JPC_TILE_DONE;
+
+ return 0;
+}
+
+static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile)
+{
+ int i;
+ int j;
+ jpc_dec_tcomp_t *tcomp;
+ jpc_dec_rlvl_t *rlvl;
+ jpc_dec_band_t *band;
+ int compno;
+ int rlvlno;
+ int bandno;
+ int adjust;
+ int v;
+ jpc_dec_ccp_t *ccp;
+ jpc_dec_cmpt_t *cmpt;
+
+ if (jpc_dec_decodecblks(dec, tile)) {
+ jas_eprintf("jpc_dec_decodecblks failed\n");
+ return -1;
+ }
+
+ /* Perform dequantization. */
+ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
+ ++compno, ++tcomp) {
+ ccp = &tile->cp->ccps[compno];
+ for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
+ ++rlvlno, ++rlvl) {
+ if (!rlvl->bands) {
+ continue;
+ }
+ for (bandno = 0, band = rlvl->bands;
+ bandno < rlvl->numbands; ++bandno, ++band) {
+ if (!band->data) {
+ continue;
+ }
+ jpc_undo_roi(band->data, band->roishift, ccp->roishift -
+ band->roishift, band->numbps);
+ if (tile->realmode) {
+ jas_matrix_asl(band->data, JPC_FIX_FRACBITS);
+ jpc_dequantize(band->data, band->absstepsize);
+ }
+
+ }
+ }
+ }
+
+ /* Apply an inverse wavelet transform if necessary. */
+ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
+ ++compno, ++tcomp) {
+ ccp = &tile->cp->ccps[compno];
+ jpc_tsfb_synthesize(tcomp->tsfb, tcomp->data);
+ }
+
+
+ /* Apply an inverse intercomponent transform if necessary. */
+ switch (tile->cp->mctid) {
+ case JPC_MCT_RCT:
+ assert(dec->numcomps == 3);
+ jpc_irct(tile->tcomps[0].data, tile->tcomps[1].data,
+ tile->tcomps[2].data);
+ break;
+ case JPC_MCT_ICT:
+ assert(dec->numcomps == 3);
+ jpc_iict(tile->tcomps[0].data, tile->tcomps[1].data,
+ tile->tcomps[2].data);
+ break;
+ }
+
+ /* Perform rounding and convert to integer values. */
+ if (tile->realmode) {
+ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
+ ++compno, ++tcomp) {
+ for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) {
+ for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) {
+ v = jas_matrix_get(tcomp->data, i, j);
+ v = jpc_fix_round(v);
+ jas_matrix_set(tcomp->data, i, j, jpc_fixtoint(v));
+ }
+ }
+ }
+ }
+
+ /* Perform level shift. */
+ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
+ dec->numcomps; ++compno, ++tcomp, ++cmpt) {
+ adjust = cmpt->sgnd ? 0 : (1 << (cmpt->prec - 1));
+ for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) {
+ for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) {
+ *jas_matrix_getref(tcomp->data, i, j) += adjust;
+ }
+ }
+ }
+
+ /* Perform clipping. */
+ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
+ dec->numcomps; ++compno, ++tcomp, ++cmpt) {
+ jpc_fix_t mn;
+ jpc_fix_t mx;
+ mn = cmpt->sgnd ? (-(1 << (cmpt->prec - 1))) : (0);
+ mx = cmpt->sgnd ? ((1 << (cmpt->prec - 1)) - 1) : ((1 <<
+ cmpt->prec) - 1);
+ jas_matrix_clip(tcomp->data, mn, mx);
+ }
+
+ /* XXX need to free tsfb struct */
+
+ /* Write the data for each component of the image. */
+ for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
+ dec->numcomps; ++compno, ++tcomp, ++cmpt) {
+ if (jas_image_writecmpt(dec->image, compno, tcomp->xstart -
+ JPC_CEILDIV(dec->xstart, cmpt->hstep), tcomp->ystart -
+ JPC_CEILDIV(dec->ystart, cmpt->vstep), jas_matrix_numcols(
+ tcomp->data), jas_matrix_numrows(tcomp->data), tcomp->data)) {
+ jas_eprintf("write component failed\n");
+ return -4;
+ }
+ }
+
+ return 0;
+}
+
+static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ int tileno;
+ jpc_dec_tile_t *tile;
+
+ /* Eliminate compiler warnings about unused variables. */
+ ms = 0;
+
+ for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
+ ++tile) {
+ if (tile->state == JPC_TILE_ACTIVE) {
+ if (jpc_dec_tiledecode(dec, tile)) {
+ return -1;
+ }
+ }
+ jpc_dec_tilefini(dec, tile);
+ }
+
+ /* We are done processing the code stream. */
+ dec->state = JPC_MT;
+
+ return 1;
+}
+
+static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ jpc_siz_t *siz = &ms->parms.siz;
+ int compno;
+ int tileno;
+ jpc_dec_tile_t *tile;
+ jpc_dec_tcomp_t *tcomp;
+ int htileno;
+ int vtileno;
+ jpc_dec_cmpt_t *cmpt;
+
+ dec->xstart = siz->xoff;
+ dec->ystart = siz->yoff;
+ dec->xend = siz->width;
+ dec->yend = siz->height;
+ dec->tilewidth = siz->tilewidth;
+ dec->tileheight = siz->tileheight;
+ dec->tilexoff = siz->tilexoff;
+ dec->tileyoff = siz->tileyoff;
+ dec->numcomps = siz->numcomps;
+ if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {
+ return -1;
+ }
+
+ if (!(dec->cmpts = jas_malloc(dec->numcomps * sizeof(jpc_dec_cmpt_t)))) {
+ return -1;
+ }
+
+ for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,
+ ++cmpt) {
+ cmpt->prec = siz->comps[compno].prec;
+ cmpt->sgnd = siz->comps[compno].sgnd;
+ cmpt->hstep = siz->comps[compno].hsamp;
+ cmpt->vstep = siz->comps[compno].vsamp;
+ cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -
+ JPC_CEILDIV(dec->xstart, cmpt->hstep);
+ cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -
+ JPC_CEILDIV(dec->ystart, cmpt->vstep);
+ cmpt->hsubstep = 0;
+ cmpt->vsubstep = 0;
+ }
+
+ dec->image = 0;
+
+ dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);
+ dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);
+ dec->numtiles = dec->numhtiles * dec->numvtiles;
+ if (!(dec->tiles = jas_malloc(dec->numtiles * sizeof(jpc_dec_tile_t)))) {
+ return -1;
+ }
+
+ for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
+ ++tile) {
+ htileno = tileno % dec->numhtiles;
+ vtileno = tileno / dec->numhtiles;
+ tile->realmode = 0;
+ tile->state = JPC_TILE_INIT;
+ tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,
+ dec->xstart);
+ tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,
+ dec->ystart);
+ tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *
+ dec->tilewidth, dec->xend);
+ tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *
+ dec->tileheight, dec->yend);
+ tile->numparts = 0;
+ tile->partno = 0;
+ tile->pkthdrstream = 0;
+ tile->pkthdrstreampos = 0;
+ tile->pptstab = 0;
+ tile->cp = 0;
+ if (!(tile->tcomps = jas_malloc(dec->numcomps *
+ sizeof(jpc_dec_tcomp_t)))) {
+ return -1;
+ }
+ for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;
+ compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {
+ tcomp->rlvls = 0;
+ tcomp->data = 0;
+ tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);
+ tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);
+ tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);
+ tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);
+ tcomp->tsfb = 0;
+ }
+ }
+
+ dec->pkthdrstreams = 0;
+
+ /* We should expect to encounter other main header marker segments
+ or an SOT marker segment next. */
+ dec->state = JPC_MH;
+
+ return 0;
+}
+
+static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ jpc_cod_t *cod = &ms->parms.cod;
+ jpc_dec_tile_t *tile;
+
+ switch (dec->state) {
+ case JPC_MH:
+ jpc_dec_cp_setfromcod(dec->cp, cod);
+ break;
+ case JPC_TPH:
+ if (!(tile = dec->curtile)) {
+ return -1;
+ }
+ if (tile->partno != 0) {
+ return -1;
+ }
+ jpc_dec_cp_setfromcod(tile->cp, cod);
+ break;
+ }
+ return 0;
+}
+
+static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ jpc_coc_t *coc = &ms->parms.coc;
+ jpc_dec_tile_t *tile;
+
+ if (JAS_CAST(int, coc->compno) > dec->numcomps) {
+ jas_eprintf("invalid component number in COC marker segment\n");
+ return -1;
+ }
+ switch (dec->state) {
+ case JPC_MH:
+ jpc_dec_cp_setfromcoc(dec->cp, coc);
+ break;
+ case JPC_TPH:
+ if (!(tile = dec->curtile)) {
+ return -1;
+ }
+ if (tile->partno > 0) {
+ return -1;
+ }
+ jpc_dec_cp_setfromcoc(tile->cp, coc);
+ break;
+ }
+ return 0;
+}
+
+static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ jpc_rgn_t *rgn = &ms->parms.rgn;
+ jpc_dec_tile_t *tile;
+
+ if (JAS_CAST(int, rgn->compno) > dec->numcomps) {
+ jas_eprintf("invalid component number in RGN marker segment\n");
+ return -1;
+ }
+ switch (dec->state) {
+ case JPC_MH:
+ jpc_dec_cp_setfromrgn(dec->cp, rgn);
+ break;
+ case JPC_TPH:
+ if (!(tile = dec->curtile)) {
+ return -1;
+ }
+ if (tile->partno > 0) {
+ return -1;
+ }
+ jpc_dec_cp_setfromrgn(tile->cp, rgn);
+ break;
+ }
+
+ return 0;
+}
+
+static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ jpc_qcd_t *qcd = &ms->parms.qcd;
+ jpc_dec_tile_t *tile;
+
+ switch (dec->state) {
+ case JPC_MH:
+ jpc_dec_cp_setfromqcd(dec->cp, qcd);
+ break;
+ case JPC_TPH:
+ if (!(tile = dec->curtile)) {
+ return -1;
+ }
+ if (tile->partno > 0) {
+ return -1;
+ }
+ jpc_dec_cp_setfromqcd(tile->cp, qcd);
+ break;
+ }
+ return 0;
+}
+
+static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ jpc_qcc_t *qcc = &ms->parms.qcc;
+ jpc_dec_tile_t *tile;
+
+ if (JAS_CAST(int, qcc->compno) > dec->numcomps) {
+ jas_eprintf("invalid component number in QCC marker segment\n");
+ return -1;
+ }
+ switch (dec->state) {
+ case JPC_MH:
+ jpc_dec_cp_setfromqcc(dec->cp, qcc);
+ break;
+ case JPC_TPH:
+ if (!(tile = dec->curtile)) {
+ return -1;
+ }
+ if (tile->partno > 0) {
+ return -1;
+ }
+ jpc_dec_cp_setfromqcc(tile->cp, qcc);
+ break;
+ }
+ return 0;
+}
+
+static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ jpc_poc_t *poc = &ms->parms.poc;
+ jpc_dec_tile_t *tile;
+ switch (dec->state) {
+ case JPC_MH:
+ if (jpc_dec_cp_setfrompoc(dec->cp, poc, 1)) {
+ return -1;
+ }
+ break;
+ case JPC_TPH:
+ if (!(tile = dec->curtile)) {
+ return -1;
+ }
+ if (!tile->partno) {
+ if (jpc_dec_cp_setfrompoc(tile->cp, poc, (!tile->partno))) {
+ return -1;
+ }
+ } else {
+ jpc_pi_addpchgfrompoc(tile->pi, poc);
+ }
+ break;
+ }
+ return 0;
+}
+
+static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ jpc_ppm_t *ppm = &ms->parms.ppm;
+ jpc_ppxstabent_t *ppmstabent;
+
+ if (!dec->ppmstab) {
+ if (!(dec->ppmstab = jpc_ppxstab_create())) {
+ return -1;
+ }
+ }
+
+ if (!(ppmstabent = jpc_ppxstabent_create())) {
+ return -1;
+ }
+ ppmstabent->ind = ppm->ind;
+ ppmstabent->data = ppm->data;
+ ppm->data = 0;
+ ppmstabent->len = ppm->len;
+ if (jpc_ppxstab_insert(dec->ppmstab, ppmstabent)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ jpc_ppt_t *ppt = &ms->parms.ppt;
+ jpc_dec_tile_t *tile;
+ jpc_ppxstabent_t *pptstabent;
+
+ tile = dec->curtile;
+ if (!tile->pptstab) {
+ if (!(tile->pptstab = jpc_ppxstab_create())) {
+ return -1;
+ }
+ }
+ if (!(pptstabent = jpc_ppxstabent_create())) {
+ return -1;
+ }
+ pptstabent->ind = ppt->ind;
+ pptstabent->data = ppt->data;
+ ppt->data = 0;
+ pptstabent->len = ppt->len;
+ if (jpc_ppxstab_insert(tile->pptstab, pptstabent)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ /* Eliminate compiler warnings about unused variables. */
+ dec = 0;
+ ms = 0;
+
+ return 0;
+}
+
+static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms)
+{
+ /* Eliminate compiler warnings about unused variables. */
+ dec = 0;
+
+ jas_eprintf("warning: ignoring unknown marker segment\n");
+ jpc_ms_dump(ms, stderr);
+ return 0;
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps)
+{
+ jpc_dec_cp_t *cp;
+ jpc_dec_ccp_t *ccp;
+ int compno;
+
+ if (!(cp = jas_malloc(sizeof(jpc_dec_cp_t)))) {
+ return 0;
+ }
+ cp->flags = 0;
+ cp->numcomps = numcomps;
+ cp->prgord = 0;
+ cp->numlyrs = 0;
+ cp->mctid = 0;
+ cp->csty = 0;
+ if (!(cp->ccps = jas_malloc(cp->numcomps * sizeof(jpc_dec_ccp_t)))) {
+ return 0;
+ }
+ if (!(cp->pchglist = jpc_pchglist_create())) {
+ jas_free(cp->ccps);
+ return 0;
+ }
+ for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
+ ++compno, ++ccp) {
+ ccp->flags = 0;
+ ccp->numrlvls = 0;
+ ccp->cblkwidthexpn = 0;
+ ccp->cblkheightexpn = 0;
+ ccp->qmfbid = 0;
+ ccp->numstepsizes = 0;
+ ccp->numguardbits = 0;
+ ccp->roishift = 0;
+ ccp->cblkctx = 0;
+ }
+ return cp;
+}
+
+static jpc_dec_cp_t *jpc_dec_cp_copy(jpc_dec_cp_t *cp)
+{
+ jpc_dec_cp_t *newcp;
+ jpc_dec_ccp_t *newccp;
+ jpc_dec_ccp_t *ccp;
+ int compno;
+
+ if (!(newcp = jpc_dec_cp_create(cp->numcomps))) {
+ return 0;
+ }
+ newcp->flags = cp->flags;
+ newcp->prgord = cp->prgord;
+ newcp->numlyrs = cp->numlyrs;
+ newcp->mctid = cp->mctid;
+ newcp->csty = cp->csty;
+ jpc_pchglist_destroy(newcp->pchglist);
+ newcp->pchglist = 0;
+ if (!(newcp->pchglist = jpc_pchglist_copy(cp->pchglist))) {
+ jas_free(newcp);
+ return 0;
+ }
+ for (compno = 0, newccp = newcp->ccps, ccp = cp->ccps;
+ compno < cp->numcomps;
+ ++compno, ++newccp, ++ccp) {
+ *newccp = *ccp;
+ }
+ return newcp;
+}
+
+static void jpc_dec_cp_resetflags(jpc_dec_cp_t *cp)
+{
+ int compno;
+ jpc_dec_ccp_t *ccp;
+ cp->flags &= (JPC_CSET | JPC_QSET);
+ for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
+ ++compno, ++ccp) {
+ ccp->flags = 0;
+ }
+}
+
+static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp)
+{
+ if (cp->ccps) {
+ jas_free(cp->ccps);
+ }
+ if (cp->pchglist) {
+ jpc_pchglist_destroy(cp->pchglist);
+ }
+ jas_free(cp);
+}
+
+static int jpc_dec_cp_isvalid(jpc_dec_cp_t *cp)
+{
+ uint_fast16_t compcnt;
+ jpc_dec_ccp_t *ccp;
+
+ if (!(cp->flags & JPC_CSET) || !(cp->flags & JPC_QSET)) {
+ return 0;
+ }
+ for (compcnt = cp->numcomps, ccp = cp->ccps; compcnt > 0; --compcnt,
+ ++ccp) {
+ /* Is there enough step sizes for the number of bands? */
+ if ((ccp->qsty != JPC_QCX_SIQNT && JAS_CAST(int, ccp->numstepsizes) < 3 *
+ ccp->numrlvls - 2) || (ccp->qsty == JPC_QCX_SIQNT &&
+ ccp->numstepsizes != 1)) {
+ return 0;
+ }
+ }
+ return 1;
+}
+
+static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls,
+ uint_fast16_t *stepsizes)
+{
+ int bandno;
+ int numbands;
+ uint_fast16_t expn;
+ uint_fast16_t mant;
+ expn = JPC_QCX_GETEXPN(refstepsize);
+ mant = JPC_QCX_GETMANT(refstepsize);
+ numbands = 3 * numrlvls - 2;
+ for (bandno = 0; bandno < numbands; ++bandno) {
+ stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn +
+ (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))));
+ }
+}
+
+static int jpc_dec_cp_prepare(jpc_dec_cp_t *cp)
+{
+ jpc_dec_ccp_t *ccp;
+ int compno;
+ int i;
+ for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
+ ++compno, ++ccp) {
+ if (!(ccp->csty & JPC_COX_PRT)) {
+ for (i = 0; i < JPC_MAXRLVLS; ++i) {
+ ccp->prcwidthexpns[i] = 15;
+ ccp->prcheightexpns[i] = 15;
+ }
+ }
+ if (ccp->qsty == JPC_QCX_SIQNT) {
+ calcstepsizes(ccp->stepsizes[0], ccp->numrlvls, ccp->stepsizes);
+ }
+ }
+ return 0;
+}
+
+static int jpc_dec_cp_setfromcod(jpc_dec_cp_t *cp, jpc_cod_t *cod)
+{
+ jpc_dec_ccp_t *ccp;
+ int compno;
+ cp->flags |= JPC_CSET;
+ cp->prgord = cod->prg;
+ if (cod->mctrans) {
+ cp->mctid = (cod->compparms.qmfbid == JPC_COX_INS) ? (JPC_MCT_ICT) : (JPC_MCT_RCT);
+ } else {
+ cp->mctid = JPC_MCT_NONE;
+ }
+ cp->numlyrs = cod->numlyrs;
+ cp->csty = cod->csty & (JPC_COD_SOP | JPC_COD_EPH);
+ for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
+ ++compno, ++ccp) {
+ jpc_dec_cp_setfromcox(cp, ccp, &cod->compparms, 0);
+ }
+ cp->flags |= JPC_CSET;
+ return 0;
+}
+
+static int jpc_dec_cp_setfromcoc(jpc_dec_cp_t *cp, jpc_coc_t *coc)
+{
+ jpc_dec_cp_setfromcox(cp, &cp->ccps[coc->compno], &coc->compparms, JPC_COC);
+ return 0;
+}
+
+static int jpc_dec_cp_setfromcox(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
+ jpc_coxcp_t *compparms, int flags)
+{
+ int rlvlno;
+
+ /* Eliminate compiler warnings about unused variables. */
+ cp = 0;
+
+ if ((flags & JPC_COC) || !(ccp->flags & JPC_COC)) {
+ ccp->numrlvls = compparms->numdlvls + 1;
+ ccp->cblkwidthexpn = JPC_COX_GETCBLKSIZEEXPN(
+ compparms->cblkwidthval);
+ ccp->cblkheightexpn = JPC_COX_GETCBLKSIZEEXPN(
+ compparms->cblkheightval);
+ ccp->qmfbid = compparms->qmfbid;
+ ccp->cblkctx = compparms->cblksty;
+ ccp->csty = compparms->csty & JPC_COX_PRT;
+ for (rlvlno = 0; rlvlno < compparms->numrlvls; ++rlvlno) {
+ ccp->prcwidthexpns[rlvlno] =
+ compparms->rlvls[rlvlno].parwidthval;
+ ccp->prcheightexpns[rlvlno] =
+ compparms->rlvls[rlvlno].parheightval;
+ }
+ ccp->flags |= flags | JPC_CSET;
+ }
+ return 0;
+}
+
+static int jpc_dec_cp_setfromqcd(jpc_dec_cp_t *cp, jpc_qcd_t *qcd)
+{
+ int compno;
+ jpc_dec_ccp_t *ccp;
+ for (compno = 0, ccp = cp->ccps; compno < cp->numcomps;
+ ++compno, ++ccp) {
+ jpc_dec_cp_setfromqcx(cp, ccp, &qcd->compparms, 0);
+ }
+ cp->flags |= JPC_QSET;
+ return 0;
+}
+
+static int jpc_dec_cp_setfromqcc(jpc_dec_cp_t *cp, jpc_qcc_t *qcc)
+{
+ return jpc_dec_cp_setfromqcx(cp, &cp->ccps[qcc->compno], &qcc->compparms, JPC_QCC);
+}
+
+static int jpc_dec_cp_setfromqcx(jpc_dec_cp_t *cp, jpc_dec_ccp_t *ccp,
+ jpc_qcxcp_t *compparms, int flags)
+{
+ int bandno;
+
+ /* Eliminate compiler warnings about unused variables. */
+ cp = 0;
+
+ if ((flags & JPC_QCC) || !(ccp->flags & JPC_QCC)) {
+ ccp->flags |= flags | JPC_QSET;
+ for (bandno = 0; bandno < compparms->numstepsizes; ++bandno) {
+ ccp->stepsizes[bandno] = compparms->stepsizes[bandno];
+ }
+ ccp->numstepsizes = compparms->numstepsizes;
+ ccp->numguardbits = compparms->numguard;
+ ccp->qsty = compparms->qntsty;
+ }
+ return 0;
+}
+
+static int jpc_dec_cp_setfromrgn(jpc_dec_cp_t *cp, jpc_rgn_t *rgn)
+{
+ jpc_dec_ccp_t *ccp;
+ ccp = &cp->ccps[rgn->compno];
+ ccp->roishift = rgn->roishift;
+ return 0;
+}
+
+static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc)
+{
+ int pchgno;
+ jpc_pchg_t *pchg;
+ for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) {
+ if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) {
+ return -1;
+ }
+ if (jpc_pchglist_insert(pi->pchglist, -1, pchg)) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset)
+{
+ int pchgno;
+ jpc_pchg_t *pchg;
+ if (reset) {
+ while (jpc_pchglist_numpchgs(cp->pchglist) > 0) {
+ pchg = jpc_pchglist_remove(cp->pchglist, 0);
+ jpc_pchg_destroy(pchg);
+ }
+ }
+ for (pchgno = 0; pchgno < poc->numpchgs; ++pchgno) {
+ if (!(pchg = jpc_pchg_copy(&poc->pchgs[pchgno]))) {
+ return -1;
+ }
+ if (jpc_pchglist_insert(cp->pchglist, -1, pchg)) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits)
+{
+ jpc_fix_t absstepsize;
+ int n;
+
+ absstepsize = jpc_inttofix(1);
+ n = JPC_FIX_FRACBITS - 11;
+ absstepsize |= (n >= 0) ? (JPC_QCX_GETMANT(stepsize) << n) :
+ (JPC_QCX_GETMANT(stepsize) >> (-n));
+ n = numbits - JPC_QCX_GETEXPN(stepsize);
+ absstepsize = (n >= 0) ? (absstepsize << n) : (absstepsize >> (-n));
+ return absstepsize;
+}
+
+static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize)
+{
+ int i;
+ int j;
+ int t;
+
+ assert(absstepsize >= 0);
+ if (absstepsize == jpc_inttofix(1)) {
+ return;
+ }
+
+ for (i = 0; i < jas_matrix_numrows(x); ++i) {
+ for (j = 0; j < jas_matrix_numcols(x); ++j) {
+ t = jas_matrix_get(x, i, j);
+ if (t) {
+ t = jpc_fix_mul(t, absstepsize);
+ } else {
+ t = 0;
+ }
+ jas_matrix_set(x, i, j, t);
+ }
+ }
+
+}
+
+static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps)
+{
+ int i;
+ int j;
+ int thresh;
+ jpc_fix_t val;
+ jpc_fix_t mag;
+ bool warn;
+ uint_fast32_t mask;
+
+ if (roishift == 0 && bgshift == 0) {
+ return;
+ }
+ thresh = 1 << roishift;
+
+ warn = false;
+ for (i = 0; i < jas_matrix_numrows(x); ++i) {
+ for (j = 0; j < jas_matrix_numcols(x); ++j) {
+ val = jas_matrix_get(x, i, j);
+ mag = JAS_ABS(val);
+ if (mag >= thresh) {
+ /* We are dealing with ROI data. */
+ mag >>= roishift;
+ val = (val < 0) ? (-mag) : mag;
+ jas_matrix_set(x, i, j, val);
+ } else {
+ /* We are dealing with non-ROI (i.e., background) data. */
+ mag <<= bgshift;
+ mask = (1 << numbps) - 1;
+ /* Perform a basic sanity check on the sample value. */
+ /* Some implementations write garbage in the unused
+ most-significant bit planes introduced by ROI shifting.
+ Here we ensure that any such bits are masked off. */
+ if (mag & (~mask)) {
+ if (!warn) {
+ jas_eprintf("warning: possibly corrupt code stream\n");
+ warn = true;
+ }
+ mag &= mask;
+ }
+ val = (val < 0) ? (-mag) : mag;
+ jas_matrix_set(x, i, j, val);
+ }
+ }
+ }
+}
+
+static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in)
+{
+ jpc_dec_t *dec;
+
+ if (!(dec = jas_malloc(sizeof(jpc_dec_t)))) {
+ return 0;
+ }
+
+ dec->image = 0;
+ dec->xstart = 0;
+ dec->ystart = 0;
+ dec->xend = 0;
+ dec->yend = 0;
+ dec->tilewidth = 0;
+ dec->tileheight = 0;
+ dec->tilexoff = 0;
+ dec->tileyoff = 0;
+ dec->numhtiles = 0;
+ dec->numvtiles = 0;
+ dec->numtiles = 0;
+ dec->tiles = 0;
+ dec->curtile = 0;
+ dec->numcomps = 0;
+ dec->in = in;
+ dec->cp = 0;
+ dec->maxlyrs = impopts->maxlyrs;
+ dec->maxpkts = impopts->maxpkts;
+dec->numpkts = 0;
+ dec->ppmseqno = 0;
+ dec->state = 0;
+ dec->cmpts = 0;
+ dec->pkthdrstreams = 0;
+ dec->ppmstab = 0;
+ dec->curtileendoff = 0;
+
+ return dec;
+}
+
+static void jpc_dec_destroy(jpc_dec_t *dec)
+{
+ if (dec->cstate) {
+ jpc_cstate_destroy(dec->cstate);
+ }
+ if (dec->pkthdrstreams) {
+ jpc_streamlist_destroy(dec->pkthdrstreams);
+ }
+ if (dec->image) {
+ jas_image_destroy(dec->image);
+ }
+
+ if (dec->cp) {
+ jpc_dec_cp_destroy(dec->cp);
+ }
+
+ if (dec->cmpts) {
+ jas_free(dec->cmpts);
+ }
+
+ if (dec->tiles) {
+ jas_free(dec->tiles);
+ }
+
+ jas_free(dec);
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+void jpc_seglist_insert(jpc_dec_seglist_t *list, jpc_dec_seg_t *ins, jpc_dec_seg_t *node)
+{
+ jpc_dec_seg_t *prev;
+ jpc_dec_seg_t *next;
+
+ prev = ins;
+ node->prev = prev;
+ next = prev ? (prev->next) : 0;
+ node->prev = prev;
+ node->next = next;
+ if (prev) {
+ prev->next = node;
+ } else {
+ list->head = node;
+ }
+ if (next) {
+ next->prev = node;
+ } else {
+ list->tail = node;
+ }
+}
+
+void jpc_seglist_remove(jpc_dec_seglist_t *list, jpc_dec_seg_t *seg)
+{
+ jpc_dec_seg_t *prev;
+ jpc_dec_seg_t *next;
+
+ prev = seg->prev;
+ next = seg->next;
+ if (prev) {
+ prev->next = next;
+ } else {
+ list->head = next;
+ }
+ if (next) {
+ next->prev = prev;
+ } else {
+ list->tail = prev;
+ }
+ seg->prev = 0;
+ seg->next = 0;
+}
+
+jpc_dec_seg_t *jpc_seg_alloc()
+{
+ jpc_dec_seg_t *seg;
+
+ if (!(seg = jas_malloc(sizeof(jpc_dec_seg_t)))) {
+ return 0;
+ }
+ seg->prev = 0;
+ seg->next = 0;
+ seg->passno = -1;
+ seg->numpasses = 0;
+ seg->maxpasses = 0;
+ seg->type = JPC_SEG_INVALID;
+ seg->stream = 0;
+ seg->cnt = 0;
+ seg->complete = 0;
+ seg->lyrno = -1;
+ return seg;
+}
+
+void jpc_seg_destroy(jpc_dec_seg_t *seg)
+{
+ if (seg->stream) {
+ jas_stream_close(seg->stream);
+ }
+ jas_free(seg);
+}
+
+static int jpc_dec_dump(jpc_dec_t *dec, FILE *out)
+{
+ jpc_dec_tile_t *tile;
+ int tileno;
+ jpc_dec_tcomp_t *tcomp;
+ int compno;
+ jpc_dec_rlvl_t *rlvl;
+ int rlvlno;
+ jpc_dec_band_t *band;
+ int bandno;
+ jpc_dec_prc_t *prc;
+ int prcno;
+ jpc_dec_cblk_t *cblk;
+ int cblkno;
+
+ for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles;
+ ++tileno, ++tile) {
+ for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
+ ++compno, ++tcomp) {
+ for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno <
+ tcomp->numrlvls; ++rlvlno, ++rlvl) {
+fprintf(out, "RESOLUTION LEVEL %d\n", rlvlno);
+fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n",
+ rlvl->xstart, rlvl->ystart, rlvl->xend, rlvl->yend, rlvl->xend -
+ rlvl->xstart, rlvl->yend - rlvl->ystart);
+ for (bandno = 0, band = rlvl->bands;
+ bandno < rlvl->numbands; ++bandno, ++band) {
+fprintf(out, "BAND %d\n", bandno);
+fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n",
+ jas_seq2d_xstart(band->data), jas_seq2d_ystart(band->data), jas_seq2d_xend(band->data),
+ jas_seq2d_yend(band->data), jas_seq2d_xend(band->data) - jas_seq2d_xstart(band->data),
+ jas_seq2d_yend(band->data) - jas_seq2d_ystart(band->data));
+ for (prcno = 0, prc = band->prcs;
+ prcno < rlvl->numprcs; ++prcno,
+ ++prc) {
+fprintf(out, "CODE BLOCK GROUP %d\n", prcno);
+fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n",
+ prc->xstart, prc->ystart, prc->xend, prc->yend, prc->xend -
+ prc->xstart, prc->yend - prc->ystart);
+ for (cblkno = 0, cblk =
+ prc->cblks; cblkno <
+ prc->numcblks; ++cblkno,
+ ++cblk) {
+fprintf(out, "CODE BLOCK %d\n", cblkno);
+fprintf(out, "xs =%d, ys = %d, xe = %d, ye = %d, w = %d, h = %d\n",
+ jas_seq2d_xstart(cblk->data), jas_seq2d_ystart(cblk->data), jas_seq2d_xend(cblk->data),
+ jas_seq2d_yend(cblk->data), jas_seq2d_xend(cblk->data) - jas_seq2d_xstart(cblk->data),
+ jas_seq2d_yend(cblk->data) - jas_seq2d_ystart(cblk->data));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return 0;
+}
+
+jpc_streamlist_t *jpc_streamlist_create()
+{
+ jpc_streamlist_t *streamlist;
+ int i;
+
+ if (!(streamlist = jas_malloc(sizeof(jpc_streamlist_t)))) {
+ return 0;
+ }
+ streamlist->numstreams = 0;
+ streamlist->maxstreams = 100;
+ if (!(streamlist->streams = jas_malloc(streamlist->maxstreams *
+ sizeof(jas_stream_t *)))) {
+ jas_free(streamlist);
+ return 0;
+ }
+ for (i = 0; i < streamlist->maxstreams; ++i) {
+ streamlist->streams[i] = 0;
+ }
+ return streamlist;
+}
+
+int jpc_streamlist_insert(jpc_streamlist_t *streamlist, int streamno,
+ jas_stream_t *stream)
+{
+ jas_stream_t **newstreams;
+ int newmaxstreams;
+ int i;
+ /* Grow the array of streams if necessary. */
+ if (streamlist->numstreams >= streamlist->maxstreams) {
+ newmaxstreams = streamlist->maxstreams + 1024;
+ if (!(newstreams = jas_realloc(streamlist->streams,
+ (newmaxstreams + 1024) * sizeof(jas_stream_t *)))) {
+ return -1;
+ }
+ for (i = streamlist->numstreams; i < streamlist->maxstreams; ++i) {
+ streamlist->streams[i] = 0;
+ }
+ streamlist->maxstreams = newmaxstreams;
+ streamlist->streams = newstreams;
+ }
+ if (streamno != streamlist->numstreams) {
+ /* Can only handle insertion at start of list. */
+ return -1;
+ }
+ streamlist->streams[streamno] = stream;
+ ++streamlist->numstreams;
+ return 0;
+}
+
+jas_stream_t *jpc_streamlist_remove(jpc_streamlist_t *streamlist, int streamno)
+{
+ jas_stream_t *stream;
+ int i;
+ if (streamno >= streamlist->numstreams) {
+ abort();
+ }
+ stream = streamlist->streams[streamno];
+ for (i = streamno + 1; i < streamlist->numstreams; ++i) {
+ streamlist->streams[i - 1] = streamlist->streams[i];
+ }
+ --streamlist->numstreams;
+ return stream;
+}
+
+void jpc_streamlist_destroy(jpc_streamlist_t *streamlist)
+{
+ int streamno;
+ if (streamlist->streams) {
+ for (streamno = 0; streamno < streamlist->numstreams;
+ ++streamno) {
+ jas_stream_close(streamlist->streams[streamno]);
+ }
+ jas_free(streamlist->streams);
+ }
+ jas_free(streamlist);
+}
+
+jas_stream_t *jpc_streamlist_get(jpc_streamlist_t *streamlist, int streamno)
+{
+ assert(streamno < streamlist->numstreams);
+ return streamlist->streams[streamno];
+}
+
+int jpc_streamlist_numstreams(jpc_streamlist_t *streamlist)
+{
+ return streamlist->numstreams;
+}
+
+jpc_ppxstab_t *jpc_ppxstab_create()
+{
+ jpc_ppxstab_t *tab;
+
+ if (!(tab = jas_malloc(sizeof(jpc_ppxstab_t)))) {
+ return 0;
+ }
+ tab->numents = 0;
+ tab->maxents = 0;
+ tab->ents = 0;
+ return tab;
+}
+
+void jpc_ppxstab_destroy(jpc_ppxstab_t *tab)
+{
+ int i;
+ for (i = 0; i < tab->numents; ++i) {
+ jpc_ppxstabent_destroy(tab->ents[i]);
+ }
+ if (tab->ents) {
+ jas_free(tab->ents);
+ }
+ jas_free(tab);
+}
+
+int jpc_ppxstab_grow(jpc_ppxstab_t *tab, int maxents)
+{
+ jpc_ppxstabent_t **newents;
+ if (tab->maxents < maxents) {
+ newents = (tab->ents) ? jas_realloc(tab->ents, maxents *
+ sizeof(jpc_ppxstabent_t *)) : jas_malloc(maxents * sizeof(jpc_ppxstabent_t *));
+ if (!newents) {
+ return -1;
+ }
+ tab->ents = newents;
+ tab->maxents = maxents;
+ }
+ return 0;
+}
+
+int jpc_ppxstab_insert(jpc_ppxstab_t *tab, jpc_ppxstabent_t *ent)
+{
+ int inspt;
+ int i;
+
+ for (i = 0; i < tab->numents; ++i) {
+ if (tab->ents[i]->ind > ent->ind) {
+ break;
+ }
+ }
+ inspt = i;
+
+ if (tab->numents >= tab->maxents) {
+ if (jpc_ppxstab_grow(tab, tab->maxents + 128)) {
+ return -1;
+ }
+ }
+
+ for (i = tab->numents; i > inspt; --i) {
+ tab->ents[i] = tab->ents[i - 1];
+ }
+ tab->ents[i] = ent;
+ ++tab->numents;
+
+ return 0;
+}
+
+jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab)
+{
+ jpc_streamlist_t *streams;
+ uchar *dataptr;
+ uint_fast32_t datacnt;
+ uint_fast32_t tpcnt;
+ jpc_ppxstabent_t *ent;
+ int entno;
+ jas_stream_t *stream;
+ int n;
+
+ if (!(streams = jpc_streamlist_create())) {
+ goto error;
+ }
+
+ if (!tab->numents) {
+ return streams;
+ }
+
+ entno = 0;
+ ent = tab->ents[entno];
+ dataptr = ent->data;
+ datacnt = ent->len;
+ for (;;) {
+
+ /* Get the length of the packet header data for the current
+ tile-part. */
+ if (datacnt < 4) {
+ goto error;
+ }
+ if (!(stream = jas_stream_memopen(0, 0))) {
+ goto error;
+ }
+ if (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams),
+ stream)) {
+ goto error;
+ }
+ tpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8)
+ | dataptr[3];
+ datacnt -= 4;
+ dataptr += 4;
+
+ /* Get the packet header data for the current tile-part. */
+ while (tpcnt) {
+ if (!datacnt) {
+ if (++entno >= tab->numents) {
+ goto error;
+ }
+ ent = tab->ents[entno];
+ dataptr = ent->data;
+ datacnt = ent->len;
+ }
+ n = JAS_MIN(tpcnt, datacnt);
+ if (jas_stream_write(stream, dataptr, n) != n) {
+ goto error;
+ }
+ tpcnt -= n;
+ dataptr += n;
+ datacnt -= n;
+ }
+ jas_stream_rewind(stream);
+ if (!datacnt) {
+ if (++entno >= tab->numents) {
+ break;
+ }
+ ent = tab->ents[entno];
+ dataptr = ent->data;
+ datacnt = ent->len;
+ }
+ }
+
+ return streams;
+
+error:
+ jpc_streamlist_destroy(streams);
+ return 0;
+}
+
+int jpc_pptstabwrite(jas_stream_t *out, jpc_ppxstab_t *tab)
+{
+ int i;
+ jpc_ppxstabent_t *ent;
+ for (i = 0; i < tab->numents; ++i) {
+ ent = tab->ents[i];
+ if (jas_stream_write(out, ent->data, ent->len) != JAS_CAST(int, ent->len)) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+jpc_ppxstabent_t *jpc_ppxstabent_create()
+{
+ jpc_ppxstabent_t *ent;
+ if (!(ent = jas_malloc(sizeof(jpc_ppxstabent_t)))) {
+ return 0;
+ }
+ ent->data = 0;
+ ent->len = 0;
+ ent->ind = 0;
+ return ent;
+}
+
+void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent)
+{
+ if (ent->data) {
+ jas_free(ent->data);
+ }
+ jas_free(ent);
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_dec.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_dec.h
new file mode 100644
index 0000000..2af98ca
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_dec.h
@@ -0,0 +1,696 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JPEG-2000 Decoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_DEC_H
+#define JPC_DEC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_stream.h"
+
+#include "jpc_tsfb.h"
+#include "jpc_bs.h"
+#include "jpc_tagtree.h"
+#include "jpc_cs.h"
+#include "jpc_cod.h"
+#include "jpc_mqdec.h"
+#include "jpc_t2cod.h"
+
+/******************************************************************************\
+* Below are some ugly warts necessary to support packed packet headers.
+\******************************************************************************/
+
+/* PPM/PPT marker segment table entry. */
+
+typedef struct {
+
+ /* The index for this entry. */
+ uint_fast16_t ind;
+
+ /* The data length. */
+ uint_fast32_t len;
+
+ /* The data. */
+ uchar *data;
+
+} jpc_ppxstabent_t;
+
+/* PPM/PPT marker segment table. */
+
+typedef struct {
+
+ /* The number of entries. */
+ int numents;
+
+ /* The maximum number of entries (i.e., the allocated size of the array
+ below). */
+ int maxents;
+
+ /* The table entries. */
+ jpc_ppxstabent_t **ents;
+
+} jpc_ppxstab_t;
+
+/* Stream list class. */
+
+typedef struct {
+
+ /* The number of streams in this list. */
+ int numstreams;
+
+ /* The maximum number of streams that can be accomodated without
+ growing the streams array. */
+ int maxstreams;
+
+ /* The streams. */
+ jas_stream_t **streams;
+
+} jpc_streamlist_t;
+
+/******************************************************************************\
+* Coding parameters class.
+\******************************************************************************/
+
+/* Per-component coding parameters. */
+
+typedef struct {
+
+ /* How were various coding parameters set? */
+ int flags;
+
+ /* Per-component coding style parameters (e.g., explicit precinct sizes) */
+ uint_fast8_t csty;
+
+ /* The number of resolution levels. */
+ uint_fast8_t numrlvls;
+
+ /* The code block width exponent. */
+ uint_fast8_t cblkwidthexpn;
+
+ /* The code block height exponent. */
+ uint_fast8_t cblkheightexpn;
+
+ /* The QMFB ID. */
+ uint_fast8_t qmfbid;
+
+ /* The quantization style. */
+ uint_fast8_t qsty;
+
+ /* The number of quantizer step sizes. */
+ uint_fast16_t numstepsizes;
+
+ /* The step sizes. */
+ uint_fast16_t stepsizes[3 * JPC_MAXRLVLS + 1];
+
+ /* The number of guard bits. */
+ uint_fast8_t numguardbits;
+
+ /* The ROI shift value. */
+ uint_fast8_t roishift;
+
+ /* The code block parameters. */
+ uint_fast8_t cblkctx;
+
+ /* The precinct width exponents. */
+ uint_fast8_t prcwidthexpns[JPC_MAXRLVLS];
+
+ /* The precinct height exponents. */
+ uint_fast8_t prcheightexpns[JPC_MAXRLVLS];
+
+} jpc_dec_ccp_t;
+
+/* Coding paramters. */
+
+typedef struct {
+
+ /* How were these coding parameters set? */
+ int flags;
+
+ /* Progression change list. */
+ jpc_pchglist_t *pchglist;
+
+ /* Progression order. */
+ uint_fast8_t prgord;
+
+ /* The number of layers. */
+ uint_fast16_t numlyrs;
+
+ /* The MCT ID. */
+ uint_fast8_t mctid;
+
+ /* The coding style parameters (e.g., SOP, EPH). */
+ uint_fast8_t csty;
+
+ /* The number of components. */
+ int numcomps;
+
+ /* The per-component coding parameters. */
+ jpc_dec_ccp_t *ccps;
+
+} jpc_dec_cp_t;
+
+/******************************************************************************\
+* Decoder class.
+\******************************************************************************/
+
+/* Decoder per-segment state information. */
+
+typedef struct jpc_dec_seg_s {
+
+ /* The next segment in the list. */
+ struct jpc_dec_seg_s *next;
+
+ /* The previous segment in the list. */
+ struct jpc_dec_seg_s *prev;
+
+ /* The starting pass number for this segment. */
+ int passno;
+
+ /* The number of passes in this segment. */
+ int numpasses;
+
+ /* The maximum number of passes in this segment. */
+ int maxpasses;
+
+ /* 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;
+
+ /* 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;
+
+ /* 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;
+
+/* Decoder segment list. */
+
+typedef struct {
+
+ /* The first entry in the list. */
+ jpc_dec_seg_t *head;
+
+ /* The last entry in the list. */
+ jpc_dec_seg_t *tail;
+
+} jpc_dec_seglist_t;
+
+/* Decoder per-code-block state information. */
+
+typedef struct {
+
+ /* The number of passes. */
+ int numpasses;
+
+ /* A list of segments that still need to be decoded. */
+ jpc_dec_seglist_t segs;
+
+ /* The first incomplete/partial segment. */
+ jpc_dec_seg_t *curseg;
+
+ /* The number of leading insignificant bit planes for this code block. */
+ int numimsbs;
+
+ /* 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 MQ decoder. */
+ jpc_mqdec_t *mqdec;
+
+ /* The raw bit stream decoder. */
+ jpc_bitstream_t *nulldec;
+
+ /* 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;
+
+} jpc_dec_cblk_t;
+
+/* Decoder per-code-block-group state information. */
+
+typedef struct {
+
+ /* The x-coordinate of the top-left corner of the precinct. */
+ uint_fast32_t xstart;
+
+ /* The y-coordinate of the top-left corner of the precinct. */
+ uint_fast32_t ystart;
+
+ /* The x-coordinate of the bottom-right corner of the precinct
+ (plus one). */
+ uint_fast32_t xend;
+
+ /* The y-coordinate of the bottom-right corner of the precinct
+ (plus one). */
+ uint_fast32_t yend;
+
+ /* The number of code blocks spanning this precinct in the horizontal
+ direction. */
+ int numhcblks;
+
+ /* 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 per code block information. */
+ jpc_dec_cblk_t *cblks;
+
+ /* The inclusion tag tree. */
+ jpc_tagtree_t *incltagtree;
+
+ /* The insignificant MSBs tag tree. */
+ jpc_tagtree_t *numimsbstagtree;
+
+} jpc_dec_prc_t;
+
+/* Decoder per-band state information. */
+
+typedef struct {
+
+ /* The per-code-block-group state information. */
+ jpc_dec_prc_t *prcs;
+
+ /* The sample data associated with this band. */
+ jas_matrix_t *data;
+
+ /* The orientation of this band (i.e., LL, LH, HL, or HH). */
+ int orient;
+
+ /* The encoded quantizer step size. */
+ int stepsize;
+
+ /* The absolute quantizer step size. */
+ jpc_fix_t absstepsize;
+
+ /* The number of bit planes for this band. */
+ int numbps;
+
+ /* The analysis gain associated with this band. */
+ int analgain;
+
+ /* The ROI shift value for this band. */
+ int roishift;
+
+} jpc_dec_band_t;
+
+/* Decoder per-resolution-level state information. */
+
+typedef struct {
+
+ /* The number of bands associated with this resolution level. */
+ int numbands;
+
+ /* The per-band information. */
+ jpc_dec_band_t *bands;
+
+ /* The x-coordinate of the top-left corner of the tile-component
+ at this resolution. */
+ uint_fast32_t xstart;
+
+ /* The y-coordinate of the top-left corner of the tile-component
+ at this resolution. */
+ uint_fast32_t ystart;
+
+ /* The x-coordinate of the bottom-right corner of the tile-component
+ at this resolution (plus one). */
+ uint_fast32_t xend;
+
+ /* The y-coordinate of the bottom-right corner of the tile-component
+ at this resolution (plus one). */
+ uint_fast32_t yend;
+
+ /* The exponent value for the nominal precinct width measured
+ relative to the associated LL band. */
+ int prcwidthexpn;
+
+ /* 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 vertical direction. */
+ int numvprcs;
+
+ /* 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 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 height. */
+ uint_fast16_t cblkheightexpn;
+
+} jpc_dec_rlvl_t;
+
+/* Decoder per-tile-component state information. */
+
+typedef struct {
+
+ /* The x-coordinate of the top-left corner of the tile-component
+ in the coordinate system of the tile-component. */
+ uint_fast32_t xstart;
+
+ /* The y-coordinate of the top-left corner of the tile-component
+ in the coordinate system of the tile-component. */
+ uint_fast32_t ystart;
+
+ /* The x-coordinate of the bottom-right corner of the tile-component
+ in the coordinate system of the tile-component (plus one). */
+ uint_fast32_t xend;
+
+ /* The y-coordinate of the bottom-right corner of the tile-component
+ in the coordinate system of the tile-component (plus one). */
+ uint_fast32_t yend;
+
+ /* The component data for the current tile. */
+ jas_matrix_t *data;
+
+ /* The number of resolution levels. */
+ int numrlvls;
+
+ /* The per resolution level information. */
+ jpc_dec_rlvl_t *rlvls;
+
+ /* The TSFB. */
+ jpc_tsfb_t *tsfb;
+
+} jpc_dec_tcomp_t;
+
+/*
+ * Tile states.
+ */
+
+#define JPC_TILE_INIT 0
+#define JPC_TILE_ACTIVE 1
+#define JPC_TILE_ACTIVELAST 2
+#define JPC_TILE_DONE 3
+
+/* Decoder per-tile state information. */
+
+typedef struct {
+
+ /* The processing state for this tile. */
+ int state;
+
+ /* The x-coordinate of the top-left corner of the tile on the reference
+ grid. */
+ uint_fast32_t xstart;
+
+ /* The y-coordinate of the top-left corner of the tile on the reference
+ grid. */
+ uint_fast32_t ystart;
+
+ /* The x-coordinate of the bottom-right corner of the tile on the
+ reference grid (plus one). */
+ uint_fast32_t xend;
+
+ /* The y-coordinate of the bottom-right corner of the tile on the
+ reference grid (plus one). */
+ uint_fast32_t yend;
+
+ /* The packed packet header data for this tile. */
+ jpc_ppxstab_t *pptstab;
+
+ /* A stream containing the packed packet header data for this tile. */
+ jas_stream_t *pkthdrstream;
+
+ /* The current position within the packed packet header stream. */
+ long pkthdrstreampos;
+
+ /* The coding parameters for this tile. */
+ jpc_dec_cp_t *cp;
+
+ /* The per tile-component information. */
+ jpc_dec_tcomp_t *tcomps;
+
+ /* The next expected tile-part number. */
+ int partno;
+
+ /* The number of tile-parts. */
+ int numparts;
+
+ /* The coding mode. */
+ int realmode;
+
+ /* The packet iterator for this tile. */
+ jpc_pi_t *pi;
+
+} jpc_dec_tile_t;
+
+/* Decoder per-component state information. */
+
+typedef struct {
+
+ /* The horizontal sampling period. */
+ uint_fast32_t hstep;
+
+ /* The vertical sampling period. */
+ uint_fast32_t vstep;
+
+ /* The number of samples in the horizontal direction. */
+ uint_fast32_t width;
+
+ /* The number of samples in the vertical direction. */
+ uint_fast32_t height;
+
+ /* The precision of the sample data. */
+ uint_fast16_t prec;
+
+ /* The signedness of the sample data. */
+ bool sgnd;
+
+ /* The sample alignment horizontal offset. */
+ uint_fast32_t hsubstep;
+
+ /* The sample alignment vertical offset. */
+ uint_fast32_t vsubstep;
+
+} jpc_dec_cmpt_t;
+
+/* Decoder state information. */
+
+typedef struct {
+
+ /* The decoded image. */
+ jas_image_t *image;
+
+ /* The x-coordinate of the top-left corner of the image area on
+ the reference grid. */
+ uint_fast32_t xstart;
+
+ /* The y-coordinate of the top-left corner of the image area on
+ the reference grid. */
+ uint_fast32_t ystart;
+
+ /* The x-coordinate of the bottom-right corner of the image area on
+ the reference grid (plus one). */
+ uint_fast32_t xend;
+
+ /* The y-coordinate of the bottom-right corner of the image area on
+ the reference grid (plus one). */
+ uint_fast32_t yend;
+
+ /* The nominal tile width in units of the image reference grid. */
+ uint_fast32_t tilewidth;
+
+ /* The nominal tile height in units of the image reference grid. */
+ uint_fast32_t tileheight;
+
+ /* The horizontal offset from the origin of the reference grid to the
+ left side of the first tile. */
+ uint_fast32_t tilexoff;
+
+ /* The vertical offset from the origin of the reference grid to the
+ top side of the first tile. */
+ uint_fast32_t tileyoff;
+
+ /* The number of tiles spanning the image area in the vertical
+ direction. */
+ int numhtiles;
+
+ /* The number of tiles spanning the image area in the horizontal
+ direction. */
+ int numvtiles;
+
+ /* The total number of tiles. */
+ int numtiles;
+
+ /* The per-tile information. */
+ jpc_dec_tile_t *tiles;
+
+ /* The tile currently being processed. */
+ jpc_dec_tile_t *curtile;
+
+ /* The number of components. */
+ int numcomps;
+
+ /* The stream containing the input JPEG-2000 code stream data. */
+ jas_stream_t *in;
+
+ /* The default coding parameters for all tiles. */
+ jpc_dec_cp_t *cp;
+
+ /* The maximum number of layers that may be decoded. */
+ int maxlyrs;
+
+ /* The maximum number of packets that may be decoded. */
+ int maxpkts;
+
+ /* The number of packets decoded so far in the processing of the entire
+ code stream. */
+ int numpkts;
+
+ /* The next expected PPM marker segment sequence number. */
+ int ppmseqno;
+
+ /* The current state for code stream processing. */
+ int state;
+
+ /* The per-component information. */
+ jpc_dec_cmpt_t *cmpts;
+
+ /* The information from PPM marker segments. */
+ jpc_ppxstab_t *ppmstab;
+
+ /* A list of streams containing packet header data from PPM marker
+ segments. */
+ jpc_streamlist_t *pkthdrstreams;
+
+ /* The expected ending offset for a tile-part. */
+ long curtileendoff;
+
+ /* This is required by the tier-2 decoder. */
+ jpc_cstate_t *cstate;
+
+} jpc_dec_t;
+
+/* Decoder options. */
+
+typedef struct {
+
+ /* The debug level for the decoder. */
+ int debug;
+
+ /* The maximum number of layers to decode. */
+ int maxlyrs;
+
+ /* The maximum number of packets to decode. */
+ int maxpkts;
+
+} jpc_dec_importopts_t;
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Create a decoder segment object. */
+jpc_dec_seg_t *jpc_seg_alloc(void);
+
+/* Destroy a decoder segment object. */
+void jpc_seg_destroy(jpc_dec_seg_t *seg);
+
+/* Remove a segment from a segment list. */
+void jpc_seglist_remove(jpc_dec_seglist_t *list, jpc_dec_seg_t *node);
+
+/* Insert a segment into a segment list. */
+void jpc_seglist_insert(jpc_dec_seglist_t *list, jpc_dec_seg_t *ins,
+ jpc_dec_seg_t *node);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_enc.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_enc.c
new file mode 100644
index 0000000..590d537
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_enc.c
@@ -0,0 +1,2620 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <math.h>
+#include <float.h>
+
+#include "jasper/jas_types.h"
+#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"
+#include "jasper/jas_debug.h"
+
+#include "jpc_flt.h"
+#include "jpc_fix.h"
+#include "jpc_tagtree.h"
+#include "jpc_enc.h"
+#include "jpc_cs.h"
+#include "jpc_mct.h"
+#include "jpc_tsfb.h"
+#include "jpc_qmfb.h"
+#include "jpc_t1enc.h"
+#include "jpc_t2enc.h"
+#include "jpc_cod.h"
+#include "jpc_math.h"
+#include "jpc_util.h"
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+#define JPC_POW2(n) \
+ (1 << (n))
+
+#define JPC_FLOORTOMULTPOW2(x, n) \
+ (((n) > 0) ? ((x) & (~((1 << n) - 1))) : (x))
+/* Round to the nearest multiple of the specified power of two in the
+ direction of negative infinity. */
+
+#define JPC_CEILTOMULTPOW2(x, n) \
+ (((n) > 0) ? JPC_FLOORTOMULTPOW2(((x) + (1 << (n)) - 1), n) : (x))
+/* Round to the nearest multiple of the specified power of two in the
+ direction of positive infinity. */
+
+#define JPC_POW2(n) \
+ (1 << (n))
+
+jpc_enc_tile_t *jpc_enc_tile_create(jpc_enc_cp_t *cp, jas_image_t *image, int tileno);
+void jpc_enc_tile_destroy(jpc_enc_tile_t *tile);
+
+static jpc_enc_tcmpt_t *tcmpt_create(jpc_enc_tcmpt_t *tcmpt, jpc_enc_cp_t *cp,
+ jas_image_t *image, jpc_enc_tile_t *tile);
+static void tcmpt_destroy(jpc_enc_tcmpt_t *tcmpt);
+static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp,
+ jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos);
+static void rlvl_destroy(jpc_enc_rlvl_t *rlvl);
+static jpc_enc_band_t *band_create(jpc_enc_band_t *band, jpc_enc_cp_t *cp,
+ jpc_enc_rlvl_t *rlvl, jpc_tsfb_band_t *bandinfos);
+static void band_destroy(jpc_enc_band_t *bands);
+static jpc_enc_prc_t *prc_create(jpc_enc_prc_t *prc, jpc_enc_cp_t *cp,
+ jpc_enc_band_t *band);
+static void prc_destroy(jpc_enc_prc_t *prcs);
+static jpc_enc_cblk_t *cblk_create(jpc_enc_cblk_t *cblk, jpc_enc_cp_t *cp,
+ jpc_enc_prc_t *prc);
+static void cblk_destroy(jpc_enc_cblk_t *cblks);
+int ratestrtosize(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);
+
+/******************************************************************************\
+* Local prototypes.
+\******************************************************************************/
+
+int dump_passes(jpc_enc_pass_t *passes, int numpasses, jpc_enc_cblk_t *cblk);
+void calcrdslopes(jpc_enc_cblk_t *cblk);
+void dump_layeringinfo(jpc_enc_t *enc);
+/*static int jpc_calcssexp(jpc_fix_t stepsize);
+static int jpc_calcssmant(jpc_fix_t stepsize);*/
+void jpc_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 rateallocate(jpc_enc_t *enc, int numlyrs, uint_fast32_t *cumlens);
+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);
+static uint_fast32_t jpc_abstorelstepsize(jpc_fix_t absdelta, int scaleexpn);
+
+static uint_fast32_t jpc_abstorelstepsize(jpc_fix_t absdelta, int scaleexpn)
+{
+ int p;
+ uint_fast32_t mant;
+ uint_fast32_t expn;
+ int n;
+
+ if (absdelta < 0) {
+ abort();
+ }
+
+ p = jpc_firstone(absdelta) - JPC_FIX_FRACBITS;
+ n = 11 - jpc_firstone(absdelta);
+ mant = ((n < 0) ? (absdelta >> (-n)) : (absdelta << n)) & 0x7ff;
+ expn = scaleexpn - p;
+ if (scaleexpn < p) {
+ abort();
+ }
+ return JPC_QCX_EXPN(expn) | JPC_QCX_MANT(mant);
+}
+
+typedef enum {
+ OPT_DEBUG,
+ OPT_IMGAREAOFFX,
+ OPT_IMGAREAOFFY,
+ OPT_TILEGRDOFFX,
+ OPT_TILEGRDOFFY,
+ OPT_TILEWIDTH,
+ OPT_TILEHEIGHT,
+ OPT_PRCWIDTH,
+ OPT_PRCHEIGHT,
+ OPT_CBLKWIDTH,
+ OPT_CBLKHEIGHT,
+ OPT_MODE,
+ OPT_PRG,
+ OPT_NOMCT,
+ OPT_MAXRLVLS,
+ OPT_SOP,
+ OPT_EPH,
+ OPT_LAZY,
+ OPT_TERMALL,
+ OPT_SEGSYM,
+ OPT_VCAUSAL,
+ OPT_RESET,
+ OPT_PTERM,
+ OPT_NUMGBITS,
+ OPT_RATE,
+ OPT_ILYRRATES,
+ OPT_JP2OVERHEAD
+} optid_t;
+
+jas_taginfo_t encopts[] = {
+ {OPT_DEBUG, "debug"},
+ {OPT_IMGAREAOFFX, "imgareatlx"},
+ {OPT_IMGAREAOFFY, "imgareatly"},
+ {OPT_TILEGRDOFFX, "tilegrdtlx"},
+ {OPT_TILEGRDOFFY, "tilegrdtly"},
+ {OPT_TILEWIDTH, "tilewidth"},
+ {OPT_TILEHEIGHT, "tileheight"},
+ {OPT_PRCWIDTH, "prcwidth"},
+ {OPT_PRCHEIGHT, "prcheight"},
+ {OPT_CBLKWIDTH, "cblkwidth"},
+ {OPT_CBLKHEIGHT, "cblkheight"},
+ {OPT_MODE, "mode"},
+ {OPT_PRG, "prg"},
+ {OPT_NOMCT, "nomct"},
+ {OPT_MAXRLVLS, "numrlvls"},
+ {OPT_SOP, "sop"},
+ {OPT_EPH, "eph"},
+ {OPT_LAZY, "lazy"},
+ {OPT_TERMALL, "termall"},
+ {OPT_SEGSYM, "segsym"},
+ {OPT_VCAUSAL, "vcausal"},
+ {OPT_PTERM, "pterm"},
+ {OPT_RESET, "resetprob"},
+ {OPT_NUMGBITS, "numgbits"},
+ {OPT_RATE, "rate"},
+ {OPT_ILYRRATES, "ilyrrates"},
+ {OPT_JP2OVERHEAD, "_jp2overhead"},
+ {-1, 0}
+};
+
+typedef enum {
+ PO_L = 0,
+ PO_R
+} poid_t;
+
+
+jas_taginfo_t prgordtab[] = {
+ {JPC_COD_LRCPPRG, "lrcp"},
+ {JPC_COD_RLCPPRG, "rlcp"},
+ {JPC_COD_RPCLPRG, "rpcl"},
+ {JPC_COD_PCRLPRG, "pcrl"},
+ {JPC_COD_CPRLPRG, "cprl"},
+ {-1, 0}
+};
+
+typedef enum {
+ MODE_INT,
+ MODE_REAL
+} modeid_t;
+
+jas_taginfo_t modetab[] = {
+ {MODE_INT, "int"},
+ {MODE_REAL, "real"},
+ {-1, 0}
+};
+
+/******************************************************************************\
+* The main encoder entry point.
+\******************************************************************************/
+
+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))) {
+ jas_eprintf("invalid JP encoder options\n");
+ goto error;
+ }
+
+ if (!(enc = jpc_enc_create(cp, out, image))) {
+ goto error;
+ }
+ cp = 0;
+
+ /* Encode the main header. */
+ if (jpc_enc_encodemainhdr(enc)) {
+ goto error;
+ }
+
+ /* Encode the main body. This constitutes most of the encoding work. */
+ if (jpc_enc_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)) {
+ jas_eprintf("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) {
+ jpc_enc_cp_destroy(cp);
+ }
+ if (enc) {
+ jpc_enc_destroy(enc);
+ }
+ return -1;
+}
+
+/******************************************************************************\
+* Option parsing code.
+\******************************************************************************/
+
+static jpc_enc_cp_t *cp_create(char *optstr, jas_image_t *image)
+{
+ jpc_enc_cp_t *cp;
+ jas_tvparser_t *tvp;
+ int ret;
+ int numilyrrates;
+ double *ilyrrates;
+ int i;
+ int tagid;
+ jpc_enc_tcp_t *tcp;
+ jpc_enc_tccp_t *tccp;
+ jpc_enc_ccp_t *ccp;
+ int cmptno;
+ uint_fast16_t rlvlno;
+ uint_fast16_t prcwidthexpn;
+ uint_fast16_t prcheightexpn;
+ bool enablemct;
+ uint_fast32_t jp2overhead;
+ uint_fast16_t lyrno;
+ uint_fast32_t hsteplcm;
+ uint_fast32_t vsteplcm;
+ bool mctvalid;
+
+ tvp = 0;
+ cp = 0;
+ ilyrrates = 0;
+ numilyrrates = 0;
+
+ if (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) {
+ goto error;
+ }
+
+ prcwidthexpn = 15;
+ prcheightexpn = 15;
+ enablemct = true;
+ jp2overhead = 0;
+
+ cp->ccps = 0;
+ cp->debug = 0;
+ cp->imgareatlx = UINT_FAST32_MAX;
+ cp->imgareatly = UINT_FAST32_MAX;
+ cp->refgrdwidth = 0;
+ cp->refgrdheight = 0;
+ cp->tilegrdoffx = UINT_FAST32_MAX;
+ cp->tilegrdoffy = UINT_FAST32_MAX;
+ cp->tilewidth = 0;
+ cp->tileheight = 0;
+ cp->numcmpts = jas_image_numcmpts(image);
+
+ hsteplcm = 1;
+ vsteplcm = 1;
+ for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {
+ if (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <=
+ jas_image_brx(image) || jas_image_cmptbry(image, cmptno) +
+ jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) {
+ jas_eprintf("unsupported image type\n");
+ goto error;
+ }
+ /* Note: We ought to be calculating the LCMs here. Fix some day. */
+ hsteplcm *= jas_image_cmpthstep(image, cmptno);
+ vsteplcm *= jas_image_cmptvstep(image, cmptno);
+ }
+
+ if (!(cp->ccps = jas_malloc(cp->numcmpts * sizeof(jpc_enc_ccp_t)))) {
+ goto error;
+ }
+ for (cmptno = 0, ccp = cp->ccps; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno,
+ ++ccp) {
+ ccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno);
+ ccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno);
+ /* XXX - this isn't quite correct for more general image */
+ ccp->sampgrdsubstepx = 0;
+ ccp->sampgrdsubstepx = 0;
+ ccp->prec = jas_image_cmptprec(image, cmptno);
+ ccp->sgnd = jas_image_cmptsgnd(image, cmptno);
+ ccp->numstepsizes = 0;
+ memset(ccp->stepsizes, 0, sizeof(ccp->stepsizes));
+ }
+
+ cp->rawsize = jas_image_rawsize(image);
+ cp->totalsize = UINT_FAST32_MAX;
+
+ tcp = &cp->tcp;
+ tcp->csty = 0;
+ tcp->intmode = true;
+ tcp->prg = JPC_COD_LRCPPRG;
+ tcp->numlyrs = 1;
+ tcp->ilyrrates = 0;
+
+ tccp = &cp->tccp;
+ tccp->csty = 0;
+ tccp->maxrlvls = 6;
+ tccp->cblkwidthexpn = 6;
+ tccp->cblkheightexpn = 6;
+ tccp->cblksty = 0;
+ tccp->numgbits = 2;
+
+ if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
+ goto error;
+ }
+
+ while (!(ret = jas_tvparser_next(tvp))) {
+ switch (jas_taginfo_nonull(jas_taginfos_lookup(encopts,
+ jas_tvparser_gettag(tvp)))->id) {
+ case OPT_DEBUG:
+ cp->debug = atoi(jas_tvparser_getval(tvp));
+ break;
+ case OPT_IMGAREAOFFX:
+ cp->imgareatlx = atoi(jas_tvparser_getval(tvp));
+ break;
+ case OPT_IMGAREAOFFY:
+ cp->imgareatly = atoi(jas_tvparser_getval(tvp));
+ break;
+ case OPT_TILEGRDOFFX:
+ cp->tilegrdoffx = atoi(jas_tvparser_getval(tvp));
+ break;
+ case OPT_TILEGRDOFFY:
+ cp->tilegrdoffy = atoi(jas_tvparser_getval(tvp));
+ break;
+ case OPT_TILEWIDTH:
+ cp->tilewidth = atoi(jas_tvparser_getval(tvp));
+ break;
+ case OPT_TILEHEIGHT:
+ cp->tileheight = atoi(jas_tvparser_getval(tvp));
+ break;
+ case OPT_PRCWIDTH:
+ prcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
+ break;
+ case OPT_PRCHEIGHT:
+ prcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
+ break;
+ case OPT_CBLKWIDTH:
+ tccp->cblkwidthexpn =
+ jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
+ break;
+ case OPT_CBLKHEIGHT:
+ tccp->cblkheightexpn =
+ jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
+ break;
+ case OPT_MODE:
+ if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab,
+ jas_tvparser_getval(tvp)))->id) < 0) {
+ jas_eprintf("ignoring invalid mode %s\n",
+ jas_tvparser_getval(tvp));
+ } else {
+ tcp->intmode = (tagid == MODE_INT);
+ }
+ break;
+ case OPT_PRG:
+ if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab,
+ jas_tvparser_getval(tvp)))->id) < 0) {
+ jas_eprintf("ignoring invalid progression order %s\n",
+ jas_tvparser_getval(tvp));
+ } else {
+ tcp->prg = tagid;
+ }
+ break;
+ case OPT_NOMCT:
+ enablemct = false;
+ break;
+ case OPT_MAXRLVLS:
+ tccp->maxrlvls = atoi(jas_tvparser_getval(tvp));
+ break;
+ case OPT_SOP:
+ cp->tcp.csty |= JPC_COD_SOP;
+ break;
+ case OPT_EPH:
+ cp->tcp.csty |= JPC_COD_EPH;
+ break;
+ case OPT_LAZY:
+ tccp->cblksty |= JPC_COX_LAZY;
+ break;
+ case OPT_TERMALL:
+ tccp->cblksty |= JPC_COX_TERMALL;
+ break;
+ case OPT_SEGSYM:
+ tccp->cblksty |= JPC_COX_SEGSYM;
+ break;
+ case OPT_VCAUSAL:
+ tccp->cblksty |= JPC_COX_VSC;
+ break;
+ case OPT_RESET:
+ tccp->cblksty |= JPC_COX_RESET;
+ break;
+ case OPT_PTERM:
+ tccp->cblksty |= JPC_COX_PTERM;
+ break;
+ case OPT_NUMGBITS:
+ cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp));
+ break;
+ case OPT_RATE:
+ if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize,
+ &cp->totalsize)) {
+ jas_eprintf("ignoring bad rate specifier %s\n",
+ jas_tvparser_getval(tvp));
+ }
+ break;
+ case OPT_ILYRRATES:
+ if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates,
+ &ilyrrates)) {
+ jas_eprintf("warning: invalid intermediate layer rates specifier ignored (%s)\n",
+ jas_tvparser_getval(tvp));
+ }
+ break;
+
+ case OPT_JP2OVERHEAD:
+ jp2overhead = atoi(jas_tvparser_getval(tvp));
+ break;
+ default:
+ jas_eprintf("warning: ignoring invalid option %s\n",
+ jas_tvparser_gettag(tvp));
+ break;
+ }
+ }
+
+ jas_tvparser_destroy(tvp);
+ tvp = 0;
+
+ if (cp->totalsize != UINT_FAST32_MAX) {
+ cp->totalsize = (cp->totalsize > jp2overhead) ?
+ (cp->totalsize - jp2overhead) : 0;
+ }
+
+ if (cp->imgareatlx == UINT_FAST32_MAX) {
+ cp->imgareatlx = 0;
+ } else {
+ if (hsteplcm != 1) {
+ jas_eprintf("warning: overriding imgareatlx value\n");
+ }
+ cp->imgareatlx *= hsteplcm;
+ }
+ if (cp->imgareatly == UINT_FAST32_MAX) {
+ cp->imgareatly = 0;
+ } else {
+ if (vsteplcm != 1) {
+ jas_eprintf("warning: overriding imgareatly value\n");
+ }
+ cp->imgareatly *= vsteplcm;
+ }
+ cp->refgrdwidth = cp->imgareatlx + jas_image_width(image);
+ cp->refgrdheight = cp->imgareatly + jas_image_height(image);
+ if (cp->tilegrdoffx == UINT_FAST32_MAX) {
+ cp->tilegrdoffx = cp->imgareatlx;
+ }
+ if (cp->tilegrdoffy == UINT_FAST32_MAX) {
+ cp->tilegrdoffy = cp->imgareatly;
+ }
+ if (!cp->tilewidth) {
+ cp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx;
+ }
+ if (!cp->tileheight) {
+ cp->tileheight = cp->refgrdheight - cp->tilegrdoffy;
+ }
+
+ if (cp->numcmpts == 3) {
+ mctvalid = true;
+ for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {
+ if (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) ||
+ jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) ||
+ jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) ||
+ jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) {
+ mctvalid = false;
+ }
+ }
+ } else {
+ mctvalid = false;
+ }
+ if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) {
+ jas_eprintf("warning: color space apparently not RGB\n");
+ }
+ if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) {
+ tcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT);
+ } else {
+ tcp->mctid = JPC_MCT_NONE;
+ }
+ tccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS);
+
+ for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
+ tccp->prcwidthexpns[rlvlno] = prcwidthexpn;
+ tccp->prcheightexpns[rlvlno] = prcheightexpn;
+ }
+ if (prcwidthexpn != 15 || prcheightexpn != 15) {
+ tccp->csty |= JPC_COX_PRT;
+ }
+
+ /* Ensure that the tile width and height is valid. */
+ if (!cp->tilewidth) {
+ jas_eprintf("invalid tile width %lu\n", (unsigned long)
+ cp->tilewidth);
+ goto error;
+ }
+ if (!cp->tileheight) {
+ jas_eprintf("invalid tile height %lu\n", (unsigned long)
+ cp->tileheight);
+ goto error;
+ }
+
+ /* Ensure that the tile grid offset is valid. */
+ if (cp->tilegrdoffx > cp->imgareatlx ||
+ cp->tilegrdoffy > cp->imgareatly ||
+ cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx ||
+ cp->tilegrdoffy + cp->tileheight < cp->imgareatly) {
+ jas_eprintf("invalid tile grid offset (%lu, %lu)\n",
+ (unsigned long) cp->tilegrdoffx, (unsigned long)
+ cp->tilegrdoffy);
+ goto error;
+ }
+
+ cp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx,
+ cp->tilewidth);
+ cp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy,
+ cp->tileheight);
+ cp->numtiles = cp->numhtiles * cp->numvtiles;
+
+ if (ilyrrates && numilyrrates > 0) {
+ tcp->numlyrs = numilyrrates + 1;
+ if (!(tcp->ilyrrates = jas_malloc((tcp->numlyrs - 1) *
+ sizeof(jpc_fix_t)))) {
+ goto error;
+ }
+ for (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) {
+ tcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]);
+ }
+ }
+
+ /* Ensure that the integer mode is used in the case of lossless
+ coding. */
+ if (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) {
+ jas_eprintf("cannot use real mode for lossless coding\n");
+ goto error;
+ }
+
+ /* Ensure that the precinct width is valid. */
+ if (prcwidthexpn > 15) {
+ jas_eprintf("invalid precinct width\n");
+ goto error;
+ }
+
+ /* Ensure that the precinct height is valid. */
+ if (prcheightexpn > 15) {
+ jas_eprintf("invalid precinct height\n");
+ goto error;
+ }
+
+ /* Ensure that the code block width is valid. */
+ if (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) {
+ jas_eprintf("invalid code block width %d\n",
+ JPC_POW2(cp->tccp.cblkwidthexpn));
+ goto error;
+ }
+
+ /* Ensure that the code block height is valid. */
+ if (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) {
+ jas_eprintf("invalid code block height %d\n",
+ JPC_POW2(cp->tccp.cblkheightexpn));
+ goto error;
+ }
+
+ /* Ensure that the code block size is not too large. */
+ if (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) {
+ jas_eprintf("code block size too large\n");
+ goto error;
+ }
+
+ /* Ensure that the number of layers is valid. */
+ if (cp->tcp.numlyrs > 16384) {
+ jas_eprintf("too many layers\n");
+ goto error;
+ }
+
+ /* There must be at least one resolution level. */
+ if (cp->tccp.maxrlvls < 1) {
+ jas_eprintf("must be at least one resolution level\n");
+ goto error;
+ }
+
+ /* Ensure that the number of guard bits is valid. */
+ if (cp->tccp.numgbits > 8) {
+ jas_eprintf("invalid number of guard bits\n");
+ goto error;
+ }
+
+ /* Ensure that the rate is within the legal range. */
+ if (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) {
+ jas_eprintf("warning: specified rate is unreasonably large (%lu > %lu)\n", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize);
+ }
+
+ /* Ensure that the intermediate layer rates are valid. */
+ if (tcp->numlyrs > 1) {
+ /* The intermediate layers rates must increase monotonically. */
+ for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) {
+ if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) {
+ jas_eprintf("intermediate layer rates must increase monotonically\n");
+ goto error;
+ }
+ }
+ /* The intermediate layer rates must be less than the overall rate. */
+ if (cp->totalsize != UINT_FAST32_MAX) {
+ for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) {
+ if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize)
+ / cp->rawsize) {
+ jas_eprintf("warning: intermediate layer rates must be less than overall rate\n");
+ goto error;
+ }
+ }
+ }
+ }
+
+ if (ilyrrates) {
+ jas_free(ilyrrates);
+ }
+
+ return cp;
+
+error:
+
+ if (ilyrrates) {
+ jas_free(ilyrrates);
+ }
+ if (tvp) {
+ jas_tvparser_destroy(tvp);
+ }
+ if (cp) {
+ jpc_enc_cp_destroy(cp);
+ }
+ return 0;
+}
+
+void jpc_enc_cp_destroy(jpc_enc_cp_t *cp)
+{
+ if (cp->ccps) {
+ if (cp->tcp.ilyrrates) {
+ jas_free(cp->tcp.ilyrrates);
+ }
+ jas_free(cp->ccps);
+ }
+ jas_free(cp);
+}
+
+int ratestrtosize(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);
+ }
+ 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);
+}
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+/*static int jpc_calcssmant(jpc_fix_t stepsize)
+{
+ int n;
+ int e;
+ int m;
+
+ n = jpc_firstone(stepsize);
+ e = n - JPC_FIX_FRACBITS;
+ if (n >= 11) {
+ m = (stepsize >> (n - 11)) & 0x7ff;
+ } else {
+ m = (stepsize & ((1 << n) - 1)) << (11 - n);
+ }
+ return m;
+}
+
+static int jpc_calcssexp(jpc_fix_t stepsize)
+{
+ return jpc_firstone(stepsize) - JPC_FIX_FRACBITS;
+}*/
+
+static int jpc_enc_encodemainhdr(jpc_enc_t *enc)
+{
+ jpc_siz_t *siz;
+ jpc_cod_t *cod;
+ jpc_qcd_t *qcd;
+ int i;
+long startoff;
+long mainhdrlen;
+ jpc_enc_cp_t *cp;
+ jpc_qcc_t *qcc;
+ jpc_enc_tccp_t *tccp;
+ uint_fast16_t cmptno;
+ jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];
+ jpc_fix_t mctsynweight;
+ jpc_enc_tcp_t *tcp;
+ jpc_tsfb_t *tsfb;
+ jpc_tsfb_band_t *bandinfo;
+ uint_fast16_t numbands;
+ uint_fast16_t bandno;
+ uint_fast16_t rlvlno;
+ uint_fast16_t analgain;
+ jpc_fix_t absstepsize;
+ char buf[1024];
+ jpc_com_t *com;
+
+ cp = enc->cp;
+
+startoff = jas_stream_getrwcount(enc->out);
+
+ /* Write SOC marker segment. */
+ if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) {
+ return -1;
+ }
+ if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+ jas_eprintf("cannot write SOC marker\n");
+ return -1;
+ }
+ jpc_ms_destroy(enc->mrk);
+ enc->mrk = 0;
+
+ /* Write SIZ marker segment. */
+ if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) {
+ return -1;
+ }
+ siz = &enc->mrk->parms.siz;
+ siz->caps = 0;
+ siz->xoff = cp->imgareatlx;
+ siz->yoff = cp->imgareatly;
+ siz->width = cp->refgrdwidth;
+ siz->height = cp->refgrdheight;
+ siz->tilexoff = cp->tilegrdoffx;
+ siz->tileyoff = cp->tilegrdoffy;
+ siz->tilewidth = cp->tilewidth;
+ siz->tileheight = cp->tileheight;
+ siz->numcomps = cp->numcmpts;
+ siz->comps = jas_malloc(siz->numcomps * sizeof(jpc_sizcomp_t));
+ assert(siz->comps);
+ for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) {
+ siz->comps[i].prec = cp->ccps[i].prec;
+ siz->comps[i].sgnd = cp->ccps[i].sgnd;
+ siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx;
+ siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy;
+ }
+ if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+ jas_eprintf("cannot write SIZ marker\n");
+ return -1;
+ }
+ jpc_ms_destroy(enc->mrk);
+ enc->mrk = 0;
+
+ if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) {
+ return -1;
+ }
+ sprintf(buf, "Creator: JasPer Version %s", jas_getversion());
+ com = &enc->mrk->parms.com;
+ com->len = strlen(buf);
+ com->regid = JPC_COM_LATIN;
+ if (!(com->data = JAS_CAST(uchar *, jas_strdup(buf)))) {
+ abort();
+ }
+ if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+ jas_eprintf("cannot write COM marker\n");
+ return -1;
+ }
+ jpc_ms_destroy(enc->mrk);
+ enc->mrk = 0;
+
+#if 0
+ if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) {
+ return -1;
+ }
+ crg = &enc->mrk->parms.crg;
+ crg->comps = jas_malloc(crg->numcomps * sizeof(jpc_crgcomp_t));
+ if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+ jas_eprintf("cannot write CRG marker\n");
+ return -1;
+ }
+ jpc_ms_destroy(enc->mrk);
+ enc->mrk = 0;
+#endif
+
+ tcp = &cp->tcp;
+ tccp = &cp->tccp;
+ for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {
+ tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1);
+ jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls,
+ bandinfos);
+ jpc_tsfb_destroy(tsfb);
+ mctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno);
+ numbands = 3 * tccp->maxrlvls - 2;
+ for (bandno = 0, bandinfo = bandinfos; bandno < numbands;
+ ++bandno, ++bandinfo) {
+ rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0;
+ analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls,
+ rlvlno, bandinfo->orient);
+ if (!tcp->intmode) {
+ absstepsize = jpc_fix_div(jpc_inttofix(1 <<
+ (analgain + 1)), bandinfo->synenergywt);
+ } else {
+ absstepsize = jpc_inttofix(1);
+ }
+ cp->ccps[cmptno].stepsizes[bandno] =
+ jpc_abstorelstepsize(absstepsize,
+ cp->ccps[cmptno].prec + analgain);
+ }
+ cp->ccps[cmptno].numstepsizes = numbands;
+ }
+
+ if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
+ return -1;
+ }
+ cod = &enc->mrk->parms.cod;
+ cod->csty = cp->tccp.csty | cp->tcp.csty;
+ cod->compparms.csty = cp->tccp.csty | cp->tcp.csty;
+ cod->compparms.numdlvls = cp->tccp.maxrlvls - 1;
+ cod->compparms.numrlvls = cp->tccp.maxrlvls;
+ cod->prg = cp->tcp.prg;
+ cod->numlyrs = cp->tcp.numlyrs;
+ cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn);
+ cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn);
+ cod->compparms.cblksty = cp->tccp.cblksty;
+ cod->compparms.qmfbid = cp->tccp.qmfbid;
+ cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE);
+ if (tccp->csty & JPC_COX_PRT) {
+ for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
+ cod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno];
+ cod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno];
+ }
+ }
+ if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+ jas_eprintf("cannot write COD marker\n");
+ return -1;
+ }
+ jpc_ms_destroy(enc->mrk);
+ enc->mrk = 0;
+
+ if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) {
+ return -1;
+ }
+ qcd = &enc->mrk->parms.qcd;
+ qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
+ JPC_QCX_SEQNT : JPC_QCX_NOQNT;
+ qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes;
+ qcd->compparms.numguard = cp->tccp.numgbits;
+ qcd->compparms.stepsizes = cp->ccps[0].stepsizes;
+ if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+ return -1;
+ }
+ /* We do not want the step size array to be freed! */
+ qcd->compparms.stepsizes = 0;
+ jpc_ms_destroy(enc->mrk);
+ enc->mrk = 0;
+
+ tccp = &cp->tccp;
+ for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) {
+ if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
+ return -1;
+ }
+ qcc = &enc->mrk->parms.qcc;
+ qcc->compno = cmptno;
+ qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
+ JPC_QCX_SEQNT : JPC_QCX_NOQNT;
+ qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes;
+ qcc->compparms.numguard = cp->tccp.numgbits;
+ qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes;
+ if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+ return -1;
+ }
+ /* We do not want the step size array to be freed! */
+ qcc->compparms.stepsizes = 0;
+ jpc_ms_destroy(enc->mrk);
+ enc->mrk = 0;
+ }
+
+#define MAINTLRLEN 2
+ mainhdrlen = jas_stream_getrwcount(enc->out) - startoff;
+ enc->len += mainhdrlen;
+ if (enc->cp->totalsize != UINT_FAST32_MAX) {
+ uint_fast32_t overhead;
+ overhead = mainhdrlen + MAINTLRLEN;
+ enc->mainbodysize = (enc->cp->totalsize >= overhead) ?
+ (enc->cp->totalsize - overhead) : 0;
+ } else {
+ enc->mainbodysize = UINT_FAST32_MAX;
+ }
+
+ return 0;
+}
+
+static int jpc_enc_encodemainbody(jpc_enc_t *enc)
+{
+ int tileno;
+ int tilex;
+ int tiley;
+ 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 numbytes;
+ long tilehdrlen;
+ long tilelen;
+ jpc_enc_tile_t *tile;
+ jpc_enc_cp_t *cp;
+ double rho;
+ int lyrno;
+ int 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;
+
+ cp = enc->cp;
+
+ /* Avoid compile warnings. */
+ numbytes = 0;
+
+ for (tileno = 0; tileno < JAS_CAST(int, cp->numtiles); ++tileno) {
+ tilex = tileno % cp->numhtiles;
+ tiley = tileno / cp->numhtiles;
+
+ if (!(enc->curtile = jpc_enc_tile_create(enc->cp, enc->image, tileno))) {
+ 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->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_CAST(uint_fast32_t, jas_matrix_numrows(band->data)); ++y) {
+ for (x = 0; x < JAS_CAST(uint_fast32_t, 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 0
+jas_eprintf("%d %d mag=%d actual=%d numgbits=%d\n", cp->ccps[cmptno].prec, band->analgain, mxmag, actualnumbps, numgbits);
+#endif
+ if (numgbits > mingbits) {
+ mingbits = numgbits;
+ }
+ if (!tile->intmode) {
+ band->absstepsize = jpc_fix_div(jpc_inttofix(1
+ << (band->analgain + 1)),
+ band->synweight);
+ } else {
+ band->absstepsize = jpc_inttofix(1);
+ }
+ 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) {
+ jpc_quantize(band->data, band->absstepsize);
+ }
+
+ comp->stepsizes[absbandno] = band->stepsize;
+ ++absbandno;
+ }
+ }
+
+ assert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS);
+ if (!tile->intmode) {
+ jas_matrix_divpow2(comp->data, JPC_FIX_FRACBITS - JPC_NUMEXTRABITS);
+ } else {
+ jas_matrix_asl(comp->data, JPC_NUMEXTRABITS);
+ }
+
+#if 0
+jas_eprintf("mingbits %d\n", mingbits);
+#endif
+ if (mingbits > cp->tccp.numgbits) {
+ jas_eprintf("error: too few guard bits (need at least %d)\n",
+ mingbits);
+ return -1;
+ }
+ }
+
+ if (!(enc->tmpstream = jas_stream_memopen(0, 0))) {
+ jas_eprintf("cannot open tmp file\n");
+ return -1;
+ }
+
+ /* Write the tile header. */
+ if (!(enc->mrk = jpc_ms_create(JPC_MS_SOT))) {
+ return -1;
+ }
+ sot = &enc->mrk->parms.sot;
+ sot->len = 0;
+ sot->tileno = tileno;
+ sot->partno = 0;
+ sot->numparts = 1;
+ if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
+ jas_eprintf("cannot write SOT marker\n");
+ return -1;
+ }
+ jpc_ms_destroy(enc->mrk);
+ enc->mrk = 0;
+
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+
+ tccp = &cp->tccp;
+ for (cmptno = 0; cmptno < JAS_CAST(int, 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 < JAS_CAST(int, cp->numcmpts); ++cmptno, ++comp) {
+ ccps = &cp->ccps[cmptno];
+ if (JAS_CAST(int, ccps->numstepsizes) == comp->numstepsizes) {
+ samestepsizes = 1;
+ for (bandno = 0; bandno < JAS_CAST(int, ccps->numstepsizes); ++bandno) {
+ if (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) {
+ samestepsizes = 0;
+ break;
+ }
+ }
+ } else {
+ samestepsizes = 0;
+ }
+ if (!samestepsizes) {
+ if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
+ return -1;
+ }
+ qcc = &enc->mrk->parms.qcc;
+ qcc->compno = cmptno;
+ qcc->compparms.numguard = cp->tccp.numgbits;
+ qcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ?
+ JPC_QCX_SEQNT : JPC_QCX_NOQNT;
+ qcc->compparms.numstepsizes = comp->numstepsizes;
+ qcc->compparms.stepsizes = comp->stepsizes;
+ if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
+ return -1;
+ }
+ qcc->compparms.stepsizes = 0;
+ jpc_ms_destroy(enc->mrk);
+ enc->mrk = 0;
+ }
+ }
+
+ /* Write a SOD marker to indicate the end of the tile header. */
+ if (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) {
+ return -1;
+ }
+ if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
+ jas_eprintf("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;
+
+ for (lyrno = 0; lyrno < tile->numlyrs - 1; ++lyrno) {
+ tile->lyrsizes[lyrno] = tile->rawsize * jpc_fixtodbl(
+ cp->tcp.ilyrrates[lyrno]);
+ }
+ tile->lyrsizes[tile->numlyrs - 1] = (cp->totalsize != UINT_FAST32_MAX) ?
+ (rho * enc->mainbodysize) : UINT_FAST32_MAX;
+ for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
+ if (tile->lyrsizes[lyrno] != UINT_FAST32_MAX) {
+ if (tilehdrlen <= JAS_CAST(long, tile->lyrsizes[lyrno])) {
+ tile->lyrsizes[lyrno] -= tilehdrlen;
+ } else {
+ tile->lyrsizes[lyrno] = 0;
+ }
+ }
+ }
+
+ if (rateallocate(enc, tile->numlyrs, tile->lyrsizes)) {
+ return -1;
+ }
+
+#if 0
+jas_eprintf("ENCODE TILE DATA\n");
+#endif
+ if (jpc_enc_encodetiledata(enc)) {
+ jas_eprintf("dotile failed\n");
+ return -1;
+ }
+
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+
+ tilelen = jas_stream_tell(enc->tmpstream);
+
+ if (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) {
+ return -1;
+ }
+ jpc_putuint32(enc->tmpstream, tilelen);
+
+ if (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) {
+ return -1;
+ }
+ if (jpc_putdata(enc->out, enc->tmpstream, -1)) {
+ return -1;
+ }
+ enc->len += tilelen;
+
+ jas_stream_close(enc->tmpstream);
+ enc->tmpstream = 0;
+
+ jpc_enc_tile_destroy(enc->curtile);
+ enc->curtile = 0;
+
+ }
+
+ return 0;
+}
+
+int jpc_enc_encodetiledata(jpc_enc_t *enc)
+{
+assert(enc->tmpstream);
+ if (jpc_enc_encpkts(enc, enc->tmpstream)) {
+ return -1;
+ }
+ return 0;
+}
+
+int dump_passes(jpc_enc_pass_t *passes, int numpasses, jpc_enc_cblk_t *cblk)
+{
+ jpc_enc_pass_t *pass;
+ int i;
+ jas_stream_memobj_t *smo;
+
+ smo = cblk->stream->obj_;
+
+ pass = passes;
+ for (i = 0; i < numpasses; ++i) {
+ jas_eprintf("start=%d end=%d type=%d term=%d lyrno=%d firstchar=%02x size=%ld pos=%ld\n",
+ (int)pass->start, (int)pass->end, (int)pass->type, (int)pass->term, (int)pass->lyrno,
+ smo->buf_[pass->start], (long)smo->len_, (long)smo->pos_);
+#if 0
+ jas_memdump(stderr, &smo->buf_[pass->start], pass->end - pass->start);
+#endif
+ ++pass;
+ }
+ return 0;
+}
+
+void jpc_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);
+ }
+ }
+}
+
+void calcrdslopes(jpc_enc_cblk_t *cblk)
+{
+ jpc_enc_pass_t *endpasses;
+ jpc_enc_pass_t *pass0;
+ jpc_enc_pass_t *pass1;
+ jpc_enc_pass_t *pass2;
+ jpc_flt_t slope0;
+ jpc_flt_t slope;
+ jpc_flt_t dd;
+ long dr;
+
+ endpasses = &cblk->passes[cblk->numpasses];
+ pass2 = cblk->passes;
+ slope0 = 0;
+ while (pass2 != endpasses) {
+ pass0 = 0;
+ for (pass1 = cblk->passes; pass1 != endpasses; ++pass1) {
+ dd = pass1->cumwmsedec;
+ dr = pass1->end;
+ if (pass0) {
+ dd -= pass0->cumwmsedec;
+ dr -= pass0->end;
+ }
+ if (dd <= 0) {
+ pass1->rdslope = JPC_BADRDSLOPE;
+ if (pass1 >= pass2) {
+ pass2 = &pass1[1];
+ }
+ continue;
+ }
+ if (pass1 < pass2 && pass1->rdslope <= 0) {
+ continue;
+ }
+ if (!dr) {
+ assert(pass0);
+ pass0->rdslope = 0;
+ break;
+ }
+ slope = dd / dr;
+ if (pass0 && slope >= slope0) {
+ pass0->rdslope = 0;
+ break;
+ }
+ pass1->rdslope = slope;
+ if (pass1 >= pass2) {
+ pass2 = &pass1[1];
+ }
+ pass0 = pass1;
+ slope0 = slope;
+ }
+ }
+
+#if 0
+ for (pass0 = cblk->passes; pass0 != endpasses; ++pass0) {
+if (pass0->rdslope > 0.0) {
+ jas_eprintf("pass %02d nmsedec=%lf dec=%lf end=%d %lf\n", pass0 - cblk->passes,
+ fixtodbl(pass0->nmsedec), pass0->wmsedec, pass0->end, pass0->rdslope);
+}
+ }
+#endif
+}
+
+void dump_layeringinfo(jpc_enc_t *enc)
+{
+
+ jpc_enc_tcmpt_t *tcmpt;
+ int tcmptno;
+ jpc_enc_rlvl_t *rlvl;
+ int rlvlno;
+ jpc_enc_band_t *band;
+ int bandno;
+ jpc_enc_prc_t *prc;
+ int prcno;
+ jpc_enc_cblk_t *cblk;
+ int cblkno;
+ jpc_enc_pass_t *pass;
+ int passno;
+ int lyrno;
+ jpc_enc_tile_t *tile;
+
+ tile = enc->curtile;
+
+ for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
+ jas_eprintf("lyrno = %02d\n", lyrno);
+ for (tcmptno = 0, tcmpt = tile->tcmpts; tcmptno < tile->numtcmpts;
+ ++tcmptno, ++tcmpt) {
+ for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
+ ++rlvlno, ++rlvl) {
+ if (!rlvl->bands) {
+ continue;
+ }
+ for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
+ ++bandno, ++band) {
+ if (!band->data) {
+ continue;
+ }
+ for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
+ ++prcno, ++prc) {
+ if (!prc->cblks) {
+ continue;
+ }
+ for (cblkno = 0, cblk = prc->cblks; cblkno <
+ prc->numcblks; ++cblkno, ++cblk) {
+ for (passno = 0, pass = cblk->passes; passno <
+ cblk->numpasses && pass->lyrno == lyrno;
+ ++passno, ++pass) {
+ jas_eprintf("lyrno=%02d cmptno=%02d rlvlno=%02d bandno=%02d prcno=%02d cblkno=%03d passno=%03d\n", lyrno, tcmptno, rlvlno, bandno, prcno, cblkno, passno);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+int rateallocate(jpc_enc_t *enc, int numlyrs, uint_fast32_t *cumlens)
+{
+ jpc_flt_t lo;
+ jpc_flt_t hi;
+ jas_stream_t *out;
+ long cumlen;
+ int lyrno;
+ jpc_flt_t thresh;
+ jpc_flt_t goodthresh;
+ int success;
+ long pos;
+ long oldpos;
+ int numiters;
+
+ jpc_enc_tcmpt_t *comp;
+ jpc_enc_tcmpt_t *endcomps;
+ jpc_enc_rlvl_t *lvl;
+ jpc_enc_rlvl_t *endlvls;
+ jpc_enc_band_t *band;
+ jpc_enc_band_t *endbands;
+ jpc_enc_cblk_t *cblk;
+ jpc_enc_cblk_t *endcblks;
+ jpc_enc_pass_t *pass;
+ jpc_enc_pass_t *endpasses;
+ jpc_enc_pass_t *pass1;
+ jpc_flt_t mxrdslope;
+ jpc_flt_t mnrdslope;
+ jpc_enc_tile_t *tile;
+ jpc_enc_prc_t *prc;
+ int prcno;
+
+ tile = enc->curtile;
+
+ for (lyrno = 1; lyrno < numlyrs - 1; ++lyrno) {
+ if (cumlens[lyrno - 1] > cumlens[lyrno]) {
+ abort();
+ }
+ }
+
+ if (!(out = jas_stream_memopen(0, 0))) {
+ return -1;
+ }
+
+
+ /* Find minimum and maximum R-D slope values. */
+ mnrdslope = DBL_MAX;
+ mxrdslope = 0;
+ endcomps = &tile->tcmpts[tile->numtcmpts];
+ for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+ endlvls = &comp->rlvls[comp->numrlvls];
+ for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
+ if (!lvl->bands) {
+ continue;
+ }
+ endbands = &lvl->bands[lvl->numbands];
+ for (band = lvl->bands; band != endbands; ++band) {
+ if (!band->data) {
+ continue;
+ }
+ for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
+ if (!prc->cblks) {
+ continue;
+ }
+ endcblks = &prc->cblks[prc->numcblks];
+ for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+ calcrdslopes(cblk);
+ endpasses = &cblk->passes[cblk->numpasses];
+ for (pass = cblk->passes; pass != endpasses; ++pass) {
+ if (pass->rdslope > 0) {
+ if (pass->rdslope < mnrdslope) {
+ mnrdslope = pass->rdslope;
+ }
+ if (pass->rdslope > mxrdslope) {
+ mxrdslope = pass->rdslope;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+if (jas_getdbglevel()) {
+ jas_eprintf("min rdslope = %f max rdslope = %f\n", mnrdslope, mxrdslope);
+}
+
+ jpc_init_t2state(enc, 1);
+
+ for (lyrno = 0; lyrno < numlyrs; ++lyrno) {
+
+ lo = mnrdslope;
+ hi = mxrdslope;
+
+ success = 0;
+ goodthresh = 0;
+ numiters = 0;
+
+ do {
+
+ cumlen = cumlens[lyrno];
+ if (cumlen == UINT_FAST32_MAX) {
+ /* Only the last layer can be free of a rate
+ constraint (e.g., for lossless coding). */
+ assert(lyrno == numlyrs - 1);
+ goodthresh = -1;
+ success = 1;
+ break;
+ }
+
+ thresh = (lo + hi) / 2;
+
+ /* Save the tier 2 coding state. */
+ jpc_save_t2state(enc);
+ oldpos = jas_stream_tell(out);
+ assert(oldpos >= 0);
+
+ /* Assign all passes with R-D slopes greater than or
+ equal to the current threshold to this layer. */
+ endcomps = &tile->tcmpts[tile->numtcmpts];
+ for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+ endlvls = &comp->rlvls[comp->numrlvls];
+ for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
+ if (!lvl->bands) {
+ continue;
+ }
+ endbands = &lvl->bands[lvl->numbands];
+ for (band = lvl->bands; band != endbands; ++band) {
+ if (!band->data) {
+ continue;
+ }
+ for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
+ if (!prc->cblks) {
+ continue;
+ }
+ endcblks = &prc->cblks[prc->numcblks];
+ for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+ if (cblk->curpass) {
+ endpasses = &cblk->passes[cblk->numpasses];
+ pass1 = cblk->curpass;
+ for (pass = cblk->curpass; pass != endpasses; ++pass) {
+ if (pass->rdslope >= thresh) {
+ pass1 = &pass[1];
+ }
+ }
+ for (pass = cblk->curpass; pass != pass1; ++pass) {
+ pass->lyrno = lyrno;
+ }
+ for (; pass != endpasses; ++pass) {
+ pass->lyrno = -1;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /* Perform tier 2 coding. */
+ endcomps = &tile->tcmpts[tile->numtcmpts];
+ for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+ endlvls = &comp->rlvls[comp->numrlvls];
+ for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
+ if (!lvl->bands) {
+ continue;
+ }
+ for (prcno = 0; prcno < lvl->numprcs; ++prcno) {
+ if (jpc_enc_encpkt(enc, out, comp - tile->tcmpts, lvl - comp->rlvls, prcno, lyrno)) {
+ return -1;
+ }
+ }
+ }
+ }
+
+ pos = jas_stream_tell(out);
+
+ /* Check the rate constraint. */
+ assert(pos >= 0);
+ if (pos > cumlen) {
+ /* The rate is too high. */
+ lo = thresh;
+ } else if (pos <= cumlen) {
+ /* The rate is low enough, so try higher. */
+ hi = thresh;
+ if (!success || thresh < goodthresh) {
+ goodthresh = thresh;
+ success = 1;
+ }
+ }
+
+ /* Save the tier 2 coding state. */
+ jpc_restore_t2state(enc);
+ if (jas_stream_seek(out, oldpos, SEEK_SET) < 0) {
+ abort();
+ }
+
+if (jas_getdbglevel()) {
+jas_eprintf("maxlen=%08ld actuallen=%08ld thresh=%f\n", cumlen, pos, thresh);
+}
+
+ ++numiters;
+ } while (lo < hi - 1e-3 && numiters < 32);
+
+ if (!success) {
+ jas_eprintf("warning: empty layer generated\n");
+ }
+
+if (jas_getdbglevel()) {
+jas_eprintf("success %d goodthresh %f\n", success, goodthresh);
+}
+
+ /* Assign all passes with R-D slopes greater than or
+ equal to the selected threshold to this layer. */
+ endcomps = &tile->tcmpts[tile->numtcmpts];
+ for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+ endlvls = &comp->rlvls[comp->numrlvls];
+ for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
+if (!lvl->bands) {
+ continue;
+}
+ endbands = &lvl->bands[lvl->numbands];
+ for (band = lvl->bands; band != endbands; ++band) {
+ if (!band->data) {
+ continue;
+ }
+ for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
+ if (!prc->cblks) {
+ continue;
+ }
+ endcblks = &prc->cblks[prc->numcblks];
+ for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+ if (cblk->curpass) {
+ endpasses = &cblk->passes[cblk->numpasses];
+ pass1 = cblk->curpass;
+ if (success) {
+ for (pass = cblk->curpass; pass != endpasses; ++pass) {
+ if (pass->rdslope >= goodthresh) {
+ pass1 = &pass[1];
+ }
+ }
+ }
+ for (pass = cblk->curpass; pass != pass1; ++pass) {
+ pass->lyrno = lyrno;
+ }
+ for (; pass != endpasses; ++pass) {
+ pass->lyrno = -1;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /* Perform tier 2 coding. */
+ endcomps = &tile->tcmpts[tile->numtcmpts];
+ for (comp = tile->tcmpts; comp != endcomps; ++comp) {
+ endlvls = &comp->rlvls[comp->numrlvls];
+ for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
+ if (!lvl->bands) {
+ continue;
+ }
+ for (prcno = 0; prcno < lvl->numprcs; ++prcno) {
+ if (jpc_enc_encpkt(enc, out, comp - tile->tcmpts, lvl - comp->rlvls, prcno, lyrno)) {
+ return -1;
+ }
+ }
+ }
+ }
+ }
+
+ if (jas_getdbglevel() >= 5) {
+ dump_layeringinfo(enc);
+ }
+
+ jas_stream_close(out);
+
+ JAS_DBGLOG(10, ("done doing rateallocation\n"));
+#if 0
+jas_eprintf("DONE RATE ALLOCATE\n");
+#endif
+
+ return 0;
+}
+
+/******************************************************************************\
+* Tile constructors and destructors.
+\******************************************************************************/
+
+jpc_enc_tile_t *jpc_enc_tile_create(jpc_enc_cp_t *cp, jas_image_t *image, int tileno)
+{
+ jpc_enc_tile_t *tile;
+ uint_fast32_t htileno;
+ uint_fast32_t vtileno;
+ uint_fast16_t lyrno;
+ uint_fast16_t cmptno;
+ jpc_enc_tcmpt_t *tcmpt;
+
+ if (!(tile = jas_malloc(sizeof(jpc_enc_tile_t)))) {
+ goto error;
+ }
+
+ /* Initialize a few members used in error recovery. */
+ tile->tcmpts = 0;
+ tile->lyrsizes = 0;
+ tile->numtcmpts = cp->numcmpts;
+ tile->pi = 0;
+
+ tile->tileno = tileno;
+ htileno = tileno % cp->numhtiles;
+ vtileno = tileno / cp->numhtiles;
+
+ /* Calculate the coordinates of the top-left and bottom-right
+ corners of the tile. */
+ tile->tlx = JAS_MAX(cp->tilegrdoffx + htileno * cp->tilewidth,
+ cp->imgareatlx);
+ tile->tly = JAS_MAX(cp->tilegrdoffy + vtileno * cp->tileheight,
+ cp->imgareatly);
+ tile->brx = JAS_MIN(cp->tilegrdoffx + (htileno + 1) * cp->tilewidth,
+ cp->refgrdwidth);
+ tile->bry = JAS_MIN(cp->tilegrdoffy + (vtileno + 1) * cp->tileheight,
+ cp->refgrdheight);
+
+ /* Initialize some tile coding parameters. */
+ tile->intmode = cp->tcp.intmode;
+ tile->csty = cp->tcp.csty;
+ tile->prg = cp->tcp.prg;
+ tile->mctid = cp->tcp.mctid;
+
+ tile->numlyrs = cp->tcp.numlyrs;
+ if (!(tile->lyrsizes = jas_malloc(tile->numlyrs *
+ sizeof(uint_fast32_t)))) {
+ goto error;
+ }
+ for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
+ tile->lyrsizes[lyrno] = 0;
+ }
+
+ /* Allocate an array for the per-tile-component information. */
+ if (!(tile->tcmpts = jas_malloc(cp->numcmpts * sizeof(jpc_enc_tcmpt_t)))) {
+ goto error;
+ }
+ /* Initialize a few members critical for error recovery. */
+ for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
+ ++cmptno, ++tcmpt) {
+ tcmpt->rlvls = 0;
+ tcmpt->tsfb = 0;
+ tcmpt->data = 0;
+ }
+ /* Initialize the per-tile-component information. */
+ for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
+ ++cmptno, ++tcmpt) {
+ if (!tcmpt_create(tcmpt, cp, image, tile)) {
+ goto error;
+ }
+ }
+
+ /* Initialize the synthesis weights for the MCT. */
+ switch (tile->mctid) {
+ case JPC_MCT_RCT:
+ tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0));
+ tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(0.6875));
+ tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(0.6875));
+ break;
+ case JPC_MCT_ICT:
+ tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0000));
+ tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(3.2584));
+ tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(2.4755));
+ break;
+ default:
+ case JPC_MCT_NONE:
+ for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
+ ++cmptno, ++tcmpt) {
+ tcmpt->synweight = JPC_FIX_ONE;
+ }
+ break;
+ }
+
+ if (!(tile->pi = jpc_enc_pi_create(cp, tile))) {
+ goto error;
+ }
+
+ return tile;
+
+error:
+
+ if (tile) {
+ jpc_enc_tile_destroy(tile);
+ }
+ return 0;
+}
+
+void jpc_enc_tile_destroy(jpc_enc_tile_t *tile)
+{
+ jpc_enc_tcmpt_t *tcmpt;
+ uint_fast16_t cmptno;
+
+ if (tile->tcmpts) {
+ for (cmptno = 0, tcmpt = tile->tcmpts; cmptno <
+ tile->numtcmpts; ++cmptno, ++tcmpt) {
+ tcmpt_destroy(tcmpt);
+ }
+ jas_free(tile->tcmpts);
+ }
+ if (tile->lyrsizes) {
+ jas_free(tile->lyrsizes);
+ }
+ if (tile->pi) {
+ jpc_pi_destroy(tile->pi);
+ }
+ jas_free(tile);
+}
+
+static jpc_enc_tcmpt_t *tcmpt_create(jpc_enc_tcmpt_t *tcmpt, jpc_enc_cp_t *cp,
+ jas_image_t *image, jpc_enc_tile_t *tile)
+{
+ uint_fast16_t cmptno;
+ uint_fast16_t rlvlno;
+ jpc_enc_rlvl_t *rlvl;
+ uint_fast32_t tlx;
+ uint_fast32_t tly;
+ uint_fast32_t brx;
+ uint_fast32_t bry;
+ uint_fast32_t cmpttlx;
+ uint_fast32_t cmpttly;
+ jpc_enc_ccp_t *ccp;
+ jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];
+
+ tcmpt->tile = tile;
+ tcmpt->tsfb = 0;
+ tcmpt->data = 0;
+ tcmpt->rlvls = 0;
+
+ /* Deduce the component number. */
+ cmptno = tcmpt - tile->tcmpts;
+
+ ccp = &cp->ccps[cmptno];
+
+ /* Compute the coordinates of the top-left and bottom-right
+ corners of this tile-component. */
+ tlx = JPC_CEILDIV(tile->tlx, ccp->sampgrdstepx);
+ tly = JPC_CEILDIV(tile->tly, ccp->sampgrdstepy);
+ brx = JPC_CEILDIV(tile->brx, ccp->sampgrdstepx);
+ bry = JPC_CEILDIV(tile->bry, ccp->sampgrdstepy);
+
+ /* Create a sequence to hold the tile-component sample data. */
+ if (!(tcmpt->data = jas_seq2d_create(tlx, tly, brx, bry))) {
+ goto error;
+ }
+
+ /* Get the image data associated with this tile-component. */
+ cmpttlx = JPC_CEILDIV(cp->imgareatlx, ccp->sampgrdstepx);
+ cmpttly = JPC_CEILDIV(cp->imgareatly, ccp->sampgrdstepy);
+ if (jas_image_readcmpt(image, cmptno, tlx - cmpttlx, tly - cmpttly,
+ brx - tlx, bry - tly, tcmpt->data)) {
+ goto error;
+ }
+
+ tcmpt->synweight = 0;
+ tcmpt->qmfbid = cp->tccp.qmfbid;
+ tcmpt->numrlvls = cp->tccp.maxrlvls;
+ tcmpt->numbands = 3 * tcmpt->numrlvls - 2;
+ if (!(tcmpt->tsfb = jpc_cod_gettsfb(tcmpt->qmfbid, tcmpt->numrlvls - 1))) {
+ goto error;
+ }
+
+ for (rlvlno = 0; rlvlno < tcmpt->numrlvls; ++rlvlno) {
+ tcmpt->prcwidthexpns[rlvlno] = cp->tccp.prcwidthexpns[rlvlno];
+ tcmpt->prcheightexpns[rlvlno] = cp->tccp.prcheightexpns[rlvlno];
+ }
+ tcmpt->cblkwidthexpn = cp->tccp.cblkwidthexpn;
+ tcmpt->cblkheightexpn = cp->tccp.cblkheightexpn;
+ tcmpt->cblksty = cp->tccp.cblksty;
+ tcmpt->csty = cp->tccp.csty;
+
+ tcmpt->numstepsizes = tcmpt->numbands;
+ assert(tcmpt->numstepsizes <= JPC_MAXBANDS);
+ memset(tcmpt->stepsizes, 0, sizeof(tcmpt->numstepsizes *
+ sizeof(uint_fast16_t)));
+
+ /* Retrieve information about the various bands. */
+ jpc_tsfb_getbands(tcmpt->tsfb, jas_seq2d_xstart(tcmpt->data),
+ jas_seq2d_ystart(tcmpt->data), jas_seq2d_xend(tcmpt->data),
+ jas_seq2d_yend(tcmpt->data), bandinfos);
+
+ if (!(tcmpt->rlvls = jas_malloc(tcmpt->numrlvls * sizeof(jpc_enc_rlvl_t)))) {
+ goto error;
+ }
+ for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
+ ++rlvlno, ++rlvl) {
+ rlvl->bands = 0;
+ rlvl->tcmpt = tcmpt;
+ }
+ for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
+ ++rlvlno, ++rlvl) {
+ if (!rlvl_create(rlvl, cp, tcmpt, bandinfos)) {
+ goto error;
+ }
+ }
+
+ return tcmpt;
+
+error:
+
+ tcmpt_destroy(tcmpt);
+ return 0;
+
+}
+
+static void tcmpt_destroy(jpc_enc_tcmpt_t *tcmpt)
+{
+ jpc_enc_rlvl_t *rlvl;
+ uint_fast16_t rlvlno;
+
+ if (tcmpt->rlvls) {
+ for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
+ ++rlvlno, ++rlvl) {
+ rlvl_destroy(rlvl);
+ }
+ jas_free(tcmpt->rlvls);
+ }
+
+ if (tcmpt->data) {
+ jas_seq2d_destroy(tcmpt->data);
+ }
+ if (tcmpt->tsfb) {
+ jpc_tsfb_destroy(tcmpt->tsfb);
+ }
+}
+
+static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp,
+ jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos)
+{
+ uint_fast16_t rlvlno;
+ uint_fast32_t tlprctlx;
+ uint_fast32_t tlprctly;
+ uint_fast32_t brprcbrx;
+ uint_fast32_t brprcbry;
+ uint_fast16_t bandno;
+ jpc_enc_band_t *band;
+
+ /* Deduce the resolution level. */
+ rlvlno = rlvl - tcmpt->rlvls;
+
+ /* Initialize members required for error recovery. */
+ rlvl->bands = 0;
+ rlvl->tcmpt = tcmpt;
+
+ /* Compute the coordinates of the top-left and bottom-right
+ corners of the tile-component at this resolution. */
+ rlvl->tlx = JPC_CEILDIVPOW2(jas_seq2d_xstart(tcmpt->data), tcmpt->numrlvls -
+ 1 - rlvlno);
+ rlvl->tly = JPC_CEILDIVPOW2(jas_seq2d_ystart(tcmpt->data), tcmpt->numrlvls -
+ 1 - rlvlno);
+ rlvl->brx = JPC_CEILDIVPOW2(jas_seq2d_xend(tcmpt->data), tcmpt->numrlvls -
+ 1 - rlvlno);
+ rlvl->bry = JPC_CEILDIVPOW2(jas_seq2d_yend(tcmpt->data), tcmpt->numrlvls -
+ 1 - rlvlno);
+
+ if (rlvl->tlx >= rlvl->brx || rlvl->tly >= rlvl->bry) {
+ rlvl->numhprcs = 0;
+ rlvl->numvprcs = 0;
+ rlvl->numprcs = 0;
+ return rlvl;
+ }
+
+ rlvl->numbands = (!rlvlno) ? 1 : 3;
+ rlvl->prcwidthexpn = cp->tccp.prcwidthexpns[rlvlno];
+ rlvl->prcheightexpn = cp->tccp.prcheightexpns[rlvlno];
+ if (!rlvlno) {
+ rlvl->cbgwidthexpn = rlvl->prcwidthexpn;
+ rlvl->cbgheightexpn = rlvl->prcheightexpn;
+ } else {
+ rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1;
+ rlvl->cbgheightexpn = rlvl->prcheightexpn - 1;
+ }
+ rlvl->cblkwidthexpn = JAS_MIN(cp->tccp.cblkwidthexpn, rlvl->cbgwidthexpn);
+ rlvl->cblkheightexpn = JAS_MIN(cp->tccp.cblkheightexpn, rlvl->cbgheightexpn);
+
+ /* Compute the number of precincts. */
+ tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn);
+ tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn);
+ brprcbrx = JPC_CEILTOMULTPOW2(rlvl->brx, rlvl->prcwidthexpn);
+ brprcbry = JPC_CEILTOMULTPOW2(rlvl->bry, rlvl->prcheightexpn);
+ rlvl->numhprcs = JPC_FLOORDIVPOW2(brprcbrx - tlprctlx, rlvl->prcwidthexpn);
+ rlvl->numvprcs = JPC_FLOORDIVPOW2(brprcbry - tlprctly, rlvl->prcheightexpn);
+ rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs;
+
+ if (!(rlvl->bands = jas_malloc(rlvl->numbands * sizeof(jpc_enc_band_t)))) {
+ goto error;
+ }
+ for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
+ ++bandno, ++band) {
+ band->prcs = 0;
+ band->data = 0;
+ band->rlvl = rlvl;
+ }
+ for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
+ ++bandno, ++band) {
+ if (!band_create(band, cp, rlvl, bandinfos)) {
+ goto error;
+ }
+ }
+
+ return rlvl;
+error:
+
+ rlvl_destroy(rlvl);
+ return 0;
+}
+
+static void rlvl_destroy(jpc_enc_rlvl_t *rlvl)
+{
+ jpc_enc_band_t *band;
+ uint_fast16_t bandno;
+
+ if (rlvl->bands) {
+ for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
+ ++bandno, ++band) {
+ band_destroy(band);
+ }
+ jas_free(rlvl->bands);
+ }
+}
+
+static jpc_enc_band_t *band_create(jpc_enc_band_t *band, jpc_enc_cp_t *cp,
+ jpc_enc_rlvl_t *rlvl, jpc_tsfb_band_t *bandinfos)
+{
+ uint_fast16_t bandno;
+ uint_fast16_t gblbandno;
+ uint_fast16_t rlvlno;
+ jpc_tsfb_band_t *bandinfo;
+ jpc_enc_tcmpt_t *tcmpt;
+ uint_fast32_t prcno;
+ jpc_enc_prc_t *prc;
+
+ tcmpt = rlvl->tcmpt;
+ band->data = 0;
+ band->prcs = 0;
+ band->rlvl = rlvl;
+
+ /* Deduce the resolution level and band number. */
+ rlvlno = rlvl - rlvl->tcmpt->rlvls;
+ bandno = band - rlvl->bands;
+ gblbandno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + bandno + 1);
+
+ bandinfo = &bandinfos[gblbandno];
+
+if (bandinfo->xstart != bandinfo->xend && bandinfo->ystart != bandinfo->yend) {
+ if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) {
+ goto error;
+ }
+ jas_seq2d_bindsub(band->data, tcmpt->data, bandinfo->locxstart,
+ bandinfo->locystart, bandinfo->locxend, bandinfo->locyend);
+ jas_seq2d_setshift(band->data, bandinfo->xstart, bandinfo->ystart);
+}
+ band->orient = bandinfo->orient;
+ band->analgain = JPC_NOMINALGAIN(cp->tccp.qmfbid, tcmpt->numrlvls, rlvlno,
+ band->orient);
+ band->numbps = 0;
+ band->absstepsize = 0;
+ band->stepsize = 0;
+ band->synweight = bandinfo->synenergywt;
+
+if (band->data) {
+ if (!(band->prcs = jas_malloc(rlvl->numprcs * sizeof(jpc_enc_prc_t)))) {
+ goto error;
+ }
+ for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno,
+ ++prc) {
+ prc->cblks = 0;
+ prc->incltree = 0;
+ prc->nlibtree = 0;
+ prc->savincltree = 0;
+ prc->savnlibtree = 0;
+ prc->band = band;
+ }
+ for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno,
+ ++prc) {
+ if (!prc_create(prc, cp, band)) {
+ goto error;
+ }
+ }
+}
+
+ return band;
+
+error:
+ band_destroy(band);
+ return 0;
+}
+
+static void band_destroy(jpc_enc_band_t *band)
+{
+ jpc_enc_prc_t *prc;
+ jpc_enc_rlvl_t *rlvl;
+ uint_fast32_t prcno;
+
+ if (band->prcs) {
+ rlvl = band->rlvl;
+ for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
+ ++prcno, ++prc) {
+ prc_destroy(prc);
+ }
+ jas_free(band->prcs);
+ }
+ if (band->data) {
+ jas_seq2d_destroy(band->data);
+ }
+}
+
+static jpc_enc_prc_t *prc_create(jpc_enc_prc_t *prc, jpc_enc_cp_t *cp, jpc_enc_band_t *band)
+{
+ uint_fast32_t prcno;
+ uint_fast32_t prcxind;
+ uint_fast32_t prcyind;
+ uint_fast32_t cbgtlx;
+ uint_fast32_t cbgtly;
+ uint_fast32_t tlprctlx;
+ uint_fast32_t tlprctly;
+ uint_fast32_t tlcbgtlx;
+ uint_fast32_t tlcbgtly;
+ uint_fast16_t rlvlno;
+ jpc_enc_rlvl_t *rlvl;
+ uint_fast32_t tlcblktlx;
+ uint_fast32_t tlcblktly;
+ uint_fast32_t brcblkbrx;
+ uint_fast32_t brcblkbry;
+ uint_fast32_t cblkno;
+ jpc_enc_cblk_t *cblk;
+ jpc_enc_tcmpt_t *tcmpt;
+
+ prc->cblks = 0;
+ prc->incltree = 0;
+ prc->savincltree = 0;
+ prc->nlibtree = 0;
+ prc->savnlibtree = 0;
+
+ rlvl = band->rlvl;
+ tcmpt = rlvl->tcmpt;
+rlvlno = rlvl - tcmpt->rlvls;
+ prcno = prc - band->prcs;
+ prcxind = prcno % rlvl->numhprcs;
+ prcyind = prcno / rlvl->numhprcs;
+ prc->band = band;
+
+tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn);
+tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn);
+if (!rlvlno) {
+ tlcbgtlx = tlprctlx;
+ tlcbgtly = tlprctly;
+} else {
+ tlcbgtlx = JPC_CEILDIVPOW2(tlprctlx, 1);
+ tlcbgtly = JPC_CEILDIVPOW2(tlprctly, 1);
+}
+
+ /* Compute the coordinates of the top-left and bottom-right
+ corners of the precinct. */
+ cbgtlx = tlcbgtlx + (prcxind << rlvl->cbgwidthexpn);
+ cbgtly = tlcbgtly + (prcyind << rlvl->cbgheightexpn);
+ prc->tlx = JAS_MAX(jas_seq2d_xstart(band->data), cbgtlx);
+ prc->tly = JAS_MAX(jas_seq2d_ystart(band->data), cbgtly);
+ prc->brx = JAS_MIN(jas_seq2d_xend(band->data), cbgtlx +
+ (1 << rlvl->cbgwidthexpn));
+ prc->bry = JAS_MIN(jas_seq2d_yend(band->data), cbgtly +
+ (1 << rlvl->cbgheightexpn));
+
+ if (prc->tlx < prc->brx && prc->tly < prc->bry) {
+ /* The precinct contains at least one code block. */
+
+ tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn);
+ tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn);
+ brcblkbrx = JPC_CEILTOMULTPOW2(prc->brx, rlvl->cblkwidthexpn);
+ brcblkbry = JPC_CEILTOMULTPOW2(prc->bry, rlvl->cblkheightexpn);
+ prc->numhcblks = JPC_FLOORDIVPOW2(brcblkbrx - tlcblktlx,
+ rlvl->cblkwidthexpn);
+ prc->numvcblks = JPC_FLOORDIVPOW2(brcblkbry - tlcblktly,
+ rlvl->cblkheightexpn);
+ prc->numcblks = prc->numhcblks * prc->numvcblks;
+
+ if (!(prc->incltree = jpc_tagtree_create(prc->numhcblks,
+ prc->numvcblks))) {
+ goto error;
+ }
+ if (!(prc->nlibtree = jpc_tagtree_create(prc->numhcblks,
+ prc->numvcblks))) {
+ goto error;
+ }
+ if (!(prc->savincltree = jpc_tagtree_create(prc->numhcblks,
+ prc->numvcblks))) {
+ goto error;
+ }
+ if (!(prc->savnlibtree = jpc_tagtree_create(prc->numhcblks,
+ prc->numvcblks))) {
+ goto error;
+ }
+
+ if (!(prc->cblks = jas_malloc(prc->numcblks * sizeof(jpc_enc_cblk_t)))) {
+ goto error;
+ }
+ for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
+ ++cblkno, ++cblk) {
+ cblk->passes = 0;
+ cblk->stream = 0;
+ cblk->mqenc = 0;
+ cblk->data = 0;
+ cblk->flags = 0;
+ cblk->prc = prc;
+ }
+ for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
+ ++cblkno, ++cblk) {
+ if (!cblk_create(cblk, cp, prc)) {
+ goto error;
+ }
+ }
+ } else {
+ /* The precinct does not contain any code blocks. */
+ prc->tlx = prc->brx;
+ prc->tly = prc->bry;
+ prc->numcblks = 0;
+ prc->numhcblks = 0;
+ prc->numvcblks = 0;
+ prc->cblks = 0;
+ prc->incltree = 0;
+ prc->nlibtree = 0;
+ prc->savincltree = 0;
+ prc->savnlibtree = 0;
+ }
+
+ return prc;
+
+error:
+ prc_destroy(prc);
+ return 0;
+}
+
+static void prc_destroy(jpc_enc_prc_t *prc)
+{
+ jpc_enc_cblk_t *cblk;
+ uint_fast32_t cblkno;
+
+ if (prc->cblks) {
+ for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
+ ++cblkno, ++cblk) {
+ cblk_destroy(cblk);
+ }
+ jas_free(prc->cblks);
+ }
+ if (prc->incltree) {
+ jpc_tagtree_destroy(prc->incltree);
+ }
+ if (prc->nlibtree) {
+ jpc_tagtree_destroy(prc->nlibtree);
+ }
+ if (prc->savincltree) {
+ jpc_tagtree_destroy(prc->savincltree);
+ }
+ if (prc->savnlibtree) {
+ jpc_tagtree_destroy(prc->savnlibtree);
+ }
+}
+
+static jpc_enc_cblk_t *cblk_create(jpc_enc_cblk_t *cblk, jpc_enc_cp_t *cp, jpc_enc_prc_t *prc)
+{
+ jpc_enc_band_t *band;
+ uint_fast32_t cblktlx;
+ uint_fast32_t cblktly;
+ uint_fast32_t cblkbrx;
+ uint_fast32_t cblkbry;
+ jpc_enc_rlvl_t *rlvl;
+ uint_fast32_t cblkxind;
+ uint_fast32_t cblkyind;
+ uint_fast32_t cblkno;
+ uint_fast32_t tlcblktlx;
+ uint_fast32_t tlcblktly;
+
+ cblkno = cblk - prc->cblks;
+ cblkxind = cblkno % prc->numhcblks;
+ cblkyind = cblkno / prc->numhcblks;
+ rlvl = prc->band->rlvl;
+ cblk->prc = prc;
+
+ cblk->numpasses = 0;
+ cblk->passes = 0;
+ cblk->numencpasses = 0;
+ cblk->numimsbs = 0;
+ cblk->numlenbits = 0;
+ cblk->stream = 0;
+ cblk->mqenc = 0;
+ cblk->flags = 0;
+ cblk->numbps = 0;
+ cblk->curpass = 0;
+ cblk->data = 0;
+ cblk->savedcurpass = 0;
+ cblk->savednumlenbits = 0;
+ cblk->savednumencpasses = 0;
+
+ band = prc->band;
+ tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn);
+ tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn);
+ cblktlx = JAS_MAX(tlcblktlx + (cblkxind << rlvl->cblkwidthexpn), prc->tlx);
+ cblktly = JAS_MAX(tlcblktly + (cblkyind << rlvl->cblkheightexpn), prc->tly);
+ cblkbrx = JAS_MIN(tlcblktlx + ((cblkxind + 1) << rlvl->cblkwidthexpn),
+ prc->brx);
+ cblkbry = JAS_MIN(tlcblktly + ((cblkyind + 1) << rlvl->cblkheightexpn),
+ prc->bry);
+
+ assert(cblktlx < cblkbrx && cblktly < cblkbry);
+ if (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) {
+ goto error;
+ }
+ jas_seq2d_bindsub(cblk->data, band->data, cblktlx, cblktly, cblkbrx, cblkbry);
+
+ return cblk;
+
+error:
+ cblk_destroy(cblk);
+ return 0;
+}
+
+static void cblk_destroy(jpc_enc_cblk_t *cblk)
+{
+ uint_fast16_t passno;
+ jpc_enc_pass_t *pass;
+ if (cblk->passes) {
+ for (passno = 0, pass = cblk->passes; passno < cblk->numpasses;
+ ++passno, ++pass) {
+ pass_destroy(pass);
+ }
+ jas_free(cblk->passes);
+ }
+ if (cblk->stream) {
+ jas_stream_close(cblk->stream);
+ }
+ if (cblk->mqenc) {
+ jpc_mqenc_destroy(cblk->mqenc);
+ }
+ if (cblk->data) {
+ jas_seq2d_destroy(cblk->data);
+ }
+ if (cblk->flags) {
+ jas_seq2d_destroy(cblk->flags);
+ }
+}
+
+static void pass_destroy(jpc_enc_pass_t *pass)
+{
+ /* XXX - need to free resources here */
+}
+
+void jpc_enc_dump(jpc_enc_t *enc)
+{
+ jpc_enc_tile_t *tile;
+ jpc_enc_tcmpt_t *tcmpt;
+ jpc_enc_rlvl_t *rlvl;
+ jpc_enc_band_t *band;
+ jpc_enc_prc_t *prc;
+ jpc_enc_cblk_t *cblk;
+ uint_fast16_t cmptno;
+ uint_fast16_t rlvlno;
+ uint_fast16_t bandno;
+ uint_fast32_t prcno;
+ uint_fast32_t cblkno;
+
+ tile = enc->curtile;
+
+ for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno,
+ ++tcmpt) {
+ jas_eprintf(" tcmpt %5d %5d %5d %5d\n", jas_seq2d_xstart(tcmpt->data), jas_seq2d_ystart(tcmpt->data), jas_seq2d_xend(tcmpt->data), jas_seq2d_yend(tcmpt->data));
+ for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
+ ++rlvlno, ++rlvl) {
+ jas_eprintf(" rlvl %5d %5d %5d %5d\n", rlvl->tlx, rlvl->tly, rlvl->brx, rlvl->bry);
+ for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
+ ++bandno, ++band) {
+ if (!band->data) {
+ continue;
+ }
+ jas_eprintf(" band %5d %5d %5d %5d\n", jas_seq2d_xstart(band->data), jas_seq2d_ystart(band->data), jas_seq2d_xend(band->data), jas_seq2d_yend(band->data));
+ for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
+ ++prcno, ++prc) {
+ jas_eprintf(" prc %5d %5d %5d %5d (%5d %5d)\n", prc->tlx, prc->tly, prc->brx, prc->bry, prc->brx - prc->tlx, prc->bry - prc->tly);
+ if (!prc->cblks) {
+ continue;
+ }
+ for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
+ ++cblkno, ++cblk) {
+ jas_eprintf(" cblk %5d %5d %5d %5d\n", jas_seq2d_xstart(cblk->data), jas_seq2d_ystart(cblk->data), jas_seq2d_xend(cblk->data), jas_seq2d_yend(cblk->data));
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_enc.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_enc.h
new file mode 100644
index 0000000..ce427fe
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_enc.h
@@ -0,0 +1,646 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef JPC_ENC_H
+#define JPC_ENC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_seq.h"
+
+#include "jpc_t2cod.h"
+#include "jpc_mqenc.h"
+#include "jpc_cod.h"
+#include "jpc_tagtree.h"
+#include "jpc_cs.h"
+#include "jpc_flt.h"
+#include "jpc_tsfb.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* The number of bits used in various lookup tables. */
+#define JPC_NUMEXTRABITS JPC_NMSEDEC_FRACBITS
+
+/* An invalid R-D slope value. */
+#define JPC_BADRDSLOPE (-1)
+
+/******************************************************************************\
+* Coding parameters types.
+\******************************************************************************/
+
+/* Per-component coding paramters. */
+
+typedef struct {
+
+ /* The horizontal sampling period. */
+ uint_fast8_t sampgrdstepx;
+
+ /* The vertical sampling period. */
+ uint_fast8_t sampgrdstepy;
+
+ /* The sample alignment horizontal offset. */
+ uint_fast8_t sampgrdsubstepx;
+
+ /* The sample alignment vertical offset. */
+ uint_fast8_t sampgrdsubstepy;
+
+ /* The precision of the samples. */
+ uint_fast8_t prec;
+
+ /* The signedness of the samples. */
+ bool sgnd;
+
+ /* The number of step sizes. */
+ uint_fast16_t numstepsizes;
+
+ /* The quantizer step sizes. */
+ uint_fast16_t stepsizes[JPC_MAXBANDS];
+
+} jpc_enc_ccp_t;
+
+/* Per-tile coding parameters. */
+
+typedef struct {
+
+ /* The coding mode. */
+ bool intmode;
+
+ /* The coding style (i.e., SOP, EPH). */
+ uint_fast8_t csty;
+
+ /* The progression order. */
+ uint_fast8_t prg;
+
+ /* The multicomponent transform. */
+ uint_fast8_t mctid;
+
+ /* The number of layers. */
+ uint_fast16_t numlyrs;
+
+ /* The normalized bit rates associated with the various
+ intermediate layers. */
+ jpc_fix_t *ilyrrates;
+
+} jpc_enc_tcp_t;
+
+/* Per tile-component coding parameters. */
+
+typedef struct {
+
+ /* The coding style (i.e., explicit precinct sizes). */
+ uint_fast8_t csty;
+
+ /* The maximum number of resolution levels allowed. */
+ uint_fast8_t maxrlvls;
+
+ /* The exponent for the nominal code block width. */
+ uint_fast16_t cblkwidthexpn;
+
+ /* The exponent for the nominal code block height. */
+ uint_fast16_t cblkheightexpn;
+
+ /* The code block style parameters (e.g., lazy, terminate all,
+ segmentation symbols, causal, reset probability models). */
+ uint_fast8_t cblksty;
+
+ /* The QMFB. */
+ uint_fast8_t qmfbid;
+
+ /* The precinct width values. */
+ uint_fast16_t prcwidthexpns[JPC_MAXRLVLS];
+
+ /* The precinct height values. */
+ uint_fast16_t prcheightexpns[JPC_MAXRLVLS];
+
+ /* The number of guard bits. */
+ uint_fast8_t numgbits;
+
+} jpc_enc_tccp_t;
+
+/* Coding parameters. */
+
+typedef struct {
+
+ /* The debug level. */
+ int debug;
+
+ /* The horizontal offset from the origin of the reference grid to the
+ left edge of the image area. */
+ uint_fast32_t imgareatlx;
+
+ /* The vertical offset from the origin of the reference grid to the
+ top edge of the image area. */
+ uint_fast32_t imgareatly;
+
+ /* The horizontal offset from the origin of the reference grid to the
+ right edge of the image area (plus one). */
+ uint_fast32_t refgrdwidth;
+
+ /* The vertical offset from the origin of the reference grid to the
+ bottom edge of the image area (plus one). */
+ uint_fast32_t refgrdheight;
+
+ /* The horizontal offset from the origin of the tile grid to the
+ origin of the reference grid. */
+ uint_fast32_t tilegrdoffx;
+
+ /* The vertical offset from the origin of the tile grid to the
+ origin of the reference grid. */
+ uint_fast32_t tilegrdoffy;
+
+ /* The nominal tile width in units of the image reference grid. */
+ uint_fast32_t tilewidth;
+
+ /* The nominal tile height in units of the image reference grid. */
+ uint_fast32_t tileheight;
+
+ /* The number of tiles spanning the image area in the horizontal
+ direction. */
+ uint_fast32_t numhtiles;
+
+ /* The number of tiles spanning the image area in the vertical
+ direction. */
+ uint_fast32_t numvtiles;
+
+ /* The number of tiles. */
+ uint_fast32_t numtiles;
+
+ /* The number of components. */
+ uint_fast16_t numcmpts;
+
+ /* The per-component coding parameters. */
+ jpc_enc_ccp_t *ccps;
+
+ /* The per-tile coding parameters. */
+ jpc_enc_tcp_t tcp;
+
+ /* The per-tile-component coding parameters. */
+ jpc_enc_tccp_t tccp;
+
+ /* The target code stream length in bytes. */
+ uint_fast32_t totalsize;
+
+ /* The raw (i.e., uncompressed) size of the image in bytes. */
+ uint_fast32_t rawsize;
+
+} jpc_enc_cp_t;
+
+/******************************************************************************\
+* Encoder class.
+\******************************************************************************/
+
+/* Encoder per-coding-pass state information. */
+
+typedef struct {
+
+ /* The starting offset for this pass. */
+ int start;
+
+ /* The ending offset for this pass. */
+ int end;
+
+ /* The type of data in this pass (i.e., MQ or raw). */
+ int type;
+
+ /* Flag indicating that this pass is terminated. */
+ int term;
+
+ /* The entropy coder state after coding this pass. */
+ jpc_mqencstate_t mqencstate;
+
+ /* The layer to which this pass has been assigned. */
+ int lyrno;
+
+ /* The R-D slope for this pass. */
+ jpc_flt_t rdslope;
+
+ /* The weighted MSE reduction associated with this pass. */
+ jpc_flt_t wmsedec;
+
+ /* The cumulative weighted MSE reduction. */
+ jpc_flt_t cumwmsedec;
+
+ /* The normalized MSE reduction. */
+ long nmsedec;
+
+} jpc_enc_pass_t;
+
+/* Encoder per-code-block state information. */
+
+typedef struct {
+
+ /* The number of passes. */
+ int numpasses;
+
+ /* The per-pass information. */
+ jpc_enc_pass_t *passes;
+
+ /* The number of passes encoded so far. */
+ int numencpasses;
+
+ /* The number of insignificant MSBs. */
+ int numimsbs;
+
+ /* The number of bits used to encode pass data lengths. */
+ int numlenbits;
+
+ /* The byte stream for this code block. */
+ jas_stream_t *stream;
+
+ /* The entropy encoder. */
+ jpc_mqenc_t *mqenc;
+
+ /* The data for this code block. */
+ jas_matrix_t *data;
+
+ /* The state for this code block. */
+ jas_matrix_t *flags;
+
+ /* The number of bit planes required for this code block. */
+ int numbps;
+
+ /* The next pass to be encoded. */
+ jpc_enc_pass_t *curpass;
+
+ /* The per-code-block-group state information. */
+ struct jpc_enc_prc_s *prc;
+
+ /* The saved current pass. */
+ /* This is used by the rate control code. */
+ jpc_enc_pass_t *savedcurpass;
+
+ /* The saved length indicator size. */
+ /* This is used by the rate control code. */
+ int savednumlenbits;
+
+ /* The saved number of encoded passes. */
+ /* This is used by the rate control code. */
+ int savednumencpasses;
+
+} jpc_enc_cblk_t;
+
+/* Encoder per-code-block-group state information. */
+
+typedef struct jpc_enc_prc_s {
+
+ /* The x-coordinate of the top-left corner of the precinct. */
+ uint_fast32_t tlx;
+
+ /* The y-coordinate of the top-left corner of the precinct. */
+ uint_fast32_t tly;
+
+ /* The x-coordinate of the bottom-right corner of the precinct
+ (plus one). */
+ uint_fast32_t brx;
+
+ /* The y-coordinate of the bottom-right corner of the precinct
+ (plus one). */
+ uint_fast32_t bry;
+
+ /* The number of code blocks spanning the precinct in the horizontal
+ direction. */
+ int numhcblks;
+
+ /* The number of code blocks spanning the precinct in the vertical
+ direction. */
+ int numvcblks;
+
+ /* The total number of code blocks. */
+ int numcblks;
+
+ /* The per-code-block information. */
+ jpc_enc_cblk_t *cblks;
+
+ /* The inclusion tag tree. */
+ jpc_tagtree_t *incltree;
+
+ /* The insignifcant MSBs tag tree. */
+ jpc_tagtree_t *nlibtree;
+
+ /* The per-band information. */
+ struct jpc_enc_band_s *band;
+
+ /* The saved inclusion tag tree. */
+ /* This is used by rate control. */
+ jpc_tagtree_t *savincltree;
+
+ /* The saved leading-insignificant-bit-planes tag tree. */
+ /* This is used by rate control. */
+ jpc_tagtree_t *savnlibtree;
+
+} jpc_enc_prc_t;
+
+/* Encoder per-band state information. */
+
+typedef struct jpc_enc_band_s {
+
+ /* The per precinct information. */
+ jpc_enc_prc_t *prcs;
+
+ /* The coefficient data for this band. */
+ jas_matrix_t *data;
+
+ /* The orientation of this band (i.e., LL, LH, HL, or HH). */
+ int orient;
+
+ /* The number of bit planes associated with this band. */
+ int numbps;
+
+ /* The quantizer step size. */
+ jpc_fix_t absstepsize;
+
+ /* The encoded quantizer step size. */
+ int stepsize;
+
+ /* The L2 norm of the synthesis basis functions associated with
+ this band. (The MCT is not considered in this value.) */
+ jpc_fix_t synweight;
+
+ /* The analysis gain for this band. */
+ int analgain;
+
+ /* The per-resolution-level information. */
+ struct jpc_enc_rlvl_s *rlvl;
+
+} jpc_enc_band_t;
+
+/* Encoder per-resolution-level state information. */
+
+typedef struct jpc_enc_rlvl_s {
+
+ /* The x-coordinate of the top-left corner of the tile-component
+ at this resolution. */
+ uint_fast32_t tlx;
+
+ /* The y-coordinate of the top-left corner of the tile-component
+ at this resolution. */
+ uint_fast32_t tly;
+
+ /* The x-coordinate of the bottom-right corner of the tile-component
+ at this resolution (plus one). */
+ uint_fast32_t brx;
+
+ /* The y-coordinate of the bottom-right corner of the tile-component
+ at this resolution (plus one). */
+ uint_fast32_t bry;
+
+ /* The exponent value for the nominal precinct width measured
+ relative to the associated LL band. */
+ int prcwidthexpn;
+
+ /* The exponent value for the nominal precinct height measured
+ relative to the associated LL band. */
+ int prcheightexpn;
+
+ /* The number of precincts spanning the resolution level in the
+ horizontal direction. */
+ int numhprcs;
+
+ /* The number of precincts spanning the resolution level in the
+ vertical direction. */
+ int numvprcs;
+
+ /* The total number of precincts. */
+ 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 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 height. */
+ uint_fast16_t cblkheightexpn;
+
+ /* The number of bands associated with this resolution level. */
+ int numbands;
+
+ /* The per-band information. */
+ jpc_enc_band_t *bands;
+
+ /* The parent tile-component. */
+ struct jpc_enc_tcmpt_s *tcmpt;
+
+} jpc_enc_rlvl_t;
+
+/* Encoder per-tile-component state information. */
+
+typedef struct jpc_enc_tcmpt_s {
+
+ /* The number of resolution levels. */
+ int numrlvls;
+
+ /* The per-resolution-level information. */
+ jpc_enc_rlvl_t *rlvls;
+
+ /* The tile-component data. */
+ jas_matrix_t *data;
+
+ /* The QMFB. */
+ int qmfbid;
+
+ /* The number of bands. */
+ int numbands;
+
+ /* The TSFB. */
+ jpc_tsfb_t *tsfb;
+
+ /* The synthesis energy weight (for the MCT). */
+ jpc_fix_t synweight;
+
+ /* The precinct width exponents. */
+ int prcwidthexpns[JPC_MAXRLVLS];
+
+ /* The precinct height exponents. */
+ int prcheightexpns[JPC_MAXRLVLS];
+
+ /* The code block width exponent. */
+ int cblkwidthexpn;
+
+ /* The code block height exponent. */
+ int cblkheightexpn;
+
+ /* Coding style (i.e., explicit precinct sizes). */
+ int csty;
+
+ /* Code block style. */
+ int cblksty;
+
+ /* The number of quantizer step sizes. */
+ int numstepsizes;
+
+ /* The encoded quantizer step sizes. */
+ uint_fast16_t stepsizes[JPC_MAXBANDS];
+
+ /* The parent tile. */
+ struct jpc_enc_tile_s *tile;
+
+} jpc_enc_tcmpt_t;
+
+/* Encoder per-tile state information. */
+
+typedef struct jpc_enc_tile_s {
+
+ /* The tile number. */
+ uint_fast32_t tileno;
+
+ /* The x-coordinate of the top-left corner of the tile measured with
+ respect to the reference grid. */
+ uint_fast32_t tlx;
+
+ /* The y-coordinate of the top-left corner of the tile measured with
+ respect to the reference grid. */
+ uint_fast32_t tly;
+
+ /* The x-coordinate of the bottom-right corner of the tile measured
+ with respect to the reference grid (plus one). */
+ uint_fast32_t brx;
+
+ /* The y-coordinate of the bottom-right corner of the tile measured
+ with respect to the reference grid (plus one). */
+ uint_fast32_t bry;
+
+ /* The coding style. */
+ uint_fast8_t csty;
+
+ /* The progression order. */
+ uint_fast8_t prg;
+
+ /* The number of layers. */
+ int numlyrs;
+
+ /* The MCT to employ (if any). */
+ uint_fast8_t mctid;
+
+ /* The packet iterator (used to determine the order of packet
+ generation). */
+ jpc_pi_t *pi;
+
+ /* The coding mode (i.e., integer or real). */
+ bool intmode;
+
+ /* The number of bytes to allocate to the various layers. */
+ uint_fast32_t *lyrsizes;
+
+ /* The number of tile-components. */
+ int numtcmpts;
+
+ /* The per tile-component information. */
+ jpc_enc_tcmpt_t *tcmpts;
+
+ /* The raw (i.e., uncompressed) size of this tile. */
+ uint_fast32_t rawsize;
+
+} jpc_enc_tile_t;
+
+/* Encoder class. */
+
+typedef struct jpc_enc_s {
+
+ /* The image being encoded. */
+ jas_image_t *image;
+
+ /* The output stream. */
+ jas_stream_t *out;
+
+ /* The coding parameters. */
+ jpc_enc_cp_t *cp;
+
+ /* The tile currently being processed. */
+ jpc_enc_tile_t *curtile;
+
+ /* The code stream state. */
+ jpc_cstate_t *cstate;
+
+ /* The number of bytes output so far. */
+ uint_fast32_t len;
+
+ /* The number of bytes available for the main body of the code stream. */
+ /* This is used for rate allocation purposes. */
+ uint_fast32_t mainbodysize;
+
+ /* The marker segment currently being processed. */
+ /* This member is a convenience for making cleanup easier. */
+ jpc_ms_t *mrk;
+
+ /* The stream used to temporarily hold tile-part data. */
+ jas_stream_t *tmpstream;
+
+} jpc_enc_t;
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_fix.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_fix.h
new file mode 100644
index 0000000..34f8d80
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_fix.h
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Fixed-Point Number Class
+ *
+ * $Id$
+ */
+
+#ifndef JPC_FIX_H
+#define JPC_FIX_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_fix.h"
+
+/******************************************************************************\
+* Basic parameters of the fixed-point type.
+\******************************************************************************/
+
+/* The integral type used to represent a fixed-point number. This
+ type must be capable of representing values from -(2^31) to 2^31-1
+ (inclusive). */
+typedef int_fast32_t jpc_fix_t;
+
+/* The integral type used to respresent higher-precision intermediate results.
+ This type should be capable of representing values from -(2^63) to 2^63-1
+ (inclusive). */
+typedef int_fast64_t jpc_fix_big_t;
+
+/* The number of bits used for the fractional part of a fixed-point number. */
+#define JPC_FIX_FRACBITS 13
+
+/******************************************************************************\
+* Instantiations of the generic fixed-point number macros for the
+* parameters given above. (Too bad C does not support templates, eh?)
+* The purpose of these macros is self-evident if one examines the
+* corresponding macros in the jasper/jas_fix.h header file.
+\******************************************************************************/
+
+#define JPC_FIX_ZERO JAS_FIX_ZERO(jpc_fix_t, JPC_FIX_FRACBITS)
+#define JPC_FIX_ONE JAS_FIX_ONE(jpc_fix_t, JPC_FIX_FRACBITS)
+#define JPC_FIX_HALF JAS_FIX_HALF(jpc_fix_t, JPC_FIX_FRACBITS)
+
+#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)
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_flt.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_flt.h
new file mode 100644
index 0000000..119465f
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_flt.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Floating-Point Class
+ *
+ * $Id$
+ */
+
+#ifndef JPC_FLT_H
+#define JPC_FLT_H
+
+#include <float.h>
+
+/* The code ought to be modified so this type is not used at all. */
+/* Very few places in the code rely on floating-point arithmetic, aside
+ from conversions in printf's. */
+typedef double jpc_flt_t;
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_math.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_math.c
new file mode 100644
index 0000000..2b70844
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_math.c
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Math Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+#include "jpc_math.h"
+
+/******************************************************************************\
+* Miscellaneous Functions
+\******************************************************************************/
+
+/* Calculate the integer quantity floor(log2(x)), where x is a positive
+ integer. */
+int jpc_floorlog2(int x)
+{
+ int y;
+
+ /* The argument must be positive. */
+ assert(x > 0);
+
+ y = 0;
+ while (x > 1) {
+ x >>= 1;
+ ++y;
+ }
+ return y;
+}
+
+/* Calculate the bit position of the first leading one in a nonnegative
+ integer. */
+/* This function is the basically the same as ceillog2(x), except that the
+ allowable range for x is slightly different. */
+int jpc_firstone(int x)
+{
+ int n;
+
+ /* The argument must be nonnegative. */
+ assert(x >= 0);
+
+ n = -1;
+ while (x > 0) {
+ x >>= 1;
+ ++n;
+ }
+ return n;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_math.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_math.h
new file mode 100644
index 0000000..e8e0978
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_math.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef JPC_MATH_H
+#define JPC_MATH_H
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+#include <assert.h>
+
+/******************************************************************************\
+* Macros
+\******************************************************************************/
+
+/* Compute the floor of the quotient of two integers. */
+#define JPC_FLOORDIV(x, y) ((x) / (y))
+
+/* Compute the ceiling of the quotient of two integers. */
+#define JPC_CEILDIV(x, y) (((x) + (y) - 1) / (y))
+
+/* Compute the floor of (x / 2^y). */
+#define JPC_FLOORDIVPOW2(x, y) ((x) >> (y))
+
+/* Compute the ceiling of (x / 2^y). */
+#define JPC_CEILDIVPOW2(x, y) (((x) + (1 << (y)) - 1) >> (y))
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Calculate the bit position of the first leading one in a nonnegative
+ integer. */
+int jpc_firstone(int x);
+
+/* Calculate the integer quantity floor(log2(x)), where x is a positive
+ integer. */
+int jpc_floorlog2(int x);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mct.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mct.c
new file mode 100644
index 0000000..2545022
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mct.c
@@ -0,0 +1,291 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Multicomponent Transform Code
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+
+#include "jasper/jas_seq.h"
+
+#include "jpc_fix.h"
+#include "jpc_mct.h"
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+/* Compute the forward RCT. */
+
+void jpc_rct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2)
+{
+ int numrows;
+ int numcols;
+ int i;
+ int j;
+ jpc_fix_t *c0p;
+ jpc_fix_t *c1p;
+ jpc_fix_t *c2p;
+
+ numrows = jas_matrix_numrows(c0);
+ numcols = jas_matrix_numcols(c0);
+
+ /* All three matrices must have the same dimensions. */
+ assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numcols(c1) == numcols
+ && jas_matrix_numrows(c2) == numrows && jas_matrix_numcols(c2) == numcols);
+
+ for (i = 0; i < numrows; i++) {
+ c0p = jas_matrix_getref(c0, i, 0);
+ c1p = jas_matrix_getref(c1, i, 0);
+ c2p = jas_matrix_getref(c2, i, 0);
+ for (j = numcols; j > 0; --j) {
+ int r;
+ int g;
+ int b;
+ int y;
+ int u;
+ int v;
+ r = *c0p;
+ g = *c1p;
+ b = *c2p;
+ y = (r + (g << 1) + b) >> 2;
+ u = b - g;
+ v = r - g;
+ *c0p++ = y;
+ *c1p++ = u;
+ *c2p++ = v;
+ }
+ }
+}
+
+/* Compute the inverse RCT. */
+
+void jpc_irct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2)
+{
+ int numrows;
+ int numcols;
+ int i;
+ int j;
+ jpc_fix_t *c0p;
+ jpc_fix_t *c1p;
+ jpc_fix_t *c2p;
+
+ numrows = jas_matrix_numrows(c0);
+ numcols = jas_matrix_numcols(c0);
+
+ /* All three matrices must have the same dimensions. */
+ assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numcols(c1) == numcols
+ && jas_matrix_numrows(c2) == numrows && jas_matrix_numcols(c2) == numcols);
+
+ for (i = 0; i < numrows; i++) {
+ c0p = jas_matrix_getref(c0, i, 0);
+ c1p = jas_matrix_getref(c1, i, 0);
+ c2p = jas_matrix_getref(c2, i, 0);
+ for (j = numcols; j > 0; --j) {
+ int r;
+ int g;
+ int b;
+ int y;
+ int u;
+ int v;
+ y = *c0p;
+ u = *c1p;
+ v = *c2p;
+ g = y - ((u + v) >> 2);
+ r = v + g;
+ b = u + g;
+ *c0p++ = r;
+ *c1p++ = g;
+ *c2p++ = b;
+ }
+ }
+}
+
+void jpc_ict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2)
+{
+ int numrows;
+ int numcols;
+ int i;
+ int j;
+ jpc_fix_t r;
+ jpc_fix_t g;
+ jpc_fix_t b;
+ jpc_fix_t y;
+ jpc_fix_t u;
+ jpc_fix_t v;
+ jpc_fix_t *c0p;
+ jpc_fix_t *c1p;
+ jpc_fix_t *c2p;
+
+ numrows = jas_matrix_numrows(c0);
+ assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numrows(c2) == numrows);
+ numcols = jas_matrix_numcols(c0);
+ assert(jas_matrix_numcols(c1) == numcols && jas_matrix_numcols(c2) == numcols);
+ for (i = 0; i < numrows; ++i) {
+ c0p = jas_matrix_getref(c0, i, 0);
+ c1p = jas_matrix_getref(c1, i, 0);
+ c2p = jas_matrix_getref(c2, i, 0);
+ for (j = numcols; j > 0; --j) {
+ r = *c0p;
+ g = *c1p;
+ b = *c2p;
+ y = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(0.299), r), jpc_fix_mul(jpc_dbltofix(0.587), g),
+ jpc_fix_mul(jpc_dbltofix(0.114), b));
+ u = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(-0.16875), r), jpc_fix_mul(jpc_dbltofix(-0.33126), g),
+ jpc_fix_mul(jpc_dbltofix(0.5), b));
+ v = jpc_fix_add3(jpc_fix_mul(jpc_dbltofix(0.5), r), jpc_fix_mul(jpc_dbltofix(-0.41869), g),
+ jpc_fix_mul(jpc_dbltofix(-0.08131), b));
+ *c0p++ = y;
+ *c1p++ = u;
+ *c2p++ = v;
+ }
+ }
+}
+
+void jpc_iict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2)
+{
+ int numrows;
+ int numcols;
+ int i;
+ int j;
+ jpc_fix_t r;
+ jpc_fix_t g;
+ jpc_fix_t b;
+ jpc_fix_t y;
+ jpc_fix_t u;
+ jpc_fix_t v;
+ jpc_fix_t *c0p;
+ jpc_fix_t *c1p;
+ jpc_fix_t *c2p;
+
+ numrows = jas_matrix_numrows(c0);
+ assert(jas_matrix_numrows(c1) == numrows && jas_matrix_numrows(c2) == numrows);
+ numcols = jas_matrix_numcols(c0);
+ assert(jas_matrix_numcols(c1) == numcols && jas_matrix_numcols(c2) == numcols);
+ for (i = 0; i < numrows; ++i) {
+ c0p = jas_matrix_getref(c0, i, 0);
+ c1p = jas_matrix_getref(c1, i, 0);
+ c2p = jas_matrix_getref(c2, i, 0);
+ for (j = numcols; j > 0; --j) {
+ y = *c0p;
+ u = *c1p;
+ v = *c2p;
+ r = jpc_fix_add(y, jpc_fix_mul(jpc_dbltofix(1.402), v));
+ g = jpc_fix_add3(y, jpc_fix_mul(jpc_dbltofix(-0.34413), u),
+ jpc_fix_mul(jpc_dbltofix(-0.71414), v));
+ b = jpc_fix_add(y, jpc_fix_mul(jpc_dbltofix(1.772), u));
+ *c0p++ = r;
+ *c1p++ = g;
+ *c2p++ = b;
+ }
+ }
+}
+
+jpc_fix_t jpc_mct_getsynweight(int mctid, int cmptno)
+{
+ jpc_fix_t synweight;
+
+ synweight = JPC_FIX_ONE;
+ 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;
+#if 0
+ default:
+ synweight = JPC_FIX_ONE;
+ break;
+#endif
+ }
+
+ return synweight;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mct.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mct.h
new file mode 100644
index 0000000..8a564e9
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mct.h
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Multicomponent Transform Code
+ *
+ * $Id$
+ */
+
+#ifndef JPC_MCT_H
+#define JPC_MCT_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_seq.h"
+#include "jasper/jas_fix.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/*
+ * Multicomponent transform IDs.
+ */
+
+#define JPC_MCT_NONE 0
+#define JPC_MCT_ICT 1
+#define JPC_MCT_RCT 2
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Calculate the forward RCT. */
+void jpc_rct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2);
+
+/* Calculate the inverse RCT. */
+void jpc_irct(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2);
+
+/* Calculate the forward ICT. */
+void jpc_ict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2);
+
+/* Calculate the inverse ICT. */
+void jpc_iict(jas_matrix_t *c0, jas_matrix_t *c1, jas_matrix_t *c2);
+
+/* Get the synthesis weight associated with a particular component. */
+jpc_fix_t jpc_mct_getsynweight(int mctid, int cmptno);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqcod.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqcod.c
new file mode 100644
index 0000000..ed56f8d
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqcod.c
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * MQ Arithmetic Coder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_malloc.h"
+
+#include "jpc_mqcod.h"
+
+/******************************************************************************\
+* Data.
+\******************************************************************************/
+
+/* 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]},
+};
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqcod.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqcod.h
new file mode 100644
index 0000000..eb44353
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqcod.h
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * MQ Arithmetic Coder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_MQCOD_H
+#define JPC_MQCOD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/*
+ * MQ coder context information.
+ */
+
+typedef struct {
+
+ /* The most probable symbol (MPS). */
+ int mps;
+
+ /* The state index. */
+ int_fast16_t ind;
+
+} jpc_mqctx_t;
+
+/*
+ * MQ coder state table entry.
+ */
+
+typedef struct jpc_mqstate_s {
+
+ /* The Qe value. */
+ uint_fast16_t qeval;
+
+ /* The MPS. */
+ int mps;
+
+ /* The NMPS state. */
+ struct jpc_mqstate_s *nmps;
+
+ /* The NLPS state. */
+ struct jpc_mqstate_s *nlps;
+
+} jpc_mqstate_t;
+
+/******************************************************************************\
+* Data.
+\******************************************************************************/
+
+/* The state table for the MQ coder. */
+extern jpc_mqstate_t jpc_mqstates[];
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqdec.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqdec.c
new file mode 100644
index 0000000..4806699
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqdec.c
@@ -0,0 +1,306 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * MQ Arithmetic Decoder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+
+#include "jpc_mqdec.h"
+
+/******************************************************************************\
+* Local macros.
+\******************************************************************************/
+
+#if defined(DEBUG)
+#define MQDEC_CALL(n, x) \
+ ((jas_getdbglevel() >= (n)) ? ((void)(x)) : ((void)0))
+#else
+#define MQDEC_CALL(n, x)
+#endif
+
+/******************************************************************************\
+* Local function prototypes.
+\******************************************************************************/
+
+static void jpc_mqdec_bytein(jpc_mqdec_t *mqdec);
+
+/******************************************************************************\
+* Code for creation and destruction of a MQ decoder.
+\******************************************************************************/
+
+/* Create a MQ decoder. */
+jpc_mqdec_t *jpc_mqdec_create(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;
+
+error:
+ /* Oops... Something has gone wrong. */
+ if (mqdec) {
+ jpc_mqdec_destroy(mqdec);
+ }
+ return 0;
+}
+
+/* Destroy a MQ decoder. */
+void jpc_mqdec_destroy(jpc_mqdec_t *mqdec)
+{
+ if (mqdec->ctxs) {
+ jas_free(mqdec->ctxs);
+ }
+ jas_free(mqdec);
+}
+
+/******************************************************************************\
+* Code for initialization of a MQ decoder.
+\******************************************************************************/
+
+/* Initialize the state of a MQ decoder. */
+
+void jpc_mqdec_init(jpc_mqdec_t *mqdec)
+{
+ int c;
+
+ mqdec->eof = 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;
+}
+
+/* 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;
+ }
+}
+
+/* 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];
+}
+
+/******************************************************************************\
+* Code for decoding a bit.
+\******************************************************************************/
+
+/* Decode a bit. */
+
+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;
+}
+
+/* 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;
+}
+
+/* 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;
+}
+
+/******************************************************************************\
+* Support code.
+\******************************************************************************/
+
+/* Apply the BYTEIN algorithm. */
+static void jpc_mqdec_bytein(jpc_mqdec_t *mqdec)
+{
+ int c;
+ unsigned char prevbuf;
+
+ if (!mqdec->eof) {
+ if ((c = jas_stream_getc(mqdec->in)) == EOF) {
+ mqdec->eof = 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;
+ }
+}
+
+/******************************************************************************\
+* Code for debugging.
+\******************************************************************************/
+
+/* Dump a MQ decoder to a stream for debugging. */
+
+void jpc_mqdec_dump(jpc_mqdec_t *mqdec, FILE *out)
+{
+ fprintf(out, "MQDEC A = %08lx, C = %08lx, CT=%08lx, ",
+ (unsigned long) mqdec->areg, (unsigned long) mqdec->creg,
+ (unsigned long) mqdec->ctreg);
+ fprintf(out, "CTX = %d, ", (int)(mqdec->curctx - mqdec->ctxs));
+ fprintf(out, "IND %d, MPS %d, QEVAL %x\n", (int)(*mqdec->curctx -
+ jpc_mqstates), (*mqdec->curctx)->mps, (*mqdec->curctx)->qeval);
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqdec.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqdec.h
new file mode 100644
index 0000000..05bf735
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqdec.h
@@ -0,0 +1,271 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * MQ Arithmetic Decoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_MQDEC_H
+#define JPC_MQDEC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_stream.h"
+
+#include "jpc_mqcod.h"
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* MQ arithmetic decoder. */
+
+typedef struct {
+
+ /* The C register. */
+ uint_fast32_t creg;
+
+ /* The A register. */
+ uint_fast32_t areg;
+
+ /* The CT register. */
+ uint_fast32_t ctreg;
+
+ /* The current context. */
+ jpc_mqstate_t **curctx;
+
+ /* The per-context information. */
+ jpc_mqstate_t **ctxs;
+
+ /* The maximum number of contexts. */
+ int maxctxs;
+
+ /* The stream from which to read data. */
+ jas_stream_t *in;
+
+ /* The last character read. */
+ uchar inbuffer;
+
+ /* The EOF indicator. */
+ int eof;
+
+} jpc_mqdec_t;
+
+/******************************************************************************\
+* Functions/macros for construction and destruction.
+\******************************************************************************/
+
+/* Create a MQ decoder. */
+jpc_mqdec_t *jpc_mqdec_create(int maxctxs, jas_stream_t *in);
+
+/* Destroy a MQ decoder. */
+void jpc_mqdec_destroy(jpc_mqdec_t *dec);
+
+/******************************************************************************\
+* Functions/macros for initialization.
+\******************************************************************************/
+
+/* Set the input stream associated with a MQ decoder. */
+void jpc_mqdec_setinput(jpc_mqdec_t *dec, jas_stream_t *in);
+
+/* Initialize a MQ decoder. */
+void jpc_mqdec_init(jpc_mqdec_t *dec);
+
+/******************************************************************************\
+* Functions/macros for manipulating contexts.
+\******************************************************************************/
+
+/* Set the current context for a MQ decoder. */
+#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);
+
+/* Set the state information for all contexts of a MQ decoder. */
+void jpc_mqdec_setctxs(jpc_mqdec_t *dec, int numctxs, jpc_mqctx_t *ctxs);
+
+/******************************************************************************\
+* Functions/macros for decoding bits.
+\******************************************************************************/
+
+/* Decode a symbol. */
+#if !defined(DEBUG)
+#define jpc_mqdec_getbit(dec) \
+ jpc_mqdec_getbit_macro(dec)
+#else
+#define jpc_mqdec_getbit(dec) \
+ jpc_mqdec_getbit_func(dec)
+#endif
+
+/* Decode a symbol (assuming an unskewed probability distribution). */
+#if !defined(DEBUG)
+#define jpc_mqdec_getbitnoskew(dec) \
+ jpc_mqdec_getbit_macro(dec)
+#else
+#define jpc_mqdec_getbitnoskew(dec) \
+ jpc_mqdec_getbit_func(dec)
+#endif
+
+/******************************************************************************\
+* Functions/macros for debugging.
+\******************************************************************************/
+
+/* Dump the MQ decoder state for debugging. */
+void jpc_mqdec_dump(jpc_mqdec_t *dec, FILE *out);
+
+/******************************************************************************\
+* EVERYTHING BELOW THIS POINT IS IMPLEMENTATION SPECIFIC AND NOT PART OF THE
+* APPLICATION INTERFACE. DO NOT RELY ON ANY OF THE INTERNAL FUNCTIONS/MACROS
+* GIVEN BELOW.
+\******************************************************************************/
+
+#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) \
+{ \
+ 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) \
+{ \
+ 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) \
+{ \
+ 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) \
+{ \
+ 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);
+int jpc_mqdec_mpsexchrenormd(jpc_mqdec_t *dec);
+int jpc_mqdec_lpsexchrenormd(jpc_mqdec_t *dec);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqenc.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqenc.c
new file mode 100644
index 0000000..7e0c99d
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqenc.c
@@ -0,0 +1,392 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * MQ Arithmetic Encoder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include "jasper/jas_stream.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+
+#include "jpc_mqenc.h"
+
+/******************************************************************************\
+* Macros
+\******************************************************************************/
+
+#if defined(DEBUG)
+#define JPC_MQENC_CALL(n, x) \
+ ((jas_getdbglevel() >= (n)) ? ((void)(x)) : ((void)0))
+#else
+#define JPC_MQENC_CALL(n, x)
+#endif
+
+#define jpc_mqenc_codemps9(areg, creg, ctreg, curctx, enc) \
+{ \
+ jpc_mqstate_t *state = *(curctx); \
+ (areg) -= state->qeval; \
+ if (!((areg) & 0x8000)) { \
+ if ((areg) < state->qeval) { \
+ (areg) = state->qeval; \
+ } else { \
+ (creg) += state->qeval; \
+ } \
+ *(curctx) = state->nmps; \
+ jpc_mqenc_renorme((areg), (creg), (ctreg), (enc)); \
+ } else { \
+ (creg) += state->qeval; \
+ } \
+}
+
+#define jpc_mqenc_codelps2(areg, creg, ctreg, curctx, enc) \
+{ \
+ jpc_mqstate_t *state = *(curctx); \
+ (areg) -= state->qeval; \
+ if ((areg) < state->qeval) { \
+ (creg) += state->qeval; \
+ } else { \
+ (areg) = state->qeval; \
+ } \
+ *(curctx) = state->nlps; \
+ jpc_mqenc_renorme((areg), (creg), (ctreg), (enc)); \
+}
+
+#define jpc_mqenc_renorme(areg, creg, ctreg, enc) \
+{ \
+ do { \
+ (areg) <<= 1; \
+ (creg) <<= 1; \
+ if (!--(ctreg)) { \
+ jpc_mqenc_byteout((areg), (creg), (ctreg), (enc)); \
+ } \
+ } while (!((areg) & 0x8000)); \
+}
+
+#define jpc_mqenc_byteout(areg, creg, ctreg, enc) \
+{ \
+ if ((enc)->outbuf != 0xff) { \
+ if ((creg) & 0x8000000) { \
+ if (++((enc)->outbuf) == 0xff) { \
+ (creg) &= 0x7ffffff; \
+ jpc_mqenc_byteout2(enc); \
+ enc->outbuf = ((creg) >> 20) & 0xff; \
+ (creg) &= 0xfffff; \
+ (ctreg) = 7; \
+ } else { \
+ jpc_mqenc_byteout2(enc); \
+ enc->outbuf = ((creg) >> 19) & 0xff; \
+ (creg) &= 0x7ffff; \
+ (ctreg) = 8; \
+ } \
+ } else { \
+ jpc_mqenc_byteout2(enc); \
+ (enc)->outbuf = ((creg) >> 19) & 0xff; \
+ (creg) &= 0x7ffff; \
+ (ctreg) = 8; \
+ } \
+ } else { \
+ jpc_mqenc_byteout2(enc); \
+ (enc)->outbuf = ((creg) >> 20) & 0xff; \
+ (creg) &= 0xfffff; \
+ (ctreg) = 7; \
+ } \
+}
+
+#define jpc_mqenc_byteout2(enc) \
+{ \
+ if (enc->outbuf >= 0) { \
+ if (jas_stream_putc(enc->out, (unsigned char)enc->outbuf) == EOF) { \
+ enc->err |= 1; \
+ } \
+ } \
+ enc->lastbyte = enc->outbuf; \
+}
+
+/******************************************************************************\
+* Local function protoypes.
+\******************************************************************************/
+
+static void jpc_mqenc_setbits(jpc_mqenc_t *mqenc);
+
+/******************************************************************************\
+* Code for creation and destruction of encoder.
+\******************************************************************************/
+
+/* Create a MQ encoder. */
+
+jpc_mqenc_t *jpc_mqenc_create(int maxctxs, jas_stream_t *out)
+{
+ jpc_mqenc_t *mqenc;
+
+ /* Allocate memory for the MQ encoder. */
+ if (!(mqenc = jas_malloc(sizeof(jpc_mqenc_t)))) {
+ goto error;
+ }
+ mqenc->out = out;
+ mqenc->maxctxs = maxctxs;
+
+ /* Allocate memory for the per-context state information. */
+ if (!(mqenc->ctxs = jas_malloc(mqenc->maxctxs * sizeof(jpc_mqstate_t *)))) {
+ goto error;
+ }
+
+ /* Set the current context to the first one. */
+ mqenc->curctx = mqenc->ctxs;
+
+ jpc_mqenc_init(mqenc);
+
+ /* Initialize the per-context state information to something sane. */
+ jpc_mqenc_setctxs(mqenc, 0, 0);
+
+ return mqenc;
+
+error:
+ if (mqenc) {
+ jpc_mqenc_destroy(mqenc);
+ }
+ return 0;
+}
+
+/* Destroy a MQ encoder. */
+
+void jpc_mqenc_destroy(jpc_mqenc_t *mqenc)
+{
+ if (mqenc->ctxs) {
+ jas_free(mqenc->ctxs);
+ }
+ jas_free(mqenc);
+}
+
+/******************************************************************************\
+* State initialization code.
+\******************************************************************************/
+
+/* Initialize the coding state of a MQ encoder. */
+
+void jpc_mqenc_init(jpc_mqenc_t *mqenc)
+{
+ mqenc->areg = 0x8000;
+ mqenc->outbuf = -1;
+ mqenc->creg = 0;
+ mqenc->ctreg = 12;
+ mqenc->lastbyte = -1;
+ mqenc->err = 0;
+}
+
+/* Initialize one or more contexts. */
+
+void jpc_mqenc_setctxs(jpc_mqenc_t *mqenc, int numctxs, jpc_mqctx_t *ctxs)
+{
+ jpc_mqstate_t **ctx;
+ int n;
+
+ ctx = mqenc->ctxs;
+ n = JAS_MIN(mqenc->maxctxs, numctxs);
+ while (--n >= 0) {
+ *ctx = &jpc_mqstates[2 * ctxs->ind + ctxs->mps];
+ ++ctx;
+ ++ctxs;
+ }
+ n = mqenc->maxctxs - numctxs;
+ while (--n >= 0) {
+ *ctx = &jpc_mqstates[0];
+ ++ctx;
+ }
+
+}
+
+/* Get the coding state for a MQ encoder. */
+
+void jpc_mqenc_getstate(jpc_mqenc_t *mqenc, jpc_mqencstate_t *state)
+{
+ state->areg = mqenc->areg;
+ state->creg = mqenc->creg;
+ state->ctreg = mqenc->ctreg;
+ state->lastbyte = mqenc->lastbyte;
+}
+
+/******************************************************************************\
+* Code for coding symbols.
+\******************************************************************************/
+
+/* Encode a bit. */
+
+int jpc_mqenc_putbit_func(jpc_mqenc_t *mqenc, int bit)
+{
+ const jpc_mqstate_t *state;
+ JAS_DBGLOG(100, ("jpc_mqenc_putbit(%p, %d)\n", mqenc, bit));
+ JPC_MQENC_CALL(100, jpc_mqenc_dump(mqenc, stderr));
+
+ state = *(mqenc->curctx);
+
+ if (state->mps == bit) {
+ /* Apply the CODEMPS algorithm as defined in the standard. */
+ mqenc->areg -= state->qeval;
+ if (!(mqenc->areg & 0x8000)) {
+ jpc_mqenc_codemps2(mqenc);
+ } else {
+ mqenc->creg += state->qeval;
+ }
+ } else {
+ /* Apply the CODELPS algorithm as defined in the standard. */
+ jpc_mqenc_codelps2(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc->curctx, mqenc);
+ }
+
+ return jpc_mqenc_error(mqenc) ? (-1) : 0;
+}
+
+int jpc_mqenc_codemps2(jpc_mqenc_t *mqenc)
+{
+ /* Note: This function only performs part of the work associated with
+ the CODEMPS algorithm from the standard. Some of the work is also
+ performed by the caller. */
+
+ jpc_mqstate_t *state = *(mqenc->curctx);
+ if (mqenc->areg < state->qeval) {
+ mqenc->areg = state->qeval;
+ } else {
+ mqenc->creg += state->qeval;
+ }
+ *mqenc->curctx = state->nmps;
+ jpc_mqenc_renorme(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc);
+ return jpc_mqenc_error(mqenc) ? (-1) : 0;
+}
+
+int jpc_mqenc_codelps(jpc_mqenc_t *mqenc)
+{
+ jpc_mqenc_codelps2(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc->curctx, mqenc);
+ return jpc_mqenc_error(mqenc) ? (-1) : 0;
+}
+
+/******************************************************************************\
+* Miscellaneous code.
+\******************************************************************************/
+
+/* Terminate the code word. */
+
+int jpc_mqenc_flush(jpc_mqenc_t *mqenc, int termmode)
+{
+ int_fast16_t k;
+
+ switch (termmode) {
+ case JPC_MQENC_PTERM:
+ k = 11 - mqenc->ctreg + 1;
+ while (k > 0) {
+ mqenc->creg <<= mqenc->ctreg;
+ mqenc->ctreg = 0;
+ jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg,
+ mqenc);
+ k -= mqenc->ctreg;
+ }
+ if (mqenc->outbuf != 0xff) {
+ jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc);
+ }
+ break;
+ case JPC_MQENC_DEFTERM:
+ jpc_mqenc_setbits(mqenc);
+ mqenc->creg <<= mqenc->ctreg;
+ jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc);
+ mqenc->creg <<= mqenc->ctreg;
+ jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc);
+ if (mqenc->outbuf != 0xff) {
+ jpc_mqenc_byteout(mqenc->areg, mqenc->creg, mqenc->ctreg, mqenc);
+ }
+ break;
+ default:
+ abort();
+ break;
+ }
+ return 0;
+}
+
+static void jpc_mqenc_setbits(jpc_mqenc_t *mqenc)
+{
+ uint_fast32_t tmp = mqenc->creg + mqenc->areg;
+ mqenc->creg |= 0xffff;
+ if (mqenc->creg >= tmp) {
+ mqenc->creg -= 0x8000;
+ }
+}
+
+/* Dump a MQ encoder to a stream for debugging. */
+
+int jpc_mqenc_dump(jpc_mqenc_t *mqenc, FILE *out)
+{
+ fprintf(out, "AREG = %08x, CREG = %08x, CTREG = %d\n",
+ mqenc->areg, mqenc->creg, mqenc->ctreg);
+ fprintf(out, "IND = %02d, MPS = %d, QEVAL = %04x\n",
+ (int)(*mqenc->curctx - jpc_mqstates), (*mqenc->curctx)->mps,
+ (*mqenc->curctx)->qeval);
+ return 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqenc.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqenc.h
new file mode 100644
index 0000000..dff1190
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_mqenc.h
@@ -0,0 +1,236 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * MQ Arithmetic Encoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_MQENC_H
+#define JPC_MQENC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_stream.h"
+
+#include "jpc_mqcod.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/*
+ * Termination modes.
+ */
+
+#define JPC_MQENC_DEFTERM 0 /* default termination */
+#define JPC_MQENC_PTERM 1 /* predictable termination */
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* MQ arithmetic encoder class. */
+
+typedef struct {
+
+ /* The C register. */
+ uint_fast32_t creg;
+
+ /* The A register. */
+ uint_fast32_t areg;
+
+ /* The CT register. */
+ uint_fast32_t ctreg;
+
+ /* The maximum number of contexts. */
+ int maxctxs;
+
+ /* The per-context information. */
+ jpc_mqstate_t **ctxs;
+
+ /* The current context. */
+ jpc_mqstate_t **curctx;
+
+ /* The stream for encoder output. */
+ jas_stream_t *out;
+
+ /* The byte buffer (i.e., the B variable in the standard). */
+ int_fast16_t outbuf;
+
+ /* The last byte output. */
+ int_fast16_t lastbyte;
+
+ /* The error indicator. */
+ int err;
+
+} jpc_mqenc_t;
+
+/* MQ arithmetic encoder state information. */
+
+typedef struct {
+
+ /* The A register. */
+ unsigned areg;
+
+ /* The C register. */
+ unsigned creg;
+
+ /* The CT register. */
+ unsigned ctreg;
+
+ /* The last byte output by the encoder. */
+ int lastbyte;
+
+} jpc_mqencstate_t;
+
+/******************************************************************************\
+* Functions/macros for construction and destruction.
+\******************************************************************************/
+
+/* Create a MQ encoder. */
+jpc_mqenc_t *jpc_mqenc_create(int maxctxs, jas_stream_t *out);
+
+/* Destroy a MQ encoder. */
+void jpc_mqenc_destroy(jpc_mqenc_t *enc);
+
+/******************************************************************************\
+* Functions/macros for initialization.
+\******************************************************************************/
+
+/* Initialize a MQ encoder. */
+void jpc_mqenc_init(jpc_mqenc_t *enc);
+
+/******************************************************************************\
+* Functions/macros for context manipulation.
+\******************************************************************************/
+
+/* Set the current context. */
+#define jpc_mqenc_setcurctx(enc, ctxno) \
+ ((enc)->curctx = &(enc)->ctxs[ctxno]);
+
+/* Set the state information for a particular context. */
+void jpc_mqenc_setctx(jpc_mqenc_t *enc, int ctxno, jpc_mqctx_t *ctx);
+
+/* Set the state information for multiple contexts. */
+void jpc_mqenc_setctxs(jpc_mqenc_t *enc, int numctxs, jpc_mqctx_t *ctxs);
+
+/******************************************************************************\
+* Miscellaneous functions/macros.
+\******************************************************************************/
+
+/* Get the error state of a MQ encoder. */
+#define jpc_mqenc_error(enc) \
+ ((enc)->err)
+
+/* Get the current encoder state. */
+void jpc_mqenc_getstate(jpc_mqenc_t *enc, jpc_mqencstate_t *state);
+
+/* Terminate the code. */
+int jpc_mqenc_flush(jpc_mqenc_t *enc, int termmode);
+
+/******************************************************************************\
+* Functions/macros for encoding bits.
+\******************************************************************************/
+
+/* Encode a bit. */
+#if !defined(DEBUG)
+#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)
+#endif
+
+/******************************************************************************\
+* Functions/macros for debugging.
+\******************************************************************************/
+
+int jpc_mqenc_dump(jpc_mqenc_t *mqenc, FILE *out);
+
+/******************************************************************************\
+* Implementation-specific details.
+\******************************************************************************/
+
+/* 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))
+
+/* Note: These function prototypes are included only to satisfy the
+ needs of the mqenc_putbit_macro macro. Do not call any of these
+ functions directly. */
+int jpc_mqenc_codemps2(jpc_mqenc_t *enc);
+int jpc_mqenc_codelps(jpc_mqenc_t *enc);
+
+/* Note: This function prototype is included only to satisfy the needs of
+ the mqenc_putbit macro. */
+int jpc_mqenc_putbit_func(jpc_mqenc_t *enc, int bit);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_qmfb.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_qmfb.c
new file mode 100644
index 0000000..00d406d
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_qmfb.c
@@ -0,0 +1,3144 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Quadrature Mirror-Image Filter Bank (QMFB) Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+#undef WT_LENONE /* This is not needed due to normalization. */
+#define WT_DOSCALE
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+#include "jasper/jas_fix.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+
+#include "jpc_qmfb.h"
+#include "jpc_tsfb.h"
+#include "jpc_math.h"
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+#define QMFB_SPLITBUFSIZE 4096
+#define QMFB_JOINBUFSIZE 4096
+
+int jpc_ft_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+ int stride);
+int jpc_ft_synthesize(int *a, int xstart, int ystart, int width, int height,
+ int stride);
+
+int jpc_ns_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+ int stride);
+int jpc_ns_synthesize(jpc_fix_t *a, int xstart, int ystart, int width,
+ int height, int stride);
+
+void jpc_ft_fwdlift_row(jpc_fix_t *a, int numcols, int parity);
+void jpc_ft_fwdlift_col(jpc_fix_t *a, int numrows, int stride,
+ int parity);
+void jpc_ft_fwdlift_colgrp(jpc_fix_t *a, int numrows, int stride,
+ int parity);
+void jpc_ft_fwdlift_colres(jpc_fix_t *a, int numrows, int numcols,
+ int stride, int parity);
+
+void jpc_ft_invlift_row(jpc_fix_t *a, int numcols, int parity);
+void jpc_ft_invlift_col(jpc_fix_t *a, int numrows, int stride,
+ int parity);
+void jpc_ft_invlift_colgrp(jpc_fix_t *a, int numrows, int stride,
+ int parity);
+void jpc_ft_invlift_colres(jpc_fix_t *a, int numrows, int numcols,
+ int stride, int parity);
+
+void jpc_ns_fwdlift_row(jpc_fix_t *a, int numcols, int parity);
+void jpc_ns_fwdlift_colgrp(jpc_fix_t *a, int numrows, int stride, int parity);
+void jpc_ns_fwdlift_colres(jpc_fix_t *a, int numrows, int numcols, int stride,
+ int parity);
+void jpc_ns_invlift_row(jpc_fix_t *a, int numcols, int parity);
+void jpc_ns_invlift_colgrp(jpc_fix_t *a, int numrows, int stride, int parity);
+void jpc_ns_invlift_colres(jpc_fix_t *a, int numrows, int numcols, int stride,
+ int parity);
+
+void jpc_qmfb_split_row(jpc_fix_t *a, int numcols, int parity);
+void jpc_qmfb_split_col(jpc_fix_t *a, int numrows, int stride, int parity);
+void jpc_qmfb_split_colgrp(jpc_fix_t *a, int numrows, int stride, int parity);
+void jpc_qmfb_split_colres(jpc_fix_t *a, int numrows, int numcols, int stride,
+ int parity);
+
+void jpc_qmfb_join_row(jpc_fix_t *a, int numcols, int parity);
+void jpc_qmfb_join_col(jpc_fix_t *a, int numrows, int stride, int parity);
+void jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride, int parity);
+void jpc_qmfb_join_colres(jpc_fix_t *a, int numrows, int numcols, int stride,
+ int parity);
+
+double jpc_ft_lpenergywts[32] = {
+ 1.2247448713915889,
+ 1.6583123951776999,
+ 2.3184046238739260,
+ 3.2691742076555053,
+ 4.6199296531440819,
+ 6.5323713152269596,
+ 9.2377452606141937,
+ 13.0639951297449581,
+ 18.4752262333915667,
+ 26.1278968190610392,
+ 36.9504194305524791,
+ 52.2557819580462777,
+ 73.9008347315741645,
+ 104.5115624560829133,
+ 147.8016689469569656,
+ 209.0231247296646018,
+ 295.6033378293900000,
+ 418.0462494347059419,
+ 591.2066756503630813,
+ 836.0924988714708661,
+ /* approximations */
+ 836.0924988714708661,
+ 836.0924988714708661,
+ 836.0924988714708661,
+ 836.0924988714708661,
+ 836.0924988714708661,
+ 836.0924988714708661,
+ 836.0924988714708661,
+ 836.0924988714708661,
+ 836.0924988714708661,
+ 836.0924988714708661,
+ 836.0924988714708661,
+ 836.0924988714708661
+};
+
+double jpc_ft_hpenergywts[32] = {
+ 0.8477912478906585,
+ 0.9601432184835760,
+ 1.2593401049756179,
+ 1.7444107171191079,
+ 2.4538713036750726,
+ 3.4656517695088755,
+ 4.8995276398597856,
+ 6.9283970402160842,
+ 9.7980274940131444,
+ 13.8564306871112652,
+ 19.5959265076535587,
+ 27.7128159494245487,
+ 39.1918369552045860,
+ 55.4256262207444053,
+ 78.3836719028959124,
+ 110.8512517317256822,
+ 156.7673435548526868,
+ 221.7025033739244293,
+ 313.5346870787551552,
+ 443.4050067351659550,
+ /* approximations */
+ 443.4050067351659550,
+ 443.4050067351659550,
+ 443.4050067351659550,
+ 443.4050067351659550,
+ 443.4050067351659550,
+ 443.4050067351659550,
+ 443.4050067351659550,
+ 443.4050067351659550,
+ 443.4050067351659550,
+ 443.4050067351659550,
+ 443.4050067351659550,
+ 443.4050067351659550
+};
+
+double jpc_ns_lpenergywts[32] = {
+ 1.4021081679297411,
+ 2.0303718560817923,
+ 2.9011625562785555,
+ 4.1152851751758002,
+ 5.8245108637728071,
+ 8.2387599345725171,
+ 11.6519546479210838,
+ 16.4785606470644375,
+ 23.3042776444606794,
+ 32.9572515613740435,
+ 46.6086013487782793,
+ 65.9145194076860861,
+ 93.2172084551803977,
+ 131.8290408510004283,
+ 186.4344176300625691,
+ 263.6580819564562148,
+ 372.8688353500955373,
+ 527.3161639447193920,
+ 745.7376707114038936,
+ 1054.6323278917823245,
+ /* approximations follow */
+ 1054.6323278917823245,
+ 1054.6323278917823245,
+ 1054.6323278917823245,
+ 1054.6323278917823245,
+ 1054.6323278917823245,
+ 1054.6323278917823245,
+ 1054.6323278917823245,
+ 1054.6323278917823245,
+ 1054.6323278917823245,
+ 1054.6323278917823245,
+ 1054.6323278917823245,
+ 1054.6323278917823245
+};
+
+double jpc_ns_hpenergywts[32] = {
+ 1.4425227650161456,
+ 1.9669426082455688,
+ 2.8839248082788891,
+ 4.1475208393432981,
+ 5.8946497530677817,
+ 8.3471789178590949,
+ 11.8086046551047463,
+ 16.7012780415647804,
+ 23.6196657032246620,
+ 33.4034255108592362,
+ 47.2396388881632632,
+ 66.8069597416714061,
+ 94.4793162154500692,
+ 133.6139330736999113,
+ 188.9586372358249378,
+ 267.2278678461869390,
+ 377.9172750722391356,
+ 534.4557359047058753,
+ 755.8345502191498326,
+ 1068.9114718353569060,
+ /* approximations follow */
+ 1068.9114718353569060,
+ 1068.9114718353569060,
+ 1068.9114718353569060,
+ 1068.9114718353569060,
+ 1068.9114718353569060,
+ 1068.9114718353569060,
+ 1068.9114718353569060,
+ 1068.9114718353569060,
+ 1068.9114718353569060,
+ 1068.9114718353569060,
+ 1068.9114718353569060
+};
+
+jpc_qmfb2d_t jpc_ft_qmfb2d = {
+ jpc_ft_analyze,
+ jpc_ft_synthesize,
+ jpc_ft_lpenergywts,
+ jpc_ft_hpenergywts
+};
+
+jpc_qmfb2d_t jpc_ns_qmfb2d = {
+ jpc_ns_analyze,
+ jpc_ns_synthesize,
+ jpc_ns_lpenergywts,
+ jpc_ns_hpenergywts
+};
+
+/******************************************************************************\
+* generic
+\******************************************************************************/
+
+void jpc_qmfb_split_row(jpc_fix_t *a, int numcols, int parity)
+{
+
+ int bufsize = JPC_CEILDIVPOW2(numcols, 1);
+#if !defined(HAVE_VLA)
+ jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE];
+#else
+ jpc_fix_t splitbuf[bufsize];
+#endif
+ jpc_fix_t *buf = splitbuf;
+ register jpc_fix_t *srcptr;
+ register jpc_fix_t *dstptr;
+ register int n;
+ register int m;
+ int hstartcol;
+
+#if !defined(HAVE_VLA)
+ /* Get a buffer. */
+ if (bufsize > QMFB_SPLITBUFSIZE) {
+ if (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) {
+ /* We have no choice but to commit suicide in this case. */
+ abort();
+ }
+ }
+#endif
+
+ if (numcols >= 2) {
+ hstartcol = (numcols + 1 - parity) >> 1;
+ m = (parity) ? hstartcol : (numcols - hstartcol);
+ /* Save the samples destined for the highpass channel. */
+ n = m;
+ dstptr = buf;
+ srcptr = &a[1 - parity];
+ while (n-- > 0) {
+ *dstptr = *srcptr;
+ ++dstptr;
+ srcptr += 2;
+ }
+ /* Copy the appropriate samples into the lowpass channel. */
+ dstptr = &a[1 - parity];
+ srcptr = &a[2 - parity];
+ n = numcols - m - (!parity);
+ while (n-- > 0) {
+ *dstptr = *srcptr;
+ ++dstptr;
+ srcptr += 2;
+ }
+ /* Copy the saved samples into the highpass channel. */
+ dstptr = &a[hstartcol];
+ srcptr = buf;
+ n = m;
+ while (n-- > 0) {
+ *dstptr = *srcptr;
+ ++dstptr;
+ ++srcptr;
+ }
+ }
+
+#if !defined(HAVE_VLA)
+ /* If the split buffer was allocated on the heap, free this memory. */
+ if (buf != splitbuf) {
+ jas_free(buf);
+ }
+#endif
+
+}
+
+void jpc_qmfb_split_col(jpc_fix_t *a, int numrows, int stride,
+ int parity)
+{
+
+ int bufsize = JPC_CEILDIVPOW2(numrows, 1);
+#if !defined(HAVE_VLA)
+ jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE];
+#else
+ jpc_fix_t splitbuf[bufsize];
+#endif
+ jpc_fix_t *buf = splitbuf;
+ register jpc_fix_t *srcptr;
+ register jpc_fix_t *dstptr;
+ register int n;
+ register int m;
+ int hstartcol;
+
+#if !defined(HAVE_VLA)
+ /* Get a buffer. */
+ if (bufsize > QMFB_SPLITBUFSIZE) {
+ if (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) {
+ /* We have no choice but to commit suicide in this case. */
+ abort();
+ }
+ }
+#endif
+
+ if (numrows >= 2) {
+ hstartcol = (numrows + 1 - parity) >> 1;
+ m = (parity) ? hstartcol : (numrows - hstartcol);
+ /* Save the samples destined for the highpass channel. */
+ n = m;
+ dstptr = buf;
+ srcptr = &a[(1 - parity) * stride];
+ while (n-- > 0) {
+ *dstptr = *srcptr;
+ ++dstptr;
+ srcptr += stride << 1;
+ }
+ /* Copy the appropriate samples into the lowpass channel. */
+ dstptr = &a[(1 - parity) * stride];
+ srcptr = &a[(2 - parity) * stride];
+ n = numrows - m - (!parity);
+ while (n-- > 0) {
+ *dstptr = *srcptr;
+ dstptr += stride;
+ srcptr += stride << 1;
+ }
+ /* Copy the saved samples into the highpass channel. */
+ dstptr = &a[hstartcol * stride];
+ srcptr = buf;
+ n = m;
+ while (n-- > 0) {
+ *dstptr = *srcptr;
+ dstptr += stride;
+ ++srcptr;
+ }
+ }
+
+#if !defined(HAVE_VLA)
+ /* If the split buffer was allocated on the heap, free this memory. */
+ if (buf != splitbuf) {
+ jas_free(buf);
+ }
+#endif
+
+}
+
+void jpc_qmfb_split_colgrp(jpc_fix_t *a, int numrows, int stride,
+ int parity)
+{
+
+ int bufsize = JPC_CEILDIVPOW2(numrows, 1);
+#if !defined(HAVE_VLA)
+ jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
+#else
+ jpc_fix_t splitbuf[bufsize * JPC_QMFB_COLGRPSIZE];
+#endif
+ jpc_fix_t *buf = splitbuf;
+ jpc_fix_t *srcptr;
+ jpc_fix_t *dstptr;
+ register jpc_fix_t *srcptr2;
+ register jpc_fix_t *dstptr2;
+ register int n;
+ register int i;
+ int m;
+ int hstartcol;
+
+#if !defined(HAVE_VLA)
+ /* Get a buffer. */
+ if (bufsize > QMFB_SPLITBUFSIZE) {
+ if (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) {
+ /* We have no choice but to commit suicide in this case. */
+ abort();
+ }
+ }
+#endif
+
+ if (numrows >= 2) {
+ hstartcol = (numrows + 1 - parity) >> 1;
+ m = (parity) ? hstartcol : (numrows - hstartcol);
+ /* Save the samples destined for the highpass channel. */
+ n = m;
+ dstptr = buf;
+ srcptr = &a[(1 - parity) * stride];
+ while (n-- > 0) {
+ dstptr2 = dstptr;
+ srcptr2 = srcptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ *dstptr2 = *srcptr2;
+ ++dstptr2;
+ ++srcptr2;
+ }
+ dstptr += JPC_QMFB_COLGRPSIZE;
+ srcptr += stride << 1;
+ }
+ /* Copy the appropriate samples into the lowpass channel. */
+ dstptr = &a[(1 - parity) * stride];
+ srcptr = &a[(2 - parity) * stride];
+ n = numrows - m - (!parity);
+ while (n-- > 0) {
+ dstptr2 = dstptr;
+ srcptr2 = srcptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ *dstptr2 = *srcptr2;
+ ++dstptr2;
+ ++srcptr2;
+ }
+ dstptr += stride;
+ srcptr += stride << 1;
+ }
+ /* Copy the saved samples into the highpass channel. */
+ dstptr = &a[hstartcol * stride];
+ srcptr = buf;
+ n = m;
+ while (n-- > 0) {
+ dstptr2 = dstptr;
+ srcptr2 = srcptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ *dstptr2 = *srcptr2;
+ ++dstptr2;
+ ++srcptr2;
+ }
+ dstptr += stride;
+ srcptr += JPC_QMFB_COLGRPSIZE;
+ }
+ }
+
+#if !defined(HAVE_VLA)
+ /* If the split buffer was allocated on the heap, free this memory. */
+ if (buf != splitbuf) {
+ jas_free(buf);
+ }
+#endif
+
+}
+
+void jpc_qmfb_split_colres(jpc_fix_t *a, int numrows, int numcols,
+ int stride, int parity)
+{
+
+ int bufsize = JPC_CEILDIVPOW2(numrows, 1);
+#if !defined(HAVE_VLA)
+ jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
+#else
+ jpc_fix_t splitbuf[bufsize * numcols];
+#endif
+ jpc_fix_t *buf = splitbuf;
+ jpc_fix_t *srcptr;
+ jpc_fix_t *dstptr;
+ register jpc_fix_t *srcptr2;
+ register jpc_fix_t *dstptr2;
+ register int n;
+ register int i;
+ int m;
+ int hstartcol;
+
+#if !defined(HAVE_VLA)
+ /* Get a buffer. */
+ if (bufsize > QMFB_SPLITBUFSIZE) {
+ if (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) {
+ /* We have no choice but to commit suicide in this case. */
+ abort();
+ }
+ }
+#endif
+
+ if (numrows >= 2) {
+ hstartcol = (numrows + 1 - parity) >> 1;
+ m = (parity) ? hstartcol : (numrows - hstartcol);
+ /* Save the samples destined for the highpass channel. */
+ n = m;
+ dstptr = buf;
+ srcptr = &a[(1 - parity) * stride];
+ while (n-- > 0) {
+ dstptr2 = dstptr;
+ srcptr2 = srcptr;
+ for (i = 0; i < numcols; ++i) {
+ *dstptr2 = *srcptr2;
+ ++dstptr2;
+ ++srcptr2;
+ }
+ dstptr += numcols;
+ srcptr += stride << 1;
+ }
+ /* Copy the appropriate samples into the lowpass channel. */
+ dstptr = &a[(1 - parity) * stride];
+ srcptr = &a[(2 - parity) * stride];
+ n = numrows - m - (!parity);
+ while (n-- > 0) {
+ dstptr2 = dstptr;
+ srcptr2 = srcptr;
+ for (i = 0; i < numcols; ++i) {
+ *dstptr2 = *srcptr2;
+ ++dstptr2;
+ ++srcptr2;
+ }
+ dstptr += stride;
+ srcptr += stride << 1;
+ }
+ /* Copy the saved samples into the highpass channel. */
+ dstptr = &a[hstartcol * stride];
+ srcptr = buf;
+ n = m;
+ while (n-- > 0) {
+ dstptr2 = dstptr;
+ srcptr2 = srcptr;
+ for (i = 0; i < numcols; ++i) {
+ *dstptr2 = *srcptr2;
+ ++dstptr2;
+ ++srcptr2;
+ }
+ dstptr += stride;
+ srcptr += numcols;
+ }
+ }
+
+#if !defined(HAVE_VLA)
+ /* If the split buffer was allocated on the heap, free this memory. */
+ if (buf != splitbuf) {
+ jas_free(buf);
+ }
+#endif
+
+}
+
+void jpc_qmfb_join_row(jpc_fix_t *a, int numcols, int parity)
+{
+
+ int bufsize = JPC_CEILDIVPOW2(numcols, 1);
+#if !defined(HAVE_VLA)
+ jpc_fix_t joinbuf[QMFB_JOINBUFSIZE];
+#else
+ jpc_fix_t joinbuf[bufsize];
+#endif
+ jpc_fix_t *buf = joinbuf;
+ register jpc_fix_t *srcptr;
+ register jpc_fix_t *dstptr;
+ register int n;
+ int hstartcol;
+
+#if !defined(HAVE_VLA)
+ /* Allocate memory for the join buffer from the heap. */
+ if (bufsize > QMFB_JOINBUFSIZE) {
+ if (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) {
+ /* We have no choice but to commit suicide. */
+ abort();
+ }
+ }
+#endif
+
+ hstartcol = (numcols + 1 - parity) >> 1;
+
+ /* Save the samples from the lowpass channel. */
+ n = hstartcol;
+ srcptr = &a[0];
+ dstptr = buf;
+ while (n-- > 0) {
+ *dstptr = *srcptr;
+ ++srcptr;
+ ++dstptr;
+ }
+ /* Copy the samples from the highpass channel into place. */
+ srcptr = &a[hstartcol];
+ dstptr = &a[1 - parity];
+ n = numcols - hstartcol;
+ while (n-- > 0) {
+ *dstptr = *srcptr;
+ dstptr += 2;
+ ++srcptr;
+ }
+ /* Copy the samples from the lowpass channel into place. */
+ srcptr = buf;
+ dstptr = &a[parity];
+ n = hstartcol;
+ while (n-- > 0) {
+ *dstptr = *srcptr;
+ dstptr += 2;
+ ++srcptr;
+ }
+
+#if !defined(HAVE_VLA)
+ /* If the join buffer was allocated on the heap, free this memory. */
+ if (buf != joinbuf) {
+ jas_free(buf);
+ }
+#endif
+
+}
+
+void jpc_qmfb_join_col(jpc_fix_t *a, int numrows, int stride,
+ int parity)
+{
+
+ int bufsize = JPC_CEILDIVPOW2(numrows, 1);
+#if !defined(HAVE_VLA)
+ jpc_fix_t joinbuf[QMFB_JOINBUFSIZE];
+#else
+ jpc_fix_t joinbuf[bufsize];
+#endif
+ jpc_fix_t *buf = joinbuf;
+ register jpc_fix_t *srcptr;
+ register jpc_fix_t *dstptr;
+ register int n;
+ int hstartcol;
+
+#if !defined(HAVE_VLA)
+ /* Allocate memory for the join buffer from the heap. */
+ if (bufsize > QMFB_JOINBUFSIZE) {
+ if (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) {
+ /* We have no choice but to commit suicide. */
+ abort();
+ }
+ }
+#endif
+
+ hstartcol = (numrows + 1 - parity) >> 1;
+
+ /* Save the samples from the lowpass channel. */
+ n = hstartcol;
+ srcptr = &a[0];
+ dstptr = buf;
+ while (n-- > 0) {
+ *dstptr = *srcptr;
+ srcptr += stride;
+ ++dstptr;
+ }
+ /* Copy the samples from the highpass channel into place. */
+ srcptr = &a[hstartcol * stride];
+ dstptr = &a[(1 - parity) * stride];
+ n = numrows - hstartcol;
+ while (n-- > 0) {
+ *dstptr = *srcptr;
+ dstptr += 2 * stride;
+ srcptr += stride;
+ }
+ /* Copy the samples from the lowpass channel into place. */
+ srcptr = buf;
+ dstptr = &a[parity * stride];
+ n = hstartcol;
+ while (n-- > 0) {
+ *dstptr = *srcptr;
+ dstptr += 2 * stride;
+ ++srcptr;
+ }
+
+#if !defined(HAVE_VLA)
+ /* If the join buffer was allocated on the heap, free this memory. */
+ if (buf != joinbuf) {
+ jas_free(buf);
+ }
+#endif
+
+}
+
+void jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride,
+ int parity)
+{
+
+ int bufsize = JPC_CEILDIVPOW2(numrows, 1);
+#if !defined(HAVE_VLA)
+ jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE];
+#else
+ jpc_fix_t joinbuf[bufsize * JPC_QMFB_COLGRPSIZE];
+#endif
+ jpc_fix_t *buf = joinbuf;
+ jpc_fix_t *srcptr;
+ jpc_fix_t *dstptr;
+ register jpc_fix_t *srcptr2;
+ register jpc_fix_t *dstptr2;
+ register int n;
+ register int i;
+ int hstartcol;
+
+#if !defined(HAVE_VLA)
+ /* Allocate memory for the join buffer from the heap. */
+ if (bufsize > QMFB_JOINBUFSIZE) {
+ if (!(buf = jas_malloc(bufsize * JPC_QMFB_COLGRPSIZE * sizeof(jpc_fix_t)))) {
+ /* We have no choice but to commit suicide. */
+ abort();
+ }
+ }
+#endif
+
+ hstartcol = (numrows + 1 - parity) >> 1;
+
+ /* Save the samples from the lowpass channel. */
+ n = hstartcol;
+ srcptr = &a[0];
+ dstptr = buf;
+ while (n-- > 0) {
+ dstptr2 = dstptr;
+ srcptr2 = srcptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ *dstptr2 = *srcptr2;
+ ++dstptr2;
+ ++srcptr2;
+ }
+ srcptr += stride;
+ dstptr += JPC_QMFB_COLGRPSIZE;
+ }
+ /* Copy the samples from the highpass channel into place. */
+ srcptr = &a[hstartcol * stride];
+ dstptr = &a[(1 - parity) * stride];
+ n = numrows - hstartcol;
+ while (n-- > 0) {
+ dstptr2 = dstptr;
+ srcptr2 = srcptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ *dstptr2 = *srcptr2;
+ ++dstptr2;
+ ++srcptr2;
+ }
+ dstptr += 2 * stride;
+ srcptr += stride;
+ }
+ /* Copy the samples from the lowpass channel into place. */
+ srcptr = buf;
+ dstptr = &a[parity * stride];
+ n = hstartcol;
+ while (n-- > 0) {
+ dstptr2 = dstptr;
+ srcptr2 = srcptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ *dstptr2 = *srcptr2;
+ ++dstptr2;
+ ++srcptr2;
+ }
+ dstptr += 2 * stride;
+ srcptr += JPC_QMFB_COLGRPSIZE;
+ }
+
+#if !defined(HAVE_VLA)
+ /* If the join buffer was allocated on the heap, free this memory. */
+ if (buf != joinbuf) {
+ jas_free(buf);
+ }
+#endif
+
+}
+
+void jpc_qmfb_join_colres(jpc_fix_t *a, int numrows, int numcols,
+ int stride, int parity)
+{
+
+ int bufsize = JPC_CEILDIVPOW2(numrows, 1);
+#if !defined(HAVE_VLA)
+ jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE];
+#else
+ jpc_fix_t joinbuf[bufsize * numcols];
+#endif
+ jpc_fix_t *buf = joinbuf;
+ jpc_fix_t *srcptr;
+ jpc_fix_t *dstptr;
+ register jpc_fix_t *srcptr2;
+ register jpc_fix_t *dstptr2;
+ register int n;
+ register int i;
+ int hstartcol;
+
+#if !defined(HAVE_VLA)
+ /* Allocate memory for the join buffer from the heap. */
+ if (bufsize > QMFB_JOINBUFSIZE) {
+ if (!(buf = jas_malloc(bufsize * numcols * sizeof(jpc_fix_t)))) {
+ /* We have no choice but to commit suicide. */
+ abort();
+ }
+ }
+#endif
+
+ hstartcol = (numrows + 1 - parity) >> 1;
+
+ /* Save the samples from the lowpass channel. */
+ n = hstartcol;
+ srcptr = &a[0];
+ dstptr = buf;
+ while (n-- > 0) {
+ dstptr2 = dstptr;
+ srcptr2 = srcptr;
+ for (i = 0; i < numcols; ++i) {
+ *dstptr2 = *srcptr2;
+ ++dstptr2;
+ ++srcptr2;
+ }
+ srcptr += stride;
+ dstptr += numcols;
+ }
+ /* Copy the samples from the highpass channel into place. */
+ srcptr = &a[hstartcol * stride];
+ dstptr = &a[(1 - parity) * stride];
+ n = numrows - hstartcol;
+ while (n-- > 0) {
+ dstptr2 = dstptr;
+ srcptr2 = srcptr;
+ for (i = 0; i < numcols; ++i) {
+ *dstptr2 = *srcptr2;
+ ++dstptr2;
+ ++srcptr2;
+ }
+ dstptr += 2 * stride;
+ srcptr += stride;
+ }
+ /* Copy the samples from the lowpass channel into place. */
+ srcptr = buf;
+ dstptr = &a[parity * stride];
+ n = hstartcol;
+ while (n-- > 0) {
+ dstptr2 = dstptr;
+ srcptr2 = srcptr;
+ for (i = 0; i < numcols; ++i) {
+ *dstptr2 = *srcptr2;
+ ++dstptr2;
+ ++srcptr2;
+ }
+ dstptr += 2 * stride;
+ srcptr += numcols;
+ }
+
+#if !defined(HAVE_VLA)
+ /* If the join buffer was allocated on the heap, free this memory. */
+ if (buf != joinbuf) {
+ jas_free(buf);
+ }
+#endif
+
+}
+
+/******************************************************************************\
+* 5/3 transform
+\******************************************************************************/
+
+void jpc_ft_fwdlift_row(jpc_fix_t *a, int numcols, int parity)
+{
+
+ register jpc_fix_t *lptr;
+ register jpc_fix_t *hptr;
+ register int n;
+ int llen;
+
+ llen = (numcols + 1 - parity) >> 1;
+
+ if (numcols > 1) {
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen];
+ if (parity) {
+ hptr[0] -= lptr[0];
+ ++hptr;
+ }
+ n = numcols - llen - parity - (parity == (numcols & 1));
+ while (n-- > 0) {
+ hptr[0] -= (lptr[0] + lptr[1]) >> 1;
+ ++hptr;
+ ++lptr;
+ }
+ if (parity == (numcols & 1)) {
+ hptr[0] -= lptr[0];
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen];
+ if (!parity) {
+ lptr[0] += (hptr[0] + 1) >> 1;
+ ++lptr;
+ }
+ n = llen - (!parity) - (parity != (numcols & 1));
+ while (n-- > 0) {
+ lptr[0] += (hptr[0] + hptr[1] + 2) >> 2;
+ ++lptr;
+ ++hptr;
+ }
+ if (parity != (numcols & 1)) {
+ lptr[0] += (hptr[0] + 1) >> 1;
+ }
+
+ } else {
+
+ if (parity) {
+ lptr = &a[0];
+ lptr[0] <<= 1;
+ }
+
+ }
+
+}
+
+void jpc_ft_fwdlift_col(jpc_fix_t *a, int numrows, int stride, int parity)
+{
+
+ jpc_fix_t *lptr;
+ jpc_fix_t *hptr;
+#if 0
+ register jpc_fix_t *lptr2;
+ register jpc_fix_t *hptr2;
+ register int i;
+#endif
+ register int n;
+ int llen;
+
+ llen = (numrows + 1 - parity) >> 1;
+
+ if (numrows > 1) {
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ hptr[0] -= lptr[0];
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ hptr[0] -= (lptr[0] + lptr[stride]) >> 1;
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ hptr[0] -= lptr[0];
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr[0] += (hptr[0] + 1) >> 1;
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr[0] += (hptr[0] + hptr[stride] + 2) >> 2;
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr[0] += (hptr[0] + 1) >> 1;
+ }
+
+ } else {
+
+ if (parity) {
+ lptr = &a[0];
+ lptr[0] <<= 1;
+ }
+
+ }
+
+}
+
+void jpc_ft_fwdlift_colgrp(jpc_fix_t *a, int numrows, int stride, int parity)
+{
+
+ jpc_fix_t *lptr;
+ jpc_fix_t *hptr;
+ register jpc_fix_t *lptr2;
+ register jpc_fix_t *hptr2;
+ register int n;
+ register int i;
+ int llen;
+
+ llen = (numrows + 1 - parity) >> 1;
+
+ if (numrows > 1) {
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ hptr2[0] -= lptr2[0];
+ ++hptr2;
+ ++lptr2;
+ }
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ hptr2[0] -= (lptr2[0] + lptr2[stride]) >> 1;
+ ++lptr2;
+ ++hptr2;
+ }
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ hptr2[0] -= lptr2[0];
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ lptr2[0] += (hptr2[0] + 1) >> 1;
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ lptr2[0] += (hptr2[0] + hptr2[stride] + 2) >> 2;
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ lptr2[0] += (hptr2[0] + 1) >> 1;
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ } else {
+
+ if (parity) {
+ lptr2 = &a[0];
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ lptr2[0] <<= 1;
+ ++lptr2;
+ }
+ }
+
+ }
+
+}
+
+void jpc_ft_fwdlift_colres(jpc_fix_t *a, int numrows, int numcols, int stride,
+ int parity)
+{
+
+ jpc_fix_t *lptr;
+ jpc_fix_t *hptr;
+ register jpc_fix_t *lptr2;
+ register jpc_fix_t *hptr2;
+ register int n;
+ register int i;
+ int llen;
+
+ llen = (numrows + 1 - parity) >> 1;
+
+ if (numrows > 1) {
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ hptr2[0] -= lptr2[0];
+ ++hptr2;
+ ++lptr2;
+ }
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ hptr2[0] -= (lptr2[0] + lptr2[stride]) >> 1;
+ ++lptr2;
+ ++hptr2;
+ }
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ hptr2[0] -= lptr2[0];
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ lptr2[0] += (hptr2[0] + 1) >> 1;
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ lptr2[0] += (hptr2[0] + hptr2[stride] + 2) >> 2;
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ lptr2[0] += (hptr2[0] + 1) >> 1;
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ } else {
+
+ if (parity) {
+ lptr2 = &a[0];
+ for (i = 0; i < numcols; ++i) {
+ lptr2[0] <<= 1;
+ ++lptr2;
+ }
+ }
+
+ }
+
+}
+
+void jpc_ft_invlift_row(jpc_fix_t *a, int numcols, int parity)
+{
+
+ register jpc_fix_t *lptr;
+ register jpc_fix_t *hptr;
+ register int n;
+ int llen;
+
+ llen = (numcols + 1 - parity) >> 1;
+
+ if (numcols > 1) {
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen];
+ if (!parity) {
+ lptr[0] -= (hptr[0] + 1) >> 1;
+ ++lptr;
+ }
+ n = llen - (!parity) - (parity != (numcols & 1));
+ while (n-- > 0) {
+ lptr[0] -= (hptr[0] + hptr[1] + 2) >> 2;
+ ++lptr;
+ ++hptr;
+ }
+ if (parity != (numcols & 1)) {
+ lptr[0] -= (hptr[0] + 1) >> 1;
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen];
+ if (parity) {
+ hptr[0] += lptr[0];
+ ++hptr;
+ }
+ n = numcols - llen - parity - (parity == (numcols & 1));
+ while (n-- > 0) {
+ hptr[0] += (lptr[0] + lptr[1]) >> 1;
+ ++hptr;
+ ++lptr;
+ }
+ if (parity == (numcols & 1)) {
+ hptr[0] += lptr[0];
+ }
+
+ } else {
+
+ if (parity) {
+ lptr = &a[0];
+ lptr[0] >>= 1;
+ }
+
+ }
+
+}
+
+void jpc_ft_invlift_col(jpc_fix_t *a, int numrows, int stride, int parity)
+{
+
+ jpc_fix_t *lptr;
+ jpc_fix_t *hptr;
+#if 0
+ register jpc_fix_t *lptr2;
+ register jpc_fix_t *hptr2;
+ register int i;
+#endif
+ register int n;
+ int llen;
+
+ llen = (numrows + 1 - parity) >> 1;
+
+ if (numrows > 1) {
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr[0] -= (hptr[0] + 1) >> 1;
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr[0] -= (hptr[0] + hptr[stride] + 2) >> 2;
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr[0] -= (hptr[0] + 1) >> 1;
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ hptr[0] += lptr[0];
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ hptr[0] += (lptr[0] + lptr[stride]) >> 1;
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ hptr[0] += lptr[0];
+ }
+
+ } else {
+
+ if (parity) {
+ lptr = &a[0];
+ lptr[0] >>= 1;
+ }
+
+ }
+
+}
+
+void jpc_ft_invlift_colgrp(jpc_fix_t *a, int numrows, int stride, int parity)
+{
+
+ jpc_fix_t *lptr;
+ jpc_fix_t *hptr;
+ register jpc_fix_t *lptr2;
+ register jpc_fix_t *hptr2;
+ register int n;
+ register int i;
+ int llen;
+
+ llen = (numrows + 1 - parity) >> 1;
+
+ if (numrows > 1) {
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ lptr2[0] -= (hptr2[0] + 1) >> 1;
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ lptr2[0] -= (hptr2[0] + hptr2[stride] + 2) >> 2;
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ lptr2[0] -= (hptr2[0] + 1) >> 1;
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ hptr2[0] += lptr2[0];
+ ++hptr2;
+ ++lptr2;
+ }
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ hptr2[0] += (lptr2[0] + lptr2[stride]) >> 1;
+ ++lptr2;
+ ++hptr2;
+ }
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ hptr2[0] += lptr2[0];
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ } else {
+
+ if (parity) {
+ lptr2 = &a[0];
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ lptr2[0] >>= 1;
+ ++lptr2;
+ }
+ }
+
+ }
+
+}
+
+void jpc_ft_invlift_colres(jpc_fix_t *a, int numrows, int numcols, int stride,
+ int parity)
+{
+
+ jpc_fix_t *lptr;
+ jpc_fix_t *hptr;
+ register jpc_fix_t *lptr2;
+ register jpc_fix_t *hptr2;
+ register int n;
+ register int i;
+ int llen;
+
+ llen = (numrows + 1 - parity) >> 1;
+
+ if (numrows > 1) {
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ lptr2[0] -= (hptr2[0] + 1) >> 1;
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ lptr2[0] -= (hptr2[0] + hptr2[stride] + 2) >> 2;
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ lptr2[0] -= (hptr2[0] + 1) >> 1;
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ hptr2[0] += lptr2[0];
+ ++hptr2;
+ ++lptr2;
+ }
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ hptr2[0] += (lptr2[0] + lptr2[stride]) >> 1;
+ ++lptr2;
+ ++hptr2;
+ }
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ hptr2[0] += lptr2[0];
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ } else {
+
+ if (parity) {
+ lptr2 = &a[0];
+ for (i = 0; i < numcols; ++i) {
+ lptr2[0] >>= 1;
+ ++lptr2;
+ }
+ }
+
+ }
+
+}
+
+int jpc_ft_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+ int stride)
+{
+ int numrows = height;
+ int numcols = width;
+ int rowparity = ystart & 1;
+ int colparity = xstart & 1;
+ int i;
+ jpc_fix_t *startptr;
+ int maxcols;
+
+ maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
+ startptr = &a[0];
+ for (i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
+ jpc_qmfb_split_colgrp(startptr, numrows, stride, rowparity);
+ jpc_ft_fwdlift_colgrp(startptr, numrows, stride, rowparity);
+ startptr += JPC_QMFB_COLGRPSIZE;
+ }
+ if (maxcols < numcols) {
+ jpc_qmfb_split_colres(startptr, numrows, numcols - maxcols, stride,
+ rowparity);
+ jpc_ft_fwdlift_colres(startptr, numrows, numcols - maxcols, stride,
+ rowparity);
+ }
+
+ startptr = &a[0];
+ for (i = 0; i < numrows; ++i) {
+ jpc_qmfb_split_row(startptr, numcols, colparity);
+ jpc_ft_fwdlift_row(startptr, numcols, colparity);
+ startptr += stride;
+ }
+
+ return 0;
+
+}
+
+int jpc_ft_synthesize(int *a, int xstart, int ystart, int width, int height,
+ int stride)
+{
+ int numrows = height;
+ int numcols = width;
+ int rowparity = ystart & 1;
+ int colparity = xstart & 1;
+
+ int maxcols;
+ jpc_fix_t *startptr;
+ int i;
+
+ startptr = &a[0];
+ for (i = 0; i < numrows; ++i) {
+ jpc_ft_invlift_row(startptr, numcols, colparity);
+ jpc_qmfb_join_row(startptr, numcols, colparity);
+ startptr += stride;
+ }
+
+ maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
+ startptr = &a[0];
+ for (i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
+ jpc_ft_invlift_colgrp(startptr, numrows, stride, rowparity);
+ jpc_qmfb_join_colgrp(startptr, numrows, stride, rowparity);
+ startptr += JPC_QMFB_COLGRPSIZE;
+ }
+ if (maxcols < numcols) {
+ jpc_ft_invlift_colres(startptr, numrows, numcols - maxcols, stride,
+ rowparity);
+ jpc_qmfb_join_colres(startptr, numrows, numcols - maxcols, stride,
+ rowparity);
+ }
+
+ return 0;
+
+}
+
+/******************************************************************************\
+* 9/7 transform
+\******************************************************************************/
+
+#define ALPHA (-1.586134342059924)
+#define BETA (-0.052980118572961)
+#define GAMMA (0.882911075530934)
+#define DELTA (0.443506852043971)
+#define LGAIN (1.0 / 1.23017410558578)
+#define HGAIN (1.0 / 1.62578613134411)
+
+void jpc_ns_fwdlift_row(jpc_fix_t *a, int numcols, int parity)
+{
+
+ register jpc_fix_t *lptr;
+ register jpc_fix_t *hptr;
+ register int n;
+ int llen;
+
+ llen = (numcols + 1 - parity) >> 1;
+
+ if (numcols > 1) {
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen];
+ if (parity) {
+ jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+ lptr[0]));
+ ++hptr;
+ }
+ n = numcols - llen - parity - (parity == (numcols & 1));
+ while (n-- > 0) {
+ jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
+ jpc_fix_add(lptr[0], lptr[1])));
+ ++hptr;
+ ++lptr;
+ }
+ if (parity == (numcols & 1)) {
+ jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+ lptr[0]));
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen];
+ if (!parity) {
+ jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr[0]));
+ ++lptr;
+ }
+ n = llen - (!parity) - (parity != (numcols & 1));
+ while (n-- > 0) {
+ jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(BETA),
+ jpc_fix_add(hptr[0], hptr[1])));
+ ++lptr;
+ ++hptr;
+ }
+ if (parity != (numcols & 1)) {
+ jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr[0]));
+ }
+
+ /* Apply the third lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen];
+ if (parity) {
+ jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+ lptr[0]));
+ ++hptr;
+ }
+ n = numcols - llen - parity - (parity == (numcols & 1));
+ while (n-- > 0) {
+ jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
+ jpc_fix_add(lptr[0], lptr[1])));
+ ++hptr;
+ ++lptr;
+ }
+ if (parity == (numcols & 1)) {
+ jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+ lptr[0]));
+ }
+
+ /* Apply the fourth lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen];
+ if (!parity) {
+ jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+ hptr[0]));
+ ++lptr;
+ }
+ n = llen - (!parity) - (parity != (numcols & 1));
+ while (n-- > 0) {
+ jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(DELTA),
+ jpc_fix_add(hptr[0], hptr[1])));
+ ++lptr;
+ ++hptr;
+ }
+ if (parity != (numcols & 1)) {
+ jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+ hptr[0]));
+ }
+
+ /* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+ lptr = &a[0];
+ n = llen;
+ while (n-- > 0) {
+ lptr[0] = jpc_fix_mul(lptr[0], jpc_dbltofix(LGAIN));
+ ++lptr;
+ }
+ hptr = &a[llen];
+ n = numcols - llen;
+ while (n-- > 0) {
+ hptr[0] = jpc_fix_mul(hptr[0], jpc_dbltofix(HGAIN));
+ ++hptr;
+ }
+#endif
+
+ } else {
+
+#if defined(WT_LENONE)
+ if (parity) {
+ lptr = &a[0];
+ lptr[0] <<= 1;
+ }
+#endif
+
+ }
+
+}
+
+void jpc_ns_fwdlift_colgrp(jpc_fix_t *a, int numrows, int stride,
+ int parity)
+{
+
+ jpc_fix_t *lptr;
+ jpc_fix_t *hptr;
+ register jpc_fix_t *lptr2;
+ register jpc_fix_t *hptr2;
+ register int n;
+ register int i;
+ int llen;
+
+ llen = (numrows + 1 - parity) >> 1;
+
+ if (numrows > 1) {
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+ lptr2[0]));
+ ++hptr2;
+ ++lptr2;
+ }
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
+ jpc_fix_add(lptr2[0], lptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+ lptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
+ jpc_fix_add(hptr2[0], hptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the third lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+ lptr2[0]));
+ ++hptr2;
+ ++lptr2;
+ }
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
+ jpc_fix_add(lptr2[0], lptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+ lptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the fourth lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
+ jpc_fix_add(hptr2[0], hptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+ lptr = &a[0];
+ n = llen;
+ while (n-- > 0) {
+ lptr2 = lptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(LGAIN));
+ ++lptr2;
+ }
+ lptr += stride;
+ }
+ hptr = &a[llen * stride];
+ n = numrows - llen;
+ while (n-- > 0) {
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(HGAIN));
+ ++hptr2;
+ }
+ hptr += stride;
+ }
+#endif
+
+ } else {
+
+#if defined(WT_LENONE)
+ if (parity) {
+ lptr2 = &a[0];
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ lptr2[0] <<= 1;
+ ++lptr2;
+ }
+ }
+#endif
+
+ }
+
+}
+
+void jpc_ns_fwdlift_colres(jpc_fix_t *a, int numrows, int numcols,
+ int stride, int parity)
+{
+
+ jpc_fix_t *lptr;
+ jpc_fix_t *hptr;
+ register jpc_fix_t *lptr2;
+ register jpc_fix_t *hptr2;
+ register int n;
+ register int i;
+ int llen;
+
+ llen = (numrows + 1 - parity) >> 1;
+
+ if (numrows > 1) {
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+ lptr2[0]));
+ ++hptr2;
+ ++lptr2;
+ }
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
+ jpc_fix_add(lptr2[0], lptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+ lptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
+ jpc_fix_add(hptr2[0], hptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the third lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+ lptr2[0]));
+ ++hptr2;
+ ++lptr2;
+ }
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
+ jpc_fix_add(lptr2[0], lptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+ lptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the fourth lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
+ jpc_fix_add(hptr2[0], hptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+ lptr = &a[0];
+ n = llen;
+ while (n-- > 0) {
+ lptr2 = lptr;
+ for (i = 0; i < numcols; ++i) {
+ lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(LGAIN));
+ ++lptr2;
+ }
+ lptr += stride;
+ }
+ hptr = &a[llen * stride];
+ n = numrows - llen;
+ while (n-- > 0) {
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(HGAIN));
+ ++hptr2;
+ }
+ hptr += stride;
+ }
+#endif
+
+ } else {
+
+#if defined(WT_LENONE)
+ if (parity) {
+ lptr2 = &a[0];
+ for (i = 0; i < numcols; ++i) {
+ lptr2[0] <<= 1;
+ ++lptr2;
+ }
+ }
+#endif
+
+ }
+
+}
+
+void jpc_ns_fwdlift_col(jpc_fix_t *a, int numrows, int stride,
+ int parity)
+{
+
+ jpc_fix_t *lptr;
+ jpc_fix_t *hptr;
+ register jpc_fix_t *lptr2;
+ register jpc_fix_t *hptr2;
+ register int n;
+ int llen;
+
+ llen = (numrows + 1 - parity) >> 1;
+
+ if (numrows > 1) {
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+ lptr2[0]));
+ ++hptr2;
+ ++lptr2;
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
+ jpc_fix_add(lptr2[0], lptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+ lptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
+ jpc_fix_add(hptr2[0], hptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+
+ /* Apply the third lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+ lptr2[0]));
+ ++hptr2;
+ ++lptr2;
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
+ jpc_fix_add(lptr2[0], lptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+ lptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+
+ /* Apply the fourth lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
+ jpc_fix_add(hptr2[0], hptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+
+ /* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+ lptr = &a[0];
+ n = llen;
+ while (n-- > 0) {
+ lptr2 = lptr;
+ lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(LGAIN));
+ ++lptr2;
+ lptr += stride;
+ }
+ hptr = &a[llen * stride];
+ n = numrows - llen;
+ while (n-- > 0) {
+ hptr2 = hptr;
+ hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(HGAIN));
+ ++hptr2;
+ hptr += stride;
+ }
+#endif
+
+ } else {
+
+#if defined(WT_LENONE)
+ if (parity) {
+ lptr2 = &a[0];
+ lptr2[0] <<= 1;
+ ++lptr2;
+ }
+#endif
+
+ }
+
+}
+
+void jpc_ns_invlift_row(jpc_fix_t *a, int numcols, int parity)
+{
+
+ register jpc_fix_t *lptr;
+ register jpc_fix_t *hptr;
+ register int n;
+ int llen;
+
+ llen = (numcols + 1 - parity) >> 1;
+
+ if (numcols > 1) {
+
+ /* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+ lptr = &a[0];
+ n = llen;
+ while (n-- > 0) {
+ lptr[0] = jpc_fix_mul(lptr[0], jpc_dbltofix(1.0 / LGAIN));
+ ++lptr;
+ }
+ hptr = &a[llen];
+ n = numcols - llen;
+ while (n-- > 0) {
+ hptr[0] = jpc_fix_mul(hptr[0], jpc_dbltofix(1.0 / HGAIN));
+ ++hptr;
+ }
+#endif
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen];
+ if (!parity) {
+ jpc_fix_minuseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+ hptr[0]));
+ ++lptr;
+ }
+ n = llen - (!parity) - (parity != (numcols & 1));
+ while (n-- > 0) {
+ jpc_fix_minuseq(lptr[0], jpc_fix_mul(jpc_dbltofix(DELTA),
+ jpc_fix_add(hptr[0], hptr[1])));
+ ++lptr;
+ ++hptr;
+ }
+ if (parity != (numcols & 1)) {
+ jpc_fix_minuseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
+ hptr[0]));
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen];
+ if (parity) {
+ jpc_fix_minuseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+ lptr[0]));
+ ++hptr;
+ }
+ n = numcols - llen - parity - (parity == (numcols & 1));
+ while (n-- > 0) {
+ jpc_fix_minuseq(hptr[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
+ jpc_fix_add(lptr[0], lptr[1])));
+ ++hptr;
+ ++lptr;
+ }
+ if (parity == (numcols & 1)) {
+ jpc_fix_minuseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
+ lptr[0]));
+ }
+
+ /* Apply the third lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen];
+ if (!parity) {
+ jpc_fix_minuseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr[0]));
+ ++lptr;
+ }
+ n = llen - (!parity) - (parity != (numcols & 1));
+ while (n-- > 0) {
+ jpc_fix_minuseq(lptr[0], jpc_fix_mul(jpc_dbltofix(BETA),
+ jpc_fix_add(hptr[0], hptr[1])));
+ ++lptr;
+ ++hptr;
+ }
+ if (parity != (numcols & 1)) {
+ jpc_fix_minuseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr[0]));
+ }
+
+ /* Apply the fourth lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen];
+ if (parity) {
+ jpc_fix_minuseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+ lptr[0]));
+ ++hptr;
+ }
+ n = numcols - llen - parity - (parity == (numcols & 1));
+ while (n-- > 0) {
+ jpc_fix_minuseq(hptr[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
+ jpc_fix_add(lptr[0], lptr[1])));
+ ++hptr;
+ ++lptr;
+ }
+ if (parity == (numcols & 1)) {
+ jpc_fix_minuseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
+ lptr[0]));
+ }
+
+ } else {
+
+#if defined(WT_LENONE)
+ if (parity) {
+ lptr = &a[0];
+ lptr[0] >>= 1;
+ }
+#endif
+
+ }
+
+}
+
+void jpc_ns_invlift_colgrp(jpc_fix_t *a, int numrows, int stride,
+ int parity)
+{
+
+ jpc_fix_t *lptr;
+ jpc_fix_t *hptr;
+ register jpc_fix_t *lptr2;
+ register jpc_fix_t *hptr2;
+ register int n;
+ register int i;
+ int llen;
+
+ llen = (numrows + 1 - parity) >> 1;
+
+ if (numrows > 1) {
+
+ /* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+ lptr = &a[0];
+ n = llen;
+ while (n-- > 0) {
+ lptr2 = lptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(1.0 / LGAIN));
+ ++lptr2;
+ }
+ lptr += stride;
+ }
+ hptr = &a[llen * stride];
+ n = numrows - llen;
+ while (n-- > 0) {
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(1.0 / HGAIN));
+ ++hptr2;
+ }
+ hptr += stride;
+ }
+#endif
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ DELTA), hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
+ jpc_fix_add(hptr2[0], hptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ DELTA), hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ GAMMA), lptr2[0]));
+ ++hptr2;
+ ++lptr2;
+ }
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
+ jpc_fix_add(lptr2[0], lptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ GAMMA), lptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the third lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
+ jpc_fix_add(hptr2[0], hptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the fourth lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ ALPHA), lptr2[0]));
+ ++hptr2;
+ ++lptr2;
+ }
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
+ jpc_fix_add(lptr2[0], lptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ ALPHA), lptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ } else {
+
+#if defined(WT_LENONE)
+ if (parity) {
+ lptr2 = &a[0];
+ for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
+ lptr2[0] >>= 1;
+ ++lptr2;
+ }
+ }
+#endif
+
+ }
+
+}
+
+void jpc_ns_invlift_colres(jpc_fix_t *a, int numrows, int numcols,
+ int stride, int parity)
+{
+
+ jpc_fix_t *lptr;
+ jpc_fix_t *hptr;
+ register jpc_fix_t *lptr2;
+ register jpc_fix_t *hptr2;
+ register int n;
+ register int i;
+ int llen;
+
+ llen = (numrows + 1 - parity) >> 1;
+
+ if (numrows > 1) {
+
+ /* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+ lptr = &a[0];
+ n = llen;
+ while (n-- > 0) {
+ lptr2 = lptr;
+ for (i = 0; i < numcols; ++i) {
+ lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(1.0 / LGAIN));
+ ++lptr2;
+ }
+ lptr += stride;
+ }
+ hptr = &a[llen * stride];
+ n = numrows - llen;
+ while (n-- > 0) {
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(1.0 / HGAIN));
+ ++hptr2;
+ }
+ hptr += stride;
+ }
+#endif
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ DELTA), hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
+ jpc_fix_add(hptr2[0], hptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ DELTA), hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ GAMMA), lptr2[0]));
+ ++hptr2;
+ ++lptr2;
+ }
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
+ jpc_fix_add(lptr2[0], lptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ GAMMA), lptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the third lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
+ jpc_fix_add(hptr2[0], hptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ /* Apply the fourth lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ ALPHA), lptr2[0]));
+ ++hptr2;
+ ++lptr2;
+ }
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
+ jpc_fix_add(lptr2[0], lptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ }
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ for (i = 0; i < numcols; ++i) {
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ ALPHA), lptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+ }
+
+ } else {
+
+#if defined(WT_LENONE)
+ if (parity) {
+ lptr2 = &a[0];
+ for (i = 0; i < numcols; ++i) {
+ lptr2[0] >>= 1;
+ ++lptr2;
+ }
+ }
+#endif
+
+ }
+
+}
+
+void jpc_ns_invlift_col(jpc_fix_t *a, int numrows, int stride,
+ int parity)
+{
+
+ jpc_fix_t *lptr;
+ jpc_fix_t *hptr;
+ register jpc_fix_t *lptr2;
+ register jpc_fix_t *hptr2;
+ register int n;
+ int llen;
+
+ llen = (numrows + 1 - parity) >> 1;
+
+ if (numrows > 1) {
+
+ /* Apply the scaling step. */
+#if defined(WT_DOSCALE)
+ lptr = &a[0];
+ n = llen;
+ while (n-- > 0) {
+ lptr2 = lptr;
+ lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(1.0 / LGAIN));
+ ++lptr2;
+ lptr += stride;
+ }
+ hptr = &a[llen * stride];
+ n = numrows - llen;
+ while (n-- > 0) {
+ hptr2 = hptr;
+ hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(1.0 / HGAIN));
+ ++hptr2;
+ hptr += stride;
+ }
+#endif
+
+ /* Apply the first lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ DELTA), hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
+ jpc_fix_add(hptr2[0], hptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ DELTA), hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+
+ /* Apply the second lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ GAMMA), lptr2[0]));
+ ++hptr2;
+ ++lptr2;
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
+ jpc_fix_add(lptr2[0], lptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ GAMMA), lptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+
+ /* Apply the third lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (!parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ lptr += stride;
+ }
+ n = llen - (!parity) - (parity != (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
+ jpc_fix_add(hptr2[0], hptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ lptr += stride;
+ hptr += stride;
+ }
+ if (parity != (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
+ hptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+
+ /* Apply the fourth lifting step. */
+ lptr = &a[0];
+ hptr = &a[llen * stride];
+ if (parity) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ ALPHA), lptr2[0]));
+ ++hptr2;
+ ++lptr2;
+ hptr += stride;
+ }
+ n = numrows - llen - parity - (parity == (numrows & 1));
+ while (n-- > 0) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
+ jpc_fix_add(lptr2[0], lptr2[stride])));
+ ++lptr2;
+ ++hptr2;
+ hptr += stride;
+ lptr += stride;
+ }
+ if (parity == (numrows & 1)) {
+ lptr2 = lptr;
+ hptr2 = hptr;
+ jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
+ ALPHA), lptr2[0]));
+ ++lptr2;
+ ++hptr2;
+ }
+
+ } else {
+
+#if defined(WT_LENONE)
+ if (parity) {
+ lptr2 = &a[0];
+ lptr2[0] >>= 1;
+ ++lptr2;
+ }
+#endif
+
+ }
+
+}
+
+int jpc_ns_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
+ int stride)
+{
+
+ int numrows = height;
+ int numcols = width;
+ int rowparity = ystart & 1;
+ int colparity = xstart & 1;
+ int i;
+ jpc_fix_t *startptr;
+ int maxcols;
+
+ maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
+ startptr = &a[0];
+ for (i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
+ jpc_qmfb_split_colgrp(startptr, numrows, stride, rowparity);
+ jpc_ns_fwdlift_colgrp(startptr, numrows, stride, rowparity);
+ startptr += JPC_QMFB_COLGRPSIZE;
+ }
+ if (maxcols < numcols) {
+ jpc_qmfb_split_colres(startptr, numrows, numcols - maxcols, stride,
+ rowparity);
+ jpc_ns_fwdlift_colres(startptr, numrows, numcols - maxcols, stride,
+ rowparity);
+ }
+
+ startptr = &a[0];
+ for (i = 0; i < numrows; ++i) {
+ jpc_qmfb_split_row(startptr, numcols, colparity);
+ jpc_ns_fwdlift_row(startptr, numcols, colparity);
+ startptr += stride;
+ }
+
+ return 0;
+
+}
+
+int jpc_ns_synthesize(jpc_fix_t *a, int xstart, int ystart, int width,
+ int height, int stride)
+{
+
+ int numrows = height;
+ int numcols = width;
+ int rowparity = ystart & 1;
+ int colparity = xstart & 1;
+ int maxcols;
+ jpc_fix_t *startptr;
+ int i;
+
+ startptr = &a[0];
+ for (i = 0; i < numrows; ++i) {
+ jpc_ns_invlift_row(startptr, numcols, colparity);
+ jpc_qmfb_join_row(startptr, numcols, colparity);
+ startptr += stride;
+ }
+
+ maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
+ startptr = &a[0];
+ for (i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
+ jpc_ns_invlift_colgrp(startptr, numrows, stride, rowparity);
+ jpc_qmfb_join_colgrp(startptr, numrows, stride, rowparity);
+ startptr += JPC_QMFB_COLGRPSIZE;
+ }
+ if (maxcols < numcols) {
+ jpc_ns_invlift_colres(startptr, numrows, numcols - maxcols, stride,
+ rowparity);
+ jpc_qmfb_join_colres(startptr, numrows, numcols - maxcols, stride,
+ rowparity);
+ }
+
+ return 0;
+
+}
+
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_qmfb.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_qmfb.h
new file mode 100644
index 0000000..75611fe
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_qmfb.h
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2004 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Quadrature Mirror-Image Filter Bank (QMFB) Routines
+ *
+ * $Id$
+ */
+
+#ifndef JPC_QMFB_H
+#define JPC_QMFB_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_seq.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* QMFB IDs. */
+#define JPC_QMFB1D_FT 1 /* 5/3 */
+#define JPC_QMFB1D_NS 2 /* 9/7 */
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+#if !defined(JPC_QMFB_COLGRPSIZE)
+/* The number of columns to group together during the vertical processing
+stage of the wavelet transform. */
+/* The default value for this parameter is probably not optimal for
+any particular platform. Hopefully, it is not too unreasonable, however. */
+#define JPC_QMFB_COLGRPSIZE 16
+#endif
+
+typedef struct {
+ int (*analyze)(int *, int, int, int, int, int);
+ int (*synthesize)(int *, int, int, int, int, int);
+ double *lpenergywts;
+ double *hpenergywts;
+} jpc_qmfb2d_t;
+
+extern jpc_qmfb2d_t jpc_ft_qmfb2d;
+extern jpc_qmfb2d_t jpc_ns_qmfb2d;
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1cod.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1cod.c
new file mode 100644
index 0000000..f75516a
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1cod.c
@@ -0,0 +1,497 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <math.h>
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_math.h"
+
+#include "jpc_bs.h"
+#include "jpc_dec.h"
+#include "jpc_cs.h"
+#include "jpc_mqcod.h"
+#include "jpc_t1cod.h"
+#include "jpc_tsfb.h"
+
+double jpc_pow2i(int n);
+
+/******************************************************************************\
+* Global data.
+\******************************************************************************/
+
+int jpc_zcctxnolut[4 * 256];
+int jpc_spblut[256];
+int jpc_scctxnolut[256];
+int jpc_magctxnolut[4096];
+
+jpc_fix_t jpc_signmsedec[1 << JPC_NMSEDEC_BITS];
+jpc_fix_t jpc_refnmsedec[1 << JPC_NMSEDEC_BITS];
+jpc_fix_t jpc_signmsedec0[1 << JPC_NMSEDEC_BITS];
+jpc_fix_t jpc_refnmsedec0[1 << JPC_NMSEDEC_BITS];
+
+jpc_mqctx_t jpc_mqctxs[JPC_NUMCTXS];
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+void jpc_initmqctxs(void);
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+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 JPC_NOMINALGAIN(int qmfbid, int numlvls, int lvlno, int orient)
+{
+ /* Avoid compiler warnings about unused parameters. */
+ numlvls = 0;
+
+if (qmfbid == JPC_COX_INS) {
+ return 0;
+}
+ assert(qmfbid == JPC_COX_RFT);
+ if (lvlno == 0) {
+ assert(orient == JPC_TSFB_LL);
+ return 0;
+ } else {
+ switch (orient) {
+ case JPC_TSFB_LH:
+ case JPC_TSFB_HL:
+ return 1;
+ break;
+ case JPC_TSFB_HH:
+ return 2;
+ break;
+ }
+ }
+ abort();
+}
+
+/******************************************************************************\
+* Coding pass related functions.
+\******************************************************************************/
+
+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 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 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;
+}
+
+/******************************************************************************\
+* Lookup table code.
+\******************************************************************************/
+
+void jpc_initluts()
+{
+ 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));
+/* 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));
+/* 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_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;
+}
+
+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 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 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 jpc_getmagctxno(int f)
+{
+ int n;
+
+ if (!(f & JPC_REFINE)) {
+ n = (f & (JPC_OTHSIGMSK)) ? 1 : 0;
+ } else {
+ n = 2;
+ }
+
+ 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;
+ }
+}
+
+void jpc_initmqctxs()
+{
+ jpc_initctxs(jpc_mqctxs);
+}
+
+/* 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;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1cod.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1cod.h
new file mode 100644
index 0000000..2edf73d
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1cod.h
@@ -0,0 +1,295 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef JPC_T1COD_H
+#define JPC_T1COD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_fix.h"
+#include "jasper/jas_math.h"
+
+#include "jpc_mqcod.h"
+#include "jpc_tsfb.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* The number of bits used to index into various lookup tables. */
+#define JPC_NMSEDEC_BITS 7
+#define JPC_NMSEDEC_FRACBITS (JPC_NMSEDEC_BITS - 1)
+
+/*
+ * Segment types.
+ */
+
+/* Invalid. */
+#define JPC_SEG_INVALID 0
+/* MQ. */
+#define JPC_SEG_MQ 1
+/* Raw. */
+#define JPC_SEG_RAW 2
+
+/* The nominal word size. */
+#define JPC_PREC 32
+
+/* Tier-1 coding pass types. */
+#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
+/* The southeast neighbour has been found to be significant. */
+#define JPC_SESIG 0x0002
+/* The southwest neighbour has been found to be significant. */
+#define JPC_SWSIG 0x0004
+/* The northwest neighbour has been found to be significant. */
+#define JPC_NWSIG 0x0008
+/* The north neighbour has been found to be significant. */
+#define JPC_NSIG 0x0010
+/* The east neighbour has been found to be significant. */
+#define JPC_ESIG 0x0020
+/* The south neighbour has been found to be significant. */
+#define JPC_SSIG 0x0040
+/* The west neighbour has been found to be significant. */
+#define JPC_WSIG 0x0080
+/* The significance mask for 8-connected neighbours. */
+#define JPC_OTHSIGMSK \
+ (JPC_NSIG | JPC_NESIG | JPC_ESIG | JPC_SESIG | JPC_SSIG | JPC_SWSIG | JPC_WSIG | JPC_NWSIG)
+/* The significance mask for 4-connected neighbours. */
+#define JPC_PRIMSIGMSK (JPC_NSIG | JPC_ESIG | JPC_SSIG | JPC_WSIG)
+
+/* The north neighbour is negative in value. */
+#define JPC_NSGN 0x0100
+/* The east neighbour is negative in value. */
+#define JPC_ESGN 0x0200
+/* The south neighbour is negative in value. */
+#define JPC_SSGN 0x0400
+/* The west neighbour is negative in value. */
+#define JPC_WSGN 0x0800
+/* The sign mask for 4-connected neighbours. */
+#define JPC_SGNMSK (JPC_NSGN | JPC_ESGN | JPC_SSGN | JPC_WSGN)
+
+/* This sample has been found to be significant. */
+#define JPC_SIG 0x1000
+/* The sample has been refined. */
+#define JPC_REFINE 0x2000
+/* This sample has been processed during the significance pass. */
+#define JPC_VISIT 0x4000
+
+/* The number of aggregation contexts. */
+#define JPC_NUMAGGCTXS 1
+/* The number of zero coding contexts. */
+#define JPC_NUMZCCTXS 9
+/* The number of magnitude contexts. */
+#define JPC_NUMMAGCTXS 3
+/* The number of sign coding contexts. */
+#define JPC_NUMSCCTXS 5
+/* The number of uniform contexts. */
+#define JPC_NUMUCTXS 1
+
+/* The context ID for the first aggregation context. */
+#define JPC_AGGCTXNO 0
+/* The context ID for the first zero coding context. */
+#define JPC_ZCCTXNO (JPC_AGGCTXNO + JPC_NUMAGGCTXS)
+/* The context ID for the first magnitude context. */
+#define JPC_MAGCTXNO (JPC_ZCCTXNO + JPC_NUMZCCTXS)
+/* The context ID for the first sign coding context. */
+#define JPC_SCCTXNO (JPC_MAGCTXNO + JPC_NUMMAGCTXS)
+/* The context ID for the first uniform context. */
+#define JPC_UCTXNO (JPC_SCCTXNO + JPC_NUMSCCTXS)
+/* The total number of contexts. */
+#define JPC_NUMCTXS (JPC_UCTXNO + JPC_NUMUCTXS)
+
+/******************************************************************************\
+* External data.
+\******************************************************************************/
+
+/* These lookup tables are used by various macros/functions. */
+/* Do not access these lookup tables directly. */
+extern int jpc_zcctxnolut[];
+extern int jpc_spblut[];
+extern int jpc_scctxnolut[];
+extern int jpc_magctxnolut[];
+extern jpc_fix_t jpc_refnmsedec[];
+extern jpc_fix_t jpc_signmsedec[];
+extern jpc_fix_t jpc_refnmsedec0[];
+extern jpc_fix_t jpc_signmsedec0[];
+
+/* The initial settings for the MQ contexts. */
+extern jpc_mqctx_t jpc_mqctxs[];
+
+/******************************************************************************\
+* Functions and macros.
+\******************************************************************************/
+
+/* Initialize the MQ contexts. */
+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)])
+
+/* Get the sign prediction bit. */
+int jpc_getspb(int f);
+#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])
+
+/* Get the magnitude context. */
+int jpc_getmagctxno(int f);
+#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)
+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)]))
+
+/* Get the normalized MSE reduction for refinement passes. */
+#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)]))
+
+/* Arithmetic shift right (with ability to shift left also). */
+#define JPC_ASR(x, n) \
+ (((n) >= 0) ? ((x) >> (n)) : ((x) << (-(n))))
+
+/* Update the per-sample state information. */
+#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; \
+ } \
+ } \
+}
+
+/* Initialize the lookup tables used by the codec. */
+void jpc_initluts(void);
+
+/* Get the nominal gain associated with a particular band. */
+int JPC_NOMINALGAIN(int qmfbid, int numlvls, int lvlno, int orient);
+
+/* Get the coding pass type. */
+int JPC_PASSTYPE(int passno);
+
+/* Get the segment type. */
+int JPC_SEGTYPE(int passno, int firstpassno, int bypass);
+
+/* Get the number of coding passess in the segment. */
+int JPC_SEGPASSCNT(int passno, int firstpassno, int numpasses, int bypass,
+ int termall);
+
+/* Is the coding pass terminated? */
+int JPC_ISTERMINATED(int passno, int firstpassno, int numpasses, int termall,
+ int lazy);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1dec.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1dec.c
new file mode 100644
index 0000000..b491ec3
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1dec.c
@@ -0,0 +1,923 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier 1 Decoder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#include "jasper/jas_fix.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_math.h"
+#include "jasper/jas_debug.h"
+
+#include "jpc_bs.h"
+#include "jpc_mqdec.h"
+#include "jpc_t1dec.h"
+#include "jpc_t1cod.h"
+#include "jpc_dec.h"
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static int jpc_dec_decodecblk(jpc_dec_t *dec, jpc_dec_tile_t *tile, jpc_dec_tcomp_t *tcomp, jpc_dec_band_t *band,
+ jpc_dec_cblk_t *cblk, int dopartial, int maxlyrs);
+static int dec_sigpass(jpc_dec_t *dec, jpc_mqdec_t *mqdec, int bitpos, int orient,
+ int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data);
+static int dec_rawsigpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos,
+ int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data);
+static int dec_refpass(jpc_dec_t *dec, jpc_mqdec_t *mqdec, int bitpos, int vcausalflag,
+ jas_matrix_t *flags, jas_matrix_t *data);
+static int dec_rawrefpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos,
+ int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data);
+static int dec_clnpass(jpc_dec_t *dec, jpc_mqdec_t *mqdec, int bitpos, int orient,
+ int vcausalflag, int segsymflag, jas_matrix_t *flags, jas_matrix_t *data);
+
+#if defined(DEBUG)
+static long t1dec_cnt = 0;
+#endif
+
+#if !defined(DEBUG)
+#define JPC_T1D_GETBIT(mqdec, v, passtypename, symtypename) \
+ ((v) = jpc_mqdec_getbit(mqdec))
+#else
+#define JPC_T1D_GETBIT(mqdec, v, passtypename, symtypename) \
+{ \
+ (v) = jpc_mqdec_getbit(mqdec); \
+ if (jas_getdbglevel() >= 100) { \
+ jas_eprintf("index = %ld; passtype = %s; symtype = %s; sym = %d\n", t1dec_cnt, passtypename, symtypename, v); \
+ ++t1dec_cnt; \
+ } \
+}
+#endif
+#define JPC_T1D_GETBITNOSKEW(mqdec, v, passtypename, symtypename) \
+ JPC_T1D_GETBIT(mqdec, v, passtypename, symtypename)
+
+#if !defined(DEBUG)
+#define JPC_T1D_RAWGETBIT(bitstream, v, passtypename, symtypename) \
+ ((v) = jpc_bitstream_getbit(bitstream))
+#else
+#define JPC_T1D_RAWGETBIT(bitstream, v, passtypename, symtypename) \
+{ \
+ (v) = jpc_bitstream_getbit(bitstream); \
+ if (jas_getdbglevel() >= 100) { \
+ jas_eprintf("index = %ld; passtype = %s; symtype = %s; sym = %d\n", t1dec_cnt, passtypename, symtypename, v); \
+ ++t1dec_cnt; \
+ } \
+}
+#endif
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+int jpc_dec_decodecblks(jpc_dec_t *dec, jpc_dec_tile_t *tile)
+{
+ jpc_dec_tcomp_t *tcomp;
+ int compcnt;
+ jpc_dec_rlvl_t *rlvl;
+ int rlvlcnt;
+ jpc_dec_band_t *band;
+ int bandcnt;
+ jpc_dec_prc_t *prc;
+ int prccnt;
+ jpc_dec_cblk_t *cblk;
+ int cblkcnt;
+
+ for (compcnt = dec->numcomps, tcomp = tile->tcomps; compcnt > 0;
+ --compcnt, ++tcomp) {
+ for (rlvlcnt = tcomp->numrlvls, rlvl = tcomp->rlvls;
+ rlvlcnt > 0; --rlvlcnt, ++rlvl) {
+ if (!rlvl->bands) {
+ continue;
+ }
+ for (bandcnt = rlvl->numbands, band = rlvl->bands;
+ bandcnt > 0; --bandcnt, ++band) {
+ if (!band->data) {
+ continue;
+ }
+ for (prccnt = rlvl->numprcs, prc = band->prcs;
+ prccnt > 0; --prccnt, ++prc) {
+ if (!prc->cblks) {
+ continue;
+ }
+ for (cblkcnt = prc->numcblks,
+ cblk = prc->cblks; cblkcnt > 0;
+ --cblkcnt, ++cblk) {
+ if (jpc_dec_decodecblk(dec, tile, tcomp,
+ band, cblk, 1, JPC_MAXLYRS)) {
+ return -1;
+ }
+ }
+ }
+
+ }
+ }
+ }
+
+ return 0;
+}
+
+static int jpc_dec_decodecblk(jpc_dec_t *dec, jpc_dec_tile_t *tile, jpc_dec_tcomp_t *tcomp, jpc_dec_band_t *band,
+ jpc_dec_cblk_t *cblk, int dopartial, int maxlyrs)
+{
+ jpc_dec_seg_t *seg;
+ int i;
+ int bpno;
+ int passtype;
+ int ret;
+ int compno;
+ int filldata;
+ int fillmask;
+ jpc_dec_ccp_t *ccp;
+
+ compno = tcomp - tile->tcomps;
+
+ if (!cblk->flags) {
+ /* Note: matrix is assumed to be zeroed */
+ if (!(cblk->flags = jas_matrix_create(jas_matrix_numrows(cblk->data) +
+ 2, jas_matrix_numcols(cblk->data) + 2))) {
+ return -1;
+ }
+ }
+
+ seg = cblk->segs.head;
+ while (seg && (seg != cblk->curseg || dopartial) && (maxlyrs < 0 ||
+ seg->lyrno < maxlyrs)) {
+ assert(seg->numpasses >= seg->maxpasses || dopartial);
+ assert(seg->stream);
+ jas_stream_rewind(seg->stream);
+ jas_stream_setrwcount(seg->stream, 0);
+ if (seg->type == JPC_SEG_MQ) {
+ if (!cblk->mqdec) {
+ if (!(cblk->mqdec = jpc_mqdec_create(JPC_NUMCTXS, 0))) {
+ return -1;
+ }
+ jpc_mqdec_setctxs(cblk->mqdec, JPC_NUMCTXS, jpc_mqctxs);
+ }
+ jpc_mqdec_setinput(cblk->mqdec, seg->stream);
+ jpc_mqdec_init(cblk->mqdec);
+ } else {
+ assert(seg->type == JPC_SEG_RAW);
+ if (!cblk->nulldec) {
+ if (!(cblk->nulldec = jpc_bitstream_sopen(seg->stream, "r"))) {
+ assert(0);
+ }
+ }
+ }
+
+
+ for (i = 0; i < seg->numpasses; ++i) {
+ if (cblk->numimsbs > band->numbps) {
+ ccp = &tile->cp->ccps[compno];
+ if (ccp->roishift <= 0) {
+ jas_eprintf("warning: corrupt code stream\n");
+ } else {
+ if (cblk->numimsbs < ccp->roishift - band->numbps) {
+ jas_eprintf("warning: corrupt code stream\n");
+ }
+ }
+ }
+ bpno = band->roishift + band->numbps - 1 - (cblk->numimsbs +
+ (seg->passno + i - cblk->firstpassno + 2) / 3);
+if (bpno < 0) {
+ goto premature_exit;
+}
+#if 1
+ passtype = (seg->passno + i + 2) % 3;
+#else
+ passtype = JPC_PASSTYPE(seg->passno + i + 2);
+#endif
+ assert(bpno >= 0 && bpno < 31);
+ switch (passtype) {
+ case JPC_SIGPASS:
+ ret = (seg->type == JPC_SEG_MQ) ? dec_sigpass(dec,
+ cblk->mqdec, bpno, band->orient,
+ (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0,
+ cblk->flags, cblk->data) :
+ dec_rawsigpass(dec, cblk->nulldec, bpno,
+ (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0,
+ cblk->flags, cblk->data);
+ break;
+ case JPC_REFPASS:
+ ret = (seg->type == JPC_SEG_MQ) ?
+ dec_refpass(dec, cblk->mqdec, bpno,
+ (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0,
+ cblk->flags, cblk->data) :
+ dec_rawrefpass(dec, cblk->nulldec, bpno,
+ (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0,
+ cblk->flags, cblk->data);
+ break;
+ case JPC_CLNPASS:
+ assert(seg->type == JPC_SEG_MQ);
+ ret = dec_clnpass(dec, cblk->mqdec, bpno,
+ band->orient, (tile->cp->ccps[compno].cblkctx &
+ JPC_COX_VSC) != 0, (tile->cp->ccps[compno].cblkctx &
+ JPC_COX_SEGSYM) != 0, cblk->flags,
+ cblk->data);
+ break;
+ default:
+ ret = -1;
+ break;
+ }
+ /* Do we need to reset after each coding pass? */
+ if (tile->cp->ccps[compno].cblkctx & JPC_COX_RESET) {
+ jpc_mqdec_setctxs(cblk->mqdec, JPC_NUMCTXS, jpc_mqctxs);
+ }
+
+ if (ret) {
+ jas_eprintf("coding pass failed passtype=%d segtype=%d\n", passtype, seg->type);
+ return -1;
+ }
+
+ }
+
+ if (seg->type == JPC_SEG_MQ) {
+/* Note: dont destroy mq decoder because context info will be lost */
+ } else {
+ assert(seg->type == JPC_SEG_RAW);
+ if (tile->cp->ccps[compno].cblkctx & JPC_COX_PTERM) {
+ fillmask = 0x7f;
+ filldata = 0x2a;
+ } else {
+ fillmask = 0;
+ filldata = 0;
+ }
+ if ((ret = jpc_bitstream_inalign(cblk->nulldec, fillmask,
+ filldata)) < 0) {
+ return -1;
+ } else if (ret > 0) {
+ jas_eprintf("warning: bad termination pattern detected\n");
+ }
+ jpc_bitstream_close(cblk->nulldec);
+ cblk->nulldec = 0;
+ }
+
+ cblk->curseg = seg->next;
+ jpc_seglist_remove(&cblk->segs, seg);
+ jpc_seg_destroy(seg);
+ seg = cblk->curseg;
+ }
+
+ assert(dopartial ? (!cblk->curseg) : 1);
+
+premature_exit:
+ return 0;
+}
+
+/******************************************************************************\
+* Code for significance pass.
+\******************************************************************************/
+
+#define jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf, orient, mqdec, vcausalflag) \
+{ \
+ int f; \
+ int v; \
+ f = *(fp); \
+ if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \
+ jpc_mqdec_setcurctx((mqdec), JPC_GETZCCTXNO(f, (orient))); \
+ JPC_T1D_GETBIT((mqdec), v, "SIG", "ZC"); \
+ if (v) { \
+ jpc_mqdec_setcurctx((mqdec), JPC_GETSCCTXNO(f)); \
+ JPC_T1D_GETBIT((mqdec), v, "SIG", "SC"); \
+ v ^= JPC_GETSPB(f); \
+ JPC_UPDATEFLAGS4((fp), (frowstep), v, (vcausalflag)); \
+ *(fp) |= JPC_SIG; \
+ *(dp) = (v) ? (-(oneplushalf)) : (oneplushalf); \
+ } \
+ *(fp) |= JPC_VISIT; \
+ } \
+}
+
+static int dec_sigpass(jpc_dec_t *dec, register jpc_mqdec_t *mqdec, int bitpos, int orient,
+ int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data)
+{
+ int i;
+ int j;
+ int one;
+ int half;
+ int oneplushalf;
+ int vscanlen;
+ int width;
+ int height;
+ jpc_fix_t *fp;
+ int frowstep;
+ int fstripestep;
+ jpc_fix_t *fstripestart;
+ jpc_fix_t *fvscanstart;
+ jpc_fix_t *dp;
+ int drowstep;
+ int dstripestep;
+ jpc_fix_t *dstripestart;
+ jpc_fix_t *dvscanstart;
+ int k;
+
+ /* Avoid compiler warning about unused parameters. */
+ dec = 0;
+
+ width = jas_matrix_numcols(data);
+ height = jas_matrix_numrows(data);
+ frowstep = jas_matrix_rowstep(flags);
+ drowstep = jas_matrix_rowstep(data);
+ fstripestep = frowstep << 2;
+ dstripestep = drowstep << 2;
+
+ one = 1 << bitpos;
+ half = one >> 1;
+ oneplushalf = one | half;
+
+ fstripestart = jas_matrix_getref(flags, 1, 1);
+ dstripestart = jas_matrix_getref(data, 0, 0);
+ for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+ dstripestart += dstripestep) {
+ fvscanstart = fstripestart;
+ dvscanstart = dstripestart;
+ vscanlen = JAS_MIN(i, 4);
+ for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+ fp = fvscanstart;
+ dp = dvscanstart;
+ k = vscanlen;
+
+ /* Process first sample in vertical scan. */
+ jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf,
+ orient, mqdec, vcausalflag);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process second sample in vertical scan. */
+ jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf,
+ orient, mqdec, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process third sample in vertical scan. */
+ jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf,
+ orient, mqdec, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process fourth sample in vertical scan. */
+ jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf,
+ orient, mqdec, 0);
+ }
+ }
+ return 0;
+}
+
+#define jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf, in, vcausalflag) \
+{ \
+ jpc_fix_t f = *(fp); \
+ jpc_fix_t v; \
+ if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \
+ JPC_T1D_RAWGETBIT(in, v, "SIG", "ZC"); \
+ if (v < 0) { \
+ return -1; \
+ } \
+ if (v) { \
+ JPC_T1D_RAWGETBIT(in, v, "SIG", "SC"); \
+ if (v < 0) { \
+ return -1; \
+ } \
+ JPC_UPDATEFLAGS4((fp), (frowstep), v, (vcausalflag)); \
+ *(fp) |= JPC_SIG; \
+ *(dp) = v ? (-oneplushalf) : (oneplushalf); \
+ } \
+ *(fp) |= JPC_VISIT; \
+ } \
+}
+
+static int dec_rawsigpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos, int vcausalflag,
+ jas_matrix_t *flags, jas_matrix_t *data)
+{
+ int i;
+ int j;
+ int k;
+ int one;
+ int half;
+ int oneplushalf;
+ int vscanlen;
+ int width;
+ int height;
+ jpc_fix_t *fp;
+ int frowstep;
+ int fstripestep;
+ jpc_fix_t *fstripestart;
+ jpc_fix_t *fvscanstart;
+ jpc_fix_t *dp;
+ int drowstep;
+ int dstripestep;
+ jpc_fix_t *dstripestart;
+ jpc_fix_t *dvscanstart;
+
+ /* Avoid compiler warning about unused parameters. */
+ dec = 0;
+
+ width = jas_matrix_numcols(data);
+ height = jas_matrix_numrows(data);
+ frowstep = jas_matrix_rowstep(flags);
+ drowstep = jas_matrix_rowstep(data);
+ fstripestep = frowstep << 2;
+ dstripestep = drowstep << 2;
+
+ one = 1 << bitpos;
+ half = one >> 1;
+ oneplushalf = one | half;
+
+ fstripestart = jas_matrix_getref(flags, 1, 1);
+ dstripestart = jas_matrix_getref(data, 0, 0);
+ for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+ dstripestart += dstripestep) {
+ fvscanstart = fstripestart;
+ dvscanstart = dstripestart;
+ vscanlen = JAS_MIN(i, 4);
+ for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+ fp = fvscanstart;
+ dp = dvscanstart;
+ k = vscanlen;
+
+ /* Process first sample in vertical scan. */
+ jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf,
+ in, vcausalflag);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process second sample in vertical scan. */
+ jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf,
+ in, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process third sample in vertical scan. */
+ jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf,
+ in, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process fourth sample in vertical scan. */
+ jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf,
+ in, 0);
+
+ }
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Code for refinement pass.
+\******************************************************************************/
+
+#define jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, vcausalflag) \
+{ \
+ int v; \
+ int t; \
+ if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \
+ jpc_mqdec_setcurctx((mqdec), JPC_GETMAGCTXNO(*(fp))); \
+ JPC_T1D_GETBITNOSKEW((mqdec), v, "REF", "MR"); \
+ t = (v ? (poshalf) : (neghalf)); \
+ *(dp) += (*(dp) < 0) ? (-t) : t; \
+ *(fp) |= JPC_REFINE; \
+ } \
+}
+
+static int dec_refpass(jpc_dec_t *dec, register jpc_mqdec_t *mqdec, int bitpos,
+ int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data)
+{
+ int i;
+ int j;
+ int vscanlen;
+ int width;
+ int height;
+ int one;
+ int poshalf;
+ int neghalf;
+ jpc_fix_t *fp;
+ int frowstep;
+ int fstripestep;
+ jpc_fix_t *fstripestart;
+ jpc_fix_t *fvscanstart;
+ jpc_fix_t *dp;
+ int drowstep;
+ int dstripestep;
+ jpc_fix_t *dstripestart;
+ jpc_fix_t *dvscanstart;
+ int k;
+
+ /* Avoid compiler warning about unused parameters. */
+ dec = 0;
+ vcausalflag = 0;
+
+ width = jas_matrix_numcols(data);
+ height = jas_matrix_numrows(data);
+ frowstep = jas_matrix_rowstep(flags);
+ drowstep = jas_matrix_rowstep(data);
+ fstripestep = frowstep << 2;
+ dstripestep = drowstep << 2;
+
+ one = 1 << bitpos;
+ poshalf = one >> 1;
+ neghalf = (bitpos > 0) ? (-poshalf) : (-1);
+
+ fstripestart = jas_matrix_getref(flags, 1, 1);
+ dstripestart = jas_matrix_getref(data, 0, 0);
+ for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+ dstripestart += dstripestep) {
+ fvscanstart = fstripestart;
+ dvscanstart = dstripestart;
+ vscanlen = JAS_MIN(i, 4);
+ for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+ fp = fvscanstart;
+ dp = dvscanstart;
+ k = vscanlen;
+
+ /* Process first sample in vertical scan. */
+ jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec,
+ vcausalflag);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process second sample in vertical scan. */
+ jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process third sample in vertical scan. */
+ jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process fourth sample in vertical scan. */
+ jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, 0);
+ }
+ }
+
+ return 0;
+}
+
+#define jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, vcausalflag) \
+{ \
+ jpc_fix_t v; \
+ jpc_fix_t t; \
+ if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \
+ JPC_T1D_RAWGETBIT(in, v, "REF", "MAGREF"); \
+ if (v < 0) { \
+ return -1; \
+ } \
+ t = (v ? poshalf : neghalf); \
+ *(dp) += (*(dp) < 0) ? (-t) : t; \
+ *(fp) |= JPC_REFINE; \
+ } \
+}
+
+static int dec_rawrefpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos, int vcausalflag,
+ jas_matrix_t *flags, jas_matrix_t *data)
+{
+ int i;
+ int j;
+ int k;
+ int vscanlen;
+ int width;
+ int height;
+ int one;
+ int poshalf;
+ int neghalf;
+ jpc_fix_t *fp;
+ int frowstep;
+ int fstripestep;
+ jpc_fix_t *fstripestart;
+ jpc_fix_t *fvscanstart;
+ jpc_fix_t *dp;
+ int drowstep;
+ int dstripestep;
+ jpc_fix_t *dstripestart;
+ jpc_fix_t *dvscanstart;
+
+ /* Avoid compiler warning about unused parameters. */
+ dec = 0;
+ vcausalflag = 0;
+
+ width = jas_matrix_numcols(data);
+ height = jas_matrix_numrows(data);
+ frowstep = jas_matrix_rowstep(flags);
+ drowstep = jas_matrix_rowstep(data);
+ fstripestep = frowstep << 2;
+ dstripestep = drowstep << 2;
+
+ one = 1 << bitpos;
+ poshalf = one >> 1;
+ neghalf = (bitpos > 0) ? (-poshalf) : (-1);
+
+ fstripestart = jas_matrix_getref(flags, 1, 1);
+ dstripestart = jas_matrix_getref(data, 0, 0);
+ for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+ dstripestart += dstripestep) {
+ fvscanstart = fstripestart;
+ dvscanstart = dstripestart;
+ vscanlen = JAS_MIN(i, 4);
+ for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+ fp = fvscanstart;
+ dp = dvscanstart;
+ k = vscanlen;
+
+ /* Process first sample in vertical scan. */
+ jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in,
+ vcausalflag);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process second sample in vertical scan. */
+ jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process third sample in vertical scan. */
+ jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process fourth sample in vertical scan. */
+ jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, 0);
+ }
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Code for cleanup pass.
+\******************************************************************************/
+
+#define jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient, mqdec, flabel, plabel, vcausalflag) \
+{ \
+ int v; \
+flabel \
+ if (!((f) & (JPC_SIG | JPC_VISIT))) { \
+ jpc_mqdec_setcurctx((mqdec), JPC_GETZCCTXNO((f), (orient))); \
+ JPC_T1D_GETBIT((mqdec), v, "CLN", "ZC"); \
+ if (v) { \
+plabel \
+ /* Coefficient is significant. */ \
+ jpc_mqdec_setcurctx((mqdec), JPC_GETSCCTXNO(f)); \
+ JPC_T1D_GETBIT((mqdec), v, "CLN", "SC"); \
+ v ^= JPC_GETSPB(f); \
+ *(dp) = (v) ? (-(oneplushalf)) : (oneplushalf); \
+ JPC_UPDATEFLAGS4((fp), (frowstep), v, (vcausalflag)); \
+ *(fp) |= JPC_SIG; \
+ } \
+ } \
+ /* XXX - Is this correct? Can aggregation cause some VISIT bits not to be reset? Check. */ \
+ *(fp) &= ~JPC_VISIT; \
+}
+
+static int dec_clnpass(jpc_dec_t *dec, register jpc_mqdec_t *mqdec, int bitpos, int orient,
+ int vcausalflag, int segsymflag, jas_matrix_t *flags, jas_matrix_t *data)
+{
+ int i;
+ int j;
+ int k;
+ int vscanlen;
+ int v;
+ int half;
+ int runlen;
+ int f;
+ int width;
+ int height;
+ int one;
+ int oneplushalf;
+
+ jpc_fix_t *fp;
+ int frowstep;
+ int fstripestep;
+ jpc_fix_t *fstripestart;
+ jpc_fix_t *fvscanstart;
+
+ jpc_fix_t *dp;
+ int drowstep;
+ int dstripestep;
+ jpc_fix_t *dstripestart;
+ jpc_fix_t *dvscanstart;
+
+ /* Avoid compiler warning about unused parameters. */
+ dec = 0;
+
+ one = 1 << bitpos;
+ half = one >> 1;
+ oneplushalf = one | half;
+
+ width = jas_matrix_numcols(data);
+ height = jas_matrix_numrows(data);
+
+ frowstep = jas_matrix_rowstep(flags);
+ drowstep = jas_matrix_rowstep(data);
+ fstripestep = frowstep << 2;
+ dstripestep = drowstep << 2;
+
+ fstripestart = jas_matrix_getref(flags, 1, 1);
+ dstripestart = jas_matrix_getref(data, 0, 0);
+ for (i = 0; i < height; i += 4, fstripestart += fstripestep,
+ dstripestart += dstripestep) {
+ fvscanstart = fstripestart;
+ dvscanstart = dstripestart;
+ vscanlen = JAS_MIN(4, height - i);
+ for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+ fp = fvscanstart;
+ if (vscanlen >= 4 && (!((*fp) & (JPC_SIG | JPC_VISIT |
+ JPC_OTHSIGMSK))) && (fp += frowstep, !((*fp) & (JPC_SIG |
+ JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep, !((*fp) &
+ (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep,
+ !((*fp) & (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK)))) {
+
+ jpc_mqdec_setcurctx(mqdec, JPC_AGGCTXNO);
+ JPC_T1D_GETBIT(mqdec, v, "CLN", "AGG");
+ if (!v) {
+ continue;
+ }
+ jpc_mqdec_setcurctx(mqdec, JPC_UCTXNO);
+ JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "RL");
+ runlen = v;
+ JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "RL");
+ runlen = (runlen << 1) | v;
+ f = *(fp = fvscanstart + frowstep * runlen);
+ dp = dvscanstart + drowstep * runlen;
+ k = vscanlen - runlen;
+ switch (runlen) {
+ case 0:
+ goto clnpass_partial0;
+ break;
+ case 1:
+ goto clnpass_partial1;
+ break;
+ case 2:
+ goto clnpass_partial2;
+ break;
+ case 3:
+ goto clnpass_partial3;
+ break;
+ }
+ } else {
+ f = *(fp = fvscanstart);
+ dp = dvscanstart;
+ k = vscanlen;
+ goto clnpass_full0;
+ }
+
+ /* Process first sample in vertical scan. */
+ jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
+ mqdec, clnpass_full0:, clnpass_partial0:,
+ vcausalflag);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process second sample in vertical scan. */
+ f = *fp;
+ jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
+ mqdec, ;, clnpass_partial1:, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process third sample in vertical scan. */
+ f = *fp;
+ jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
+ mqdec, ;, clnpass_partial2:, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ /* Process fourth sample in vertical scan. */
+ f = *fp;
+ jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
+ mqdec, ;, clnpass_partial3:, 0);
+ }
+ }
+
+ if (segsymflag) {
+ int segsymval;
+ segsymval = 0;
+ jpc_mqdec_setcurctx(mqdec, JPC_UCTXNO);
+ JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM");
+ segsymval = (segsymval << 1) | (v & 1);
+ JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM");
+ segsymval = (segsymval << 1) | (v & 1);
+ JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM");
+ segsymval = (segsymval << 1) | (v & 1);
+ JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM");
+ segsymval = (segsymval << 1) | (v & 1);
+ if (segsymval != 0xa) {
+ jas_eprintf("warning: bad segmentation symbol\n");
+ }
+ }
+
+ return 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1dec.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1dec.h
new file mode 100644
index 0000000..79cc2ed
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1dec.h
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier 1 Decoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_T1DEC_H
+#define JPC_T1DEC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_dec.h"
+#include "jpc_mqdec.h"
+#include "jpc_t1cod.h"
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Decode all of the code blocks for a particular tile. */
+int jpc_dec_decodecblks(jpc_dec_t *dec, jpc_dec_tile_t *tile);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1enc.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1enc.c
new file mode 100644
index 0000000..3a5acea
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1enc.c
@@ -0,0 +1,959 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier 1 Encoder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#include "jasper/jas_fix.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+
+#include "jpc_t1enc.h"
+#include "jpc_t1cod.h"
+#include "jpc_enc.h"
+#include "jpc_cod.h"
+#include "jpc_math.h"
+
+static int jpc_encsigpass(jpc_mqenc_t *mqenc, int bitpos, int orient, int,
+ jas_matrix_t *flags, jas_matrix_t *data, int term, long *nmsedec);
+
+static int jpc_encrefpass(jpc_mqenc_t *mqenc, int bitpos, int, jas_matrix_t *flags,
+ jas_matrix_t *data, int term, long *nmsedec);
+
+static int jpc_encclnpass(jpc_mqenc_t *mqenc, int bitpos, int orient, int,
+ int, jas_matrix_t *flags, jas_matrix_t *data, int term, long *nmsedec);
+
+static int jpc_encrawsigpass(jpc_bitstream_t *out, int bitpos, int,
+ jas_matrix_t *flags, jas_matrix_t *data, int term, long *nmsedec);
+
+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;
+
+ tile = enc->curtile;
+
+ endcomps = &tile->tcmpts[tile->numtcmpts];
+ for (tcmpt = tile->tcmpts; tcmpt != endcomps; ++tcmpt) {
+ endlvls = &tcmpt->rlvls[tcmpt->numrlvls];
+ for (lvl = tcmpt->rlvls; lvl != endlvls; ++lvl) {
+ if (!lvl->bands) {
+ continue;
+ }
+ endbands = &lvl->bands[lvl->numbands];
+ for (band = lvl->bands; band != endbands; ++band) {
+ if (!band->data) {
+ continue;
+ }
+ for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
+ if (!prc->cblks) {
+ continue;
+ }
+ bmx = 0;
+ endcblks = &prc->cblks[prc->numcblks];
+ for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+ mx = 0;
+ for (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);
+ }
+
+ for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+ cblk->numimsbs = band->numbps - cblk->numbps;
+ assert(cblk->numimsbs >= 0);
+ }
+
+ for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
+ if (jpc_enc_enccblk(enc, cblk->stream, tcmpt, band, cblk)) {
+ return -1;
+ }
+ }
+ }
+ }
+ }
+ }
+ return 0;
+}
+
+int getthebyte(jas_stream_t *in, long off)
+{
+ int c;
+ long oldpos;
+ oldpos = jas_stream_tell(in);
+ assert(oldpos >= 0);
+ jas_stream_seek(in, off, SEEK_SET);
+ c = jas_stream_peekc(in);
+ jas_stream_seek(in, oldpos, SEEK_SET);
+ return c;
+}
+
+/* Encode a single code block. */
+int jpc_enc_enccblk(jpc_enc_t *enc, jas_stream_t *out, jpc_enc_tcmpt_t *tcmpt, jpc_enc_band_t *band, jpc_enc_cblk_t *cblk)
+{
+ jpc_enc_pass_t *pass;
+ jpc_enc_pass_t *endpasses;
+ int bitpos;
+ int n;
+ int adjust;
+ int ret;
+ int passtype;
+ int t;
+ jpc_bitstream_t *bout;
+ jpc_enc_pass_t *termpass;
+ jpc_enc_rlvl_t *rlvl;
+ int vcausal;
+ int segsym;
+ int termmode;
+ int c;
+
+ bout = 0;
+ rlvl = band->rlvl;
+
+ cblk->stream = jas_stream_memopen(0, 0);
+ assert(cblk->stream);
+ cblk->mqenc = jpc_mqenc_create(JPC_NUMCTXS, cblk->stream);
+ assert(cblk->mqenc);
+ jpc_mqenc_setctxs(cblk->mqenc, JPC_NUMCTXS, jpc_mqctxs);
+
+ cblk->numpasses = (cblk->numbps > 0) ? (3 * cblk->numbps - 2) : 0;
+ if (cblk->numpasses > 0) {
+ cblk->passes = jas_malloc(cblk->numpasses * sizeof(jpc_enc_pass_t));
+ assert(cblk->passes);
+ } else {
+ cblk->passes = 0;
+ }
+ endpasses = &cblk->passes[cblk->numpasses];
+ for (pass = cblk->passes; pass != endpasses; ++pass) {
+ pass->start = 0;
+ pass->end = 0;
+ pass->term = JPC_ISTERMINATED(pass - cblk->passes, 0, cblk->numpasses, (tcmpt->cblksty & JPC_COX_TERMALL) != 0, (tcmpt->cblksty & JPC_COX_LAZY) != 0);
+ pass->type = JPC_SEGTYPE(pass - cblk->passes, 0, (tcmpt->cblksty & JPC_COX_LAZY) != 0);
+ pass->lyrno = -1;
+if (pass == endpasses - 1) {
+assert(pass->term == 1);
+ pass->term = 1;
+}
+ }
+
+ cblk->flags = jas_matrix_create(jas_matrix_numrows(cblk->data) + 2,
+ jas_matrix_numcols(cblk->data) + 2);
+ assert(cblk->flags);
+
+
+ bitpos = cblk->numbps - 1;
+ pass = cblk->passes;
+ n = cblk->numpasses;
+ while (--n >= 0) {
+
+ if (pass->type == JPC_SEG_MQ) {
+ /* NOP */
+ } else {
+ assert(pass->type == JPC_SEG_RAW);
+ if (!bout) {
+ bout = jpc_bitstream_sopen(cblk->stream, "w");
+ assert(bout);
+ }
+ }
+
+#if 1
+ passtype = (pass - cblk->passes + 2) % 3;
+#else
+ passtype = JPC_PASSTYPE(pass - cblk->passes + 2);
+#endif
+ pass->start = jas_stream_tell(cblk->stream);
+#if 0
+assert(jas_stream_tell(cblk->stream) == jas_stream_getrwcount(cblk->stream));
+#endif
+ assert(bitpos >= 0);
+ vcausal = (tcmpt->cblksty & JPC_COX_VSC) != 0;
+ segsym = (tcmpt->cblksty & JPC_COX_SEGSYM) != 0;
+ if (pass->term) {
+ termmode = ((tcmpt->cblksty & JPC_COX_PTERM) ?
+ JPC_MQENC_PTERM : JPC_MQENC_DEFTERM) + 1;
+ } else {
+ termmode = 0;
+ }
+ switch (passtype) {
+ case JPC_SIGPASS:
+ ret = (pass->type == JPC_SEG_MQ) ? jpc_encsigpass(cblk->mqenc,
+ bitpos, band->orient, vcausal, cblk->flags,
+ cblk->data, termmode, &pass->nmsedec) :
+ jpc_encrawsigpass(bout, bitpos, vcausal, cblk->flags,
+ cblk->data, termmode, &pass->nmsedec);
+ break;
+ case JPC_REFPASS:
+ ret = (pass->type == JPC_SEG_MQ) ? jpc_encrefpass(cblk->mqenc,
+ bitpos, vcausal, cblk->flags, cblk->data, termmode,
+ &pass->nmsedec) : jpc_encrawrefpass(bout, bitpos,
+ vcausal, cblk->flags, cblk->data, termmode,
+ &pass->nmsedec);
+ break;
+ case JPC_CLNPASS:
+ assert(pass->type == JPC_SEG_MQ);
+ ret = jpc_encclnpass(cblk->mqenc, bitpos, band->orient,
+ vcausal, segsym, cblk->flags, cblk->data, termmode,
+ &pass->nmsedec);
+ break;
+ default:
+ assert(0);
+ break;
+ }
+
+ if (pass->type == JPC_SEG_MQ) {
+ if (pass->term) {
+ jpc_mqenc_init(cblk->mqenc);
+ }
+ jpc_mqenc_getstate(cblk->mqenc, &pass->mqencstate);
+ pass->end = jas_stream_tell(cblk->stream);
+ if (tcmpt->cblksty & JPC_COX_RESET) {
+ jpc_mqenc_setctxs(cblk->mqenc, JPC_NUMCTXS, jpc_mqctxs);
+ }
+ } else {
+ if (pass->term) {
+ if (jpc_bitstream_pending(bout)) {
+ jpc_bitstream_outalign(bout, 0x2a);
+ }
+ jpc_bitstream_close(bout);
+ bout = 0;
+ pass->end = jas_stream_tell(cblk->stream);
+ } else {
+ pass->end = jas_stream_tell(cblk->stream) +
+ jpc_bitstream_pending(bout);
+/* NOTE - This will not work. need to adjust by # of pending output bytes */
+ }
+ }
+#if 0
+/* XXX - This assertion fails sometimes when various coding modes are used.
+This seems to be harmless, but why does it happen at all? */
+assert(jas_stream_tell(cblk->stream) == jas_stream_getrwcount(cblk->stream));
+#endif
+
+ pass->wmsedec = jpc_fixtodbl(band->rlvl->tcmpt->synweight) *
+ jpc_fixtodbl(band->rlvl->tcmpt->synweight) *
+ jpc_fixtodbl(band->synweight) *
+ jpc_fixtodbl(band->synweight) *
+ jpc_fixtodbl(band->absstepsize) * jpc_fixtodbl(band->absstepsize) *
+ ((double) (1 << bitpos)) * ((double)(1 << bitpos)) *
+ jpc_fixtodbl(pass->nmsedec);
+ pass->cumwmsedec = pass->wmsedec;
+ if (pass != cblk->passes) {
+ pass->cumwmsedec += pass[-1].cumwmsedec;
+ }
+ if (passtype == JPC_CLNPASS) {
+ --bitpos;
+ }
+ ++pass;
+ }
+
+#if 0
+dump_passes(cblk->passes, cblk->numpasses, cblk);
+#endif
+
+ n = 0;
+ endpasses = &cblk->passes[cblk->numpasses];
+ for (pass = cblk->passes; pass != endpasses; ++pass) {
+ if (pass->start < n) {
+ pass->start = n;
+ }
+ if (pass->end < n) {
+ pass->end = n;
+ }
+ if (!pass->term) {
+ termpass = pass;
+ while (termpass - pass < cblk->numpasses &&
+ !termpass->term) {
+ ++termpass;
+ }
+ if (pass->type == JPC_SEG_MQ) {
+ t = (pass->mqencstate.lastbyte == 0xff) ? 1 : 0;
+ if (pass->mqencstate.ctreg >= 5) {
+ adjust = 4 + t;
+ } else {
+ adjust = 5 + t;
+ }
+ pass->end += adjust;
+ }
+ if (pass->end > termpass->end) {
+ pass->end = termpass->end;
+ }
+ if ((c = getthebyte(cblk->stream, pass->end - 1)) == EOF) {
+ abort();
+ }
+ if (c == 0xff) {
+ ++pass->end;
+ }
+ n = JAS_MAX(n, pass->end);
+ } else {
+ n = JAS_MAX(n, pass->end);
+ }
+ }
+
+#if 0
+dump_passes(cblk->passes, cblk->numpasses, cblk);
+#endif
+
+ if (bout) {
+ jpc_bitstream_close(bout);
+ }
+
+ return 0;
+}
+
+/******************************************************************************\
+* Code for significance pass.
+\******************************************************************************/
+
+#define sigpass_step(fp, frowstep, dp, bitpos, one, nmsedec, orient, mqenc, vcausalflag) \
+{ \
+ int f; \
+ int v; \
+ f = *(fp); \
+ if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \
+ v = (abs(*(dp)) & (one)) ? 1 : 0; \
+ jpc_mqenc_setcurctx(mqenc, JPC_GETZCCTXNO(f, (orient))); \
+ jpc_mqenc_putbit(mqenc, v); \
+ if (v) { \
+ *(nmsedec) += JPC_GETSIGNMSEDEC(abs(*(dp)), (bitpos) + JPC_NUMEXTRABITS); \
+ v = ((*(dp) < 0) ? 1 : 0); \
+ jpc_mqenc_setcurctx(mqenc, JPC_GETSCCTXNO(f)); \
+ jpc_mqenc_putbit(mqenc, v ^ JPC_GETSPB(f)); \
+ JPC_UPDATEFLAGS4(fp, frowstep, v, vcausalflag); \
+ *(fp) |= JPC_SIG; \
+ } \
+ *(fp) |= JPC_VISIT; \
+ } \
+}
+
+static int jpc_encsigpass(jpc_mqenc_t *mqenc, int bitpos, int orient, int vcausalflag,
+ jas_matrix_t *flags, jas_matrix_t *data, int term, long *nmsedec)
+{
+ int i;
+ int j;
+ int one;
+ int vscanlen;
+ int width;
+ int height;
+ int frowstep;
+ int drowstep;
+ int fstripestep;
+ int dstripestep;
+ jpc_fix_t *fstripestart;
+ jpc_fix_t *dstripestart;
+ jpc_fix_t *fp;
+ jpc_fix_t *dp;
+ jpc_fix_t *fvscanstart;
+ jpc_fix_t *dvscanstart;
+ int k;
+
+ *nmsedec = 0;
+ width = jas_matrix_numcols(data);
+ height = jas_matrix_numrows(data);
+ frowstep = jas_matrix_rowstep(flags);
+ drowstep = jas_matrix_rowstep(data);
+ fstripestep = frowstep << 2;
+ dstripestep = drowstep << 2;
+
+ one = 1 << (bitpos + JPC_NUMEXTRABITS);
+
+ fstripestart = jas_matrix_getref(flags, 1, 1);
+ dstripestart = jas_matrix_getref(data, 0, 0);
+ for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+ dstripestart += dstripestep) {
+ fvscanstart = fstripestart;
+ dvscanstart = dstripestart;
+ vscanlen = JAS_MIN(i, 4);
+ for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+ fp = fvscanstart;
+ dp = dvscanstart;
+ k = vscanlen;
+
+ sigpass_step(fp, frowstep, dp, bitpos, one,
+ nmsedec, orient, mqenc, vcausalflag);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+ sigpass_step(fp, frowstep, dp, bitpos, one,
+ nmsedec, orient, mqenc, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+ sigpass_step(fp, frowstep, dp, bitpos, one,
+ nmsedec, orient, mqenc, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+ sigpass_step(fp, frowstep, dp, bitpos, one,
+ nmsedec, orient, mqenc, 0);
+
+ }
+ }
+
+ if (term) {
+ jpc_mqenc_flush(mqenc, term - 1);
+ }
+
+ return jpc_mqenc_error(mqenc) ? (-1) : 0;
+}
+
+#define rawsigpass_step(fp, frowstep, dp, bitpos, one, nmsedec, out, vcausalflag) \
+{ \
+ jpc_fix_t f = *(fp); \
+ jpc_fix_t v; \
+ if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \
+ v = (abs(*(dp)) & (one)) ? 1 : 0; \
+ if ((jpc_bitstream_putbit((out), v)) == EOF) { \
+ return -1; \
+ } \
+ if (v) { \
+ *(nmsedec) += JPC_GETSIGNMSEDEC(abs(*(dp)), (bitpos) + JPC_NUMEXTRABITS); \
+ v = ((*(dp) < 0) ? 1 : 0); \
+ if (jpc_bitstream_putbit(out, v) == EOF) { \
+ return -1; \
+ } \
+ JPC_UPDATEFLAGS4(fp, frowstep, v, vcausalflag); \
+ *(fp) |= JPC_SIG; \
+ } \
+ *(fp) |= JPC_VISIT; \
+ } \
+}
+
+static int jpc_encrawsigpass(jpc_bitstream_t *out, int bitpos, int vcausalflag, jas_matrix_t *flags,
+ jas_matrix_t *data, int term, long *nmsedec)
+{
+ int i;
+ int j;
+ int k;
+ int one;
+ int vscanlen;
+ int width;
+ int height;
+ int frowstep;
+ int drowstep;
+ int fstripestep;
+ int dstripestep;
+ jpc_fix_t *fstripestart;
+ jpc_fix_t *dstripestart;
+ jpc_fix_t *fp;
+ jpc_fix_t *dp;
+ jpc_fix_t *fvscanstart;
+ jpc_fix_t *dvscanstart;
+
+ *nmsedec = 0;
+ width = jas_matrix_numcols(data);
+ height = jas_matrix_numrows(data);
+ frowstep = jas_matrix_rowstep(flags);
+ drowstep = jas_matrix_rowstep(data);
+ fstripestep = frowstep << 2;
+ dstripestep = drowstep << 2;
+
+ one = 1 << (bitpos + JPC_NUMEXTRABITS);
+
+ fstripestart = jas_matrix_getref(flags, 1, 1);
+ dstripestart = jas_matrix_getref(data, 0, 0);
+ for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+ dstripestart += dstripestep) {
+ fvscanstart = fstripestart;
+ dvscanstart = dstripestart;
+ vscanlen = JAS_MIN(i, 4);
+ for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+ fp = fvscanstart;
+ dp = dvscanstart;
+ k = vscanlen;
+
+ rawsigpass_step(fp, frowstep, dp, bitpos, one,
+ nmsedec, out, vcausalflag);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ rawsigpass_step(fp, frowstep, dp, bitpos, one,
+ nmsedec, out, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ rawsigpass_step(fp, frowstep, dp, bitpos, one,
+ nmsedec, out, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ rawsigpass_step(fp, frowstep, dp, bitpos, one,
+ nmsedec, out, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+
+ }
+ }
+
+ if (term) {
+ jpc_bitstream_outalign(out, 0x2a);
+ }
+
+ return 0;
+}
+
+/******************************************************************************\
+* Code for refinement pass.
+\******************************************************************************/
+
+#define refpass_step(fp, dp, bitpos, one, nmsedec, mqenc, vcausalflag) \
+{ \
+ int v; \
+ if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \
+ (d) = *(dp); \
+ *(nmsedec) += JPC_GETREFNMSEDEC(abs(d), (bitpos) + JPC_NUMEXTRABITS); \
+ jpc_mqenc_setcurctx((mqenc), JPC_GETMAGCTXNO(*(fp))); \
+ v = (abs(d) & (one)) ? 1 : 0; \
+ jpc_mqenc_putbit((mqenc), v); \
+ *(fp) |= JPC_REFINE; \
+ } \
+}
+
+static int jpc_encrefpass(jpc_mqenc_t *mqenc, int bitpos, int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data,
+ int term, long *nmsedec)
+{
+ int i;
+ int j;
+ int one;
+ int vscanlen;
+ int d;
+ int width;
+ int height;
+ int frowstep;
+ int drowstep;
+ int fstripestep;
+ int dstripestep;
+ jpc_fix_t *fstripestart;
+ jpc_fix_t *dstripestart;
+ jpc_fix_t *fvscanstart;
+ jpc_fix_t *dvscanstart;
+ jpc_fix_t *dp;
+ jpc_fix_t *fp;
+int k;
+
+ *nmsedec = 0;
+ width = jas_matrix_numcols(data);
+ height = jas_matrix_numrows(data);
+ frowstep = jas_matrix_rowstep(flags);
+ drowstep = jas_matrix_rowstep(data);
+ fstripestep = frowstep << 2;
+ dstripestep = drowstep << 2;
+
+ one = 1 << (bitpos + JPC_NUMEXTRABITS);
+
+ fstripestart = jas_matrix_getref(flags, 1, 1);
+ dstripestart = jas_matrix_getref(data, 0, 0);
+ for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+ dstripestart += dstripestep) {
+ fvscanstart = fstripestart;
+ dvscanstart = dstripestart;
+ vscanlen = JAS_MIN(i, 4);
+ for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+ fp = fvscanstart;
+ dp = dvscanstart;
+ k = vscanlen;
+
+ refpass_step(fp, dp, bitpos, one, nmsedec,
+ mqenc, vcausalflag);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+ refpass_step(fp, dp, bitpos, one, nmsedec,
+ mqenc, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+ refpass_step(fp, dp, bitpos, one, nmsedec,
+ mqenc, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+ refpass_step(fp, dp, bitpos, one, nmsedec,
+ mqenc, 0);
+
+ }
+ }
+
+ if (term) {
+ jpc_mqenc_flush(mqenc, term - 1);
+ }
+
+ return jpc_mqenc_error(mqenc) ? (-1) : 0;
+}
+
+#define rawrefpass_step(fp, dp, bitpos, one, nmsedec, out, vcausalflag) \
+{ \
+ jpc_fix_t d; \
+ jpc_fix_t v; \
+ if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \
+ d = *(dp); \
+ *(nmsedec) += JPC_GETREFNMSEDEC(abs(d), (bitpos) + JPC_NUMEXTRABITS); \
+ v = (abs(d) & (one)) ? 1 : 0; \
+ if (jpc_bitstream_putbit((out), v) == EOF) { \
+ return -1; \
+ } \
+ *(fp) |= JPC_REFINE; \
+ } \
+}
+
+static int jpc_encrawrefpass(jpc_bitstream_t *out, int bitpos, int vcausalflag, jas_matrix_t *flags,
+ jas_matrix_t *data, int term, long *nmsedec)
+{
+ int i;
+ int j;
+ int k;
+ int one;
+ int vscanlen;
+ int width;
+ int height;
+ int frowstep;
+ int drowstep;
+ int fstripestep;
+ int dstripestep;
+ jpc_fix_t *fstripestart;
+ jpc_fix_t *dstripestart;
+ jpc_fix_t *fvscanstart;
+ jpc_fix_t *dvscanstart;
+ jpc_fix_t *dp;
+ jpc_fix_t *fp;
+
+ *nmsedec = 0;
+ width = jas_matrix_numcols(data);
+ height = jas_matrix_numrows(data);
+ frowstep = jas_matrix_rowstep(flags);
+ drowstep = jas_matrix_rowstep(data);
+ fstripestep = frowstep << 2;
+ dstripestep = drowstep << 2;
+
+ one = 1 << (bitpos + JPC_NUMEXTRABITS);
+
+ fstripestart = jas_matrix_getref(flags, 1, 1);
+ dstripestart = jas_matrix_getref(data, 0, 0);
+ for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+ dstripestart += dstripestep) {
+ fvscanstart = fstripestart;
+ dvscanstart = dstripestart;
+ vscanlen = JAS_MIN(i, 4);
+ for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+ fp = fvscanstart;
+ dp = dvscanstart;
+ k = vscanlen;
+
+ rawrefpass_step(fp, dp, bitpos, one, nmsedec,
+ out, vcausalflag);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+ rawrefpass_step(fp, dp, bitpos, one, nmsedec,
+ out, vcausalflag);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+ rawrefpass_step(fp, dp, bitpos, one, nmsedec,
+ out, vcausalflag);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+ rawrefpass_step(fp, dp, bitpos, one, nmsedec,
+ out, vcausalflag);
+
+ }
+ }
+
+ if (term) {
+ jpc_bitstream_outalign(out, 0x2a);
+ }
+
+ return 0;
+}
+
+/******************************************************************************\
+* Code for cleanup pass.
+\******************************************************************************/
+
+#define clnpass_step(fp, frowstep, dp, bitpos, one, orient, nmsedec, mqenc, label1, label2, vcausalflag) \
+{ \
+ int f; \
+ int v; \
+label1 \
+ f = *(fp); \
+ if (!(f & (JPC_SIG | JPC_VISIT))) { \
+ jpc_mqenc_setcurctx(mqenc, JPC_GETZCCTXNO(f, (orient))); \
+ v = (abs(*(dp)) & (one)) ? 1 : 0; \
+ jpc_mqenc_putbit((mqenc), v); \
+ if (v) { \
+label2 \
+ f = *(fp); \
+ /* Coefficient is significant. */ \
+ *(nmsedec) += JPC_GETSIGNMSEDEC(abs(*(dp)), (bitpos) + JPC_NUMEXTRABITS); \
+ jpc_mqenc_setcurctx((mqenc), JPC_GETSCCTXNO(f)); \
+ v = ((*(dp) < 0) ? 1 : 0); \
+ jpc_mqenc_putbit((mqenc), v ^ JPC_GETSPB(f)); \
+ JPC_UPDATEFLAGS4((fp), (frowstep), v, vcausalflag); \
+ *(fp) |= JPC_SIG; \
+ } \
+ } \
+ *(fp) &= ~JPC_VISIT; \
+}
+
+static int jpc_encclnpass(jpc_mqenc_t *mqenc, int bitpos, int orient, int vcausalflag, int segsymflag, jas_matrix_t *flags,
+ jas_matrix_t *data, int term, long *nmsedec)
+{
+ int i;
+ int j;
+ int k;
+ int vscanlen;
+ int v;
+ int runlen;
+ jpc_fix_t *fp;
+ int width;
+ int height;
+ jpc_fix_t *dp;
+ int one;
+ int frowstep;
+ int drowstep;
+ int fstripestep;
+ int dstripestep;
+ jpc_fix_t *fstripestart;
+ jpc_fix_t *dstripestart;
+ jpc_fix_t *fvscanstart;
+ jpc_fix_t *dvscanstart;
+
+ *nmsedec = 0;
+ width = jas_matrix_numcols(data);
+ height = jas_matrix_numrows(data);
+ frowstep = jas_matrix_rowstep(flags);
+ drowstep = jas_matrix_rowstep(data);
+ fstripestep = frowstep << 2;
+ dstripestep = drowstep << 2;
+
+ one = 1 << (bitpos + JPC_NUMEXTRABITS);
+
+ fstripestart = jas_matrix_getref(flags, 1, 1);
+ dstripestart = jas_matrix_getref(data, 0, 0);
+ for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+ dstripestart += dstripestep) {
+ fvscanstart = fstripestart;
+ dvscanstart = dstripestart;
+ vscanlen = JAS_MIN(i, 4);
+ for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+
+ fp = fvscanstart;
+ if (vscanlen >= 4 && !((*fp) & (JPC_SIG | JPC_VISIT |
+ JPC_OTHSIGMSK)) && (fp += frowstep, !((*fp) & (JPC_SIG |
+ JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep, !((*fp) &
+ (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep,
+ !((*fp) & (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK)))) {
+ dp = dvscanstart;
+ for (k = 0; k < vscanlen; ++k) {
+ v = (abs(*dp) & one) ? 1 : 0;
+ if (v) {
+ break;
+ }
+ dp += drowstep;
+ }
+ runlen = k;
+ if (runlen >= 4) {
+ jpc_mqenc_setcurctx(mqenc, JPC_AGGCTXNO);
+ jpc_mqenc_putbit(mqenc, 0);
+ continue;
+ }
+ jpc_mqenc_setcurctx(mqenc, JPC_AGGCTXNO);
+ jpc_mqenc_putbit(mqenc, 1);
+ jpc_mqenc_setcurctx(mqenc, JPC_UCTXNO);
+ jpc_mqenc_putbit(mqenc, runlen >> 1);
+ jpc_mqenc_putbit(mqenc, runlen & 1);
+ fp = fvscanstart + frowstep * runlen;
+ dp = dvscanstart + drowstep * runlen;
+ k = vscanlen - runlen;
+ switch (runlen) {
+ case 0:
+ goto clnpass_partial0;
+ break;
+ case 1:
+ goto clnpass_partial1;
+ break;
+ case 2:
+ goto clnpass_partial2;
+ break;
+ case 3:
+ goto clnpass_partial3;
+ break;
+ }
+ } else {
+ runlen = 0;
+ fp = fvscanstart;
+ dp = dvscanstart;
+ k = vscanlen;
+ goto clnpass_full0;
+ }
+ clnpass_step(fp, frowstep, dp, bitpos, one,
+ orient, nmsedec, mqenc, clnpass_full0:, clnpass_partial0:, vcausalflag);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+ clnpass_step(fp, frowstep, dp, bitpos, one,
+ orient, nmsedec, mqenc, ;, clnpass_partial1:, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+ clnpass_step(fp, frowstep, dp, bitpos, one,
+ orient, nmsedec, mqenc, ;, clnpass_partial2:, 0);
+ if (--k <= 0) {
+ continue;
+ }
+ fp += frowstep;
+ dp += drowstep;
+ clnpass_step(fp, frowstep, dp, bitpos, one,
+ orient, nmsedec, mqenc, ;, clnpass_partial3:, 0);
+ }
+ }
+
+ if (segsymflag) {
+ jpc_mqenc_setcurctx(mqenc, JPC_UCTXNO);
+ jpc_mqenc_putbit(mqenc, 1);
+ jpc_mqenc_putbit(mqenc, 0);
+ jpc_mqenc_putbit(mqenc, 1);
+ jpc_mqenc_putbit(mqenc, 0);
+ }
+
+ if (term) {
+ jpc_mqenc_flush(mqenc, term - 1);
+ }
+
+ return jpc_mqenc_error(mqenc) ? (-1) : 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1enc.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1enc.h
new file mode 100644
index 0000000..a4845a5
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t1enc.h
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier 1 Encoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_T1ENC_H
+#define JPC_T1ENC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_seq.h"
+
+#include "jpc_enc.h"
+#include "jpc_t1cod.h"
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Encode all of the code blocks. */
+int jpc_enc_enccblks(jpc_enc_t *enc);
+
+/* Encode a single code block. */
+int jpc_enc_enccblk(jpc_enc_t *enc, jas_stream_t *out, jpc_enc_tcmpt_t *comp,
+ jpc_enc_band_t *band, jpc_enc_cblk_t *cblk);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2cod.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2cod.c
new file mode 100644
index 0000000..e734900
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2cod.c
@@ -0,0 +1,684 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier-2 Coding Library
+ *
+ * $Id$
+ */
+
+#include "jasper/jas_math.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_math.h"
+
+#include "jpc_cs.h"
+#include "jpc_t2cod.h"
+#include "jpc_math.h"
+
+static int jpc_pi_nextlrcp(jpc_pi_t *pi);
+static int jpc_pi_nextrlcp(jpc_pi_t *pi);
+static int jpc_pi_nextrpcl(jpc_pi_t *pi);
+static int jpc_pi_nextpcrl(jpc_pi_t *pi);
+static int jpc_pi_nextcprl(jpc_pi_t *pi);
+
+int jpc_pi_next(jpc_pi_t *pi)
+{
+ 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 <
+ JAS_CAST(int, 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 < JAS_CAST(int, pchg->compnoend); ++pi->compno,
+ ++pi->picomp) {
+ if (pi->rlvlno >= pi->picomp->numrlvls) {
+ continue;
+ }
+ pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
+ for (pi->prcno = 0, prclyrno =
+ pi->pirlvl->prclyrnos; pi->prcno <
+ pi->pirlvl->numprcs; ++pi->prcno,
+ ++prclyrno) {
+ if (pi->lyrno >= *prclyrno) {
+ *prclyrno = pi->lyrno;
+ ++(*prclyrno);
+ return 0;
+ }
+skip:
+ ;
+ }
+ }
+ }
+ }
+ return 1;
+}
+
+static int jpc_pi_nextrlcp(register jpc_pi_t *pi)
+{
+ 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 <
+ JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
+ for (pi->compno = pchg->compnostart, pi->picomp =
+ &pi->picomps[pi->compno]; pi->compno < pi->numcomps &&
+ pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) {
+ if (pi->rlvlno >= pi->picomp->numrlvls) {
+ continue;
+ }
+ pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
+ for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos;
+ pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) {
+ if (pi->lyrno >= *prclyrno) {
+ *prclyrno = pi->lyrno;
+ ++(*prclyrno);
+ return 0;
+ }
+skip:
+ ;
+ }
+ }
+ }
+ }
+ return 1;
+}
+
+static int jpc_pi_nextrpcl(register jpc_pi_t *pi)
+{
+ 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 < JAS_CAST(int, 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 < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
+ prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
+ if (pi->lyrno >= *prclyrno) {
+ ++(*prclyrno);
+ return 0;
+ }
+skip:
+ ;
+ }
+ }
+ }
+ }
+ }
+ }
+ return 1;
+}
+
+static int jpc_pi_nextpcrl(register jpc_pi_t *pi)
+{
+ 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 < JAS_CAST(int, 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 < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
+ prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
+ if (pi->lyrno >= *prclyrno) {
+ ++(*prclyrno);
+ return 0;
+ }
+skip:
+ ;
+ }
+ }
+ }
+ }
+ }
+ }
+ return 1;
+}
+
+static int jpc_pi_nextcprl(register jpc_pi_t *pi)
+{
+ 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 < JAS_CAST(int, 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 < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
+ prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
+ if (pi->lyrno >= *prclyrno) {
+ ++(*prclyrno);
+ return 0;
+ }
+skip:
+ ;
+ }
+ }
+ }
+ }
+ }
+ }
+ return 1;
+}
+
+static void pirlvl_destroy(jpc_pirlvl_t *rlvl)
+{
+ if (rlvl->prclyrnos) {
+ jas_free(rlvl->prclyrnos);
+ }
+}
+
+static void jpc_picomp_destroy(jpc_picomp_t *picomp)
+{
+ 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_pi_t *jpc_pi_create0()
+{
+ jpc_pi_t *pi;
+ if (!(pi = jas_malloc(sizeof(jpc_pi_t)))) {
+ return 0;
+ }
+ pi->picomps = 0;
+ pi->pchgno = 0;
+ if (!(pi->pchglist = jpc_pchglist_create())) {
+ jas_free(pi);
+ return 0;
+ }
+ return pi;
+}
+
+int jpc_pi_addpchg(jpc_pi_t *pi, jpc_pocpchg_t *pchg)
+{
+ return jpc_pchglist_insert(pi->pchglist, -1, pchg);
+}
+
+jpc_pchglist_t *jpc_pchglist_create()
+{
+ jpc_pchglist_t *pchglist;
+ if (!(pchglist = jas_malloc(sizeof(jpc_pchglist_t)))) {
+ return 0;
+ }
+ pchglist->numpchgs = 0;
+ pchglist->maxpchgs = 0;
+ pchglist->pchgs = 0;
+ return pchglist;
+}
+
+int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg)
+{
+ 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;
+}
+
+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_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;
+}
+
+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);
+}
+
+void jpc_pchg_destroy(jpc_pchg_t *pchg)
+{
+ jas_free(pchg);
+}
+
+jpc_pchg_t *jpc_pchglist_get(jpc_pchglist_t *pchglist, int pchgno)
+{
+ return pchglist->pchgs[pchgno];
+}
+
+int jpc_pchglist_numpchgs(jpc_pchglist_t *pchglist)
+{
+ 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;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2cod.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2cod.h
new file mode 100644
index 0000000..0a176c9
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2cod.h
@@ -0,0 +1,299 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier-2 Coding Library
+ *
+ * $Id$
+ */
+
+#ifndef JPC_T2COD_H
+#define JPC_T2COD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jpc_cs.h"
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* Progression change list. */
+
+typedef struct {
+
+ /* The number of progression changes. */
+ int numpchgs;
+
+ /* The maximum number of progression changes that can be accomodated
+ without growing the progression change array. */
+ int maxpchgs;
+
+ /* The progression changes. */
+ jpc_pchg_t **pchgs;
+
+} jpc_pchglist_t;
+
+/* Packet iterator per-resolution-level information. */
+
+typedef struct {
+
+ /* The number of precincts. */
+ int numprcs;
+
+ /* The last layer processed for each precinct. */
+ int *prclyrnos;
+
+ /* The precinct width exponent. */
+ int prcwidthexpn;
+
+ /* The precinct height exponent. */
+ int prcheightexpn;
+
+ /* The number of precincts spanning the resolution level in the horizontal
+ direction. */
+ int numhprcs;
+
+} jpc_pirlvl_t;
+
+/* Packet iterator per-component information. */
+
+typedef struct {
+
+ /* The number of resolution levels. */
+ int numrlvls;
+
+ /* The per-resolution-level information. */
+ jpc_pirlvl_t *pirlvls;
+
+ /* The horizontal sampling period. */
+ int hsamp;
+
+ /* The vertical sampling period. */
+ int vsamp;
+
+} jpc_picomp_t;
+
+/* Packet iterator class. */
+
+typedef struct {
+
+ /* The number of layers. */
+ int numlyrs;
+
+ /* The number of resolution levels. */
+ int maxrlvls;
+
+ /* The number of components. */
+ int numcomps;
+
+ /* The per-component information. */
+ jpc_picomp_t *picomps;
+
+ /* The current component. */
+ jpc_picomp_t *picomp;
+
+ /* The current resolution level. */
+ jpc_pirlvl_t *pirlvl;
+
+ /* The number of the current component. */
+ int compno;
+
+ /* The number of the current resolution level. */
+ int rlvlno;
+
+ /* The number of the current precinct. */
+ int prcno;
+
+ /* The number of the current layer. */
+ int lyrno;
+
+ /* The x-coordinate of the current position. */
+ int x;
+
+ /* The y-coordinate of the current position. */
+ int y;
+
+ /* The horizontal step size. */
+ int xstep;
+
+ /* The vertical step size. */
+ int ystep;
+
+ /* 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 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 current progression change. */
+ jpc_pchg_t *pchg;
+
+ /* The progression change list. */
+ jpc_pchglist_t *pchglist;
+
+ /* The progression to use in the absense of explicit specification. */
+ jpc_pchg_t defaultpchg;
+
+ /* The current progression change number. */
+ int pchgno;
+
+ /* Is this the first time in the current progression volume? */
+ bool prgvolfirst;
+
+ /* Is the current iterator value valid? */
+ bool valid;
+
+ /* The current packet number. */
+ int pktno;
+
+} jpc_pi_t;
+
+/******************************************************************************\
+* Functions/macros for packet iterators.
+\******************************************************************************/
+
+/* Create a packet iterator. */
+jpc_pi_t *jpc_pi_create0(void);
+
+/* Destroy a packet iterator. */
+void jpc_pi_destroy(jpc_pi_t *pi);
+
+/* Add a progression change to a packet iterator. */
+int jpc_pi_addpchg(jpc_pi_t *pi, jpc_pocpchg_t *pchg);
+
+/* Prepare a packet iterator for iteration. */
+int jpc_pi_init(jpc_pi_t *pi);
+
+/* Set the iterator to the first packet. */
+int jpc_pi_begin(jpc_pi_t *pi);
+
+/* Proceed to the next packet in sequence. */
+int jpc_pi_next(jpc_pi_t *pi);
+
+/* Get the index of the current packet. */
+#define jpc_pi_getind(pi) ((pi)->pktno)
+
+/* Get the component number of the current packet. */
+#define jpc_pi_cmptno(pi) (assert(pi->valid), (pi)->compno)
+
+/* Get the resolution level of the current packet. */
+#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)
+
+/* Get the precinct number of the current packet. */
+#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)
+
+/******************************************************************************\
+* Functions/macros for progression change lists.
+\******************************************************************************/
+
+/* Create a progression change list. */
+jpc_pchglist_t *jpc_pchglist_create(void);
+
+/* Destroy a progression change list. */
+void jpc_pchglist_destroy(jpc_pchglist_t *pchglist);
+
+/* Insert a new element into a progression change list. */
+int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg);
+
+/* Remove an element from a progression change list. */
+jpc_pchg_t *jpc_pchglist_remove(jpc_pchglist_t *pchglist, int pchgno);
+
+/* Get an element from a progression change list. */
+jpc_pchg_t *jpc_pchglist_get(jpc_pchglist_t *pchglist, int pchgno);
+
+/* Copy a progression change list. */
+jpc_pchglist_t *jpc_pchglist_copy(jpc_pchglist_t *pchglist);
+
+/* Get the number of elements in a progression change list. */
+int jpc_pchglist_numpchgs(jpc_pchglist_t *pchglist);
+
+/******************************************************************************\
+* Functions/macros for progression changes.
+\******************************************************************************/
+
+/* Destroy a progression change. */
+void jpc_pchg_destroy(jpc_pchg_t *pchg);
+
+/* Copy a progression change. */
+jpc_pchg_t *jpc_pchg_copy(jpc_pchg_t *pchg);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2dec.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2dec.c
new file mode 100644
index 0000000..6d2cb72
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2dec.c
@@ -0,0 +1,581 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier 2 Decoder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#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"
+#include "jasper/jas_debug.h"
+
+#include "jpc_bs.h"
+#include "jpc_dec.h"
+#include "jpc_cs.h"
+#include "jpc_mqdec.h"
+#include "jpc_t2dec.h"
+#include "jpc_t1cod.h"
+#include "jpc_math.h"
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+long jpc_dec_lookahead(jas_stream_t *in);
+static int jpc_getcommacode(jpc_bitstream_t *in);
+static int jpc_getnumnewpasses(jpc_bitstream_t *in);
+static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int lvlno,
+ int prcno, int lyrno);
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+static int jpc_getcommacode(jpc_bitstream_t *in)
+{
+ int n;
+ int v;
+
+ n = 0;
+ for (;;) {
+ if ((v = jpc_bitstream_getbit(in)) < 0) {
+ return -1;
+ }
+ if (jpc_bitstream_eof(in)) {
+ return -1;
+ }
+ if (!v) {
+ break;
+ }
+ ++n;
+ }
+
+ return n;
+}
+
+static int jpc_getnumnewpasses(jpc_bitstream_t *in)
+{
+ int n;
+
+ if ((n = jpc_bitstream_getbit(in)) > 0) {
+ if ((n = jpc_bitstream_getbit(in)) > 0) {
+ if ((n = jpc_bitstream_getbits(in, 2)) == 3) {
+ if ((n = jpc_bitstream_getbits(in, 5)) == 31) {
+ if ((n = jpc_bitstream_getbits(in, 7)) >= 0) {
+ n += 36 + 1;
+ }
+ } else if (n >= 0) {
+ n += 5 + 1;
+ }
+ } else if (n >= 0) {
+ n += 2 + 1;
+ }
+ } else if (!n) {
+ n += 2;
+ }
+ } else if (!n) {
+ ++n;
+ }
+
+ return n;
+}
+
+static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int rlvlno,
+ int prcno, 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;
+
+ /* Avoid compiler warning about possible use of uninitialized
+ variable. */
+ bodylen = 0;
+
+ discard = (lyrno >= dec->maxlyrs);
+
+ tile = dec->curtile;
+ cp = tile->cp;
+ ccp = &cp->ccps[compno];
+
+ /*
+ * Decode the packet header.
+ */
+
+ /* Decode the SOP marker segment if present. */
+ if (cp->csty & JPC_COD_SOP) {
+ if (jpc_dec_lookahead(in) == JPC_MS_SOP) {
+ if (!(ms = jpc_getms(in, dec->cstate))) {
+ return -1;
+ }
+ if (jpc_ms_gettype(ms) != JPC_MS_SOP) {
+ jpc_ms_destroy(ms);
+ jas_eprintf("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)) {
+ jas_eprintf("alignment failed\n");
+ return -1;
+ }
+ }
+ jpc_bitstream_close(inb);
+
+ hdroffend = jas_stream_getrwcount(pkthdrstream);
+ hdrlen = hdroffend - hdroffstart;
+ if (jas_getdbglevel() >= 5) {
+ jas_eprintf("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))) {
+ jas_eprintf("cannot get (EPH) marker segment\n");
+ return -1;
+ }
+ if (jpc_ms_gettype(ms) != JPC_MS_EPH) {
+ jpc_ms_destroy(ms);
+ jas_eprintf("missing EPH marker segment\n");
+ return -1;
+ }
+ jpc_ms_destroy(ms);
+ }
+ }
+
+ /* decode the packet body. */
+
+ if (jas_getdbglevel() >= 1) {
+ jas_eprintf("packet body offset=%06ld\n", (long) jas_stream_getrwcount(in));
+ }
+
+ if (!discard) {
+ tcomp = &tile->tcomps[compno];
+ rlvl = &tcomp->rlvls[rlvlno];
+ 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
+jas_eprintf("lyrno=%02d, compno=%02d, lvlno=%02d, prcno=%02d, bandno=%02d, cblkno=%02d, passno=%02d numpasses=%02d cnt=%d numbps=%d, numimsbs=%d\n", lyrno, compno, rlvlno, prcno, band - rlvl->bands, cblk - prc->cblks, seg->passno, seg->numpasses, seg->cnt, band->numbps, cblk->numimsbs);
+#endif
+ if (seg->cnt > 0) {
+ if (jpc_getdata(in, seg->stream, seg->cnt) < 0) {
+ return -1;
+ }
+ seg->cnt = 0;
+ }
+ if (seg->numpasses >= seg->maxpasses) {
+ cblk->curseg = seg->next;
+ }
+ seg = seg->next;
+ }
+ }
+ }
+ } else {
+ if (jas_stream_gobble(in, bodylen) != JAS_CAST(int, bodylen)) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+/********************************************************************************************/
+/********************************************************************************************/
+
+int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in)
+{
+ jpc_dec_tile_t *tile;
+ jpc_pi_t *pi;
+ int ret;
+
+ tile = dec->curtile;
+ pi = tile->pi;
+ for (;;) {
+if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) {
+ switch (jpc_dec_lookahead(in)) {
+ case JPC_MS_EOC:
+ case JPC_MS_SOT:
+ return 0;
+ 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 (dec->maxpkts >= 0 && dec->numpkts >= dec->maxpkts) {
+ jas_eprintf("warning: stopping decode prematurely as requested\n");
+ return 0;
+}
+ if (jas_getdbglevel() >= 1) {
+ jas_eprintf("packet offset=%08ld prg=%d cmptno=%02d "
+ "rlvlno=%02d prcno=%03d lyrno=%02d\n", (long)
+ jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi),
+ jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi));
+ }
+ if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi),
+ jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {
+ return -1;
+ }
+++dec->numpkts;
+ }
+
+ 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) {
+/* 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;
+}
+
+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;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2dec.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2dec.h
new file mode 100644
index 0000000..68c8202
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2dec.h
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier 2 Decoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_T2DEC_H
+#define JPC_T2DEC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_fix.h"
+#include "jasper/jas_stream.h"
+
+#include "jpc_bs.h"
+#include "jpc_dec.h"
+#include "jpc_mqdec.h"
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Decode the packets for a tile-part. */
+int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream,
+ jas_stream_t *in);
+
+/* Create a packet iterator for the decoder. */
+jpc_pi_t *jpc_dec_pi_create(jpc_dec_t *dec, jpc_dec_tile_t *tile);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2enc.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2enc.c
new file mode 100644
index 0000000..9358a1c
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2enc.c
@@ -0,0 +1,655 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier 2 Encoder
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#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"
+
+#include "jpc_flt.h"
+#include "jpc_t2enc.h"
+#include "jpc_t2cod.h"
+#include "jpc_tagtree.h"
+#include "jpc_enc.h"
+#include "jpc_math.h"
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+static int jpc_putcommacode(jpc_bitstream_t *out, int n)
+{
+ assert(n >= 0);
+
+ while (--n >= 0) {
+ if (jpc_bitstream_putbit(out, 1) == EOF) {
+ return -1;
+ }
+ }
+ if (jpc_bitstream_putbit(out, 0) == EOF) {
+ return -1;
+ }
+ return 0;
+}
+
+static int jpc_putnumnewpasses(jpc_bitstream_t *out, int n)
+{
+ int ret;
+
+ if (n <= 0) {
+ return -1;
+ } else if (n == 1) {
+ ret = jpc_bitstream_putbit(out, 0);
+ } else if (n == 2) {
+ ret = jpc_bitstream_putbits(out, 2, 2);
+ } else if (n <= 5) {
+ ret = jpc_bitstream_putbits(out, 4, 0xc | (n - 3));
+ } else if (n <= 36) {
+ ret = jpc_bitstream_putbits(out, 9, 0x1e0 | (n - 6));
+ } else if (n <= 164) {
+ ret = jpc_bitstream_putbits(out, 16, 0xff80 | (n - 37));
+ } else {
+ /* The standard has no provision for encoding a larger value.
+ In practice, however, it is highly unlikely that this
+ limitation will ever be encountered. */
+ return -1;
+ }
+
+ return (ret != EOF) ? 0 : (-1);
+}
+
+int jpc_enc_encpkts(jpc_enc_t *enc, jas_stream_t *out)
+{
+ jpc_enc_tile_t *tile;
+ jpc_pi_t *pi;
+
+ tile = enc->curtile;
+
+ jpc_init_t2state(enc, 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;
+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;
+}
+
+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;
+ int 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;
+ int 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;
+ int 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) {
+/* 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;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2enc.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2enc.h
new file mode 100644
index 0000000..83b325c
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_t2enc.h
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tier 2 Encoder
+ *
+ * $Id$
+ */
+
+#ifndef JPC_T2ENC_H
+#define JPC_T2ENC_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#include "jpc_enc.h"
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Encode the packets for a tile. */
+int jpc_enc_encpkts(jpc_enc_t *enc, jas_stream_t *out);
+
+/* Encode the specified packet. */
+int jpc_enc_encpkt(jpc_enc_t *enc, jas_stream_t *out, int compno, int lvlno,
+ int prcno, int lyrno);
+
+/* Save the tier-2 coding state. */
+void jpc_save_t2state(jpc_enc_t *enc);
+
+/* Restore the tier-2 coding state. */
+void jpc_restore_t2state(jpc_enc_t *enc);
+
+/* Initialize the tier-2 coding state. */
+void jpc_init_t2state(jpc_enc_t *enc, int raflag);
+
+/* Create a packet iterator for the encoder. */
+jpc_pi_t *jpc_enc_pi_create(jpc_enc_cp_t *cp, jpc_enc_tile_t *tile);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tagtree.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tagtree.c
new file mode 100644
index 0000000..06422d3
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tagtree.c
@@ -0,0 +1,393 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tag Tree Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <limits.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <stdio.h>
+
+#include "jasper/jas_malloc.h"
+
+#include "jpc_tagtree.h"
+
+/******************************************************************************\
+* Prototypes.
+\******************************************************************************/
+
+static jpc_tagtree_t *jpc_tagtree_alloc(void);
+
+/******************************************************************************\
+* Code for creating and destroying tag trees.
+\******************************************************************************/
+
+/* Create a tag tree. */
+
+jpc_tagtree_t *jpc_tagtree_create(int numleafsh, int numleafsv)
+{
+ int nplh[JPC_TAGTREE_MAXDEPTH];
+ int nplv[JPC_TAGTREE_MAXDEPTH];
+ jpc_tagtreenode_t *node;
+ jpc_tagtreenode_t *parentnode;
+ jpc_tagtreenode_t *parentnode0;
+ jpc_tagtree_t *tree;
+ int i;
+ int j;
+ int k;
+ int numlvls;
+ int n;
+
+ assert(numleafsh > 0 && numleafsv > 0);
+
+ if (!(tree = jpc_tagtree_alloc())) {
+ return 0;
+ }
+ tree->numleafsh_ = numleafsh;
+ tree->numleafsv_ = numleafsv;
+
+ numlvls = 0;
+ nplh[0] = numleafsh;
+ nplv[0] = numleafsv;
+ do {
+ n = nplh[numlvls] * nplv[numlvls];
+ nplh[numlvls + 1] = (nplh[numlvls] + 1) / 2;
+ nplv[numlvls + 1] = (nplv[numlvls] + 1) / 2;
+ tree->numnodes_ += n;
+ ++numlvls;
+ } while (n > 1);
+
+ if (!(tree->nodes_ = jas_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);
+}
+
+static jpc_tagtree_t *jpc_tagtree_alloc()
+{
+ jpc_tagtree_t *tree;
+
+ if (!(tree = jas_malloc(sizeof(jpc_tagtree_t)))) {
+ return 0;
+ }
+ tree->numleafsh_ = 0;
+ tree->numleafsv_ = 0;
+ tree->numnodes_ = 0;
+ tree->nodes_ = 0;
+
+ return tree;
+}
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+/* Copy state information from one tag tree to another. */
+
+void jpc_tagtree_copy(jpc_tagtree_t *dsttree, 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;
+ }
+}
+
+/* Reset all of the state information associated with a tag tree. */
+
+void jpc_tagtree_reset(jpc_tagtree_t *tree)
+{
+ int n;
+ jpc_tagtreenode_t *node;
+
+ n = tree->numnodes_;
+ node = tree->nodes_;
+
+ while (--n >= 0) {
+ node->value_ = INT_MAX;
+ node->low_ = 0;
+ node->known_ = 0;
+ ++node;
+ }
+}
+
+/* Set the value associated with the specified leaf node, updating
+the other nodes as necessary. */
+
+void jpc_tagtree_setvalue(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf,
+ int value)
+{
+ jpc_tagtreenode_t *node;
+
+ /* Avoid compiler warnings about unused parameters. */
+ tree = 0;
+
+ assert(value >= 0);
+
+ node = leaf;
+ while (node && node->value_ > value) {
+ node->value_ = value;
+ node = node->parent_;
+ }
+}
+
+/* Get a particular leaf node. */
+
+jpc_tagtreenode_t *jpc_tagtree_getleaf(jpc_tagtree_t *tree, int n)
+{
+ return &tree->nodes_[n];
+}
+
+/* Invoke the tag tree encoding procedure. */
+
+int jpc_tagtree_encode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf,
+ int threshold, jpc_bitstream_t *out)
+{
+ jpc_tagtreenode_t *stk[JPC_TAGTREE_MAXDEPTH - 1];
+ jpc_tagtreenode_t **stkptr;
+ jpc_tagtreenode_t *node;
+ int low;
+
+ /* Avoid compiler warnings about unused parameters. */
+ tree = 0;
+
+ assert(leaf);
+ assert(threshold >= 0);
+
+ /* Traverse to the root of the tree, recording the path taken. */
+ stkptr = stk;
+ node = leaf;
+ while (node->parent_) {
+ *stkptr++ = node;
+ node = node->parent_;
+ }
+
+ low = 0;
+ for (;;) {
+ if (low > node->low_) {
+ /* Deferred propagation of the lower bound downward in
+ the tree. */
+ node->low_ = low;
+ } else {
+ low = node->low_;
+ }
+
+ while (low < threshold) {
+ if (low >= node->value_) {
+ if (!node->known_) {
+ if (jpc_bitstream_putbit(out, 1) == EOF) {
+ return -1;
+ }
+ node->known_ = 1;
+ }
+ break;
+ }
+ if (jpc_bitstream_putbit(out, 0) == EOF) {
+ return -1;
+ }
+ ++low;
+ }
+ node->low_ = low;
+ if (stkptr == stk) {
+ break;
+ }
+ node = *--stkptr;
+
+ }
+ return (leaf->low_ < threshold) ? 1 : 0;
+
+}
+
+/* Invoke the tag tree decoding procedure. */
+
+int jpc_tagtree_decode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf,
+ int threshold, jpc_bitstream_t *in)
+{
+ jpc_tagtreenode_t *stk[JPC_TAGTREE_MAXDEPTH - 1];
+ jpc_tagtreenode_t **stkptr;
+ jpc_tagtreenode_t *node;
+ int low;
+ int ret;
+
+ /* Avoid compiler warnings about unused parameters. */
+ tree = 0;
+
+ assert(threshold >= 0);
+
+ /* Traverse to the root of the tree, recording the path taken. */
+ stkptr = stk;
+ node = leaf;
+ while (node->parent_) {
+ *stkptr++ = node;
+ node = node->parent_;
+ }
+
+ low = 0;
+ for (;;) {
+ if (low > node->low_) {
+ node->low_ = low;
+ } else {
+ low = node->low_;
+ }
+ while (low < threshold && low < node->value_) {
+ if ((ret = jpc_bitstream_getbit(in)) < 0) {
+ return -1;
+ }
+ if (ret) {
+ node->value_ = low;
+ } else {
+ ++low;
+ }
+ }
+ node->low_ = low;
+ if (stkptr == stk) {
+ break;
+ }
+ node = *--stkptr;
+ }
+
+ return (node->value_ < threshold) ? 1 : 0;
+}
+
+/******************************************************************************\
+* Code for debugging.
+\******************************************************************************/
+
+void jpc_tagtree_dump(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;
+ }
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tagtree.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tagtree.h
new file mode 100644
index 0000000..52a75e2
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tagtree.h
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tag Tree Library
+ *
+ * $Id$
+ */
+
+#ifndef JPC_TAGTREE_H
+#define JPC_TAGTREE_H
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+#include <limits.h>
+#include <stdio.h>
+
+#include "jpc_bs.h"
+
+/******************************************************************************\
+* Constants
+\******************************************************************************/
+
+/* The maximum allowable depth for a tag tree. */
+#define JPC_TAGTREE_MAXDEPTH 32
+
+/******************************************************************************\
+* Types
+\******************************************************************************/
+
+/*
+ * Tag tree node.
+ */
+
+typedef struct jpc_tagtreenode_ {
+
+ /* The parent of this node. */
+ struct jpc_tagtreenode_ *parent_;
+
+ /* The value associated with this node. */
+ int value_;
+
+ /* The lower bound on the value associated with this node. */
+ int low_;
+
+ /* A flag indicating if the value is known exactly. */
+ int known_;
+
+} jpc_tagtreenode_t;
+
+/*
+ * Tag tree.
+ */
+
+typedef struct {
+
+ /* The number of leaves in the horizontal direction. */
+ int numleafsh_;
+
+ /* The number of leaves in the vertical direction. */
+ int numleafsv_;
+
+ /* The total number of nodes in the tree. */
+ int numnodes_;
+
+ /* The nodes. */
+ jpc_tagtreenode_t *nodes_;
+
+} jpc_tagtree_t;
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Create a tag tree. */
+jpc_tagtree_t *jpc_tagtree_create(int numleafsh, int numleafsv);
+
+/* Destroy a tag tree. */
+void jpc_tagtree_destroy(jpc_tagtree_t *tree);
+
+/* Copy data from one tag tree to another. */
+void jpc_tagtree_copy(jpc_tagtree_t *dsttree, jpc_tagtree_t *srctree);
+
+/* Reset the tag tree state. */
+void jpc_tagtree_reset(jpc_tagtree_t *tree);
+
+/* Set the value associated with a particular leaf node of a tag tree. */
+void jpc_tagtree_setvalue(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf,
+ int value);
+
+/* Get a pointer to a particular leaf node. */
+jpc_tagtreenode_t *jpc_tagtree_getleaf(jpc_tagtree_t *tree, int n);
+
+/* Invoke the tag tree decoding procedure. */
+int jpc_tagtree_decode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf,
+ int threshold, jpc_bitstream_t *in);
+
+/* Invoke the tag tree encoding procedure. */
+int jpc_tagtree_encode(jpc_tagtree_t *tree, jpc_tagtreenode_t *leaf,
+ int threshold, jpc_bitstream_t *out);
+
+/* Dump a tag tree (for debugging purposes). */
+void jpc_tagtree_dump(jpc_tagtree_t *tree, FILE *out);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tsfb.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tsfb.c
new file mode 100644
index 0000000..81ff752
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tsfb.c
@@ -0,0 +1,288 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2004 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tree-Structured Filter Bank (TSFB) Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_seq.h"
+
+#include "jpc_tsfb.h"
+#include "jpc_cod.h"
+#include "jpc_cs.h"
+#include "jpc_util.h"
+#include "jpc_math.h"
+
+void jpc_tsfb_getbands2(jpc_tsfb_t *tsfb, int locxstart, int locystart,
+ int xstart, int ystart, int xend, int yend, jpc_tsfb_band_t **bands,
+ int numlvls);
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+jpc_tsfb_t *jpc_cod_gettsfb(int qmfbid, int numlvls)
+{
+ jpc_tsfb_t *tsfb;
+
+ if (!(tsfb = malloc(sizeof(jpc_tsfb_t))))
+ return 0;
+
+ if (numlvls > 0) {
+ switch (qmfbid) {
+ case JPC_COX_INS:
+ tsfb->qmfb = &jpc_ns_qmfb2d;
+ break;
+ default:
+ case JPC_COX_RFT:
+ tsfb->qmfb = &jpc_ft_qmfb2d;
+ break;
+ }
+ } else {
+ tsfb->qmfb = 0;
+ }
+ tsfb->numlvls = numlvls;
+ return tsfb;
+}
+
+void jpc_tsfb_destroy(jpc_tsfb_t *tsfb)
+{
+ free(tsfb);
+}
+
+int jpc_tsfb_analyze2(jpc_tsfb_t *tsfb, int *a, int xstart, int ystart,
+ int width, int height, int stride, int numlvls)
+{
+ if (width > 0 && height > 0) {
+ if ((*tsfb->qmfb->analyze)(a, xstart, ystart, width, height, stride))
+ return -1;
+ if (numlvls > 0) {
+ if (jpc_tsfb_analyze2(tsfb, a, JPC_CEILDIVPOW2(xstart,
+ 1), JPC_CEILDIVPOW2(ystart, 1), JPC_CEILDIVPOW2(
+ xstart + width, 1) - JPC_CEILDIVPOW2(xstart, 1),
+ JPC_CEILDIVPOW2(ystart + height, 1) -
+ JPC_CEILDIVPOW2(ystart, 1), stride, numlvls - 1)) {
+ return -1;
+ }
+ }
+ }
+ return 0;
+}
+
+int jpc_tsfb_analyze(jpc_tsfb_t *tsfb, jas_seq2d_t *a)
+{
+ return (tsfb->numlvls > 0) ? jpc_tsfb_analyze2(tsfb, jas_seq2d_getref(a,
+ jas_seq2d_xstart(a), jas_seq2d_ystart(a)), jas_seq2d_xstart(a),
+ jas_seq2d_ystart(a), jas_seq2d_width(a),
+ jas_seq2d_height(a), jas_seq2d_rowstep(a), tsfb->numlvls - 1) : 0;
+}
+
+int jpc_tsfb_synthesize2(jpc_tsfb_t *tsfb, int *a, int xstart, int ystart,
+ int width, int height, int stride, int numlvls)
+{
+ if (numlvls > 0) {
+ if (jpc_tsfb_synthesize2(tsfb, a, JPC_CEILDIVPOW2(xstart, 1),
+ JPC_CEILDIVPOW2(ystart, 1), JPC_CEILDIVPOW2(xstart + width,
+ 1) - JPC_CEILDIVPOW2(xstart, 1), JPC_CEILDIVPOW2(ystart +
+ height, 1) - JPC_CEILDIVPOW2(ystart, 1), stride, numlvls -
+ 1)) {
+ return -1;
+ }
+ }
+ if (width > 0 && height > 0) {
+ if ((*tsfb->qmfb->synthesize)(a, xstart, ystart, width, height, stride)) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+int jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *a)
+{
+ return (tsfb->numlvls > 0) ? jpc_tsfb_synthesize2(tsfb,
+ jas_seq2d_getref(a, jas_seq2d_xstart(a), jas_seq2d_ystart(a)),
+ jas_seq2d_xstart(a), jas_seq2d_ystart(a), jas_seq2d_width(a),
+ jas_seq2d_height(a), jas_seq2d_rowstep(a), tsfb->numlvls - 1) : 0;
+}
+
+int jpc_tsfb_getbands(jpc_tsfb_t *tsfb, uint_fast32_t xstart,
+ uint_fast32_t ystart, uint_fast32_t xend, uint_fast32_t yend,
+ jpc_tsfb_band_t *bands)
+{
+ jpc_tsfb_band_t *band;
+
+ band = bands;
+ if (tsfb->numlvls > 0) {
+ jpc_tsfb_getbands2(tsfb, xstart, ystart, xstart, ystart, xend, yend,
+ &band, tsfb->numlvls);
+ } else {
+
+ band->xstart = xstart;
+ band->ystart = ystart;
+ band->xend = xend;
+ band->yend = yend;
+ band->locxstart = xstart;
+ band->locystart = ystart;
+ band->locxend = band->locxstart + band->xend - band->xstart;
+ band->locyend = band->locystart + band->yend - band->ystart;
+ band->orient = JPC_TSFB_LL;
+ band->synenergywt = JPC_FIX_ONE;
+ ++band;
+ }
+ return band - bands;
+}
+
+void jpc_tsfb_getbands2(jpc_tsfb_t *tsfb, int locxstart, int locystart,
+ int xstart, int ystart, int xend, int yend, jpc_tsfb_band_t **bands,
+ int numlvls)
+{
+ int newxstart;
+ int newystart;
+ int newxend;
+ int newyend;
+ jpc_tsfb_band_t *band;
+
+ newxstart = JPC_CEILDIVPOW2(xstart, 1);
+ newystart = JPC_CEILDIVPOW2(ystart, 1);
+ newxend = JPC_CEILDIVPOW2(xend, 1);
+ newyend = JPC_CEILDIVPOW2(yend, 1);
+
+ if (numlvls > 0) {
+
+ jpc_tsfb_getbands2(tsfb, locxstart, locystart, newxstart, newystart,
+ newxend, newyend, bands, numlvls - 1);
+
+ band = *bands;
+ band->xstart = JPC_FLOORDIVPOW2(xstart, 1);
+ band->ystart = newystart;
+ band->xend = JPC_FLOORDIVPOW2(xend, 1);
+ band->yend = newyend;
+ band->locxstart = locxstart + newxend - newxstart;
+ band->locystart = locystart;
+ band->locxend = band->locxstart + band->xend - band->xstart;
+ band->locyend = band->locystart + band->yend - band->ystart;
+ band->orient = JPC_TSFB_HL;
+ band->synenergywt = jpc_dbltofix(tsfb->qmfb->hpenergywts[
+ tsfb->numlvls - numlvls] * tsfb->qmfb->lpenergywts[
+ tsfb->numlvls - numlvls]);
+ ++(*bands);
+
+ band = *bands;
+ band->xstart = newxstart;
+ band->ystart = JPC_FLOORDIVPOW2(ystart, 1);
+ band->xend = newxend;
+ band->yend = JPC_FLOORDIVPOW2(yend, 1);
+ band->locxstart = locxstart;
+ band->locystart = locystart + newyend - newystart;
+ band->locxend = band->locxstart + band->xend - band->xstart;
+ band->locyend = band->locystart + band->yend - band->ystart;
+ band->orient = JPC_TSFB_LH;
+ band->synenergywt = jpc_dbltofix(tsfb->qmfb->lpenergywts[
+ tsfb->numlvls - numlvls] * tsfb->qmfb->hpenergywts[
+ tsfb->numlvls - numlvls]);
+ ++(*bands);
+
+ band = *bands;
+ band->xstart = JPC_FLOORDIVPOW2(xstart, 1);
+ band->ystart = JPC_FLOORDIVPOW2(ystart, 1);
+ band->xend = JPC_FLOORDIVPOW2(xend, 1);
+ band->yend = JPC_FLOORDIVPOW2(yend, 1);
+ band->locxstart = locxstart + newxend - newxstart;
+ band->locystart = locystart + newyend - newystart;
+ band->locxend = band->locxstart + band->xend - band->xstart;
+ band->locyend = band->locystart + band->yend - band->ystart;
+ band->orient = JPC_TSFB_HH;
+ band->synenergywt = jpc_dbltofix(tsfb->qmfb->hpenergywts[
+ tsfb->numlvls - numlvls] * tsfb->qmfb->hpenergywts[
+ tsfb->numlvls - numlvls]);
+ ++(*bands);
+
+ } else {
+
+ band = *bands;
+ band->xstart = xstart;
+ band->ystart = ystart;
+ band->xend = xend;
+ band->yend = yend;
+ band->locxstart = locxstart;
+ band->locystart = locystart;
+ band->locxend = band->locxstart + band->xend - band->xstart;
+ band->locyend = band->locystart + band->yend - band->ystart;
+ band->orient = JPC_TSFB_LL;
+ band->synenergywt = jpc_dbltofix(tsfb->qmfb->lpenergywts[
+ tsfb->numlvls - numlvls - 1] * tsfb->qmfb->lpenergywts[
+ tsfb->numlvls - numlvls - 1]);
+ ++(*bands);
+
+ }
+
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tsfb.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tsfb.h
new file mode 100644
index 0000000..1bf9736
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_tsfb.h
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2004 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Tree-Structured Filter Bank (TSFB) Library
+ *
+ * $Id$
+ */
+
+#ifndef JPC_TSFB_H
+#define JPC_TSFB_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_seq.h"
+
+#include "jpc_fix.h"
+#include "jpc_qmfb.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+#define JPC_TSFB_MAXBANDS (JPC_TSFB_MAXDEPTH * 3 + 1)
+#define JPC_TSFB_MAXDEPTH 32
+#define JPC_TSFB_RITIMODE JPC_QMFB1D_RITIMODE
+
+#define JPC_TSFB_LL 0
+#define JPC_TSFB_LH 1
+#define JPC_TSFB_HL 2
+#define JPC_TSFB_HH 3
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+typedef struct {
+ 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;
+
+typedef struct {
+ int numlvls;
+ jpc_qmfb2d_t *qmfb;
+} jpc_tsfb_t;
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+/* Create a TSFB. */
+jpc_tsfb_t *jpc_cod_gettsfb(int qmfbid, int numlevels);
+
+/* Destroy a TSFB. */
+void jpc_tsfb_destroy(jpc_tsfb_t *tsfb);
+
+/* Perform analysis. */
+int jpc_tsfb_analyze(jpc_tsfb_t *tsfb, jas_seq2d_t *x);
+
+/* Perform synthesis. */
+int jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *x);
+
+/* Get band information for a TSFB. */
+int jpc_tsfb_getbands(jpc_tsfb_t *tsfb, uint_fast32_t xstart,
+ uint_fast32_t ystart, uint_fast32_t xend, uint_fast32_t yend,
+ jpc_tsfb_band_t *bands);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_util.c b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_util.c
new file mode 100644
index 0000000..f53e248
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_util.c
@@ -0,0 +1,194 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes
+\******************************************************************************/
+
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+#include "jasper/jas_math.h"
+#include "jasper/jas_malloc.h"
+
+#include "jpc_fix.h"
+#include "jpc_cs.h"
+#include "jpc_flt.h"
+#include "jpc_util.h"
+
+/******************************************************************************\
+* Miscellaneous Functions
+\******************************************************************************/
+
+int jpc_atoaf(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') {
+ ++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') {
+ vs[n] = atof(cp);
+ ++n;
+ }
+ }
+ }
+ } else {
+ vs = 0;
+ }
+
+ *numvalues = n;
+ *values = vs;
+
+ return 0;
+}
+
+jas_seq_t *jpc_seq_upsample(jas_seq_t *x, int m)
+{
+ jas_seq_t *z;
+ int i;
+
+ if (!(z = jas_seq_create(jas_seq_start(x) * m, (jas_seq_end(x) - 1) * m + 1)))
+ return 0;
+ for (i = jas_seq_start(z); i < jas_seq_end(z); i++) {
+ *jas_seq_getref(z, i) = (!JAS_MOD(i, m)) ? jas_seq_get(x, i / m) :
+ jpc_inttofix(0);
+ }
+
+ return z;
+}
+
+jpc_fix_t jpc_seq_norm(jas_seq_t *x)
+{
+ jpc_fix_t s;
+ int i;
+
+ s = jpc_inttofix(0);
+ for (i = jas_seq_start(x); i < jas_seq_end(x); i++) {
+ s = jpc_fix_add(s, jpc_fix_mul(jas_seq_get(x, i), jas_seq_get(x, i)));
+ }
+
+ return jpc_dbltofix(sqrt(jpc_fixtodbl(s)));
+}
+
+jas_seq_t *jpc_seq_conv(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;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_util.h b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_util.h
new file mode 100644
index 0000000..526312a
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpc/jpc_util.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef JPC_UTIL_H
+#define JPC_UTIL_H
+
+/* Parse a comma separated list of real numbers into an array of doubles. */
+int jpc_atoaf(char *s, int *numvalues, double **values);
+
+/* Upsample a sequence. */
+jas_seq_t *jpc_seq_upsample(jas_seq_t *seq, int n);
+
+/* Convolve two sequences. */
+jas_seq_t *jpc_seq_conv(jas_seq_t *seq0, jas_seq_t *seq1);
+
+/* Compute the norm of a sequence. */
+jpc_fix_t jpc_seq_norm(jas_seq_t *x);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpg/Makefile.am b/jasper-1.900.1-6ct/src/libjasper/jpg/Makefile.am
new file mode 100644
index 0000000..b6dd646
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpg/Makefile.am
@@ -0,0 +1,79 @@
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+EXTRA_DIST = README
+
+if HAVE_LIBJPEG
+MISCSOURCES = jpg_dec.c jpg_enc.c
+else
+MISCSOURCES = jpg_dummy.c
+endif
+
+noinst_LTLIBRARIES = libjpg.la
+libjpg_la_SOURCES = \
+ jpg_cod.h \
+ jpg_enc.h \
+ jpg_jpeglib.h \
+ $(MISCSOURCES) \
+ jpg_val.c
+EXTRA_libjpg_la_SOURCES = \
+ jpg_dec.c \
+ jpg_enc.c \
+ jpg_dummy.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpg/Makefile.in b/jasper-1.900.1-6ct/src/libjasper/jpg/Makefile.in
new file mode 100644
index 0000000..d688eaf
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpg/Makefile.in
@@ -0,0 +1,524 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src/libjasper/jpg
+DIST_COMMON = README $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+LTLIBRARIES = $(noinst_LTLIBRARIES)
+libjpg_la_LIBADD =
+am__libjpg_la_SOURCES_DIST = jpg_cod.h jpg_enc.h jpg_jpeglib.h \
+ jpg_dummy.c jpg_dec.c jpg_enc.c jpg_val.c
+ at HAVE_LIBJPEG_FALSE@am__objects_1 = jpg_dummy.lo
+ at HAVE_LIBJPEG_TRUE@am__objects_1 = jpg_dec.lo jpg_enc.lo
+am_libjpg_la_OBJECTS = $(am__objects_1) jpg_val.lo
+libjpg_la_OBJECTS = $(am_libjpg_la_OBJECTS)
+DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/src/libjasper/include/jasper
+depcomp = $(SHELL) $(top_srcdir)/acaux/depcomp
+am__depfiles_maybe = depfiles
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LTCOMPILE = $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) \
+ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+ $(AM_CFLAGS) $(CFLAGS)
+CCLD = $(CC)
+LINK = $(LIBTOOL) --tag=CC --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+ $(AM_LDFLAGS) $(LDFLAGS) -o $@
+SOURCES = $(libjpg_la_SOURCES) $(EXTRA_libjpg_la_SOURCES)
+DIST_SOURCES = $(am__libjpg_la_SOURCES_DIST) \
+ $(EXTRA_libjpg_la_SOURCES)
+ETAGS = etags
+CTAGS = ctags
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+EXTRA_DIST = README
+ at HAVE_LIBJPEG_FALSE@MISCSOURCES = jpg_dummy.c
+ at HAVE_LIBJPEG_TRUE@MISCSOURCES = jpg_dec.c jpg_enc.c
+noinst_LTLIBRARIES = libjpg.la
+libjpg_la_SOURCES = \
+ jpg_cod.h \
+ jpg_enc.h \
+ jpg_jpeglib.h \
+ $(MISCSOURCES) \
+ jpg_val.c
+
+EXTRA_libjpg_la_SOURCES = \
+ jpg_dec.c \
+ jpg_enc.c \
+ jpg_dummy.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
+all: all-am
+
+.SUFFIXES:
+.SUFFIXES: .c .lo .o .obj
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libjasper/jpg/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/libjasper/jpg/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+clean-noinstLTLIBRARIES:
+ -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
+ @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \
+ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
+ test "$$dir" != "$$p" || dir=.; \
+ echo "rm -f \"$${dir}/so_locations\""; \
+ rm -f "$${dir}/so_locations"; \
+ done
+libjpg.la: $(libjpg_la_OBJECTS) $(libjpg_la_DEPENDENCIES)
+ $(LINK) $(libjpg_la_LDFLAGS) $(libjpg_la_OBJECTS) $(libjpg_la_LIBADD) $(LIBS)
+
+mostlyclean-compile:
+ -rm -f *.$(OBJEXT)
+
+distclean-compile:
+ -rm -f *.tab.c
+
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpg_dec.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpg_dummy.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpg_enc.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/jpg_val.Plo at am__quote@
+
+.c.o:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c $<
+
+.c.obj:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
+
+.c.lo:
+ at am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $<
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-am
+all-am: Makefile $(LTLIBRARIES)
+installdirs:
+install: install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-am
+
+clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \
+ mostlyclean-am
+
+distclean: distclean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+distclean-am: clean-am distclean-compile distclean-generic \
+ distclean-libtool distclean-tags
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+info: info-am
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-am
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-compile mostlyclean-generic \
+ mostlyclean-libtool
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
+ clean-libtool clean-noinstLTLIBRARIES ctags distclean \
+ distclean-compile distclean-generic distclean-libtool \
+ distclean-tags distdir dvi dvi-am html html-am info info-am \
+ install install-am install-data install-data-am install-exec \
+ install-exec-am install-info install-info-am install-man \
+ install-strip installcheck installcheck-am installdirs \
+ maintainer-clean maintainer-clean-generic mostlyclean \
+ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
+ pdf pdf-am ps ps-am tags uninstall uninstall-am \
+ uninstall-info-am
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpg/README b/jasper-1.900.1-6ct/src/libjasper/jpg/README
new file mode 100644
index 0000000..00ff0ff
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpg/README
@@ -0,0 +1,6 @@
+This directory contains code to support the JPEG image format. In order
+for the code in this directory to be useful, the free JPEG library from
+the Independent JPEG Group (IJG) is needed. For legal reasons, the
+IJG JPEG software is not included in the JasPer software distribution.
+The IJG JPEG software can be obtained, however, from:
+ http://www.ijg.org
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_cod.h b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_cod.h
new file mode 100644
index 0000000..a25eccc
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_cod.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * JPG Format Library
+ *
+ * $Id$
+ */
+
+#ifndef JPG_COD_H
+#define JPG_COD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+#define JPG_MAGIC 0xffd8
+#define JPG_MAGICLEN 2
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_dec.c b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_dec.c
new file mode 100644
index 0000000..202f4b1
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_dec.c
@@ -0,0 +1,354 @@
+/*
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "jasper/jas_tvp.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_string.h"
+
+#include "jpg_jpeglib.h"
+#include "jpg_cod.h"
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* JPEG decoder data sink type. */
+
+typedef struct jpg_dest_s {
+
+ /* Initialize output. */
+ void (*start_output)(j_decompress_ptr cinfo, struct jpg_dest_s *dinfo);
+
+ /* Output rows of decompressed data. */
+ void (*put_pixel_rows)(j_decompress_ptr cinfo, struct jpg_dest_s *dinfo,
+ JDIMENSION rows_supplied);
+
+ /* Cleanup output. */
+ void (*finish_output)(j_decompress_ptr cinfo, struct jpg_dest_s *dinfo);
+
+ /* Output buffer. */
+ JSAMPARRAY buffer;
+
+ /* Height of output buffer. */
+ JDIMENSION buffer_height;
+
+ /* The current row. */
+ JDIMENSION row;
+
+ /* The image used to hold the decompressed sample data. */
+ jas_image_t *image;
+
+ /* The row buffer. */
+ jas_matrix_t *data;
+
+ /* The error indicator. If this is nonzero, something has gone wrong
+ during decompression. */
+ int error;
+
+} jpg_dest_t;
+
+/******************************************************************************\
+* Local functions.
+\******************************************************************************/
+
+static void jpg_start_output(j_decompress_ptr cinfo, jpg_dest_t *dinfo);
+static void jpg_put_pixel_rows(j_decompress_ptr cinfo, jpg_dest_t *dinfo,
+ JDIMENSION rows_supplied);
+static void jpg_finish_output(j_decompress_ptr cinfo, jpg_dest_t *dinfo);
+static int jpg_copystreamtofile(FILE *out, jas_stream_t *in);
+static jas_image_t *jpg_mkimage(j_decompress_ptr cinfo);
+
+/******************************************************************************\
+* Code for load operation.
+\******************************************************************************/
+
+/* Load an image from a stream in the JPG format. */
+
+jas_image_t *jpg_decode(jas_stream_t *in, char *optstr)
+{
+ struct jpeg_decompress_struct cinfo;
+ struct jpeg_error_mgr jerr;
+ FILE *input_file;
+ jpg_dest_t dest_mgr_buf;
+ jpg_dest_t *dest_mgr = &dest_mgr_buf;
+ int num_scanlines, byte_width;
+ jas_image_t *image;
+
+ /* Avoid compiler warnings about unused parameters. */
+ optstr = 0;
+
+ image = 0;
+ input_file = 0;
+ if (!(input_file = tmpfile())) {
+ goto error;
+ }
+ if (jpg_copystreamtofile(input_file, in)) {
+ goto error;
+ }
+ rewind(input_file);
+
+ /* Allocate and initialize a JPEG decompression object. */
+ cinfo.err = jpeg_std_error(&jerr);
+ jpeg_create_decompress(&cinfo);
+
+ /* Specify the data source for decompression. */
+ jpeg_stdio_src(&cinfo, input_file);
+
+ /* Read the file header to obtain the image information. */
+ jpeg_read_header(&cinfo, TRUE);
+
+ /* Start the decompressor. */
+ jpeg_start_decompress(&cinfo);
+
+ /* Create an image object to hold the decoded data. */
+ if (!(image = jpg_mkimage(&cinfo))) {
+ goto error;
+ }
+
+ /* Initialize the data sink object. */
+ dest_mgr->image = image;
+ dest_mgr->data = jas_matrix_create(1, cinfo.output_width);
+ dest_mgr->start_output = jpg_start_output;
+ dest_mgr->put_pixel_rows = jpg_put_pixel_rows;
+ dest_mgr->finish_output = jpg_finish_output;
+ if (cinfo.data_precision > 8) byte_width = 2;/* 12 or 16 */
+ else byte_width = 1;/* 8 */
+ dest_mgr->buffer = (*cinfo.mem->alloc_sarray)
+ ((j_common_ptr) &cinfo, JPOOL_IMAGE,
+ cinfo.output_width * cinfo.output_components * byte_width, (JDIMENSION) 1);
+ dest_mgr->buffer_height = 1;
+ dest_mgr->error = 0;
+
+ /* Process the compressed data. */
+ (*dest_mgr->start_output)(&cinfo, dest_mgr);
+ while (cinfo.output_scanline < cinfo.output_height) {
+ num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
+ dest_mgr->buffer_height);
+ (*dest_mgr->put_pixel_rows)(&cinfo, dest_mgr, num_scanlines);
+ }
+ (*dest_mgr->finish_output)(&cinfo, dest_mgr);
+
+ /* Complete the decompression process. */
+ jpeg_finish_decompress(&cinfo);
+
+ /* Destroy the JPEG decompression object. */
+ jpeg_destroy_decompress(&cinfo);
+
+ jas_matrix_destroy(dest_mgr->data);
+
+ fclose(input_file);
+
+ if (dest_mgr->error) {
+ goto error;
+ }
+
+ return image;
+
+error:
+ if (image) {
+ jas_image_destroy(image);
+ }
+ if (input_file) {
+ fclose(input_file);
+ }
+ return 0;
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static jas_image_t *jpg_mkimage(j_decompress_ptr cinfo)
+{
+ jas_image_t *image;
+ int cmptno;
+ jas_image_cmptparm_t cmptparm;
+ int numcmpts;
+
+ image = 0;
+ numcmpts = cinfo->output_components;
+ if (!(image = jas_image_create0())) {
+ goto error;
+ }
+ for (cmptno = 0; cmptno < numcmpts; ++cmptno) {
+ cmptparm.tlx = 0;
+ cmptparm.tly = 0;
+ cmptparm.hstep = 1;
+ cmptparm.vstep = 1;
+ cmptparm.width = cinfo->image_width;
+ cmptparm.height = cinfo->image_height;
+ cmptparm.prec = cinfo->data_precision;
+ cmptparm.sgnd = false;
+ if (jas_image_addcmpt(image, cmptno, &cmptparm)) {
+ goto error;
+ }
+ }
+
+ if (numcmpts == 3) {
+ jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
+ jas_image_setcmpttype(image, 0,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
+ jas_image_setcmpttype(image, 1,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
+ jas_image_setcmpttype(image, 2,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
+ } else {
+ jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
+ jas_image_setcmpttype(image, 0,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
+ }
+
+ return image;
+
+error:
+ if (image) {
+ jas_image_destroy(image);
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Data source code.
+\******************************************************************************/
+
+static int jpg_copystreamtofile(FILE *out, jas_stream_t *in)
+{
+ int c;
+
+ while ((c = jas_stream_getc(in)) != EOF) {
+ if (fputc(c, out) == EOF) {
+ return -1;
+ }
+ }
+ if (jas_stream_error(in)) {
+ return -1;
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Data sink code.
+\******************************************************************************/
+
+static void jpg_start_output(j_decompress_ptr cinfo, jpg_dest_t *dinfo)
+{
+ /* Avoid compiler warnings about unused parameters. */
+ cinfo = 0;
+
+ dinfo->row = 0;
+}
+
+static void jpg_put_pixel_rows(j_decompress_ptr cinfo, jpg_dest_t *dinfo,
+ JDIMENSION rows_supplied)
+{
+ JSAMPLE *bufptr;
+ JSAMPLE16 *bufptr16;
+ int cmptno;
+ JDIMENSION x;
+ uint_fast32_t width;
+ bool wide = FALSE;
+
+ if (dinfo->error) {
+ return;
+ }
+
+ if (cinfo->data_precision > 8) wide = TRUE;
+
+ assert(cinfo->output_components == jas_image_numcmpts(dinfo->image));
+
+ for (cmptno = 0; cmptno < cinfo->output_components; ++cmptno) {
+ width = jas_image_cmptwidth(dinfo->image, cmptno);
+ if (wide) {
+ bufptr16 = (JSAMPROW16)(dinfo->buffer[0]) + cmptno;
+ for (x = 0; x < width; ++x) {
+ jas_matrix_set(dinfo->data, 0, x, GETJSAMPLE(*bufptr16));
+ bufptr16 += cinfo->output_components;
+ }
+ } else {
+ bufptr = (dinfo->buffer[0]) + cmptno;
+ for (x = 0; x < width; ++x) {
+ jas_matrix_set(dinfo->data, 0, x, GETJSAMPLE(*bufptr));
+ bufptr += cinfo->output_components;
+ }
+ }
+ if (jas_image_writecmpt(dinfo->image, cmptno, 0, dinfo->row, width, 1,
+ dinfo->data)) {
+ dinfo->error = 1;
+ }
+ }
+ dinfo->row += rows_supplied;
+}
+
+static void jpg_finish_output(j_decompress_ptr cinfo, jpg_dest_t *dinfo)
+{
+ /* Avoid compiler warnings about unused parameters. */
+ cinfo = 0;
+ dinfo = 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_dummy.c b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_dummy.c
new file mode 100644
index 0000000..bc8b7c5
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_dummy.c
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+
+#include "jasper/jas_tvp.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_string.h"
+#include "jasper/jas_debug.h"
+
+#include "jpg_cod.h"
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+#define JPG_IJGINFO \
+ "The source code for the IJG JPEG library can be downloaded from:\n" \
+ " http://www.ijg.org\n"
+
+/******************************************************************************\
+* Code for load operation.
+\******************************************************************************/
+
+/* Load an image from a stream in the JPG format. */
+
+jas_image_t *jpg_decode(jas_stream_t *in, char *optstr)
+{
+ jas_eprintf("error: JPEG decoder not available\n");
+ jas_eprintf("The IJG JPEG library is required for JPEG decoding support.\n");
+ jas_eprintf("%s", JPG_IJGINFO);
+ return 0;
+}
+
+/******************************************************************************\
+* Code for save operation.
+\******************************************************************************/
+
+/* Save an image to a stream in the the JPG format. */
+
+int jpg_encode(jas_image_t *image, jas_stream_t *out, char *optstr)
+{
+ jas_eprintf("error: JPEG encoder not available\n");
+ jas_eprintf("The IJG JPEG library is required for JPEG encoding support.\n");
+ jas_eprintf("%s", JPG_IJGINFO);
+ return -1;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_enc.c b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_enc.c
new file mode 100644
index 0000000..b5f82de
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_enc.c
@@ -0,0 +1,435 @@
+/*
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+#include "jasper/jas_types.h"
+
+#include "jasper/jas_tvp.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_string.h"
+#include "jasper/jas_debug.h"
+
+#include "jpg_jpeglib.h"
+#include "jpg_cod.h"
+#include "jpg_enc.h"
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+typedef struct jpg_src_s {
+
+ /* Output buffer. */
+ JSAMPARRAY buffer;
+
+ /* Height of output buffer. */
+ JDIMENSION buffer_height;
+
+ /* The current row. */
+ JDIMENSION row;
+
+ /* The image used to hold the decompressed sample data. */
+ jas_image_t *image;
+
+ /* The row buffer. */
+ jas_matrix_t *data;
+
+ /* The error indicator. If this is nonzero, something has gone wrong
+ during decompression. */
+ int error;
+
+ jpg_enc_t *enc;
+
+} jpg_src_t;
+
+typedef struct {
+ int qual;
+ bool lossless;
+} jpg_encopts_t;
+
+typedef enum {
+ OPT_QUAL,
+ LOSSLESS
+} jpg_optid_t;
+
+jas_taginfo_t jpg_opttab[] = {
+ {OPT_QUAL, "quality"},
+ {LOSSLESS, "lossless"},
+ {-1, 0}
+};
+
+/******************************************************************************\
+* Local prototypes.
+\******************************************************************************/
+
+static int jpg_copyfiletostream(jas_stream_t *out, FILE *in);
+static void jpg_start_input(j_compress_ptr cinfo, struct jpg_src_s *sinfo);
+static JDIMENSION jpg_get_pixel_rows(j_compress_ptr cinfo, struct jpg_src_s *sinfo);
+static void jpg_finish_input(j_compress_ptr cinfo, struct jpg_src_s *sinfo);
+static J_COLOR_SPACE tojpgcs(int colorspace);
+static int jpg_parseencopts(char *optstr, jpg_encopts_t *encopts);
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static int jpg_copyfiletostream(jas_stream_t *out, FILE *in)
+{
+ int c;
+ while ((c = fgetc(in)) != EOF) {
+ if (jas_stream_putc(out, c) == EOF) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static void jpg_start_input(j_compress_ptr cinfo, struct jpg_src_s *sinfo)
+{
+ /* Avoid compiler warnings about unused parameters. */
+ cinfo = 0;
+
+ sinfo->row = 0;
+}
+
+static JDIMENSION jpg_get_pixel_rows(j_compress_ptr cinfo, struct jpg_src_s *sinfo)
+{
+ JSAMPLE *bufptr;
+ int i;
+ int cmptno;
+ int width;
+ int *cmpts;
+
+ cmpts = sinfo->enc->cmpts;
+
+ width = jas_image_width(sinfo->image);
+
+ if (sinfo->error) {
+ return 0;
+ }
+ for (cmptno = 0; cmptno < cinfo->input_components; ++cmptno) {
+ if (jas_image_readcmpt(sinfo->image, cmpts[cmptno], 0, sinfo->row, width, 1, sinfo->data)) {
+ ;
+ }
+ bufptr = (sinfo->buffer[0]) + cmptno;
+ for (i = 0; i < width; ++i) {
+ *bufptr = jas_matrix_get(sinfo->data, 0, i);
+ bufptr += cinfo->input_components;
+ }
+ }
+ ++sinfo->row;
+ return 1;
+}
+
+static void jpg_finish_input(j_compress_ptr cinfo, struct jpg_src_s *sinfo)
+{
+ /* Avoid compiler warnings about unused parameters. */
+ cinfo = 0;
+ sinfo = 0;
+}
+
+/******************************************************************************\
+* Code for save operation.
+\******************************************************************************/
+
+/* Save an image to a stream in the the JPG format. */
+
+int jpg_encode(jas_image_t *image, jas_stream_t *out, char *optstr)
+{
+ JDIMENSION numscanlines;
+ struct jpeg_compress_struct cinfo;
+ struct jpeg_error_mgr jerr;
+ jas_image_coord_t width;
+ jas_image_coord_t height;
+ jpg_src_t src_mgr_buf;
+ jpg_src_t *src_mgr = &src_mgr_buf;
+ FILE *output_file;
+ int cmptno;
+ jpg_enc_t encbuf;
+ jpg_enc_t *enc = &encbuf;
+ jpg_encopts_t encopts;
+ uint_fast8_t prec = 8;
+ uint byte_width;
+
+ output_file = 0;
+
+ if (jpg_parseencopts(optstr, &encopts))
+ goto error;
+
+ switch (jas_clrspc_fam(jas_image_clrspc(image))) {
+ case JAS_CLRSPC_FAM_RGB:
+ if (jas_image_clrspc(image) != JAS_CLRSPC_SRGB)
+ jas_eprintf("warning: inaccurate color\n");
+ enc->numcmpts = 3;
+ if ((enc->cmpts[0] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R))) < 0 ||
+ (enc->cmpts[1] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G))) < 0 ||
+ (enc->cmpts[2] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))) < 0) {
+ jas_eprintf("error: missing color component\n");
+ goto error;
+ }
+ break;
+ case JAS_CLRSPC_FAM_YCBCR:
+ if (jas_image_clrspc(image) != JAS_CLRSPC_SYCBCR)
+ jas_eprintf("warning: inaccurate color\n");
+ enc->numcmpts = 3;
+ if ((enc->cmpts[0] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y))) < 0 ||
+ (enc->cmpts[1] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB))) < 0 ||
+ (enc->cmpts[2] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR))) < 0) {
+ jas_eprintf("error: missing color component\n");
+ goto error;
+ }
+ break;
+ case JAS_CLRSPC_FAM_GRAY:
+ if (jas_image_clrspc(image) != JAS_CLRSPC_SGRAY)
+ jas_eprintf("warning: inaccurate color\n");
+ enc->numcmpts = 1;
+ if ((enc->cmpts[0] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y))) < 0) {
+ jas_eprintf("error: missing color component\n");
+ goto error;
+ }
+ break;
+ default:
+ jas_eprintf("error: JPG format does not support color space\n");
+ goto error;
+ break;
+ }
+
+ width = jas_image_width(image);
+ height = jas_image_height(image);
+
+ for (cmptno = 0; cmptno < enc->numcmpts; ++cmptno) {
+ if (jas_image_cmptwidth(image, enc->cmpts[cmptno]) != width ||
+ jas_image_cmptheight(image, enc->cmpts[cmptno]) != height ||
+ jas_image_cmpttlx(image, enc->cmpts[cmptno]) != 0 ||
+ jas_image_cmpttly(image, enc->cmpts[cmptno]) != 0 ||
+ jas_image_cmpthstep(image, enc->cmpts[cmptno]) != 1 ||
+ jas_image_cmptvstep(image, enc->cmpts[cmptno]) != 1 ||
+/* jas_image_cmptprec(image, enc->cmpts[cmptno]) != 8 ||*/
+ jas_image_cmptsgnd(image, enc->cmpts[cmptno]) != false) {
+ jas_eprintf("error: The JPG encoder cannot handle an image with this geometry.\n");
+ goto error;
+ }
+ prec = jas_image_cmptprec(image, enc->cmpts[cmptno]);
+ if ( prec != 8 && prec != 12 && prec != 16) {
+ jas_eprintf("error: The JPG encoder cannot handle an image with a %d bit width.\n", prec);
+ goto error;
+ }
+ }
+
+ if (!(output_file = tmpfile())) {
+ goto error;
+ }
+
+ /* Create a JPEG compression object. */
+ cinfo.err = jpeg_std_error(&jerr);
+ jpeg_create_compress(&cinfo);
+
+ /* Specify data destination for compression */
+ jpeg_stdio_dest(&cinfo, output_file);
+
+ cinfo.in_color_space = tojpgcs(jas_image_clrspc(image));
+ cinfo.image_width = width;
+ cinfo.image_height = height;
+ cinfo.input_components = enc->numcmpts;
+ cinfo.data_precision = prec;
+ cinfo.data_precision_other = prec;
+ if (prec > 8) byte_width = 2; /* 12 or 16 */
+ else byte_width = 1; /* 8 */
+ cinfo.lossless = encopts.lossless;
+ if (prec == 16) cinfo.lossless = TRUE;/* 16 bits for lossless only*/
+ jpeg_set_defaults(&cinfo);
+
+ src_mgr->error = 0;
+ src_mgr->image = image;
+ src_mgr->data = jas_matrix_create(1, width);
+ assert(src_mgr->data);
+ src_mgr->buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr) &cinfo,
+ JPOOL_IMAGE, (JDIMENSION) width * cinfo.input_components * byte_width,
+ (JDIMENSION) 1);
+ src_mgr->buffer_height = 1;
+ src_mgr->enc = enc;
+
+ /* Read the input file header to obtain file size & colorspace. */
+ jpg_start_input(&cinfo, src_mgr);
+
+ if (encopts.qual >= 0) {
+ jpeg_set_quality(&cinfo, encopts.qual, TRUE);
+ }
+
+ /* Now that we know input colorspace, fix colorspace-dependent defaults */
+ jpeg_default_colorspace(&cinfo);
+
+ /* Start compressor */
+ jpeg_start_compress(&cinfo, TRUE);
+
+ /* Process data */
+ while (cinfo.next_scanline < cinfo.image_height) {
+ if ((numscanlines = jpg_get_pixel_rows(&cinfo, src_mgr)) <= 0) {
+ break;
+ }
+ jpeg_write_scanlines(&cinfo, src_mgr->buffer, numscanlines);
+ }
+
+ /* Finish compression and release memory */
+ jpg_finish_input(&cinfo, src_mgr);
+ jpeg_finish_compress(&cinfo);
+ jpeg_destroy_compress(&cinfo);
+ jas_matrix_destroy(src_mgr->data);
+
+ rewind(output_file);
+ jpg_copyfiletostream(out, output_file);
+ fclose(output_file);
+ output_file = 0;
+
+ return 0;
+
+error:
+ if (output_file) {
+ fclose(output_file);
+ }
+ return -1;
+}
+
+static J_COLOR_SPACE tojpgcs(int colorspace)
+{
+ switch (jas_clrspc_fam(colorspace)) {
+ case JAS_CLRSPC_FAM_RGB:
+ return JCS_RGB;
+ break;
+ case JAS_CLRSPC_FAM_YCBCR:
+ return JCS_YCbCr;
+ break;
+ case JAS_CLRSPC_FAM_GRAY:
+ return JCS_GRAYSCALE;
+ break;
+ default:
+ abort();
+ break;
+ }
+}
+
+/* Parse the encoder options string. */
+static int jpg_parseencopts(char *optstr, jpg_encopts_t *encopts)
+{
+ jas_tvparser_t *tvp;
+ char *qual_str;
+ int ret;
+
+ tvp = 0;
+
+ /* Initialize default values for encoder options. */
+ encopts->qual = -1;
+ encopts->lossless = FALSE;
+
+ /* Create the tag-value parser. */
+ if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
+ goto error;
+ }
+
+ /* Get tag-value pairs, and process as necessary. */
+ while (!(ret = jas_tvparser_next(tvp))) {
+ switch (jas_taginfo_nonull(jas_taginfos_lookup(jpg_opttab,
+ jas_tvparser_gettag(tvp)))->id) {
+ case OPT_QUAL:
+ qual_str = jas_tvparser_getval(tvp);
+ if (sscanf(qual_str, "%d", &encopts->qual) != 1) {
+ jas_eprintf("ignoring bad quality specifier %s\n",
+ jas_tvparser_getval(tvp));
+ encopts->qual = -1;
+ }
+ break;
+ case LOSSLESS:
+ encopts->lossless = TRUE;
+ encopts->qual = -1;
+ break;
+ default:
+ jas_eprintf("warning: ignoring invalid option %s\n",
+ jas_tvparser_gettag(tvp));
+ break;
+ }
+ }
+ if (ret < 0) {
+ goto error;
+ }
+
+ /* Destroy the tag-value parser. */
+ jas_tvparser_destroy(tvp);
+
+ return 0;
+
+error:
+ if (tvp) {
+ jas_tvparser_destroy(tvp);
+ }
+ return -1;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_enc.h b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_enc.h
new file mode 100644
index 0000000..d0d6c5f
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_enc.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef JPG_ENC_H
+#define JPG_ENC_H
+
+typedef struct {
+ int numcmpts;
+ int cmpts[4];
+} jpg_enc_t;
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_jpeglib.h b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_jpeglib.h
new file mode 100644
index 0000000..ad5818c
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_jpeglib.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef JPG_JPEGLIB_H
+#define JPG_JPEGLIB_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include "jasper/jas_types.h"
+
+/* Note: The jpeglib.h header file does not include definitions of
+ FILE, size_t, etc. */
+#include <jpeglib.h>
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_val.c b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_val.c
new file mode 100644
index 0000000..338afaf
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/jpg/jpg_val.c
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+#include <assert.h>
+
+#include "jasper/jas_stream.h"
+#include "jasper/jas_image.h"
+
+#include "jpg_cod.h"
+
+/******************************************************************************\
+* Code for validate operation.
+\******************************************************************************/
+
+int jpg_validate(jas_stream_t *in)
+{
+ uchar buf[JPG_MAGICLEN];
+ int i;
+ int n;
+
+ assert(JAS_STREAM_MAXPUTBACK >= JPG_MAGICLEN);
+
+ /* Read the validation data (i.e., the data used for detecting
+ the format). */
+ if ((n = jas_stream_read(in, buf, JPG_MAGICLEN)) < 0) {
+ return -1;
+ }
+
+ /* Put the validation data back onto the stream, so that the
+ stream position will not be changed. */
+ for (i = n - 1; i >= 0; --i) {
+ if (jas_stream_ungetc(in, buf[i]) == EOF) {
+ return -1;
+ }
+ }
+
+ /* Did we read enough data? */
+ if (n < JPG_MAGICLEN) {
+ return -1;
+ }
+
+ /* Does this look like JPEG? */
+ if (buf[0] != (JPG_MAGIC >> 8) || buf[1] != (JPG_MAGIC & 0xff)) {
+ return -1;
+ }
+
+ return 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/mif/Makefile.am b/jasper-1.900.1-6ct/src/libjasper/mif/Makefile.am
new file mode 100644
index 0000000..b01a233
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/mif/Makefile.am
@@ -0,0 +1,66 @@
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+EXTRA_DIST = README
+
+noinst_LTLIBRARIES = libmif.la
+libmif_la_SOURCES = \
+ mif_cod.h \
+ mif_cod.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
diff --git a/jasper-1.900.1-6ct/src/libjasper/mif/Makefile.in b/jasper-1.900.1-6ct/src/libjasper/mif/Makefile.in
new file mode 100644
index 0000000..94a1ff5
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/mif/Makefile.in
@@ -0,0 +1,506 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src/libjasper/mif
+DIST_COMMON = README $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+LTLIBRARIES = $(noinst_LTLIBRARIES)
+libmif_la_LIBADD =
+am_libmif_la_OBJECTS = mif_cod.lo
+libmif_la_OBJECTS = $(am_libmif_la_OBJECTS)
+DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/src/libjasper/include/jasper
+depcomp = $(SHELL) $(top_srcdir)/acaux/depcomp
+am__depfiles_maybe = depfiles
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LTCOMPILE = $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) \
+ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+ $(AM_CFLAGS) $(CFLAGS)
+CCLD = $(CC)
+LINK = $(LIBTOOL) --tag=CC --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+ $(AM_LDFLAGS) $(LDFLAGS) -o $@
+SOURCES = $(libmif_la_SOURCES)
+DIST_SOURCES = $(libmif_la_SOURCES)
+ETAGS = etags
+CTAGS = ctags
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+EXTRA_DIST = README
+noinst_LTLIBRARIES = libmif.la
+libmif_la_SOURCES = \
+ mif_cod.h \
+ mif_cod.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
+all: all-am
+
+.SUFFIXES:
+.SUFFIXES: .c .lo .o .obj
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libjasper/mif/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/libjasper/mif/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+clean-noinstLTLIBRARIES:
+ -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
+ @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \
+ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
+ test "$$dir" != "$$p" || dir=.; \
+ echo "rm -f \"$${dir}/so_locations\""; \
+ rm -f "$${dir}/so_locations"; \
+ done
+libmif.la: $(libmif_la_OBJECTS) $(libmif_la_DEPENDENCIES)
+ $(LINK) $(libmif_la_LDFLAGS) $(libmif_la_OBJECTS) $(libmif_la_LIBADD) $(LIBS)
+
+mostlyclean-compile:
+ -rm -f *.$(OBJEXT)
+
+distclean-compile:
+ -rm -f *.tab.c
+
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/mif_cod.Plo at am__quote@
+
+.c.o:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c $<
+
+.c.obj:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
+
+.c.lo:
+ at am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $<
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-am
+all-am: Makefile $(LTLIBRARIES)
+installdirs:
+install: install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-am
+
+clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \
+ mostlyclean-am
+
+distclean: distclean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+distclean-am: clean-am distclean-compile distclean-generic \
+ distclean-libtool distclean-tags
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+info: info-am
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-am
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-compile mostlyclean-generic \
+ mostlyclean-libtool
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
+ clean-libtool clean-noinstLTLIBRARIES ctags distclean \
+ distclean-compile distclean-generic distclean-libtool \
+ distclean-tags distdir dvi dvi-am html html-am info info-am \
+ install install-am install-data install-data-am install-exec \
+ install-exec-am install-info install-info-am install-man \
+ install-strip installcheck installcheck-am installdirs \
+ maintainer-clean maintainer-clean-generic mostlyclean \
+ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
+ pdf pdf-am ps ps-am tags uninstall uninstall-am \
+ uninstall-info-am
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/libjasper/mif/README b/jasper-1.900.1-6ct/src/libjasper/mif/README
new file mode 100644
index 0000000..85adb18
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/mif/README
@@ -0,0 +1 @@
+This directory contains the code for support of the MIF format.
diff --git a/jasper-1.900.1-6ct/src/libjasper/mif/mif_cod.c b/jasper-1.900.1-6ct/src/libjasper/mif/mif_cod.c
new file mode 100644
index 0000000..d482c00
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/mif/mif_cod.c
@@ -0,0 +1,752 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+
+#include "jasper/jas_tvp.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_string.h"
+#include "jasper/jas_malloc.h"
+#include "jasper/jas_debug.h"
+
+#include "mif_cod.h"
+
+/******************************************************************************\
+* Local types.
+\******************************************************************************/
+
+typedef enum {
+ MIF_END = 0,
+ MIF_CMPT
+} mif_tagid2_t;
+
+typedef enum {
+ MIF_TLX = 0,
+ MIF_TLY,
+ MIF_WIDTH,
+ MIF_HEIGHT,
+ MIF_HSAMP,
+ MIF_VSAMP,
+ MIF_PREC,
+ MIF_SGND,
+ MIF_DATA
+} mif_tagid_t;
+
+/******************************************************************************\
+* Local functions.
+\******************************************************************************/
+
+static mif_hdr_t *mif_hdr_create(int maxcmpts);
+static void mif_hdr_destroy(mif_hdr_t *hdr);
+static int mif_hdr_growcmpts(mif_hdr_t *hdr, int maxcmpts);
+static mif_hdr_t *mif_hdr_get(jas_stream_t *in);
+static int mif_process_cmpt(mif_hdr_t *hdr, char *buf);
+static int mif_hdr_put(mif_hdr_t *hdr, jas_stream_t *out);
+static int mif_hdr_addcmpt(mif_hdr_t *hdr, int cmptno, mif_cmpt_t *cmpt);
+static mif_cmpt_t *mif_cmpt_create(void);
+static void mif_cmpt_destroy(mif_cmpt_t *cmpt);
+static char *mif_getline(jas_stream_t *jas_stream, char *buf, int bufsize);
+static int mif_getc(jas_stream_t *in);
+static mif_hdr_t *mif_makehdrfromimage(jas_image_t *image);
+
+/******************************************************************************\
+* Local data.
+\******************************************************************************/
+
+jas_taginfo_t mif_tags2[] = {
+ {MIF_CMPT, "component"},
+ {MIF_END, "end"},
+ {-1, 0}
+};
+
+jas_taginfo_t mif_tags[] = {
+ {MIF_TLX, "tlx"},
+ {MIF_TLY, "tly"},
+ {MIF_WIDTH, "width"},
+ {MIF_HEIGHT, "height"},
+ {MIF_HSAMP, "sampperx"},
+ {MIF_VSAMP, "samppery"},
+ {MIF_PREC, "prec"},
+ {MIF_SGND, "sgnd"},
+ {MIF_DATA, "data"},
+ {-1, 0}
+};
+
+/******************************************************************************\
+* Code for load operation.
+\******************************************************************************/
+
+/* Load an image from a stream in the MIF format. */
+
+jas_image_t *mif_decode(jas_stream_t *in, char *optstr)
+{
+ mif_hdr_t *hdr;
+ jas_image_t *image;
+ jas_image_t *tmpimage;
+ jas_stream_t *tmpstream;
+ int cmptno;
+ mif_cmpt_t *cmpt;
+ jas_image_cmptparm_t cmptparm;
+ jas_seq2d_t *data;
+ int_fast32_t x;
+ int_fast32_t y;
+ int bias;
+
+ /* Avoid warnings about unused parameters. */
+ optstr = 0;
+
+ hdr = 0;
+ image = 0;
+ tmpimage = 0;
+ tmpstream = 0;
+ data = 0;
+
+ if (!(hdr = mif_hdr_get(in))) {
+ goto error;
+ }
+
+ if (!(image = jas_image_create0())) {
+ goto error;
+ }
+
+ for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) {
+ cmpt = hdr->cmpts[cmptno];
+ tmpstream = cmpt->data ? jas_stream_fopen(cmpt->data, "rb") : in;
+ if (!tmpstream) {
+ goto error;
+ }
+ if (!(tmpimage = jas_image_decode(tmpstream, -1, 0))) {
+ goto error;
+ }
+ if (tmpstream != in) {
+ jas_stream_close(tmpstream);
+ tmpstream = 0;
+ }
+ if (!cmpt->width) {
+ cmpt->width = jas_image_cmptwidth(tmpimage, 0);
+ }
+ if (!cmpt->height) {
+ cmpt->height = jas_image_cmptwidth(tmpimage, 0);
+ }
+ if (!cmpt->prec) {
+ cmpt->prec = jas_image_cmptprec(tmpimage, 0);
+ }
+ if (cmpt->sgnd < 0) {
+ cmpt->sgnd = jas_image_cmptsgnd(tmpimage, 0);
+ }
+ cmptparm.tlx = cmpt->tlx;
+ cmptparm.tly = cmpt->tly;
+ cmptparm.hstep = cmpt->sampperx;
+ cmptparm.vstep = cmpt->samppery;
+ cmptparm.width = cmpt->width;
+ cmptparm.height = cmpt->height;
+ cmptparm.prec = cmpt->prec;
+ cmptparm.sgnd = cmpt->sgnd;
+ if (jas_image_addcmpt(image, jas_image_numcmpts(image), &cmptparm)) {
+ goto error;
+ }
+ if (!(data = jas_seq2d_create(0, 0, cmpt->width, cmpt->height))) {
+ goto error;
+ }
+ if (jas_image_readcmpt(tmpimage, 0, 0, 0, cmpt->width, cmpt->height,
+ data)) {
+ goto error;
+ }
+ if (cmpt->sgnd) {
+ bias = 1 << (cmpt->prec - 1);
+ for (y = 0; y < cmpt->height; ++y) {
+ for (x = 0; x < cmpt->width; ++x) {
+ *jas_seq2d_getref(data, x, y) -= bias;
+ }
+ }
+ }
+ if (jas_image_writecmpt(image, jas_image_numcmpts(image) - 1, 0, 0,
+ cmpt->width, cmpt->height, data)) {
+ goto error;
+ }
+ jas_seq2d_destroy(data);
+ data = 0;
+ jas_image_destroy(tmpimage);
+ tmpimage = 0;
+ }
+
+ mif_hdr_destroy(hdr);
+ hdr = 0;
+ return image;
+
+error:
+ if (image) {
+ jas_image_destroy(image);
+ }
+ if (hdr) {
+ mif_hdr_destroy(hdr);
+ }
+ if (tmpstream && tmpstream != in) {
+ jas_stream_close(tmpstream);
+ }
+ if (tmpimage) {
+ jas_image_destroy(tmpimage);
+ }
+ if (data) {
+ jas_seq2d_destroy(data);
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Code for save operation.
+\******************************************************************************/
+
+/* Save an image to a stream in the the MIF format. */
+
+int mif_encode(jas_image_t *image, jas_stream_t *out, char *optstr)
+{
+ mif_hdr_t *hdr;
+ jas_image_t *tmpimage;
+ int fmt;
+ int cmptno;
+ mif_cmpt_t *cmpt;
+ jas_image_cmptparm_t cmptparm;
+ jas_seq2d_t *data;
+ int_fast32_t x;
+ int_fast32_t y;
+ int bias;
+
+ hdr = 0;
+ tmpimage = 0;
+ data = 0;
+
+ if (optstr && *optstr != '\0') {
+ jas_eprintf("warning: ignoring unsupported options\n");
+ }
+
+ if ((fmt = jas_image_strtofmt("pnm")) < 0) {
+ jas_eprintf("error: PNM support required\n");
+ goto error;
+ }
+
+ if (!(hdr = mif_makehdrfromimage(image))) {
+ goto error;
+ }
+ if (mif_hdr_put(hdr, out)) {
+ goto error;
+ }
+
+ /* Output component data. */
+ for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) {
+ cmpt = hdr->cmpts[cmptno];
+ if (!cmpt->data) {
+ if (!(tmpimage = jas_image_create0())) {
+ goto error;
+ }
+ cmptparm.tlx = 0;
+ cmptparm.tly = 0;
+ cmptparm.hstep = cmpt->sampperx;
+ cmptparm.vstep = cmpt->samppery;
+ cmptparm.width = cmpt->width;
+ cmptparm.height = cmpt->height;
+ cmptparm.prec = cmpt->prec;
+ cmptparm.sgnd = false;
+ if (jas_image_addcmpt(tmpimage, jas_image_numcmpts(tmpimage), &cmptparm)) {
+ goto error;
+ }
+ if (!(data = jas_seq2d_create(0, 0, cmpt->width, cmpt->height))) {
+ goto error;
+ }
+ if (jas_image_readcmpt(image, cmptno, 0, 0, cmpt->width, cmpt->height,
+ data)) {
+ goto error;
+ }
+ if (cmpt->sgnd) {
+ bias = 1 << (cmpt->prec - 1);
+ for (y = 0; y < cmpt->height; ++y) {
+ for (x = 0; x < cmpt->width; ++x) {
+ *jas_seq2d_getref(data, x, y) += bias;
+ }
+ }
+ }
+ if (jas_image_writecmpt(tmpimage, 0, 0, 0, cmpt->width, cmpt->height,
+ data)) {
+ goto error;
+ }
+ jas_seq2d_destroy(data);
+ data = 0;
+ if (jas_image_encode(tmpimage, out, fmt, 0)) {
+ goto error;
+ }
+ jas_image_destroy(tmpimage);
+ tmpimage = 0;
+ }
+ }
+
+ mif_hdr_destroy(hdr);
+
+ return 0;
+
+error:
+ if (hdr) {
+ mif_hdr_destroy(hdr);
+ }
+ if (tmpimage) {
+ jas_image_destroy(tmpimage);
+ }
+ if (data) {
+ jas_seq2d_destroy(data);
+ }
+ return -1;
+}
+
+/******************************************************************************\
+* Code for validate operation.
+\******************************************************************************/
+
+int mif_validate(jas_stream_t *in)
+{
+ uchar buf[MIF_MAGICLEN];
+ uint_fast32_t magic;
+ int i;
+ int n;
+
+ assert(JAS_STREAM_MAXPUTBACK >= MIF_MAGICLEN);
+
+ /* Read the validation data (i.e., the data used for detecting
+ the format). */
+ if ((n = jas_stream_read(in, buf, MIF_MAGICLEN)) < 0) {
+ return -1;
+ }
+
+ /* Put the validation data back onto the stream, so that the
+ stream position will not be changed. */
+ for (i = n - 1; i >= 0; --i) {
+ if (jas_stream_ungetc(in, buf[i]) == EOF) {
+ return -1;
+ }
+ }
+
+ /* Was enough data read? */
+ if (n < MIF_MAGICLEN) {
+ return -1;
+ }
+
+ /* Compute the signature value. */
+ magic = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
+
+ /* Ensure that the signature is correct for this format. */
+ if (magic != MIF_MAGIC) {
+ return -1;
+ }
+
+ return 0;
+}
+
+/******************************************************************************\
+* Code for MIF header class.
+\******************************************************************************/
+
+static mif_hdr_t *mif_hdr_create(int maxcmpts)
+{
+ mif_hdr_t *hdr;
+ if (!(hdr = jas_malloc(sizeof(mif_hdr_t)))) {
+ return 0;
+ }
+ hdr->numcmpts = 0;
+ hdr->maxcmpts = 0;
+ hdr->cmpts = 0;
+ if (mif_hdr_growcmpts(hdr, maxcmpts)) {
+ mif_hdr_destroy(hdr);
+ return 0;
+ }
+ return hdr;
+}
+
+static void mif_hdr_destroy(mif_hdr_t *hdr)
+{
+ int cmptno;
+ if (hdr->cmpts) {
+ for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) {
+ mif_cmpt_destroy(hdr->cmpts[cmptno]);
+ }
+ jas_free(hdr->cmpts);
+ }
+ jas_free(hdr);
+}
+
+static int mif_hdr_growcmpts(mif_hdr_t *hdr, int maxcmpts)
+{
+ int cmptno;
+ mif_cmpt_t **newcmpts;
+ assert(maxcmpts >= hdr->numcmpts);
+ newcmpts = (!hdr->cmpts) ? jas_malloc(maxcmpts * sizeof(mif_cmpt_t *)) :
+ jas_realloc(hdr->cmpts, maxcmpts * sizeof(mif_cmpt_t *));
+ if (!newcmpts) {
+ return -1;
+ }
+ hdr->maxcmpts = maxcmpts;
+ hdr->cmpts = newcmpts;
+ for (cmptno = hdr->numcmpts; cmptno < hdr->maxcmpts; ++cmptno) {
+ hdr->cmpts[cmptno] = 0;
+ }
+ return 0;
+}
+
+static mif_hdr_t *mif_hdr_get(jas_stream_t *in)
+{
+ uchar magicbuf[MIF_MAGICLEN];
+ char buf[4096];
+ mif_hdr_t *hdr;
+ bool done;
+ jas_tvparser_t *tvp;
+ int id;
+
+ hdr = 0;
+
+ if (jas_stream_read(in, magicbuf, MIF_MAGICLEN) != MIF_MAGICLEN) {
+ goto error;
+ }
+ if (magicbuf[0] != (MIF_MAGIC >> 24) || magicbuf[1] != ((MIF_MAGIC >> 16) &
+ 0xff) || magicbuf[2] != ((MIF_MAGIC >> 8) & 0xff) || magicbuf[3] !=
+ (MIF_MAGIC & 0xff)) {
+ jas_eprintf("error: bad signature\n");
+ goto error;
+ }
+
+ if (!(hdr = mif_hdr_create(0))) {
+ goto error;
+ }
+
+ done = false;
+ do {
+ if (!mif_getline(in, buf, sizeof(buf))) {
+ goto error;
+ }
+ if (buf[0] == '\0') {
+ continue;
+ }
+ if (!(tvp = jas_tvparser_create(buf))) {
+ goto error;
+ }
+ if (jas_tvparser_next(tvp)) {
+ abort();
+ }
+ id = jas_taginfo_nonull(jas_taginfos_lookup(mif_tags2, jas_tvparser_gettag(tvp)))->id;
+ jas_tvparser_destroy(tvp);
+ switch (id) {
+ case MIF_CMPT:
+ mif_process_cmpt(hdr, buf);
+ break;
+ case MIF_END:
+ done = 1;
+ break;
+ }
+ } while (!done);
+
+ return hdr;
+
+error:
+ if (hdr) {
+ mif_hdr_destroy(hdr);
+ }
+ return 0;
+}
+
+static int mif_process_cmpt(mif_hdr_t *hdr, char *buf)
+{
+ jas_tvparser_t *tvp;
+ mif_cmpt_t *cmpt;
+ int id;
+
+ cmpt = 0;
+ tvp = 0;
+
+ if (!(cmpt = mif_cmpt_create())) {
+ goto error;
+ }
+ cmpt->tlx = 0;
+ cmpt->tly = 0;
+ cmpt->sampperx = 0;
+ cmpt->samppery = 0;
+ cmpt->width = 0;
+ cmpt->height = 0;
+ cmpt->prec = 0;
+ cmpt->sgnd = -1;
+ cmpt->data = 0;
+
+ if (!(tvp = jas_tvparser_create(buf))) {
+ goto error;
+ }
+ while (!(id = jas_tvparser_next(tvp))) {
+ switch (jas_taginfo_nonull(jas_taginfos_lookup(mif_tags,
+ jas_tvparser_gettag(tvp)))->id) {
+ case MIF_TLX:
+ cmpt->tlx = atoi(jas_tvparser_getval(tvp));
+ break;
+ case MIF_TLY:
+ cmpt->tly = atoi(jas_tvparser_getval(tvp));
+ break;
+ case MIF_WIDTH:
+ cmpt->width = atoi(jas_tvparser_getval(tvp));
+ break;
+ case MIF_HEIGHT:
+ cmpt->height = atoi(jas_tvparser_getval(tvp));
+ break;
+ case MIF_HSAMP:
+ cmpt->sampperx = atoi(jas_tvparser_getval(tvp));
+ break;
+ case MIF_VSAMP:
+ cmpt->samppery = atoi(jas_tvparser_getval(tvp));
+ break;
+ case MIF_PREC:
+ cmpt->prec = atoi(jas_tvparser_getval(tvp));
+ break;
+ case MIF_SGND:
+ cmpt->sgnd = atoi(jas_tvparser_getval(tvp));
+ break;
+ case MIF_DATA:
+ if (!(cmpt->data = jas_strdup(jas_tvparser_getval(tvp)))) {
+ return -1;
+ }
+ break;
+ }
+ }
+ jas_tvparser_destroy(tvp);
+ if (!cmpt->sampperx || !cmpt->samppery) {
+ goto error;
+ }
+ if (mif_hdr_addcmpt(hdr, hdr->numcmpts, cmpt)) {
+ goto error;
+ }
+ return 0;
+
+error:
+ if (cmpt) {
+ mif_cmpt_destroy(cmpt);
+ }
+ if (tvp) {
+ jas_tvparser_destroy(tvp);
+ }
+ return -1;
+}
+
+static int mif_hdr_put(mif_hdr_t *hdr, jas_stream_t *out)
+{
+ int cmptno;
+ mif_cmpt_t *cmpt;
+
+ /* Output signature. */
+ jas_stream_putc(out, (MIF_MAGIC >> 24) & 0xff);
+ jas_stream_putc(out, (MIF_MAGIC >> 16) & 0xff);
+ jas_stream_putc(out, (MIF_MAGIC >> 8) & 0xff);
+ jas_stream_putc(out, MIF_MAGIC & 0xff);
+
+ /* Output component information. */
+ for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) {
+ cmpt = hdr->cmpts[cmptno];
+ jas_stream_printf(out, "component tlx=%ld tly=%ld "
+ "sampperx=%ld samppery=%ld width=%ld height=%ld prec=%d sgnd=%d",
+ cmpt->tlx, cmpt->tly, cmpt->sampperx, cmpt->samppery, cmpt->width,
+ cmpt->height, cmpt->prec, cmpt->sgnd);
+ if (cmpt->data) {
+ jas_stream_printf(out, " data=%s", cmpt->data);
+ }
+ jas_stream_printf(out, "\n");
+ }
+
+ /* Output end of header indicator. */
+ jas_stream_printf(out, "end\n");
+
+ return 0;
+}
+
+static int mif_hdr_addcmpt(mif_hdr_t *hdr, int cmptno, mif_cmpt_t *cmpt)
+{
+ assert(cmptno >= hdr->numcmpts);
+ if (hdr->numcmpts >= hdr->maxcmpts) {
+ if (mif_hdr_growcmpts(hdr, hdr->numcmpts + 128)) {
+ return -1;
+ }
+ }
+ hdr->cmpts[hdr->numcmpts] = cmpt;
+ ++hdr->numcmpts;
+ return 0;
+}
+
+/******************************************************************************\
+* Code for MIF component class.
+\******************************************************************************/
+
+static mif_cmpt_t *mif_cmpt_create()
+{
+ mif_cmpt_t *cmpt;
+ if (!(cmpt = jas_malloc(sizeof(mif_cmpt_t)))) {
+ return 0;
+ }
+ memset(cmpt, 0, sizeof(mif_cmpt_t));
+ return cmpt;
+}
+
+static void mif_cmpt_destroy(mif_cmpt_t *cmpt)
+{
+ if (cmpt->data) {
+ jas_free(cmpt->data);
+ }
+ jas_free(cmpt);
+}
+
+/******************************************************************************\
+* MIF parsing code.
+\******************************************************************************/
+
+static char *mif_getline(jas_stream_t *stream, char *buf, int bufsize)
+{
+ int c;
+ char *bufptr;
+ assert(bufsize > 0);
+
+ bufptr = buf;
+ while (bufsize > 1) {
+ if ((c = mif_getc(stream)) == EOF) {
+ break;
+ }
+ *bufptr++ = c;
+ --bufsize;
+ if (c == '\n') {
+ break;
+ }
+ }
+ *bufptr = '\0';
+ if (!(bufptr = strchr(buf, '\n'))) {
+ return 0;
+ }
+ *bufptr = '\0';
+ return buf;
+}
+
+static int mif_getc(jas_stream_t *in)
+{
+ int c;
+ bool done;
+
+ done = false;
+ do {
+ switch (c = jas_stream_getc(in)) {
+ case EOF:
+ done = 1;
+ break;
+ case '#':
+ for (;;) {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ done = 1;
+ break;
+ }
+ if (c == '\n') {
+ break;
+ }
+ }
+ break;
+ case '\\':
+ if (jas_stream_peekc(in) == '\n') {
+ jas_stream_getc(in);
+ }
+ break;
+ default:
+ done = 1;
+ break;
+ }
+ } while (!done);
+
+ return c;
+}
+
+/******************************************************************************\
+* Miscellaneous functions.
+\******************************************************************************/
+
+static mif_hdr_t *mif_makehdrfromimage(jas_image_t *image)
+{
+ mif_hdr_t *hdr;
+ int cmptno;
+ mif_cmpt_t *cmpt;
+
+ if (!(hdr = mif_hdr_create(jas_image_numcmpts(image)))) {
+ return 0;
+ }
+ hdr->magic = MIF_MAGIC;
+ hdr->numcmpts = jas_image_numcmpts(image);
+ for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) {
+ hdr->cmpts[cmptno] = jas_malloc(sizeof(mif_cmpt_t));
+ cmpt = hdr->cmpts[cmptno];
+ cmpt->tlx = jas_image_cmpttlx(image, cmptno);
+ cmpt->tly = jas_image_cmpttly(image, cmptno);
+ cmpt->width = jas_image_cmptwidth(image, cmptno);
+ cmpt->height = jas_image_cmptheight(image, cmptno);
+ cmpt->sampperx = jas_image_cmpthstep(image, cmptno);
+ cmpt->samppery = jas_image_cmptvstep(image, cmptno);
+ cmpt->prec = jas_image_cmptprec(image, cmptno);
+ cmpt->sgnd = jas_image_cmptsgnd(image, cmptno);
+ cmpt->data = 0;
+ }
+ return hdr;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/mif/mif_cod.h b/jasper-1.900.1-6ct/src/libjasper/mif/mif_cod.h
new file mode 100644
index 0000000..a265afa
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/mif/mif_cod.h
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef MIF_COD_H
+#define MIF_COD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+#define MIF_MAGIC 0x4d49460a
+/* signature */
+
+#define MIF_MAGICLEN 4
+/* length of signature in bytes */
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* Per-component information. */
+
+typedef struct {
+
+ int_fast32_t tlx;
+
+ int_fast32_t tly;
+
+ int_fast32_t width;
+
+ int_fast32_t height;
+
+ int_fast32_t sampperx;
+
+ int_fast32_t samppery;
+
+ int_fast16_t prec;
+
+ int_fast16_t sgnd;
+
+ char *data;
+
+} mif_cmpt_t;
+
+/* MIF header. */
+
+typedef struct {
+
+ uint_fast32_t magic;
+
+ int numcmpts;
+
+ int maxcmpts;
+
+ mif_cmpt_t **cmpts;
+
+} mif_hdr_t;
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/pgx/Makefile.am b/jasper-1.900.1-6ct/src/libjasper/pgx/Makefile.am
new file mode 100644
index 0000000..e3c6d1a
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pgx/Makefile.am
@@ -0,0 +1,67 @@
+# Copyright (c) 2001-2003 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+noinst_LTLIBRARIES = libpgx.la
+libpgx_la_SOURCES = \
+ pgx_cod.h \
+ pgx_enc.h \
+ pgx_cod.c \
+ pgx_dec.c \
+ pgx_enc.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
diff --git a/jasper-1.900.1-6ct/src/libjasper/pgx/Makefile.in b/jasper-1.900.1-6ct/src/libjasper/pgx/Makefile.in
new file mode 100644
index 0000000..b2f360b
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pgx/Makefile.in
@@ -0,0 +1,510 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2003 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src/libjasper/pgx
+DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+LTLIBRARIES = $(noinst_LTLIBRARIES)
+libpgx_la_LIBADD =
+am_libpgx_la_OBJECTS = pgx_cod.lo pgx_dec.lo pgx_enc.lo
+libpgx_la_OBJECTS = $(am_libpgx_la_OBJECTS)
+DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/src/libjasper/include/jasper
+depcomp = $(SHELL) $(top_srcdir)/acaux/depcomp
+am__depfiles_maybe = depfiles
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LTCOMPILE = $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) \
+ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+ $(AM_CFLAGS) $(CFLAGS)
+CCLD = $(CC)
+LINK = $(LIBTOOL) --tag=CC --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+ $(AM_LDFLAGS) $(LDFLAGS) -o $@
+SOURCES = $(libpgx_la_SOURCES)
+DIST_SOURCES = $(libpgx_la_SOURCES)
+ETAGS = etags
+CTAGS = ctags
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+noinst_LTLIBRARIES = libpgx.la
+libpgx_la_SOURCES = \
+ pgx_cod.h \
+ pgx_enc.h \
+ pgx_cod.c \
+ pgx_dec.c \
+ pgx_enc.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
+all: all-am
+
+.SUFFIXES:
+.SUFFIXES: .c .lo .o .obj
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libjasper/pgx/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/libjasper/pgx/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+clean-noinstLTLIBRARIES:
+ -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
+ @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \
+ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
+ test "$$dir" != "$$p" || dir=.; \
+ echo "rm -f \"$${dir}/so_locations\""; \
+ rm -f "$${dir}/so_locations"; \
+ done
+libpgx.la: $(libpgx_la_OBJECTS) $(libpgx_la_DEPENDENCIES)
+ $(LINK) $(libpgx_la_LDFLAGS) $(libpgx_la_OBJECTS) $(libpgx_la_LIBADD) $(LIBS)
+
+mostlyclean-compile:
+ -rm -f *.$(OBJEXT)
+
+distclean-compile:
+ -rm -f *.tab.c
+
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/pgx_cod.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/pgx_dec.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/pgx_enc.Plo at am__quote@
+
+.c.o:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c $<
+
+.c.obj:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
+
+.c.lo:
+ at am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $<
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-am
+all-am: Makefile $(LTLIBRARIES)
+installdirs:
+install: install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-am
+
+clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \
+ mostlyclean-am
+
+distclean: distclean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+distclean-am: clean-am distclean-compile distclean-generic \
+ distclean-libtool distclean-tags
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+info: info-am
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-am
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-compile mostlyclean-generic \
+ mostlyclean-libtool
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
+ clean-libtool clean-noinstLTLIBRARIES ctags distclean \
+ distclean-compile distclean-generic distclean-libtool \
+ distclean-tags distdir dvi dvi-am html html-am info info-am \
+ install install-am install-data install-data-am install-exec \
+ install-exec-am install-info install-info-am install-man \
+ install-strip installcheck installcheck-am installdirs \
+ maintainer-clean maintainer-clean-generic mostlyclean \
+ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
+ pdf pdf-am ps ps-am tags uninstall uninstall-am \
+ uninstall-info-am
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_cod.c b/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_cod.c
new file mode 100644
index 0000000..8950788
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_cod.c
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "pgx_cod.h"
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+void pgx_dumphdr(FILE *out, pgx_hdr_t *hdr)
+{
+ fprintf(out, "byteorder=%s sgnd=%s prec=%d width=%d height=%d\n",
+ hdr->bigendian ? "bigendian" : "littleendian",
+ hdr->sgnd ? "signed" : "unsigned",
+ hdr->prec, hdr->width, hdr->height);
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_cod.h b/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_cod.h
new file mode 100644
index 0000000..79a21e8
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_cod.h
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * PGX Format Library
+ *
+ * $Id$
+ */
+
+#ifndef PGX_COD_H
+#define PGX_COD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <stdio.h>
+
+#include "jasper/jas_types.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+#define PGX_MAGIC 0x5047
+#define PGX_MAGICLEN 2
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+typedef struct {
+
+ uint_fast16_t magic;
+ /* The signature. */
+
+ bool bigendian;
+ /* The byte ordering used. */
+
+ bool sgnd;
+ /* The signedness of the samples. */
+
+ uint_fast32_t prec;
+ /* The precision of the samples. */
+
+ uint_fast32_t width;
+ /* The width of the component. */
+
+ uint_fast32_t height;
+ /* The height of the component. */
+
+} pgx_hdr_t;
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+void pgx_dumphdr(FILE *out, pgx_hdr_t *hdr);
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_dec.c b/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_dec.c
new file mode 100644
index 0000000..560eae4
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_dec.c
@@ -0,0 +1,414 @@
+/*
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+#include <ctype.h>
+
+#include "jasper/jas_tvp.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_string.h"
+
+#include "pgx_cod.h"
+
+/******************************************************************************\
+* Local prototypes.
+\******************************************************************************/
+
+static int pgx_gethdr(jas_stream_t *in, pgx_hdr_t *hdr);
+static int pgx_getdata(jas_stream_t *in, pgx_hdr_t *hdr, jas_image_t *image);
+static int_fast32_t pgx_getword(jas_stream_t *in, bool bigendian, int prec);
+static int pgx_getsgnd(jas_stream_t *in, bool *sgnd);
+static int pgx_getbyteorder(jas_stream_t *in, bool *bigendian);
+static int pgx_getc(jas_stream_t *in);
+static int pgx_getuint32(jas_stream_t *in, uint_fast32_t *val);
+static jas_seqent_t pgx_wordtoint(uint_fast32_t word, int prec, bool sgnd);
+
+/******************************************************************************\
+* Code for load operation.
+\******************************************************************************/
+
+/* Load an image from a stream in the PGX format. */
+
+jas_image_t *pgx_decode(jas_stream_t *in, char *optstr)
+{
+ jas_image_t *image;
+ pgx_hdr_t hdr;
+ jas_image_cmptparm_t cmptparm;
+
+ /* Avoid compiler warnings about unused parameters. */
+ optstr = 0;
+
+ image = 0;
+
+ if (pgx_gethdr(in, &hdr)) {
+ goto error;
+ }
+
+#ifdef PGX_DEBUG
+ pgx_dumphdr(stderr, &hdr);
+#endif
+
+ if (!(image = jas_image_create0())) {
+ goto error;
+ }
+ cmptparm.tlx = 0;
+ cmptparm.tly = 0;
+ cmptparm.hstep = 1;
+ cmptparm.vstep = 1;
+ cmptparm.width = hdr.width;
+ cmptparm.height = hdr.height;
+ cmptparm.prec = hdr.prec;
+ cmptparm.sgnd = hdr.sgnd;
+ if (jas_image_addcmpt(image, 0, &cmptparm)) {
+ goto error;
+ }
+ if (pgx_getdata(in, &hdr, image)) {
+ goto error;
+ }
+
+ jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
+ jas_image_setcmpttype(image, 0,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
+
+ return image;
+
+error:
+ if (image) {
+ jas_image_destroy(image);
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Code for validate operation.
+\******************************************************************************/
+
+int pgx_validate(jas_stream_t *in)
+{
+ uchar buf[PGX_MAGICLEN];
+ uint_fast32_t magic;
+ int i;
+ int n;
+
+ assert(JAS_STREAM_MAXPUTBACK >= PGX_MAGICLEN);
+
+ /* Read the validation data (i.e., the data used for detecting
+ the format). */
+ if ((n = jas_stream_read(in, buf, PGX_MAGICLEN)) < 0) {
+ return -1;
+ }
+
+ /* Put the validation data back onto the stream, so that the
+ stream position will not be changed. */
+ for (i = n - 1; i >= 0; --i) {
+ if (jas_stream_ungetc(in, buf[i]) == EOF) {
+ return -1;
+ }
+ }
+
+ /* Did we read enough data? */
+ if (n < PGX_MAGICLEN) {
+ return -1;
+ }
+
+ /* Compute the signature value. */
+ magic = (buf[0] << 8) | buf[1];
+
+ /* Ensure that the signature is correct for this format. */
+ if (magic != PGX_MAGIC) {
+ return -1;
+ }
+
+ return 0;
+}
+
+/******************************************************************************\
+*
+\******************************************************************************/
+
+static int pgx_gethdr(jas_stream_t *in, pgx_hdr_t *hdr)
+{
+ int c;
+ uchar buf[2];
+
+ if ((c = jas_stream_getc(in)) == EOF) {
+ goto error;
+ }
+ buf[0] = c;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ goto error;
+ }
+ buf[1] = c;
+ hdr->magic = buf[0] << 8 | buf[1];
+ if (hdr->magic != PGX_MAGIC) {
+ goto error;
+ }
+ if ((c = pgx_getc(in)) == EOF || !isspace(c)) {
+ goto error;
+ }
+ if (pgx_getbyteorder(in, &hdr->bigendian)) {
+ goto error;
+ }
+ if (pgx_getsgnd(in, &hdr->sgnd)) {
+ goto error;
+ }
+ if (pgx_getuint32(in, &hdr->prec)) {
+ goto error;
+ }
+ if (pgx_getuint32(in, &hdr->width)) {
+ goto error;
+ }
+ if (pgx_getuint32(in, &hdr->height)) {
+ goto error;
+ }
+ return 0;
+
+error:
+ return -1;
+}
+
+static int pgx_getdata(jas_stream_t *in, pgx_hdr_t *hdr, jas_image_t *image)
+{
+ jas_matrix_t *data;
+ uint_fast32_t x;
+ uint_fast32_t y;
+ uint_fast32_t word;
+ int_fast32_t v;
+
+ data = 0;
+
+ if (!(data = jas_matrix_create(1, hdr->width))) {
+ goto error;
+ }
+ for (y = 0; y < hdr->height; ++y) {
+ for (x = 0; x < hdr->width; ++x) {
+ /* Need to adjust signed value. */
+ if ((v = pgx_getword(in, hdr->bigendian, hdr->prec)) < 0) {
+ goto error;
+ }
+ word = v;
+ v = pgx_wordtoint(word, hdr->prec, hdr->sgnd);
+ jas_matrix_set(data, 0, x, v);
+ }
+ if (jas_image_writecmpt(image, 0, 0, y, hdr->width, 1, data)) {
+ goto error;
+ }
+ }
+ jas_matrix_destroy(data);
+ return 0;
+
+error:
+ if (data) {
+ jas_matrix_destroy(data);
+ }
+ return -1;
+}
+
+static int_fast32_t pgx_getword(jas_stream_t *in, bool bigendian, int prec)
+{
+ uint_fast32_t val;
+ int i;
+ int j;
+ int c;
+ int wordsize;
+
+ wordsize = (prec + 7) / 8;
+
+ if (prec > 32) {
+ goto error;
+ }
+
+ val = 0;
+ for (i = 0; i < wordsize; ++i) {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ goto error;
+ }
+ j = bigendian ? (wordsize - 1 - i) : i;
+ val = val | ((c & 0xff) << (8 * j));
+ }
+ val &= (1 << prec) - 1;
+ return val;
+
+error:
+ return -1;
+}
+
+static int pgx_getc(jas_stream_t *in)
+{
+ int c;
+ for (;;) {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ if (c != '#') {
+ return c;
+ }
+ do {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ } while (c != '\n' && c != '\r');
+ }
+}
+
+static int pgx_getbyteorder(jas_stream_t *in, bool *bigendian)
+{
+ int c;
+ char buf[2];
+
+ do {
+ if ((c = pgx_getc(in)) == EOF) {
+ return -1;
+ }
+ } while (isspace(c));
+
+ buf[0] = c;
+ if ((c = pgx_getc(in)) == EOF) {
+ goto error;
+ }
+ buf[1] = c;
+ if (buf[0] == 'M' && buf[1] == 'L') {
+ *bigendian = true;
+ } else if (buf[0] == 'L' && buf[1] == 'M') {
+ *bigendian = false;
+ } else {
+ goto error;
+ }
+
+ while ((c = pgx_getc(in)) != EOF && !isspace(c)) {
+ ;
+ }
+ if (c == EOF) {
+ goto error;
+ }
+ return 0;
+
+error:
+ return -1;
+}
+
+static int pgx_getsgnd(jas_stream_t *in, bool *sgnd)
+{
+ int c;
+
+ do {
+ if ((c = pgx_getc(in)) == EOF) {
+ return -1;
+ }
+ } while (isspace(c));
+
+ if (c == '+') {
+ *sgnd = false;
+ } else if (c == '-') {
+ *sgnd = true;
+ } else {
+ goto error;
+ }
+ while ((c = pgx_getc(in)) != EOF && !isspace(c)) {
+ ;
+ }
+ if (c == EOF) {
+ goto error;
+ }
+ return 0;
+
+error:
+ return -1;
+}
+
+static int pgx_getuint32(jas_stream_t *in, uint_fast32_t *val)
+{
+ int c;
+ uint_fast32_t v;
+
+ do {
+ if ((c = pgx_getc(in)) == EOF) {
+ return -1;
+ }
+ } while (isspace(c));
+
+ v = 0;
+ while (isdigit(c)) {
+ v = 10 * v + c - '0';
+ if ((c = pgx_getc(in)) < 0) {
+ return -1;
+ }
+ }
+ if (!isspace(c)) {
+ return -1;
+ }
+ *val = v;
+
+ return 0;
+}
+
+static jas_seqent_t pgx_wordtoint(uint_fast32_t v, int prec, bool sgnd)
+{
+ jas_seqent_t ret;
+ v &= (1 << prec) - 1;
+ ret = (sgnd && (v & (1 << (prec - 1)))) ? (v - (1 << prec)) : v;
+ return ret;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_enc.c b/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_enc.c
new file mode 100644
index 0000000..070edfb
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_enc.c
@@ -0,0 +1,230 @@
+/*
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+
+#include "jasper/jas_tvp.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_string.h"
+#include "jasper/jas_debug.h"
+
+#include "pgx_cod.h"
+#include "pgx_enc.h"
+
+/******************************************************************************\
+* Local functions.
+\******************************************************************************/
+
+static int pgx_puthdr(jas_stream_t *out, pgx_hdr_t *hdr);
+static int pgx_putdata(jas_stream_t *out, pgx_hdr_t *hdr, jas_image_t *image, int cmpt);
+static int pgx_putword(jas_stream_t *out, bool bigendian, int prec,
+ uint_fast32_t val);
+static uint_fast32_t pgx_inttoword(int_fast32_t val, int prec, bool sgnd);
+
+/******************************************************************************\
+* Code for save operation.
+\******************************************************************************/
+
+/* Save an image to a stream in the the PGX format. */
+
+int pgx_encode(jas_image_t *image, jas_stream_t *out, char *optstr)
+{
+ pgx_hdr_t hdr;
+ uint_fast32_t width;
+ uint_fast32_t height;
+ bool sgnd;
+ int prec;
+ pgx_enc_t encbuf;
+ pgx_enc_t *enc = &encbuf;
+
+ /* Avoid compiler warnings about unused parameters. */
+ optstr = 0;
+
+ switch (jas_clrspc_fam(jas_image_clrspc(image))) {
+ case JAS_CLRSPC_FAM_GRAY:
+ if ((enc->cmpt = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y))) < 0) {
+ jas_eprintf("error: missing color component\n");
+ return -1;
+ }
+ break;
+ default:
+ jas_eprintf("error: BMP format does not support color space\n");
+ return -1;
+ break;
+ }
+
+ width = jas_image_cmptwidth(image, enc->cmpt);
+ height = jas_image_cmptheight(image, enc->cmpt);
+ prec = jas_image_cmptprec(image, enc->cmpt);
+ sgnd = jas_image_cmptsgnd(image, enc->cmpt);
+
+ /* The PGX format is quite limited in the set of image geometries
+ that it can handle. Here, we check to ensure that the image to
+ be saved can actually be represented reasonably accurately using the
+ PGX format. */
+ /* There must be exactly one component. */
+ if (jas_image_numcmpts(image) > 1 || prec > 16) {
+ jas_eprintf("The PNM format cannot be used to represent an image with this geometry.\n");
+ return -1;
+ }
+
+ hdr.magic = PGX_MAGIC;
+ hdr.bigendian = true;
+ hdr.sgnd = sgnd;
+ hdr.prec = prec;
+ hdr.width = width;
+ hdr.height = height;
+
+#ifdef PGX_DEBUG
+ pgx_dumphdr(stderr, &hdr);
+#endif
+
+ if (pgx_puthdr(out, &hdr)) {
+ return -1;
+ }
+
+ if (pgx_putdata(out, &hdr, image, enc->cmpt)) {
+ return -1;
+ }
+
+ return 0;
+}
+
+/******************************************************************************\
+\******************************************************************************/
+
+static int pgx_puthdr(jas_stream_t *out, pgx_hdr_t *hdr)
+{
+ jas_stream_printf(out, "%c%c", hdr->magic >> 8, hdr->magic & 0xff);
+ jas_stream_printf(out, " %s %s %d %ld %ld\n", hdr->bigendian ? "ML" : "LM",
+ hdr->sgnd ? "-" : "+", hdr->prec, (long) hdr->width, (long) hdr->height);
+ if (jas_stream_error(out)) {
+ return -1;
+ }
+ return 0;
+}
+
+static int pgx_putdata(jas_stream_t *out, pgx_hdr_t *hdr, jas_image_t *image, int cmpt)
+{
+ jas_matrix_t *data;
+ uint_fast32_t x;
+ uint_fast32_t y;
+ int_fast32_t v;
+ uint_fast32_t word;
+
+ data = 0;
+
+ if (!(data = jas_matrix_create(1, hdr->width))) {
+ goto error;
+ }
+ for (y = 0; y < hdr->height; ++y) {
+ if (jas_image_readcmpt(image, cmpt, 0, y, hdr->width, 1, data)) {
+ goto error;
+ }
+ for (x = 0; x < hdr->width; ++x) {
+ v = jas_matrix_get(data, 0, x);
+ word = pgx_inttoword(v, hdr->prec, hdr->sgnd);
+ if (pgx_putword(out, hdr->bigendian, hdr->prec, word)) {
+ goto error;
+ }
+ }
+ }
+ jas_matrix_destroy(data);
+ data = 0;
+ return 0;
+
+error:
+ if (data) {
+ jas_matrix_destroy(data);
+ }
+ return -1;
+}
+
+static int pgx_putword(jas_stream_t *out, bool bigendian, int prec,
+ uint_fast32_t val)
+{
+ int i;
+ int j;
+ int wordsize;
+
+ val &= (1 << prec) - 1;
+ wordsize = (prec + 7) /8;
+ for (i = 0; i < wordsize; ++i) {
+ j = bigendian ? (wordsize - 1 - i) : i;
+ if (jas_stream_putc(out, (val >> (8 * j)) & 0xff) == EOF) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static uint_fast32_t pgx_inttoword(jas_seqent_t v, int prec, bool sgnd)
+{
+ uint_fast32_t ret;
+ ret = ((sgnd && v < 0) ? ((1 << prec) + v) : v) & ((1 << prec) - 1);
+ return ret;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_enc.h b/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_enc.h
new file mode 100644
index 0000000..fce059a
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pgx/pgx_enc.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef PGX_ENC_H
+#define PGX_ENC_H
+
+typedef struct {
+ int cmpt;
+} pgx_enc_t;
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/pnm/Makefile.am b/jasper-1.900.1-6ct/src/libjasper/pnm/Makefile.am
new file mode 100644
index 0000000..5eb88ee
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pnm/Makefile.am
@@ -0,0 +1,67 @@
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+noinst_LTLIBRARIES = libpnm.la
+libpnm_la_SOURCES = \
+ pnm_cod.h \
+ pnm_enc.h \
+ pnm_cod.c \
+ pnm_dec.c \
+ pnm_enc.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
diff --git a/jasper-1.900.1-6ct/src/libjasper/pnm/Makefile.in b/jasper-1.900.1-6ct/src/libjasper/pnm/Makefile.in
new file mode 100644
index 0000000..93385a8
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pnm/Makefile.in
@@ -0,0 +1,510 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src/libjasper/pnm
+DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+LTLIBRARIES = $(noinst_LTLIBRARIES)
+libpnm_la_LIBADD =
+am_libpnm_la_OBJECTS = pnm_cod.lo pnm_dec.lo pnm_enc.lo
+libpnm_la_OBJECTS = $(am_libpnm_la_OBJECTS)
+DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/src/libjasper/include/jasper
+depcomp = $(SHELL) $(top_srcdir)/acaux/depcomp
+am__depfiles_maybe = depfiles
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LTCOMPILE = $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) \
+ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+ $(AM_CFLAGS) $(CFLAGS)
+CCLD = $(CC)
+LINK = $(LIBTOOL) --tag=CC --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+ $(AM_LDFLAGS) $(LDFLAGS) -o $@
+SOURCES = $(libpnm_la_SOURCES)
+DIST_SOURCES = $(libpnm_la_SOURCES)
+ETAGS = etags
+CTAGS = ctags
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+noinst_LTLIBRARIES = libpnm.la
+libpnm_la_SOURCES = \
+ pnm_cod.h \
+ pnm_enc.h \
+ pnm_cod.c \
+ pnm_dec.c \
+ pnm_enc.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
+all: all-am
+
+.SUFFIXES:
+.SUFFIXES: .c .lo .o .obj
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libjasper/pnm/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/libjasper/pnm/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+clean-noinstLTLIBRARIES:
+ -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
+ @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \
+ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
+ test "$$dir" != "$$p" || dir=.; \
+ echo "rm -f \"$${dir}/so_locations\""; \
+ rm -f "$${dir}/so_locations"; \
+ done
+libpnm.la: $(libpnm_la_OBJECTS) $(libpnm_la_DEPENDENCIES)
+ $(LINK) $(libpnm_la_LDFLAGS) $(libpnm_la_OBJECTS) $(libpnm_la_LIBADD) $(LIBS)
+
+mostlyclean-compile:
+ -rm -f *.$(OBJEXT)
+
+distclean-compile:
+ -rm -f *.tab.c
+
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/pnm_cod.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/pnm_dec.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/pnm_enc.Plo at am__quote@
+
+.c.o:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c $<
+
+.c.obj:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
+
+.c.lo:
+ at am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $<
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-am
+all-am: Makefile $(LTLIBRARIES)
+installdirs:
+install: install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-am
+
+clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \
+ mostlyclean-am
+
+distclean: distclean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+distclean-am: clean-am distclean-compile distclean-generic \
+ distclean-libtool distclean-tags
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+info: info-am
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-am
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-compile mostlyclean-generic \
+ mostlyclean-libtool
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
+ clean-libtool clean-noinstLTLIBRARIES ctags distclean \
+ distclean-compile distclean-generic distclean-libtool \
+ distclean-tags distdir dvi dvi-am html html-am info info-am \
+ install install-am install-data install-data-am install-exec \
+ install-exec-am install-info install-info-am install-man \
+ install-strip installcheck installcheck-am installdirs \
+ maintainer-clean maintainer-clean-generic mostlyclean \
+ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
+ pdf pdf-am ps ps-am tags uninstall uninstall-am \
+ uninstall-info-am
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_cod.c b/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_cod.c
new file mode 100644
index 0000000..56e09a7
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_cod.c
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Portable Pixmap/Graymap Format Support
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <ctype.h>
+#include <math.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#include "jasper/jas_math.h"
+
+#include "pnm_cod.h"
+
+/******************************************************************************\
+* Miscellaneous utilities.
+\******************************************************************************/
+
+/* Determine the PNM type (i.e., PGM or PPM) from the magic number. */
+int pnm_type(uint_fast16_t magic)
+{
+ int type;
+ switch (magic) {
+ case PNM_MAGIC_TXTPPM:
+ case PNM_MAGIC_BINPPM:
+ type = PNM_TYPE_PPM;
+ break;
+ case PNM_MAGIC_TXTPGM:
+ case PNM_MAGIC_BINPGM:
+ type = PNM_TYPE_PGM;
+ break;
+ case PNM_MAGIC_TXTPBM:
+ case PNM_MAGIC_BINPBM:
+ type = PNM_TYPE_PBM;
+ break;
+ default:
+ /* This should not happen. */
+ abort();
+ break;
+ }
+ return type;
+}
+
+/* Determine the PNM format (i.e., text or binary) from the magic number. */
+int pnm_fmt(uint_fast16_t magic)
+{
+ int fmt;
+ switch (magic) {
+ case PNM_MAGIC_TXTPBM:
+ case PNM_MAGIC_TXTPGM:
+ case PNM_MAGIC_TXTPPM:
+ fmt = PNM_FMT_TXT;
+ break;
+ case PNM_MAGIC_BINPBM:
+ case PNM_MAGIC_BINPGM:
+ case PNM_MAGIC_BINPPM:
+ fmt = PNM_FMT_BIN;
+ break;
+ default:
+ /* This should not happen. */
+ abort();
+ break;
+ }
+ return fmt;
+}
+
+/* Determine the depth (i.e., precision) from the maximum value. */
+int pnm_maxvaltodepth(uint_fast32_t maxval)
+{
+ int n;
+
+ n = 0;
+ while (maxval > 0) {
+ maxval >>= 1;
+ ++n;
+ }
+ return n;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_cod.h b/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_cod.h
new file mode 100644
index 0000000..e73e223
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_cod.h
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Portable Pixmap/Graymap Format Support
+ *
+ * $Id$
+ */
+
+#ifndef PNM_COD_H
+#define PNM_COD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+/* Magic numbers. */
+#define PNM_MAGIC_TXTPBM 0x5031 /* Text Portable BitMap (P1) */
+#define PNM_MAGIC_TXTPGM 0x5032 /* Text Portable GrayMap (P2) */
+#define PNM_MAGIC_TXTPPM 0x5033 /* Text Portable PixMap (P3) */
+#define PNM_MAGIC_BINPBM 0x5034 /* Binary Portable BitMap (P4) */
+#define PNM_MAGIC_BINPGM 0x5035 /* Binary Portable GrayMap (P5) */
+#define PNM_MAGIC_BINPPM 0x5036 /* Binary Portable PixMap (P6) */
+#define PNM_MAGIC_PAM 0x5037 /* PAM (P7) */
+
+/* Type of image data. */
+#define PNM_TYPE_PPM 0 /* PixMap */
+#define PNM_TYPE_PGM 1 /* GrayMap */
+#define PNM_TYPE_PBM 2 /* BitMap */
+
+/* Format of image data. */
+#define PNM_FMT_TXT 0 /* Text */
+#define PNM_FMT_BIN 1 /* Binary */
+
+#define PNM_MAXLINELEN 79
+
+#define PNM_TUPLETYPE_UNKNOWN 0
+#define PNM_TUPLETYPE_MONO 1
+#define PNM_TUPLETYPE_GRAY 2
+#define PNM_TUPLETYPE_GRAYA 3
+#define PNM_TUPLETYPE_RGB 4
+#define PNM_TUPLETYPE_RGBA 5
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* File header. */
+
+typedef struct {
+
+ int magic;
+ /* The magic number. */
+
+ int width;
+ /* The image width. */
+
+ int height;
+ /* The image height. */
+
+ int numcmpts;
+
+ int maxval;
+ /* The maximum allowable sample value. */
+
+#if 0
+ int tupletype;
+#endif
+
+ bool sgnd;
+ /* The sample data is signed. */
+
+} pnm_hdr_t;
+
+/******************************************************************************\
+* Functions.
+\******************************************************************************/
+
+int pnm_type(uint_fast16_t magic);
+/* Determine type (i.e., PGM or PPM) from magic number. */
+
+int pnm_fmt(uint_fast16_t magic);
+/* Determine format (i.e., text or binary) from magic number. */
+
+int pnm_maxvaltodepth(uint_fast32_t maxval);
+/* Determine depth (i.e., precision) from maximum value. */
+
+#define PNM_ONES(n) \
+ (((n) < 32) ? ((1UL << (n)) - 1) : 0xffffffffUL)
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_dec.c b/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_dec.c
new file mode 100644
index 0000000..9de7cb7
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_dec.c
@@ -0,0 +1,565 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Portable Pixmap/Graymap Format Support
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <ctype.h>
+#include <math.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_debug.h"
+
+#include "pnm_cod.h"
+
+/******************************************************************************\
+* Local function prototypes.
+\******************************************************************************/
+
+static int pnm_gethdr(jas_stream_t *in, pnm_hdr_t *hdr);
+static int pnm_getdata(jas_stream_t *in, pnm_hdr_t *hdr, jas_image_t *image);
+
+static int pnm_getsintstr(jas_stream_t *in, int_fast32_t *val);
+static int pnm_getuintstr(jas_stream_t *in, uint_fast32_t *val);
+static int pnm_getbitstr(jas_stream_t *in, int *val);
+static int pnm_getc(jas_stream_t *in);
+
+static int pnm_getsint(jas_stream_t *in, int wordsize, int_fast32_t *val);
+static int pnm_getuint(jas_stream_t *in, int wordsize, uint_fast32_t *val);
+static int pnm_getint16(jas_stream_t *in, int *val);
+#define pnm_getuint32(in, val) pnm_getuint(in, 32, val)
+
+/******************************************************************************\
+* Local data.
+\******************************************************************************/
+
+static int pnm_allowtrunc = 1;
+
+/******************************************************************************\
+* Load function.
+\******************************************************************************/
+
+jas_image_t *pnm_decode(jas_stream_t *in, char *opts)
+{
+ pnm_hdr_t hdr;
+ jas_image_t *image;
+ jas_image_cmptparm_t cmptparms[3];
+ jas_image_cmptparm_t *cmptparm;
+ int i;
+
+ if (opts) {
+ jas_eprintf("warning: ignoring options\n");
+ }
+
+ /* Read the file header. */
+ if (pnm_gethdr(in, &hdr)) {
+ return 0;
+ }
+
+ /* Create an image of the correct size. */
+ for (i = 0, cmptparm = cmptparms; i < hdr.numcmpts; ++i, ++cmptparm) {
+ cmptparm->tlx = 0;
+ cmptparm->tly = 0;
+ cmptparm->hstep = 1;
+ cmptparm->vstep = 1;
+ cmptparm->width = hdr.width;
+ cmptparm->height = hdr.height;
+ cmptparm->prec = pnm_maxvaltodepth(hdr.maxval);
+ cmptparm->sgnd = hdr.sgnd;
+ }
+ if (!(image = jas_image_create(hdr.numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) {
+ return 0;
+ }
+
+ if (hdr.numcmpts == 3) {
+ jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
+ jas_image_setcmpttype(image, 0,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
+ jas_image_setcmpttype(image, 1,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
+ jas_image_setcmpttype(image, 2,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
+ } else {
+ jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
+ jas_image_setcmpttype(image, 0,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
+ }
+
+ /* Read image data from stream into image. */
+ if (pnm_getdata(in, &hdr, image)) {
+ jas_image_destroy(image);
+ return 0;
+ }
+
+ return image;
+}
+
+/******************************************************************************\
+* Validation function.
+\******************************************************************************/
+
+int pnm_validate(jas_stream_t *in)
+{
+ uchar buf[2];
+ int i;
+ int n;
+
+ assert(JAS_STREAM_MAXPUTBACK >= 2);
+
+ /* Read the first two characters that constitute the signature. */
+ if ((n = jas_stream_read(in, buf, 2)) < 0) {
+ return -1;
+ }
+ /* Put these characters back to the stream. */
+ for (i = n - 1; i >= 0; --i) {
+ if (jas_stream_ungetc(in, buf[i]) == EOF) {
+ return -1;
+ }
+ }
+ /* Did we read enough data? */
+ if (n < 2) {
+ return -1;
+ }
+ /* Is this the correct signature for a PNM file? */
+ if (buf[0] == 'P' && isdigit(buf[1])) {
+ return 0;
+ }
+ return -1;
+}
+
+/******************************************************************************\
+* Functions for reading the header.
+\******************************************************************************/
+
+static int pnm_gethdr(jas_stream_t *in, pnm_hdr_t *hdr)
+{
+ int_fast32_t maxval;
+ int_fast32_t width;
+ int_fast32_t height;
+ if (pnm_getint16(in, &hdr->magic) || pnm_getsintstr(in, &width) ||
+ pnm_getsintstr(in, &height)) {
+ return -1;
+ }
+ hdr->width = width;
+ hdr->height = height;
+ if (pnm_type(hdr->magic) != PNM_TYPE_PBM) {
+ if (pnm_getsintstr(in, &maxval)) {
+ return -1;
+ }
+ } else {
+ maxval = 1;
+ }
+ if (maxval < 0) {
+ hdr->maxval = -maxval;
+ hdr->sgnd = true;
+ } else {
+ hdr->maxval = maxval;
+ hdr->sgnd = false;
+ }
+
+ switch (pnm_type(hdr->magic)) {
+ case PNM_TYPE_PBM:
+ case PNM_TYPE_PGM:
+ hdr->numcmpts = 1;
+ break;
+ case PNM_TYPE_PPM:
+ hdr->numcmpts = 3;
+ break;
+ default:
+ abort();
+ break;
+ }
+
+ return 0;
+}
+
+/******************************************************************************\
+* Functions for processing the sample data.
+\******************************************************************************/
+
+static int pnm_getdata(jas_stream_t *in, pnm_hdr_t *hdr, jas_image_t *image)
+{
+ int ret;
+#if 0
+ int numcmpts;
+#endif
+ int cmptno;
+ int fmt;
+ jas_matrix_t *data[3];
+ int x;
+ int y;
+ int_fast64_t v;
+ int depth;
+ int type;
+ int c;
+ int n;
+
+ ret = -1;
+
+#if 0
+ numcmpts = jas_image_numcmpts(image);
+#endif
+ fmt = pnm_fmt(hdr->magic);
+ type = pnm_type(hdr->magic);
+ depth = pnm_maxvaltodepth(hdr->maxval);
+
+ data[0] = 0;
+ data[1] = 0;
+ data[2] = 0;
+ for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) {
+ if (!(data[cmptno] = jas_matrix_create(1, hdr->width))) {
+ goto done;
+ }
+ }
+
+ for (y = 0; y < hdr->height; ++y) {
+ if (type == PNM_TYPE_PBM) {
+ if (fmt == PNM_FMT_BIN) {
+ for (x = 0; x < hdr->width;) {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ goto done;
+ }
+ n = 8;
+ while (n > 0 && x < hdr->width) {
+ jas_matrix_set(data[0], 0, x, 1 - ((c >> 7) & 1));
+ c <<= 1;
+ --n;
+ ++x;
+ }
+ }
+ } else {
+ for (x = 0; x < hdr->width; ++x) {
+ int uv;
+ if (pnm_getbitstr(in, &uv)) {
+ goto done;
+ }
+ jas_matrix_set(data[0], 0, x, 1 - uv);
+ }
+ }
+ } else {
+ for (x = 0; x < hdr->width; ++x) {
+ for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) {
+ if (fmt == PNM_FMT_BIN) {
+ /* The sample data is in binary format. */
+ if (hdr->sgnd) {
+ /* The sample data is signed. */
+ int_fast32_t sv;
+ if (pnm_getsint(in, depth, &sv)) {
+ if (!pnm_allowtrunc) {
+ goto done;
+ }
+ sv = 0;
+ }
+ v = sv;
+ } else {
+ /* The sample data is unsigned. */
+ uint_fast32_t uv;
+ if (pnm_getuint(in, depth, &uv)) {
+ if (!pnm_allowtrunc) {
+ goto done;
+ }
+ uv = 0;
+ }
+ v = uv;
+ }
+ } else {
+ /* The sample data is in text format. */
+ if (hdr->sgnd) {
+ /* The sample data is signed. */
+ int_fast32_t sv;
+ if (pnm_getsintstr(in, &sv)) {
+ if (!pnm_allowtrunc) {
+ goto done;
+ }
+ sv = 0;
+ }
+ v = sv;
+ } else {
+ /* The sample data is unsigned. */
+ uint_fast32_t uv;
+ if (pnm_getuintstr(in, &uv)) {
+ if (!pnm_allowtrunc) {
+ goto done;
+ }
+ uv = 0;
+ }
+ v = uv;
+ }
+ }
+ jas_matrix_set(data[cmptno], 0, x, v);
+ }
+ }
+ }
+ for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) {
+ if (jas_image_writecmpt(image, cmptno, 0, y, hdr->width, 1,
+ data[cmptno])) {
+ goto done;
+ }
+ }
+ }
+
+ ret = 0;
+
+done:
+
+ for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) {
+ if (data[cmptno]) {
+ jas_matrix_destroy(data[cmptno]);
+ }
+ }
+
+ return ret;
+}
+
+/******************************************************************************\
+* Miscellaneous functions.
+\******************************************************************************/
+
+static int pnm_getsint(jas_stream_t *in, int wordsize, int_fast32_t *val)
+{
+ uint_fast32_t tmpval;
+
+ if (pnm_getuint(in, wordsize, &tmpval)) {
+ return -1;
+ }
+ if (val) {
+ assert((tmpval & (1 << (wordsize - 1))) == 0);
+ *val = tmpval;
+ }
+
+ return 0;
+}
+
+static int pnm_getuint(jas_stream_t *in, int wordsize, uint_fast32_t *val)
+{
+ uint_fast32_t tmpval;
+ int c;
+ int n;
+
+ tmpval = 0;
+ n = (wordsize + 7) / 8;
+ while (--n >= 0) {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ tmpval = (tmpval << 8) | c;
+ }
+ tmpval &= (((uint_fast64_t) 1) << wordsize) - 1;
+ if (val) {
+ *val = tmpval;
+ }
+
+ return 0;
+}
+
+static int pnm_getbitstr(jas_stream_t *in, int *val)
+{
+ int c;
+ int_fast32_t v;
+ for (;;) {
+ if ((c = pnm_getc(in)) == EOF) {
+ return -1;
+ }
+ if (c == '#') {
+ for (;;) {
+ if ((c = pnm_getc(in)) == EOF) {
+ return -1;
+ }
+ if (c == '\n') {
+ break;
+ }
+ }
+ } else if (c == '0' || c == '1') {
+ v = c - '0';
+ break;
+ }
+ }
+ if (val) {
+ *val = v;
+ }
+ return 0;
+}
+
+static int pnm_getuintstr(jas_stream_t *in, uint_fast32_t *val)
+{
+ uint_fast32_t v;
+ int c;
+
+ /* Discard any leading whitespace. */
+ do {
+ if ((c = pnm_getc(in)) == EOF) {
+ return -1;
+ }
+ } while (isspace(c));
+
+ /* Parse the number. */
+ v = 0;
+ while (isdigit(c)) {
+ v = 10 * v + c - '0';
+ if ((c = pnm_getc(in)) < 0) {
+ return -1;
+ }
+ }
+
+ /* The number must be followed by whitespace. */
+ if (!isspace(c)) {
+ return -1;
+ }
+
+ if (val) {
+ *val = v;
+ }
+ return 0;
+}
+
+static int pnm_getsintstr(jas_stream_t *in, int_fast32_t *val)
+{
+ int c;
+ int s;
+ int_fast32_t v;
+
+ /* Discard any leading whitespace. */
+ do {
+ if ((c = pnm_getc(in)) == EOF) {
+ return -1;
+ }
+ } while (isspace(c));
+
+ /* Get the number, allowing for a negative sign. */
+ s = 1;
+ if (c == '-') {
+ s = -1;
+ if ((c = pnm_getc(in)) == EOF) {
+ return -1;
+ }
+ } else if (c == '+') {
+ if ((c = pnm_getc(in)) == EOF) {
+ return -1;
+ }
+ }
+ v = 0;
+ while (isdigit(c)) {
+ v = 10 * v + c - '0';
+ if ((c = pnm_getc(in)) < 0) {
+ return -1;
+ }
+ }
+
+ /* The number must be followed by whitespace. */
+ if (!isspace(c)) {
+ return -1;
+ }
+
+ if (val) {
+ *val = (s >= 0) ? v : (-v);
+ }
+
+ return 0;
+}
+
+static int pnm_getc(jas_stream_t *in)
+{
+ int c;
+ for (;;) {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ if (c != '#') {
+ return c;
+ }
+ do {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ } while (c != '\n' && c != '\r');
+ }
+}
+
+static int pnm_getint16(jas_stream_t *in, int *val)
+{
+ int v;
+ int c;
+
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = c & 0xff;
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ v = (v << 8) | (c & 0xff);
+ *val = v;
+
+ return 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_enc.c b/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_enc.c
new file mode 100644
index 0000000..3ab889d
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_enc.c
@@ -0,0 +1,452 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Portable Pixmap/Graymap Format Support
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <ctype.h>
+#include <math.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#include "jasper/jas_types.h"
+#include "jasper/jas_tvp.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_debug.h"
+
+#include "pnm_cod.h"
+#include "pnm_enc.h"
+
+/******************************************************************************\
+* Local types.
+\******************************************************************************/
+
+typedef struct {
+ bool bin;
+} pnm_encopts_t;
+
+typedef enum {
+ OPT_TEXT
+} pnm_optid_t;
+
+jas_taginfo_t pnm_opttab[] = {
+ {OPT_TEXT, "text"},
+ {-1, 0}
+};
+
+/******************************************************************************\
+* Local function prototypes.
+\******************************************************************************/
+
+static int pnm_parseencopts(char *optstr, pnm_encopts_t *encopts);
+static int pnm_puthdr(jas_stream_t *out, pnm_hdr_t *hdr);
+static int pnm_putdata(jas_stream_t *out, pnm_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts);
+
+static int pnm_putsint(jas_stream_t *out, int wordsize, int_fast32_t *val);
+static int pnm_putuint(jas_stream_t *out, int wordsize, uint_fast32_t *val);
+static int pnm_putuint16(jas_stream_t *out, uint_fast16_t val);
+
+/******************************************************************************\
+* Save function.
+\******************************************************************************/
+
+int pnm_encode(jas_image_t *image, jas_stream_t *out, char *optstr)
+{
+ int width;
+ int height;
+ int cmptno;
+ pnm_hdr_t hdr;
+ pnm_encopts_t encopts;
+ int prec;
+ int sgnd;
+ pnm_enc_t encbuf;
+ pnm_enc_t *enc = &encbuf;
+
+ /* Parse the encoder option string. */
+ if (pnm_parseencopts(optstr, &encopts)) {
+ jas_eprintf("invalid PNM encoder options specified\n");
+ return -1;
+ }
+
+ switch (jas_clrspc_fam(jas_image_clrspc(image))) {
+ case JAS_CLRSPC_FAM_RGB:
+ if (jas_image_clrspc(image) != JAS_CLRSPC_SRGB)
+ jas_eprintf("warning: inaccurate color\n");
+ enc->numcmpts = 3;
+ if ((enc->cmpts[0] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R))) < 0 ||
+ (enc->cmpts[1] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G))) < 0 ||
+ (enc->cmpts[2] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))) < 0) {
+ jas_eprintf("error: missing color component\n");
+ return -1;
+ }
+ break;
+ case JAS_CLRSPC_FAM_GRAY:
+ if (jas_image_clrspc(image) != JAS_CLRSPC_SGRAY)
+ jas_eprintf("warning: inaccurate color\n");
+ enc->numcmpts = 1;
+ if ((enc->cmpts[0] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y))) < 0) {
+ jas_eprintf("error: missing color component\n");
+ return -1;
+ }
+ break;
+ default:
+ jas_eprintf("error: unsupported color space\n");
+ return -1;
+ break;
+ }
+
+
+ width = jas_image_cmptwidth(image, enc->cmpts[0]);
+ height = jas_image_cmptheight(image, enc->cmpts[0]);
+ prec = jas_image_cmptprec(image, enc->cmpts[0]);
+ sgnd = jas_image_cmptsgnd(image, enc->cmpts[0]);
+
+ /* The PNM format is quite limited in the set of image geometries
+ that it can handle. Here, we check to ensure that the image to
+ be saved can actually be represented reasonably accurately using the
+ PNM format. */
+ /* All of the components must have the same width and height. */
+ /* All of the components must have unsigned samples with the same
+ precision.*/
+ /* All of the components must have their top-left corner located at
+ the origin. */
+ for (cmptno = 0; cmptno < enc->numcmpts; ++cmptno) {
+ if (jas_image_cmptwidth(image, enc->cmpts[cmptno]) != width ||
+ jas_image_cmptheight(image, enc->cmpts[cmptno]) != height ||
+ jas_image_cmptprec(image, enc->cmpts[cmptno]) != prec ||
+ jas_image_cmptsgnd(image, enc->cmpts[cmptno]) != sgnd ||
+ jas_image_cmpthstep(image, enc->cmpts[cmptno]) != jas_image_cmpthstep(image, 0) ||
+ jas_image_cmptvstep(image, enc->cmpts[cmptno]) != jas_image_cmptvstep(image, 0) ||
+ jas_image_cmpttlx(image, enc->cmpts[cmptno]) != jas_image_cmpttlx(image, 0) ||
+ jas_image_cmpttly(image, enc->cmpts[cmptno]) != jas_image_cmpttly(image, 0)) {
+ jas_eprintf("The PNM format cannot be used to represent an image with this geometry.\n");
+ return -1;
+ }
+ }
+
+ if (sgnd) {
+ jas_eprintf("warning: support for signed sample data requires use of nonstandard extension to PNM format\n");
+ jas_eprintf("You may not be able to read or correctly display the resulting PNM data with other software.\n");
+ }
+
+ /* Initialize the header. */
+ if (enc->numcmpts == 1) {
+ hdr.magic = encopts.bin ? PNM_MAGIC_BINPGM : PNM_MAGIC_TXTPGM;
+ } else if (enc->numcmpts == 3) {
+ hdr.magic = encopts.bin ? PNM_MAGIC_BINPPM : PNM_MAGIC_TXTPPM;
+ } else {
+ return -1;
+ }
+ hdr.width = width;
+ hdr.height = height;
+ hdr.maxval = (1 << prec) - 1;
+ hdr.sgnd = sgnd;
+
+ /* Write the header. */
+ if (pnm_puthdr(out, &hdr)) {
+ return -1;
+ }
+
+ /* Write the image data. */
+ if (pnm_putdata(out, &hdr, image, enc->numcmpts, enc->cmpts)) {
+ return -1;
+ }
+
+ /* Flush the output stream. */
+ if (jas_stream_flush(out)) {
+ return -1;
+ }
+
+ return 0;
+}
+
+/******************************************************************************\
+* Code for parsing options.
+\******************************************************************************/
+
+/* Parse the encoder options string. */
+static int pnm_parseencopts(char *optstr, pnm_encopts_t *encopts)
+{
+ jas_tvparser_t *tvp;
+ int ret;
+
+ tvp = 0;
+
+ /* Initialize default values for encoder options. */
+ encopts->bin = true;
+
+ /* Create the tag-value parser. */
+ if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
+ goto error;
+ }
+
+ /* Get tag-value pairs, and process as necessary. */
+ while (!(ret = jas_tvparser_next(tvp))) {
+ switch (jas_taginfo_nonull(jas_taginfos_lookup(pnm_opttab,
+ jas_tvparser_gettag(tvp)))->id) {
+ case OPT_TEXT:
+ encopts->bin = false;
+ break;
+ default:
+ jas_eprintf("warning: ignoring invalid option %s\n",
+ jas_tvparser_gettag(tvp));
+ break;
+ }
+ }
+ if (ret < 0) {
+ goto error;
+ }
+
+ /* Destroy the tag-value parser. */
+ jas_tvparser_destroy(tvp);
+
+ return 0;
+
+error:
+ if (tvp) {
+ jas_tvparser_destroy(tvp);
+ }
+ return -1;
+}
+
+/******************************************************************************\
+* Function for writing header.
+\******************************************************************************/
+
+/* Write the header. */
+static int pnm_puthdr(jas_stream_t *out, pnm_hdr_t *hdr)
+{
+ int_fast32_t maxval;
+
+ if (pnm_putuint16(out, hdr->magic)) {
+ return -1;
+ }
+ if (hdr->sgnd) {
+ maxval = -hdr->maxval;
+ } else {
+ maxval = hdr->maxval;
+ }
+ jas_stream_printf(out, "\n%lu %lu\n%ld\n", (unsigned long) hdr->width,
+ (unsigned long) hdr->height, (long) maxval);
+ if (jas_stream_error(out)) {
+ return -1;
+ }
+ return 0;
+}
+
+/******************************************************************************\
+* Functions for processing the sample data.
+\******************************************************************************/
+
+/* Write the image sample data. */
+static int pnm_putdata(jas_stream_t *out, pnm_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts)
+{
+ int ret;
+ int cmptno;
+ int x;
+ int y;
+ jas_matrix_t *data[3];
+ int fmt;
+ jas_seqent_t *d[3];
+ jas_seqent_t v;
+ int minval;
+ int linelen;
+ int n;
+ char buf[256];
+ int depth;
+
+ ret = -1;
+ fmt = pnm_fmt(hdr->magic);
+ minval = -((int) hdr->maxval + 1);
+ depth = pnm_maxvaltodepth(hdr->maxval);
+
+ data[0] = 0;
+ data[1] = 0;
+ data[2] = 0;
+ for (cmptno = 0; cmptno < numcmpts; ++cmptno) {
+ if (!(data[cmptno] = jas_matrix_create(1, hdr->width))) {
+ goto done;
+ }
+ }
+
+ for (y = 0; y < hdr->height; ++y) {
+ for (cmptno = 0; cmptno < numcmpts; ++cmptno) {
+ if (jas_image_readcmpt(image, cmpts[cmptno], 0, y, hdr->width, 1,
+ data[cmptno])) {
+ goto done;
+ }
+ d[cmptno] = jas_matrix_getref(data[cmptno], 0, 0);
+ }
+ linelen = 0;
+ for (x = 0; x < hdr->width; ++x) {
+ for (cmptno = 0; cmptno < numcmpts; ++cmptno) {
+ v = *d[cmptno];
+ if (v < minval) {
+ v = minval;
+ }
+ if (v > ((int) hdr->maxval)) {
+ v = hdr->maxval;
+ }
+ if (fmt == PNM_FMT_BIN) {
+ if (hdr->sgnd) {
+ int_fast32_t sv;
+ sv = v;
+ if (pnm_putsint(out, depth, &sv)) {
+ goto done;
+ }
+ } else {
+ uint_fast32_t uv;
+ uv = v;
+ if (pnm_putuint(out, depth, &uv)) {
+ goto done;
+ }
+ }
+ } else {
+ n = sprintf(buf, "%s%ld", ((!(!x && !cmptno)) ? " " : ""),
+ (long) v);
+ if (linelen > 0 && linelen + n > PNM_MAXLINELEN) {
+ jas_stream_printf(out, "\n");
+ linelen = 0;
+ }
+ jas_stream_printf(out, "%s", buf);
+ linelen += n;
+ }
+ ++d[cmptno];
+ }
+ }
+ if (fmt != PNM_FMT_BIN) {
+ jas_stream_printf(out, "\n");
+ linelen = 0;
+ }
+ if (jas_stream_error(out)) {
+ goto done;
+ }
+ }
+
+ ret = 0;
+
+done:
+
+ for (cmptno = 0; cmptno < numcmpts; ++cmptno) {
+ if (data[cmptno]) {
+ jas_matrix_destroy(data[cmptno]);
+ }
+ }
+
+ return ret;
+}
+
+/******************************************************************************\
+* Miscellaneous functions.
+\******************************************************************************/
+
+static int pnm_putsint(jas_stream_t *out, int wordsize, int_fast32_t *val)
+{
+ uint_fast32_t tmpval;
+ tmpval = (*val < 0) ?
+ ((~(JAS_CAST(uint_fast32_t, -(*val)) + 1)) & PNM_ONES(wordsize)) :
+ JAS_CAST(uint_fast32_t, (*val));
+ return pnm_putuint(out, wordsize, &tmpval);
+}
+
+static int pnm_putuint(jas_stream_t *out, int wordsize, uint_fast32_t *val)
+{
+ int n;
+ uint_fast32_t tmpval;
+ int c;
+
+ n = (wordsize + 7) / 8;
+ tmpval = (*val);
+ tmpval &= PNM_ONES(8 * n);
+ tmpval = tmpval << (8 * (4 - n));
+ while (--n >= 0) {
+ c = (tmpval >> 24) & 0xff;
+ if (jas_stream_putc(out, c) == EOF) {
+ return -1;
+ }
+ tmpval = (tmpval << 8) & 0xffffffff;
+ }
+ return 0;
+}
+
+/* Write a 16-bit unsigned integer to a stream. */
+static int pnm_putuint16(jas_stream_t *out, uint_fast16_t val)
+{
+ if (jas_stream_putc(out, (unsigned char)(val >> 8)) == EOF ||
+ jas_stream_putc(out, (unsigned char)(val & 0xff)) == EOF) {
+ return -1;
+ }
+ return 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_enc.h b/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_enc.h
new file mode 100644
index 0000000..6425e59
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/pnm/pnm_enc.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef PNM_ENC_H
+#define PNM_ENC_H
+
+typedef struct {
+ int numcmpts;
+ int cmpts[4];
+} pnm_enc_t;
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/ras/Makefile.am b/jasper-1.900.1-6ct/src/libjasper/ras/Makefile.am
new file mode 100644
index 0000000..49cfe4b
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/ras/Makefile.am
@@ -0,0 +1,67 @@
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+noinst_LTLIBRARIES = libras.la
+libras_la_SOURCES = \
+ ras_cod.h \
+ ras_enc.h \
+ ras_cod.c \
+ ras_dec.c \
+ ras_enc.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
diff --git a/jasper-1.900.1-6ct/src/libjasper/ras/Makefile.in b/jasper-1.900.1-6ct/src/libjasper/ras/Makefile.in
new file mode 100644
index 0000000..57b83f5
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/ras/Makefile.in
@@ -0,0 +1,510 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src/libjasper/ras
+DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+LTLIBRARIES = $(noinst_LTLIBRARIES)
+libras_la_LIBADD =
+am_libras_la_OBJECTS = ras_cod.lo ras_dec.lo ras_enc.lo
+libras_la_OBJECTS = $(am_libras_la_OBJECTS)
+DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)/src/libjasper/include/jasper
+depcomp = $(SHELL) $(top_srcdir)/acaux/depcomp
+am__depfiles_maybe = depfiles
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LTCOMPILE = $(LIBTOOL) --tag=CC --mode=compile $(CC) $(DEFS) \
+ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+ $(AM_CFLAGS) $(CFLAGS)
+CCLD = $(CC)
+LINK = $(LIBTOOL) --tag=CC --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
+ $(AM_LDFLAGS) $(LDFLAGS) -o $@
+SOURCES = $(libras_la_SOURCES)
+DIST_SOURCES = $(libras_la_SOURCES)
+ETAGS = etags
+CTAGS = ctags
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+noinst_LTLIBRARIES = libras.la
+libras_la_SOURCES = \
+ ras_cod.h \
+ ras_enc.h \
+ ras_cod.c \
+ ras_dec.c \
+ ras_enc.c
+
+INCLUDES = -I$(top_srcdir)/src/libjasper/include
+all: all-am
+
+.SUFFIXES:
+.SUFFIXES: .c .lo .o .obj
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libjasper/ras/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/libjasper/ras/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+clean-noinstLTLIBRARIES:
+ -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
+ @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \
+ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \
+ test "$$dir" != "$$p" || dir=.; \
+ echo "rm -f \"$${dir}/so_locations\""; \
+ rm -f "$${dir}/so_locations"; \
+ done
+libras.la: $(libras_la_OBJECTS) $(libras_la_DEPENDENCIES)
+ $(LINK) $(libras_la_LDFLAGS) $(libras_la_OBJECTS) $(libras_la_LIBADD) $(LIBS)
+
+mostlyclean-compile:
+ -rm -f *.$(OBJEXT)
+
+distclean-compile:
+ -rm -f *.tab.c
+
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ras_cod.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ras_dec.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ras_enc.Plo at am__quote@
+
+.c.o:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c $<
+
+.c.obj:
+ at am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'`
+
+.c.lo:
+ at am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ at am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $<
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-am
+all-am: Makefile $(LTLIBRARIES)
+installdirs:
+install: install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-am
+
+clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \
+ mostlyclean-am
+
+distclean: distclean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+distclean-am: clean-am distclean-compile distclean-generic \
+ distclean-libtool distclean-tags
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+info: info-am
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-am
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-compile mostlyclean-generic \
+ mostlyclean-libtool
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
+ clean-libtool clean-noinstLTLIBRARIES ctags distclean \
+ distclean-compile distclean-generic distclean-libtool \
+ distclean-tags distdir dvi dvi-am html html-am info info-am \
+ install install-am install-data install-data-am install-exec \
+ install-exec-am install-info install-info-am install-man \
+ install-strip installcheck installcheck-am installdirs \
+ maintainer-clean maintainer-clean-generic mostlyclean \
+ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
+ pdf pdf-am ps ps-am tags uninstall uninstall-am \
+ uninstall-info-am
+
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/libjasper/ras/ras_cod.c b/jasper-1.900.1-6ct/src/libjasper/ras/ras_cod.c
new file mode 100644
index 0000000..816c23b
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/ras/ras_cod.c
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Sun Rasterfile Library
+ *
+ * $Id$
+ */
+
+/* Note: There is not currently any code common to both the encoder and
+ decoder. */
+
+/* Keep picky compilers happy. */
+int ras_dummy;
diff --git a/jasper-1.900.1-6ct/src/libjasper/ras/ras_cod.h b/jasper-1.900.1-6ct/src/libjasper/ras/ras_cod.h
new file mode 100644
index 0000000..a8c53ba
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/ras/ras_cod.h
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Sun Rasterfile Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Sun Rasterfile
+\******************************************************************************/
+
+#ifndef RAS_COD_H
+#define RAS_COD_H
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include "jasper/jas_types.h"
+
+/******************************************************************************\
+* Constants.
+\******************************************************************************/
+
+#define RAS_MAGIC 0x59a66a95
+#define RAS_MAGICLEN 4
+
+#define RAS_TYPE_OLD 0
+#define RAS_TYPE_STD 1
+#define RAS_TYPE_RLE 2
+
+#define RAS_MT_NONE 0
+#define RAS_MT_EQUALRGB 1
+#define RAS_MT_RAW 2
+
+/******************************************************************************\
+* Types.
+\******************************************************************************/
+
+/* Sun Rasterfile header. */
+typedef struct {
+
+ int_fast32_t magic;
+ /* signature */
+
+ int_fast32_t width;
+ /* width of image (in pixels) */
+
+ int_fast32_t height;
+ /* height of image (in pixels) */
+
+ int_fast32_t depth;
+ /* number of bits per pixel */
+
+ int_fast32_t length;
+ /* length of image data (in bytes) */
+
+ int_fast32_t type;
+ /* format of image data */
+
+ int_fast32_t maptype;
+ /* colormap type */
+
+ int_fast32_t maplength;
+ /* length of colormap data (in bytes) */
+
+} ras_hdr_t;
+
+#define RAS_CMAP_MAXSIZ 256
+
+/* Color map. */
+typedef struct {
+
+ int len;
+ /* The number of entries in the color map. */
+
+ int data[RAS_CMAP_MAXSIZ];
+ /* The color map data. */
+
+} ras_cmap_t;
+
+/******************************************************************************\
+* Macros.
+\******************************************************************************/
+
+#define RAS_GETBLUE(x) (((x) >> 16) & 0xff)
+#define RAS_GETGREEN(x) (((x) >> 8) & 0xff)
+#define RAS_GETRED(x) ((x) & 0xff)
+
+#define RAS_BLUE(x) (((x) & 0xff) << 16)
+#define RAS_GREEN(x) (((x) & 0xff) << 8)
+#define RAS_RED(x) ((x) & 0xff)
+
+#define RAS_ROWSIZE(hdr) \
+ ((((hdr)->width * (hdr)->depth + 15) / 16) * 2)
+#define RAS_ISRGB(hdr) \
+ ((hdr)->depth == 24 || (hdr)->depth == 32)
+
+#define RAS_ONES(n) \
+ (((n) == 32) ? 0xffffffffUL : ((1UL << (n)) - 1))
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/libjasper/ras/ras_dec.c b/jasper-1.900.1-6ct/src/libjasper/ras/ras_dec.c
new file mode 100644
index 0000000..a53da8b
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/ras/ras_dec.c
@@ -0,0 +1,398 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Sun Rasterfile Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include "jasper/jas_stream.h"
+#include "jasper/jas_image.h"
+#include "jasper/jas_debug.h"
+
+#include "ras_cod.h"
+
+/******************************************************************************\
+* Prototypes.
+\******************************************************************************/
+
+static int ras_gethdr(jas_stream_t *in, ras_hdr_t *hdr);
+static int ras_getint(jas_stream_t *in, int_fast32_t *val);
+
+static int ras_getdata(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap,
+ jas_image_t *image);
+static int ras_getdatastd(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap,
+ jas_image_t *image);
+static int ras_getcmap(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap);
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+jas_image_t *ras_decode(jas_stream_t *in, char *optstr)
+{
+ ras_hdr_t hdr;
+ ras_cmap_t cmap;
+ jas_image_t *image;
+ jas_image_cmptparm_t cmptparms[3];
+ jas_image_cmptparm_t *cmptparm;
+ int clrspc;
+ int numcmpts;
+ int i;
+
+ if (optstr) {
+ jas_eprintf("warning: ignoring RAS decoder options\n");
+ }
+
+ /* Read the header. */
+ if (ras_gethdr(in, &hdr)) {
+ return 0;
+ }
+
+ /* Does the header information look reasonably sane? */
+ if (hdr.magic != RAS_MAGIC || hdr.width <= 0 || hdr.height <= 0 ||
+ hdr.depth <= 0 || hdr.depth > 32) {
+ return 0;
+ }
+
+ /* In the case of the old format, do not rely on the length field
+ being properly specified. Calculate the quantity from scratch. */
+ if (hdr.type == RAS_TYPE_OLD) {
+ hdr.length = RAS_ROWSIZE(&hdr) * hdr.height;
+ }
+
+ /* Calculate some quantities needed for creation of the image
+ object. */
+ if (RAS_ISRGB(&hdr)) {
+ clrspc = JAS_CLRSPC_SRGB;
+ numcmpts = 3;
+ } else {
+ clrspc = JAS_CLRSPC_SGRAY;
+ numcmpts = 1;
+ }
+ for (i = 0, cmptparm = cmptparms; i < numcmpts; ++i, ++cmptparm) {
+ cmptparm->tlx = 0;
+ cmptparm->tly = 0;
+ cmptparm->hstep = 1;
+ cmptparm->vstep = 1;
+ cmptparm->width = hdr.width;
+ cmptparm->height = hdr.height;
+ cmptparm->prec = RAS_ISRGB(&hdr) ? 8 : hdr.depth;
+ cmptparm->sgnd = false;
+ }
+ /* Create the image object. */
+ if (!(image = jas_image_create(numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) {
+ return 0;
+ }
+
+ /* Read the color map (if there is one). */
+ if (ras_getcmap(in, &hdr, &cmap)) {
+ jas_image_destroy(image);
+ return 0;
+ }
+
+ /* Read the pixel data. */
+ if (ras_getdata(in, &hdr, &cmap, image)) {
+ jas_image_destroy(image);
+ return 0;
+ }
+
+ jas_image_setclrspc(image, clrspc);
+ if (clrspc == JAS_CLRSPC_SRGB) {
+ jas_image_setcmpttype(image, 0,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
+ jas_image_setcmpttype(image, 1,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
+ jas_image_setcmpttype(image, 2,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
+ } else {
+ jas_image_setcmpttype(image, 0,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
+ }
+
+ return image;
+}
+
+int ras_validate(jas_stream_t *in)
+{
+ uchar buf[RAS_MAGICLEN];
+ int i;
+ int n;
+ uint_fast32_t magic;
+
+ assert(JAS_STREAM_MAXPUTBACK >= RAS_MAGICLEN);
+
+ /* Read the validation data (i.e., the data used for detecting
+ the format). */
+ if ((n = jas_stream_read(in, buf, RAS_MAGICLEN)) < 0) {
+ return -1;
+ }
+
+ /* Put the validation data back onto the stream, so that the
+ stream position will not be changed. */
+ for (i = n - 1; i >= 0; --i) {
+ if (jas_stream_ungetc(in, buf[i]) == EOF) {
+ return -1;
+ }
+ }
+
+ /* Did we read enough data? */
+ if (n < RAS_MAGICLEN) {
+ return -1;
+ }
+
+ magic = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
+
+ /* Is the signature correct for the Sun Rasterfile format? */
+ if (magic != RAS_MAGIC) {
+ return -1;
+ }
+ return 0;
+}
+
+static int ras_getdata(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap,
+ jas_image_t *image)
+{
+ int ret;
+
+ switch (hdr->type) {
+ case RAS_TYPE_OLD:
+ case RAS_TYPE_STD:
+ ret = ras_getdatastd(in, hdr, cmap, image);
+ break;
+ case RAS_TYPE_RLE:
+ jas_eprintf("error: RLE encoding method not supported\n");
+ ret = -1;
+ break;
+ default:
+ jas_eprintf("error: encoding method not supported\n");
+ ret = -1;
+ break;
+ }
+ return ret;
+}
+
+static int ras_getdatastd(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap,
+ jas_image_t *image)
+{
+ int pad;
+ int nz;
+ int z;
+ int c;
+ int y;
+ int x;
+ int v;
+ int i;
+ jas_matrix_t *data[3];
+
+/* Note: This function does not properly handle images with a colormap. */
+ /* Avoid compiler warnings about unused parameters. */
+ cmap = 0;
+
+ for (i = 0; i < jas_image_numcmpts(image); ++i) {
+ data[i] = jas_matrix_create(1, jas_image_width(image));
+ assert(data[i]);
+ }
+
+ pad = RAS_ROWSIZE(hdr) - (hdr->width * hdr->depth + 7) / 8;
+
+ for (y = 0; y < hdr->height; y++) {
+ nz = 0;
+ z = 0;
+ for (x = 0; x < hdr->width; x++) {
+ while (nz < hdr->depth) {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ z = (z << 8) | c;
+ nz += 8;
+ }
+
+ v = (z >> (nz - hdr->depth)) & RAS_ONES(hdr->depth);
+ z &= RAS_ONES(nz - hdr->depth);
+ nz -= hdr->depth;
+
+ if (jas_image_numcmpts(image) == 3) {
+ jas_matrix_setv(data[0], x, (RAS_GETRED(v)));
+ jas_matrix_setv(data[1], x, (RAS_GETGREEN(v)));
+ jas_matrix_setv(data[2], x, (RAS_GETBLUE(v)));
+ } else {
+ jas_matrix_setv(data[0], x, (v));
+ }
+ }
+ if (pad) {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ }
+ for (i = 0; i < jas_image_numcmpts(image); ++i) {
+ if (jas_image_writecmpt(image, i, 0, y, hdr->width, 1,
+ data[i])) {
+ return -1;
+ }
+ }
+ }
+
+ for (i = 0; i < jas_image_numcmpts(image); ++i) {
+ jas_matrix_destroy(data[i]);
+ }
+
+ return 0;
+}
+
+static int ras_getcmap(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap)
+{
+ int i;
+ int j;
+ int x;
+ int c;
+ int numcolors;
+ int actualnumcolors;
+
+ switch (hdr->maptype) {
+ case RAS_MT_NONE:
+ break;
+ case RAS_MT_EQUALRGB:
+ {
+ jas_eprintf("warning: palettized images not fully supported\n");
+ numcolors = 1 << hdr->depth;
+ assert(numcolors <= RAS_CMAP_MAXSIZ);
+ actualnumcolors = hdr->maplength / 3;
+ for (i = 0; i < numcolors; i++) {
+ cmap->data[i] = 0;
+ }
+ if ((hdr->maplength % 3) || hdr->maplength < 0 ||
+ hdr->maplength > 3 * numcolors) {
+ return -1;
+ }
+ for (i = 0; i < 3; i++) {
+ for (j = 0; j < actualnumcolors; j++) {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ x = 0;
+ switch (i) {
+ case 0:
+ x = RAS_RED(c);
+ break;
+ case 1:
+ x = RAS_GREEN(c);
+ break;
+ case 2:
+ x = RAS_BLUE(c);
+ break;
+ }
+ cmap->data[j] |= x;
+ }
+ }
+ }
+ break;
+ default:
+ return -1;
+ break;
+ }
+
+ return 0;
+}
+
+static int ras_gethdr(jas_stream_t *in, ras_hdr_t *hdr)
+{
+ if (ras_getint(in, &hdr->magic) || ras_getint(in, &hdr->width) ||
+ ras_getint(in, &hdr->height) || ras_getint(in, &hdr->depth) ||
+ ras_getint(in, &hdr->length) || ras_getint(in, &hdr->type) ||
+ ras_getint(in, &hdr->maptype) || ras_getint(in, &hdr->maplength)) {
+ return -1;
+ }
+
+ if (hdr->magic != RAS_MAGIC) {
+ return -1;
+ }
+
+ return 0;
+}
+
+static int ras_getint(jas_stream_t *in, int_fast32_t *val)
+{
+ int x;
+ int c;
+ int i;
+
+ x = 0;
+ for (i = 0; i < 4; i++) {
+ if ((c = jas_stream_getc(in)) == EOF) {
+ return -1;
+ }
+ x = (x << 8) | (c & 0xff);
+ }
+
+ *val = x;
+ return 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/ras/ras_enc.c b/jasper-1.900.1-6ct/src/libjasper/ras/ras_enc.c
new file mode 100644
index 0000000..21e7fcb
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/ras/ras_enc.c
@@ -0,0 +1,318 @@
+/*
+ * Copyright (c) 1999-2000 Image Power, Inc. and the University of
+ * British Columbia.
+ * Copyright (c) 2001-2003 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+/*
+ * Sun Rasterfile Library
+ *
+ * $Id$
+ */
+
+/******************************************************************************\
+* Includes.
+\******************************************************************************/
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include "jasper/jas_image.h"
+#include "jasper/jas_stream.h"
+#include "jasper/jas_debug.h"
+
+#include "ras_cod.h"
+#include "ras_enc.h"
+
+/******************************************************************************\
+* Prototypes.
+\******************************************************************************/
+
+static int ras_puthdr(jas_stream_t *out, ras_hdr_t *hdr);
+static int ras_putint(jas_stream_t *out, int val);
+
+static int ras_putdata(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts);
+static int ras_putdatastd(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts);
+
+/******************************************************************************\
+* Code.
+\******************************************************************************/
+
+int ras_encode(jas_image_t *image, jas_stream_t *out, char *optstr)
+{
+ int_fast32_t width;
+ int_fast32_t height;
+ int_fast32_t depth;
+ int cmptno;
+#if 0
+ uint_fast16_t numcmpts;
+#endif
+ int i;
+ ras_hdr_t hdr;
+ int rowsize;
+ ras_enc_t encbuf;
+ ras_enc_t *enc = &encbuf;
+
+ if (optstr) {
+ jas_eprintf("warning: ignoring RAS encoder options\n");
+ }
+
+ switch (jas_clrspc_fam(jas_image_clrspc(image))) {
+ case JAS_CLRSPC_FAM_RGB:
+ if (jas_image_clrspc(image) != JAS_CLRSPC_SRGB)
+ jas_eprintf("warning: inaccurate color\n");
+ enc->numcmpts = 3;
+ if ((enc->cmpts[0] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R))) < 0 ||
+ (enc->cmpts[1] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G))) < 0 ||
+ (enc->cmpts[2] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))) < 0) {
+ jas_eprintf("error: missing color component\n");
+ return -1;
+ }
+ break;
+ case JAS_CLRSPC_FAM_GRAY:
+ if (jas_image_clrspc(image) != JAS_CLRSPC_SGRAY)
+ jas_eprintf("warning: inaccurate color\n");
+ enc->numcmpts = 1;
+ if ((enc->cmpts[0] = jas_image_getcmptbytype(image,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y))) < 0) {
+ jas_eprintf("error: missing color component\n");
+ return -1;
+ }
+ break;
+ default:
+ jas_eprintf("error: unsupported color space\n");
+ return -1;
+ break;
+ }
+
+ width = jas_image_cmptwidth(image, enc->cmpts[0]);
+ height = jas_image_cmptheight(image, enc->cmpts[0]);
+ depth = jas_image_cmptprec(image, enc->cmpts[0]);
+
+ for (cmptno = 0; cmptno < enc->numcmpts; ++cmptno) {
+ if (jas_image_cmptwidth(image, enc->cmpts[cmptno]) != width ||
+ jas_image_cmptheight(image, enc->cmpts[cmptno]) != height ||
+ jas_image_cmptprec(image, enc->cmpts[cmptno]) != depth ||
+ jas_image_cmptsgnd(image, enc->cmpts[cmptno]) != false ||
+ jas_image_cmpttlx(image, enc->cmpts[cmptno]) != 0 ||
+ jas_image_cmpttly(image, enc->cmpts[cmptno]) != 0) {
+ jas_eprintf("The RAS format cannot be used to represent an image with this geometry.\n");
+ return -1;
+ }
+ }
+
+ /* Ensure that the image can be encoded in the desired format. */
+ if (enc->numcmpts == 3) {
+
+ /* All three components must have the same subsampling
+ factor and have a precision of eight bits. */
+ if (enc->numcmpts > 1) {
+ for (i = 0; i < enc->numcmpts; ++i) {
+ if (jas_image_cmptprec(image, enc->cmpts[i]) != 8) {
+ return -1;
+ }
+ }
+ }
+ } else if (enc->numcmpts == 1) {
+ /* NOP */
+ } else {
+ return -1;
+ }
+
+ hdr.magic = RAS_MAGIC;
+ hdr.width = width;
+ hdr.height = height;
+ hdr.depth = (enc->numcmpts == 3) ? 24 : depth;
+
+ rowsize = RAS_ROWSIZE(&hdr);
+ hdr.length = rowsize * hdr.height;
+ hdr.type = RAS_TYPE_STD;
+
+ hdr.maptype = RAS_MT_NONE;
+ hdr.maplength = 0;
+
+ if (ras_puthdr(out, &hdr)) {
+ return -1;
+ }
+
+ if (ras_putdata(out, &hdr, image, enc->numcmpts, enc->cmpts)) {
+ return -1;
+ }
+
+ return 0;
+}
+
+static int ras_putdata(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts)
+{
+ int ret;
+
+ switch (hdr->type) {
+ case RAS_TYPE_STD:
+ ret = ras_putdatastd(out, hdr, image, numcmpts, cmpts);
+ break;
+ default:
+ ret = -1;
+ break;
+ }
+ return ret;
+}
+
+static int ras_putdatastd(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts)
+{
+ int rowsize;
+ int pad;
+ unsigned int z;
+ int nz;
+ int c;
+ int x;
+ int y;
+ int v;
+ jas_matrix_t *data[3];
+ int i;
+
+ for (i = 0; i < numcmpts; ++i) {
+ data[i] = jas_matrix_create(jas_image_height(image), jas_image_width(image));
+ assert(data[i]);
+ }
+
+ rowsize = RAS_ROWSIZE(hdr);
+ pad = rowsize - (hdr->width * hdr->depth + 7) / 8;
+
+ hdr->length = hdr->height * rowsize;
+
+ for (y = 0; y < hdr->height; y++) {
+ for (i = 0; i < numcmpts; ++i) {
+ jas_image_readcmpt(image, cmpts[i], 0, y, jas_image_width(image),
+ 1, data[i]);
+ }
+ z = 0;
+ nz = 0;
+ for (x = 0; x < hdr->width; x++) {
+ z <<= hdr->depth;
+ if (RAS_ISRGB(hdr)) {
+ v = RAS_RED((jas_matrix_getv(data[0], x))) |
+ RAS_GREEN((jas_matrix_getv(data[1], x))) |
+ RAS_BLUE((jas_matrix_getv(data[2], x)));
+ } else {
+ v = (jas_matrix_getv(data[0], x));
+ }
+ z |= v & RAS_ONES(hdr->depth);
+ nz += hdr->depth;
+ while (nz >= 8) {
+ c = (z >> (nz - 8)) & 0xff;
+ if (jas_stream_putc(out, c) == EOF) {
+ return -1;
+ }
+ nz -= 8;
+ z &= RAS_ONES(nz);
+ }
+ }
+ if (nz > 0) {
+ c = (z >> (8 - nz)) & RAS_ONES(nz);
+ if (jas_stream_putc(out, c) == EOF) {
+ return -1;
+ }
+ }
+ if (pad % 2) {
+ if (jas_stream_putc(out, 0) == EOF) {
+ return -1;
+ }
+ }
+ }
+
+ for (i = 0; i < numcmpts; ++i) {
+ jas_matrix_destroy(data[i]);
+ }
+
+ return 0;
+}
+
+static int ras_puthdr(jas_stream_t *out, ras_hdr_t *hdr)
+{
+ if (ras_putint(out, RAS_MAGIC) || ras_putint(out, hdr->width) ||
+ ras_putint(out, hdr->height) || ras_putint(out, hdr->depth) ||
+ ras_putint(out, hdr->length) || ras_putint(out, hdr->type) ||
+ ras_putint(out, hdr->maptype) || ras_putint(out, hdr->maplength)) {
+ return -1;
+ }
+
+ return 0;
+}
+
+static int ras_putint(jas_stream_t *out, int val)
+{
+ int x;
+ int i;
+ int c;
+
+ x = val;
+ for (i = 0; i < 4; i++) {
+ c = (x >> 24) & 0xff;
+ if (jas_stream_putc(out, c) == EOF) {
+ return -1;
+ }
+ x <<= 8;
+ }
+
+ return 0;
+}
diff --git a/jasper-1.900.1-6ct/src/libjasper/ras/ras_enc.h b/jasper-1.900.1-6ct/src/libjasper/ras/ras_enc.h
new file mode 100644
index 0000000..bf5fe1b
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/libjasper/ras/ras_enc.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2002 Michael David Adams.
+ * All rights reserved.
+ */
+
+/* __START_OF_JASPER_LICENSE__
+ *
+ * JasPer License Version 2.0
+ *
+ * Copyright (c) 2001-2006 Michael David Adams
+ * Copyright (c) 1999-2000 Image Power, Inc.
+ * Copyright (c) 1999-2000 The University of British Columbia
+ *
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person (the
+ * "User") obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, and/or sell copies of the Software, and to permit
+ * persons to whom the Software is furnished to do so, subject to the
+ * following conditions:
+ *
+ * 1. The above copyright notices and this permission notice (which
+ * includes the disclaimer below) shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * 2. The name of a copyright holder shall not be used to endorse or
+ * promote products derived from the Software without specific prior
+ * written permission.
+ *
+ * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+ * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+ * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+ * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+ * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+ * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+ * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+ * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+ * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+ * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+ * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+ * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+ * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+ * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+ * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+ * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+ * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+ * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+ * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+ * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+ * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+ * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+ * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+ *
+ * __END_OF_JASPER_LICENSE__
+ */
+
+#ifndef RAS_ENC_H
+#define RAS_ENC_H
+
+typedef struct {
+ int numcmpts;
+ int cmpts[4];
+} ras_enc_t;
+
+#endif
diff --git a/jasper-1.900.1-6ct/src/msvc/Makefile.am b/jasper-1.900.1-6ct/src/msvc/Makefile.am
new file mode 100644
index 0000000..f3160a5
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/Makefile.am
@@ -0,0 +1,71 @@
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+
+EXTRA_DIST = \
+ README \
+ jasper.dsw \
+ libjasper.dsp \
+ jasper.dsp \
+ jiv.dsp \
+ imgcmp.dsp \
+ imginfo.dsp
+
+clean-local:
+ rm -rf *Win32_Debug *Win32_Release
+ rm -rf Release Debug
+ rm -rf *.ncb *.opt *.plg
diff --git a/jasper-1.900.1-6ct/src/msvc/Makefile.in b/jasper-1.900.1-6ct/src/msvc/Makefile.in
new file mode 100644
index 0000000..8884b22
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/Makefile.in
@@ -0,0 +1,405 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# @configure_input@
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+ at SET_MAKE@
+
+# Copyright (c) 2001-2002 Michael David Adams.
+# All rights reserved.
+
+# __START_OF_JASPER_LICENSE__
+#
+# JasPer License Version 2.0
+#
+# Copyright (c) 2001-2006 Michael David Adams
+# Copyright (c) 1999-2000 Image Power, Inc.
+# Copyright (c) 1999-2000 The University of British Columbia
+#
+# All rights reserved.
+#
+# Permission is hereby granted, free of charge, to any person (the
+# "User") obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the
+# following conditions:
+#
+# 1. The above copyright notices and this permission notice (which
+# includes the disclaimer below) shall be included in all copies or
+# substantial portions of the Software.
+#
+# 2. The name of a copyright holder shall not be used to endorse or
+# promote products derived from the Software without specific prior
+# written permission.
+#
+# THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
+# LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
+# THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+# "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
+# EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+# INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
+# PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
+# THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
+# EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
+# BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
+# PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
+# GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
+# ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
+# IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
+# SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
+# AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
+# SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
+# THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
+# PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
+# RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
+# EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
+#
+# __END_OF_JASPER_LICENSE__
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+pkgdatadir = $(datadir)/@PACKAGE@
+pkglibdir = $(libdir)/@PACKAGE@
+pkgincludedir = $(includedir)/@PACKAGE@
+top_builddir = ../..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = @INSTALL@
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+build_triplet = @build@
+host_triplet = @host@
+target_triplet = @target@
+subdir = src/msvc
+DIST_COMMON = README $(srcdir)/Makefile.am $(srcdir)/Makefile.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(SHELL) $(top_srcdir)/acaux/mkinstalldirs
+CONFIG_HEADER = \
+ $(top_builddir)/src/libjasper/include/jasper/jas_config.h
+CONFIG_CLEAN_FILES =
+SOURCES =
+DIST_SOURCES =
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = @ACLOCAL@
+AMDEP_FALSE = @AMDEP_FALSE@
+AMDEP_TRUE = @AMDEP_TRUE@
+AMTAR = @AMTAR@
+AR = @AR@
+AUTOCONF = @AUTOCONF@
+AUTOHEADER = @AUTOHEADER@
+AUTOMAKE = @AUTOMAKE@
+AWK = @AWK@
+CC = @CC@
+CCDEPMODE = @CCDEPMODE@
+CFLAGS = @CFLAGS@
+CPP = @CPP@
+CPPFLAGS = @CPPFLAGS@
+CXX = @CXX@
+CXXCPP = @CXXCPP@
+CXXDEPMODE = @CXXDEPMODE@
+CXXFLAGS = @CXXFLAGS@
+CYGPATH_W = @CYGPATH_W@
+DEFS = @DEFS@
+DEPDIR = @DEPDIR@
+ECHO = @ECHO@
+ECHO_C = @ECHO_C@
+ECHO_N = @ECHO_N@
+ECHO_T = @ECHO_T@
+EGREP = @EGREP@
+EXEEXT = @EXEEXT@
+F77 = @F77@
+FFLAGS = @FFLAGS@
+HAVE_LIBJPEG_FALSE = @HAVE_LIBJPEG_FALSE@
+HAVE_LIBJPEG_TRUE = @HAVE_LIBJPEG_TRUE@
+HAVE_OPENGL_FALSE = @HAVE_OPENGL_FALSE@
+HAVE_OPENGL_TRUE = @HAVE_OPENGL_TRUE@
+INSTALL_DATA = @INSTALL_DATA@
+INSTALL_PROGRAM = @INSTALL_PROGRAM@
+INSTALL_SCRIPT = @INSTALL_SCRIPT@
+INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
+JAS_MAJOR_VERSION = @JAS_MAJOR_VERSION@
+JAS_MICRO_VERSION = @JAS_MICRO_VERSION@
+JAS_MINOR_VERSION = @JAS_MINOR_VERSION@
+JAS_RPM_RELEASE = @JAS_RPM_RELEASE@
+JAS_VERSION = @JAS_VERSION@
+LDFLAGS = @LDFLAGS@
+LIBOBJS = @LIBOBJS@
+LIBS = @LIBS@
+LIBTOOL = @LIBTOOL@
+LN_S = @LN_S@
+LTLIBOBJS = @LTLIBOBJS@
+LT_AGE = @LT_AGE@
+LT_CURRENT = @LT_CURRENT@
+LT_RELEASE = @LT_RELEASE@
+LT_REVISION = @LT_REVISION@
+MAKEINFO = @MAKEINFO@
+OBJEXT = @OBJEXT@
+OPENGL_LIBS = @OPENGL_LIBS@
+PACKAGE = @PACKAGE@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+PACKAGE_NAME = @PACKAGE_NAME@
+PACKAGE_STRING = @PACKAGE_STRING@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PATH_SEPARATOR = @PATH_SEPARATOR@
+RANLIB = @RANLIB@
+SED = @SED@
+SET_MAKE = @SET_MAKE@
+SHELL = @SHELL@
+STRIP = @STRIP@
+VERSION = @VERSION@
+X_CFLAGS = @X_CFLAGS@
+X_EXTRA_LIBS = @X_EXTRA_LIBS@
+X_LIBS = @X_LIBS@
+X_PRE_LIBS = @X_PRE_LIBS@
+ac_ct_AR = @ac_ct_AR@
+ac_ct_CC = @ac_ct_CC@
+ac_ct_CXX = @ac_ct_CXX@
+ac_ct_F77 = @ac_ct_F77@
+ac_ct_RANLIB = @ac_ct_RANLIB@
+ac_ct_STRIP = @ac_ct_STRIP@
+am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
+am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
+am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
+am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
+am__include = @am__include@
+am__leading_dot = @am__leading_dot@
+am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
+bindir = @bindir@
+build = @build@
+build_alias = @build_alias@
+build_cpu = @build_cpu@
+build_os = @build_os@
+build_vendor = @build_vendor@
+datadir = @datadir@
+exec_prefix = @exec_prefix@
+host = @host@
+host_alias = @host_alias@
+host_cpu = @host_cpu@
+host_os = @host_os@
+host_vendor = @host_vendor@
+includedir = @includedir@
+infodir = @infodir@
+install_sh = @install_sh@
+libdir = @libdir@
+libexecdir = @libexecdir@
+localstatedir = @localstatedir@
+mandir = @mandir@
+mkdir_p = @mkdir_p@
+oldincludedir = @oldincludedir@
+prefix = @prefix@
+program_transform_name = @program_transform_name@
+sbindir = @sbindir@
+sharedstatedir = @sharedstatedir@
+sysconfdir = @sysconfdir@
+target = @target@
+target_alias = @target_alias@
+target_cpu = @target_cpu@
+target_os = @target_os@
+target_vendor = @target_vendor@
+EXTRA_DIST = \
+ README \
+ jasper.dsw \
+ libjasper.dsp \
+ jasper.dsp \
+ jiv.dsp \
+ imgcmp.dsp \
+ imginfo.dsp
+
+all: all-am
+
+.SUFFIXES:
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/msvc/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --foreign src/msvc/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+mostlyclean-libtool:
+ -rm -f *.lo
+
+clean-libtool:
+ -rm -rf .libs _libs
+
+distclean-libtool:
+ -rm -f libtool
+uninstall-info-am:
+tags: TAGS
+TAGS:
+
+ctags: CTAGS
+CTAGS:
+
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-am
+all-am: Makefile
+installdirs:
+install: install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-am
+
+clean-am: clean-generic clean-libtool clean-local mostlyclean-am
+
+distclean: distclean-am
+ -rm -f Makefile
+distclean-am: clean-am distclean-generic distclean-libtool
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+info: info-am
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-am
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-generic mostlyclean-libtool
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+.PHONY: all all-am check check-am clean clean-generic clean-libtool \
+ clean-local distclean distclean-generic distclean-libtool \
+ distdir dvi dvi-am html html-am info info-am install \
+ install-am install-data install-data-am install-exec \
+ install-exec-am install-info install-info-am install-man \
+ install-strip installcheck installcheck-am installdirs \
+ maintainer-clean maintainer-clean-generic mostlyclean \
+ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
+ uninstall uninstall-am uninstall-info-am
+
+
+clean-local:
+ rm -rf *Win32_Debug *Win32_Release
+ rm -rf Release Debug
+ rm -rf *.ncb *.opt *.plg
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/jasper-1.900.1-6ct/src/msvc/README b/jasper-1.900.1-6ct/src/msvc/README
new file mode 100644
index 0000000..d0b9884
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/README
@@ -0,0 +1,2 @@
+This directory contains the workspace and project files necessary to
+build JasPer under Windows using MS Visual C Studio.
diff --git a/jasper-1.900.1-6ct/src/msvc/imgcmp.dsp b/jasper-1.900.1-6ct/src/msvc/imgcmp.dsp
new file mode 100644
index 0000000..4d0c53d
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/imgcmp.dsp
@@ -0,0 +1,100 @@
+# Microsoft Developer Studio Project File - Name="imgcmp" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 6.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Console Application" 0x0103
+
+CFG=imgcmp - Win32 Debug
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "imgcmp.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "imgcmp.mak" CFG="imgcmp - Win32 Debug"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "imgcmp - Win32 Release" (based on "Win32 (x86) Console Application")
+!MESSAGE "imgcmp - Win32 Debug" (based on "Win32 (x86) Console Application")
+!MESSAGE
+
+# Begin Project
+# PROP AllowPerConfigDependencies 0
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "imgcmp - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "imgcmp___Win32_Release"
+# PROP BASE Intermediate_Dir "imgcmp___Win32_Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "Win32_Release"
+# PROP Intermediate_Dir "imgcmp___Win32_Release"
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
+# ADD CPP /nologo /W3 /GX /O2 /I "..\libjasper\include" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "JAS_WIN_MSVC_BUILD" /YX /FD /c
+# ADD BASE RSC /l 0x409 /d "NDEBUG"
+# ADD RSC /l 0x409 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libjasper.lib /nologo /subsystem:console /machine:I386 /libpath:"Win32_Release"
+
+!ELSEIF "$(CFG)" == "imgcmp - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "imgcmp___Win32_Debug"
+# PROP BASE Intermediate_Dir "imgcmp___Win32_Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "Win32_Debug"
+# PROP Intermediate_Dir "imgcmp___Win32_Debug"
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
+# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "..\libjasper\include" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "JAS_WIN_MSVC_BUILD" /YX /FD /GZ /c
+# ADD BASE RSC /l 0x409 /d "_DEBUG"
+# ADD RSC /l 0x409 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libjasper.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"Win32_Debug"
+
+!ENDIF
+
+# Begin Target
+
+# Name "imgcmp - Win32 Release"
+# Name "imgcmp - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+# Begin Source File
+
+SOURCE=..\appl\imgcmp.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl"
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
diff --git a/jasper-1.900.1-6ct/src/msvc/imgcmp.vcproj b/jasper-1.900.1-6ct/src/msvc/imgcmp.vcproj
new file mode 100644
index 0000000..aa284e0
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/imgcmp.vcproj
@@ -0,0 +1,344 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="9.00"
+ Name="imgcmp"
+ ProjectGUID="{08D097E0-4FF1-42F3-9C4C-12C70519B42B}"
+ TargetFrameworkVersion="0"
+ >
+ <Platforms>
+ <Platform
+ Name="Win32"
+ />
+ </Platforms>
+ <ToolFiles>
+ </ToolFiles>
+ <Configurations>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Win32_Debug"
+ IntermediateDirectory=".\imgcmp___Win32_Debug"
+ ConfigurationType="1"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Win32_Debug/imgcmp.tlb"
+ HeaderFileName=""
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="_DEBUG;WIN32;_CONSOLE;JAS_WIN_MSVC_BUILD"
+ MinimalRebuild="true"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ PrecompiledHeaderFile=".\imgcmp___Win32_Debug/imgcmp.pch"
+ AssemblerListingLocation=".\imgcmp___Win32_Debug/"
+ ObjectFile=".\imgcmp___Win32_Debug/"
+ ProgramDataBaseFileName=".\imgcmp___Win32_Debug/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ DebugInformationFormat="4"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib libjasper.lib"
+ OutputFile=".\Win32_Debug/imgcmp.exe"
+ LinkIncremental="2"
+ SuppressStartupBanner="true"
+ AdditionalLibraryDirectories="Win32_Debug"
+ GenerateDebugInformation="true"
+ ProgramDatabaseFile=".\Win32_Debug/imgcmp.pdb"
+ SubSystem="1"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Debug/imgcmp.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Win32_Release"
+ IntermediateDirectory=".\imgcmp___Win32_Release"
+ ConfigurationType="1"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Win32_Release/imgcmp.tlb"
+ HeaderFileName=""
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="NDEBUG;WIN32;_CONSOLE;JAS_WIN_MSVC_BUILD"
+ StringPooling="true"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="true"
+ PrecompiledHeaderFile=".\imgcmp___Win32_Release/imgcmp.pch"
+ AssemblerListingLocation=".\imgcmp___Win32_Release/"
+ ObjectFile=".\imgcmp___Win32_Release/"
+ ProgramDataBaseFileName=".\imgcmp___Win32_Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib libjasper.lib"
+ OutputFile=".\Win32_Release/imgcmp.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="true"
+ AdditionalLibraryDirectories="Win32_Release"
+ ProgramDatabaseFile=".\Win32_Release/imgcmp.pdb"
+ SubSystem="1"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Release/imgcmp.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Release64|Win32"
+ OutputDirectory="$(ConfigurationName)"
+ IntermediateDirectory="$(ConfigurationName)"
+ ConfigurationType="1"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Win32_Release/imgcmp.tlb"
+ HeaderFileName=""
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="NDEBUG;WIN32;_CONSOLE;JAS_WIN_MSVC_BUILD"
+ StringPooling="true"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="true"
+ PrecompiledHeaderFile=".\imgcmp___Win32_Release/imgcmp.pch"
+ AssemblerListingLocation=".\imgcmp___Win32_Release/"
+ ObjectFile=".\imgcmp___Win32_Release/"
+ ProgramDataBaseFileName=".\imgcmp___Win32_Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib libjasper.lib"
+ OutputFile=".\Win32_Release/imgcmp.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="true"
+ AdditionalLibraryDirectories="Win32_Release"
+ ProgramDatabaseFile=".\Win32_Release/imgcmp.pdb"
+ SubSystem="1"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Release/imgcmp.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+ >
+ <File
+ RelativePath="..\appl\imgcmp.c"
+ >
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl"
+ >
+ </Filter>
+ <Filter
+ Name="Resource Files"
+ Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+ >
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/jasper-1.900.1-6ct/src/msvc/imgcmp.vcproj.paradigit.marcel.user b/jasper-1.900.1-6ct/src/msvc/imgcmp.vcproj.paradigit.marcel.user
new file mode 100644
index 0000000..c1a4582
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/imgcmp.vcproj.paradigit.marcel.user
@@ -0,0 +1,93 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioUserFile
+ ProjectType="Visual C++"
+ Version="9.00"
+ ShowAllFiles="false"
+ >
+ <Configurations>
+ <Configuration
+ Name="Debug|Win32"
+ >
+ <DebugSettings
+ Command="$(TargetPath)"
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ >
+ <DebugSettings
+ Command="$(TargetPath)"
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ <Configuration
+ Name="Release64|Win32"
+ >
+ <DebugSettings
+ Command="$(TargetPath)"
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ </Configurations>
+</VisualStudioUserFile>
diff --git a/jasper-1.900.1-6ct/src/msvc/imginfo.dsp b/jasper-1.900.1-6ct/src/msvc/imginfo.dsp
new file mode 100644
index 0000000..e18f9c2
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/imginfo.dsp
@@ -0,0 +1,102 @@
+# Microsoft Developer Studio Project File - Name="imginfo" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 6.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Console Application" 0x0103
+
+CFG=imginfo - Win32 Debug
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "imginfo.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "imginfo.mak" CFG="imginfo - Win32 Debug"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "imginfo - Win32 Release" (based on "Win32 (x86) Console Application")
+!MESSAGE "imginfo - Win32 Debug" (based on "Win32 (x86) Console Application")
+!MESSAGE
+
+# Begin Project
+# PROP AllowPerConfigDependencies 0
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "imginfo - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "imginfo___Win32_Release"
+# PROP BASE Intermediate_Dir "imginfo___Win32_Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "Win32_Release"
+# PROP Intermediate_Dir "imginfo___Win32_Release"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
+# ADD CPP /nologo /W3 /GX /O2 /I "..\libjasper\include" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "JAS_WIN_MSVC_BUILD" /YX /FD /c
+# ADD BASE RSC /l 0x409 /d "NDEBUG"
+# ADD RSC /l 0x409 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libjasper.lib /nologo /subsystem:console /machine:I386 /libpath:"Win32_Release"
+
+!ELSEIF "$(CFG)" == "imginfo - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "imginfo___Win32_Debug"
+# PROP BASE Intermediate_Dir "imginfo___Win32_Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "Win32_Debug"
+# PROP Intermediate_Dir "imginfo___Win32_Debug"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
+# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "..\libjasper\include" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "JAS_WIN_MSVC_BUILD" /YX /FD /GZ /c
+# ADD BASE RSC /l 0x409 /d "_DEBUG"
+# ADD RSC /l 0x409 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libjasper.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"Win32_Debug"
+
+!ENDIF
+
+# Begin Target
+
+# Name "imginfo - Win32 Release"
+# Name "imginfo - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+# Begin Source File
+
+SOURCE=..\appl\imginfo.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl"
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
diff --git a/jasper-1.900.1-6ct/src/msvc/imginfo.vcproj b/jasper-1.900.1-6ct/src/msvc/imginfo.vcproj
new file mode 100644
index 0000000..0987104
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/imginfo.vcproj
@@ -0,0 +1,344 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="9.00"
+ Name="imginfo"
+ ProjectGUID="{F479BCC4-400C-4FFB-A18F-E291A6C08FAF}"
+ TargetFrameworkVersion="0"
+ >
+ <Platforms>
+ <Platform
+ Name="Win32"
+ />
+ </Platforms>
+ <ToolFiles>
+ </ToolFiles>
+ <Configurations>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Win32_Release"
+ IntermediateDirectory=".\imginfo___Win32_Release"
+ ConfigurationType="1"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Win32_Release/imginfo.tlb"
+ HeaderFileName=""
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="NDEBUG;WIN32;_CONSOLE;JAS_WIN_MSVC_BUILD"
+ StringPooling="true"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="true"
+ PrecompiledHeaderFile=".\imginfo___Win32_Release/imginfo.pch"
+ AssemblerListingLocation=".\imginfo___Win32_Release/"
+ ObjectFile=".\imginfo___Win32_Release/"
+ ProgramDataBaseFileName=".\imginfo___Win32_Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib libjasper.lib"
+ OutputFile=".\Win32_Release/imginfo.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="true"
+ AdditionalLibraryDirectories="Win32_Release"
+ ProgramDatabaseFile=".\Win32_Release/imginfo.pdb"
+ SubSystem="1"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Release/imginfo.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Win32_Debug"
+ IntermediateDirectory=".\imginfo___Win32_Debug"
+ ConfigurationType="1"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Win32_Debug/imginfo.tlb"
+ HeaderFileName=""
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="_DEBUG;WIN32;_CONSOLE;JAS_WIN_MSVC_BUILD"
+ MinimalRebuild="true"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ PrecompiledHeaderFile=".\imginfo___Win32_Debug/imginfo.pch"
+ AssemblerListingLocation=".\imginfo___Win32_Debug/"
+ ObjectFile=".\imginfo___Win32_Debug/"
+ ProgramDataBaseFileName=".\imginfo___Win32_Debug/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ DebugInformationFormat="4"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib libjasper.lib"
+ OutputFile=".\Win32_Debug/imginfo.exe"
+ LinkIncremental="2"
+ SuppressStartupBanner="true"
+ AdditionalLibraryDirectories="Win32_Debug"
+ GenerateDebugInformation="true"
+ ProgramDatabaseFile=".\Win32_Debug/imginfo.pdb"
+ SubSystem="1"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Debug/imginfo.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Release64|Win32"
+ OutputDirectory="$(ConfigurationName)"
+ IntermediateDirectory="$(ConfigurationName)"
+ ConfigurationType="1"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Win32_Release/imginfo.tlb"
+ HeaderFileName=""
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="NDEBUG;WIN32;_CONSOLE;JAS_WIN_MSVC_BUILD"
+ StringPooling="true"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="true"
+ PrecompiledHeaderFile=".\imginfo___Win32_Release/imginfo.pch"
+ AssemblerListingLocation=".\imginfo___Win32_Release/"
+ ObjectFile=".\imginfo___Win32_Release/"
+ ProgramDataBaseFileName=".\imginfo___Win32_Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib libjasper.lib"
+ OutputFile=".\Win32_Release/imginfo.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="true"
+ AdditionalLibraryDirectories="Win32_Release"
+ ProgramDatabaseFile=".\Win32_Release/imginfo.pdb"
+ SubSystem="1"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Release/imginfo.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+ >
+ <File
+ RelativePath="..\appl\imginfo.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl"
+ >
+ </Filter>
+ <Filter
+ Name="Resource Files"
+ Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+ >
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/jasper-1.900.1-6ct/src/msvc/imginfo.vcproj.paradigit.marcel.user b/jasper-1.900.1-6ct/src/msvc/imginfo.vcproj.paradigit.marcel.user
new file mode 100644
index 0000000..c63787b
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/imginfo.vcproj.paradigit.marcel.user
@@ -0,0 +1,93 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioUserFile
+ ProjectType="Visual C++"
+ Version="9.00"
+ ShowAllFiles="false"
+ >
+ <Configurations>
+ <Configuration
+ Name="Release|Win32"
+ >
+ <DebugSettings
+ Command="$(TargetPath)"
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ >
+ <DebugSettings
+ Command="$(TargetPath)"
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ <Configuration
+ Name="Release64|Win32"
+ >
+ <DebugSettings
+ Command="$(TargetPath)"
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ </Configurations>
+</VisualStudioUserFile>
diff --git a/jasper-1.900.1-6ct/src/msvc/jasper.dsp b/jasper-1.900.1-6ct/src/msvc/jasper.dsp
new file mode 100644
index 0000000..34e82ad
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/jasper.dsp
@@ -0,0 +1,102 @@
+# Microsoft Developer Studio Project File - Name="jasper" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 6.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Console Application" 0x0103
+
+CFG=jasper - Win32 Debug
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "jasper.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "jasper.mak" CFG="jasper - Win32 Debug"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "jasper - Win32 Release" (based on "Win32 (x86) Console Application")
+!MESSAGE "jasper - Win32 Debug" (based on "Win32 (x86) Console Application")
+!MESSAGE
+
+# Begin Project
+# PROP AllowPerConfigDependencies 0
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "jasper - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "Release"
+# PROP BASE Intermediate_Dir "Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "Win32_Release"
+# PROP Intermediate_Dir "jasper___Win32_Release"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
+# ADD CPP /nologo /W3 /GX /O2 /I "..\libjasper\include" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "JAS_WIN_MSVC_BUILD" /YX /FD /c
+# ADD BASE RSC /l 0x409 /d "NDEBUG"
+# ADD RSC /l 0x409 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libjasper.lib /nologo /subsystem:console /machine:I386 /libpath:"Win32_Release"
+
+!ELSEIF "$(CFG)" == "jasper - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "jasper___Win32_Debug"
+# PROP BASE Intermediate_Dir "jasper___Win32_Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "Win32_Debug"
+# PROP Intermediate_Dir "jasper___Win32_Debug"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
+# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "..\libjasper\include" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "JAS_WIN_MSVC_BUILD" /YX /FD /GZ /c
+# ADD BASE RSC /l 0x409 /d "_DEBUG"
+# ADD RSC /l 0x409 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libjasper.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"Win32_Debug"
+
+!ENDIF
+
+# Begin Target
+
+# Name "jasper - Win32 Release"
+# Name "jasper - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+# Begin Source File
+
+SOURCE=..\appl\jasper.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl"
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
diff --git a/jasper-1.900.1-6ct/src/msvc/jasper.dsw b/jasper-1.900.1-6ct/src/msvc/jasper.dsw
new file mode 100644
index 0000000..f4cf8f4
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/jasper.dsw
@@ -0,0 +1,86 @@
+Microsoft Developer Studio Workspace File, Format Version 6.00
+# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
+
+###############################################################################
+
+Project: "imgcmp"=".\imgcmp.dsp" - Package Owner=<4>
+
+Package=<5>
+{{{
+}}}
+
+Package=<4>
+{{{
+ Begin Project Dependency
+ Project_Dep_Name libjasper
+ End Project Dependency
+}}}
+
+###############################################################################
+
+Project: "imginfo"=".\imginfo.dsp" - Package Owner=<4>
+
+Package=<5>
+{{{
+}}}
+
+Package=<4>
+{{{
+ Begin Project Dependency
+ Project_Dep_Name libjasper
+ End Project Dependency
+}}}
+
+###############################################################################
+
+Project: "jasper"=".\jasper.dsp" - Package Owner=<4>
+
+Package=<5>
+{{{
+}}}
+
+Package=<4>
+{{{
+ Begin Project Dependency
+ Project_Dep_Name libjasper
+ End Project Dependency
+}}}
+
+###############################################################################
+
+Project: "jiv"=".\jiv.dsp" - Package Owner=<4>
+
+Package=<5>
+{{{
+}}}
+
+Package=<4>
+{{{
+}}}
+
+###############################################################################
+
+Project: "libjasper"=".\libjasper.dsp" - Package Owner=<4>
+
+Package=<5>
+{{{
+}}}
+
+Package=<4>
+{{{
+}}}
+
+###############################################################################
+
+Global:
+
+Package=<5>
+{{{
+}}}
+
+Package=<3>
+{{{
+}}}
+
+###############################################################################
+
diff --git a/jasper-1.900.1-6ct/src/msvc/jasper.sln b/jasper-1.900.1-6ct/src/msvc/jasper.sln
new file mode 100644
index 0000000..b60fffc
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/jasper.sln
@@ -0,0 +1,92 @@
+
+Microsoft Visual Studio Solution File, Format Version 10.00
+# Visual C++ Express 2008
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "imgcmp", "imgcmp.vcproj", "{08D097E0-4FF1-42F3-9C4C-12C70519B42B}"
+ ProjectSection(ProjectDependencies) = postProject
+ {4833E235-DFCB-4260-BE5A-789169420FA8} = {4833E235-DFCB-4260-BE5A-789169420FA8}
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "imginfo", "imginfo.vcproj", "{F479BCC4-400C-4FFB-A18F-E291A6C08FAF}"
+ ProjectSection(ProjectDependencies) = postProject
+ {4833E235-DFCB-4260-BE5A-789169420FA8} = {4833E235-DFCB-4260-BE5A-789169420FA8}
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jasper", "jasper.vcproj", "{966F6EA1-6334-4346-A6D2-EEDB24E7A39C}"
+ ProjectSection(ProjectDependencies) = postProject
+ {4833E235-DFCB-4260-BE5A-789169420FA8} = {4833E235-DFCB-4260-BE5A-789169420FA8}
+ EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jiv", "jiv.vcproj", "{D5A23715-B01A-4050-B5C6-560939246C4E}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libjasper", "libjasper.vcproj", "{4833E235-DFCB-4260-BE5A-789169420FA8}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Win32 = Debug|Win32
+ Debug|X64 = Debug|X64
+ Release|Win32 = Release|Win32
+ Release|X64 = Release|X64
+ Release64|Win32 = Release64|Win32
+ Release64|X64 = Release64|X64
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {08D097E0-4FF1-42F3-9C4C-12C70519B42B}.Debug|Win32.ActiveCfg = Debug|Win32
+ {08D097E0-4FF1-42F3-9C4C-12C70519B42B}.Debug|Win32.Build.0 = Debug|Win32
+ {08D097E0-4FF1-42F3-9C4C-12C70519B42B}.Debug|X64.ActiveCfg = Debug|Win32
+ {08D097E0-4FF1-42F3-9C4C-12C70519B42B}.Debug|X64.Build.0 = Debug|Win32
+ {08D097E0-4FF1-42F3-9C4C-12C70519B42B}.Release|Win32.ActiveCfg = Release|Win32
+ {08D097E0-4FF1-42F3-9C4C-12C70519B42B}.Release|Win32.Build.0 = Release|Win32
+ {08D097E0-4FF1-42F3-9C4C-12C70519B42B}.Release|X64.ActiveCfg = Release|Win32
+ {08D097E0-4FF1-42F3-9C4C-12C70519B42B}.Release|X64.Build.0 = Release|Win32
+ {08D097E0-4FF1-42F3-9C4C-12C70519B42B}.Release64|Win32.ActiveCfg = Release64|Win32
+ {08D097E0-4FF1-42F3-9C4C-12C70519B42B}.Release64|Win32.Build.0 = Release64|Win32
+ {08D097E0-4FF1-42F3-9C4C-12C70519B42B}.Release64|X64.ActiveCfg = Release64|Win32
+ {F479BCC4-400C-4FFB-A18F-E291A6C08FAF}.Debug|Win32.ActiveCfg = Debug|Win32
+ {F479BCC4-400C-4FFB-A18F-E291A6C08FAF}.Debug|Win32.Build.0 = Debug|Win32
+ {F479BCC4-400C-4FFB-A18F-E291A6C08FAF}.Debug|X64.ActiveCfg = Debug|Win32
+ {F479BCC4-400C-4FFB-A18F-E291A6C08FAF}.Debug|X64.Build.0 = Debug|Win32
+ {F479BCC4-400C-4FFB-A18F-E291A6C08FAF}.Release|Win32.ActiveCfg = Release|Win32
+ {F479BCC4-400C-4FFB-A18F-E291A6C08FAF}.Release|Win32.Build.0 = Release|Win32
+ {F479BCC4-400C-4FFB-A18F-E291A6C08FAF}.Release|X64.ActiveCfg = Release|Win32
+ {F479BCC4-400C-4FFB-A18F-E291A6C08FAF}.Release|X64.Build.0 = Release|Win32
+ {F479BCC4-400C-4FFB-A18F-E291A6C08FAF}.Release64|Win32.ActiveCfg = Release64|Win32
+ {F479BCC4-400C-4FFB-A18F-E291A6C08FAF}.Release64|Win32.Build.0 = Release64|Win32
+ {F479BCC4-400C-4FFB-A18F-E291A6C08FAF}.Release64|X64.ActiveCfg = Release64|Win32
+ {966F6EA1-6334-4346-A6D2-EEDB24E7A39C}.Debug|Win32.ActiveCfg = Debug|Win32
+ {966F6EA1-6334-4346-A6D2-EEDB24E7A39C}.Debug|Win32.Build.0 = Debug|Win32
+ {966F6EA1-6334-4346-A6D2-EEDB24E7A39C}.Debug|X64.ActiveCfg = Debug|Win32
+ {966F6EA1-6334-4346-A6D2-EEDB24E7A39C}.Debug|X64.Build.0 = Debug|Win32
+ {966F6EA1-6334-4346-A6D2-EEDB24E7A39C}.Release|Win32.ActiveCfg = Release|Win32
+ {966F6EA1-6334-4346-A6D2-EEDB24E7A39C}.Release|Win32.Build.0 = Release|Win32
+ {966F6EA1-6334-4346-A6D2-EEDB24E7A39C}.Release|X64.ActiveCfg = Release|Win32
+ {966F6EA1-6334-4346-A6D2-EEDB24E7A39C}.Release|X64.Build.0 = Release|Win32
+ {966F6EA1-6334-4346-A6D2-EEDB24E7A39C}.Release64|Win32.ActiveCfg = Release64|Win32
+ {966F6EA1-6334-4346-A6D2-EEDB24E7A39C}.Release64|Win32.Build.0 = Release64|Win32
+ {966F6EA1-6334-4346-A6D2-EEDB24E7A39C}.Release64|X64.ActiveCfg = Release64|Win32
+ {D5A23715-B01A-4050-B5C6-560939246C4E}.Debug|Win32.ActiveCfg = Debug|Win32
+ {D5A23715-B01A-4050-B5C6-560939246C4E}.Debug|Win32.Build.0 = Debug|Win32
+ {D5A23715-B01A-4050-B5C6-560939246C4E}.Debug|X64.ActiveCfg = Debug|Win32
+ {D5A23715-B01A-4050-B5C6-560939246C4E}.Debug|X64.Build.0 = Debug|Win32
+ {D5A23715-B01A-4050-B5C6-560939246C4E}.Release|Win32.ActiveCfg = Release|Win32
+ {D5A23715-B01A-4050-B5C6-560939246C4E}.Release|Win32.Build.0 = Release|Win32
+ {D5A23715-B01A-4050-B5C6-560939246C4E}.Release|X64.ActiveCfg = Release|Win32
+ {D5A23715-B01A-4050-B5C6-560939246C4E}.Release|X64.Build.0 = Release|Win32
+ {D5A23715-B01A-4050-B5C6-560939246C4E}.Release64|Win32.ActiveCfg = Release64|Win32
+ {D5A23715-B01A-4050-B5C6-560939246C4E}.Release64|Win32.Build.0 = Release64|Win32
+ {D5A23715-B01A-4050-B5C6-560939246C4E}.Release64|X64.ActiveCfg = Release64|Win32
+ {4833E235-DFCB-4260-BE5A-789169420FA8}.Debug|Win32.ActiveCfg = Debug|Win32
+ {4833E235-DFCB-4260-BE5A-789169420FA8}.Debug|Win32.Build.0 = Debug|Win32
+ {4833E235-DFCB-4260-BE5A-789169420FA8}.Debug|X64.ActiveCfg = Debug|Win32
+ {4833E235-DFCB-4260-BE5A-789169420FA8}.Debug|X64.Build.0 = Debug|Win32
+ {4833E235-DFCB-4260-BE5A-789169420FA8}.Release|Win32.ActiveCfg = Release|Win32
+ {4833E235-DFCB-4260-BE5A-789169420FA8}.Release|Win32.Build.0 = Release|Win32
+ {4833E235-DFCB-4260-BE5A-789169420FA8}.Release|X64.ActiveCfg = Release|Win32
+ {4833E235-DFCB-4260-BE5A-789169420FA8}.Release|X64.Build.0 = Release|Win32
+ {4833E235-DFCB-4260-BE5A-789169420FA8}.Release64|Win32.ActiveCfg = Release64|Win32
+ {4833E235-DFCB-4260-BE5A-789169420FA8}.Release64|Win32.Build.0 = Release64|Win32
+ {4833E235-DFCB-4260-BE5A-789169420FA8}.Release64|X64.ActiveCfg = Release64|Win32
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/jasper-1.900.1-6ct/src/msvc/jasper.vcproj b/jasper-1.900.1-6ct/src/msvc/jasper.vcproj
new file mode 100644
index 0000000..b649836
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/jasper.vcproj
@@ -0,0 +1,344 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="9.00"
+ Name="jasper"
+ ProjectGUID="{966F6EA1-6334-4346-A6D2-EEDB24E7A39C}"
+ TargetFrameworkVersion="0"
+ >
+ <Platforms>
+ <Platform
+ Name="Win32"
+ />
+ </Platforms>
+ <ToolFiles>
+ </ToolFiles>
+ <Configurations>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Win32_Debug"
+ IntermediateDirectory=".\jasper___Win32_Debug"
+ ConfigurationType="1"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Win32_Debug/jasper.tlb"
+ HeaderFileName=""
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="_DEBUG;WIN32;_CONSOLE;JAS_WIN_MSVC_BUILD"
+ MinimalRebuild="true"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ PrecompiledHeaderFile=".\jasper___Win32_Debug/jasper.pch"
+ AssemblerListingLocation=".\jasper___Win32_Debug/"
+ ObjectFile=".\jasper___Win32_Debug/"
+ ProgramDataBaseFileName=".\jasper___Win32_Debug/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ DebugInformationFormat="4"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib libjasper.lib"
+ OutputFile=".\Win32_Debug/jasper.exe"
+ LinkIncremental="2"
+ SuppressStartupBanner="true"
+ AdditionalLibraryDirectories="Win32_Debug"
+ GenerateDebugInformation="true"
+ ProgramDatabaseFile=".\Win32_Debug/jasper.pdb"
+ SubSystem="1"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Debug/jasper.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Win32_Release"
+ IntermediateDirectory=".\jasper___Win32_Release"
+ ConfigurationType="1"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Win32_Release/jasper.tlb"
+ HeaderFileName=""
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="NDEBUG;WIN32;_CONSOLE;JAS_WIN_MSVC_BUILD"
+ StringPooling="true"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="true"
+ PrecompiledHeaderFile=".\jasper___Win32_Release/jasper.pch"
+ AssemblerListingLocation=".\jasper___Win32_Release/"
+ ObjectFile=".\jasper___Win32_Release/"
+ ProgramDataBaseFileName=".\jasper___Win32_Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib libjasper.lib"
+ OutputFile=".\Win32_Release/jasper.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="true"
+ AdditionalLibraryDirectories="Win32_Release"
+ ProgramDatabaseFile=".\Win32_Release/jasper.pdb"
+ SubSystem="1"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Release/jasper.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Release64|Win32"
+ OutputDirectory="$(ConfigurationName)"
+ IntermediateDirectory="$(ConfigurationName)"
+ ConfigurationType="1"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Win32_Release/jasper.tlb"
+ HeaderFileName=""
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="NDEBUG;WIN32;_CONSOLE;JAS_WIN_MSVC_BUILD"
+ StringPooling="true"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="true"
+ PrecompiledHeaderFile=".\jasper___Win32_Release/jasper.pch"
+ AssemblerListingLocation=".\jasper___Win32_Release/"
+ ObjectFile=".\jasper___Win32_Release/"
+ ProgramDataBaseFileName=".\jasper___Win32_Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib libjasper.lib"
+ OutputFile=".\Win32_Release/jasper.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="true"
+ AdditionalLibraryDirectories="Win32_Release"
+ ProgramDatabaseFile=".\Win32_Release/jasper.pdb"
+ SubSystem="1"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Release/jasper.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+ >
+ <File
+ RelativePath="..\appl\jasper.c"
+ >
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl"
+ >
+ </Filter>
+ <Filter
+ Name="Resource Files"
+ Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+ >
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/jasper-1.900.1-6ct/src/msvc/jasper.vcproj.paradigit.marcel.user b/jasper-1.900.1-6ct/src/msvc/jasper.vcproj.paradigit.marcel.user
new file mode 100644
index 0000000..c1a4582
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/jasper.vcproj.paradigit.marcel.user
@@ -0,0 +1,93 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioUserFile
+ ProjectType="Visual C++"
+ Version="9.00"
+ ShowAllFiles="false"
+ >
+ <Configurations>
+ <Configuration
+ Name="Debug|Win32"
+ >
+ <DebugSettings
+ Command="$(TargetPath)"
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ >
+ <DebugSettings
+ Command="$(TargetPath)"
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ <Configuration
+ Name="Release64|Win32"
+ >
+ <DebugSettings
+ Command="$(TargetPath)"
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ </Configurations>
+</VisualStudioUserFile>
diff --git a/jasper-1.900.1-6ct/src/msvc/jiv.dsp b/jasper-1.900.1-6ct/src/msvc/jiv.dsp
new file mode 100644
index 0000000..0bb09ee
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/jiv.dsp
@@ -0,0 +1,102 @@
+# Microsoft Developer Studio Project File - Name="jiv" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 6.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Console Application" 0x0103
+
+CFG=jiv - Win32 Debug
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "jiv.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "jiv.mak" CFG="jiv - Win32 Debug"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "jiv - Win32 Release" (based on "Win32 (x86) Console Application")
+!MESSAGE "jiv - Win32 Debug" (based on "Win32 (x86) Console Application")
+!MESSAGE
+
+# Begin Project
+# PROP AllowPerConfigDependencies 0
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "jiv - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "Release"
+# PROP BASE Intermediate_Dir "Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "Win32_Release"
+# PROP Intermediate_Dir "jiv___Win32_Release"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
+# ADD CPP /nologo /W3 /GX /O2 /I "..\libjasper\include" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "JAS_WIN_MSVC_BUILD" /YX /FD /c
+# ADD BASE RSC /l 0x409 /d "NDEBUG"
+# ADD RSC /l 0x409 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libjasper.lib /nologo /subsystem:console /machine:I386 /libpath:"Win32_Release"
+
+!ELSEIF "$(CFG)" == "jiv - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "Debug"
+# PROP BASE Intermediate_Dir "Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "Win32_Debug"
+# PROP Intermediate_Dir "jiv___Win32_Debug"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c
+# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "..\libjasper\include" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "JAS_WIN_MSVC_BUILD" /YX /FD /GZ /c
+# ADD BASE RSC /l 0x409 /d "_DEBUG"
+# ADD RSC /l 0x409 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib libjasper.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"Win32_Debug"
+
+!ENDIF
+
+# Begin Target
+
+# Name "jiv - Win32 Release"
+# Name "jiv - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+# Begin Source File
+
+SOURCE=..\appl\jiv.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl"
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+# End Group
+# End Target
+# End Project
diff --git a/jasper-1.900.1-6ct/src/msvc/jiv.vcproj b/jasper-1.900.1-6ct/src/msvc/jiv.vcproj
new file mode 100644
index 0000000..5131dc6
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/jiv.vcproj
@@ -0,0 +1,344 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="9.00"
+ Name="jiv"
+ ProjectGUID="{D5A23715-B01A-4050-B5C6-560939246C4E}"
+ TargetFrameworkVersion="0"
+ >
+ <Platforms>
+ <Platform
+ Name="Win32"
+ />
+ </Platforms>
+ <ToolFiles>
+ </ToolFiles>
+ <Configurations>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Win32_Release"
+ IntermediateDirectory=".\jiv___Win32_Release"
+ ConfigurationType="1"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Win32_Release/jiv.tlb"
+ HeaderFileName=""
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="NDEBUG;WIN32;_CONSOLE;JAS_WIN_MSVC_BUILD"
+ StringPooling="true"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="true"
+ PrecompiledHeaderFile=".\jiv___Win32_Release/jiv.pch"
+ AssemblerListingLocation=".\jiv___Win32_Release/"
+ ObjectFile=".\jiv___Win32_Release/"
+ ProgramDataBaseFileName=".\jiv___Win32_Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib libjasper.lib"
+ OutputFile=".\Win32_Release/jiv.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="true"
+ AdditionalLibraryDirectories="Win32_Release"
+ ProgramDatabaseFile=".\Win32_Release/jiv.pdb"
+ SubSystem="1"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Release/jiv.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Win32_Debug"
+ IntermediateDirectory=".\jiv___Win32_Debug"
+ ConfigurationType="1"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Win32_Debug/jiv.tlb"
+ HeaderFileName=""
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="_DEBUG;WIN32;_CONSOLE;JAS_WIN_MSVC_BUILD"
+ MinimalRebuild="true"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ PrecompiledHeaderFile=".\jiv___Win32_Debug/jiv.pch"
+ AssemblerListingLocation=".\jiv___Win32_Debug/"
+ ObjectFile=".\jiv___Win32_Debug/"
+ ProgramDataBaseFileName=".\jiv___Win32_Debug/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ DebugInformationFormat="4"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib libjasper.lib"
+ OutputFile=".\Win32_Debug/jiv.exe"
+ LinkIncremental="2"
+ SuppressStartupBanner="true"
+ AdditionalLibraryDirectories="Win32_Debug"
+ GenerateDebugInformation="true"
+ ProgramDatabaseFile=".\Win32_Debug/jiv.pdb"
+ SubSystem="1"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Debug/jiv.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Release64|Win32"
+ OutputDirectory="$(ConfigurationName)"
+ IntermediateDirectory="$(ConfigurationName)"
+ ConfigurationType="1"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ TypeLibraryName=".\Win32_Release/jiv.tlb"
+ HeaderFileName=""
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="NDEBUG;WIN32;_CONSOLE;JAS_WIN_MSVC_BUILD"
+ StringPooling="true"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="true"
+ PrecompiledHeaderFile=".\jiv___Win32_Release/jiv.pch"
+ AssemblerListingLocation=".\jiv___Win32_Release/"
+ ObjectFile=".\jiv___Win32_Release/"
+ ProgramDataBaseFileName=".\jiv___Win32_Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="odbc32.lib odbccp32.lib libjasper.lib"
+ OutputFile=".\Win32_Release/jiv.exe"
+ LinkIncremental="1"
+ SuppressStartupBanner="true"
+ AdditionalLibraryDirectories="Win32_Release"
+ ProgramDatabaseFile=".\Win32_Release/jiv.pdb"
+ SubSystem="1"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Release/jiv.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+ >
+ <File
+ RelativePath="..\appl\jiv.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl"
+ >
+ </Filter>
+ <Filter
+ Name="Resource Files"
+ Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+ >
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/jasper-1.900.1-6ct/src/msvc/jiv.vcproj.paradigit.marcel.user b/jasper-1.900.1-6ct/src/msvc/jiv.vcproj.paradigit.marcel.user
new file mode 100644
index 0000000..c63787b
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/jiv.vcproj.paradigit.marcel.user
@@ -0,0 +1,93 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioUserFile
+ ProjectType="Visual C++"
+ Version="9.00"
+ ShowAllFiles="false"
+ >
+ <Configurations>
+ <Configuration
+ Name="Release|Win32"
+ >
+ <DebugSettings
+ Command="$(TargetPath)"
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ >
+ <DebugSettings
+ Command="$(TargetPath)"
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ <Configuration
+ Name="Release64|Win32"
+ >
+ <DebugSettings
+ Command="$(TargetPath)"
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ </Configurations>
+</VisualStudioUserFile>
diff --git a/jasper-1.900.1-6ct/src/msvc/libjasper.dsp b/jasper-1.900.1-6ct/src/msvc/libjasper.dsp
new file mode 100644
index 0000000..86cb324
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/libjasper.dsp
@@ -0,0 +1,428 @@
+# Microsoft Developer Studio Project File - Name="libjasper" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 6.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Static Library" 0x0104
+
+CFG=libjasper - Win32 Debug
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE
+!MESSAGE NMAKE /f "libjasper.mak".
+!MESSAGE
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "libjasper.mak" CFG="libjasper - Win32 Debug"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "libjasper - Win32 Release" (based on "Win32 (x86) Static Library")
+!MESSAGE "libjasper - Win32 Debug" (based on "Win32 (x86) Static Library")
+!MESSAGE
+
+# Begin Project
+# PROP AllowPerConfigDependencies 0
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "libjasper - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "Release"
+# PROP BASE Intermediate_Dir "Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "Win32_Release"
+# PROP Intermediate_Dir "libjasper___Win32_Release"
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
+# ADD CPP /nologo /W3 /GX /O2 /I "..\libjasper\include" /D "NDEBUG" /D "WIN32" /D "_MBCS" /D "_LIB" /D "JAS_WIN_MSVC_BUILD" /YX /FD /c
+# ADD BASE RSC /l 0x409 /d "NDEBUG"
+# ADD RSC /l 0x409 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LIB32=link.exe -lib
+# ADD BASE LIB32 /nologo
+# ADD LIB32 /nologo
+
+!ELSEIF "$(CFG)" == "libjasper - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "Debug"
+# PROP BASE Intermediate_Dir "Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "Win32_Debug"
+# PROP Intermediate_Dir "libjasper___Win32_Debug"
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
+# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "..\libjasper\include" /D "_DEBUG" /D "WIN32" /D "_MBCS" /D "_LIB" /D "JAS_WIN_MSVC_BUILD" /YX /FD /GZ /c
+# ADD BASE RSC /l 0x409 /d "_DEBUG"
+# ADD RSC /l 0x409 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LIB32=link.exe -lib
+# ADD BASE LIB32 /nologo
+# ADD LIB32 /nologo
+
+!ENDIF
+
+# Begin Target
+
+# Name "libjasper - Win32 Release"
+# Name "libjasper - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+# Begin Source File
+
+SOURCE=..\libjasper\bmp\bmp_cod.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\bmp\bmp_dec.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\bmp\bmp_enc.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_cm.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_debug.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_getopt.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_icc.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_iccdata.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_image.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_init.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_malloc.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_seq.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_stream.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_string.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_tmr.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_tvp.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\base\jas_version.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jp2\jp2_cod.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jp2\jp2_dec.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jp2\jp2_enc.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_bs.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_cs.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_dec.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_enc.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_math.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_mct.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_mqcod.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_mqdec.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_mqenc.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_qmfb.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_t1cod.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_t1dec.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_t1enc.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_t2cod.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_t2dec.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_t2enc.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_tagtree.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_tsfb.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_util.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpg\jpg_dummy.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpg\jpg_val.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\mif\mif_cod.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\pgx\pgx_cod.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\pgx\pgx_dec.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\pgx\pgx_enc.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\pnm\pnm_cod.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\pnm\pnm_dec.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\pnm\pnm_enc.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\ras\ras_cod.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\ras\ras_dec.c
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\ras\ras_enc.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl"
+# Begin Source File
+
+SOURCE=..\libjasper\bmp\bmp_cod.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\include\jasper\jas_cm.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\include\jasper\jas_icc.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\include\jasper\jas_tmr.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jp2\jp2_cod.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jp2\jp2_dec.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_bs.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_cod.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_cs.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_dec.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_enc.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_fix.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_flt.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_math.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_mct.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_mqcod.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_mqdec.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_mqenc.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_qmfb.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_t1cod.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_t1dec.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_t1enc.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_t2cod.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_t2dec.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_t2enc.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_tagtree.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_tsfb.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpc\jpc_util.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\jpg\jpg_cod.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\mif\mif_cod.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\pgx\pgx_cod.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\pnm\pnm_cod.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\libjasper\ras\ras_cod.h
+# End Source File
+# End Group
+# End Target
+# End Project
diff --git a/jasper-1.900.1-6ct/src/msvc/libjasper.vcproj b/jasper-1.900.1-6ct/src/msvc/libjasper.vcproj
new file mode 100644
index 0000000..01f8d6c
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/libjasper.vcproj
@@ -0,0 +1,1972 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="9.00"
+ Name="libjasper"
+ ProjectGUID="{4833E235-DFCB-4260-BE5A-789169420FA8}"
+ TargetFrameworkVersion="0"
+ >
+ <Platforms>
+ <Platform
+ Name="Win32"
+ />
+ </Platforms>
+ <ToolFiles>
+ </ToolFiles>
+ <Configurations>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory=".\Win32_Release"
+ IntermediateDirectory=".\libjasper___Win32_Release"
+ ConfigurationType="4"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="NDEBUG;WIN32;_LIB;JAS_WIN_MSVC_BUILD"
+ StringPooling="true"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="true"
+ PrecompiledHeaderFile=".\libjasper___Win32_Release/libjasper.pch"
+ AssemblerListingLocation=".\libjasper___Win32_Release/"
+ ObjectFile=".\libjasper___Win32_Release/"
+ ProgramDataBaseFileName=".\libjasper___Win32_Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Win32_Release\libjasper.lib"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Release/libjasper.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory=".\Win32_Debug"
+ IntermediateDirectory=".\libjasper___Win32_Debug"
+ ConfigurationType="4"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="_DEBUG;WIN32;_LIB;JAS_WIN_MSVC_BUILD"
+ MinimalRebuild="true"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="1"
+ PrecompiledHeaderFile=".\libjasper___Win32_Debug/libjasper.pch"
+ AssemblerListingLocation=".\libjasper___Win32_Debug/"
+ ObjectFile=".\libjasper___Win32_Debug/"
+ ProgramDataBaseFileName=".\libjasper___Win32_Debug/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ DebugInformationFormat="4"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="_DEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Win32_Debug\libjasper.lib"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Debug/libjasper.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Release64|Win32"
+ OutputDirectory="$(ConfigurationName)"
+ IntermediateDirectory="$(ConfigurationName)"
+ ConfigurationType="4"
+ InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
+ UseOfMFC="0"
+ ATLMinimizesCRunTimeLibraryUsage="false"
+ CharacterSet="2"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="2"
+ InlineFunctionExpansion="1"
+ AdditionalIncludeDirectories="..\libjasper\include"
+ PreprocessorDefinitions="NDEBUG;WIN32;_LIB;JAS_WIN_MSVC_BUILD"
+ StringPooling="true"
+ RuntimeLibrary="0"
+ EnableFunctionLevelLinking="true"
+ PrecompiledHeaderFile=".\libjasper___Win32_Release/libjasper.pch"
+ AssemblerListingLocation=".\libjasper___Win32_Release/"
+ ObjectFile=".\libjasper___Win32_Release/"
+ ProgramDataBaseFileName=".\libjasper___Win32_Release/"
+ WarningLevel="3"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ PreprocessorDefinitions="NDEBUG"
+ Culture="1033"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLibrarianTool"
+ OutputFile=".\Win32_Release\libjasper.lib"
+ SuppressStartupBanner="true"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ SuppressStartupBanner="true"
+ OutputFile=".\Win32_Release/libjasper.bsc"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ </Configurations>
+ <References>
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+ >
+ <File
+ RelativePath="..\libjasper\bmp\bmp_cod.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\bmp\bmp_dec.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\bmp\bmp_enc.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_cm.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_debug.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_getopt.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_icc.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_iccdata.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_image.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_init.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_malloc.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_seq.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_stream.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_string.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_tmr.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_tvp.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\base\jas_version.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jp2\jp2_cod.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jp2\jp2_dec.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jp2\jp2_enc.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_bs.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_cs.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_dec.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_enc.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_math.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_mct.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_mqcod.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_mqdec.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_mqenc.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_qmfb.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_t1cod.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_t1dec.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_t1enc.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_t2cod.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_t2dec.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_t2enc.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_tagtree.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_tsfb.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_util.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpg\jpg_dummy.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\jpg\jpg_val.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\mif\mif_cod.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\pgx\pgx_cod.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\pgx\pgx_dec.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\pgx\pgx_enc.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\pnm\pnm_cod.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\pnm\pnm_dec.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\pnm\pnm_enc.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\ras\ras_cod.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\ras\ras_dec.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ <File
+ RelativePath="..\libjasper\ras\ras_enc.c"
+ >
+ <FileConfiguration
+ Name="Release|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Debug|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ <FileConfiguration
+ Name="Release64|Win32"
+ >
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""
+ PreprocessorDefinitions=""
+ />
+ </FileConfiguration>
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl"
+ >
+ <File
+ RelativePath="..\libjasper\bmp\bmp_cod.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\include\jasper\jas_cm.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\include\jasper\jas_icc.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\include\jasper\jas_tmr.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jp2\jp2_cod.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jp2\jp2_dec.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_bs.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_cod.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_cs.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_dec.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_enc.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_fix.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_flt.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_math.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_mct.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_mqcod.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_mqdec.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_mqenc.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_qmfb.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_t1cod.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_t1dec.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_t1enc.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_t2cod.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_t2dec.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_t2enc.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_tagtree.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_tsfb.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpc\jpc_util.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\jpg\jpg_cod.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\mif\mif_cod.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\pgx\pgx_cod.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\pnm\pnm_cod.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libjasper\ras\ras_cod.h"
+ >
+ </File>
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/jasper-1.900.1-6ct/src/msvc/libjasper.vcproj.paradigit.marcel.user b/jasper-1.900.1-6ct/src/msvc/libjasper.vcproj.paradigit.marcel.user
new file mode 100644
index 0000000..2af40a1
--- /dev/null
+++ b/jasper-1.900.1-6ct/src/msvc/libjasper.vcproj.paradigit.marcel.user
@@ -0,0 +1,93 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioUserFile
+ ProjectType="Visual C++"
+ Version="9.00"
+ ShowAllFiles="false"
+ >
+ <Configurations>
+ <Configuration
+ Name="Release|Win32"
+ >
+ <DebugSettings
+ Command=""
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ <Configuration
+ Name="Debug|Win32"
+ >
+ <DebugSettings
+ Command=""
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ <Configuration
+ Name="Release64|Win32"
+ >
+ <DebugSettings
+ Command=""
+ WorkingDirectory=""
+ CommandArguments=""
+ Attach="false"
+ DebuggerType="3"
+ Remote="1"
+ RemoteMachine="PARADIGIT"
+ RemoteCommand=""
+ HttpUrl=""
+ PDBPath=""
+ SQLDebugging=""
+ Environment=""
+ EnvironmentMerge="true"
+ DebuggerFlavor=""
+ MPIRunCommand=""
+ MPIRunArguments=""
+ MPIRunWorkingDirectory=""
+ ApplicationCommand=""
+ ApplicationArguments=""
+ ShimCommand=""
+ MPIAcceptMode=""
+ MPIAcceptFilter=""
+ />
+ </Configuration>
+ </Configurations>
+</VisualStudioUserFile>
diff --git a/jpeg-6c/Darwin.rtf b/jpeg-6c/Darwin.rtf
new file mode 100644
index 0000000..9b59459
--- /dev/null
+++ b/jpeg-6c/Darwin.rtf
@@ -0,0 +1,27 @@
+{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf110
+{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
+{\colortbl;\red255\green255\blue255;}
+\margl1440\margr1440\vieww8960\viewh9260\viewkind0
+\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural
+
+\f0\fs24 \cf0 /* How I built jpeg universal on my mac powerbook G4:\
+Please note I did not put the programs in the normal place and I also didn't build the shared version, just the static. */\
+\
+cd /Developer/Projects\
+/* Unzip jpeg-6c here*/\
+mkdir jpeg\
+mkdir jpeg/bin\
+mkdir jpeg/bin/cjpeg\
+mkdir jpeg/include\
+mkdir jpeg/lib\
+mkdir jpeg/man\
+mkdir jpeg/man/man1\
+cp -f /Developer/usr/share/libtool/config/config.sub jpeg-6c/config.sub\
+cp -f /Developer/usr/share/libtool/config/config.guess jpeg-6c/config.guess\
+cd jpeg-6c\
+CFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -Os -mmacosx-version-min=10.3.9 -pipe -no-cpp-precomp -Wall" CCFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -Os -mmacosx-version-min=10.3.9 -pipe -Wall" CXXFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64 -Os -mmacosx-version-min=10.3.9 -pipe -Wall" LDFLAGS="-arch ppc -arch ppc64 -arch i386 -arch x86_64" ./configure --enable-static --with-xincludes=/usr/X11/include --with-xlibraries=/usr/X11/lib --prefix=/Developer/Projects/jpeg\
+make\
+make install\
+make install-lib\
+\
+}
\ No newline at end of file
diff --git a/jpeg-6c/Makefile.osx b/jpeg-6c/Makefile.osx
new file mode 100644
index 0000000..c9a626d
--- /dev/null
+++ b/jpeg-6c/Makefile.osx
@@ -0,0 +1,344 @@
+# Generated automatically from makefile.cfg by configure.
+# Makefile for Independent JPEG Group's software
+
+# makefile.cfg is edited by configure to produce a custom Makefile.
+
+# Read installation instructions before saying "make" !!
+
+# For compiling with source and object files in different directories.
+srcdir = .
+
+# Where to install the programs and man pages.
+prefix = /usr/local
+exec_prefix = ${prefix}
+bindir = $(exec_prefix)/bin
+libdir = $(exec_prefix)/lib
+includedir = $(prefix)/include
+binprefix =
+manprefix =
+manext = 1
+mandir = $(prefix)/man/man$(manext)
+
+# The name of your C compiler:
+CC= gcc
+
+# You may need to adjust these cc options:
+CFLAGS= -arch ppc -arch ppc64 -arch i386 -arch x86_64 -Os -mmacosx-version-min=10.3.9 -pipe -no-cpp-precomp -Wall -I$(srcdir)
+# Generally, we recommend defining any configuration symbols in jconfig.h,
+# NOT via -D switches here.
+# However, any special defines for ansi2knr.c may be included here:
+ANSI2KNRFLAGS=
+
+# Link-time cc options:
+LDFLAGS= -arch ppc -arch ppc64 -arch i386 -arch x86_64
+
+# To link any special libraries, add the necessary -l commands here.
+LDLIBS=
+
+# If using GNU libtool, LIBTOOL references it; if not, LIBTOOL is empty.
+LIBTOOL = ./libtool
+# $(O) expands to "lo" if using libtool, plain "o" if not.
+# Similarly, $(A) expands to "la" or "a".
+O = lo
+A = la
+
+# Library version ID; libtool uses this for the shared library version number.
+# Note: we suggest this match the macro of the same name in jpeglib.h.
+JPEG_LIB_VERSION = 63
+
+# Put here the object file name for the correct system-dependent memory
+# manager file. For Unix this is usually jmemnobs.o, but you may want
+# to use jmemansi.o or jmemname.o if you have limited swap space.
+SYSDEPMEM= jmemnobs.$(O)
+
+# miscellaneous OS-dependent stuff
+SHELL= /bin/sh
+# linker
+LN= $(LIBTOOL) --mode=link $(CC)
+# file deletion command
+RM= rm -f
+# directory creation command
+MKDIR= mkdir
+# library (.a) file creation command
+AR= ar rc
+# second step in .a creation (use "touch" if not needed)
+AR2= ranlib
+# installation program
+INSTALL= /usr/bin/install -c
+INSTALL_PROGRAM= $(LIBTOOL) --mode=install ${INSTALL}
+INSTALL_LIB= $(LIBTOOL) --mode=install ${INSTALL}
+INSTALL_DATA= ${INSTALL} -m 644
+
+# End of configurable options.
+
+
+# source files: JPEG library proper
+LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jcdiffct.c \
+ jchuff.c jcinit.c jclhuff.c jclossls.c jclossy.c jcmainct.c \
+ jcmarker.c jcmaster.c jcodec.c jcomapi.c jcparam.c jcphuff.c jcpred.c \
+ jcprepct.c jcsample.c jcscale.c jcshuff.c jctrans.c jdapimin.c \
+ jdapistd.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c \
+ jddiffct.c jdhuff.c jdinput.c jdlhuff.c jdlossls.c jdlossy.c \
+ jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c jdpostct.c \
+ jdpred.c jdsample.c jdscale.c jdshuff.c jdtrans.c jerror.c jfdctflt.c \
+ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c \
+ jquant1.c jquant2.c jutils.c jmemmgr.c
+# memmgr back ends: compile only one of these into a working library
+SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \
+ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+# files included by source files
+INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jlossls.h jlossy.h \
+ jmemsys.h jmorecfg.h jpegint.h jpeglib.h jversion.h cdjpeg.h \
+ cderror.h transupp.h
+# documentation, test, and support files
+DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
+ coderules.doc filelist.doc change.log
+MKFILES= configure makefile.cfg makefile.ansi makefile.unix makefile.bcc \
+ makefile.mc6 makefile.dj makefile.wat makefile.vc makelib.ds \
+ makeapps.ds makeproj.mac makcjpeg.st makdjpeg.st makljpeg.st \
+ maktjpeg.st makefile.manx makefile.sas makefile.mms makefile.vms \
+ makvms.opt
+CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \
+ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \
+ jconfig.vms
+CONFIGUREFILES= config.guess config.sub install-sh ltconfig ltmain.sh
+OTHERFILES= jconfig.doc ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm
+TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \
+ testimgp.jpg
+DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+# library object files common to compression and decompression
+COMOBJECTS= jcomapi.$(O) jcodec.$(O) jutils.$(O) jerror.$(O) jmemmgr.$(O) \
+ $(SYSDEPMEM)
+# compression library object files
+CLIBOBJECTS= jcapimin.$(O) jcapistd.$(O) jctrans.$(O) jcparam.$(O) \
+ jdatadst.$(O) jcinit.$(O) jcmaster.$(O) jcmarker.$(O) jcmainct.$(O) \
+ jcprepct.$(O) jclossls.$(O) jclossy.$(O) jccoefct.$(O) jccolor.$(O) \
+ jcsample.$(O) jchuff.$(O) jcphuff.$(O) jcshuff.$(O) jclhuff.$(O) \
+ jcpred.$(O) jcscale.$(O) jcdiffct.$(O) jcdctmgr.$(O) jfdctfst.$(O) \
+ jfdctflt.$(O) jfdctint.$(O)
+# decompression library object files
+DLIBOBJECTS= jdapimin.$(O) jdapistd.$(O) jdtrans.$(O) jdatasrc.$(O) \
+ jdmaster.$(O) jdinput.$(O) jdmarker.$(O) jdlossls.$(O) jdlossy.$(O) \
+ jdhuff.$(O) jdlhuff.$(O) jdphuff.$(O) jdshuff.$(O) jdpred.$(O) \
+ jdscale.$(O) jddiffct.$(O) jdmainct.$(O) jdcoefct.$(O) jdpostct.$(O) \
+ jddctmgr.$(O) jidctfst.$(O) jidctflt.$(O) jidctint.$(O) jidctred.$(O) \
+ jdsample.$(O) jdcolor.$(O) jquant1.$(O) jquant2.$(O) jdmerge.$(O)
+# These objectfiles are included in libjpeg.a
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+# object files for sample applications (excluding library files)
+COBJECTS= cjpeg.$(O) rdppm.$(O) rdgif.$(O) rdtarga.$(O) rdrle.$(O) \
+ rdbmp.$(O) rdswitch.$(O) cdjpeg.$(O)
+DOBJECTS= djpeg.$(O) wrppm.$(O) wrgif.$(O) wrtarga.$(O) wrrle.$(O) \
+ wrbmp.$(O) rdcolmap.$(O) cdjpeg.$(O)
+TROBJECTS= jpegtran.$(O) rdswitch.$(O) cdjpeg.$(O) transupp.$(O)
+
+
+all: libjpeg.$(A) cjpeg djpeg jpegtran rdjpgcom wrjpgcom
+
+# Special compilation rules to support ansi2knr and libtool.
+.SUFFIXES: .lo .la
+
+# How to compile with libtool.
+.c.lo:
+ $(LIBTOOL) --mode=compile $(CC) $(CFLAGS) -c $(srcdir)/$*.c
+
+# How to use ansi2knr, when not using libtool.
+# .c.o:
+# ./ansi2knr $(srcdir)/$*.c knr/$*.c
+# $(CC) $(CFLAGS) -c knr/$*.c
+# $(RM) knr/$*.c
+
+# How to use ansi2knr AND libtool.
+# .c.lo:
+# ./ansi2knr $(srcdir)/$*.c knr/$*.c
+# $(LIBTOOL) --mode=compile $(CC) $(CFLAGS) -c knr/$*.c
+# $(RM) knr/$*.c
+
+ansi2knr: ansi2knr.c
+ $(CC) $(CFLAGS) $(ANSI2KNRFLAGS) -o ansi2knr $(srcdir)/ansi2knr.c
+ $(MKDIR) knr
+
+# the library:
+
+# without libtool:
+libjpeg.a: $(LIBOBJECTS)
+ $(RM) libjpeg.a
+ $(AR) libjpeg.a $(LIBOBJECTS)
+ $(AR2) libjpeg.a
+
+# with libtool:
+libjpeg.la: $(LIBOBJECTS)
+ $(LIBTOOL) --mode=link $(CC) -o libjpeg.la $(LIBOBJECTS) \
+ -rpath $(libdir) -version-info $(JPEG_LIB_VERSION)
+
+# sample programs:
+
+cjpeg: $(COBJECTS) libjpeg.$(A)
+ $(LN) $(LDFLAGS) -o cjpeg $(COBJECTS) libjpeg.$(A) $(LDLIBS)
+
+djpeg: $(DOBJECTS) libjpeg.$(A)
+ $(LN) $(LDFLAGS) -o djpeg $(DOBJECTS) libjpeg.$(A) $(LDLIBS)
+
+jpegtran: $(TROBJECTS) libjpeg.$(A)
+ $(LN) $(LDFLAGS) -o jpegtran $(TROBJECTS) libjpeg.$(A) $(LDLIBS)
+
+rdjpgcom: rdjpgcom.$(O)
+ $(LN) $(LDFLAGS) -o rdjpgcom rdjpgcom.$(O) $(LDLIBS)
+
+wrjpgcom: wrjpgcom.$(O)
+ $(LN) $(LDFLAGS) -o wrjpgcom wrjpgcom.$(O) $(LDLIBS)
+
+# Installation rules:
+
+install: cjpeg djpeg jpegtran rdjpgcom wrjpgcom
+ $(INSTALL_PROGRAM) cjpeg $(bindir)/$(binprefix)cjpeg
+ $(INSTALL_PROGRAM) djpeg $(bindir)/$(binprefix)djpeg
+ $(INSTALL_PROGRAM) jpegtran $(bindir)/$(binprefix)jpegtran
+ $(INSTALL_PROGRAM) rdjpgcom $(bindir)/$(binprefix)rdjpgcom
+ $(INSTALL_PROGRAM) wrjpgcom $(bindir)/$(binprefix)wrjpgcom
+ $(INSTALL_DATA) $(srcdir)/cjpeg.1 $(mandir)/$(manprefix)cjpeg.$(manext)
+ $(INSTALL_DATA) $(srcdir)/djpeg.1 $(mandir)/$(manprefix)djpeg.$(manext)
+ $(INSTALL_DATA) $(srcdir)/jpegtran.1 $(mandir)/$(manprefix)jpegtran.$(manext)
+ $(INSTALL_DATA) $(srcdir)/rdjpgcom.1 $(mandir)/$(manprefix)rdjpgcom.$(manext)
+ $(INSTALL_DATA) $(srcdir)/wrjpgcom.1 $(mandir)/$(manprefix)wrjpgcom.$(manext)
+
+install-lib: libjpeg.$(A) install-headers
+ $(INSTALL_LIB) libjpeg.$(A) $(libdir)/$(binprefix)libjpeg.$(A)
+
+install-headers: jconfig.h
+ $(INSTALL_DATA) jconfig.h $(includedir)/jconfig.h
+ $(INSTALL_DATA) $(srcdir)/jpeglib.h $(includedir)/jpeglib.h
+ $(INSTALL_DATA) $(srcdir)/jmorecfg.h $(includedir)/jmorecfg.h
+ $(INSTALL_DATA) $(srcdir)/jerror.h $(includedir)/jerror.h
+
+clean:
+ $(RM) *.o *.lo libjpeg.a libjpeg.la
+ $(RM) cjpeg djpeg jpegtran rdjpgcom wrjpgcom
+ $(RM) ansi2knr core testout* config.log config.status
+ $(RM) -r knr .libs _libs
+
+distclean: clean
+ $(RM) Makefile jconfig.h libtool config.cache
+
+test: cjpeg djpeg jpegtran
+ $(RM) testout*
+ ./djpeg -dct int -ppm -outfile testout.ppm $(srcdir)/testorig.jpg
+ ./djpeg -dct int -bmp -colors 256 -outfile testout.bmp $(srcdir)/testorig.jpg
+ ./cjpeg -dct int -outfile testout.jpg $(srcdir)/testimg.ppm
+ ./djpeg -dct int -ppm -outfile testoutp.ppm $(srcdir)/testprog.jpg
+ ./cjpeg -dct int -progressive -opt -outfile testoutp.jpg $(srcdir)/testimg.ppm
+ ./jpegtran -outfile testoutt.jpg $(srcdir)/testprog.jpg
+ ./djpeg -ppm -outfile testoutl.ppm $(srcdir)/testimgl.jpg
+ ./cjpeg -lossless 4,1 -outfile testoutl.jpg $(srcdir)/testimg.ppm
+ cmp $(srcdir)/testimg.ppm testout.ppm
+ cmp $(srcdir)/testimg.bmp testout.bmp
+ cmp $(srcdir)/testimg.jpg testout.jpg
+ cmp $(srcdir)/testimg.ppm testoutp.ppm
+ cmp $(srcdir)/testimgp.jpg testoutp.jpg
+ cmp $(srcdir)/testorig.jpg testoutt.jpg
+ cmp $(srcdir)/testimgl.ppm testoutl.ppm
+ cmp $(srcdir)/testimgl.jpg testoutl.jpg
+
+check: test
+
+# Mistake catcher:
+
+jconfig.h: jconfig.doc
+ echo You must prepare a system-dependent jconfig.h file.
+ echo Please read the installation directions in install.doc.
+ exit 1
+
+# GNU Make likes to know which target names are not really files to be made:
+.PHONY: all install install-lib install-headers clean distclean test check
+
+
+jcapimin.$(O): jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcapistd.$(O): jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccoefct.$(O): jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+jcodec.$(O): jcodec.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jlossls.h
+jccolor.$(O): jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcdctmgr.$(O): jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jdct.h
+jcdiffct.$(O): jcdiffct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jchuff.$(O): jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jlossls.h jchuff.h
+jcinit.$(O): jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jclhuff.$(O): jclhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h jchuff.h
+jclossls.$(O): jclossls.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jclossy.$(O): jclossy.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+jcmainct.$(O): jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmarker.$(O): jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmaster.$(O): jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcomapi.$(O): jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcparam.$(O): jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcphuff.$(O): jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jchuff.h
+jcpred.$(O): jcpred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jcprepct.$(O): jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcsample.$(O): jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcscale.$(O): jcscale.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jcshuff.$(O): jcshuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jlossls.h jchuff.h
+jctrans.$(O): jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+jdapimin.$(O): jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapistd.$(O): jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdatadst.$(O): jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdatasrc.$(O): jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdcoefct.$(O): jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+jdcolor.$(O): jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jddctmgr.$(O): jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jdct.h
+jddiffct.$(O): jddiffct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jdhuff.$(O): jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jlossls.h jdhuff.h
+jdinput.$(O): jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdlhuff.$(O): jdlhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h jdhuff.h
+jdlossls.$(O): jdlossls.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jdlossy.$(O): jdlossy.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+jdmainct.$(O): jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmarker.$(O): jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmaster.$(O): jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmerge.$(O): jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdphuff.$(O): jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jdhuff.h
+jdpostct.$(O): jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdpred.$(O): jdpred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jdsample.$(O): jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdscale.$(O): jdscale.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jdshuff.$(O): jdshuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jdhuff.h
+jdtrans.$(O): jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+jerror.$(O): jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+jfdctflt.$(O): jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctfst.$(O): jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctint.$(O): jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctflt.$(O): jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctfst.$(O): jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctint.$(O): jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctred.$(O): jidctred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jquant1.$(O): jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jquant2.$(O): jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jutils.$(O): jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jmemmgr.$(O): jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemansi.$(O): jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemname.$(O): jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemnobs.$(O): jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemdos.$(O): jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemmac.$(O): jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+cjpeg.$(O): cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+djpeg.$(O): djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+jpegtran.$(O): jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
+rdjpgcom.$(O): rdjpgcom.c jinclude.h jconfig.h
+wrjpgcom.$(O): wrjpgcom.c jinclude.h jconfig.h
+cdjpeg.$(O): cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdcolmap.$(O): rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdswitch.$(O): rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+transupp.$(O): transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
+rdppm.$(O): rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrppm.$(O): wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdgif.$(O): rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrgif.$(O): wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdtarga.$(O): rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrtarga.$(O): wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdbmp.$(O): rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrbmp.$(O): wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdrle.$(O): rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrrle.$(O): wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
diff --git a/jpeg-6c/README b/jpeg-6c/README
new file mode 100644
index 0000000..2423594
--- /dev/null
+++ b/jpeg-6c/README
@@ -0,0 +1,385 @@
+The Independent JPEG Group's JPEG software
+==========================================
+
+README for release 6b of 27-Mar-1998
+====================================
+
+This distribution contains the sixth public release of the Independent JPEG
+Group's free JPEG software. You are welcome to redistribute this software and
+to use it for any purpose, subject to the conditions under LEGAL ISSUES, below.
+
+Serious users of this software (particularly those incorporating it into
+larger programs) should contact IJG at jpeg-info at uunet.uu.net to be added to
+our electronic mailing list. Mailing list members are notified of updates
+and have a chance to participate in technical discussions, etc.
+
+This software is the work of Tom Lane, Philip Gladstone, Jim Boucher,
+Lee Crocker, Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi,
+Guido Vollbeding, Ge' Weijers, and other members of the Independent JPEG
+Group.
+
+IJG is not affiliated with the official ISO JPEG standards committee.
+
+
+DOCUMENTATION ROADMAP
+=====================
+
+This file contains the following sections:
+
+OVERVIEW General description of JPEG and the IJG software.
+LEGAL ISSUES Copyright, lack of warranty, terms of distribution.
+REFERENCES Where to learn more about JPEG.
+ARCHIVE LOCATIONS Where to find newer versions of this software.
+RELATED SOFTWARE Other stuff you should get.
+FILE FORMAT WARS Software *not* to get.
+TO DO Plans for future IJG releases.
+
+Other documentation files in the distribution are:
+
+User documentation:
+ install.doc How to configure and install the IJG software.
+ usage.doc Usage instructions for cjpeg, djpeg, jpegtran,
+ rdjpgcom, and wrjpgcom.
+ *.1 Unix-style man pages for programs (same info as usage.doc).
+ wizard.doc Advanced usage instructions for JPEG wizards only.
+ change.log Version-to-version change highlights.
+Programmer and internal documentation:
+ libjpeg.doc How to use the JPEG library in your own programs.
+ example.c Sample code for calling the JPEG library.
+ structure.doc Overview of the JPEG library's internal structure.
+ filelist.doc Road map of IJG files.
+ coderules.doc Coding style rules --- please read if you contribute code.
+
+Please read at least the files install.doc and usage.doc. Useful information
+can also be found in the JPEG FAQ (Frequently Asked Questions) article. See
+ARCHIVE LOCATIONS below to find out where to obtain the FAQ article.
+
+If you want to understand how the JPEG code works, we suggest reading one or
+more of the REFERENCES, then looking at the documentation files (in roughly
+the order listed) before diving into the code.
+
+
+OVERVIEW
+========
+
+This package contains C software to implement JPEG image compression and
+decompression. JPEG (pronounced "jay-peg") is a standardized compression
+method for full-color and gray-scale images. JPEG is intended for compressing
+"real-world" scenes; line drawings, cartoons and other non-realistic images
+are not its strong suit. JPEG is lossy, meaning that the output image is not
+exactly identical to the input image. Hence you must not use JPEG if you
+have to have identical output bits. However, on typical photographic images,
+very good compression levels can be obtained with no visible change, and
+remarkably high compression levels are possible if you can tolerate a
+low-quality image. For more details, see the references, or just experiment
+with various compression settings.
+
+This software implements JPEG baseline, extended-sequential, progressive
+and lossless compression processes. Provision is made for supporting all
+variants of these processes, although some uncommon parameter settings aren't
+implemented yet. For legal reasons, we are not distributing code for the
+arithmetic-coding variants of JPEG; see LEGAL ISSUES. We have made no
+provision for supporting the hierarchical processes defined in the standard.
+
+We provide a set of library routines for reading and writing JPEG image files,
+plus two sample applications "cjpeg" and "djpeg", which use the library to
+perform conversion between JPEG and some other popular image file formats.
+The library is intended to be reused in other applications.
+
+In order to support file conversion and viewing software, we have included
+considerable functionality beyond the bare JPEG coding/decoding capability;
+for example, the color quantization modules are not strictly part of JPEG
+decoding, but they are essential for output to colormapped file formats or
+colormapped displays. These extra functions can be compiled out of the
+library if not required for a particular application. We have also included
+"jpegtran", a utility for lossless transcoding between different JPEG
+processes, and "rdjpgcom" and "wrjpgcom", two simple applications for
+inserting and extracting textual comments in JFIF files.
+
+The emphasis in designing this software has been on achieving portability and
+flexibility, while also making it fast enough to be useful. In particular,
+the software is not intended to be read as a tutorial on JPEG. (See the
+REFERENCES section for introductory material.) Rather, it is intended to
+be reliable, portable, industrial-strength code. We do not claim to have
+achieved that goal in every aspect of the software, but we strive for it.
+
+We welcome the use of this software as a component of commercial products.
+No royalty is required, but we do ask for an acknowledgement in product
+documentation, as described under LEGAL ISSUES.
+
+
+LEGAL ISSUES
+============
+
+In plain English:
+
+1. We don't promise that this software works. (But if you find any bugs,
+ please let us know!)
+2. You can use this software for whatever you want. You don't have to pay us.
+3. You may not pretend that you wrote this software. If you use it in a
+ program, you must acknowledge somewhere in your documentation that
+ you've used the IJG code.
+
+In legalese:
+
+The authors make NO WARRANTY or representation, either express or implied,
+with respect to this software, its quality, accuracy, merchantability, or
+fitness for a particular purpose. This software is provided "AS IS", and you,
+its user, assume the entire risk as to its quality and accuracy.
+
+This software is copyright (C) 1991-1998, Thomas G. Lane.
+All Rights Reserved except as specified below.
+
+Permission is hereby granted to use, copy, modify, and distribute this
+software (or portions thereof) for any purpose, without fee, subject to these
+conditions:
+(1) If any part of the source code for this software is distributed, then this
+README file must be included, with this copyright and no-warranty notice
+unaltered; and any additions, deletions, or changes to the original files
+must be clearly indicated in accompanying documentation.
+(2) If only executable code is distributed, then the accompanying
+documentation must state that "this software is based in part on the work of
+the Independent JPEG Group".
+(3) Permission for use of this software is granted only if the user accepts
+full responsibility for any undesirable consequences; the authors accept
+NO LIABILITY for damages of any kind.
+
+These conditions apply to any software derived from or based on the IJG code,
+not just to the unmodified library. If you use our work, you ought to
+acknowledge us.
+
+Permission is NOT granted for the use of any IJG author's name or company name
+in advertising or publicity relating to this software or products derived from
+it. This software may be referred to only as "the Independent JPEG Group's
+software".
+
+We specifically permit and encourage the use of this software as the basis of
+commercial products, provided that all warranty or liability claims are
+assumed by the product vendor.
+
+
+ansi2knr.c is included in this distribution by permission of L. Peter Deutsch,
+sole proprietor of its copyright holder, Aladdin Enterprises of Menlo Park, CA.
+ansi2knr.c is NOT covered by the above copyright and conditions, but instead
+by the usual distribution terms of the Free Software Foundation; principally,
+that you must include source code if you redistribute it. (See the file
+ansi2knr.c for full details.) However, since ansi2knr.c is not needed as part
+of any program generated from the IJG code, this does not limit you more than
+the foregoing paragraphs do.
+
+The Unix configuration script "configure" was produced with GNU Autoconf.
+It is copyright by the Free Software Foundation but is freely distributable.
+The same holds for its supporting scripts (config.guess, config.sub,
+ltconfig, ltmain.sh). Another support script, install-sh, is copyright
+by M.I.T. but is also freely distributable.
+
+It appears that the arithmetic coding option of the JPEG spec is covered by
+patents owned by IBM, AT&T, and Mitsubishi. Hence arithmetic coding cannot
+legally be used without obtaining one or more licenses. For this reason,
+support for arithmetic coding has been removed from the free JPEG software.
+(Since arithmetic coding provides only a marginal gain over the unpatented
+Huffman mode, it is unlikely that very many implementations will support it.)
+So far as we are aware, there are no patent restrictions on the remaining
+code.
+
+The IJG distribution formerly included code to read and write GIF files.
+To avoid entanglement with the Unisys LZW patent, GIF reading support has
+been removed altogether, and the GIF writer has been simplified to produce
+"uncompressed GIFs". This technique does not use the LZW algorithm; the
+resulting GIF files are larger than usual, but are readable by all standard
+GIF decoders.
+
+We are required to state that
+ "The Graphics Interchange Format(c) is the Copyright property of
+ CompuServe Incorporated. GIF(sm) is a Service Mark property of
+ CompuServe Incorporated."
+
+
+REFERENCES
+==========
+
+We highly recommend reading one or more of these references before trying to
+understand the innards of the JPEG software.
+
+The best short technical introduction to the JPEG compression algorithm is
+ Wallace, Gregory K. "The JPEG Still Picture Compression Standard",
+ Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44.
+(Adjacent articles in that issue discuss MPEG motion picture compression,
+applications of JPEG, and related topics.) If you don't have the CACM issue
+handy, a PostScript file containing a revised version of Wallace's article is
+available at ftp://ftp.uu.net/graphics/jpeg/wallace.ps.gz. The file (actually
+a preprint for an article that appeared in IEEE Trans. Consumer Electronics)
+omits the sample images that appeared in CACM, but it includes corrections
+and some added material. Note: the Wallace article is copyright ACM and IEEE,
+and it may not be used for commercial purposes.
+
+A somewhat less technical, more leisurely introduction to JPEG can be found in
+"The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by
+M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1. This book provides
+good explanations and example C code for a multitude of compression methods
+including JPEG. It is an excellent source if you are comfortable reading C
+code but don't know much about data compression in general. The book's JPEG
+sample code is far from industrial-strength, but when you are ready to look
+at a full implementation, you've got one here...
+
+The best full description of JPEG is the textbook "JPEG Still Image Data
+Compression Standard" by William B. Pennebaker and Joan L. Mitchell, published
+by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1. Price US$59.95, 638 pp.
+The book includes the complete text of the ISO JPEG standards (DIS 10918-1
+and draft DIS 10918-2). This is by far the most complete exposition of JPEG
+in existence, and we highly recommend it.
+
+The JPEG standard itself is not available electronically; you must order a
+paper copy through ISO or ITU. (Unless you feel a need to own a certified
+official copy, we recommend buying the Pennebaker and Mitchell book instead;
+it's much cheaper and includes a great deal of useful explanatory material.)
+In the USA, copies of the standard may be ordered from ANSI Sales at (212)
+642-4900, or from Global Engineering Documents at (800) 854-7179. (ANSI
+doesn't take credit card orders, but Global does.) It's not cheap: as of
+1992, ANSI was charging $95 for Part 1 and $47 for Part 2, plus 7%
+shipping/handling. The standard is divided into two parts, Part 1 being the
+actual specification, while Part 2 covers compliance testing methods. Part 1
+is titled "Digital Compression and Coding of Continuous-tone Still Images,
+Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS
+10918-1, ITU-T T.81. Part 2 is titled "Digital Compression and Coding of
+Continuous-tone Still Images, Part 2: Compliance testing" and has document
+numbers ISO/IEC IS 10918-2, ITU-T T.83.
+
+Some extensions to the original JPEG standard are defined in JPEG Part 3,
+a newer ISO standard numbered ISO/IEC IS 10918-3 and ITU-T T.84. IJG
+currently does not support any Part 3 extensions.
+
+The JPEG standard does not specify all details of an interchangeable file
+format. For the omitted details we follow the "JFIF" conventions, revision
+1.02. A copy of the JFIF spec is available from:
+ Literature Department
+ C-Cube Microsystems, Inc.
+ 1778 McCarthy Blvd.
+ Milpitas, CA 95035
+ phone (408) 944-6300, fax (408) 944-6314
+A PostScript version of this document is available by FTP at
+ftp://ftp.uu.net/graphics/jpeg/jfif.ps.gz. There is also a plain text
+version at ftp://ftp.uu.net/graphics/jpeg/jfif.txt.gz, but it is missing
+the figures.
+
+The TIFF 6.0 file format specification can be obtained by FTP from
+ftp://ftp.sgi.com/graphics/tiff/TIFF6.ps.gz. The JPEG incorporation scheme
+found in the TIFF 6.0 spec of 3-June-92 has a number of serious problems.
+IJG does not recommend use of the TIFF 6.0 design (TIFF Compression tag 6).
+Instead, we recommend the JPEG design proposed by TIFF Technical Note #2
+(Compression tag 7). Copies of this Note can be obtained from ftp.sgi.com or
+from ftp://ftp.uu.net/graphics/jpeg/. It is expected that the next revision
+of the TIFF spec will replace the 6.0 JPEG design with the Note's design.
+Although IJG's own code does not support TIFF/JPEG, the free libtiff library
+uses our library to implement TIFF/JPEG per the Note. libtiff is available
+from ftp://ftp.sgi.com/graphics/tiff/.
+
+
+ARCHIVE LOCATIONS
+=================
+
+The "official" archive site for this software is ftp.uu.net (Internet
+address 192.48.96.9). The most recent released version can always be found
+there in directory graphics/jpeg. This particular version will be archived
+as ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz. If you don't have
+direct Internet access, UUNET's archives are also available via UUCP; contact
+help at uunet.uu.net for information on retrieving files that way.
+
+Numerous Internet sites maintain copies of the UUNET files. However, only
+ftp.uu.net is guaranteed to have the latest official version.
+
+You can also obtain this software in DOS-compatible "zip" archive format from
+the SimTel archives (ftp://ftp.simtel.net/pub/simtelnet/msdos/graphics/), or
+on CompuServe in the Graphics Support forum (GO CIS:GRAPHSUP), library 12
+"JPEG Tools". Again, these versions may sometimes lag behind the ftp.uu.net
+release.
+
+The JPEG FAQ (Frequently Asked Questions) article is a useful source of
+general information about JPEG. It is updated constantly and therefore is
+not included in this distribution. The FAQ is posted every two weeks to
+Usenet newsgroups comp.graphics.misc, news.answers, and other groups.
+It is available on the World Wide Web at http://www.faqs.org/faqs/jpeg-faq/
+and other news.answers archive sites, including the official news.answers
+archive at rtfm.mit.edu: ftp://rtfm.mit.edu/pub/usenet/news.answers/jpeg-faq/.
+If you don't have Web or FTP access, send e-mail to mail-server at rtfm.mit.edu
+with body
+ send usenet/news.answers/jpeg-faq/part1
+ send usenet/news.answers/jpeg-faq/part2
+
+
+RELATED SOFTWARE
+================
+
+Numerous viewing and image manipulation programs now support JPEG. (Quite a
+few of them use this library to do so.) The JPEG FAQ described above lists
+some of the more popular free and shareware viewers, and tells where to
+obtain them on Internet.
+
+If you are on a Unix machine, we highly recommend Jef Poskanzer's free
+PBMPLUS software, which provides many useful operations on PPM-format image
+files. In particular, it can convert PPM images to and from a wide range of
+other formats, thus making cjpeg/djpeg considerably more useful. The latest
+version is distributed by the NetPBM group, and is available from numerous
+sites, notably ftp://wuarchive.wustl.edu/graphics/graphics/packages/NetPBM/.
+Unfortunately PBMPLUS/NETPBM is not nearly as portable as the IJG software is;
+you are likely to have difficulty making it work on any non-Unix machine.
+
+A different free JPEG implementation, written by the PVRG group at Stanford,
+is available from ftp://havefun.stanford.edu/pub/jpeg/. This program
+is designed for research and experimentation rather than production use;
+it is slower, harder to use, and less portable than the IJG code, but it
+is easier to read and modify. Also, the PVRG code supports lossless JPEG,
+which we do not. (On the other hand, it doesn't do progressive JPEG.)
+
+
+FILE FORMAT WARS
+================
+
+Some JPEG programs produce files that are not compatible with our library.
+The root of the problem is that the ISO JPEG committee failed to specify a
+concrete file format. Some vendors "filled in the blanks" on their own,
+creating proprietary formats that no one else could read. (For example, none
+of the early commercial JPEG implementations for the Macintosh were able to
+exchange compressed files.)
+
+The file format we have adopted is called JFIF (see REFERENCES). This format
+has been agreed to by a number of major commercial JPEG vendors, and it has
+become the de facto standard. JFIF is a minimal or "low end" representation.
+We recommend the use of TIFF/JPEG (TIFF revision 6.0 as modified by TIFF
+Technical Note #2) for "high end" applications that need to record a lot of
+additional data about an image. TIFF/JPEG is fairly new and not yet widely
+supported, unfortunately.
+
+The upcoming JPEG Part 3 standard defines a file format called SPIFF.
+SPIFF is interoperable with JFIF, in the sense that most JFIF decoders should
+be able to read the most common variant of SPIFF. SPIFF has some technical
+advantages over JFIF, but its major claim to fame is simply that it is an
+official standard rather than an informal one. At this point it is unclear
+whether SPIFF will supersede JFIF or whether JFIF will remain the de-facto
+standard. IJG intends to support SPIFF once the standard is frozen, but we
+have not decided whether it should become our default output format or not.
+(In any case, our decoder will remain capable of reading JFIF indefinitely.)
+
+Various proprietary file formats incorporating JPEG compression also exist.
+We have little or no sympathy for the existence of these formats. Indeed,
+one of the original reasons for developing this free software was to help
+force convergence on common, open format standards for JPEG files. Don't
+use a proprietary file format!
+
+
+TO DO
+=====
+
+The major thrust for v7 will probably be improvement of visual quality.
+The current method for scaling the quantization tables is known not to be
+very good at low Q values. We also intend to investigate block boundary
+smoothing, "poor man's variable quantization", and other means of improving
+quality-vs-file-size performance without sacrificing compatibility.
+
+In future versions, we are considering supporting some of the upcoming JPEG
+Part 3 extensions --- principally, variable quantization and the SPIFF file
+format.
+
+As always, speeding things up is of great interest.
+
+Please send bug reports, offers of help, etc. to jpeg-info at uunet.uu.net.
diff --git a/jpeg-6c/TODO b/jpeg-6c/TODO
new file mode 100644
index 0000000..9f21066
--- /dev/null
+++ b/jpeg-6c/TODO
@@ -0,0 +1,13 @@
+List of things to complete for lossless codec:
+
+* How to deal with data_precision vs. BITS_PER_JSAMPLE for compression codec.
+
+* Re-visit use of insufficient_data - see jdhuff.c and jdlhuff.c.
+
+* How to check BITS_PER_JSAMPLE for lossy mode (ie, 16-bit data)? -
+ see jdinput.c.
+
+* Check comment blocks for errors/changes.
+
+* Review new filenames. Try to avoid filename conflicts with possible JPEG-LS
+ codec.
diff --git a/jpeg-6c/ansi2knr.1 b/jpeg-6c/ansi2knr.1
new file mode 100644
index 0000000..f9ee5a6
--- /dev/null
+++ b/jpeg-6c/ansi2knr.1
@@ -0,0 +1,36 @@
+.TH ANSI2KNR 1 "19 Jan 1996"
+.SH NAME
+ansi2knr \- convert ANSI C to Kernighan & Ritchie C
+.SH SYNOPSIS
+.I ansi2knr
+[--varargs] input_file [output_file]
+.SH DESCRIPTION
+If no output_file is supplied, output goes to stdout.
+.br
+There are no error messages.
+.sp
+.I ansi2knr
+recognizes function definitions by seeing a non-keyword identifier at the left
+margin, followed by a left parenthesis, with a right parenthesis as the last
+character on the line, and with a left brace as the first token on the
+following line (ignoring possible intervening comments). It will recognize a
+multi-line header provided that no intervening line ends with a left or right
+brace or a semicolon. These algorithms ignore whitespace and comments, except
+that the function name must be the first thing on the line.
+.sp
+The following constructs will confuse it:
+.br
+ - Any other construct that starts at the left margin and follows the
+above syntax (such as a macro or function call).
+.br
+ - Some macros that tinker with the syntax of the function header.
+.sp
+The --varargs switch is obsolete, and is recognized only for
+backwards compatibility. The present version of
+.I ansi2knr
+will always attempt to convert a ... argument to va_alist and va_dcl.
+.SH AUTHOR
+L. Peter Deutsch <ghost at aladdin.com> wrote the original ansi2knr and
+continues to maintain the current version; most of the code in the current
+version is his work. ansi2knr also includes contributions by Francois
+Pinard <pinard at iro.umontreal.ca> and Jim Avera <jima at netcom.com>.
diff --git a/jpeg-6c/ansi2knr.c b/jpeg-6c/ansi2knr.c
new file mode 100644
index 0000000..4e05fc2
--- /dev/null
+++ b/jpeg-6c/ansi2knr.c
@@ -0,0 +1,693 @@
+/* ansi2knr.c */
+/* Convert ANSI C function definitions to K&R ("traditional C") syntax */
+
+/*
+ansi2knr is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY. No author or distributor accepts responsibility to anyone for the
+consequences of using it or for whether it serves any particular purpose or
+works at all, unless he says so in writing. Refer to the GNU General Public
+License (the "GPL") for full details.
+
+Everyone is granted permission to copy, modify and redistribute ansi2knr,
+but only under the conditions described in the GPL. A copy of this license
+is supposed to have been given to you along with ansi2knr so you can know
+your rights and responsibilities. It should be in a file named COPYLEFT.
+[In the IJG distribution, the GPL appears below, not in a separate file.]
+Among other things, the copyright notice and this notice must be preserved
+on all copies.
+
+We explicitly state here what we believe is already implied by the GPL: if
+the ansi2knr program is distributed as a separate set of sources and a
+separate executable file which are aggregated on a storage medium together
+with another program, this in itself does not bring the other program under
+the GPL, nor does the mere fact that such a program or the procedures for
+constructing it invoke the ansi2knr executable bring any other part of the
+program under the GPL.
+*/
+
+/*
+---------- Here is the GNU GPL file COPYLEFT, referred to above ----------
+----- These terms do NOT apply to the JPEG software itself; see README ------
+
+ GHOSTSCRIPT GENERAL PUBLIC LICENSE
+ (Clarified 11 Feb 1988)
+
+ Copyright (C) 1988 Richard M. Stallman
+ Everyone is permitted to copy and distribute verbatim copies of this
+ license, but changing it is not allowed. You can also use this wording
+ to make the terms for other programs.
+
+ The license agreements of most software companies keep you at the
+mercy of those companies. By contrast, our general public license is
+intended to give everyone the right to share Ghostscript. To make sure
+that you get the rights we want you to have, we need to make
+restrictions that forbid anyone to deny you these rights or to ask you
+to surrender the rights. Hence this license agreement.
+
+ Specifically, we want to make sure that you have the right to give
+away copies of Ghostscript, that you receive source code or else can get
+it if you want it, that you can change Ghostscript or use pieces of it
+in new free programs, and that you know you can do these things.
+
+ To make sure that everyone has such rights, we have to forbid you to
+deprive anyone else of these rights. For example, if you distribute
+copies of Ghostscript, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must tell them their rights.
+
+ Also, for our own protection, we must make certain that everyone finds
+out that there is no warranty for Ghostscript. If Ghostscript is
+modified by someone else and passed on, we want its recipients to know
+that what they have is not what we distributed, so that any problems
+introduced by others will not reflect on our reputation.
+
+ Therefore we (Richard M. Stallman and the Free Software Foundation,
+Inc.) make the following terms which say what you must do to be allowed
+to distribute or change Ghostscript.
+
+
+ COPYING POLICIES
+
+ 1. You may copy and distribute verbatim copies of Ghostscript source
+code as you receive it, in any medium, provided that you conspicuously
+and appropriately publish on each copy a valid copyright and license
+notice "Copyright (C) 1989 Aladdin Enterprises. All rights reserved.
+Distributed by Free Software Foundation, Inc." (or with whatever year is
+appropriate); keep intact the notices on all files that refer to this
+License Agreement and to the absence of any warranty; and give any other
+recipients of the Ghostscript program a copy of this License Agreement
+along with the program. You may charge a distribution fee for the
+physical act of transferring a copy.
+
+ 2. You may modify your copy or copies of Ghostscript or any portion of
+it, and copy and distribute such modifications under the terms of
+Paragraph 1 above, provided that you also do the following:
+
+ a) cause the modified files to carry prominent notices stating
+ that you changed the files and the date of any change; and
+
+ b) cause the whole of any work that you distribute or publish,
+ that in whole or in part contains or is a derivative of Ghostscript
+ or any part thereof, to be licensed at no charge to all third
+ parties on terms identical to those contained in this License
+ Agreement (except that you may choose to grant more extensive
+ warranty protection to some or all third parties, at your option).
+
+ c) You may charge a distribution fee for the physical act of
+ transferring a copy, and you may at your option offer warranty
+ protection in exchange for a fee.
+
+Mere aggregation of another unrelated program with this program (or its
+derivative) on a volume of a storage or distribution medium does not bring
+the other program under the scope of these terms.
+
+ 3. You may copy and distribute Ghostscript (or a portion or derivative
+of it, under Paragraph 2) in object code or executable form under the
+terms of Paragraphs 1 and 2 above provided that you also do one of the
+following:
+
+ a) accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of
+ Paragraphs 1 and 2 above; or,
+
+ b) accompany it with a written offer, valid for at least three
+ years, to give any third party free (except for a nominal
+ shipping charge) a complete machine-readable copy of the
+ corresponding source code, to be distributed under the terms of
+ Paragraphs 1 and 2 above; or,
+
+ c) accompany it with the information you received as to where the
+ corresponding source code may be obtained. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form alone.)
+
+For an executable file, complete source code means all the source code for
+all modules it contains; but, as a special exception, it need not include
+source code for modules which are standard libraries that accompany the
+operating system on which the executable file runs.
+
+ 4. You may not copy, sublicense, distribute or transfer Ghostscript
+except as expressly provided under this License Agreement. Any attempt
+otherwise to copy, sublicense, distribute or transfer Ghostscript is
+void and your rights to use the program under this License agreement
+shall be automatically terminated. However, parties who have received
+computer software programs from you with this License Agreement will not
+have their licenses terminated so long as such parties remain in full
+compliance.
+
+ 5. If you wish to incorporate parts of Ghostscript into other free
+programs whose distribution conditions are different, write to the Free
+Software Foundation at 675 Mass Ave, Cambridge, MA 02139. We have not
+yet worked out a simple rule that can be stated here, but we will often
+permit this. We will be guided by the two goals of preserving the free
+status of all derivatives of our free software and of promoting the
+sharing and reuse of software.
+
+Your comments and suggestions about our licensing policies and our
+software are welcome! Please contact the Free Software Foundation,
+Inc., 675 Mass Ave, Cambridge, MA 02139, or call (617) 876-3296.
+
+ NO WARRANTY
+
+ BECAUSE GHOSTSCRIPT IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
+NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW. EXCEPT
+WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC, RICHARD
+M. STALLMAN, ALADDIN ENTERPRISES, L. PETER DEUTSCH, AND/OR OTHER PARTIES
+PROVIDE GHOSTSCRIPT "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
+EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
+ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF GHOSTSCRIPT IS WITH
+YOU. SHOULD GHOSTSCRIPT PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
+NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
+STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., L. PETER DEUTSCH, ALADDIN
+ENTERPRISES, AND/OR ANY OTHER PARTY WHO MAY MODIFY AND REDISTRIBUTE
+GHOSTSCRIPT AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING
+ANY LOST PROFITS, LOST MONIES, OR OTHER SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
+(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
+INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR A FAILURE OF THE
+PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) GHOSTSCRIPT, EVEN IF YOU
+HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR ANY CLAIM
+BY ANY OTHER PARTY.
+
+-------------------- End of file COPYLEFT ------------------------------
+*/
+
+/*
+ * Usage:
+ ansi2knr input_file [output_file]
+ * If no output_file is supplied, output goes to stdout.
+ * There are no error messages.
+ *
+ * ansi2knr recognizes function definitions by seeing a non-keyword
+ * identifier at the left margin, followed by a left parenthesis,
+ * with a right parenthesis as the last character on the line,
+ * and with a left brace as the first token on the following line
+ * (ignoring possible intervening comments).
+ * It will recognize a multi-line header provided that no intervening
+ * line ends with a left or right brace or a semicolon.
+ * These algorithms ignore whitespace and comments, except that
+ * the function name must be the first thing on the line.
+ * The following constructs will confuse it:
+ * - Any other construct that starts at the left margin and
+ * follows the above syntax (such as a macro or function call).
+ * - Some macros that tinker with the syntax of the function header.
+ */
+
+/*
+ * The original and principal author of ansi2knr is L. Peter Deutsch
+ * <ghost at aladdin.com>. Other authors are noted in the change history
+ * that follows (in reverse chronological order):
+ lpd 96-01-21 added code to cope with not HAVE_CONFIG_H and with
+ compilers that don't understand void, as suggested by
+ Tom Lane
+ lpd 96-01-15 changed to require that the first non-comment token
+ on the line following a function header be a left brace,
+ to reduce sensitivity to macros, as suggested by Tom Lane
+ <tgl at sss.pgh.pa.us>
+ lpd 95-06-22 removed #ifndefs whose sole purpose was to define
+ undefined preprocessor symbols as 0; changed all #ifdefs
+ for configuration symbols to #ifs
+ lpd 95-04-05 changed copyright notice to make it clear that
+ including ansi2knr in a program does not bring the entire
+ program under the GPL
+ lpd 94-12-18 added conditionals for systems where ctype macros
+ don't handle 8-bit characters properly, suggested by
+ Francois Pinard <pinard at iro.umontreal.ca>;
+ removed --varargs switch (this is now the default)
+ lpd 94-10-10 removed CONFIG_BROKETS conditional
+ lpd 94-07-16 added some conditionals to help GNU `configure',
+ suggested by Francois Pinard <pinard at iro.umontreal.ca>;
+ properly erase prototype args in function parameters,
+ contributed by Jim Avera <jima at netcom.com>;
+ correct error in writeblanks (it shouldn't erase EOLs)
+ lpd 89-xx-xx original version
+ */
+
+/* Most of the conditionals here are to make ansi2knr work with */
+/* or without the GNU configure machinery. */
+
+#if HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include <stdio.h>
+#include <ctype.h>
+
+#if HAVE_CONFIG_H
+
+/*
+ For properly autoconfiguring ansi2knr, use AC_CONFIG_HEADER(config.h).
+ This will define HAVE_CONFIG_H and so, activate the following lines.
+ */
+
+# if STDC_HEADERS || HAVE_STRING_H
+# include <string.h>
+# else
+# include <strings.h>
+# endif
+
+#else /* not HAVE_CONFIG_H */
+
+/* Otherwise do it the hard way */
+
+# ifdef BSD
+# include <strings.h>
+# else
+# ifdef VMS
+ extern int strlen(), strncmp();
+# else
+# include <string.h>
+# endif
+# endif
+
+#endif /* not HAVE_CONFIG_H */
+
+#if STDC_HEADERS
+# include <stdlib.h>
+#else
+/*
+ malloc and free should be declared in stdlib.h,
+ but if you've got a K&R compiler, they probably aren't.
+ */
+# ifdef MSDOS
+# include <malloc.h>
+# else
+# ifdef VMS
+ extern char *malloc();
+ extern void free();
+# else
+ extern char *malloc();
+ extern int free();
+# endif
+# endif
+
+#endif
+
+/*
+ * The ctype macros don't always handle 8-bit characters correctly.
+ * Compensate for this here.
+ */
+#ifdef isascii
+# undef HAVE_ISASCII /* just in case */
+# define HAVE_ISASCII 1
+#else
+#endif
+#if STDC_HEADERS || !HAVE_ISASCII
+# define is_ascii(c) 1
+#else
+# define is_ascii(c) isascii(c)
+#endif
+
+#define is_space(c) (is_ascii(c) && isspace(c))
+#define is_alpha(c) (is_ascii(c) && isalpha(c))
+#define is_alnum(c) (is_ascii(c) && isalnum(c))
+
+/* Scanning macros */
+#define isidchar(ch) (is_alnum(ch) || (ch) == '_')
+#define isidfirstchar(ch) (is_alpha(ch) || (ch) == '_')
+
+/* Forward references */
+char *skipspace();
+int writeblanks();
+int test1();
+int convert1();
+
+/* The main program */
+int
+main(argc, argv)
+ int argc;
+ char *argv[];
+{ FILE *in, *out;
+#define bufsize 5000 /* arbitrary size */
+ char *buf;
+ char *line;
+ char *more;
+ /*
+ * In previous versions, ansi2knr recognized a --varargs switch.
+ * If this switch was supplied, ansi2knr would attempt to convert
+ * a ... argument to va_alist and va_dcl; if this switch was not
+ * supplied, ansi2knr would simply drop any such arguments.
+ * Now, ansi2knr always does this conversion, and we only
+ * check for this switch for backward compatibility.
+ */
+ int convert_varargs = 1;
+
+ if ( argc > 1 && argv[1][0] == '-' )
+ { if ( !strcmp(argv[1], "--varargs") )
+ { convert_varargs = 1;
+ argc--;
+ argv++;
+ }
+ else
+ { fprintf(stderr, "Unrecognized switch: %s\n", argv[1]);
+ exit(1);
+ }
+ }
+ switch ( argc )
+ {
+ default:
+ printf("Usage: ansi2knr input_file [output_file]\n");
+ exit(0);
+ case 2:
+ out = stdout;
+ break;
+ case 3:
+ out = fopen(argv[2], "w");
+ if ( out == NULL )
+ { fprintf(stderr, "Cannot open output file %s\n", argv[2]);
+ exit(1);
+ }
+ }
+ in = fopen(argv[1], "r");
+ if ( in == NULL )
+ { fprintf(stderr, "Cannot open input file %s\n", argv[1]);
+ exit(1);
+ }
+ fprintf(out, "#line 1 \"%s\"\n", argv[1]);
+ buf = malloc(bufsize);
+ line = buf;
+ while ( fgets(line, (unsigned)(buf + bufsize - line), in) != NULL )
+ {
+test: line += strlen(line);
+ switch ( test1(buf) )
+ {
+ case 2: /* a function header */
+ convert1(buf, out, 1, convert_varargs);
+ break;
+ case 1: /* a function */
+ /* Check for a { at the start of the next line. */
+ more = ++line;
+f: if ( line >= buf + (bufsize - 1) ) /* overflow check */
+ goto wl;
+ if ( fgets(line, (unsigned)(buf + bufsize - line), in) == NULL )
+ goto wl;
+ switch ( *skipspace(more, 1) )
+ {
+ case '{':
+ /* Definitely a function header. */
+ convert1(buf, out, 0, convert_varargs);
+ fputs(more, out);
+ break;
+ case 0:
+ /* The next line was blank or a comment: */
+ /* keep scanning for a non-comment. */
+ line += strlen(line);
+ goto f;
+ default:
+ /* buf isn't a function header, but */
+ /* more might be. */
+ fputs(buf, out);
+ strcpy(buf, more);
+ line = buf;
+ goto test;
+ }
+ break;
+ case -1: /* maybe the start of a function */
+ if ( line != buf + (bufsize - 1) ) /* overflow check */
+ continue;
+ /* falls through */
+ default: /* not a function */
+wl: fputs(buf, out);
+ break;
+ }
+ line = buf;
+ }
+ if ( line != buf )
+ fputs(buf, out);
+ free(buf);
+ fclose(out);
+ fclose(in);
+ return 0;
+}
+
+/* Skip over space and comments, in either direction. */
+char *
+skipspace(p, dir)
+ register char *p;
+ register int dir; /* 1 for forward, -1 for backward */
+{ for ( ; ; )
+ { while ( is_space(*p) )
+ p += dir;
+ if ( !(*p == '/' && p[dir] == '*') )
+ break;
+ p += dir; p += dir;
+ while ( !(*p == '*' && p[dir] == '/') )
+ { if ( *p == 0 )
+ return p; /* multi-line comment?? */
+ p += dir;
+ }
+ p += dir; p += dir;
+ }
+ return p;
+}
+
+/*
+ * Write blanks over part of a string.
+ * Don't overwrite end-of-line characters.
+ */
+int
+writeblanks(start, end)
+ char *start;
+ char *end;
+{ char *p;
+ for ( p = start; p < end; p++ )
+ if ( *p != '\r' && *p != '\n' )
+ *p = ' ';
+ return 0;
+}
+
+/*
+ * Test whether the string in buf is a function definition.
+ * The string may contain and/or end with a newline.
+ * Return as follows:
+ * 0 - definitely not a function definition;
+ * 1 - definitely a function definition;
+ * 2 - definitely a function prototype (NOT USED);
+ * -1 - may be the beginning of a function definition,
+ * append another line and look again.
+ * The reason we don't attempt to convert function prototypes is that
+ * Ghostscript's declaration-generating macros look too much like
+ * prototypes, and confuse the algorithms.
+ */
+int
+test1(buf)
+ char *buf;
+{ register char *p = buf;
+ char *bend;
+ char *endfn;
+ int contin;
+
+ if ( !isidfirstchar(*p) )
+ return 0; /* no name at left margin */
+ bend = skipspace(buf + strlen(buf) - 1, -1);
+ switch ( *bend )
+ {
+ case ';': contin = 0 /*2*/; break;
+ case ')': contin = 1; break;
+ case '{': return 0; /* not a function */
+ case '}': return 0; /* not a function */
+ default: contin = -1;
+ }
+ while ( isidchar(*p) )
+ p++;
+ endfn = p;
+ p = skipspace(p, 1);
+ if ( *p++ != '(' )
+ return 0; /* not a function */
+ p = skipspace(p, 1);
+ if ( *p == ')' )
+ return 0; /* no parameters */
+ /* Check that the apparent function name isn't a keyword. */
+ /* We only need to check for keywords that could be followed */
+ /* by a left parenthesis (which, unfortunately, is most of them). */
+ { static char *words[] =
+ { "asm", "auto", "case", "char", "const", "double",
+ "extern", "float", "for", "if", "int", "long",
+ "register", "return", "short", "signed", "sizeof",
+ "static", "switch", "typedef", "unsigned",
+ "void", "volatile", "while", 0
+ };
+ char **key = words;
+ char *kp;
+ int len = endfn - buf;
+
+ while ( (kp = *key) != 0 )
+ { if ( strlen(kp) == len && !strncmp(kp, buf, len) )
+ return 0; /* name is a keyword */
+ key++;
+ }
+ }
+ return contin;
+}
+
+/* Convert a recognized function definition or header to K&R syntax. */
+int
+convert1(buf, out, header, convert_varargs)
+ char *buf;
+ FILE *out;
+ int header; /* Boolean */
+ int convert_varargs; /* Boolean */
+{ char *endfn;
+ register char *p;
+ char **breaks;
+ unsigned num_breaks = 2; /* for testing */
+ char **btop;
+ char **bp;
+ char **ap;
+ char *vararg = 0;
+
+ /* Pre-ANSI implementations don't agree on whether strchr */
+ /* is called strchr or index, so we open-code it here. */
+ for ( endfn = buf; *(endfn++) != '('; )
+ ;
+top: p = endfn;
+ breaks = (char **)malloc(sizeof(char *) * num_breaks * 2);
+ if ( breaks == 0 )
+ { /* Couldn't allocate break table, give up */
+ fprintf(stderr, "Unable to allocate break table!\n");
+ fputs(buf, out);
+ return -1;
+ }
+ btop = breaks + num_breaks * 2 - 2;
+ bp = breaks;
+ /* Parse the argument list */
+ do
+ { int level = 0;
+ char *lp = NULL;
+ char *rp;
+ char *end = NULL;
+
+ if ( bp >= btop )
+ { /* Filled up break table. */
+ /* Allocate a bigger one and start over. */
+ free((char *)breaks);
+ num_breaks <<= 1;
+ goto top;
+ }
+ *bp++ = p;
+ /* Find the end of the argument */
+ for ( ; end == NULL; p++ )
+ { switch(*p)
+ {
+ case ',':
+ if ( !level ) end = p;
+ break;
+ case '(':
+ if ( !level ) lp = p;
+ level++;
+ break;
+ case ')':
+ if ( --level < 0 ) end = p;
+ else rp = p;
+ break;
+ case '/':
+ p = skipspace(p, 1) - 1;
+ break;
+ default:
+ ;
+ }
+ }
+ /* Erase any embedded prototype parameters. */
+ if ( lp )
+ writeblanks(lp + 1, rp);
+ p--; /* back up over terminator */
+ /* Find the name being declared. */
+ /* This is complicated because of procedure and */
+ /* array modifiers. */
+ for ( ; ; )
+ { p = skipspace(p - 1, -1);
+ switch ( *p )
+ {
+ case ']': /* skip array dimension(s) */
+ case ')': /* skip procedure args OR name */
+ { int level = 1;
+ while ( level )
+ switch ( *--p )
+ {
+ case ']': case ')': level++; break;
+ case '[': case '(': level--; break;
+ case '/': p = skipspace(p, -1) + 1; break;
+ default: ;
+ }
+ }
+ if ( *p == '(' && *skipspace(p + 1, 1) == '*' )
+ { /* We found the name being declared */
+ while ( !isidfirstchar(*p) )
+ p = skipspace(p, 1) + 1;
+ goto found;
+ }
+ break;
+ default:
+ goto found;
+ }
+ }
+found: if ( *p == '.' && p[-1] == '.' && p[-2] == '.' )
+ { if ( convert_varargs )
+ { *bp++ = "va_alist";
+ vararg = p-2;
+ }
+ else
+ { p++;
+ if ( bp == breaks + 1 ) /* sole argument */
+ writeblanks(breaks[0], p);
+ else
+ writeblanks(bp[-1] - 1, p);
+ bp--;
+ }
+ }
+ else
+ { while ( isidchar(*p) ) p--;
+ *bp++ = p+1;
+ }
+ p = end;
+ }
+ while ( *p++ == ',' );
+ *bp = p;
+ /* Make a special check for 'void' arglist */
+ if ( bp == breaks+2 )
+ { p = skipspace(breaks[0], 1);
+ if ( !strncmp(p, "void", 4) )
+ { p = skipspace(p+4, 1);
+ if ( p == breaks[2] - 1 )
+ { bp = breaks; /* yup, pretend arglist is empty */
+ writeblanks(breaks[0], p + 1);
+ }
+ }
+ }
+ /* Put out the function name and left parenthesis. */
+ p = buf;
+ while ( p != endfn ) putc(*p, out), p++;
+ /* Put out the declaration. */
+ if ( header )
+ { fputs(");", out);
+ for ( p = breaks[0]; *p; p++ )
+ if ( *p == '\r' || *p == '\n' )
+ putc(*p, out);
+ }
+ else
+ { for ( ap = breaks+1; ap < bp; ap += 2 )
+ { p = *ap;
+ while ( isidchar(*p) )
+ putc(*p, out), p++;
+ if ( ap < bp - 1 )
+ fputs(", ", out);
+ }
+ fputs(") ", out);
+ /* Put out the argument declarations */
+ for ( ap = breaks+2; ap <= bp; ap += 2 )
+ (*ap)[-1] = ';';
+ if ( vararg != 0 )
+ { *vararg = 0;
+ fputs(breaks[0], out); /* any prior args */
+ fputs("va_dcl", out); /* the final arg */
+ fputs(bp[0], out);
+ }
+ else
+ fputs(breaks[0], out);
+ }
+ free((char *)breaks);
+ return 0;
+}
diff --git a/jpeg-6c/cderror.h b/jpeg-6c/cderror.h
new file mode 100644
index 0000000..273072f
--- /dev/null
+++ b/jpeg-6c/cderror.h
@@ -0,0 +1,134 @@
+/*
+ * cderror.h
+ *
+ * Copyright (C) 1994-1997, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file defines the error and message codes for the cjpeg/djpeg
+ * applications. These strings are not needed as part of the JPEG library
+ * proper.
+ * Edit this file to add new codes, or to translate the message strings to
+ * some other language.
+ */
+
+/*
+ * To define the enum list of message codes, include this file without
+ * defining macro JMESSAGE. To create a message string table, include it
+ * again with a suitable JMESSAGE definition (see jerror.c for an example).
+ */
+#ifndef JMESSAGE
+#ifndef CDERROR_H
+#define CDERROR_H
+/* First time through, define the enum list */
+#define JMAKE_ENUM_LIST
+#else
+/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
+#define JMESSAGE(code,string)
+#endif /* CDERROR_H */
+#endif /* JMESSAGE */
+
+#ifdef JMAKE_ENUM_LIST
+
+typedef enum {
+
+#define JMESSAGE(code,string) code ,
+
+#endif /* JMAKE_ENUM_LIST */
+
+JMESSAGE(JMSG_FIRSTADDONCODE=1000, NULL) /* Must be first entry! */
+
+#ifdef BMP_SUPPORTED
+JMESSAGE(JERR_BMP_BADCMAP, "Unsupported BMP colormap format")
+JMESSAGE(JERR_BMP_BADDEPTH, "Only 8- and 24-bit BMP files are supported")
+JMESSAGE(JERR_BMP_BADHEADER, "Invalid BMP file: bad header length")
+JMESSAGE(JERR_BMP_BADPLANES, "Invalid BMP file: biPlanes not equal to 1")
+JMESSAGE(JERR_BMP_COLORSPACE, "BMP output must be grayscale or RGB")
+JMESSAGE(JERR_BMP_COMPRESSED, "Sorry, compressed BMPs not yet supported")
+JMESSAGE(JERR_BMP_NOT, "Not a BMP file - does not start with BM")
+JMESSAGE(JTRC_BMP, "%ux%u 24-bit BMP image")
+JMESSAGE(JTRC_BMP_MAPPED, "%ux%u 8-bit colormapped BMP image")
+JMESSAGE(JTRC_BMP_OS2, "%ux%u 24-bit OS2 BMP image")
+JMESSAGE(JTRC_BMP_OS2_MAPPED, "%ux%u 8-bit colormapped OS2 BMP image")
+#endif /* BMP_SUPPORTED */
+
+#ifdef GIF_SUPPORTED
+JMESSAGE(JERR_GIF_BUG, "GIF output got confused")
+JMESSAGE(JERR_GIF_CODESIZE, "Bogus GIF codesize %d")
+JMESSAGE(JERR_GIF_COLORSPACE, "GIF output must be grayscale or RGB")
+JMESSAGE(JERR_GIF_IMAGENOTFOUND, "Too few images in GIF file")
+JMESSAGE(JERR_GIF_NOT, "Not a GIF file")
+JMESSAGE(JTRC_GIF, "%ux%ux%d GIF image")
+JMESSAGE(JTRC_GIF_BADVERSION,
+ "Warning: unexpected GIF version number '%c%c%c'")
+JMESSAGE(JTRC_GIF_EXTENSION, "Ignoring GIF extension block of type 0x%02x")
+JMESSAGE(JTRC_GIF_NONSQUARE, "Caution: nonsquare pixels in input")
+JMESSAGE(JWRN_GIF_BADDATA, "Corrupt data in GIF file")
+JMESSAGE(JWRN_GIF_CHAR, "Bogus char 0x%02x in GIF file, ignoring")
+JMESSAGE(JWRN_GIF_ENDCODE, "Premature end of GIF image")
+JMESSAGE(JWRN_GIF_NOMOREDATA, "Ran out of GIF bits")
+#endif /* GIF_SUPPORTED */
+
+#ifdef PPM_SUPPORTED
+JMESSAGE(JERR_PPM_COLORSPACE, "PPM output must be grayscale or RGB")
+JMESSAGE(JERR_PPM_NONNUMERIC, "Nonnumeric data in PPM file")
+JMESSAGE(JERR_PPM_NOT, "Not a PPM/PGM file")
+JMESSAGE(JERR_PPM_ONLY, "-width for use only width a PPM file")
+JMESSAGE(JTRC_PGM, "%ux%u PGM image")
+JMESSAGE(JTRC_PGM_TEXT, "%ux%u text PGM image")
+JMESSAGE(JTRC_PPM, "%ux%u PPM image")
+JMESSAGE(JTRC_PPM_TEXT, "%ux%u text PPM image")
+#endif /* PPM_SUPPORTED */
+
+#ifdef RLE_SUPPORTED
+JMESSAGE(JERR_RLE_BADERROR, "Bogus error code from RLE library")
+JMESSAGE(JERR_RLE_COLORSPACE, "RLE output must be grayscale or RGB")
+JMESSAGE(JERR_RLE_DIMENSIONS, "Image dimensions (%ux%u) too large for RLE")
+JMESSAGE(JERR_RLE_EMPTY, "Empty RLE file")
+JMESSAGE(JERR_RLE_EOF, "Premature EOF in RLE header")
+JMESSAGE(JERR_RLE_MEM, "Insufficient memory for RLE header")
+JMESSAGE(JERR_RLE_NOT, "Not an RLE file")
+JMESSAGE(JERR_RLE_TOOMANYCHANNELS, "Cannot handle %d output channels for RLE")
+JMESSAGE(JERR_RLE_UNSUPPORTED, "Cannot handle this RLE setup")
+JMESSAGE(JTRC_RLE, "%ux%u full-color RLE file")
+JMESSAGE(JTRC_RLE_FULLMAP, "%ux%u full-color RLE file with map of length %d")
+JMESSAGE(JTRC_RLE_GRAY, "%ux%u grayscale RLE file")
+JMESSAGE(JTRC_RLE_MAPGRAY, "%ux%u grayscale RLE file with map of length %d")
+JMESSAGE(JTRC_RLE_MAPPED, "%ux%u colormapped RLE file with map of length %d")
+#endif /* RLE_SUPPORTED */
+
+#ifdef TARGA_SUPPORTED
+JMESSAGE(JERR_TGA_BADCMAP, "Unsupported Targa colormap format")
+JMESSAGE(JERR_TGA_BADPARMS, "Invalid or unsupported Targa file")
+JMESSAGE(JERR_TGA_COLORSPACE, "Targa output must be grayscale or RGB")
+JMESSAGE(JTRC_TGA, "%ux%u RGB Targa image")
+JMESSAGE(JTRC_TGA_GRAY, "%ux%u grayscale Targa image")
+JMESSAGE(JTRC_TGA_MAPPED, "%ux%u colormapped Targa image")
+#else
+JMESSAGE(JERR_TGA_NOTCOMP, "Targa support was not compiled")
+#endif /* TARGA_SUPPORTED */
+
+JMESSAGE(JERR_BAD_CMAP_FILE,
+ "Color map file is invalid or of unsupported format")
+JMESSAGE(JERR_TOO_MANY_COLORS,
+ "Output file format cannot handle %d colormap entries")
+JMESSAGE(JERR_UNGETC_FAILED, "ungetc failed")
+#ifdef TARGA_SUPPORTED
+JMESSAGE(JERR_UNKNOWN_FORMAT,
+ "Unrecognized input file format --- perhaps you need -targa")
+#else
+JMESSAGE(JERR_UNKNOWN_FORMAT, "Unrecognized input file format")
+#endif
+JMESSAGE(JERR_UNSUPPORTED_FORMAT, "Unsupported output file format")
+
+#ifdef JMAKE_ENUM_LIST
+
+ JMSG_LASTADDONCODE
+} ADDON_MESSAGE_CODE;
+
+#undef JMAKE_ENUM_LIST
+#endif /* JMAKE_ENUM_LIST */
+
+/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
+#undef JMESSAGE
diff --git a/jpeg-6c/cdjpeg.c b/jpeg-6c/cdjpeg.c
new file mode 100644
index 0000000..b6250ff
--- /dev/null
+++ b/jpeg-6c/cdjpeg.c
@@ -0,0 +1,181 @@
+/*
+ * cdjpeg.c
+ *
+ * Copyright (C) 1991-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains common support routines used by the IJG application
+ * programs (cjpeg, djpeg, jpegtran).
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+#include <ctype.h> /* to declare isupper(), tolower() */
+#ifdef NEED_SIGNAL_CATCHER
+#include <signal.h> /* to declare signal() */
+#endif
+#ifdef USE_SETMODE
+#include <fcntl.h> /* to declare setmode()'s parameter macros */
+/* If you have setmode() but not <io.h>, just delete this line: */
+#include <io.h> /* to declare setmode() */
+#endif
+
+
+/*
+ * Signal catcher to ensure that temporary files are removed before aborting.
+ * NB: for Amiga Manx C this is actually a global routine named _abort();
+ * we put "#define signal_catcher _abort" in jconfig.h. Talk about bogus...
+ */
+
+#ifdef NEED_SIGNAL_CATCHER
+
+static j_common_ptr sig_cinfo;
+
+void /* must be global for Manx C */
+signal_catcher (int signum)
+{
+ if (sig_cinfo != NULL) {
+ if (sig_cinfo->err != NULL) /* turn off trace output */
+ sig_cinfo->err->trace_level = 0;
+ jpeg_destroy(sig_cinfo); /* clean up memory allocation & temp files */
+ }
+ exit(EXIT_FAILURE);
+}
+
+
+GLOBAL(void)
+enable_signal_catcher (j_common_ptr cinfo)
+{
+ sig_cinfo = cinfo;
+#ifdef SIGINT /* not all systems have SIGINT */
+ signal(SIGINT, signal_catcher);
+#endif
+#ifdef SIGTERM /* not all systems have SIGTERM */
+ signal(SIGTERM, signal_catcher);
+#endif
+}
+
+#endif
+
+
+/*
+ * Optional progress monitor: display a percent-done figure on stderr.
+ */
+
+#ifdef PROGRESS_REPORT
+
+METHODDEF(void)
+progress_monitor (j_common_ptr cinfo)
+{
+ cd_progress_ptr prog = (cd_progress_ptr) cinfo->progress;
+ int total_passes = prog->pub.total_passes + prog->total_extra_passes;
+ int percent_done = (int) (prog->pub.pass_counter*100L/prog->pub.pass_limit);
+
+ if (percent_done != prog->percent_done) {
+ prog->percent_done = percent_done;
+ if (total_passes > 1) {
+ fprintf(stderr, "\rPass %d/%d: %3d%% ",
+ prog->pub.completed_passes + prog->completed_extra_passes + 1,
+ total_passes, percent_done);
+ } else {
+ fprintf(stderr, "\r %3d%% ", percent_done);
+ }
+ fflush(stderr);
+ }
+}
+
+
+GLOBAL(void)
+start_progress_monitor (j_common_ptr cinfo, cd_progress_ptr progress)
+{
+ /* Enable progress display, unless trace output is on */
+ if (cinfo->err->trace_level == 0) {
+ progress->pub.progress_monitor = progress_monitor;
+ progress->completed_extra_passes = 0;
+ progress->total_extra_passes = 0;
+ progress->percent_done = -1;
+ cinfo->progress = &progress->pub;
+ }
+}
+
+
+GLOBAL(void)
+end_progress_monitor (j_common_ptr cinfo)
+{
+ /* Clear away progress display */
+ if (cinfo->err->trace_level == 0) {
+ fprintf(stderr, "\r \r");
+ fflush(stderr);
+ }
+}
+
+#endif
+
+
+/*
+ * Case-insensitive matching of possibly-abbreviated keyword switches.
+ * keyword is the constant keyword (must be lower case already),
+ * minchars is length of minimum legal abbreviation.
+ */
+
+GLOBAL(boolean)
+keymatch (char * arg, const char * keyword, int minchars)
+{
+ register int ca, ck;
+ register int nmatched = 0;
+
+ while ((ca = *arg++) != '\0') {
+ if ((ck = *keyword++) == '\0')
+ return FALSE; /* arg longer than keyword, no good */
+ if (isupper(ca)) /* force arg to lcase (assume ck is already) */
+ ca = tolower(ca);
+ if (ca != ck)
+ return FALSE; /* no good */
+ nmatched++; /* count matched characters */
+ }
+ /* reached end of argument; fail if it's too short for unique abbrev */
+ if (nmatched < minchars)
+ return FALSE;
+ return TRUE; /* A-OK */
+}
+
+
+/*
+ * Routines to establish binary I/O mode for stdin and stdout.
+ * Non-Unix systems often require some hacking to get out of text mode.
+ */
+
+GLOBAL(FILE *)
+read_stdin (void)
+{
+ FILE * input_file = stdin;
+
+#ifdef USE_SETMODE /* need to hack file mode? */
+ setmode(fileno(stdin), O_BINARY);
+#endif
+#ifdef USE_FDOPEN /* need to re-open in binary mode? */
+ if ((input_file = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
+ fprintf(stderr, "Cannot reopen stdin\n");
+ exit(EXIT_FAILURE);
+ }
+#endif
+ return input_file;
+}
+
+
+GLOBAL(FILE *)
+write_stdout (void)
+{
+ FILE * output_file = stdout;
+
+#ifdef USE_SETMODE /* need to hack file mode? */
+ setmode(fileno(stdout), O_BINARY);
+#endif
+#ifdef USE_FDOPEN /* need to re-open in binary mode? */
+ if ((output_file = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) {
+ fprintf(stderr, "Cannot reopen stdout\n");
+ exit(EXIT_FAILURE);
+ }
+#endif
+ return output_file;
+}
diff --git a/jpeg-6c/cdjpeg.h b/jpeg-6c/cdjpeg.h
new file mode 100644
index 0000000..df9fec5
--- /dev/null
+++ b/jpeg-6c/cdjpeg.h
@@ -0,0 +1,191 @@
+/*
+ * cdjpeg.h
+ *
+ * Copyright (C) 1994-1997, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains common declarations for the sample applications
+ * cjpeg and djpeg. It is NOT used by the core JPEG library.
+ */
+
+#define JPEG_CJPEG_DJPEG /* define proper options in jconfig.h */
+#define JPEG_INTERNAL_OPTIONS /* cjpeg.c,djpeg.c need to see xxx_SUPPORTED */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jerror.h" /* get library error codes too */
+#include "cderror.h" /* get application-specific error codes */
+
+
+/*
+ * Object interface for cjpeg's source file decoding modules
+ */
+
+typedef struct cjpeg_source_struct * cjpeg_source_ptr;
+
+struct cjpeg_source_struct {
+ JMETHOD(void, start_input, (j_compress_ptr cinfo,
+ cjpeg_source_ptr sinfo));
+ JMETHOD(JDIMENSION, get_pixel_rows, (j_compress_ptr cinfo,
+ cjpeg_source_ptr sinfo));
+ JMETHOD(void, finish_input, (j_compress_ptr cinfo,
+ cjpeg_source_ptr sinfo));
+
+ FILE *input_file;
+
+ JSAMPARRAY buffer;
+ JDIMENSION buffer_height;
+};
+
+
+/*
+ * Object interface for djpeg's output file encoding modules
+ */
+
+typedef struct djpeg_dest_struct * djpeg_dest_ptr;
+
+struct djpeg_dest_struct {
+ /* start_output is called after jpeg_start_decompress finishes.
+ * The color map will be ready at this time, if one is needed.
+ */
+ JMETHOD(void, start_output, (j_decompress_ptr cinfo,
+ djpeg_dest_ptr dinfo));
+ /* Emit the specified number of pixel rows from the buffer. */
+ JMETHOD(void, put_pixel_rows, (j_decompress_ptr cinfo,
+ djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied));
+ /* Finish up at the end of the image. */
+ JMETHOD(void, finish_output, (j_decompress_ptr cinfo,
+ djpeg_dest_ptr dinfo));
+
+ /* Target file spec; filled in by djpeg.c after object is created. */
+ FILE * output_file;
+
+ /* Output pixel-row buffer. Created by module init or start_output.
+ * Width is cinfo->output_width * cinfo->output_components;
+ * height is buffer_height.
+ */
+ JSAMPARRAY buffer;
+ JDIMENSION buffer_height;
+};
+
+
+/*
+ * cjpeg/djpeg may need to perform extra passes to convert to or from
+ * the source/destination file format. The JPEG library does not know
+ * about these passes, but we'd like them to be counted by the progress
+ * monitor. We use an expanded progress monitor object to hold the
+ * additional pass count.
+ */
+
+struct cdjpeg_progress_mgr {
+ struct jpeg_progress_mgr pub; /* fields known to JPEG library */
+ int completed_extra_passes; /* extra passes completed */
+ int total_extra_passes; /* total extra */
+ /* last printed percentage stored here to avoid multiple printouts */
+ int percent_done;
+};
+
+typedef struct cdjpeg_progress_mgr * cd_progress_ptr;
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jinit_read_bmp jIRdBMP
+#define jinit_write_bmp jIWrBMP
+#define jinit_read_gif jIRdGIF
+#define jinit_write_gif jIWrGIF
+#define jinit_read_ppm jIRdPPM
+#define jinit_write_ppm jIWrPPM
+#define jinit_read_rle jIRdRLE
+#define jinit_write_rle jIWrRLE
+#define jinit_read_targa jIRdTarga
+#define jinit_write_targa jIWrTarga
+#define read_quant_tables RdQTables
+#define read_scan_script RdScnScript
+#define set_quant_slots SetQSlots
+#define set_sample_factors SetSFacts
+#define read_color_map RdCMap
+#define enable_signal_catcher EnSigCatcher
+#define start_progress_monitor StProgMon
+#define end_progress_monitor EnProgMon
+#define read_stdin RdStdin
+#define write_stdout WrStdout
+#ifdef C_LOSSLESS_SUPPORTED
+#define set_simple_lossless SetSplLs
+#endif
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+/* Module selection routines for I/O modules. */
+
+EXTERN(cjpeg_source_ptr) jinit_read_bmp JPP((j_compress_ptr cinfo));
+EXTERN(djpeg_dest_ptr) jinit_write_bmp JPP((j_decompress_ptr cinfo,
+ boolean is_os2));
+EXTERN(cjpeg_source_ptr) jinit_read_gif JPP((j_compress_ptr cinfo));
+EXTERN(djpeg_dest_ptr) jinit_write_gif JPP((j_decompress_ptr cinfo));
+EXTERN(cjpeg_source_ptr) jinit_read_ppm JPP((j_compress_ptr cinfo));
+EXTERN(djpeg_dest_ptr) jinit_write_ppm JPP((j_decompress_ptr cinfo));
+EXTERN(cjpeg_source_ptr) jinit_read_rle JPP((j_compress_ptr cinfo));
+EXTERN(djpeg_dest_ptr) jinit_write_rle JPP((j_decompress_ptr cinfo));
+EXTERN(cjpeg_source_ptr) jinit_read_targa JPP((j_compress_ptr cinfo));
+EXTERN(djpeg_dest_ptr) jinit_write_targa JPP((j_decompress_ptr cinfo));
+
+/* cjpeg support routines (in rdswitch.c) */
+
+EXTERN(boolean) read_quant_tables JPP((j_compress_ptr cinfo, char * filename,
+ int scale_factor, boolean force_baseline));
+EXTERN(boolean) read_scan_script JPP((j_compress_ptr cinfo, char * filename));
+EXTERN(boolean) set_quant_slots JPP((j_compress_ptr cinfo, char *arg));
+EXTERN(boolean) set_sample_factors JPP((j_compress_ptr cinfo, char *arg));
+#ifdef C_LOSSLESS_SUPPORTED
+EXTERN(boolean) set_simple_lossless JPP((j_compress_ptr cinfo, char *arg));
+#endif
+
+/* djpeg support routines (in rdcolmap.c) */
+
+EXTERN(void) read_color_map JPP((j_decompress_ptr cinfo, FILE * infile));
+
+/* common support routines (in cdjpeg.c) */
+
+EXTERN(void) enable_signal_catcher JPP((j_common_ptr cinfo));
+EXTERN(void) start_progress_monitor JPP((j_common_ptr cinfo,
+ cd_progress_ptr progress));
+EXTERN(void) end_progress_monitor JPP((j_common_ptr cinfo));
+EXTERN(boolean) keymatch JPP((char * arg, const char * keyword, int minchars));
+EXTERN(FILE *) read_stdin JPP((void));
+EXTERN(FILE *) write_stdout JPP((void));
+
+/* miscellaneous useful macros */
+
+#ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
+#define READ_BINARY "r"
+#define WRITE_BINARY "w"
+#else
+#ifdef VMS /* VMS is very nonstandard */
+#define READ_BINARY "rb", "ctx=stm"
+#define WRITE_BINARY "wb", "ctx=stm"
+#else /* standard ANSI-compliant case */
+#define READ_BINARY "rb"
+#define WRITE_BINARY "wb"
+#endif
+#endif
+
+#ifndef EXIT_FAILURE /* define exit() codes if not provided */
+#define EXIT_FAILURE 1
+#endif
+#ifndef EXIT_SUCCESS
+#ifdef VMS
+#define EXIT_SUCCESS 1 /* VMS is very nonstandard */
+#else
+#define EXIT_SUCCESS 0
+#endif
+#endif
+#ifndef EXIT_WARNING
+#ifdef VMS
+#define EXIT_WARNING 1 /* VMS is very nonstandard */
+#else
+#define EXIT_WARNING 2
+#endif
+#endif
diff --git a/jpeg-6c/change.log b/jpeg-6c/change.log
new file mode 100644
index 0000000..67e4277
--- /dev/null
+++ b/jpeg-6c/change.log
@@ -0,0 +1,229 @@
+CHANGE LOG for Independent JPEG Group's JPEG software
+
+
+Version 7 29-Jun-2009
+-----------------------
+
+Multi-bit, the bit with can now be set "on the fly".
+
+Unisys LZW patent expired, djpeg's GIF output capability has been
+restored.
+
+cjpeg and djpeg handle different bit widths for PPM.
+
+Lossless and cropping now included without a patch.
+
+Version 6b 27-Mar-1998
+-----------------------
+
+jpegtran has new features for lossless image transformations (rotation
+and flipping) as well as "lossless" reduction to grayscale.
+
+jpegtran now copies comments by default; it has a -copy switch to enable
+copying all APPn blocks as well, or to suppress comments. (Formerly it
+always suppressed comments and APPn blocks.) jpegtran now also preserves
+JFIF version and resolution information.
+
+New decompressor library feature: COM and APPn markers found in the input
+file can be saved in memory for later use by the application. (Before,
+you had to code this up yourself with a custom marker processor.)
+
+There is an unused field "void * client_data" now in compress and decompress
+parameter structs; this may be useful in some applications.
+
+JFIF version number information is now saved by the decoder and accepted by
+the encoder. jpegtran uses this to copy the source file's version number,
+to ensure "jpegtran -copy all" won't create bogus files that contain JFXX
+extensions but claim to be version 1.01. Applications that generate their
+own JFXX extension markers also (finally) have a supported way to cause the
+encoder to emit JFIF version number 1.02.
+
+djpeg's trace mode reports JFIF 1.02 thumbnail images as such, rather
+than as unknown APP0 markers.
+
+In -verbose mode, djpeg and rdjpgcom will try to print the contents of
+APP12 markers as text. Some digital cameras store useful text information
+in APP12 markers.
+
+Handling of truncated data streams is more robust: blocks beyond the one in
+which the error occurs will be output as uniform gray, or left unchanged
+if decoding a progressive JPEG. The appearance no longer depends on the
+Huffman tables being used.
+
+Huffman tables are checked for validity much more carefully than before.
+
+To avoid the Unisys LZW patent, djpeg's GIF output capability has been
+changed to produce "uncompressed GIFs", and cjpeg's GIF input capability
+has been removed altogether. We're not happy about it either, but there
+seems to be no good alternative.
+
+The configure script now supports building libjpeg as a shared library
+on many flavors of Unix (all the ones that GNU libtool knows how to
+build shared libraries for). Use "./configure --enable-shared" to
+try this out.
+
+New jconfig file and makefiles for Microsoft Visual C++ and Developer Studio.
+Also, a jconfig file and a build script for Metrowerks CodeWarrior
+on Apple Macintosh. makefile.dj has been updated for DJGPP v2, and there
+are miscellaneous other minor improvements in the makefiles.
+
+jmemmac.c now knows how to create temporary files following Mac System 7
+conventions.
+
+djpeg's -map switch is now able to read raw-format PPM files reliably.
+
+cjpeg -progressive -restart no longer generates any unnecessary DRI markers.
+
+Multiple calls to jpeg_simple_progression for a single JPEG object
+no longer leak memory.
+
+
+Version 6a 7-Feb-96
+--------------------
+
+Library initialization sequence modified to detect version mismatches
+and struct field packing mismatches between library and calling application.
+This change requires applications to be recompiled, but does not require
+any application source code change.
+
+All routine declarations changed to the style "GLOBAL(type) name ...",
+that is, GLOBAL, LOCAL, METHODDEF, EXTERN are now macros taking the
+routine's return type as an argument. This makes it possible to add
+Microsoft-style linkage keywords to all the routines by changing just
+these macros. Note that any application code that was using these macros
+will have to be changed.
+
+DCT coefficient quantization tables are now stored in normal array order
+rather than zigzag order. Application code that calls jpeg_add_quant_table,
+or otherwise manipulates quantization tables directly, will need to be
+changed. If you need to make such code work with either older or newer
+versions of the library, a test like "#if JPEG_LIB_VERSION >= 61" is
+recommended.
+
+djpeg's trace capability now dumps DQT tables in natural order, not zigzag
+order. This allows the trace output to be made into a "-qtables" file
+more easily.
+
+New system-dependent memory manager module for use on Apple Macintosh.
+
+Fix bug in cjpeg's -smooth option: last one or two scanlines would be
+duplicates of the prior line unless the image height mod 16 was 1 or 2.
+
+Repair minor problems in VMS, BCC, MC6 makefiles.
+
+New configure script based on latest GNU Autoconf.
+
+Correct the list of include files needed by MetroWerks C for ccommand().
+
+Numerous small documentation updates.
+
+
+Version 6 2-Aug-95
+-------------------
+
+Progressive JPEG support: library can read and write full progressive JPEG
+files. A "buffered image" mode supports incremental decoding for on-the-fly
+display of progressive images. Simply recompiling an existing IJG-v5-based
+decoder with v6 should allow it to read progressive files, though of course
+without any special progressive display.
+
+New "jpegtran" application performs lossless transcoding between different
+JPEG formats; primarily, it can be used to convert baseline to progressive
+JPEG and vice versa. In support of jpegtran, the library now allows lossless
+reading and writing of JPEG files as DCT coefficient arrays. This ability
+may be of use in other applications.
+
+Notes for programmers:
+* We changed jpeg_start_decompress() to be able to suspend; this makes all
+decoding modes available to suspending-input applications. However,
+existing applications that use suspending input will need to be changed
+to check the return value from jpeg_start_decompress(). You don't need to
+do anything if you don't use a suspending data source.
+* We changed the interface to the virtual array routines: access_virt_array
+routines now take a count of the number of rows to access this time. The
+last parameter to request_virt_array routines is now interpreted as the
+maximum number of rows that may be accessed at once, but not necessarily
+the height of every access.
+
+
+Version 5b 15-Mar-95
+---------------------
+
+Correct bugs with grayscale images having v_samp_factor > 1.
+
+jpeg_write_raw_data() now supports output suspension.
+
+Correct bugs in "configure" script for case of compiling in
+a directory other than the one containing the source files.
+
+Repair bug in jquant1.c: sometimes didn't use as many colors as it could.
+
+Borland C makefile and jconfig file work under either MS-DOS or OS/2.
+
+Miscellaneous improvements to documentation.
+
+
+Version 5a 7-Dec-94
+--------------------
+
+Changed color conversion roundoff behavior so that grayscale values are
+represented exactly. (This causes test image files to change.)
+
+Make ordered dither use 16x16 instead of 4x4 pattern for a small quality
+improvement.
+
+New configure script based on latest GNU Autoconf.
+Fix configure script to handle CFLAGS correctly.
+Rename *.auto files to *.cfg, so that configure script still works if
+file names have been truncated for DOS.
+
+Fix bug in rdbmp.c: didn't allow for extra data between header and image.
+
+Modify rdppm.c/wrppm.c to handle 2-byte raw PPM/PGM formats for 12-bit data.
+
+Fix several bugs in rdrle.c.
+
+NEED_SHORT_EXTERNAL_NAMES option was broken.
+
+Revise jerror.h/jerror.c for more flexibility in message table.
+
+Repair oversight in jmemname.c NO_MKTEMP case: file could be there
+but unreadable.
+
+
+Version 5 24-Sep-94
+--------------------
+
+Version 5 represents a nearly complete redesign and rewrite of the IJG
+software. Major user-visible changes include:
+ * Automatic configuration simplifies installation for most Unix systems.
+ * A range of speed vs. image quality tradeoffs are supported.
+ This includes resizing of an image during decompression: scaling down
+ by a factor of 1/2, 1/4, or 1/8 is handled very efficiently.
+ * New programs rdjpgcom and wrjpgcom allow insertion and extraction
+ of text comments in a JPEG file.
+
+The application programmer's interface to the library has changed completely.
+Notable improvements include:
+ * We have eliminated the use of callback routines for handling the
+ uncompressed image data. The application now sees the library as a
+ set of routines that it calls to read or write image data on a
+ scanline-by-scanline basis.
+ * The application image data is represented in a conventional interleaved-
+ pixel format, rather than as a separate array for each color channel.
+ This can save a copying step in many programs.
+ * The handling of compressed data has been cleaned up: the application can
+ supply routines to source or sink the compressed data. It is possible to
+ suspend processing on source/sink buffer overrun, although this is not
+ supported in all operating modes.
+ * All static state has been eliminated from the library, so that multiple
+ instances of compression or decompression can be active concurrently.
+ * JPEG abbreviated datastream formats are supported, ie, quantization and
+ Huffman tables can be stored separately from the image data.
+ * And not only that, but the documentation of the library has improved
+ considerably!
+
+
+The last widely used release before the version 5 rewrite was version 4A of
+18-Feb-93. Change logs before that point have been discarded, since they
+are not of much interest after the rewrite.
diff --git a/jpeg-6c/changes6c.txt b/jpeg-6c/changes6c.txt
new file mode 100644
index 0000000..69a3bb9
--- /dev/null
+++ b/jpeg-6c/changes6c.txt
@@ -0,0 +1,4354 @@
+These are the changes I made to the files to allow bit changes "on the fly".
+8 bits is the default input and output for compatibility with most code. There is an extra
+copy step to move the 8 bit data into the 16 bit buffers for decompression and for both
+compression and decompression of raw data. All code should that use this should change
+to a 16 bit buffer. Currently this supports 8 and 12 bit lossy and 2 - 16 bit lossless.
+
+Changes:
+-----------------------------------------------------------------------
+In jcdiffct.c, jcsample.c, jcscale.c, jdcolor.c, jddiffct.c, jdmaster.c, jdmerge.c, jdsample.c, jdscale.c, jidctflt.c, jidctfst.c, jidctint.c, jidctred.c, jmemmgr.c, jquant1.c, jquant2.c, and jutils.c, changed all JSAMPLEs to JSAMPLE16.
+
+In jcdctmgr.c, jcdiffct.c jcpred.c, jcprepct.c, jcsample.c, jcscale.c, jdcolor.c, jdmerge.c, jdsample.c, jdscale.c, jidctflt.c, jidctfst.c, jidctint.c, jidctred.c, jlossls.h, jmaintct.c, jmemmgr.c, jquant1.c, jquant2.c, and jutils.c, changed all JSAMPROWs to JSAMPROW16.
+
+In jcdctmgr.c, jcdiffct.c, jcmainct.c jcprepct.c, jcsample.c, jdapistd.c, jdcoefct.c, jdcolor.c, jdct.c, jddiffct.c jdmainct.c, jdpostct.c jdsample.c, jidctflt.c, jidctfst.c jidctint.c, jidctred.c, jlossy.h, jmemmgr.c, jdmerge.c, jquant1.c, jquant2.c, and jutils.c, changed all JSAMPARRAYs to JSAMPARRAY16.
+
+In jcapimin.c, jccoefct.c, jccolor.c, jcdiffct.c, cjprepct.c, jcsample.c, jctrans.c, jdapistd.c, jdcoefct.c, cdcolor.c, jddiffct.c, jdmainct.c jdmerge.c, jdpost.c, jdsample.c, jlossy.h, jpegint.h changed all JSAMPIMAGEs to JSAMPIMAGE16
+
+
+-----------------------------------------------------------------------
+cderror.h from:
+JMESSAGE(JERR_PPM_NOT, "Not a PPM/PGM file")
+to:
+JMESSAGE(JERR_PPM_NOT, "Not a PPM/PGM file")
+JMESSAGE(JERR_PPM_ONLY, "-width for use only width a PPM file")
+
+-----------------------------------------------------------------------
+cdjpeg.h (GCC4.1 Warning) from:
+#define write_stdout WrStdout
+to:
+#define write_stdout WrStdout
+#ifdef C_LOSSLESS_SUPPORTED
+#define set_simple_lossless SetSplLs
+#endif
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 Warning) from:
+EXTERN(boolean) set_sample_factors JPP((j_compress_ptr cinfo, char *arg));
+to:
+EXTERN(boolean) set_sample_factors JPP((j_compress_ptr cinfo, char *arg));
+#ifdef C_LOSSLESS_SUPPORTED
+EXTERN(boolean) set_simple_lossless JPP((j_compress_ptr cinfo, char *arg));
+#endif
+
+-----------------------------------------------------------------------
+cjpeg.c from:
+static boolean is_targa; /* records user -targa switch */
+to:
+static boolean is_targa; /* records user -targa switch */
+static boolean var_width; /* sets variable width for ppm */
+static boolean loss_less; /* Tells ppm to allow 16 bits */
+++++++++++++++++++++++++++++++++++++++++
+from:
+ case 'B':
+ return jinit_read_bmp(cinfo);
+#endif
+#ifdef GIF_SUPPORTED
+ case 'G':
+ return jinit_read_gif(cinfo);
+#endif
+#ifdef PPM_SUPPORTED
+ case 'P':
+ return jinit_read_ppm(cinfo);
+#endif
+#ifdef RLE_SUPPORTED
+ case 'R':
+ return jinit_read_rle(cinfo);
+#endif
+#ifdef TARGA_SUPPORTED
+ case 0x00:
+ return jinit_read_targa(cinfo);
+to:
+ case 'B':
+ if (cinfo->data_precision != 8)
+ ERREXIT(cinfo, JERR_PPM_ONLY);
+ return jinit_read_bmp(cinfo);
+#endif
+#ifdef GIF_SUPPORTED
+ case 'G':
+ if (cinfo->data_precision != 8)
+ ERREXIT(cinfo, JERR_PPM_ONLY);
+ return jinit_read_gif(cinfo);
+#endif
+#ifdef PPM_SUPPORTED
+ case 'P':
+ return jinit_read_ppm(cinfo);
+#endif
+#ifdef RLE_SUPPORTED
+ case 'R':
+ if (cinfo->data_precision != 8)
+ ERREXIT(cinfo, JERR_PPM_ONLY);
+ return jinit_read_rle(cinfo);
+#endif
+#ifdef TARGA_SUPPORTED
+ case 0x00:
+ if (cinfo->data_precision != 8)
+ ERREXIT(cinfo, JERR_PPM_ONLY);
+ return jinit_read_targa(cinfo);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ fprintf(stderr, " -grayscale Create monochrome JPEG file\n");
+to:
+ fprintf(stderr, " -grayscale Create monochrome JPEG file\n");
+#ifdef PPM_SUPPORTED
+ fprintf(stderr, " -width N Output bit width for PPN to JPEG (N = 0 for same as input)\n");
+#endif
+++++++++++++++++++++++++++++++++++++++++
+from:
+ is_targa = FALSE;
+to:
+ is_targa = FALSE;
+ var_width = FALSE;
+ loss_less = FALSE;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ losslsarg = argv[argn];
+ /* We must postpone execution until num_components is known. */
+to:
+ losslsarg = argv[argn];
+ /* We must postpone execution until num_components is known. */
+ loss_less = TRUE; /* Let ppm know. */
+++++++++++++++++++++++++++++++++++++++++
+from:
+ is_targa = TRUE;
+to:
+ is_targa = TRUE;
+ } else if (keymatch(arg, "width", 1)) {
+#ifdef PPM_SUPPORTED
+ int val;
+
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (sscanf(argv[argn], "%d", &val) != 1)
+ usage();
+ if (val < 0 || val > JSAMPLEMAX)
+ usage();
+ if (!for_real) {/* Set ppm output width the first time. */
+ if (val == 0) {
+ val = 12;
+ var_width = TRUE;
+ }
+ cinfo->data_precision = val;
+ }
+#else
+ fprintf(stderr, "%s: sorry, ppm output was not compiled\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+++++++++++++++++++++++++++++++++++++++++
+from:
+ /* Read the input file header to obtain file size & colorspace. */
+ (*src_mgr->start_input) (&cinfo, src_mgr);
+to:
+ /* If PPM and variable width, tell PPM with a 0 data precision. */
+ if (var_width) cinfo.data_precision = 0;
+
+ /* Read the input file header to obtain file size & colorspace. */
+ (*src_mgr->start_input) (&cinfo, src_mgr);
+
+ if (cinfo.data_precision != 8) if (loss_less) cinfo.lossless = TRUE; /* Tell colorspace */
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 Warning) from:
+ (void) jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);
+to:
+ (void) jpeg_write_scanlines(&cinfo, (JSAMPARRAY)src_mgr->buffer, num_scanlines);
+
+-----------------------------------------------------------------------
+djpeg.c from:
+ FMT_PPM, /* PPM/PGM (PBMPLUS formats) */
+to:
+ FMT_PPM, /* PPM/PGM (PBMPLUS formats) */
+ FMT_PPMW, /* PPM/PGM 12/16 bit (PBMPLUS formats) */
+++++++++++++++++++++++++++++++++++++++++
+from:
+#ifdef PPM_SUPPORTED
+ fprintf(stderr, " -pnm Select PBMPLUS (PPM/PGM) output format%s\n",
+ (DEFAULT_FMT == FMT_PPM ? " (default)" : ""));
+#endif
+to:
+#ifdef PPM_SUPPORTED
+ fprintf(stderr, " -pnm Select PBMPLUS (PPM/PGM) output format%s\n",
+ (DEFAULT_FMT == FMT_PPM ? " (default)" : ""));
+ fprintf(stderr, " -widepnm Select PBMPLUS (PPM/PGM) 12/16 bit output format\n");
+#endif
+++++++++++++++++++++++++++++++++++++++++
+from:
+ } else if (keymatch(arg, "pnm", 1) || keymatch(arg, "ppm", 1)) {
+ /* PPM/PGM output format. */
+ requested_fmt = FMT_PPM;
+to:
+ } else if (keymatch(arg, "pnm", 1) || keymatch(arg, "ppm", 1)) {
+ /* PPM/PGM output format. */
+ requested_fmt = FMT_PPM;
+
+ } else if (keymatch(arg, "widepnm", 1) || keymatch(arg, "wideppm", 1)) {
+ /* PPM/PGM 12/16 bit output format. */
+ requested_fmt = FMT_PPMW;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ switch (requested_fmt) {
+to:
+ cinfo.data_precision_other = 8;
+ cinfo.shft = 0;
+ switch (requested_fmt) {
+++++++++++++++++++++++++++++++++++++++++
+from:
+ case FMT_PPM:
+ dest_mgr = jinit_write_ppm(&cinfo);
+ break;
+to:
+ case FMT_PPMW:
+ cinfo.data_precision_other = cinfo.data_precision;
+ case FMT_PPM:
+ dest_mgr = jinit_write_ppm(&cinfo);
+ break;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ dest_mgr->output_file = output_file;
+to:
+ if (cinfo.data_precision_other <= 8)
+ if (cinfo.process != JPROC_LOSSLESS) /* Lossless scales itself. */
+ cinfo.shft = cinfo.data_precision - cinfo.data_precision_other;
+ dest_mgr->output_file = output_file;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
+to:
+ num_scanlines = jpeg_read_scanlines(&cinfo,(JSAMPARRAY) dest_mgr->buffer,
+
+-----------------------------------------------------------------------
+jcapimin.c from:
+ cinfo->input_gamma = 1.0; /* in case application forgets */
+to:
+ cinfo->input_gamma = 1.0; /* in case application forgets */
+ cinfo->data_precision = 8; /* defaults for backward compatibility */
+ cinfo->data_precision_other =8;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ if (! (*cinfo->codec->compress_data) (cinfo, NULL))
+to:
+ if (! (*cinfo->codec->compress_data) (cinfo, (JSAMPIMAGE16) NULL))
+-----------------------------------------------------------------------
+jcapistd.c from:
+jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
+(stays JSAMPARRAY)to:
+jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 Warning) from:
+main
+to:
+mainp
+++++++++++++++++++++++++++++++++++++++++
+from:
+jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
+ JDIMENSION num_lines)
+(stays JSAMPIMAGE)to:
+jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
+ JDIMENSION num_lines)
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JDIMENSION lines_per_iMCU_row;
+to:
+ JDIMENSION lines_per_iMCU_row;
+ register JDIMENSION width, line, col;
+ register JSAMPLE16 *temp_buf_ptr;
+ register JSAMPLE *in_buf_row_ptr;
+ int cmp;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ /* Directly compress the row. */
+ if (! (*cinfo->codec->compress_data) (cinfo, data)) {
+ /* If compressor did not consume the whole row, suspend processing. */
+ return 0;
+to:
+ if (cinfo->data_precision_other > 8) {
+ /* Directly compress the row if short. */
+ if (! (*cinfo->codec->compress_data) (cinfo, (JSAMPIMAGE16)data)) {
+ /* If compressor did not consume the whole row, suspend processing. */
+ return 0;
+ }
+ } else {
+ /* 8 or less, time for buffering. */
+ if (cinfo->raw_data_buffer == NULL) { /* Not output suspension */
+ /* Allocate space for image array and copy the data if */
+ cinfo->raw_data_buffer = (JSAMPIMAGE16)cinfo->mem->alloc_small((j_common_ptr)cinfo, JPOOL_IMAGE_BUF,
+ (size_t) (cinfo->num_components));
+ for (cmp = 0; cmp < cinfo->num_components; cmp++) {
+ /* Allocate space for JSAMPARRAY16 arrays */
+ width = (JDIMENSION) (((long) cinfo->comp_info[cmp].width_in_data_units * cinfo->data_unit *
+ cinfo->max_h_samp_factor) / cinfo->comp_info[cmp].h_samp_factor);
+
+ /* (((cinfo->comp_info[cmp].h_samp_factor*cinfo->image_height)/DCTSIZE);*/
+ cinfo->raw_data_buffer[cmp] = (JSAMPARRAY16)(cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE_BUF,
+ width * SIZEOF(JSAMPLE16), (JDIMENSION) num_lines);
+ for (line = 0; line < num_lines; line++) {
+ temp_buf_ptr = cinfo->raw_data_buffer[cmp][line];
+ in_buf_row_ptr = data[cmp][line];
+ for (col = 0; col < width; col++)
+ *temp_buf_ptr++ = (JSAMPLE16) *in_buf_row_ptr++;
+ }
+ }
+ }
+ if (! (*cinfo->codec->compress_data) (cinfo, cinfo->raw_data_buffer))
+ /* If compressor did not consume the whole row, suspend processing,
+ and keep the buffer. */
+ return 0;
+ /* Free the buffer */
+ cinfo->mem->free_pool ((j_common_ptr)cinfo, JPOOL_IMAGE_BUF);
+ cinfo->raw_data_buffer = NULL;
+ }
+
+ /* OK, we processed one iMCU row. */
+ cinfo->next_scanline += lines_per_iMCU_row;
+ return lines_per_iMCU_row;
+}
+
+
+-----------------------------------------------------------------------
+jccolor.c from:
+#define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
+to:
+#define CBCR_OFFSET ((INT32) cinfo->centerjsample << SCALEBITS)
+++++++++++++++++++++++++++++++++++++++++
+from:
+#define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
+#define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
+#define R_CB_OFF (3*(MAXJSAMPLE+1))
+#define G_CB_OFF (4*(MAXJSAMPLE+1))
+#define B_CB_OFF (5*(MAXJSAMPLE+1))
+#define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
+#define G_CR_OFF (6*(MAXJSAMPLE+1))
+#define B_CR_OFF (7*(MAXJSAMPLE+1))
+#define TABLE_SIZE (8*(MAXJSAMPLE+1))
+to:
+#define G_Y_OFF (1*(cinfo->maxjsample+1)) /* offset to G => Y section */
+#define B_Y_OFF (2*(cinfo->maxjsample+1)) /* etc. */
+#define R_CB_OFF (3*(cinfo->maxjsample+1))
+#define G_CB_OFF (4*(cinfo->maxjsample+1))
+#define B_CB_OFF (5*(cinfo->maxjsample+1))
+#define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
+#define G_CR_OFF (6*(cinfo->maxjsample+1))
+#define B_CR_OFF (7*(cinfo->maxjsample+1))
+#define TABLE_SIZE (8*(cinfo->maxjsample+1))
+++++++++++++++++++++++++++++++++++++++++
+from:
+ for (i = 0; i <= MAXJSAMPLE; i++) {
+to:
+ for (i = 0; i <= cinfo->maxjsample; i++) {
+++++++++++++++++++++++++++++++++++++++++
+from:
+rgb_ycc_convert (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+to:
+rgb_ycc_convert8 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+++++++++++++++++++++++++++++++++++++++++
+from:
+ register JSAMPROW outptr0, outptr1, outptr2;
+to:
+ register JSAMPROW16 outptr0, outptr1, outptr2;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ outptr0[col] = (JSAMPLE)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ /* Cb */
+ outptr1[col] = (JSAMPLE)
+ ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+ >> SCALEBITS);
+ /* Cr */
+ outptr2[col] = (JSAMPLE)
+to:
+ outptr0[col] = (JSAMPLE16)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ /* Cb */
+ outptr1[col] = (JSAMPLE16)
+ ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+ >> SCALEBITS);
+ /* Cr */
+ outptr2[col] = (JSAMPLE16)
+++++++++++++++++++++++++++++++++++++++++
+add:
+METHODDEF(void)
+rgb_ycc_convert16 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int r, g, b;
+ register INT32 * ctab = cconvert->rgb_ycc_tab;
+ register JSAMPROW16 inptr;
+ register JSAMPROW16 outptr0, outptr1, outptr2;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ inptr = (JSAMPROW16)*input_buf++;
+ outptr0 = output_buf[0][output_row];
+ outptr1 = output_buf[1][output_row];
+ outptr2 = output_buf[2][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ r = GETJSAMPLE(inptr[RGB_RED]);
+ g = GETJSAMPLE(inptr[RGB_GREEN]);
+ b = GETJSAMPLE(inptr[RGB_BLUE]);
+ inptr += RGB_PIXELSIZE;
+ /* If the inputs are 0..cinfo->maxjsample, the outputs of these equations
+ * must be too; we do not need an explicit range-limiting operation.
+ * Hence the value being shifted is never negative, and we don't
+ * need the general RIGHT_SHIFT macro.
+ */
+ /* Y */
+ outptr0[col] = (JSAMPLE16)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ /* Cb */
+ outptr1[col] = (JSAMPLE16)
+ ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+ >> SCALEBITS);
+ /* Cr */
+ outptr2[col] = (JSAMPLE16)
+ ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
+ >> SCALEBITS);
+ }
+ }
+}
+++++++++++++++++++++++++++++++++++++++++
+from:
+rgb_gray_convert (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+to:
+rgb_gray_convert8 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+++++++++++++++++++++++++++++++++++++++++
+from:
+ register JSAMPROW outptr;
+to:
+ register JSAMPROW16 outptr;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ outptr[col] = (JSAMPLE)
+to:
+ outptr[col] = (JSAMPLE16)
+++++++++++++++++++++++++++++++++++++++++
+add:
+METHODDEF(void)
+rgb_gray_convert16 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int r, g, b;
+ register INT32 * ctab = cconvert->rgb_ycc_tab;
+ register JSAMPROW16 inptr;
+ register JSAMPROW16 outptr;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ inptr = (JSAMPROW16)*input_buf++;
+ outptr = output_buf[0][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ r = GETJSAMPLE(inptr[RGB_RED]);
+ g = GETJSAMPLE(inptr[RGB_GREEN]);
+ b = GETJSAMPLE(inptr[RGB_BLUE]);
+ inptr += RGB_PIXELSIZE;
+ /* Y */
+ outptr[col] = (JSAMPLE16)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ }
+ }
+}
+++++++++++++++++++++++++++++++++++++++++
+from:
+cmyk_ycck_convert (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+to:
+cmyk_ycck_convert8 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+++++++++++++++++++++++++++++++++++++++++
+from:
+ register JSAMPROW outptr0, outptr1, outptr2, outptr3;
+to:
+ register JSAMPROW16 outptr0, outptr1, outptr2, outptr3;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
+ g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
+ b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
+to:
+ r = cinfo->maxjsample - GETJSAMPLE(inptr[0]);
+ g = cinfo->maxjsample - GETJSAMPLE(inptr[1]);
+ b = cinfo->maxjsample - GETJSAMPLE(inptr[2]);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ outptr0[col] = (JSAMPLE)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ /* Cb */
+ outptr1[col] = (JSAMPLE)
+ ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+ >> SCALEBITS);
+ /* Cr */
+ outptr2[col] = (JSAMPLE)
+to:
+ outptr0[col] = (JSAMPLE16)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ /* Cb */
+ outptr1[col] = (JSAMPLE16)
+ ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+ >> SCALEBITS);
+ /* Cr */
+ outptr2[col] = (JSAMPLE16)
+++++++++++++++++++++++++++++++++++++++++
+add:
+METHODDEF(void)
+cmyk_ycck_convert16 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int r, g, b;
+ register INT32 * ctab = cconvert->rgb_ycc_tab;
+ register JSAMPROW16 inptr;
+ register JSAMPROW16 outptr0, outptr1, outptr2, outptr3;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ inptr = (JSAMPROW16)*input_buf++;
+ outptr0 = output_buf[0][output_row];
+ outptr1 = output_buf[1][output_row];
+ outptr2 = output_buf[2][output_row];
+ outptr3 = output_buf[3][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ r = cinfo->maxjsample - GETJSAMPLE(inptr[0]);
+ g = cinfo->maxjsample - GETJSAMPLE(inptr[1]);
+ b = cinfo->maxjsample - GETJSAMPLE(inptr[2]);
+ /* K passes through as-is */
+ outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
+ inptr += 4;
+ /* If the inputs are 0..cinfo->maxjsample, the outputs of these equations
+ * must be too; we do not need an explicit range-limiting operation.
+ * Hence the value being shifted is never negative, and we don't
+ * need the general RIGHT_SHIFT macro.
+ */
+ /* Y */
+ outptr0[col] = (JSAMPLE16)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ /* Cb */
+ outptr1[col] = (JSAMPLE16)
+ ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+ >> SCALEBITS);
+ /* Cr */
+ outptr2[col] = (JSAMPLE16)
+ ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
+ >> SCALEBITS);
+ }
+ }
+}
+++++++++++++++++++++++++++++++++++++++++
+from:
+grayscale_convert (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+to:
+grayscale_convert8 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+++++++++++++++++++++++++++++++++++++++++
+from:
+ register JSAMPROW outptr;
+to:
+ register JSAMPROW16 outptr;
+++++++++++++++++++++++++++++++++++++++++
+add:
+METHODDEF(void)
+grayscale_convert16 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ register JSAMPROW16 inptr;
+ register JSAMPROW16 outptr;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+ int instride = cinfo->input_components;
+
+ while (--num_rows >= 0) {
+ inptr = (JSAMPROW16)*input_buf++;
+ outptr = output_buf[0][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
+ inptr += instride;
+ }
+ }
+}
+++++++++++++++++++++++++++++++++++++++++
+from:
+null_convert (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+to:
+null_convert8 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+++++++++++++++++++++++++++++++++++++++++
+from:
+ register JSAMPROW outptr;
+to:
+ register JSAMPROW16 outptr;
+++++++++++++++++++++++++++++++++++++++++
+add:
+METHODDEF(void)
+null_convert16 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ register JSAMPROW16 inptr;
+ register JSAMPROW16 outptr;
+ register JDIMENSION col;
+ register int ci;
+ int nc = cinfo->num_components;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ /* It seems fastest to make a separate pass for each component. */
+ for (ci = 0; ci < nc; ci++) {
+ inptr = (JSAMPROW16)*input_buf;
+ outptr = output_buf[ci][output_row];
+ for (col = 0; col < num_cols; col++) {
+ outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
+ inptr += nc;
+ }
+ }
+ input_buf++;
+ output_row++;
+ }
+}
+++++++++++++++++++++++++++++++++++++++++
+from:
+ my_cconvert_ptr cconvert;
+to:
+ my_cconvert_ptr cconvert;
+ boolean inp8 = FALSE;
+
+ if (cinfo->data_precision_other <= 8) inp8 = TRUE;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ if (cinfo->in_color_space == JCS_GRAYSCALE)
+ cconvert->pub.color_convert = grayscale_convert;
+ else if (cinfo->in_color_space == JCS_RGB) {
+ cconvert->pub.start_pass = rgb_ycc_start;
+ cconvert->pub.color_convert = rgb_gray_convert;
+ } else if (cinfo->in_color_space == JCS_YCbCr)
+ cconvert->pub.color_convert = grayscale_convert;
+to:
+ if (cinfo->in_color_space == JCS_GRAYSCALE) {
+ if (inp8) cconvert->pub.color_convert = grayscale_convert8;
+ else cconvert->pub.color_convert = grayscale_convert16; }
+ else if (cinfo->in_color_space == JCS_RGB) {
+ cconvert->pub.start_pass = rgb_ycc_start;
+ if (inp8) cconvert->pub.color_convert = rgb_gray_convert8;
+ else cconvert->pub.color_convert = rgb_gray_convert16;
+ } else if (cinfo->in_color_space == JCS_YCbCr) {
+ if (inp8) cconvert->pub.color_convert = grayscale_convert8;
+ else cconvert->pub.color_convert = grayscale_convert16; }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
+ cconvert->pub.color_convert = null_convert;
+to:
+ if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
+ if (inp8) cconvert->pub.color_convert = null_convert8;
+ else cconvert->pub.color_convert = null_convert16; }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cconvert->pub.start_pass = rgb_ycc_start;
+ cconvert->pub.color_convert = rgb_ycc_convert;
+ } else if (cinfo->in_color_space == JCS_YCbCr)
+ cconvert->pub.color_convert = null_convert;
+to:
+ if (inp8) cconvert->pub.color_convert = rgb_ycc_convert8;
+ else cconvert->pub.color_convert = rgb_ycc_convert16;
+ } else if (cinfo->in_color_space == JCS_YCbCr) {
+ if (inp8) cconvert->pub.color_convert = null_convert8;
+ else cconvert->pub.color_convert = null_convert16; }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ if (cinfo->in_color_space == JCS_CMYK)
+ cconvert->pub.color_convert = null_convert;
+to:
+ if (cinfo->in_color_space == JCS_CMYK) {
+ if (inp8) cconvert->pub.color_convert = null_convert8;
+ else cconvert->pub.color_convert = null_convert16; }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cconvert->pub.color_convert = cmyk_ycck_convert;
+ } else if (cinfo->in_color_space == JCS_YCCK)
+ cconvert->pub.color_convert = null_convert;
+to:
+ if (inp8) cconvert->pub.color_convert = cmyk_ycck_convert8;
+ else cconvert->pub.color_convert = cmyk_ycck_convert16;
+ } else if (cinfo->in_color_space == JCS_YCCK) {
+ if (inp8) cconvert->pub.color_convert = null_convert8;
+ else cconvert->pub.color_convert = null_convert16; }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cconvert->pub.color_convert = null_convert;
+to:
+ if (inp8) cconvert->pub.color_convert = null_convert8;
+ else cconvert->pub.color_convert = null_convert16;
+
+-----------------------------------------------------------------------
+jcdctmgr.c from:
+ JDIMENSION bi;
+to:
+ JDIMENSION bi;
+ boolean jpeg8 = FALSE;
+
+ if (cinfo->data_precision <= 8) jpeg8 = TRUE;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+#else
+ { register int elemc;
+ for (elemc = DCTSIZE; elemc > 0; elemc--) {
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+to:
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+#else
+ { register int elemc;
+ for (elemc = DCTSIZE; elemc > 0; elemc--) {
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+++++++++++++++++++++++++++++++++++++++++
+in from:
+ (*do_dct) (workspace);
+to:
+ (*do_dct) (workspace, jpeg8);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+#else
+ { register int elemc;
+ for (elemc = DCTSIZE; elemc > 0; elemc--) {
+ *workspaceptr++ = (FAST_FLOAT)
+ (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
+to:
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+#else
+ { register int elemc;
+ for (elemc = DCTSIZE; elemc > 0; elemc--) {
+ *workspaceptr++ = (FAST_FLOAT)
+ (GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+
+-----------------------------------------------------------------------
+jcdiffct.c (GCC4.1 Warning) from:
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+to:
+/* JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+ buffer[ci] = (*cinfo->mem->access_virt_sarray)
+to:
+ buffer[ci] = (JSAMPARRAY16)(*cinfo->mem->access_virt_sarray)
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 Warning) from:
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION MCU_count; /* number of MCUs encoded */
+ int comp, ci, yoffset;
+to:
+/* JDIMENSION MCU_col_num; *//* index of current MCU within row */
+/* JDIMENSION MCU_count;*/ /* number of MCUs encoded */
+ int comp, ci;/*, yoffset;*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+ buffer[ci] = (*cinfo->mem->access_virt_sarray)
+to:
+ buffer[ci] = (JSAMPARRAY16)(*cinfo->mem->access_virt_sarray)
+++++++++++++++++++++++++++++++++++++++++
+from:
+ diff->cur_row[ci] = *(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor),
+ (JDIMENSION) 1);
+ diff->prev_row[ci] = *(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor),
+to:
+ diff->cur_row[ci] = (JSAMPROW16)*(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units
+ * SIZEOF(JSAMPLE16), (long) compptr->h_samp_factor),
+ (JDIMENSION) 1);
+ diff->prev_row[ci] = (JSAMPROW16)*(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units
+ * SIZEOF(JSAMPLE16), (long) compptr->h_samp_factor),
+++++++++++++++++++++++++++++++++++++++++
+from:
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor),
+to:
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JSAMPLE16),
+++++++++++++++++++++++++++++++++++++++++
+from:
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor),
+to:
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JSAMPLE16),
+++++++++++++++++++++++++++++++++++++++++
+from:
+ C_MAX_DATA_UNITS_IN_MCU * SIZEOF(JBLOCK));
+to:
+ C_MAX_DATA_UNITS_IN_MCU * SIZEOF(JBLOCK) * SIZEOF(JSAMPLE16));
+
+-----------------------------------------------------------------------
+jchuff.h from:
+#if BITS_IN_JSAMPLE == 8
+#define MAX_COEF_BITS 10
+#else
+#define MAX_COEF_BITS 14
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8
+#define MAX_COEF_BITS 10
+#else
+#define MAX_COEF_BITS 14
+#endif*/
+
+-----------------------------------------------------------------------
+jclhuff.c (GCC4.1 Warning) from:
+ int ci;
+to:
+/* int ci;*/
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 Warning) 2 places from:
+ jpeg_component_info * compptr;
+to:
+/* jpeg_component_info * compptr;*/
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 Warning) from:
+ register int temp, temp2, temp3;
+to:
+ register int temp, temp2;/*, temp3;*/
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 Warning) from:
+ c_derived_tbl *dctbl = entropy->cur_tbls[sampn];
+to:
+/* c_derived_tbl *dctbl = entropy->cur_tbls[sampn];*/
+
+-----------------------------------------------------------------------
+jcmainct.c from:
+ JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
+ JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+METHODDEF(void) process_data_buffer_main
+ JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
+(stays JSAMPARRAY) to:
+ JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
+ JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+METHODDEF(void) process_data_buffer_main
+ JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
+++++++++++++++++++++++++++++++++++++++++
+from:
+process_data_simple_main (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+(stays JSAMPARRAY) to:
+process_data_simple_main (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+++++++++++++++++++++++++++++++++++++++++
+from:
+process_data_buffer_main (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+(stays JSAMPARRAY) to:
+process_data_buffer_main (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+++++++++++++++++++++++++++++++++++++++++
+from:
+ mainp->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ compptr->width_in_data_units * data_unit,
+to:
+ mainp->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ compptr->width_in_data_units * data_unit * SIZEOF(JSAMPLE16),
+++++++++++++++++++++++++++++++++++++++++
+from:
+ main->buffer[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ compptr->width_in_data_units * data_unit,
+to:
+ mainp->buffer[ci] = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ compptr->width_in_data_units * data_unit * SIZEOF(JSAMPLE16),
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 Warning) from:
+main
+to:
+mainp
+
+-----------------------------------------------------------------------
+jcmarker.c(GCC4.1 Warning) from:
+ int ci, prec;
+to:
+ int ci, prec = 0;
+
+-----------------------------------------------------------------------
+jcmaster.c from:
+ if (cinfo->data_precision != BITS_IN_JSAMPLE)
+ ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
+to:
+/* if (cinfo->data_precision != BITS_IN_JSAMPLE)
+ ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+ Al < 0 || Al >= cinfo->data_precision) /* point transform */
+to:
+ Al < 0 || Al >= cinfo->data_precision || Al >= JSAMPLEMAX) /* point transform */
+++++++++++++++++++++++++++++++++++++++++
+from:
+#if BITS_IN_JSAMPLE == 8
+#define MAX_AH_AL 10
+#else
+#define MAX_AH_AL 13
+#endif
+ if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
+ Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+to:
+/*#if BITS_IN_JSAMPLE == 8
+#define MAX_AH_AL 10
+#else
+#define MAX_AH_AL 13
+#endif*/
+ if (cinfo->data_precision <= 8) {
+ if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
+ Ah < 0 || Ah > 10 || Al < 0 || Al > 10)
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ } else {
+ if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
+ Ah < 0 || Ah > 13 || Al < 0 || Al > 13)
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ }
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 Warning) line 460 from:
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+to:
+/* j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;*/
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 Warning) from:
+main
+to:
+mainp
+
+-----------------------------------------------------------------------
+jcparam.c from:
+ cinfo->data_precision = BITS_IN_JSAMPLE;
+to:
+ cinfo->lossless = FALSE;
+ cinfo->lossless_scaling = TRUE;
+ cinfo->data_precision = 8;
+ cinfo->maxjsample = 255;
+ cinfo->centerjsample = 128;
+#ifdef HAVE_GETJSAMPLE_MASK
+ cinfo->maskjsample = 0xFF;
+#endif
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cinfo->raw_data_in = FALSE;
+to:
+ cinfo->raw_data_in = FALSE;
+ cinfo->raw_data_buffer = NULL;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ /* By default, don't do extra passes to optimize entropy coding */
+ cinfo->optimize_coding = FALSE;
+
+ /* The standard Huffman tables are only valid for 8-bit data precision.
+ * If the precision is higher, force optimization on so that usable
+ * tables will be computed. This test can be removed if default tables
+ * are supplied that are valid for the desired precision.
+ */
+ if (cinfo->data_precision > 8)
+ cinfo->optimize_coding = TRUE;
+ to:
+ /* By default, don't do extra passes to optimize entropy coding */
+ cinfo->optimize_coding = FALSE;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
+ to:
+ cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
+
+ /* Fix the bit width stuff here, by now cinfo->data_precision should be set */
+ if (2 > cinfo->data_precision || cinfo->data_precision > 16)
+ ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
+ if (!cinfo->lossless) {
+ if (!cinfo->lossless) {
+ if (cinfo->data_precision <=8) {
+ if (cinfo->data_precision !=8) {
+ WARNMS2(cinfo, JWRN_JPEG_PRECISION_CHANGED, cinfo->data_precision, 8);
+ cinfo->data_precision = 8;
+ }
+ } else if (cinfo->data_precision != 12) {
+ WARNMS2(cinfo, JWRN_JPEG_PRECISION_CHANGED, cinfo->data_precision, 12);
+ cinfo->data_precision = 12;
+ }
+ }
+ cinfo->maxjsample = (1 << cinfo->data_precision) - 1;
+ cinfo->centerjsample = (cinfo->maxjsample + 1)/2;
+#ifdef HAVE_GETJSAMPLE_MASK
+ cinfo->maskjsample = cinfo->maxjsample;
+#endif
+
+ /* The standard Huffman tables are only valid for 8-bit data precision.
+ * If the precision is higher, force optimization on so that usable
+ * tables will be computed. This test can be removed if default tables
+ * are supplied that are valid for the desired precision.
+ */
+ if (cinfo->data_precision != 8)
+ cinfo->optimize_coding = TRUE;
+
+-----------------------------------------------------------------------
+jcphuff.c from:
+ if (nbits > 14)
+ ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
+to:
+ if (nbits > 18)
+ ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ */
+ if (nbits > MAX_COEF_BITS+1)
+ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+to:
+ * was MAX_COEF_BITS +1, 11 or 15, now data_precision + 3.
+ */
+ if (nbits > (cinfo->data_precision + 3))
+ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ if (nbits > MAX_COEF_BITS)
+ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+to:
+ /* was MAX_COEF_BITS, 10 or 14, now data_precision + 2. */
+ if (nbits > (cinfo->data_precision + 2))
+ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+
+-----------------------------------------------------------------------
+jcpred.c (GCC4.1 Warning) from:
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ c_pred_ptr pred = (c_pred_ptr) losslsc->pred_private;
+to:
+/* j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ c_pred_ptr pred = (c_pred_ptr) losslsc->pred_private;*/
+
+-----------------------------------------------------------------------
+jcprepct.c from:
+pre_process_data (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail,
+ JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
+ JDIMENSION out_row_groups_avail)
+to:
+pre_process_data (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail,
+ JSAMPIMAGE16 output_buf, JDIMENSION *out_row_group_ctr,
+ JDIMENSION out_row_groups_avail)
+++++++++++++++++++++++++++++++++++++++++
+from:
+pre_process_context (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail,
+ JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
+ JDIMENSION out_row_groups_avail)
+to:
+pre_process_context (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail,
+ JSAMPIMAGE16 output_buf, JDIMENSION *out_row_group_ctr,
+ JDIMENSION out_row_groups_avail)
+++++++++++++++++++++++++++++++++++++++++
+from:
+ true_buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) (((long) compptr->width_in_data_units * cinfo->data_unit *
+ cinfo->max_h_samp_factor) / compptr->h_samp_factor),
+to:
+ true_buffer = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) (((long) compptr->width_in_data_units * cinfo->data_unit *
+ cinfo->max_h_samp_factor * SIZEOF(JSAMPLE16)) / compptr->h_samp_factor),
+++++++++++++++++++++++++++++++++++++++++
+from:
+ prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) (((long) compptr->width_in_data_units * cinfo->data_unit *
+ cinfo->max_h_samp_factor) / compptr->h_samp_factor),
+to:
+ prep->color_buf[ci] = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) (((long) compptr->width_in_data_units * cinfo->data_unit *
+ cinfo->max_h_samp_factor * SIZEOF(JSAMPLE16)) / compptr->h_samp_factor),
+
+-----------------------------------------------------------------------
+jcscale.c (GCC4.1 Warning) from:
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+to:
+/* j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+ if (cinfo->Al)
+to:
+ if ((cinfo->Al) && cinfo->lossless_scaling)
+
+-----------------------------------------------------------------------
+jcshuff.c from:
+ */
+ if (nbits > MAX_COEF_BITS+1)
+ ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
+to:
+ * was MAX_COEF_BITS +1, 11 or 15, now data_precision + 3.
+ */
+ if (nbits > (state->cinfo->data_precision + 3))
+ ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ if (nbits > MAX_COEF_BITS)
+ ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
+to:
+ /* was MAX_COEF_BITS, 10 or 14, now data_precision + 2. */
+ if (nbits > (cinfo->data_precision + 2))
+ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ */
+ if (nbits > MAX_COEF_BITS+1)
+ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+to:
+ * was MAX_COEF_BITS +1, 11 or 15, now data_precision + 3.
+ */
+ if (nbits > (cinfo->data_precision + 3))
+ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ if (nbits > MAX_COEF_BITS)
+ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+to:
+ /* was MAX_COEF_BITS, 10 or 14, now data_precision + 2. */
+ if (nbits > (cinfo->data_precision + 2))
+ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+
+-----------------------------------------------------------------------
+jctrans.c from:
+ dstinfo->data_precision = srcinfo->data_precision;
+to:
+ dstinfo->data_precision = srcinfo->data_precision;
+ dstinfo->data_precision_other = srcinfo->data_precision_other;
+ dstinfo->maxjsample = srcinfo->maxjsample;
+ dstinfo->centerjsample = srcinfo->centerjsample;
+#ifdef HAVE_GETJSAMPLE_MASK
+ dstinfo->maskjsample = srcinfo->maskjsample;
+#endif
+-----------------------------------------------------------------------
+jdapimin.c from:
+ cinfo->colormap = NULL;
+to:
+ cinfo->colormap = NULL;
+ cinfo->colormap16 = NULL;
+
+-----------------------------------------------------------------------
+jdapistd.c from:
+jpeg_start_decompress (j_decompress_ptr cinfo)
+{
+to:
+jpeg_start_decompress (j_decompress_ptr cinfo)
+{
+ /* Fix scaling here */
+ if (cinfo->data_precision == cinfo->data_precision_other)
+ cinfo->shft = 0;
+ /* Warn now if scaled */
+ if (cinfo->shft != 0) WARNMS2(cinfo, JWRN_SCALED,
+ cinfo->data_precision, cinfo->data_precision_other);
+++++++++++++++++++++++++++++++++++++++++
+from:
+jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
+ JDIMENSION max_lines)
+{
+ JDIMENSION row_ctr;
+to:
+jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
+ JDIMENSION max_lines)
+{
+ JDIMENSION row_ctr;
+ JSAMPARRAY16 scanlines16;
+ JDIMENSION max_lines_buffer;
+ register JDIMENSION width, line, col;
+ register JSAMPLE16 *temp_buf_ptr;
+ register JSAMPLE16 *out_buf16_row_ptr;
+ register JSAMPLE *out_buf_row_ptr;
+ register int rshft;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ /* Call progress monitor hook if present */
+to:
+ /* Deal with 8 bit outputs and scaling. */
+ max_lines_buffer = max_lines;
+ if ((cinfo->shft != 0) || (cinfo->buffer_size_char)) {
+ /* Create a data buffer <= DCTSIZE */
+ if (max_lines_buffer > DCTSIZE) max_lines_buffer = DCTSIZE;
+ width = cinfo->output_width * cinfo->output_components;
+ scanlines16 = (JSAMPARRAY16)(cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE_BUF, (JDIMENSION) width *
+ SIZEOF(JSAMPLE16), max_lines_buffer);
+
+ } else { /* Short buffer, no scalling, just cast. */
+ scanlines16 = (JSAMPARRAY16)scanlines;
+ }
+
+ /* Call progress monitor hook if present */
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cinfo->output_scanline += row_ctr;
+
+ return row_ctr;
+to:
+ cinfo->output_scanline += row_ctr;
+
+ /* Copy the buffer if needed. */
+ rshft = cinfo->shft;
+ if (cinfo->buffer_size_char) {
+ for (line = 0; line < row_ctr; line++) {
+ temp_buf_ptr = scanlines16[line];
+ out_buf_row_ptr = scanlines[line];
+ if (rshft == 0 ) { /* Faster */
+ for (col = 0; col < width; col++) {
+ *temp_buf_ptr++ = *out_buf_row_ptr++;
+ }
+ } else if (rshft > 0) { /* Shift data. */
+ for (col = 0; col < width; col++) {
+ *temp_buf_ptr++ = (*out_buf_row_ptr++ >> rshft);
+ }
+ } else { /* Shift data the other way. */
+ rshft = -rshft;
+ for (col = 0; col < width; col++) {
+ *temp_buf_ptr++ = (*out_buf_row_ptr++ << rshft);
+ }
+ }
+ }
+ } else if ( rshft != 0) { /* 16 bit shifted. */
+ for (line = 0; line < row_ctr; line++) {
+ temp_buf_ptr = scanlines16[line];
+ out_buf16_row_ptr = (JSAMPARRAY16)scanlines[line];
+ if (rshft > 0) { /* Shift data. */
+ for (col = 0; col < width; col++) {
+ *temp_buf_ptr++ = (*out_buf16_row_ptr++ >> rshft);
+ }
+ } else { /* Shift data the other way. */
+ rshft = -rshft;
+ for (col = 0; col < width; col++) {
+ *temp_buf_ptr++ = (*out_buf16_row_ptr++ << rshft);
+ }
+ }
+ }
+ }
+
+ /* Free the buffer if used. */
+ if ( scanlines16 == (JSAMPARRAY16)scanlines ) {
+ cinfo->mem->free_pool ((j_common_ptr)cinfo, JPOOL_IMAGE_BUF);
+ scanlines16 = NULL;
+ }
+
+ return row_ctr;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JDIMENSION lines_per_iMCU_row;
+
+ if (cinfo->global_state != DSTATE_RAW_OK)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ if (cinfo->output_scanline >= cinfo->output_height) {
+ WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+ return 0;
+ }
+
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->output_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->output_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+
+ /* Verify that at least one iMCU row can be returned. */
+ lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_codec_data_unit;
+ if (max_lines < lines_per_iMCU_row)
+ ERREXIT(cinfo, JERR_BUFFER_SIZE);
+
+ /* Decompress directly into user's buffer. */
+ if (! (*cinfo->codec->decompress_data) (cinfo, (JSAMPIMAGE16)data))
+ return 0; /* suspension forced, can do nothing more */
+
+ /* OK, we processed one iMCU row. */
+ cinfo->output_scanline += lines_per_iMCU_row;
+ return lines_per_iMCU_row;
+}
+to:
+++++++++++++++++++++++++++++++++++++++++
+for GCC4.1 Warning from:
+main
+to:
+mainp
+
+-----------------------------------------------------------------------
+jdcoefct.c (GCC4.1 Warning) from:
+ d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+to:
+/* d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+ coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor),
+to:
+ coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JSAMPLE16),
+
+-----------------------------------------------------------------------
+jdcolor.c from:
+ cconvert->Cr_r_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(int));
+ cconvert->Cb_b_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(int));
+ cconvert->Cr_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(INT32));
+ cconvert->Cb_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(INT32));
+
+ for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
+to:
+ cconvert->Cr_r_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(int));
+ cconvert->Cb_b_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(int));
+ cconvert->Cr_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(INT32));
+ cconvert->Cb_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(INT32));
+
+ for (i = 0, x = -cinfo->centerjsample; i <= cinfo->maxjsample; i++, x++) {
+++++++++++++++++++++++++++++++++++++++++
+from:
+ outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
+ outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
+ ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
+ SCALEBITS)))];
+ outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
+to:
+ outptr[0] = range_limit[cinfo->maxjsample - (y + Crrtab[cr])]; /* red */
+ outptr[1] = range_limit[cinfo->maxjsample - (y + /* green */
+ ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
+ SCALEBITS)))];
+ outptr[2] = range_limit[cinfo->maxjsample - (y + Cbbtab[cb])]; /* blue */
+
+-----------------------------------------------------------------------
+jdct.h from:
+#if BITS_IN_JSAMPLE == 8
+typedef int DCTELEM; /* 16 or 32 bits is fine */
+#else
+typedef INT32 DCTELEM; /* must have 32 bits */
+#endif
+
+typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
+to:
+/*#if BITS_IN_JSAMPLE == 8
+typedef int DCTELEM;*/ /* 16 or 32 bits is fine */
+/*#else*/
+typedef INT32 DCTELEM; /* must have 32 bits */
+/*#endif*/
+
+typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data, boolean jpeg8));
+++++++++++++++++++++++++++++++++++++++++
+from:
+#if BITS_IN_JSAMPLE == 8
+typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
+#define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
+#else
+typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
+#define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8
+typedef MULTIPLIER IFAST_MULT_TYPE;*/ /* 16 bits is OK, use short if faster */
+/*#define IFAST_SCALE_BITS 2*/ /* fractional bits in scale factors */
+/*#else*/
+typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
+/*#define IFAST_SCALE_BITS 13*/ /* fractional bits in scale factors */
+/*#endif*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+#define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
+
+#define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
+to:
+#define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + cinfo->centerjsample)
+
+#define RANGE_MASK (cinfo->maxjsample * 4 + 3) /* 2 bits wider than legal samples */
+++++++++++++++++++++++++++++++++++++++++
+from:
+EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
+EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
+to:
+EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data, boolean jpeg8));
+EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data, boolean jpeg8));
+
+-----------------------------------------------------------------------
+jddctmgr.c from:
+ int ci, i;
+to:
+ int ci, i, ifast_sb;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ SHIFT_TEMPS
+ if(cinfo->data_precision <= 8 ) ifast_sb = 2;
+ else ifast_sb = 13;
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ ifmtbl[i] = (IFAST_MULT_TYPE)
+ DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
+ (INT32) aanscales[i]),
+ CONST_BITS-IFAST_SCALE_BITS);
+to:
+ for (i = 0; i < DCTSIZE2; i++) {
+ ifmtbl[i] = (IFAST_MULT_TYPE)
+ DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
+ (INT32) aanscales[i]),
+ CONST_BITS-ifast_sb);
+
+-----------------------------------------------------------------------
+jddiffct.c (GCC4.1 Warning) from:
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION MCU_count; /* number of MCUs decoded */
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ int comp, ci, yoffset, row, prev_row;
+to:
+/* JDIMENSION MCU_col_num; *//* index of current MCU within row */
+/* JDIMENSION MCU_count; */ /* number of MCUs decoded */
+/* JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;*/
+ int comp, ci;/*, yoffset, row, prev_row;*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+ buffer[ci] = (*cinfo->mem->access_virt_sarray)
+to:
+ buffer[ci] = (JSAMPARRAY16)(*cinfo->mem->access_virt_sarray)
+++++++++++++++++++++++++++++++++++++++++
+from:
+ buffer = (*cinfo->mem->access_virt_sarray)
+to:
+ buffer = (JSAMPARRAY16)(*cinfo->mem->access_virt_sarray)
+++++++++++++++++++++++++++++++++++++++++
+from:
+ diff->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor),
+to:
+ diff->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JSAMPLE16),
+++++++++++++++++++++++++++++++++++++++++
+from:
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor),
+ (JDIMENSION) compptr->v_samp_factor);
+ diff->undiff_buf[ci] = (*cinfo->mem->alloc_darray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor),
+to:
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JSAMPLE16),
+ (JDIMENSION) compptr->v_samp_factor);
+ diff->undiff_buf[ci] = (*cinfo->mem->alloc_darray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JSAMPLE16),
+
+-----------------------------------------------------------------------
+jdinput.c from:
+ if (cinfo->process == JPROC_LOSSLESS) {
+ /* If precision > compiled-in value, we must downscale */
+ if (cinfo->data_precision > BITS_IN_JSAMPLE)
+ WARNMS2(cinfo, JWRN_MUST_DOWNSCALE,
+ cinfo->data_precision, BITS_IN_JSAMPLE);
+ }
+ else { /* Lossy processes */
+ /* For now, precision must match compiled-in value... */
+ if (cinfo->data_precision != BITS_IN_JSAMPLE)
+ ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
+ }
+to:
+/* if (cinfo->process == JPROC_LOSSLESS) {*/
+ /* If precision > compiled-in value, we must downscale */
+/* if (cinfo->data_precision > BITS_IN_JSAMPLE)
+ WARNMS2(cinfo, JWRN_MUST_DOWNSCALE,
+ cinfo->data_precision, BITS_IN_JSAMPLE);
+ }
+ else {*/ /* Lossy processes */
+ /* For now, precision must match compiled-in value... */
+/* if (cinfo->data_precision != BITS_IN_JSAMPLE)
+ ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
+ }*/
+
+-----------------------------------------------------------------------
+jdlhuff.c (GCC4.1 Warning) from:
+ int ci;
+to:
+/* int ci;*/
+
+-----------------------------------------------------------------------
+jdmainct.c from:
+ mainp->buffer[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ compptr->width_in_data_units * compptr->codec_data_unit,
+ (JDIMENSION) (rgroup * ngroups));
+to:
+ mainp->buffer[ci] = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ compptr->width_in_data_units * compptr->codec_data_unit *
+ SIZEOF(JSAMPLE16), (JDIMENSION) (rgroup * ngroups));
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 warning)from:
+main
+to:
+mainp
+
+-----------------------------------------------------------------------
+jdmarker.c from:
+ INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
+to:
+ INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
+ cinfo->maxjsample = ((1<<cinfo->data_precision)-1);
+ cinfo->centerjsample = ((1<<cinfo->data_precision)/2);
+ cinfo->data_precision_other = 8; /* Default for compatabilty. */
+ cinfo->buffer_size_char = TRUE; /* Default for compatabilty. */
+ cinfo->shft = cinfo->data_precision - 8;
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 warning)from:
+ int n, i, prec;
+to:
+ int n, i, prec = 0;
+
+-----------------------------------------------------------------------
+jdmaster.c from:
+ (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
+ table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
+ cinfo->sample_range_limit = table;
+ /* First segment of "simple" table: limit[x] = 0 for x < 0 */
+ MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
+ /* Main part of "simple" table: limit[x] = x */
+ for (i = 0; i <= MAXJSAMPLE; i++)
+ table[i] = (JSAMPLE) i;
+ table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
+ /* End of simple table, rest of first half of post-IDCT table */
+ for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
+ table[i] = MAXJSAMPLE;
+ /* Second half of post-IDCT table */
+ MEMZERO(table + (2 * (MAXJSAMPLE+1)),
+ (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
+ MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
+ cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
+to:
+ (5 * (cinfo->maxjsample+1) + cinfo->centerjsample) * SIZEOF(JSAMPLE16));
+ table += (cinfo->maxjsample+1); /* allow negative subscripts of simple table */
+ cinfo->sample_range_limit = table;
+ /* First segment of "simple" table: limit[x] = 0 for x < 0 */
+ MEMZERO(table - (cinfo->maxjsample+1), (cinfo->maxjsample+1) * SIZEOF(JSAMPLE16));
+ /* Main part of "simple" table: limit[x] = x */
+ for (i = 0; i <= cinfo->maxjsample; i++)
+ table[i] = (JSAMPLE16) i;
+ table += cinfo->centerjsample; /* Point to where post-IDCT table starts */
+ /* End of simple table, rest of first half of post-IDCT table */
+ for (i = cinfo->centerjsample; i < 2*(cinfo->maxjsample+1); i++)
+ table[i] = cinfo->maxjsample;
+ /* Second half of post-IDCT table */
+ MEMZERO(table + (2 * (cinfo->maxjsample+1)),
+ (2 * (cinfo->maxjsample+1) - cinfo->centerjsample) * SIZEOF(JSAMPLE16));
+ MEMCOPY(table + (4 * (cinfo->maxjsample+1) - cinfo->centerjsample),
+ cinfo->sample_range_limit, cinfo->centerjsample * SIZEOF(JSAMPLE16));
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JDIMENSION jd_samplesperrow;
+to:
+ JDIMENSION jd_samplesperrow;
+ JSAMPROW colormap_in_ptr;
+ JSAMPROW16 colormap_out_ptr;
+ int sample, col;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cinfo->colormap = NULL;
+ } else if (cinfo->colormap != NULL) {
+ cinfo->enable_external_quant = TRUE;
+to:
+ cinfo->colormap = NULL;
+ cinfo->colormap16 = NULL;
+ } else if (cinfo->colormap != NULL) {
+ if (cinfo->colormap16 == NULL) {
+ /* Copy the color map to 16 bits */
+ cinfo->colormap16 =
+ (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) ((cinfo->maxjsample + 1) * SIZEOF(JSAMPLE16)),
+ (JDIMENSION) cinfo->out_color_components);
+ for (sample = 0; sample < cinfo->out_color_components; sample++) {
+ colormap_in_ptr = cinfo->colormap[sample];
+ colormap_out_ptr = cinfo->colormap16[sample];
+ for (col = 0; col < cinfo->actual_number_of_colors; col++)
+ *colormap_out_ptr++ = (JSAMPLE16)*colormap_in_ptr++;
+ }
+ }
+ } else if (cinfo->colormap16 != NULL) {
+ cinfo->enable_external_quant = TRUE;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ if (cinfo->quantize_colors && cinfo->colormap == NULL) {
+to:
+ if (cinfo->quantize_colors && cinfo->colormap16 == NULL) {
+++++++++++++++++++++++++++++++++++++++++
+from:
+ if (cinfo->quantize_colors && cinfo->enable_external_quant &&
+ cinfo->colormap != NULL) {
+to:
+ if (cinfo->quantize_colors && cinfo->enable_external_quant &&
+ cinfo->colormap16 != NULL) {
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 warning) in 2 places from:
+main
+to:
+mainp
+
+-----------------------------------------------------------------------
+jdmerge.c from:
+ upsample->Cr_r_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(int));
+ upsample->Cb_b_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(int));
+ upsample->Cr_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(INT32));
+ upsample->Cb_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (MAXJSAMPLE+1) * SIZEOF(INT32));
+
+ for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
+to:
+ upsample->Cr_r_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(int));
+ upsample->Cb_b_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(int));
+ upsample->Cr_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(INT32));
+ upsample->Cb_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(INT32));
+
+ for (i = 0, x = -cinfo->centerjsample; i <= cinfo->maxjsample; i++, x++) {
+
+-----------------------------------------------------------------------
+jdpostct.c in 4 places from:
+ post->buffer = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->output_width * cinfo->out_color_components,
+to:
+ post->buffer = (JSAMPARRAY16)(*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->output_width * cinfo->out_color_components,
+++++++++++++++++++++++++++++++++++++++++
+from:
+ post->buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->output_width * cinfo->out_color_components,
+to:
+ post->buffer = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->output_width * cinfo->out_color_components * SIZEOF(JSAMPLE16),
+++++++++++++++++++++++++++++++++++++++++
+from:
+ post->whole_image = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ cinfo->output_width * cinfo->out_color_components,
+to:
+ post->whole_image = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ cinfo->output_width * cinfo->out_color_components * SIZEOF(JSAMPLE16),
+-----------------------------------------------------------------------
+jdsample.c from:
+#if BITS_IN_JSAMPLE == 8
+ register int thiscolsum, lastcolsum, nextcolsum;
+#else
+ register INT32 thiscolsum, lastcolsum, nextcolsum;
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8
+ register int thiscolsum, lastcolsum, nextcolsum;
+#else*/
+ register INT32 thiscolsum, lastcolsum, nextcolsum;
+/*#endif*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+ upsample->color_buf[ci] = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) cinfo->output_width,
+ (long) cinfo->max_h_samp_factor),
+to:
+ upsample->color_buf[ci] = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) cinfo->output_width * SIZEOF(JSAMPLE16),
+ (long) cinfo->max_h_samp_factor),
+
+-----------------------------------------------------------------------
+jdscale.c from:
+ downscale = BITS_IN_JSAMPLE < cinfo->data_precision ?
+ cinfo->data_precision - BITS_IN_JSAMPLE : 0;
+to:
+ downscale = cinfo->data_precision < cinfo->data_precision_other ?
+ cinfo->data_precision - cinfo->data_precision_other : 0;
+
+-----------------------------------------------------------------------
+jdtran.c from:
+ j_lossy_d_ptr decomp;
+to:
+/* j_lossy_d_ptr decomp;*/
+
+-----------------------------------------------------------------------
+jerror.h from:
+JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
+to:
+JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
+JMESSAGE(JERR_BAD_CROP_SPEC, "Invalid crop request")
+++++++++++++++++++++++++++++++++++++++++
+from:
+JMESSAGE(JERR_BAD_DIFF, "spatial difference out of range")
+to:
+JMESSAGE(JERR_BAD_DIFF, "spatial difference out of range")
+JMESSAGE(JERR_BAD_DROP_SAMPLING,
+ "Component index %d: mismatching sampling ratio %d:%d, %d:%d, %c")
+++++++++++++++++++++++++++++++++++++++++
+from:
+JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
+to:
+JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
+JMESSAGE(JWRN_SCALED, "Data scaled from %d bits to %d bits")
+++++++++++++++++++++++++++++++++++++++++
+from:
+#define ERREXITS(cinfo,code,str) \
+to:
+#define ERREXIT6(cinfo,code,p1,p2,p3,p4,p5,p6) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (cinfo)->err->msg_parm.i[2] = (p3), \
+ (cinfo)->err->msg_parm.i[3] = (p4), \
+ (cinfo)->err->msg_parm.i[4] = (p5), \
+ (cinfo)->err->msg_parm.i[5] = (p6), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXITS(cinfo,code,str) \
+
+-----------------------------------------------------------------------
+jfdctfst.c from:
+jpeg_fdct_ifast (DCTELEM * data)
+to:
+jpeg_fdct_ifast (DCTELEM * data,boolean jpeg8)
+
+-----------------------------------------------------------------------
+jfdctint.c from:
+#if BITS_IN_JSAMPLE == 8
+#define CONST_BITS 13
+#define PASS1_BITS 2
+#else
+#define CONST_BITS 13
+#define PASS1_BITS 1 /* lose a little precision to avoid overflow */
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8*/
+#define CONST_BITS 13
+/*#define PASS1_BITS 2
+#else
+#define CONST_BITS 13
+#define PASS1_BITS 1*/ /* lose a little precision to avoid overflow */
+/*#endif*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+#if BITS_IN_JSAMPLE == 8
+#define MULTIPLY(var,const) MULTIPLY16C16(var,const)
+#else
+#define MULTIPLY(var,const) ((var) * (const))
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8
+#define MULTIPLY(var,const) MULTIPLY16C16(var,const)
+#else
+#define MULTIPLY(var,const) ((var) * (const))
+#endif*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+jpeg_fdct_islow (DCTELEM * data)
+to:
+jpeg_fdct_islow (DCTELEM * data, boolean jpeg8)
+++++++++++++++++++++++++++++++++++++++++
+from:
+ int ctr;
+ SHIFT_TEMPS
+to:
+ int ctr, pass1_bits;
+
+ /* set pass1_bits */
+ if (jpeg8) pass1_bits = 2;
+ else pass1_bits = 1;
+
+ SHIFT_TEMPS
+++++++++++++++++++++++++++++++++++++++++
+from:
+ dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
+ dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
+
+ z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
+ dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
+ CONST_BITS-PASS1_BITS);
+ dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
+ CONST_BITS-PASS1_BITS);
+to:
+ dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << pass1_bits);
+ dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << pass1_bits);
+
+ if (jpeg8){
+ z1 = MULTIPLY16C16(tmp12 + tmp13, FIX_0_541196100);
+ dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY16C16(tmp13, FIX_0_765366865),
+ CONST_BITS-pass1_bits);
+ dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY16C16(tmp12, - FIX_1_847759065),
+ CONST_BITS-pass1_bits);
+ } else {
+ z1 = (tmp12 + tmp13) * FIX_0_541196100;
+ dataptr[2] = (DCTELEM) DESCALE(z1 + ( tmp13 * FIX_0_765366865),
+ CONST_BITS-pass1_bits);
+ dataptr[6] = (DCTELEM) DESCALE(z1 + ( tmp12 * ( - FIX_1_847759065)),
+ CONST_BITS-pass1_bits); }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+
+ z3 += z5;
+ z4 += z5;
+
+ dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
+ dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
+ dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
+ dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
+to:
+ if (jpeg8) {
+ z5 = MULTIPLY16C16(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp4 = MULTIPLY16C16(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp5 = MULTIPLY16C16(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp6 = MULTIPLY16C16(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp7 = MULTIPLY16C16(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY16C16(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY16C16(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY16C16(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY16C16(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ } else {
+ z5 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */
+
+ tmp4 = tmp4 * FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp5 = tmp5 * FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp6 = tmp6 * FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp7 = tmp7 * FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = z1 * (- FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = z2 * (- FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = z3 * (- FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = z4 * (- FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ }
+
+ z3 += z5;
+ z4 += z5;
+
+ dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-pass1_bits);
+ dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-pass1_bits);
+ dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-pass1_bits);
+ dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-pass1_bits);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
+ dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
+
+ z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
+ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
+ CONST_BITS+PASS1_BITS);
+ dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
+ CONST_BITS+PASS1_BITS);
+to:
+ if (jpeg8) {
+ z1 = MULTIPLY16C16(tmp12 + tmp13, FIX_0_541196100);
+ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY16C16(tmp13, FIX_0_765366865),
+ CONST_BITS+pass1_bits);
+ dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY16C16(tmp12, - FIX_1_847759065),
+ CONST_BITS+pass1_bits);
+ } else {
+ z1 = (tmp12 + tmp13) * FIX_0_541196100;
+ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + (tmp13 * FIX_0_765366865),
+ CONST_BITS+pass1_bits);
+ dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + (tmp12 * (- FIX_1_847759065)),
+ CONST_BITS+pass1_bits);
+ }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+
+ z3 += z5;
+ z4 += z5;
+
+ dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
+ CONST_BITS+PASS1_BITS);
+ dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
+ CONST_BITS+PASS1_BITS);
+ dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
+ CONST_BITS+PASS1_BITS);
+ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
+ CONST_BITS+PASS1_BITS);
+to:
+ if (jpeg8) {
+ z5 = MULTIPLY16C16(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp4 = MULTIPLY16C16(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp5 = MULTIPLY16C16(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp6 = MULTIPLY16C16(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp7 = MULTIPLY16C16(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY16C16(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY16C16(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY16C16(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY16C16(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ } else {
+ z5 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */
+
+ tmp4 = tmp4 * FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp5 = tmp5 * FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp6 = tmp6 * FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp7 = tmp7 * FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = z1 * ( - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = z2 * ( - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = z3 * ( - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = z4 * ( - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ }
+ z3 += z5;
+ z4 += z5;
+
+ dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
+ CONST_BITS+pass1_bits);
+ dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
+ CONST_BITS+pass1_bits);
+ dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
+ CONST_BITS+pass1_bits);
+ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
+ CONST_BITS+pass1_bits);
+
+-----------------------------------------------------------------------
+jidctfst.c from:
+#if BITS_IN_JSAMPLE == 8
+#define CONST_BITS 8
+#define PASS1_BITS 2
+#else
+#define CONST_BITS 8
+#define PASS1_BITS 1 /* lose a little precision to avoid overflow */
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8*/
+#define CONST_BITS 8
+/*#define PASS1_BITS 2
+#else
+#define CONST_BITS 8
+#define PASS1_BITS 1*/ /* lose a little precision to avoid overflow */
+/*#endif*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+#if BITS_IN_JSAMPLE == 8
+#define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
+#else
+#define DEQUANTIZE(coef,quantval) \
+ DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8
+#define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
+#else
+#define DEQUANTIZE(coef,quantval) \
+ DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
+#endif*/
+/* IFAST_SCALE_BITS-PASS1_BITS now isbMp1b */
+++++++++++++++++++++++++++++++++++++++++
+from:
+#if BITS_IN_JSAMPLE == 8
+#define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
+#else
+#define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8
+#define DCTELEMBITS 16*/ /* DCTELEM may be 16 or 32 bits */
+/*#else*/
+#define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
+/*#endif*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+ int ctr;
+ int workspace[DCTSIZE2]; /* buffers data between passes */
+ SHIFT_TEMPS /* for DESCALE */
+ ISHIFT_TEMPS /* for IDESCALE */
+to:
+ int ctr, pass1_bits, dcval, isbMp1b;
+ boolean jpeg8;
+ int workspace[DCTSIZE2]; /* buffers data between passes */
+ SHIFT_TEMPS /* for DESCALE */
+ ISHIFT_TEMPS /* for IDESCALE */
+
+ /* set pass1_bits */
+ if (cinfo->data_precision <= 8) {
+ pass1_bits = 2;
+ isbMp1b = 0;/*was IFAST_SCALE_BITS-PASS1_BITS (2-2)*/
+ jpeg8 = TRUE;
+ } else {
+ pass1_bits = 1;
+ isbMp1b = 12;/*was IFAST_SCALE_BITS-PASS1_BITS (13-1)*/
+ jpeg8 = FALSE; }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+to:
+ if( jpeg8 ) dcval = (int)((IFAST_MULT_TYPE)inptr[DCTSIZE*0] * quantptr[DCTSIZE*0]);
+ else dcval = (int)DESCALE(inptr[DCTSIZE*0] * quantptr[DCTSIZE*0], isbMp1b);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+ tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
+ tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
+ tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
+to:
+ if( jpeg8 ) {
+ tmp0 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*0] * quantptr[DCTSIZE*0]);
+ tmp1 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*2] * quantptr[DCTSIZE*2]);
+ tmp2 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*4] * quantptr[DCTSIZE*4]);
+ tmp3 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*6] * quantptr[DCTSIZE*6]);
+ } else {
+ tmp0 = DESCALE(inptr[DCTSIZE*0] * quantptr[DCTSIZE*0], isbMp1b);
+ tmp1 = DESCALE(inptr[DCTSIZE*2] * quantptr[DCTSIZE*2], isbMp1b);
+ tmp2 = DESCALE(inptr[DCTSIZE*4] * quantptr[DCTSIZE*4], isbMp1b);
+ tmp3 = DESCALE(inptr[DCTSIZE*6] * quantptr[DCTSIZE*6], isbMp1b); }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+ tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
+to:
+ if( jpeg8 ) {
+ tmp4 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*1] * quantptr[DCTSIZE*1]);
+ tmp5 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*3] * quantptr[DCTSIZE*3]);
+ tmp6 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*5] * quantptr[DCTSIZE*5]);
+ tmp7 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*7] * quantptr[DCTSIZE*7]);
+ } else {
+ tmp4 = DESCALE(inptr[DCTSIZE*1] * quantptr[DCTSIZE*1], isbMp1b);
+ tmp5 = DESCALE(inptr[DCTSIZE*3] * quantptr[DCTSIZE*3], isbMp1b);
+ tmp6 = DESCALE(inptr[DCTSIZE*5] * quantptr[DCTSIZE*5], isbMp1b);
+ tmp7 = DESCALE(inptr[DCTSIZE*7] * quantptr[DCTSIZE*7], isbMp1b); }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
+to:
+ JSAMPLE16 dcval = range_limit[IDESCALE(wsptr[0], pass1_bits+3)
+++++++++++++++++++++++++++++++++++++++++
+from:
+ outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
+ & RANGE_MASK];
+to:
+ outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, pass1_bits+3)
+ & RANGE_MASK];
+
+-----------------------------------------------------------------------
+jidctint.c from:
+#if BITS_IN_JSAMPLE == 8
+#define CONST_BITS 13
+#define PASS1_BITS 2
+#else
+#define CONST_BITS 13
+#define PASS1_BITS 1 /* lose a little precision to avoid overflow */
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8*/
+#define CONST_BITS 13
+/*#define PASS1_BITS 2
+#else
+#define CONST_BITS 13
+#define PASS1_BITS 1*/ /* lose a little precision to avoid overflow */
+/*#endif*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+#if BITS_IN_JSAMPLE == 8
+#define MULTIPLY(var,const) MULTIPLY16C16(var,const)
+#else
+#define MULTIPLY(var,const) ((var) * (const))
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8
+#define MULTIPLY(var,const) MULTIPLY16C16(var,const)
+#else
+#define MULTIPLY(var,const) ((var) * (const))
+#endif*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+ int ctr;
+ int workspace[DCTSIZE2]; /* buffers data between passes */
+ SHIFT_TEMPS
+to:
+ int ctr, pass1_bits;
+ int workspace[DCTSIZE2]; /* buffers data between passes */
+ boolean jpeg8;
+ SHIFT_TEMPS
+
+ /* set pass1_bits */
+ if (cinfo->data_precision <= 8) {
+ pass1_bits = 2;
+ jpeg8 = TRUE;
+ } else {
+ pass1_bits = 1;
+ jpeg8 = FALSE; }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
+to:
+ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << pass1_bits;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
+ tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
+ tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
+to:
+ if( jpeg8 ) {
+ z1 = MULTIPLY16C16(z2 + z3, FIX_0_541196100);
+ tmp2 = z1 + MULTIPLY16C16(z3, - FIX_1_847759065);
+ tmp3 = z1 + MULTIPLY16C16(z2, FIX_0_765366865);
+ } else {
+ z1 = (z2 + z3) * FIX_0_541196100;
+ tmp2 = z1 + (z3 * (- FIX_1_847759065));
+ tmp3 = z1 + (z2 * FIX_0_765366865);
+ }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+to:
+ if( jpeg8 ) {
+ z5 = MULTIPLY16C16(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp0 = MULTIPLY16C16(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = MULTIPLY16C16(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = MULTIPLY16C16(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = MULTIPLY16C16(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY16C16(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY16C16(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY16C16(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY16C16(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ } else {
+ z5 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */
+
+ tmp0 = tmp0 * FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = tmp1 * FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = tmp2 * FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = tmp3 * FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = z1 * ( - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = z2 * ( - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = z3 * ( - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = z4 * ( - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
+ wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
+to:
+ wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-pass1_bits);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
+to:
+ JSAMPLE16 dcval = range_limit[(int) DESCALE((INT32) wsptr[0], pass1_bits+3)
+++++++++++++++++++++++++++++++++++++++++
+from:
+ z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
+ tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
+ tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
+to:
+ if( jpeg8 ) {
+ z1 = MULTIPLY16C16(z2 + z3, FIX_0_541196100);
+ tmp2 = z1 + MULTIPLY16C16(z3, - FIX_1_847759065);
+ tmp3 = z1 + MULTIPLY16C16(z2, FIX_0_765366865);
+ } else {
+ z1 = (z2 + z3) * FIX_0_541196100;
+ tmp2 = z1 + (z3 * ( - FIX_1_847759065));
+ tmp3 = z1 + (z2 * FIX_0_765366865);
+ }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+to:
+ if( jpeg8 ) {
+ z5 = MULTIPLY16C16(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp0 = MULTIPLY16C16(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = MULTIPLY16C16(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = MULTIPLY16C16(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = MULTIPLY16C16(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY16C16(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY16C16(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY16C16(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY16C16(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ } else {
+ z5 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */
+
+ tmp0 = tmp0 * FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = tmp1 * FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = tmp2 * FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = tmp3 * FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = z1 * ( - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = z2 * ( - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = z3 * ( - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = z4 * ( - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
+ CONST_BITS+PASS1_BITS+3)
+ & RANGE_MASK];
+ outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
+ CONST_BITS+PASS1_BITS+3)
+to:
+ outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
+ CONST_BITS+pass1_bits+3)
+
+-----------------------------------------------------------------------
+jidctred.c from:
+#if BITS_IN_JSAMPLE == 8
+#define CONST_BITS 13
+#define PASS1_BITS 2
+#else
+#define CONST_BITS 13
+#define PASS1_BITS 1 /* lose a little precision to avoid overflow */
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8*/
+#define CONST_BITS 13
+/*#define PASS1_BITS 2
+#else
+#define CONST_BITS 13
+#define PASS1_BITS 1*/ /* lose a little precision to avoid overflow */
+/*#endif*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+#if BITS_IN_JSAMPLE == 8
+#define MULTIPLY(var,const) MULTIPLY16C16(var,const)
+#else
+#define MULTIPLY(var,const) ((var) * (const))
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8
+#define MULTIPLY(var,const) MULTIPLY16C16(var,const)
+#else
+#define MULTIPLY(var,const) ((var) * (const))
+#endif*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+ int ctr;
+ int workspace[DCTSIZE*4]; /* buffers data between passes */
+ SHIFT_TEMPS
+to:
+ int ctr, pass1_bits;
+ int workspace[DCTSIZE*4]; /* buffers data between passes */
+ boolean jpeg8;
+ SHIFT_TEMPS
+
+ /* set pass1_bits */
+ if (cinfo->data_precision <= 8) {
+ pass1_bits = 2;
+ jpeg8 = TRUE;
+ } else {
+ pass1_bits = 1;
+ jpeg8 = FALSE; }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
+to:
+ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << pass1_bits;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
+to:
+ if (jpeg8) tmp2 = MULTIPLY16C16(z2, FIX_1_847759065) + MULTIPLY16C16(z3, - FIX_0_765366865);
+ else tmp2 = (z2 * FIX_1_847759065) + (z3* ( - FIX_0_765366865));
+++++++++++++++++++++++++++++++++++++++++
+from:
+ tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
+ + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
+ + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
+ + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
+
+ tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
+ + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
+ + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
+ + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
+
+ /* Final output stage */
+
+ wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
+ wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
+ wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
+ wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
+to:
+ if (jpeg8) {
+ tmp0 = MULTIPLY16C16(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
+ + MULTIPLY16C16(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
+ + MULTIPLY16C16(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
+ + MULTIPLY16C16(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
+
+ tmp2 = MULTIPLY16C16(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
+ + MULTIPLY16C16(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
+ + MULTIPLY16C16(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
+ + MULTIPLY16C16(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
+ } else {
+ tmp0 = (z1 * ( - FIX_0_211164243)) /* sqrt(2) * (c3-c1) */
+ + (z2 * FIX_1_451774981) /* sqrt(2) * (c3+c7) */
+ + (z3 * ( - FIX_2_172734803)) /* sqrt(2) * (-c1-c5) */
+ + (z4 * FIX_1_061594337); /* sqrt(2) * (c5+c7) */
+
+ tmp2 = (z1 * ( - FIX_0_509795579)) /* sqrt(2) * (c7-c5) */
+ + (z2 * ( - FIX_0_601344887)) /* sqrt(2) * (c5-c1) */
+ + (z3 * FIX_0_899976223) /* sqrt(2) * (c3-c7) */
+ + (z4 * FIX_2_562915447); /* sqrt(2) * (c1+c3) */
+ }
+
+ /* Final output stage */
+
+ wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-pass1_bits+1);
+ wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-pass1_bits+1);
+ wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-pass1_bits+1);
+ wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-pass1_bits+1);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
+to:
+ JSAMPLE16 dcval = range_limit[(int) DESCALE((INT32) wsptr[0], pass1_bits+3)
+++++++++++++++++++++++++++++++++++++++++
+from:
+ tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
+ + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
+to:
+ if (jpeg8) tmp2 = MULTIPLY16C16((INT32) wsptr[2], FIX_1_847759065)
+ + MULTIPLY16C16((INT32) wsptr[6], - FIX_0_765366865);
+ else tmp2 = ((INT32) wsptr[2] * FIX_1_847759065)
+ + ((INT32) wsptr[6] * ( - FIX_0_765366865));
+++++++++++++++++++++++++++++++++++++++++
+from:
+ tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
+ + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
+ + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
+ + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
+
+ tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
+ + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
+ + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
+ + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
+
+ /* Final output stage */
+
+ outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
+ CONST_BITS+PASS1_BITS+3+1)
+ & RANGE_MASK];
+ outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
+ CONST_BITS+PASS1_BITS+3+1)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
+ CONST_BITS+PASS1_BITS+3+1)
+ & RANGE_MASK];
+ outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
+ CONST_BITS+PASS1_BITS+3+1)
+to:
+ if (jpeg8) {
+ tmp0 = MULTIPLY16C16(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
+ + MULTIPLY16C16(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
+ + MULTIPLY16C16(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
+ + MULTIPLY16C16(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
+
+ tmp2 = MULTIPLY16C16(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
+ + MULTIPLY16C16(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
+ + MULTIPLY16C16(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
+ + MULTIPLY16C16(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
+ } else {
+ tmp0 = (z1 * ( - FIX_0_211164243)) /* sqrt(2) * (c3-c1) */
+ + (z2 * FIX_1_451774981) /* sqrt(2) * (c3+c7) */
+ + (z3 * ( - FIX_2_172734803)) /* sqrt(2) * (-c1-c5) */
+ + (z4 * FIX_1_061594337); /* sqrt(2) * (c5+c7) */
+
+ tmp2 = (z1 * ( - FIX_0_509795579)) /* sqrt(2) * (c7-c5) */
+ + (z2 * ( - FIX_0_601344887)) /* sqrt(2) * (c5-c1) */
+ + (z3 * FIX_0_899976223) /* sqrt(2) * (c3-c7) */
+ + (z4 * FIX_2_562915447); /* sqrt(2) * (c1+c3) */
+ }
+
+ /* Final output stage */
+
+ outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
+ CONST_BITS+pass1_bits+3+1)
+ & RANGE_MASK];
+ outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
+ CONST_BITS+pass1_bits+3+1)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
+ CONST_BITS+pass1_bits+3+1)
+ & RANGE_MASK];
+ outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
+ CONST_BITS+pass1_bits+3+1)
+++++++++++++++++++++++++++++++++++++++++
+from:
+ int ctr;
+ int workspace[DCTSIZE*2]; /* buffers data between passes */
+ SHIFT_TEMPS
+to:
+ int ctr, pass1_bits;
+ int workspace[DCTSIZE*2]; /* buffers data between passes */
+ boolean jpeg8;
+ SHIFT_TEMPS
+
+ /* set pass1_bits */
+ if (cinfo->data_precision <= 8) {
+ pass1_bits = 2;
+ jpeg8 = TRUE;
+ } else {
+ pass1_bits = 1;
+ jpeg8 = FALSE; }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
+to:
+ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << pass1_bits;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+ tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
+
+ /* Final output stage */
+
+ wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
+ wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
+to:
+ if (jpeg8) {
+ tmp0 = MULTIPLY16C16(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ tmp0 += MULTIPLY16C16(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ tmp0 += MULTIPLY16C16(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+ tmp0 += MULTIPLY16C16(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
+ } else {
+ tmp0 = z1 * ( - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ tmp0 += (z1 * FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ tmp0 += (z1 * ( - FIX_1_272758580)); /* sqrt(2) * (-c1+c3-c5-c7) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+ tmp0 += (z1 * FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
+ }
+
+ /* Final output stage */
+
+ wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-pass1_bits+2);
+ wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-pass1_bits+2);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
+to:
+ JSAMPLE16 dcval = range_limit[(int) DESCALE((INT32) wsptr[0], pass1_bits+3)
+++++++++++++++++++++++++++++++++++++++++
+from:
+ tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
+ + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
+ + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
+ + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
+
+ /* Final output stage */
+
+ outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
+ CONST_BITS+PASS1_BITS+3+2)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
+ CONST_BITS+PASS1_BITS+3+2)
+to:
+ if (jpeg8) tmp0 = MULTIPLY16C16((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
+ + MULTIPLY16C16((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
+ + MULTIPLY16C16((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
+ + MULTIPLY16C16((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
+ else tmp0 = ((INT32) wsptr[7] * ( - FIX_0_720959822)) /* sqrt(2) * (c7-c5+c3-c1) */
+ + ((INT32) wsptr[5] * FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
+ + ((INT32) wsptr[3] * ( - FIX_1_272758580)) /* sqrt(2) * (-c1+c3-c5-c7) */
+ + ((INT32) wsptr[1] * FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
+
+ /* Final output stage */
+
+ outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
+ CONST_BITS+pass1_bits+3+2)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
+ CONST_BITS+pass1_bits+3+2)
+
+-----------------------------------------------------------------------
+jlossls.h from:
+/* Compression module initialization routines */
+EXTERN(void) jinit_lhuff_encoder JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_differencer JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_c_scaler JPP((j_compress_ptr cinfo));
+/* Decompression module initialization routines */
+EXTERN(void) jinit_lhuff_decoder JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_undifferencer JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_d_scaler JPP((j_decompress_ptr cinfo));
+to:
+/* Compression module initialization routines */
+EXTERN(void) jinit_lossless_c_codec JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_lhuff_encoder JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_differencer JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_c_scaler JPP((j_compress_ptr cinfo));
+/* Decompression module initialization routines */
+EXTERN(void) jinit_lossless_d_codec JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_lhuff_decoder JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_undifferencer JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_d_scaler JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_d_diff_controller JPP((j_decompress_ptr cinfo, boolean need_full_buffer));
+
+-----------------------------------------------------------------------
+jmmemmgr.c from:
+ JSAMPARRAY mem_buffer; /* => the in-memory buffer */
+(stays JSAMPARRAY)to:
+ JSAMPARRAY mem_buffer; /* => the in-memory buffer */
+
+++++++++++++++++++++++++++++++++++++++++
+in:
+METHODDEF(JSAMPARRAY)
+alloc_sarray (j_common_ptr cinfo, int pool_id,
+stays without "16"
+++++++++++++++++++++++++++++++++++++++++
+from:
+METHODDEF(JSAMPARRAY)
+access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
+(stays JSAMPARRAY)to:
+METHODDEF(JSAMPARRAY)
+access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
+-----------------------------------------------------------------------
+jmorecfg.h from:
+#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
+to:
+#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
+/* Now is 16 for defines and cinfo->data_precision or
+ * cinfo->data_precision_other for data values,
+ * but is left at 8 for compatibility. */
+++++++++++++++++++++++++++++++++++++++++
+from:
+#if BITS_IN_JSAMPLE == 8
+/* JSAMPLE should be the smallest type that will hold the values 0..255.
+ * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
+ */
+
+#ifdef HAVE_UNSIGNED_CHAR
+
+typedef unsigned char JSAMPLE;
+#define GETJSAMPLE(value) ((int) (value))
+
+#else /* not HAVE_UNSIGNED_CHAR */
+
+typedef char JSAMPLE;
+#ifdef CHAR_IS_UNSIGNED
+#define GETJSAMPLE(value) ((int) (value))
+#else
+#define GETJSAMPLE(value) ((int) (value) & 0xFF)
+#endif /* CHAR_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_CHAR */
+
+#define MAXJSAMPLE 255
+#define CENTERJSAMPLE 128
+
+#endif /* BITS_IN_JSAMPLE == 8 */
+
+
+#if BITS_IN_JSAMPLE == 12
+/* JSAMPLE should be the smallest type that will hold the values 0..4095.
+ * On nearly all machines "short" will do nicely.
+ */
+
+typedef short JSAMPLE;
+#define GETJSAMPLE(value) ((int) (value))
+
+#define MAXJSAMPLE 4095
+#define CENTERJSAMPLE 2048
+
+#endif /* BITS_IN_JSAMPLE == 12 */
+
+
+#if BITS_IN_JSAMPLE == 16
+/* JSAMPLE should be the smallest type that will hold the values 0..65535.
+ * You can use a signed short by having GETJSAMPLE mask it with 0xFFFF.
+ */
+
+#ifdef HAVE_UNSIGNED_SHORT
+
+typedef unsigned short JSAMPLE;
+#define GETJSAMPLE(value) ((int) (value))
+
+#else /* not HAVE_UNSIGNED_SHORT */
+
+typedef short JSAMPLE;
+#ifdef SHORT_IS_UNSIGNED
+#define GETJSAMPLE(value) ((int) (value))
+#else
+#define GETJSAMPLE(value) ((int) (value) & 0xFFFF)
+#endif /* SHORT_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_SHORT */
+
+#define MAXJSAMPLE 65535
+#define CENTERJSAMPLE 32768
+
+#endif /* BITS_IN_JSAMPLE == 16 */
+to:
+/*#if BITS_IN_JSAMPLE == 8*/
+/* JSAMPLE should be the smallest type that will hold the values 0..255.
+ * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
+ */
+
+#ifdef HAVE_UNSIGNED_CHAR
+
+typedef unsigned char JSAMPLE8;
+/*#define GETJSAMPLE(value) ((int) (value))*/
+
+#else /* not HAVE_UNSIGNED_CHAR */
+
+typedef char JSAMPLE8;
+/*#ifdef CHAR_IS_UNSIGNED
+#define GETJSAMPLE(value) ((int) (value))
+#else
+#define GETJSAMPLE(value) ((int) (value) & 0xFF)
+#endif*/ /* CHAR_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_CHAR */
+
+/*#define MAXJSAMPLE 255
+#define CENTERJSAMPLE 128
+
+#endif*/ /* BITS_IN_JSAMPLE == 8 */
+
+
+/*#if BITS_IN_JSAMPLE == 12*/
+/* JSAMPLE should be the smallest type that will hold the values 0..4095.
+ * On nearly all machines "short" will do nicely.
+ */
+
+/*typedef short JSAMPLE;
+#define GETJSAMPLE(value) ((int) (value))
+
+#define MAXJSAMPLE 4095
+#define CENTERJSAMPLE 2048
+
+#endif*/ /* BITS_IN_JSAMPLE == 12 */
+
+
+/*#if BITS_IN_JSAMPLE == 16*/
+/* JSAMPLE16 should be the smallest type that will hold the values 0..65535.
+ * You can use a signed short by having GETJSAMPLE mask it with 0xFFFF.
+ */
+/* Always 16 now. 0xFFFF is now mask ( 0xFF, 0xFFF or 0xFFFF )*/
+/* Added 12 bit mask, may not be needed. */
+#ifdef HAVE_UNSIGNED_SHORT
+
+typedef unsigned short JSAMPLE16;
+#define GETJSAMPLE(value) ((int) (value))
+
+#else /* not HAVE_UNSIGNED_SHORT */
+
+typedef short JSAMPLE16;
+#ifdef SHORT_IS_UNSIGNED
+#define GETJSAMPLE(value) ((int) (value))
+#else
+#define GETJSAMPLE(value) ((int) (value) & cinfo->maskjsample)
+#define HAVE_GETJSAMPLE_MASK 1
+#endif /* SHORT_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_SHORT */
+
+#define JSAMPLEMAX 16 /* Maximum bits in JSAMPLE16 */
+
+/*#define MAXJSAMPLE 65535
+#define CENTERJSAMPLE 32768
+
+#endif*/ /* BITS_IN_JSAMPLE == 16 */
+
+-----------------------------------------------------------------------
+jpegint.h from:
+ JMETHOD(void, process_data, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+(stays JSAMPARRAY)to:
+ JMETHOD(void, process_data, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf,
+ JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail,
+ JSAMPIMAGE output_buf,
+(stays JSAMPARRAY)to:
+ JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf,
+ JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail,
+ JSAMPIMAGE16 output_buf,
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JMETHOD(void, color_convert, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+(stays JSAMPARRAY)to:
+ JMETHOD(void, color_convert, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+
+-----------------------------------------------------------------------
+jpeglib.h from:
+ * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
+ */
+
+#define JPEG_LIB_VERSION 62 /* Version 6b */
+to:
+ * Might be useful for tests like "#if JPEG_LIB_VERSION >= 70".
+ */
+
+#define JPEG_LIB_VERSION 63 /* Version 6c */
+++++++++++++++++++++++++++++++++++++++++
+from:
+typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
+typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
+typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
+to:
+typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
+typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
+typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
+typedef JSAMPLE16 FAR *JSAMPROW16; /* ptr to one image row of pixel samples. */
+typedef JSAMPROW16 *JSAMPARRAY16; /* ptr to some rows (a 2-D sample array) */
+typedef JSAMPARRAY16 *JSAMPIMAGE16; /* a 3-D sample array: top index is color */
+++++++++++++++++++++++++++++++++++++++++
+from:
+ boolean lossless; /* TRUE=lossless encoding, FALSE=lossy */
+
+ UINT8 data_precision; /* bits of precision in image data */
+to:
+ boolean lossless; /* TRUE=lossless encoding, FALSE=lossy */
+ boolean lossless_scaling; /* If lossless is allowed to scale */
+
+ UINT8 data_precision; /* bits of precision in jpeg image data */
+ UINT8 data_precision_other; /* bits of precision in input image data */
+ UINT16 maxjsample; /* max value of jpeg bits ( 255,4095 or 65535 ) */
+ UINT16 centerjsample; /* center value of jpeg bits ( 128,2048 or 32768 ) */
+#ifdef HAVE_GETJSAMPLE_MASK
+ UINT16 maskjsample; /* mask value of the sample */
+#endif
+++++++++++++++++++++++++++++++++++++++++
+from:
+ boolean raw_data_in; /* TRUE=caller supplies downsampled data */
+to:
+ boolean raw_data_in; /* TRUE=caller supplies downsampled data */
+ JSAMPIMAGE16 raw_data_buffer; /* 8 to 16 raw data buffer */
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 Warning)from:
+ struct jpeg_c_main_controller * main;
+to:
+ struct jpeg_c_main_controller * mainp;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
+to:
+ JSAMPARRAY colormap; /* The color map as a 2-D pixel array of 8 bits */
+ JSAMPARRAY16 colormap16; /* The color map as a 2-D pixel array of 16 bits */
+++++++++++++++++++++++++++++++++++++++++
+from:
+ UINT8 data_precision; /* bits of precision in image data */
+to:
+ UINT8 data_precision; /* bits of precision in jpeg image data */
+ UINT8 data_precision_other; /* bits of precision in output image data */
+ boolean buffer_size_char /* each output pixel is char wide, default TRUE */
+ UINT16 maxjsample; /* max value of jpeg bits ( 255,4095 or 65535 ) */
+ UINT16 centerjsample; /* center value of jpeg bits ( 128,2048 or 32768 ) */
+#ifdef HAVE_GETJSAMPLE_MASK
+ UINT16 maskjsample; /* mask value of the sample */
+#endif
+ /* Used to shift data to a char. */
+ int shft;
+++++++++++++++++++++++++++++++++++++++++
+(GCC4.1 Warning)from:
+ struct jpeg_d_main_controller * main;
+to:
+ struct jpeg_d_main_controller * mainp;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JSAMPLE * sample_range_limit; /* table for fast range-limiting */
+to:
+ JSAMPLE16 * sample_range_limit; /* table for fast range-limiting */
+++++++++++++++++++++++++++++++++++++++++
+from:
+#define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
+#define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
+#define JPOOL_NUMPOOLS 2
+to:
+#define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
+#define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
+#define JPOOL_IMAGE 2 /* lasts until done with image/datastream */
+#define JPOOL_NUMPOOLS 3
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
+(stays JSAMPARRAY)to:
+ JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
+(stays JSAMPARRAY)to:
+ JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
+++++++++++++++++++++++++++++++++++++++++
+added:
+/* The fix for CPP */
+#ifdef __cplusplus
+extern "C" {
+#endif
+++++++++++++++++++++++++++++++++++++++++
+from:
+EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
+ JSAMPARRAY scanlines,
+ JDIMENSION num_lines));
+(stays JSAMPARRAY)to:
+EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
+ JSAMPARRAY scanlines,
+ JDIMENSION num_lines));
+++++++++++++++++++++++++++++++++++++++++
+from:
+EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
+ JSAMPIMAGE data,
+ JDIMENSION num_lines));
+(stays JSAMPIMAGE)to:
+EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
+ JSAMPIMAGE data,
+ JDIMENSION num_lines));
+++++++++++++++++++++++++++++++++++++++++
+from:
+EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
+ JSAMPARRAY scanlines,
+ JDIMENSION max_lines));
+(stays JSAMPARRAY)to:
+EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
+ JSAMPARRAY scanlines,
+ JDIMENSION max_lines));
+++++++++++++++++++++++++++++++++++++++++
+from:
+EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE data,
+ JDIMENSION max_lines));
+(stays JSAMPIMAGE)to:
+EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE data,
+ JDIMENSION max_lines));
+++++++++++++++++++++++++++++++++++++++++
+added:
+/* End of CPP fix */
+#ifdef __cplusplus
+}
+#endif
+
+-----------------------------------------------------------------------
+Use jpegtran.c from patch file.
+
+-----------------------------------------------------------------------
+jquant1.c from:
+#if BITS_IN_JSAMPLE == 8
+typedef INT16 FSERROR; /* 16 bits should be enough */
+typedef int LOCFSERROR; /* use 'int' for calculation temps */
+#else
+typedef INT32 FSERROR; /* may need more than 16 bits */
+typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8
+typedef INT16 FSERROR;*/ /* 16 bits should be enough */
+/*typedef int LOCFSERROR;*/ /* use 'int' for calculation temps */
+/*#else*/
+typedef INT32 FSERROR; /* may need more than 16 bits */
+typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
+/*#endif*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+ return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
+to:
+ return (int) (((INT32) j * cinfo->maxjsample + maxj/2) / maxj);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
+to:
+ return (int) (((INT32) (2*j + 1) * cinfo->maxjsample + maxj) / (2*maxj));
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JSAMPARRAY colormap; /* Created colormap */
+to:
+ JSAMPARRAY16 colormap16; /* Created colormap */
+ JSAMPARRAY colormap; /* Created 8 bit colormap */
+++++++++++++++++++++++++++++++++++++++++
+from:
+ colormap = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
+to:
+ colormap16 = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) total_colors * SIZEOF(JSAMPLE16),
+ (JDIMENSION) cinfo->out_color_components);
+
+ colormap = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) total_colors * SIZEOF(JSAMPLE),
+ (JDIMENSION) cinfo->out_color_components);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ colormap[i][ptr+k] = (JSAMPLE) val;
+to:
+ colormap16[i][ptr+k] = (JSAMPLE16) val;
+ colormap[i][ptr+k] = (JSAMPLE)(val & 0xFF);/* 8 bit too. */
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cquantize->sv_colormap = colormap;
+to:
+ cquantize->sv_colormap = colormap16;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cquantize->colorindex = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ pad = MAXJSAMPLE*2;
+to:
+ cquantize->colorindex = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) (cinfo->maxjsample+1 + pad) * SIZEOF(JSAMPLE16),
+++++++++++++++++++++++++++++++++++++++++
+from:
+ (JDIMENSION) (MAXJSAMPLE+1 + pad),
+to:
+ (JDIMENSION) (cinfo->maxjsample+1 + pad),
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cquantize->colorindex[i] += MAXJSAMPLE;
+to:
+ cquantize->colorindex[i] += cinfo->maxjsample;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ for (j = 0; j <= MAXJSAMPLE; j++) {
+to:
+ for (j = 0; j <= cinfo->maxjsample; j++) {
+++++++++++++++++++++++++++++++++++++++++
+from:
+ for (j = 1; j <= MAXJSAMPLE; j++) {
+to:
+ for (j = 1; j <= cinfo->maxjsample; j++) {
+++++++++++++++++++++++++++++++++++++++++
+from:
+ indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
+to:
+ indexptr[cinfo->maxjsample+j] = indexptr[cinfo->maxjsample];
+++++++++++++++++++++++++++++++++++++++++
+from:
+ num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
+ * MAXJSAMPLE;
+to:
+ num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
+ * cinfo->maxjsample;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cinfo->colormap = cquantize->sv_colormap;
+to:
+ cinfo->colormap16 = cquantize->sv_colormap;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
+ ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
+to:
+ if (cinfo->desired_number_of_colors > (cinfo->maxjsample+1))
+ ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, cinfo->maxjsample+1);
+
+-----------------------------------------------------------------------
+jquant2.c from:
+#define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
+to:
+#define MAXNUMCOLORS (cinfo->maxjsample+1) /* maximum size of colormap */
+++++++++++++++++++++++++++++++++++++++++
+from:
+#define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
+#define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
+#define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
+to:
+#define C0_SHIFT (cinfo->data_precision - HIST_C0_BITS)
+#define C1_SHIFT (cinfo->data_precision - HIST_C1_BITS)
+#define C2_SHIFT (cinfo->data_precision - HIST_C2_BITS)
+++++++++++++++++++++++++++++++++++++++++
+from:
+#if BITS_IN_JSAMPLE == 8
+typedef INT16 FSERROR; /* 16 bits should be enough */
+typedef int LOCFSERROR; /* use 'int' for calculation temps */
+#else
+typedef INT32 FSERROR; /* may need more than 16 bits */
+typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8
+typedef INT16 FSERROR;*/ /* 16 bits should be enough */
+/*typedef int LOCFSERROR;*/ /* use 'int' for calculation temps */
+/*#else*/
+typedef INT32 FSERROR; /* may need more than 16 bits */
+typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
+/*#endif*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JSAMPARRAY sv_colormap; /* colormap allocated at init time */
+to:
+ JSAMPARRAY16 sv_colormap; /* colormap allocated at init time */
+ JSAMPARRAY sv_colormap8; /* colormap allocated at init time */
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
+ cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
+ cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
+to:
+ cinfo->colormap16[0][icolor] = (JSAMPLE16) ((c0total + (total>>1)) / total);
+ cinfo->colormap16[1][icolor] = (JSAMPLE16) ((c1total + (total>>1)) / total);
+ cinfo->colormap16[2][icolor] = (JSAMPLE16) ((c2total + (total>>1)) / total);
+ /* Now for the 8 bits color map. */
+ cinfo->colormap[0][icolor] = (JSAMPLE) (((c0total + (total>>1)) / total) & 0xFF);
+ cinfo->colormap[1][icolor] = (JSAMPLE) (((c1total + (total>>1)) / total) & 0xFF);
+ cinfo->colormap[2][icolor] = (JSAMPLE) (((c2total + (total>>1)) / total) & 0xFF);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
+ boxlist[0].c1min = 0;
+ boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
+ boxlist[0].c2min = 0;
+ boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
+to:
+ boxlist[0].c0max = cinfo->maxjsample >> C0_SHIFT;
+ boxlist[0].c1min = 0;
+ boxlist[0].c1max = cinfo->maxjsample >> C1_SHIFT;
+ boxlist[0].c2min = 0;
+ boxlist[0].c2max = cinfo->maxjsample >> C2_SHIFT;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
+to:
+ /* mvh,bcb 20100121 Allocate and free mindist */
+ INT32 * mindist = (INT32*)jpeg_get_large((j_common_ptr)cinfo,
+ MAXNUMCOLORS * sizeof(INT32)); /* min distance to colormap entry i */
+++++++++++++++++++++++++++++++++++++++++
+from:
+ x = GETJSAMPLE(cinfo->colormap[0][i]);
+to:
+ x = GETJSAMPLE(cinfo->colormap16[0][i]);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ x = GETJSAMPLE(cinfo->colormap[1][i]);
+to:
+ x = GETJSAMPLE(cinfo->colormap16[1][i]);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ x = GETJSAMPLE(cinfo->colormap[2][i]);
+to:
+ x = GETJSAMPLE(cinfo->colormap16[2][i]);
+++++++++++++++++++++++++++++++++++++++++
+added:
+ /* mvh,bcb 20100121 Allocate and free mindist */
+ jpeg_free_large((j_common_ptr)cinfo, mindist, MAXNUMCOLORS * sizeof(INT32));
+++++++++++++++++++++++++++++++++++++++++
+from:
+ inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
+ dist0 = inc0*inc0;
+ inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
+ dist0 += inc1*inc1;
+ inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
+to:
+ inc0 = (minc0 - GETJSAMPLE(cinfo->colormap16[0][icolor])) * C0_SCALE;
+ dist0 = inc0*inc0;
+ inc1 = (minc1 - GETJSAMPLE(cinfo->colormap16[1][icolor])) * C1_SCALE;
+ dist0 += inc1*inc1;
+ inc2 = (minc2 - GETJSAMPLE(cinfo->colormap16[2][icolor])) * C2_SCALE;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JSAMPLE16 colorlist[MAXNUMCOLORS]; /* min distance to colormap entry i */
+to:
+ /* mvh,bcb 20100121 Allocate and free colorlist */
+ JSAMPLE16 *colorlist = (JSAMPLE16 *)jpeg_get_large((j_common_ptr)cinfo,
+ MAXNUMCOLORS * sizeof(INT32)); /* min distance to colormap entry i */
+++++++++++++++++++++++++++++++++++++++++
+added:
+ /* mvh,bcb 20100121 Allocate and free colorlist */
+ jpeg_free_large((j_common_ptr)cinfo, colorlist, MAXNUMCOLORS * sizeof(INT32));
+
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JSAMPROW colormap0 = cinfo->colormap[0];
+ JSAMPROW colormap1 = cinfo->colormap[1];
+ JSAMPROW colormap2 = cinfo->colormap[2];
+to:
+ JSAMPROW16 colormap0 = cinfo->colormap16[0];
+ JSAMPROW16 colormap1 = cinfo->colormap16[1];
+ JSAMPROW16 colormap2 = cinfo->colormap16[2];
+++++++++++++++++++++++++++++++++++++++++
+from:
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
+ table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
+ cquantize->error_limiter = table;
+
+#define STEPSIZE ((MAXJSAMPLE+1)/16)
+ /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
+ out = 0;
+ for (in = 0; in < STEPSIZE; in++, out++) {
+ table[in] = out; table[-in] = -out;
+ }
+ /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
+ for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
+ table[in] = out; table[-in] = -out;
+ }
+ /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
+ for (; in <= MAXJSAMPLE; in++) {
+to:
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, (cinfo->maxjsample*2+1) * SIZEOF(int));
+ table += cinfo->maxjsample; /* so can index -cinfo->maxjsample .. +cinfo->maxjsample */
+ cquantize->error_limiter = table;
+
+#define STEPSIZE ((cinfo->maxjsample+1)/16)
+ /* Map errors 1:1 up to +- cinfo->maxjsample/16 */
+ out = 0;
+ for (in = 0; in < STEPSIZE; in++, out++) {
+ table[in] = out; table[-in] = -out;
+ }
+ /* Map errors 1:2 up to +- 3*cinfo->maxjsample/16 */
+ for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
+ table[in] = out; table[-in] = -out;
+ }
+ /* Clamp the rest to final out value (which is (cinfo->maxjsample+1)/8) */
+ for (; in <= cinfo->maxjsample; in++) {
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cinfo->colormap = cquantize->sv_colormap;
+to:
+ cinfo->colormap16 = cquantize->sv_colormap;
+ cinfo->colormap = cquantize->sv_colormap8;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
+to:
+ cquantize->sv_colormap = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired
+ * SIZEOF(JSAMPLE16), (JDIMENSION) 3);
+ cquantize->sv_colormap8 = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired
+ * SIZEOF(JSAMPLE), (JDIMENSION) 3);
+
+-----------------------------------------------------------------------
+jversion.h from:
+#define JVERSION "6b 27-Mar-1998"
+to:
+#define JVERSION "7 29-Jun-2009"
+-----------------------------------------------------------------------
+makefile.cfg from:
+ jcprepct.$(O) jclossls.$(O) jclossy.o jccoefct.$(O) jccolor.$(O) \
+to:
+ jcprepct.$(O) jclossls.$(O) jclossy.$(O) jccoefct.$(O) jccolor.$(O) \
+
+-----------------------------------------------------------------------
+rdcolmap.c from:
+ JSAMPROW colormap0 = cinfo->colormap[0];
+ JSAMPROW colormap1 = cinfo->colormap[1];
+ JSAMPROW colormap2 = cinfo->colormap[2];
+to:
+ JSAMPROW16 colormap0 = cinfo->colormap16[0];
+ JSAMPROW16 colormap1 = cinfo->colormap16[1];
+ JSAMPROW16 colormap2 = cinfo->colormap16[2];
+ JSAMPROW colormap8_0 = cinfo->colormap[0];
+ JSAMPROW colormap8_1 = cinfo->colormap[1];
+ JSAMPROW colormap8_2 = cinfo->colormap[2];
+++++++++++++++++++++++++++++++++++++++++ Check later
+from:
+ if (ncolors >= (MAXJSAMPLE+1))
+ ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, (MAXJSAMPLE+1));
+to:
+ if (ncolors >= (cinfo->maxjsample+1))
+ ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, (cinfo->maxjsample+1));
+++++++++++++++++++++++++++++++++++++++++
+from:
+ /* OK, add color to map. */
+ colormap0[ncolors] = (JSAMPLE) R;
+ colormap1[ncolors] = (JSAMPLE) G;
+ colormap2[ncolors] = (JSAMPLE) B;
+to:
+ /* OK, add color to maps. */
+ colormap0[ncolors] = (JSAMPLE16) R;
+ colormap1[ncolors] = (JSAMPLE16) G;
+ colormap2[ncolors] = (JSAMPLE16) B;
+ colormap8_0[ncolors] = (JSAMPLE)(R & 0xFF);
+ colormap8_1[ncolors] = (JSAMPLE)(G & 0xFF);
+ colormap8_2[ncolors] = (JSAMPLE)(B & 0xFF);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ R << (BITS_IN_JSAMPLE-8),
+ G << (BITS_IN_JSAMPLE-8),
+ B << (BITS_IN_JSAMPLE-8));
+to:
+ R << (cinfo->data_precision -8),
+ G << (cinfo->data_precision -8),
+ B << (cinfo->data_precision -8));
+++++++++++++++++++++++++++++++++++++++++
+from:
+ if (maxval != (unsigned int) MAXJSAMPLE)
+to:
+ if (maxval != (unsigned int) cinfo->maxjsample)
+++++++++++++++++++++++++++++++++++++++++
+from:
+ /* Allocate space for a color map of maximum supported size. */
+ cinfo->colormap = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) (MAXJSAMPLE+1), (JDIMENSION) 3);
+to:
+ /* Allocate space for a color map of maximum supported size. */
+ cinfo->colormap16 = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) ((cinfo->maxjsample + 1) * SIZEOF(JSAMPLE16)), (JDIMENSION) 3);
+ cinfo->actual_number_of_colors = 0; /* initialize map to empty */
+
+-----------------------------------------------------------------------
+rdgif.c (ver 6a) from:
+ boolean out_of_blocks; /* TRUE if hit terminator data block */
+to:
+ boolean out_of_blocks; /* TRUE if hit terminator data block */
+ boolean grayscale; /* TRUE if r = g = b for all bits in the table */
+to:
+++++++++++++++++++++++++++++++++++++++++
+from:
+ReadColorMap (gif_source_ptr sinfo, int cmaplen, JSAMPARRAY cmap)
+/* Read a GIF colormap */
+{
+ int i;
+to:
+ReadColorMap (gif_source_ptr sinfo, int cmaplen, JSAMPARRAY cmap, int upscale)
+/* Read a GIF colormap */
+{
+ int i;
+ sinfo->grayscale = TRUE;
+++++++++++++++++++++++++++++++++++++++++
+from:
+#if BITS_IN_JSAMPLE == 8
+#define UPSCALE(x) (x)
+#else
+#define UPSCALE(x) ((x) << (BITS_IN_JSAMPLE-8))
+#endif
+ cmap[CM_RED][i] = (JSAMPLE) UPSCALE(ReadByte(sinfo));
+ cmap[CM_GREEN][i] = (JSAMPLE) UPSCALE(ReadByte(sinfo));
+ cmap[CM_BLUE][i] = (JSAMPLE) UPSCALE(ReadByte(sinfo));
+to:
+/*#if BITS_IN_JSAMPLE == 8
+#define UPSCALE(x) (x)
+#else
+#define UPSCALE(x) ((x) << (BITS_IN_JSAMPLE-8))
+#endif
+ cmap[CM_RED][i] = (JSAMPLE) UPSCALE(ReadByte(sinfo));
+ cmap[CM_GREEN][i] = (JSAMPLE) UPSCALE(ReadByte(sinfo));
+ cmap[CM_BLUE][i] = (JSAMPLE) UPSCALE(ReadByte(sinfo));*/
+ cmap[CM_RED][i] = (JSAMPLE)(ReadByte(sinfo) << upscale);
+ cmap[CM_GREEN][i] = (JSAMPLE) (ReadByte(sinfo) << upscale);
+ cmap[CM_BLUE][i] = (JSAMPLE) (ReadByte(sinfo) << upscale);
+ if( sinfo->grayscale ){
+ if( cmap[CM_RED][i] != cmap[CM_GREEN][i] ) sinfo->grayscale = FALSE;
+ if( cmap[CM_RED][i] != cmap[CM_BLUE][i] ) sinfo->grayscale = FALSE;
+ }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ source->colormap = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) MAXCOLORMAPSIZE, (JDIMENSION) NUMCOLORS);
+to:
+ source->colormap = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) MAXCOLORMAPSIZE * SIZEOF(JSAMPLE16),
+ (JDIMENSION) NUMCOLORS);
+++++++++++++++++++++++++++++++++++++++++
+in 2 places from:
+ ReadColorMap(source, colormaplen, source->colormap);
+to:
+ ReadColorMap(source, colormaplen, source->colormap,
+ cinfo->data_precision - cinfo->data_precision_other);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ /* Create compressor input buffer. */
+ source->pub.buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) width * NUMCOLORS, (JDIMENSION) 1);
+ source->pub.buffer_height = 1;
+
+ /* Return info about the image. */
+ cinfo->in_color_space = JCS_RGB;
+ cinfo->input_components = NUMCOLORS;
+ cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */
+ cinfo->image_width = width;
+ cinfo->image_height = height;
+
+ TRACEMS3(cinfo, 1, JTRC_GIF, width, height, colormaplen);
+to:
+ /* Return info about the image. */
+ cinfo->in_color_space = JCS_RGB;
+ cinfo->input_components = NUMCOLORS;
+ if( source->grayscale ) {
+ cinfo->in_color_space = JCS_GRAYSCALE;
+ cinfo->input_components = 1;
+ }
+ /*cinfo->data_precision = BITS_IN_JSAMPLE;*/ /* we always rescale data to this */
+/* cinfo->data_precision_other = 8; *//* Word size, not data size */
+ cinfo->data_precision = 8; /* Real datawidth */
+ cinfo->centerjsample = 128;
+ cinfo->maxjsample = 255;
+#ifdef HAVE_GETJSAMPLE_MASK
+ cinfo->maskjsample 0xFF
+#endif
+ cinfo->image_width = width;
+ cinfo->image_height = height;
+
+ TRACEMS3(cinfo, 1, JTRC_GIF, width, height, colormaplen);
+
+ /* Create compressor input buffer. */
+ source->pub.buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) width * cinfo->input_components,
+ (JDIMENSION) 1);
+ source->pub.buffer_height = 1;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ for (col = cinfo->image_width; col > 0; col--) {
+ c = LZWReadByte(source);
+ *ptr++ = colormap[CM_RED][c];
+ *ptr++ = colormap[CM_GREEN][c];
+ *ptr++ = colormap[CM_BLUE][c];
+ }
+to:
+ if (cinfo->in_color_space == JCS_GRAYSCALE) {
+ for (col = cinfo->image_width; col > 0; col--) {
+ c = LZWReadByte(source);
+ *ptr++ = colormap[CM_RED][c];
+ }
+ } else {
+ for (col = cinfo->image_width; col > 0; col--) {
+ c = LZWReadByte(source);
+ *ptr++ = colormap[CM_RED][c];
+ *ptr++ = colormap[CM_GREEN][c];
+ *ptr++ = colormap[CM_BLUE][c];
+ }
+ }
+++++++++++++++++++++++++++++++++++++++++
+from:
+ for (col = cinfo->image_width; col > 0; col--) {
+ c = GETJSAMPLE(*sptr++);
+ *ptr++ = colormap[CM_RED][c];
+ *ptr++ = colormap[CM_GREEN][c];
+ *ptr++ = colormap[CM_BLUE][c];
+to:
+ if (cinfo->in_color_space == JCS_GRAYSCALE) {
+ for (col = cinfo->image_width; col > 0; col--) {
+ c = GETJSAMPLE(*sptr++);
+ *ptr++ = colormap[CM_RED][c];
+ }
+ } else {
+ for (col = cinfo->image_width; col > 0; col--) {
+ c = GETJSAMPLE(*sptr++);
+ *ptr++ = colormap[CM_RED][c];
+ *ptr++ = colormap[CM_GREEN][c];
+ *ptr++ = colormap[CM_BLUE][c];
+ }
+ }
+
+-----------------------------------------------------------------------
+rdppm.c from:
+to:
+++++++++++++++++++++++++++++++++++++++++
+add:
+METHODDEF(JDIMENSION)
+get_text_gray_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading text-format PGM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ FILE * infile = source->pub.input_file;
+ register JSAMPROW16 ptr;
+ register JSAMPLE16 *rescale = (JSAMPROW16)source->rescale;
+ JDIMENSION col;
+
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
+ }
+ return 1;
+}
+++++++++++++++++++++++++++++++++++++++++
+add:
+METHODDEF(JDIMENSION)
+get_text_rgb_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading text-format PPM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ FILE * infile = source->pub.input_file;
+ register JSAMPROW16 ptr;
+ register JSAMPLE16 *rescale = (JSAMPROW16)source->rescale;
+ JDIMENSION col;
+
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
+ *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
+ *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
+ }
+ return 1;
+}
+++++++++++++++++++++++++++++++++++++++++
+add:
+METHODDEF(JDIMENSION)
+get_scaled_gray_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-byte-format PGM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW16 ptr;
+ register U_CHAR * bufferptr;
+ register JSAMPLE16 *rescale = (JSAMPROW16)source->rescale;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr++ = rescale[UCH(*bufferptr++)];
+ }
+ return 1;
+}
+++++++++++++++++++++++++++++++++++++++++
+add:
+METHODDEF(JDIMENSION)
+get_scaled_rgb_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-byte-format PPM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW16 ptr;
+ register U_CHAR * bufferptr;
+ register JSAMPLE16 *rescale = (JSAMPROW16)source->rescale;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr++ = rescale[UCH(*bufferptr++)];
+ *ptr++ = rescale[UCH(*bufferptr++)];
+ *ptr++ = rescale[UCH(*bufferptr++)];
+ }
+ return 1;
+}
+++++++++++++++++++++++++++++++++++++++++
+add:
+METHODDEF(JDIMENSION)
+get_corr_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-word-format maxval = MAXJSAMPLE, any endian */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW16 ptr;
+ register U_CHAR * bufferptr;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr = UCH(*bufferptr++) << 8;
+ *ptr++ |= UCH(*bufferptr++);
+ }
+ return 1;
+}
+++++++++++++++++++++++++++++++++++++++++
+to correct PGM standard MSB first, from:
+ temp = UCH(*bufferptr++);
+ temp |= UCH(*bufferptr++) << 8;
+to:
+ temp = UCH(*bufferptr++) << 8;
+ temp |= UCH(*bufferptr++);
+++++++++++++++++++++++++++++++++++++++++
+add:
+METHODDEF(JDIMENSION)
+get_word_gray_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-word-format PGM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW16 ptr;
+ register U_CHAR * bufferptr;
+ register JSAMPLE16 *rescale = (JSAMPROW16)source->rescale;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ register int temp;
+ temp = UCH(*bufferptr++) << 8;
+ temp |= UCH(*bufferptr++);
+ *ptr++ = rescale[temp];
+ }
+ return 1;
+}
+++++++++++++++++++++++++++++++++++++++++
+to correct PGM standard MSB first, from:
+ temp = UCH(*bufferptr++);
+ temp |= UCH(*bufferptr++) << 8;
+ *ptr++ = rescale[temp];
+ temp = UCH(*bufferptr++);
+ temp |= UCH(*bufferptr++) << 8;
+ *ptr++ = rescale[temp];
+ temp = UCH(*bufferptr++);
+ temp |= UCH(*bufferptr++) << 8;
+to:
+ temp = UCH(*bufferptr++) << 8;
+ temp |= UCH(*bufferptr++);
+ *ptr++ = rescale[temp];
+ temp = UCH(*bufferptr++) << 8;
+ temp |= UCH(*bufferptr++);
+ *ptr++ = rescale[temp];
+ temp = UCH(*bufferptr++) << 8;
+ temp |= UCH(*bufferptr++);
+++++++++++++++++++++++++++++++++++++++++
+add:
+METHODDEF(JDIMENSION)
+get_word_rgb_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-word-format PPM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW16 ptr;
+ register U_CHAR * bufferptr;
+ register JSAMPLE16 *rescale = (JSAMPROW16)source->rescale;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ register int temp;
+ temp = UCH(*bufferptr++);
+ temp |= UCH(*bufferptr++) << 8;
+ *ptr++ = rescale[temp];
+ temp = UCH(*bufferptr++);
+ temp |= UCH(*bufferptr++) << 8;
+ *ptr++ = rescale[temp];
+ temp = UCH(*bufferptr++);
+ temp |= UCH(*bufferptr++) << 8;
+ *ptr++ = rescale[temp];
+ }
+ return 1;
+}
+++++++++++++++++++++++++++++++++++++++++
+from:
+ int c;
+ unsigned int w, h, maxval;
+to:
+ int c, bit_width;
+ unsigned int w, h, maxval;
+/* On 16-bit-int machines we have to be careful of maxval = 65535 + 1 */
+ long maxval_shift;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */
+to:
+/* cinfo->data_precision = BITS_IN_JSAMPLE;*/ /* we always rescale data to this */
+/* Find the # of bits for maxval. */
+ cinfo->data_precision_other = 0;
+ for (maxval_shift = (long)maxval + 1L ; maxval_shift > 1; maxval_shift >>= 1)
+ cinfo->data_precision_other++;
+/* Set to 0 for: use input value from file */
+ if (cinfo->data_precision == 0)
+ cinfo->data_precision = cinfo->data_precision_other;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ source->pub.get_pixel_rows = get_text_gray_row;
+ need_iobuffer = FALSE;
+ break;
+
+ case '3': /* it's a text-format PPM file */
+ cinfo->input_components = 3;
+ cinfo->in_color_space = JCS_RGB;
+ TRACEMS2(cinfo, 1, JTRC_PPM_TEXT, w, h);
+ source->pub.get_pixel_rows = get_text_rgb_row;
+ need_iobuffer = FALSE;
+ break;
+
+ case '5': /* it's a raw-format PGM file */
+ cinfo->input_components = 1;
+ cinfo->in_color_space = JCS_GRAYSCALE;
+ TRACEMS2(cinfo, 1, JTRC_PGM, w, h);
+ if (maxval > 255) {
+ source->pub.get_pixel_rows = get_word_gray_row;
+ } else if (maxval == MAXJSAMPLE && SIZEOF(JSAMPLE) == SIZEOF(U_CHAR)) {
+ source->pub.get_pixel_rows = get_raw_row;
+ use_raw_buffer = TRUE;
+ need_rescale = FALSE;
+ } else {
+ source->pub.get_pixel_rows = get_scaled_gray_row;
+ }
+ break;
+
+ case '6': /* it's a raw-format PPM file */
+ cinfo->input_components = 3;
+ cinfo->in_color_space = JCS_RGB;
+ TRACEMS2(cinfo, 1, JTRC_PPM, w, h);
+ if (maxval > 255) {
+ source->pub.get_pixel_rows = get_word_rgb_row;
+ } else if (maxval == MAXJSAMPLE && SIZEOF(JSAMPLE) == SIZEOF(U_CHAR)) {
+ source->pub.get_pixel_rows = get_raw_row;
+ use_raw_buffer = TRUE;
+ need_rescale = FALSE;
+to:
+ if (cinfo->data_precision <= 8)
+ source->pub.get_pixel_rows = get_text_gray_row;
+ else source->pub.get_pixel_rows = get_text_gray_row16;
+ need_iobuffer = FALSE;
+ break;
+
+ case '3': /* it's a text-format PPM file */
+ cinfo->input_components = 3;
+ cinfo->in_color_space = JCS_RGB;
+ TRACEMS2(cinfo, 1, JTRC_PPM_TEXT, w, h);
+ if (cinfo->data_precision <= 8)
+ source->pub.get_pixel_rows = get_text_rgb_row;
+ else source->pub.get_pixel_rows = get_text_rgb_row16;
+ need_iobuffer = FALSE;
+ break;
+
+ case '5': /* it's a raw-format PGM file */
+ cinfo->input_components = 1;
+ cinfo->in_color_space = JCS_GRAYSCALE;
+ TRACEMS2(cinfo, 1, JTRC_PGM, w, h);
+ if (cinfo->data_precision == cinfo->data_precision_other) {
+ need_rescale = FALSE;
+ if (cinfo->data_precision > 8) {
+ source->pub.get_pixel_rows = get_corr_row16;
+ use_raw_buffer = FALSE;
+ } else { /* 8 bit*/
+ source->pub.get_pixel_rows = get_raw_row;
+ use_raw_buffer = TRUE;
+ }
+ } else if (cinfo->data_precision > 8) {
+ if (cinfo->data_precision_other > 8)
+ source->pub.get_pixel_rows = get_word_gray_row16;
+ else source->pub.get_pixel_rows = get_word_gray_row;
+ } else {
+ if (cinfo->data_precision_other > 8)
+ source->pub.get_pixel_rows = get_scaled_gray_row16;
+ else source->pub.get_pixel_rows = get_scaled_gray_row;
+ }
+ break;
+
+ case '6': /* it's a raw-format PPM file */
+ cinfo->input_components = 3;
+ cinfo->in_color_space = JCS_RGB;
+ TRACEMS2(cinfo, 1, JTRC_PPM, w, h);
+ if (cinfo->data_precision == cinfo->data_precision_other) {
+ need_rescale = FALSE;
+ if (cinfo->data_precision > 8) {
+ source->pub.get_pixel_rows = get_corr_row16;
+ use_raw_buffer = FALSE;
+ } else { /* 8 bit*/
+ source->pub.get_pixel_rows = get_raw_row;
+ use_raw_buffer = TRUE;
+ }
+ } else if (cinfo->data_precision > 8) {
+ if (cinfo->data_precision_other > 8)
+ source->pub.get_pixel_rows = get_word_rgb_row16;
+ else source->pub.get_pixel_rows = get_word_rgb_row;
+ } else {
+ if (cinfo->data_precision_other > 8)
+ source->pub.get_pixel_rows = get_scaled_rgb_row16;
+ else source->pub.get_pixel_rows = get_scaled_rgb_row;
+++++++++++++++++++++++++++++++++++++++++
+from:
+ /* Create compressor input buffer. */
+to:
+ /* Create compressor input buffer. */
+ bit_width = ((cinfo->data_precision<=8) ? SIZEOF(JSAMPLE) : SIZEOF(JSAMPLE16));
+++++++++++++++++++++++++++++++++++++++++
+from:
+ (JDIMENSION) w * cinfo->input_components, (JDIMENSION) 1);
+to:
+ (JDIMENSION) w * cinfo->input_components *
+ bit_width, (JDIMENSION) 1);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ INT32 val, half_maxval;
+
+ /* On 16-bit-int machines we have to be careful of maxval = 65535 */
+ source->rescale = (JSAMPLE *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (size_t) (((long) maxval + 1L) * SIZEOF(JSAMPLE)));
+ half_maxval = maxval / 2;
+ for (val = 0; val <= (INT32) maxval; val++) {
+ /* The multiplication here must be done in 32 bits to avoid overflow */
+ source->rescale[val] = (JSAMPLE) ((val*MAXJSAMPLE + half_maxval)/maxval);
+to:
+ INT32 val, half_maxval, maxjsample;
+
+ /* On 16-bit-int machines we have to be careful of maxval = 65535 */
+ source->rescale = (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (size_t) (((long) maxval + 1L) * (long)bit_width));
+ half_maxval = maxval / 2;
+ maxjsample = (1 << cinfo->data_precision) - 1;
+ if (bit_width == 1) {
+ if (maxjsample == maxval) {
+ for (val = 0; val <= (INT32) maxval; val++) source->rescale[val] = val;
+ } else {
+ for (val = 0; val <= (INT32) maxval; val++) {
+ /* The multiplication here must be done in 32 bits to avoid overflow */
+ source->rescale[val] = (JSAMPLE) ((val*maxjsample + half_maxval)/maxval);
+ }
+ }
+ } else {
+ JSAMPLE16 *rescale16;
+ rescale16 = (JSAMPLE16 *)source->rescale;
+ if (maxjsample == maxval) {
+ for (val = 0; val <= (INT32) maxval; val++) rescale16[val] = val;
+ } else {
+ for (val = 0; val <= (INT32) maxval; val++) {
+ /* The multiplication here must be done in 32 bits to avoid overflow */
+ rescale16[val] = (JSAMPLE16) ((val*maxjsample + half_maxval)/maxval);
+ }
+ }
+
+-----------------------------------------------------------------------
+Use transupp.c from droppatch with changes.
+in 14 places from:
+height_in_blocks
+to:
+height_in_data_units
+++++++++++++++++++++++++++++++++++++++++
+in 18 places from:
+width_in_blocks
+to:
+width_in_data_units
+++++++++++++++++++++++++++++++++++++++++
+from:
+ coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
+ ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
+ width_in_data_units, height_in_data_units, (JDIMENSION) v_samp_factor);
+to:
+ coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
+ ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
+ width_in_data_units * SIZEOF(JSAMPLE16), height_in_data_units, (JDIMENSION) v_samp_factor);
+
+-----------------------------------------------------------------------
+Use transupp.h from droppatch.
+
+-----------------------------------------------------------------------
+wrppm.c from:
+#if BITS_IN_JSAMPLE == 8
+#define PUTPPMSAMPLE(ptr,v) *ptr++ = (char) (v)
+#define BYTESPERSAMPLE 1
+#define PPM_MAXVAL 255
+#else
+#ifdef PPM_NORAWWORD
+#define PUTPPMSAMPLE(ptr,v) *ptr++ = (char) ((v) >> (BITS_IN_JSAMPLE-8))
+#define BYTESPERSAMPLE 1
+#define PPM_MAXVAL 255
+#else
+/* The word-per-sample format always puts the LSB first. */
+#define PUTPPMSAMPLE(ptr,v) \
+ { register int val_ = v; \
+ *ptr++ = (char) (val_ & 0xFF); \
+ *ptr++ = (char) ((val_ >> 8) & 0xFF); \
+ }
+#define BYTESPERSAMPLE 2
+#define PPM_MAXVAL ((1<<BITS_IN_JSAMPLE)-1)
+#endif
+#endif
+to:
+/*#if BITS_IN_JSAMPLE == 8
+#define PUTPPMSAMPLE(ptr,v) *ptr++ = (char) (v)
+#define BYTESPERSAMPLE 1
+#define PPM_MAXVAL 255
+#else
+#ifdef PPM_NORAWWORD
+#define PUTPPMSAMPLE(ptr,v) *ptr++ = (char) ((v) >> (cinfo->data_precision-8))
+#define BYTESPERSAMPLE 1
+#define PPM_MAXVAL 255
+#else*/
+/* The word-per-sample format always puts the LSB first. */
+/*#define PUTPPMSAMPLE(ptr,v) \
+ { register int val_ = v; \
+ *ptr++ = (char) (val_ & 0xFF); \
+ *ptr++ = (char) ((val_ >> 8) & 0xFF); \
+ }
+#define BYTESPERSAMPLE 2
+#define PPM_MAXVAL ((1<<cinfo->data_precision)-1)
+#endif
+#endif*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+ JSAMPROW pixrow; /* decompressor output buffer */
+ size_t buffer_width; /* width of I/O buffer */
+ JDIMENSION samples_per_row; /* JSAMPLEs per output row */
+to:
+/* JSAMPROW16 pixrow;*/ /* decompressor output buffer */
+ size_t buffer_width; /* width of I/O buffer */
+ JDIMENSION samples_per_row; /* JSAMPLEs per output row */
+++++++++++++++++++++++++++++++++++++++++
+from:
+/*
+ * Write some pixel data.
+ * In this module rows_supplied will always be 1.
+ *
+ * put_pixel_rows handles the "normal" 8-bit case where the decompressor
+ * output buffer is physically the same as the fwrite buffer.
+ */
+
+METHODDEF(void)
+put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+to:
+/*
+ * Write some pixel data.
+ * In this module rows_supplied will always be 1.
+ *
+ * put_pixel_rows handles the "normal" 8-bit case where the decompressor
+ * output buffer is physically the same as the fwrite buffer.
+ */
+
+/*METHODDEF(void)
+put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}*/
+++++++++++++++++++++++++++++++++++++++++
+from:
+METHODDEF(void)
+copy_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register JSAMPROW ptr;
+ register JDIMENSION col;
+
+ ptr = dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = dest->samples_per_row; col > 0; col--) {
+ PUTPPMSAMPLE(bufferptr, GETJSAMPLE(*ptr++));
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+to:
+METHODDEF(void)
+copy_pixel_rows8 (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register JSAMPROW16 ptr;
+ register JDIMENSION col;
+ register int shft;
+
+ ptr = (JSAMPROW16)dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = dest->samples_per_row; col > 0; col--) {
+ *bufferptr++ = (char)GETJSAMPLE(*ptr++);
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+METHODDEF(void)
+copy_pixel_rows16 (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+fprintf(stderr,"16 ");/*delme*/
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register JSAMPROW16 ptr;
+ register JDIMENSION col;
+ register int val;
+
+ ptr = (JSAMPROW16)dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = dest->samples_per_row; col > 0; col--) {
+ val = GETJSAMPLE(*ptr++);
+ *bufferptr++ = (char)((val >> 8) & 0xFF);
+ *bufferptr++ = (char)(val & 0xFF);
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+++++++++++++++++++++++++++++++++++++++++
+from:
+METHODDEF(void)
+put_demapped_rgb (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register int pixval;
+ register JSAMPROW ptr;
+ register JSAMPROW color_map0 = cinfo->colormap16[0];
+ register JSAMPROW color_map1 = cinfo->colormap16[1];
+ register JSAMPROW color_map2 = cinfo->colormap16[2];
+ register JDIMENSION col;
+
+ ptr = (JSAMPROW16)dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = cinfo->output_width; col > 0; col--) {
+ pixval = GETJSAMPLE(*ptr++);
+ PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map0[pixval]));
+ PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map1[pixval]));
+ PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map2[pixval]));
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+METHODDEF(void)
+put_demapped_gray (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register JSAMPROW ptr;
+ register JSAMPROW color_map = cinfo->colormap16[0];
+ register JDIMENSION col;
+
+ ptr = dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = cinfo->output_width; col > 0; col--) {
+ PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map[GETJSAMPLE(*ptr++)]));
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+to:
+METHODDEF(void)
+put_demapped_rgb8 (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register int pixval, shft;
+ register JSAMPROW16 ptr;
+ register JSAMPROW16 color_map0 = cinfo->colormap16[0];
+ register JSAMPROW16 color_map1 = cinfo->colormap16[1];
+ register JSAMPROW16 color_map2 = cinfo->colormap16[2];
+ register JDIMENSION col;
+
+ ptr = (JSAMPROW16)dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ if (dest->cshift == 0) { /* Fast */
+ for (col = cinfo->output_width; col > 0; col--) {
+ pixval = GETJSAMPLE(*ptr++);
+ *bufferptr++ = (char)GETJSAMPLE(color_map0[pixval]);
+ *bufferptr++ = (char)GETJSAMPLE(color_map1[pixval]);
+ *bufferptr++ = (char)GETJSAMPLE(color_map2[pixval]);
+ }
+ } else if (dest->cshift > 0) { /* Down */
+ shft = dest->cshift;
+ for (col = cinfo->output_width; col > 0; col--) {
+ pixval = GETJSAMPLE(*ptr++);
+ *bufferptr++ = (char)((GETJSAMPLE(color_map0[pixval])) >> shft);
+ *bufferptr++ = (char)((GETJSAMPLE(color_map1[pixval])) >> shft);
+ *bufferptr++ = (char)((GETJSAMPLE(color_map2[pixval])) >> shft);
+ }
+ } else { /* Up */
+ shft = - dest->cshift;
+ for (col = cinfo->output_width; col > 0; col--) {
+ pixval = GETJSAMPLE(*ptr++);
+ *bufferptr++ = (char)((GETJSAMPLE(color_map0[pixval])) << shft);
+ *bufferptr++ = (char)((GETJSAMPLE(color_map1[pixval])) << shft);
+ *bufferptr++ = (char)((GETJSAMPLE(color_map2[pixval])) << shft);
+ }
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+METHODDEF(void)
+put_demapped_rgb16 (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register int pixval, val;
+ register JSAMPROW16 ptr;
+ register JSAMPROW16 color_map0 = cinfo->colormap16[0];
+ register JSAMPROW16 color_map1 = cinfo->colormap16[1];
+ register JSAMPROW16 color_map2 = cinfo->colormap16[2];
+ register JDIMENSION col;
+
+ ptr = (JSAMPROW16)dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = cinfo->output_width; col > 0; col--) {
+ pixval = GETJSAMPLE(*ptr++);
+ val = GETJSAMPLE(color_map0[pixval]);
+ *bufferptr++ = (char)((val >> 8) & 0xFF);
+ *bufferptr++ = (char)(val & 0xFF);
+ val = GETJSAMPLE(color_map1[pixval]);
+ *bufferptr++ = (char)((val >> 8) & 0xFF);
+ *bufferptr++ = (char)(val & 0xFF);
+ val = GETJSAMPLE(color_map2[pixval]);
+ *bufferptr++ = (char)((val >> 8) & 0xFF);
+ *bufferptr++ = (char)(val & 0xFF);
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+METHODDEF(void)
+put_demapped_gray8 (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register JSAMPROW16 ptr;
+ register JSAMPROW16 color_map = cinfo->colormap16[0];
+ register JDIMENSION col;
+
+ ptr = (JSAMPROW16)dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = cinfo->output_width; col > 0; col--) {
+ *bufferptr++ = (char)GETJSAMPLE(color_map[GETJSAMPLE(*ptr++)]);
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+METHODDEF(void)
+put_demapped_gray16 (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register JSAMPROW16 ptr;
+ register JSAMPROW16 color_map = cinfo->colormap16[0];
+ register JDIMENSION col;
+ register int val;
+
+ ptr = (JSAMPROW16)dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = cinfo->output_width; col > 0; col--) {
+ val = GETJSAMPLE(color_map[GETJSAMPLE(*ptr++)]);
+ *bufferptr++ = (char)((val >> 8) & 0xFF);
+ *bufferptr++ = (char)(val & 0xFF);
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+++++++++++++++++++++++++++++++++++++++++
+from:
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+
+ /* Emit file header */
+ switch (cinfo->out_color_space) {
+ case JCS_GRAYSCALE:
+ /* emit header for raw PGM format */
+ fprintf(dest->pub.output_file, "P5\n%ld %ld\n%d\n",
+ (long) cinfo->output_width, (long) cinfo->output_height,
+ PPM_MAXVAL);
+ break;
+ case JCS_RGB:
+ /* emit header for raw PPM format */
+ fprintf(dest->pub.output_file, "P6\n%ld %ld\n%d\n",
+ (long) cinfo->output_width, (long) cinfo->output_height,
+ PPM_MAXVAL);
+to:
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ int ppm_maxval;
+
+ /* Create physical I/O buffer. Note we make this near on a PC. */
+ cinfo->buffer_size_char = FALSE; /* JSAMPLE16 buffer sent. */
+ if (cinfo->data_precision_other <= 8)
+ dest->buffer_width = dest->samples_per_row * SIZEOF(char);
+ else dest->buffer_width = dest->samples_per_row * SIZEOF(JSAMPLE16);
+ dest->iobuffer = (char *) (*cinfo->mem->alloc_small)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, dest->buffer_width);
+
+ ppm_maxval = (1<<cinfo->data_precision_other)-1;
+
+ /* Emit file header */
+ switch (cinfo->out_color_space) {
+ case JCS_GRAYSCALE:
+ /* emit header for raw PGM format */
+ fprintf(dest->pub.output_file, "P5\n%ld %ld\n%d\n",
+ (long) cinfo->output_width, (long) cinfo->output_height,
+ ppm_maxval);
+ break;
+ case JCS_RGB:
+ /* emit header for raw PPM format */
+ fprintf(dest->pub.output_file, "P6\n%ld %ld\n%d\n",
+ (long) cinfo->output_width, (long) cinfo->output_height,
+ ppm_maxval);
+++++++++++++++++++++++++++++++++++++++++
+from:
+ /* Create physical I/O buffer. Note we make this near on a PC. */
+ dest->samples_per_row = cinfo->output_width * cinfo->out_color_components;
+ dest->buffer_width = dest->samples_per_row * (BYTESPERSAMPLE * SIZEOF(char));
+ dest->iobuffer = (char *) (*cinfo->mem->alloc_small)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, dest->buffer_width);
+
+ if (cinfo->quantize_colors || BITS_IN_JSAMPLE != 8 ||
+ SIZEOF(JSAMPLE) != SIZEOF(char)) {
+ /* When quantizing, we need an output buffer for colormap indexes
+ * that's separate from the physical I/O buffer. We also need a
+ * separate buffer if pixel format translation must take place.
+ */
+ dest->pub.buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->output_width * cinfo->output_components, (JDIMENSION) 1);
+ dest->pub.buffer_height = 1;
+ if (! cinfo->quantize_colors)
+ dest->pub.put_pixel_rows = copy_pixel_rows;
+ else if (cinfo->out_color_space == JCS_GRAYSCALE)
+ dest->pub.put_pixel_rows = put_demapped_gray;
+ else
+ dest->pub.put_pixel_rows = put_demapped_rgb;
+ } else {
+ /* We will fwrite() directly from decompressor output buffer. */
+ /* Synthesize a JSAMPARRAY pointer structure */
+ /* Cast here implies near->far pointer conversion on PCs */
+ dest->pixrow = (JSAMPROW) dest->iobuffer;
+ dest->pub.buffer = & dest->pixrow;
+ dest->pub.buffer_height = 1;
+ dest->pub.put_pixel_rows = put_pixel_rows;
+ }
+to:
+ /* Dimensions for the physical I/O buffer. */
+ dest->samples_per_row = cinfo->output_width * cinfo->out_color_components;
+
+ /* A JSAMPLE16 buffer for decompression now that jdapistd take it.
+ * Conversion to 8 bit if needed is done later with copy or put 8.
+ * Scaling is now done by the jpeg library. */
+ dest->pub.buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) cinfo->output_width * cinfo->output_components
+ * SIZEOF(JSAMPLE16),(JDIMENSION) 1);
+ dest->pub.buffer_height = 1;
+
+ if (cinfo->data_precision_other <= 8) {
+ if (cinfo->quantize_colors) {
+ if (cinfo->out_color_space == JCS_GRAYSCALE)
+ dest->pub.put_pixel_rows = put_demapped_gray8;
+ else dest->pub.put_pixel_rows = put_demapped_rgb8; /* Maped color */
+ } else dest->pub.put_pixel_rows = copy_pixel_rows8; /* Default 8 bit */
+ } else { /* > 8 bit output */
+ if (cinfo->quantize_colors) {
+ if (cinfo->out_color_space == JCS_GRAYSCALE)
+ dest->pub.put_pixel_rows = put_demapped_gray16;
+ else dest->pub.put_pixel_rows = put_demapped_rgb16;
+ } else dest->pub.put_pixel_rows = copy_pixel_rows16; /* No quanttize */
+ }
+
diff --git a/jpeg-6c/cjpeg.1 b/jpeg-6c/cjpeg.1
new file mode 100644
index 0000000..ca10fe9
--- /dev/null
+++ b/jpeg-6c/cjpeg.1
@@ -0,0 +1,299 @@
+.TH CJPEG 1 "20 March 1998"
+.SH NAME
+cjpeg \- compress an image file to a JPEG file
+.SH SYNOPSIS
+.B cjpeg
+[
+.I options
+]
+[
+.I filename
+]
+.LP
+.SH DESCRIPTION
+.LP
+.B cjpeg
+compresses the named image file, or the standard input if no file is
+named, and produces a JPEG/JFIF file on the standard output.
+The currently supported input file formats are: PPM (PBMPLUS color
+format), PGM (PBMPLUS gray-scale format), BMP, Targa, and RLE (Utah Raster
+Toolkit format). (RLE is supported only if the URT library is available.)
+.SH OPTIONS
+All switch names may be abbreviated; for example,
+.B \-grayscale
+may be written
+.B \-gray
+or
+.BR \-gr .
+Most of the "basic" switches can be abbreviated to as little as one letter.
+Upper and lower case are equivalent (thus
+.B \-BMP
+is the same as
+.BR \-bmp ).
+British spellings are also accepted (e.g.,
+.BR \-greyscale ),
+though for brevity these are not mentioned below.
+.PP
+The basic switches are:
+.TP
+.BI \-quality " N"
+Scale quantization tables to adjust image quality. Quality is 0 (worst) to
+100 (best); default is 75. (See below for more info.)
+.TP
+.B \-grayscale
+Create monochrome JPEG file from color input. Be sure to use this switch when
+compressing a grayscale BMP file, because
+.B cjpeg
+isn't bright enough to notice whether a BMP file uses only shades of gray.
+By saying
+.BR \-grayscale ,
+you'll get a smaller JPEG file that takes less time to process.
+.TP
+.B \-optimize
+Perform optimization of entropy encoding parameters. Without this, default
+encoding parameters are used.
+.B \-optimize
+usually makes the JPEG file a little smaller, but
+.B cjpeg
+runs somewhat slower and needs much more memory. Image quality and speed of
+decompression are unaffected by
+.BR \-optimize .
+.TP
+.B \-progressive
+Create progressive JPEG file (see below).
+.TP
+.BI \-lossless " psv[,Pt]"
+Create a lossless JPEG file using the specified predictor selection value (1-7)
+and optional point transform.
+.B Caution:
+lossless JPEG is not widely implemented, so many decoders will be
+unable to view a lossless JPEG file at all.
+.TP
+.B \-targa
+Input file is Targa format. Targa files that contain an "identification"
+field will not be automatically recognized by
+.BR cjpeg ;
+for such files you must specify
+.B \-targa
+to make
+.B cjpeg
+treat the input as Targa format.
+For most Targa files, you won't need this switch.
+.PP
+The
+.B \-quality
+switch lets you trade off compressed file size against quality of the
+reconstructed image: the higher the quality setting, the larger the JPEG file,
+and the closer the output image will be to the original input. Normally you
+want to use the lowest quality setting (smallest file) that decompresses into
+something visually indistinguishable from the original image. For this
+purpose the quality setting should be between 50 and 95; the default of 75 is
+often about right. If you see defects at
+.B \-quality
+75, then go up 5 or 10 counts at a time until you are happy with the output
+image. (The optimal setting will vary from one image to another.)
+.PP
+.B \-quality
+100 will generate a quantization table of all 1's, minimizing loss in the
+quantization step (but there is still information loss in subsampling, as well
+as roundoff error). This setting is mainly of interest for experimental
+purposes. Quality values above about 95 are
+.B not
+recommended for normal use; the compressed file size goes up dramatically for
+hardly any gain in output image quality.
+.PP
+In the other direction, quality values below 50 will produce very small files
+of low image quality. Settings around 5 to 10 might be useful in preparing an
+index of a large image library, for example. Try
+.B \-quality
+2 (or so) for some amusing Cubist effects. (Note: quality
+values below about 25 generate 2-byte quantization tables, which are
+considered optional in the JPEG standard.
+.B cjpeg
+emits a warning message when you give such a quality value, because some
+other JPEG programs may be unable to decode the resulting file. Use
+.B \-baseline
+if you need to ensure compatibility at low quality values.)
+.PP
+The
+.B \-progressive
+switch creates a "progressive JPEG" file. In this type of JPEG file, the data
+is stored in multiple scans of increasing quality. If the file is being
+transmitted over a slow communications link, the decoder can use the first
+scan to display a low-quality image very quickly, and can then improve the
+display with each subsequent scan. The final image is exactly equivalent to a
+standard JPEG file of the same quality setting, and the total file size is
+about the same --- often a little smaller.
+.B Caution:
+progressive JPEG is not yet widely implemented, so many decoders will be
+unable to view a progressive JPEG file at all.
+.PP
+Switches for advanced users:
+.TP
+.B \-dct int
+Use integer DCT method (default).
+.TP
+.B \-dct fast
+Use fast integer DCT (less accurate).
+.TP
+.B \-dct float
+Use floating-point DCT method.
+The float method is very slightly more accurate than the int method, but is
+much slower unless your machine has very fast floating-point hardware. Also
+note that results of the floating-point method may vary slightly across
+machines, while the integer methods should give the same results everywhere.
+The fast integer method is much less accurate than the other two.
+.TP
+.BI \-restart " N"
+Emit a JPEG restart marker every N MCU rows, or every N MCU blocks if "B" is
+attached to the number.
+.B \-restart 0
+(the default) means no restart markers.
+.TP
+.BI \-smooth " N"
+Smooth the input image to eliminate dithering noise. N, ranging from 1 to
+100, indicates the strength of smoothing. 0 (the default) means no smoothing.
+.TP
+.BI \-maxmemory " N"
+Set limit for amount of memory to use in processing large images. Value is
+in thousands of bytes, or millions of bytes if "M" is attached to the
+number. For example,
+.B \-max 4m
+selects 4000000 bytes. If more space is needed, temporary files will be used.
+.TP
+.BI \-outfile " name"
+Send output image to the named file, not to standard output.
+.TP
+.B \-verbose
+Enable debug printout. More
+.BR \-v 's
+give more output. Also, version information is printed at startup.
+.TP
+.B \-debug
+Same as
+.BR \-verbose .
+.PP
+The
+.B \-restart
+option inserts extra markers that allow a JPEG decoder to resynchronize after
+a transmission error. Without restart markers, any damage to a compressed
+file will usually ruin the image from the point of the error to the end of the
+image; with restart markers, the damage is usually confined to the portion of
+the image up to the next restart marker. Of course, the restart markers
+occupy extra space. We recommend
+.B \-restart 1
+for images that will be transmitted across unreliable networks such as Usenet.
+.PP
+The
+.B \-smooth
+option filters the input to eliminate fine-scale noise. This is often useful
+when converting dithered images to JPEG: a moderate smoothing factor of 10 to
+50 gets rid of dithering patterns in the input file, resulting in a smaller
+JPEG file and a better-looking image. Too large a smoothing factor will
+visibly blur the image, however.
+.PP
+Switches for wizards:
+.TP
+.B \-baseline
+Force baseline-compatible quantization tables to be generated. This clamps
+quantization values to 8 bits even at low quality settings. (This switch is
+poorly named, since it does not ensure that the output is actually baseline
+JPEG. For example, you can use
+.B \-baseline
+and
+.B \-progressive
+together.)
+.TP
+.BI \-qtables " file"
+Use the quantization tables given in the specified text file.
+.TP
+.BI \-qslots " N[,...]"
+Select which quantization table to use for each color component.
+.TP
+.BI \-sample " HxV[,...]"
+Set JPEG sampling factors for each color component.
+.TP
+.BI \-scans " file"
+Use the scan script given in the specified text file.
+.PP
+The "wizard" switches are intended for experimentation with JPEG. If you
+don't know what you are doing, \fBdon't use them\fR. These switches are
+documented further in the file wizard.doc.
+.SH EXAMPLES
+.LP
+This example compresses the PPM file foo.ppm with a quality factor of
+60 and saves the output as foo.jpg:
+.IP
+.B cjpeg \-quality
+.I 60 foo.ppm
+.B >
+.I foo.jpg
+.SH HINTS
+Color GIF files are not the ideal input for JPEG; JPEG is really intended for
+compressing full-color (24-bit) images. In particular, don't try to convert
+cartoons, line drawings, and other images that have only a few distinct
+colors. GIF works great on these, JPEG does not. If you want to convert a
+GIF to JPEG, you should experiment with
+.BR cjpeg 's
+.B \-quality
+and
+.B \-smooth
+options to get a satisfactory conversion.
+.B \-smooth 10
+or so is often helpful.
+.PP
+Avoid running an image through a series of JPEG compression/decompression
+cycles. Image quality loss will accumulate; after ten or so cycles the image
+may be noticeably worse than it was after one cycle. It's best to use a
+lossless format while manipulating an image, then convert to JPEG format when
+you are ready to file the image away.
+.PP
+The
+.B \-optimize
+option to
+.B cjpeg
+is worth using when you are making a "final" version for posting or archiving.
+It's also a win when you are using low quality settings to make very small
+JPEG files; the percentage improvement is often a lot more than it is on
+larger files. (At present,
+.B \-optimize
+mode is always selected when generating progressive JPEG files.)
+.SH ENVIRONMENT
+.TP
+.B JPEGMEM
+If this environment variable is set, its value is the default memory limit.
+The value is specified as described for the
+.B \-maxmemory
+switch.
+.B JPEGMEM
+overrides the default value specified when the program was compiled, and
+itself is overridden by an explicit
+.BR \-maxmemory .
+.SH SEE ALSO
+.BR djpeg (1),
+.BR jpegtran (1),
+.BR rdjpgcom (1),
+.BR wrjpgcom (1)
+.br
+.BR ppm (5),
+.BR pgm (5)
+.br
+Wallace, Gregory K. "The JPEG Still Picture Compression Standard",
+Communications of the ACM, April 1991 (vol. 34, no. 4), pp. 30-44.
+.SH AUTHOR
+Independent JPEG Group
+.SH BUGS
+Arithmetic coding is not supported for legal reasons.
+.PP
+GIF input files are no longer supported, to avoid the Unisys LZW patent.
+Use a Unisys-licensed program if you need to read a GIF file. (Conversion
+of GIF files to JPEG is usually a bad idea anyway.)
+.PP
+Not all variants of BMP and Targa file formats are supported.
+.PP
+The
+.B \-targa
+switch is not a bug, it's a feature. (It would be a bug if the Targa format
+designers had not been clueless.)
+.PP
+Still not as fast as we'd like.
diff --git a/jpeg-6c/cjpeg.c b/jpeg-6c/cjpeg.c
new file mode 100644
index 0000000..c320703
--- /dev/null
+++ b/jpeg-6c/cjpeg.c
@@ -0,0 +1,672 @@
+/*
+ * cjpeg.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a command-line user interface for the JPEG compressor.
+ * It should work on any system with Unix- or MS-DOS-style command lines.
+ *
+ * Two different command line styles are permitted, depending on the
+ * compile-time switch TWO_FILE_COMMANDLINE:
+ * cjpeg [options] inputfile outputfile
+ * cjpeg [options] [inputfile]
+ * In the second style, output is always to standard output, which you'd
+ * normally redirect to a file or pipe to some other program. Input is
+ * either from a named file or from standard input (typically redirected).
+ * The second style is convenient on Unix but is unhelpful on systems that
+ * don't support pipes. Also, you MUST use the first style if your system
+ * doesn't do binary I/O to stdin/stdout.
+ * To simplify script writing, the "-outfile" switch is provided. The syntax
+ * cjpeg [options] -outfile outputfile inputfile
+ * works regardless of which command line style is used.
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+#include "jversion.h" /* for version message */
+
+#ifdef USE_CCOMMAND /* command-line reader for Macintosh */
+#ifdef __MWERKS__
+#include <SIOUX.h> /* Metrowerks needs this */
+#include <console.h> /* ... and this */
+#endif
+#ifdef THINK_C
+#include <console.h> /* Think declares it here */
+#endif
+#endif
+
+
+/* Create the add-on message string table. */
+
+#define JMESSAGE(code,string) string ,
+
+static const char * const cdjpeg_message_table[] = {
+#include "cderror.h"
+ NULL
+};
+
+
+/*
+ * This routine determines what format the input file is,
+ * and selects the appropriate input-reading module.
+ *
+ * To determine which family of input formats the file belongs to,
+ * we may look only at the first byte of the file, since C does not
+ * guarantee that more than one character can be pushed back with ungetc.
+ * Looking at additional bytes would require one of these approaches:
+ * 1) assume we can fseek() the input file (fails for piped input);
+ * 2) assume we can push back more than one character (works in
+ * some C implementations, but unportable);
+ * 3) provide our own buffering (breaks input readers that want to use
+ * stdio directly, such as the RLE library);
+ * or 4) don't put back the data, and modify the input_init methods to assume
+ * they start reading after the start of file (also breaks RLE library).
+ * #1 is attractive for MS-DOS but is untenable on Unix.
+ *
+ * The most portable solution for file types that can't be identified by their
+ * first byte is to make the user tell us what they are. This is also the
+ * only approach for "raw" file types that contain only arbitrary values.
+ * We presently apply this method for Targa files. Most of the time Targa
+ * files start with 0x00, so we recognize that case. Potentially, however,
+ * a Targa file could start with any byte value (byte 0 is the length of the
+ * seldom-used ID field), so we provide a switch to force Targa input mode.
+ */
+
+static boolean is_targa; /* records user -targa switch */
+static boolean var_width; /* sets variable width for ppm */
+static boolean loss_less; /* Tells ppm to allow 16 bits */
+
+
+LOCAL(cjpeg_source_ptr)
+select_file_type (j_compress_ptr cinfo, FILE * infile)
+{
+ int c;
+
+ if (is_targa) {
+#ifdef TARGA_SUPPORTED
+ return jinit_read_targa(cinfo);
+#else
+ ERREXIT(cinfo, JERR_TGA_NOTCOMP);
+#endif
+ }
+
+ if ((c = getc(infile)) == EOF)
+ ERREXIT(cinfo, JERR_INPUT_EMPTY);
+ if (ungetc(c, infile) == EOF)
+ ERREXIT(cinfo, JERR_UNGETC_FAILED);
+
+ switch (c) {
+#ifdef BMP_SUPPORTED
+ case 'B':
+ if (cinfo->data_precision != 8)
+ ERREXIT(cinfo, JERR_PPM_ONLY);
+ return jinit_read_bmp(cinfo);
+#endif
+#ifdef GIF_SUPPORTED
+ case 'G':
+ if (cinfo->data_precision != 8)
+ ERREXIT(cinfo, JERR_PPM_ONLY);
+ return jinit_read_gif(cinfo);
+#endif
+#ifdef PPM_SUPPORTED
+ case 'P':
+ return jinit_read_ppm(cinfo);
+#endif
+#ifdef RLE_SUPPORTED
+ case 'R':
+ if (cinfo->data_precision != 8)
+ ERREXIT(cinfo, JERR_PPM_ONLY);
+ return jinit_read_rle(cinfo);
+#endif
+#ifdef TARGA_SUPPORTED
+ case 0x00:
+ if (cinfo->data_precision != 8)
+ ERREXIT(cinfo, JERR_PPM_ONLY);
+ return jinit_read_targa(cinfo);
+#endif
+ default:
+ ERREXIT(cinfo, JERR_UNKNOWN_FORMAT);
+ break;
+ }
+
+ return NULL; /* suppress compiler warnings */
+}
+
+
+/*
+ * Argument-parsing code.
+ * The switch parser is designed to be useful with DOS-style command line
+ * syntax, ie, intermixed switches and file names, where only the switches
+ * to the left of a given file name affect processing of that file.
+ * The main program in this file doesn't actually use this capability...
+ */
+
+
+static const char * progname; /* program name for error messages */
+static char * outfilename; /* for -outfile switch */
+
+
+LOCAL(void)
+usage (void)
+/* complain about bad command line */
+{
+ fprintf(stderr, "usage: %s [switches] ", progname);
+#ifdef TWO_FILE_COMMANDLINE
+ fprintf(stderr, "inputfile outputfile\n");
+#else
+ fprintf(stderr, "[inputfile]\n");
+#endif
+
+ fprintf(stderr, "Switches (names may be abbreviated):\n");
+ fprintf(stderr, " -quality N Compression quality (0..100; 5-95 is useful range)\n");
+ fprintf(stderr, " -grayscale Create monochrome JPEG file\n");
+#ifdef PPM_SUPPORTED
+ fprintf(stderr, " -width N Output bit width for PPN to JPEG (N = 0 for same as input)\n");
+#endif
+#ifdef ENTROPY_OPT_SUPPORTED
+ fprintf(stderr, " -optimize Optimize Huffman table (smaller file, but slow compression)\n");
+#endif
+#ifdef C_PROGRESSIVE_SUPPORTED
+ fprintf(stderr, " -progressive Create progressive JPEG file\n");
+#endif
+#ifdef C_LOSSLESS_SUPPORTED
+ fprintf(stderr, " -lossless psv[,Pt] Create lossless JPEG file\n");
+#endif
+#ifdef TARGA_SUPPORTED
+ fprintf(stderr, " -targa Input file is Targa format (usually not needed)\n");
+#endif
+ fprintf(stderr, "Switches for advanced users:\n");
+#ifdef DCT_ISLOW_SUPPORTED
+ fprintf(stderr, " -dct int Use integer DCT method%s\n",
+ (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+ fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n",
+ (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ fprintf(stderr, " -dct float Use floating-point DCT method%s\n",
+ (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
+#endif
+ fprintf(stderr, " -restart N Set restart interval in rows, or in blocks with B\n");
+#ifdef INPUT_SMOOTHING_SUPPORTED
+ fprintf(stderr, " -smooth N Smooth dithered input (N=1..100 is strength)\n");
+#endif
+ fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
+ fprintf(stderr, " -outfile name Specify name for output file\n");
+ fprintf(stderr, " -verbose or -debug Emit debug output\n");
+ fprintf(stderr, "Switches for wizards:\n");
+#ifdef C_ARITH_CODING_SUPPORTED
+ fprintf(stderr, " -arithmetic Use arithmetic coding\n");
+#endif
+ fprintf(stderr, " -baseline Force baseline quantization tables\n");
+ fprintf(stderr, " -qtables file Use quantization tables given in file\n");
+ fprintf(stderr, " -qslots N[,...] Set component quantization tables\n");
+ fprintf(stderr, " -sample HxV[,...] Set component sampling factors\n");
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+ fprintf(stderr, " -scans file Create multi-scan JPEG per script file\n");
+#endif
+ exit(EXIT_FAILURE);
+}
+
+
+LOCAL(int)
+parse_switches (j_compress_ptr cinfo, int argc, char **argv,
+ int last_file_arg_seen, boolean for_real)
+/* Parse optional switches.
+ * Returns argv[] index of first file-name argument (== argc if none).
+ * Any file names with indexes <= last_file_arg_seen are ignored;
+ * they have presumably been processed in a previous iteration.
+ * (Pass 0 for last_file_arg_seen on the first or only iteration.)
+ * for_real is FALSE on the first (dummy) pass; we may skip any expensive
+ * processing.
+ */
+{
+ int argn;
+ char * arg;
+ int quality; /* -quality parameter */
+ int q_scale_factor; /* scaling percentage for -qtables */
+ boolean force_baseline;
+ boolean simple_progressive;
+ char * qtablefile = NULL; /* saves -qtables filename if any */
+ char * qslotsarg = NULL; /* saves -qslots parm if any */
+ char * samplearg = NULL; /* saves -sample parm if any */
+ char * scansarg = NULL; /* saves -scans parm if any */
+ char * losslsarg = NULL; /* saves -lossless parm if any */
+
+ /* Set up default JPEG parameters. */
+ /* Note that default -quality level need not, and does not,
+ * match the default scaling for an explicit -qtables argument.
+ */
+ quality = 75; /* default -quality value */
+ q_scale_factor = 100; /* default to no scaling for -qtables */
+ force_baseline = FALSE; /* by default, allow 16-bit quantizers */
+ simple_progressive = FALSE;
+ is_targa = FALSE;
+ var_width = FALSE;
+ loss_less = FALSE;
+ outfilename = NULL;
+ cinfo->err->trace_level = 0;
+
+ /* Scan command line options, adjust parameters */
+
+ for (argn = 1; argn < argc; argn++) {
+ arg = argv[argn];
+ if (*arg != '-') {
+ /* Not a switch, must be a file name argument */
+ if (argn <= last_file_arg_seen) {
+ outfilename = NULL; /* -outfile applies to just one input file */
+ continue; /* ignore this name if previously processed */
+ }
+ break; /* else done parsing switches */
+ }
+ arg++; /* advance past switch marker character */
+
+ if (keymatch(arg, "arithmetic", 1)) {
+ /* Use arithmetic coding. */
+#ifdef C_ARITH_CODING_SUPPORTED
+ cinfo->arith_code = TRUE;
+#else
+ fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+
+ } else if (keymatch(arg, "baseline", 1)) {
+ /* Force baseline-compatible output (8-bit quantizer values). */
+ force_baseline = TRUE;
+
+ } else if (keymatch(arg, "dct", 2)) {
+ /* Select DCT algorithm. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (keymatch(argv[argn], "int", 1)) {
+ cinfo->dct_method = JDCT_ISLOW;
+ } else if (keymatch(argv[argn], "fast", 2)) {
+ cinfo->dct_method = JDCT_IFAST;
+ } else if (keymatch(argv[argn], "float", 2)) {
+ cinfo->dct_method = JDCT_FLOAT;
+ } else
+ usage();
+
+ } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
+ /* Enable debug printouts. */
+ /* On first -d, print version identification */
+ static boolean printed_version = FALSE;
+
+ if (! printed_version) {
+ fprintf(stderr, "Independent JPEG Group's CJPEG, version %s\n%s\n",
+ JVERSION, JCOPYRIGHT);
+ printed_version = TRUE;
+ }
+ cinfo->err->trace_level++;
+
+ } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
+ /* Force a monochrome JPEG file to be generated. */
+ jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
+
+ } else if (keymatch(arg, "lossless", 1)) {
+/* Select simple lossless mode. */
+#ifdef C_LOSSLESS_SUPPORTED
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ losslsarg = argv[argn];
+ /* We must postpone execution until num_components is known. */
+ loss_less = TRUE; /* Let ppm know. */
+#else
+ fprintf(stderr, "%s: sorry, lossless output was not compiled\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+
+ } else if (keymatch(arg, "maxmemory", 3)) {
+ /* Maximum memory in Kb (or Mb with 'm'). */
+ long lval;
+ char ch = 'x';
+
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
+ usage();
+ if (ch == 'm' || ch == 'M')
+ lval *= 1000L;
+ cinfo->mem->max_memory_to_use = lval * 1000L;
+
+ } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
+ /* Enable entropy parm optimization. */
+#ifdef ENTROPY_OPT_SUPPORTED
+ cinfo->optimize_coding = TRUE;
+#else
+ fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+
+ } else if (keymatch(arg, "outfile", 4)) {
+ /* Set output file name. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ outfilename = argv[argn]; /* save it away for later use */
+
+ } else if (keymatch(arg, "progressive", 1)) {
+ /* Select simple progressive mode. */
+#ifdef C_PROGRESSIVE_SUPPORTED
+ simple_progressive = TRUE;
+ /* We must postpone execution until num_components is known. */
+#else
+ fprintf(stderr, "%s: sorry, progressive output was not compiled\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+
+ } else if (keymatch(arg, "quality", 1)) {
+ /* Quality factor (quantization table scaling factor). */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (sscanf(argv[argn], "%d", &quality) != 1)
+ usage();
+ /* Change scale factor in case -qtables is present. */
+ q_scale_factor = jpeg_quality_scaling(quality);
+
+ } else if (keymatch(arg, "qslots", 2)) {
+ /* Quantization table slot numbers. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ qslotsarg = argv[argn];
+ /* Must delay setting qslots until after we have processed any
+ * colorspace-determining switches, since jpeg_set_colorspace sets
+ * default quant table numbers.
+ */
+
+ } else if (keymatch(arg, "qtables", 2)) {
+ /* Quantization tables fetched from file. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ qtablefile = argv[argn];
+ /* We postpone actually reading the file in case -quality comes later. */
+
+ } else if (keymatch(arg, "restart", 1)) {
+ /* Restart interval in MCU rows (or in MCUs with 'b'). */
+ long lval;
+ char ch = 'x';
+
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
+ usage();
+ if (lval < 0 || lval > 65535L)
+ usage();
+ if (ch == 'b' || ch == 'B') {
+ cinfo->restart_interval = (unsigned int) lval;
+ cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
+ } else {
+ cinfo->restart_in_rows = (int) lval;
+ /* restart_interval will be computed during startup */
+ }
+
+ } else if (keymatch(arg, "sample", 2)) {
+ /* Set sampling factors. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ samplearg = argv[argn];
+ /* Must delay setting sample factors until after we have processed any
+ * colorspace-determining switches, since jpeg_set_colorspace sets
+ * default sampling factors.
+ */
+
+ } else if (keymatch(arg, "scans", 2)) {
+ /* Set scan script. */
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ scansarg = argv[argn];
+ /* We must postpone reading the file in case -progressive appears. */
+#else
+ fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+
+ } else if (keymatch(arg, "smooth", 2)) {
+ /* Set input smoothing factor. */
+ int val;
+
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (sscanf(argv[argn], "%d", &val) != 1)
+ usage();
+ if (val < 0 || val > 100)
+ usage();
+ cinfo->smoothing_factor = val;
+
+ } else if (keymatch(arg, "targa", 1)) {
+ /* Input file is Targa format. */
+ is_targa = TRUE;
+ } else if (keymatch(arg, "width", 1)) {
+#ifdef PPM_SUPPORTED
+ int val;
+
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (sscanf(argv[argn], "%d", &val) != 1)
+ usage();
+ if (val < 0 || val > JSAMPLEMAX)
+ usage();
+ if (!for_real) {/* Set ppm output width the first time. */
+ if (val == 0) {
+ val = 12;
+ var_width = TRUE;
+ }
+ cinfo->data_precision = val;
+ }
+#else
+ fprintf(stderr, "%s: sorry, ppm output was not compiled\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+ } else {
+ usage(); /* bogus switch */
+ }
+ }
+
+ /* Post-switch-scanning cleanup */
+
+ if (for_real) {
+
+ /* Set quantization tables for selected quality. */
+ /* Some or all may be overridden if -qtables is present. */
+ jpeg_set_quality(cinfo, quality, force_baseline);
+
+ if (qtablefile != NULL) /* process -qtables if it was present */
+ if (! read_quant_tables(cinfo, qtablefile,
+ q_scale_factor, force_baseline))
+ usage();
+
+ if (qslotsarg != NULL) /* process -qslots if it was present */
+ if (! set_quant_slots(cinfo, qslotsarg))
+ usage();
+
+ if (samplearg != NULL) /* process -sample if it was present */
+ if (! set_sample_factors(cinfo, samplearg))
+ usage();
+
+#ifdef C_PROGRESSIVE_SUPPORTED
+ if (simple_progressive) /* process -progressive; -scans can override */
+ jpeg_simple_progression(cinfo);
+#endif
+
+#ifdef C_LOSSLESS_SUPPORTED
+ if (losslsarg != NULL) /* process -lossless if it was present */
+ if (! set_simple_lossless(cinfo, losslsarg))
+ usage();
+#endif
+
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+ if (scansarg != NULL) /* process -scans if it was present */
+ if (! read_scan_script(cinfo, scansarg))
+ usage();
+#endif
+ }
+
+ return argn; /* return index of next arg (file name) */
+}
+
+
+/*
+ * The main program.
+ */
+
+int
+main (int argc, char **argv)
+{
+ struct jpeg_compress_struct cinfo;
+ struct jpeg_error_mgr jerr;
+#ifdef PROGRESS_REPORT
+ struct cdjpeg_progress_mgr progress;
+#endif
+ int file_index;
+ cjpeg_source_ptr src_mgr;
+ FILE * input_file;
+ FILE * output_file;
+ JDIMENSION num_scanlines;
+
+ /* On Mac, fetch a command line. */
+#ifdef USE_CCOMMAND
+ argc = ccommand(&argv);
+#endif
+
+ progname = argv[0];
+ if (progname == NULL || progname[0] == 0)
+ progname = "cjpeg"; /* in case C library doesn't provide it */
+
+ /* Initialize the JPEG compression object with default error handling. */
+ cinfo.err = jpeg_std_error(&jerr);
+ jpeg_create_compress(&cinfo);
+ /* Add some application-specific error messages (from cderror.h) */
+ jerr.addon_message_table = cdjpeg_message_table;
+ jerr.first_addon_message = JMSG_FIRSTADDONCODE;
+ jerr.last_addon_message = JMSG_LASTADDONCODE;
+
+ /* Now safe to enable signal catcher. */
+#ifdef NEED_SIGNAL_CATCHER
+ enable_signal_catcher((j_common_ptr) &cinfo);
+#endif
+
+ /* Initialize JPEG parameters.
+ * Much of this may be overridden later.
+ * In particular, we don't yet know the input file's color space,
+ * but we need to provide some value for jpeg_set_defaults() to work.
+ */
+
+ cinfo.in_color_space = JCS_RGB; /* arbitrary guess */
+ jpeg_set_defaults(&cinfo);
+
+ /* Scan command line to find file names.
+ * It is convenient to use just one switch-parsing routine, but the switch
+ * values read here are ignored; we will rescan the switches after opening
+ * the input file.
+ */
+
+ file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
+
+#ifdef TWO_FILE_COMMANDLINE
+ /* Must have either -outfile switch or explicit output file name */
+ if (outfilename == NULL) {
+ if (file_index != argc-2) {
+ fprintf(stderr, "%s: must name one input and one output file\n",
+ progname);
+ usage();
+ }
+ outfilename = argv[file_index+1];
+ } else {
+ if (file_index != argc-1) {
+ fprintf(stderr, "%s: must name one input and one output file\n",
+ progname);
+ usage();
+ }
+ }
+#else
+ /* Unix style: expect zero or one file name */
+ if (file_index < argc-1) {
+ fprintf(stderr, "%s: only one input file\n", progname);
+ usage();
+ }
+#endif /* TWO_FILE_COMMANDLINE */
+
+ /* Open the input file. */
+ if (file_index < argc) {
+ if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ /* default input file is stdin */
+ input_file = read_stdin();
+ }
+
+ /* Open the output file. */
+ if (outfilename != NULL) {
+ if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ /* default output file is stdout */
+ output_file = write_stdout();
+ }
+
+#ifdef PROGRESS_REPORT
+ start_progress_monitor((j_common_ptr) &cinfo, &progress);
+#endif
+
+ /* Figure out the input file format, and set up to read it. */
+ src_mgr = select_file_type(&cinfo, input_file);
+ src_mgr->input_file = input_file;
+
+ /* If PPM and variable width, tell PPM with a 0 data precision. */
+ if (var_width) cinfo.data_precision = 0;
+
+ /* Read the input file header to obtain file size & colorspace. */
+ (*src_mgr->start_input) (&cinfo, src_mgr);
+
+ if (cinfo.data_precision != 8) if (loss_less) cinfo.lossless = TRUE; /* Tell colorspace */
+
+ /* Now that we know input colorspace, fix colorspace-dependent defaults */
+ jpeg_default_colorspace(&cinfo);
+
+ /* Adjust default compression parameters by re-parsing the options */
+ file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
+
+ /* Specify data destination for compression */
+ jpeg_stdio_dest(&cinfo, output_file);
+
+ /* Start compressor */
+ jpeg_start_compress(&cinfo, TRUE);
+
+ /* Process data */
+ while (cinfo.next_scanline < cinfo.image_height) {
+ num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
+ (void) jpeg_write_scanlines(&cinfo, (JSAMPARRAY)src_mgr->buffer, num_scanlines);
+ }
+
+ /* Finish compression and release memory */
+ (*src_mgr->finish_input) (&cinfo, src_mgr);
+ jpeg_finish_compress(&cinfo);
+ jpeg_destroy_compress(&cinfo);
+
+ /* Close files, if we opened them */
+ if (input_file != stdin)
+ fclose(input_file);
+ if (output_file != stdout)
+ fclose(output_file);
+
+#ifdef PROGRESS_REPORT
+ end_progress_monitor((j_common_ptr) &cinfo);
+#endif
+
+ /* All done. */
+ exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
+ return 0; /* suppress no-return-value warnings */
+}
diff --git a/jpeg-6c/ckconfig.c b/jpeg-6c/ckconfig.c
new file mode 100644
index 0000000..34baf79
--- /dev/null
+++ b/jpeg-6c/ckconfig.c
@@ -0,0 +1,402 @@
+/*
+ * ckconfig.c
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ */
+
+/*
+ * This program is intended to help you determine how to configure the JPEG
+ * software for installation on a particular system. The idea is to try to
+ * compile and execute this program. If your compiler fails to compile the
+ * program, make changes as indicated in the comments below. Once you can
+ * compile the program, run it, and it will produce a "jconfig.h" file for
+ * your system.
+ *
+ * As a general rule, each time you try to compile this program,
+ * pay attention only to the *first* error message you get from the compiler.
+ * Many C compilers will issue lots of spurious error messages once they
+ * have gotten confused. Go to the line indicated in the first error message,
+ * and read the comments preceding that line to see what to change.
+ *
+ * Almost all of the edits you may need to make to this program consist of
+ * changing a line that reads "#define SOME_SYMBOL" to "#undef SOME_SYMBOL",
+ * or vice versa. This is called defining or undefining that symbol.
+ */
+
+
+/* First we must see if your system has the include files we need.
+ * We start out with the assumption that your system has all the ANSI-standard
+ * include files. If you get any error trying to include one of these files,
+ * undefine the corresponding HAVE_xxx symbol.
+ */
+
+#define HAVE_STDDEF_H /* replace 'define' by 'undef' if error here */
+#ifdef HAVE_STDDEF_H /* next line will be skipped if you undef... */
+#include <stddef.h>
+#endif
+
+#define HAVE_STDLIB_H /* same thing for stdlib.h */
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+
+#include <stdio.h> /* If you ain't got this, you ain't got C. */
+
+/* We have to see if your string functions are defined by
+ * strings.h (old BSD convention) or string.h (everybody else).
+ * We try the non-BSD convention first; define NEED_BSD_STRINGS
+ * if the compiler says it can't find string.h.
+ */
+
+#undef NEED_BSD_STRINGS
+
+#ifdef NEED_BSD_STRINGS
+#include <strings.h>
+#else
+#include <string.h>
+#endif
+
+/* On some systems (especially older Unix machines), type size_t is
+ * defined only in the include file <sys/types.h>. If you get a failure
+ * on the size_t test below, try defining NEED_SYS_TYPES_H.
+ */
+
+#undef NEED_SYS_TYPES_H /* start by assuming we don't need it */
+#ifdef NEED_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+
+/* Usually type size_t is defined in one of the include files we've included
+ * above. If not, you'll get an error on the "typedef size_t my_size_t;" line.
+ * In that case, first try defining NEED_SYS_TYPES_H just above.
+ * If that doesn't work, you'll have to search through your system library
+ * to figure out which include file defines "size_t". Look for a line that
+ * says "typedef something-or-other size_t;". Then, change the line below
+ * that says "#include <someincludefile.h>" to instead include the file
+ * you found size_t in, and define NEED_SPECIAL_INCLUDE. If you can't find
+ * type size_t anywhere, try replacing "#include <someincludefile.h>" with
+ * "typedef unsigned int size_t;".
+ */
+
+#undef NEED_SPECIAL_INCLUDE /* assume we DON'T need it, for starters */
+
+#ifdef NEED_SPECIAL_INCLUDE
+#include <someincludefile.h>
+#endif
+
+typedef size_t my_size_t; /* The payoff: do we have size_t now? */
+
+
+/* The next question is whether your compiler supports ANSI-style function
+ * prototypes. You need to know this in order to choose between using
+ * makefile.ansi and using makefile.unix.
+ * The #define line below is set to assume you have ANSI function prototypes.
+ * If you get an error in this group of lines, undefine HAVE_PROTOTYPES.
+ */
+
+#define HAVE_PROTOTYPES
+
+#ifdef HAVE_PROTOTYPES
+int testfunction (int arg1, int * arg2); /* check prototypes */
+
+struct methods_struct { /* check method-pointer declarations */
+ int (*error_exit) (char *msgtext);
+ int (*trace_message) (char *msgtext);
+ int (*another_method) (void);
+};
+
+int testfunction (int arg1, int * arg2) /* check definitions */
+{
+ return arg2[arg1];
+}
+
+int test2function (void) /* check void arg list */
+{
+ return 0;
+}
+#endif
+
+
+/* Now we want to find out if your compiler knows what "unsigned char" means.
+ * If you get an error on the "unsigned char un_char;" line,
+ * then undefine HAVE_UNSIGNED_CHAR.
+ */
+
+#define HAVE_UNSIGNED_CHAR
+
+#ifdef HAVE_UNSIGNED_CHAR
+unsigned char un_char;
+#endif
+
+
+/* Now we want to find out if your compiler knows what "unsigned short" means.
+ * If you get an error on the "unsigned short un_short;" line,
+ * then undefine HAVE_UNSIGNED_SHORT.
+ */
+
+#define HAVE_UNSIGNED_SHORT
+
+#ifdef HAVE_UNSIGNED_SHORT
+unsigned short un_short;
+#endif
+
+
+/* Now we want to find out if your compiler understands type "void".
+ * If you get an error anywhere in here, undefine HAVE_VOID.
+ */
+
+#define HAVE_VOID
+
+#ifdef HAVE_VOID
+/* Caution: a C++ compiler will insist on complete prototypes */
+typedef void * void_ptr; /* check void * */
+#ifdef HAVE_PROTOTYPES /* check ptr to function returning void */
+typedef void (*void_func) (int a, int b);
+#else
+typedef void (*void_func) ();
+#endif
+
+#ifdef HAVE_PROTOTYPES /* check void function result */
+void test3function (void_ptr arg1, void_func arg2)
+#else
+void test3function (arg1, arg2)
+ void_ptr arg1;
+ void_func arg2;
+#endif
+{
+ char * locptr = (char *) arg1; /* check casting to and from void * */
+ arg1 = (void *) locptr;
+ (*arg2) (1, 2); /* check call of fcn returning void */
+}
+#endif
+
+
+/* Now we want to find out if your compiler knows what "const" means.
+ * If you get an error here, undefine HAVE_CONST.
+ */
+
+#define HAVE_CONST
+
+#ifdef HAVE_CONST
+static const int carray[3] = {1, 2, 3};
+
+#ifdef HAVE_PROTOTYPES
+int test4function (const int arg1)
+#else
+int test4function (arg1)
+ const int arg1;
+#endif
+{
+ return carray[arg1];
+}
+#endif
+
+
+/* If you get an error or warning about this structure definition,
+ * define INCOMPLETE_TYPES_BROKEN.
+ */
+
+#undef INCOMPLETE_TYPES_BROKEN
+
+#ifndef INCOMPLETE_TYPES_BROKEN
+typedef struct undefined_structure * undef_struct_ptr;
+#endif
+
+
+/* If you get an error about duplicate names,
+ * define NEED_SHORT_EXTERNAL_NAMES.
+ */
+
+#undef NEED_SHORT_EXTERNAL_NAMES
+
+#ifndef NEED_SHORT_EXTERNAL_NAMES
+
+int possibly_duplicate_function ()
+{
+ return 0;
+}
+
+int possibly_dupli_function ()
+{
+ return 1;
+}
+
+#endif
+
+
+
+/************************************************************************
+ * OK, that's it. You should not have to change anything beyond this
+ * point in order to compile and execute this program. (You might get
+ * some warnings, but you can ignore them.)
+ * When you run the program, it will make a couple more tests that it
+ * can do automatically, and then it will create jconfig.h and print out
+ * any additional suggestions it has.
+ ************************************************************************
+ */
+
+
+#ifdef HAVE_PROTOTYPES
+int is_char_signed (int arg)
+#else
+int is_char_signed (arg)
+ int arg;
+#endif
+{
+ if (arg == 189) { /* expected result for unsigned char */
+ return 0; /* type char is unsigned */
+ }
+ else if (arg != -67) { /* expected result for signed char */
+ printf("Hmm, it seems 'char' is not eight bits wide on your machine.\n");
+ printf("I fear the JPEG software will not work at all.\n\n");
+ }
+ return 1; /* assume char is signed otherwise */
+}
+
+
+#ifdef HAVE_PROTOTYPES
+int is_shifting_signed (long arg)
+#else
+int is_shifting_signed (arg)
+ long arg;
+#endif
+/* See whether right-shift on a long is signed or not. */
+{
+ long res = arg >> 4;
+
+ if (res == -0x7F7E80CL) { /* expected result for signed shift */
+ return 1; /* right shift is signed */
+ }
+ /* see if unsigned-shift hack will fix it. */
+ /* we can't just test exact value since it depends on width of long... */
+ res |= (~0L) << (32-4);
+ if (res == -0x7F7E80CL) { /* expected result now? */
+ return 0; /* right shift is unsigned */
+ }
+ printf("Right shift isn't acting as I expect it to.\n");
+ printf("I fear the JPEG software will not work at all.\n\n");
+ return 0; /* try it with unsigned anyway */
+}
+
+
+#ifdef HAVE_PROTOTYPES
+int main (int argc, char ** argv)
+#else
+int main (argc, argv)
+ int argc;
+ char ** argv;
+#endif
+{
+ char signed_char_check = (char) (-67);
+ FILE *outfile;
+
+ /* Attempt to write jconfig.h */
+ if ((outfile = fopen("jconfig.h", "w")) == NULL) {
+ printf("Failed to write jconfig.h\n");
+ return 1;
+ }
+
+ /* Write out all the info */
+ fprintf(outfile, "/* jconfig.h --- generated by ckconfig.c */\n");
+ fprintf(outfile, "/* see jconfig.doc for explanations */\n\n");
+#ifdef HAVE_PROTOTYPES
+ fprintf(outfile, "#define HAVE_PROTOTYPES\n");
+#else
+ fprintf(outfile, "#undef HAVE_PROTOTYPES\n");
+#endif
+#ifdef HAVE_UNSIGNED_CHAR
+ fprintf(outfile, "#define HAVE_UNSIGNED_CHAR\n");
+#else
+ fprintf(outfile, "#undef HAVE_UNSIGNED_CHAR\n");
+#endif
+#ifdef HAVE_UNSIGNED_SHORT
+ fprintf(outfile, "#define HAVE_UNSIGNED_SHORT\n");
+#else
+ fprintf(outfile, "#undef HAVE_UNSIGNED_SHORT\n");
+#endif
+#ifdef HAVE_VOID
+ fprintf(outfile, "/* #define void char */\n");
+#else
+ fprintf(outfile, "#define void char\n");
+#endif
+#ifdef HAVE_CONST
+ fprintf(outfile, "/* #define const */\n");
+#else
+ fprintf(outfile, "#define const\n");
+#endif
+ if (is_char_signed((int) signed_char_check))
+ fprintf(outfile, "#undef CHAR_IS_UNSIGNED\n");
+ else
+ fprintf(outfile, "#define CHAR_IS_UNSIGNED\n");
+#ifdef HAVE_STDDEF_H
+ fprintf(outfile, "#define HAVE_STDDEF_H\n");
+#else
+ fprintf(outfile, "#undef HAVE_STDDEF_H\n");
+#endif
+#ifdef HAVE_STDLIB_H
+ fprintf(outfile, "#define HAVE_STDLIB_H\n");
+#else
+ fprintf(outfile, "#undef HAVE_STDLIB_H\n");
+#endif
+#ifdef NEED_BSD_STRINGS
+ fprintf(outfile, "#define NEED_BSD_STRINGS\n");
+#else
+ fprintf(outfile, "#undef NEED_BSD_STRINGS\n");
+#endif
+#ifdef NEED_SYS_TYPES_H
+ fprintf(outfile, "#define NEED_SYS_TYPES_H\n");
+#else
+ fprintf(outfile, "#undef NEED_SYS_TYPES_H\n");
+#endif
+ fprintf(outfile, "#undef NEED_FAR_POINTERS\n");
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+ fprintf(outfile, "#define NEED_SHORT_EXTERNAL_NAMES\n");
+#else
+ fprintf(outfile, "#undef NEED_SHORT_EXTERNAL_NAMES\n");
+#endif
+#ifdef INCOMPLETE_TYPES_BROKEN
+ fprintf(outfile, "#define INCOMPLETE_TYPES_BROKEN\n");
+#else
+ fprintf(outfile, "#undef INCOMPLETE_TYPES_BROKEN\n");
+#endif
+ fprintf(outfile, "\n#ifdef JPEG_INTERNALS\n\n");
+ if (is_shifting_signed(-0x7F7E80B1L))
+ fprintf(outfile, "#undef RIGHT_SHIFT_IS_UNSIGNED\n");
+ else
+ fprintf(outfile, "#define RIGHT_SHIFT_IS_UNSIGNED\n");
+ fprintf(outfile, "\n#endif /* JPEG_INTERNALS */\n");
+ fprintf(outfile, "\n#ifdef JPEG_CJPEG_DJPEG\n\n");
+ fprintf(outfile, "#define BMP_SUPPORTED /* BMP image file format */\n");
+ fprintf(outfile, "#define GIF_SUPPORTED /* GIF image file format */\n");
+ fprintf(outfile, "#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */\n");
+ fprintf(outfile, "#undef RLE_SUPPORTED /* Utah RLE image file format */\n");
+ fprintf(outfile, "#define TARGA_SUPPORTED /* Targa image file format */\n\n");
+ fprintf(outfile, "#undef TWO_FILE_COMMANDLINE /* You may need this on non-Unix systems */\n");
+ fprintf(outfile, "#undef NEED_SIGNAL_CATCHER /* Define this if you use jmemname.c */\n");
+ fprintf(outfile, "#undef DONT_USE_B_MODE\n");
+ fprintf(outfile, "/* #define PROGRESS_REPORT */ /* optional */\n");
+ fprintf(outfile, "\n#endif /* JPEG_CJPEG_DJPEG */\n");
+
+ /* Close the jconfig.h file */
+ fclose(outfile);
+
+ /* User report */
+ printf("Configuration check for Independent JPEG Group's software done.\n");
+ printf("\nI have written the jconfig.h file for you.\n\n");
+#ifdef HAVE_PROTOTYPES
+ printf("You should use makefile.ansi as the starting point for your Makefile.\n");
+#else
+ printf("You should use makefile.unix as the starting point for your Makefile.\n");
+#endif
+
+#ifdef NEED_SPECIAL_INCLUDE
+ printf("\nYou'll need to change jconfig.h to include the system include file\n");
+ printf("that you found type size_t in, or add a direct definition of type\n");
+ printf("size_t if that's what you used. Just add it to the end.\n");
+#endif
+
+ return 0;
+}
diff --git a/jpeg-6c/coderules.doc b/jpeg-6c/coderules.doc
new file mode 100644
index 0000000..0ab5d9b
--- /dev/null
+++ b/jpeg-6c/coderules.doc
@@ -0,0 +1,118 @@
+IJG JPEG LIBRARY: CODING RULES
+
+Copyright (C) 1991-1996, Thomas G. Lane.
+This file is part of the Independent JPEG Group's software.
+For conditions of distribution and use, see the accompanying README file.
+
+
+Since numerous people will be contributing code and bug fixes, it's important
+to establish a common coding style. The goal of using similar coding styles
+is much more important than the details of just what that style is.
+
+In general we follow the recommendations of "Recommended C Style and Coding
+Standards" revision 6.1 (Cannon et al. as modified by Spencer, Keppel and
+Brader). This document is available in the IJG FTP archive (see
+jpeg/doc/cstyle.ms.tbl.Z, or cstyle.txt.Z for those without nroff/tbl).
+
+Block comments should be laid out thusly:
+
+/*
+ * Block comments in this style.
+ */
+
+We indent statements in K&R style, e.g.,
+ if (test) {
+ then-part;
+ } else {
+ else-part;
+ }
+with two spaces per indentation level. (This indentation convention is
+handled automatically by GNU Emacs and many other text editors.)
+
+Multi-word names should be written in lower case with underscores, e.g.,
+multi_word_name (not multiWordName). Preprocessor symbols and enum constants
+are similar but upper case (MULTI_WORD_NAME). Names should be unique within
+the first fifteen characters. (On some older systems, global names must be
+unique within six characters. We accommodate this without cluttering the
+source code by using macros to substitute shorter names.)
+
+We use function prototypes everywhere; we rely on automatic source code
+transformation to feed prototype-less C compilers. Transformation is done
+by the simple and portable tool 'ansi2knr.c' (courtesy of Ghostscript).
+ansi2knr is not very bright, so it imposes a format requirement on function
+declarations: the function name MUST BEGIN IN COLUMN 1. Thus all functions
+should be written in the following style:
+
+LOCAL(int *)
+function_name (int a, char *b)
+{
+ code...
+}
+
+Note that each function definition must begin with GLOBAL(type), LOCAL(type),
+or METHODDEF(type). These macros expand to "static type" or just "type" as
+appropriate. They provide a readable indication of the routine's usage and
+can readily be changed for special needs. (For instance, special linkage
+keywords can be inserted for use in Windows DLLs.)
+
+ansi2knr does not transform method declarations (function pointers in
+structs). We handle these with a macro JMETHOD, defined as
+ #ifdef HAVE_PROTOTYPES
+ #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
+ #else
+ #define JMETHOD(type,methodname,arglist) type (*methodname) ()
+ #endif
+which is used like this:
+ struct function_pointers {
+ JMETHOD(void, init_entropy_encoder, (int somearg, jparms *jp));
+ JMETHOD(void, term_entropy_encoder, (void));
+ };
+Note the set of parentheses surrounding the parameter list.
+
+A similar solution is used for forward and external function declarations
+(see the EXTERN and JPP macros).
+
+If the code is to work on non-ANSI compilers, we cannot rely on a prototype
+declaration to coerce actual parameters into the right types. Therefore, use
+explicit casts on actual parameters whenever the actual parameter type is not
+identical to the formal parameter. Beware of implicit conversions to "int".
+
+It seems there are some non-ANSI compilers in which the sizeof() operator
+is defined to return int, yet size_t is defined as long. Needless to say,
+this is brain-damaged. Always use the SIZEOF() macro in place of sizeof(),
+so that the result is guaranteed to be of type size_t.
+
+
+The JPEG library is intended to be used within larger programs. Furthermore,
+we want it to be reentrant so that it can be used by applications that process
+multiple images concurrently. The following rules support these requirements:
+
+1. Avoid direct use of file I/O, "malloc", error report printouts, etc;
+pass these through the common routines provided.
+
+2. Minimize global namespace pollution. Functions should be declared static
+wherever possible. (Note that our method-based calling conventions help this
+a lot: in many modules only the initialization function will ever need to be
+called directly, so only that function need be externally visible.) All
+global function names should begin with "jpeg_", and should have an
+abbreviated name (unique in the first six characters) substituted by macro
+when NEED_SHORT_EXTERNAL_NAMES is set.
+
+3. Don't use global variables; anything that must be used in another module
+should be in the common data structures.
+
+4. Don't use static variables except for read-only constant tables. Variables
+that should be private to a module can be placed into private structures (see
+the system architecture document, structure.doc).
+
+5. Source file names should begin with "j" for files that are part of the
+library proper; source files that are not part of the library, such as cjpeg.c
+and djpeg.c, do not begin with "j". Keep source file names to eight
+characters (plus ".c" or ".h", etc) to make life easy for MS-DOSers. Keep
+compression and decompression code in separate source files --- some
+applications may want only one half of the library.
+
+Note: these rules (particularly #4) are not followed religiously in the
+modules that are used in cjpeg/djpeg but are not part of the JPEG library
+proper. Those modules are not really intended to be used in other
+applications.
diff --git a/jpeg-6c/config.guess b/jpeg-6c/config.guess
new file mode 100644
index 0000000..8088714
--- /dev/null
+++ b/jpeg-6c/config.guess
@@ -0,0 +1,1472 @@
+#! /bin/sh
+# Attempt to guess a canonical system name.
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+# 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
+
+timestamp='2005-12-13'
+
+# This file 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 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, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+
+# Originally written by Per Bothner <per at bothner.com>.
+# Please send patches to <config-patches at gnu.org>. Submit a context
+# diff and a properly formatted ChangeLog entry.
+#
+# This script attempts to guess a canonical system name similar to
+# config.sub. If it succeeds, it prints the system name on stdout, and
+# exits with 0. Otherwise, it exits with 1.
+#
+# The plan is that this can be called by configure scripts if you
+# don't specify an explicit build system type.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION]
+
+Output the configuration name of the system \`$me' is run on.
+
+Operation modes:
+ -h, --help print this help, then exit
+ -t, --time-stamp print date of last modification, then exit
+ -v, --version print version number, then exit
+
+Report bugs and patches to <config-patches at gnu.org>."
+
+version="\
+GNU config.guess ($timestamp)
+
+Originally written by Per Bothner.
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
+Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions. There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+ case $1 in
+ --time-stamp | --time* | -t )
+ echo "$timestamp" ; exit ;;
+ --version | -v )
+ echo "$version" ; exit ;;
+ --help | --h* | -h )
+ echo "$usage"; exit ;;
+ -- ) # Stop option processing
+ shift; break ;;
+ - ) # Use stdin as input.
+ break ;;
+ -* )
+ echo "$me: invalid option $1$help" >&2
+ exit 1 ;;
+ * )
+ break ;;
+ esac
+done
+
+if test $# != 0; then
+ echo "$me: too many arguments$help" >&2
+ exit 1
+fi
+
+trap 'exit 1' 1 2 15
+
+# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
+# compiler to aid in system detection is discouraged as it requires
+# temporary files to be created and, as you can see below, it is a
+# headache to deal with in a portable fashion.
+
+# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
+# use `HOST_CC' if defined, but it is deprecated.
+
+# Portable tmp directory creation inspired by the Autoconf team.
+
+set_cc_for_build='
+trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
+trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
+: ${TMPDIR=/tmp} ;
+ { tmp=`(umask 077 && mktemp -d -q "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
+ { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
+ { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
+ { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
+dummy=$tmp/dummy ;
+tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
+case $CC_FOR_BUILD,$HOST_CC,$CC in
+ ,,) echo "int x;" > $dummy.c ;
+ for c in cc gcc c89 c99 ; do
+ if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
+ CC_FOR_BUILD="$c"; break ;
+ fi ;
+ done ;
+ if test x"$CC_FOR_BUILD" = x ; then
+ CC_FOR_BUILD=no_compiler_found ;
+ fi
+ ;;
+ ,,*) CC_FOR_BUILD=$CC ;;
+ ,*,*) CC_FOR_BUILD=$HOST_CC ;;
+esac ; set_cc_for_build= ;'
+
+# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
+# (ghazi at noc.rutgers.edu 1994-08-24)
+if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
+ PATH=$PATH:/.attbin ; export PATH
+fi
+
+UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
+UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
+UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown
+UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
+
+# Note: order is significant - the case branches are not exclusive.
+
+case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
+ *:NetBSD:*:*)
+ # NetBSD (nbsd) targets should (where applicable) match one or
+ # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*,
+ # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently
+ # switched to ELF, *-*-netbsd* would select the old
+ # object file format. This provides both forward
+ # compatibility and a consistent mechanism for selecting the
+ # object file format.
+ #
+ # Note: NetBSD doesn't particularly care about the vendor
+ # portion of the name. We always set it to "unknown".
+ sysctl="sysctl -n hw.machine_arch"
+ UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
+ /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
+ case "${UNAME_MACHINE_ARCH}" in
+ armeb) machine=armeb-unknown ;;
+ arm*) machine=arm-unknown ;;
+ sh3el) machine=shl-unknown ;;
+ sh3eb) machine=sh-unknown ;;
+ *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
+ esac
+ # The Operating System including object format, if it has switched
+ # to ELF recently, or will in the future.
+ case "${UNAME_MACHINE_ARCH}" in
+ arm*|i386|m68k|ns32k|sh3*|sparc|vax)
+ eval $set_cc_for_build
+ if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
+ | grep __ELF__ >/dev/null
+ then
+ # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
+ # Return netbsd for either. FIX?
+ os=netbsd
+ else
+ os=netbsdelf
+ fi
+ ;;
+ *)
+ os=netbsd
+ ;;
+ esac
+ # The OS release
+ # Debian GNU/NetBSD machines have a different userland, and
+ # thus, need a distinct triplet. However, they do not need
+ # kernel version information, so it can be replaced with a
+ # suitable tag, in the style of linux-gnu.
+ case "${UNAME_VERSION}" in
+ Debian*)
+ release='-gnu'
+ ;;
+ *)
+ release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+ ;;
+ esac
+ # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
+ # contains redundant information, the shorter form:
+ # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
+ echo "${machine}-${os}${release}"
+ exit ;;
+ *:OpenBSD:*:*)
+ UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
+ echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
+ exit ;;
+ *:ekkoBSD:*:*)
+ echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
+ exit ;;
+ macppc:MirBSD:*:*)
+ echo powerppc-unknown-mirbsd${UNAME_RELEASE}
+ exit ;;
+ *:MirBSD:*:*)
+ echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
+ exit ;;
+ alpha:OSF1:*:*)
+ case $UNAME_RELEASE in
+ *4.0)
+ UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
+ ;;
+ *5.*)
+ UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
+ ;;
+ esac
+ # According to Compaq, /usr/sbin/psrinfo has been available on
+ # OSF/1 and Tru64 systems produced since 1995. I hope that
+ # covers most systems running today. This code pipes the CPU
+ # types through head -n 1, so we only detect the type of CPU 0.
+ ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1`
+ case "$ALPHA_CPU_TYPE" in
+ "EV4 (21064)")
+ UNAME_MACHINE="alpha" ;;
+ "EV4.5 (21064)")
+ UNAME_MACHINE="alpha" ;;
+ "LCA4 (21066/21068)")
+ UNAME_MACHINE="alpha" ;;
+ "EV5 (21164)")
+ UNAME_MACHINE="alphaev5" ;;
+ "EV5.6 (21164A)")
+ UNAME_MACHINE="alphaev56" ;;
+ "EV5.6 (21164PC)")
+ UNAME_MACHINE="alphapca56" ;;
+ "EV5.7 (21164PC)")
+ UNAME_MACHINE="alphapca57" ;;
+ "EV6 (21264)")
+ UNAME_MACHINE="alphaev6" ;;
+ "EV6.7 (21264A)")
+ UNAME_MACHINE="alphaev67" ;;
+ "EV6.8CB (21264C)")
+ UNAME_MACHINE="alphaev68" ;;
+ "EV6.8AL (21264B)")
+ UNAME_MACHINE="alphaev68" ;;
+ "EV6.8CX (21264D)")
+ UNAME_MACHINE="alphaev68" ;;
+ "EV6.9A (21264/EV69A)")
+ UNAME_MACHINE="alphaev69" ;;
+ "EV7 (21364)")
+ UNAME_MACHINE="alphaev7" ;;
+ "EV7.9 (21364A)")
+ UNAME_MACHINE="alphaev79" ;;
+ esac
+ # A Pn.n version is a patched version.
+ # A Vn.n version is a released version.
+ # A Tn.n version is a released field test version.
+ # A Xn.n version is an unreleased experimental baselevel.
+ # 1.2 uses "1.2" for uname -r.
+ echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+ exit ;;
+ Alpha\ *:Windows_NT*:*)
+ # How do we know it's Interix rather than the generic POSIX subsystem?
+ # Should we change UNAME_MACHINE based on the output of uname instead
+ # of the specific Alpha model?
+ echo alpha-pc-interix
+ exit ;;
+ 21064:Windows_NT:50:3)
+ echo alpha-dec-winnt3.5
+ exit ;;
+ Amiga*:UNIX_System_V:4.0:*)
+ echo m68k-unknown-sysv4
+ exit ;;
+ *:[Aa]miga[Oo][Ss]:*:*)
+ echo ${UNAME_MACHINE}-unknown-amigaos
+ exit ;;
+ *:[Mm]orph[Oo][Ss]:*:*)
+ echo ${UNAME_MACHINE}-unknown-morphos
+ exit ;;
+ *:OS/390:*:*)
+ echo i370-ibm-openedition
+ exit ;;
+ *:z/VM:*:*)
+ echo s390-ibm-zvmoe
+ exit ;;
+ *:OS400:*:*)
+ echo powerpc-ibm-os400
+ exit ;;
+ arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
+ echo arm-acorn-riscix${UNAME_RELEASE}
+ exit ;;
+ arm:riscos:*:*|arm:RISCOS:*:*)
+ echo arm-unknown-riscos
+ exit ;;
+ SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
+ echo hppa1.1-hitachi-hiuxmpp
+ exit ;;
+ Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
+ # akee at wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
+ if test "`(/bin/universe) 2>/dev/null`" = att ; then
+ echo pyramid-pyramid-sysv3
+ else
+ echo pyramid-pyramid-bsd
+ fi
+ exit ;;
+ NILE*:*:*:dcosx)
+ echo pyramid-pyramid-svr4
+ exit ;;
+ DRS?6000:unix:4.0:6*)
+ echo sparc-icl-nx6
+ exit ;;
+ DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
+ case `/usr/bin/uname -p` in
+ sparc) echo sparc-icl-nx7; exit ;;
+ esac ;;
+ sun4H:SunOS:5.*:*)
+ echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
+ echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ i86pc:SunOS:5.*:*)
+ echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ sun4*:SunOS:6*:*)
+ # According to config.sub, this is the proper way to canonicalize
+ # SunOS6. Hard to guess exactly what SunOS6 will be like, but
+ # it's likely to be more like Solaris than SunOS4.
+ echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ sun4*:SunOS:*:*)
+ case "`/usr/bin/arch -k`" in
+ Series*|S4*)
+ UNAME_RELEASE=`uname -v`
+ ;;
+ esac
+ # Japanese Language versions have a version number like `4.1.3-JL'.
+ echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
+ exit ;;
+ sun3*:SunOS:*:*)
+ echo m68k-sun-sunos${UNAME_RELEASE}
+ exit ;;
+ sun*:*:4.2BSD:*)
+ UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
+ test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
+ case "`/bin/arch`" in
+ sun3)
+ echo m68k-sun-sunos${UNAME_RELEASE}
+ ;;
+ sun4)
+ echo sparc-sun-sunos${UNAME_RELEASE}
+ ;;
+ esac
+ exit ;;
+ aushp:SunOS:*:*)
+ echo sparc-auspex-sunos${UNAME_RELEASE}
+ exit ;;
+ # The situation for MiNT is a little confusing. The machine name
+ # can be virtually everything (everything which is not
+ # "atarist" or "atariste" at least should have a processor
+ # > m68000). The system name ranges from "MiNT" over "FreeMiNT"
+ # to the lowercase version "mint" (or "freemint"). Finally
+ # the system name "TOS" denotes a system which is actually not
+ # MiNT. But MiNT is downward compatible to TOS, so this should
+ # be no problem.
+ atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
+ echo m68k-atari-mint${UNAME_RELEASE}
+ exit ;;
+ atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
+ echo m68k-atari-mint${UNAME_RELEASE}
+ exit ;;
+ *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
+ echo m68k-atari-mint${UNAME_RELEASE}
+ exit ;;
+ milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
+ echo m68k-milan-mint${UNAME_RELEASE}
+ exit ;;
+ hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
+ echo m68k-hades-mint${UNAME_RELEASE}
+ exit ;;
+ *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
+ echo m68k-unknown-mint${UNAME_RELEASE}
+ exit ;;
+ m68k:machten:*:*)
+ echo m68k-apple-machten${UNAME_RELEASE}
+ exit ;;
+ powerpc:machten:*:*)
+ echo powerpc-apple-machten${UNAME_RELEASE}
+ exit ;;
+ RISC*:Mach:*:*)
+ echo mips-dec-mach_bsd4.3
+ exit ;;
+ RISC*:ULTRIX:*:*)
+ echo mips-dec-ultrix${UNAME_RELEASE}
+ exit ;;
+ VAX*:ULTRIX*:*:*)
+ echo vax-dec-ultrix${UNAME_RELEASE}
+ exit ;;
+ 2020:CLIX:*:* | 2430:CLIX:*:*)
+ echo clipper-intergraph-clix${UNAME_RELEASE}
+ exit ;;
+ mips:*:*:UMIPS | mips:*:*:RISCos)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+#ifdef __cplusplus
+#include <stdio.h> /* for printf() prototype */
+ int main (int argc, char *argv[]) {
+#else
+ int main (argc, argv) int argc; char *argv[]; {
+#endif
+ #if defined (host_mips) && defined (MIPSEB)
+ #if defined (SYSTYPE_SYSV)
+ printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
+ #endif
+ #if defined (SYSTYPE_SVR4)
+ printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
+ #endif
+ #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
+ printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
+ #endif
+ #endif
+ exit (-1);
+ }
+EOF
+ $CC_FOR_BUILD -o $dummy $dummy.c &&
+ dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
+ SYSTEM_NAME=`$dummy $dummyarg` &&
+ { echo "$SYSTEM_NAME"; exit; }
+ echo mips-mips-riscos${UNAME_RELEASE}
+ exit ;;
+ Motorola:PowerMAX_OS:*:*)
+ echo powerpc-motorola-powermax
+ exit ;;
+ Motorola:*:4.3:PL8-*)
+ echo powerpc-harris-powermax
+ exit ;;
+ Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
+ echo powerpc-harris-powermax
+ exit ;;
+ Night_Hawk:Power_UNIX:*:*)
+ echo powerpc-harris-powerunix
+ exit ;;
+ m88k:CX/UX:7*:*)
+ echo m88k-harris-cxux7
+ exit ;;
+ m88k:*:4*:R4*)
+ echo m88k-motorola-sysv4
+ exit ;;
+ m88k:*:3*:R3*)
+ echo m88k-motorola-sysv3
+ exit ;;
+ AViiON:dgux:*:*)
+ # DG/UX returns AViiON for all architectures
+ UNAME_PROCESSOR=`/usr/bin/uname -p`
+ if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
+ then
+ if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
+ [ ${TARGET_BINARY_INTERFACE}x = x ]
+ then
+ echo m88k-dg-dgux${UNAME_RELEASE}
+ else
+ echo m88k-dg-dguxbcs${UNAME_RELEASE}
+ fi
+ else
+ echo i586-dg-dgux${UNAME_RELEASE}
+ fi
+ exit ;;
+ M88*:DolphinOS:*:*) # DolphinOS (SVR3)
+ echo m88k-dolphin-sysv3
+ exit ;;
+ M88*:*:R3*:*)
+ # Delta 88k system running SVR3
+ echo m88k-motorola-sysv3
+ exit ;;
+ XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
+ echo m88k-tektronix-sysv3
+ exit ;;
+ Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
+ echo m68k-tektronix-bsd
+ exit ;;
+ *:IRIX*:*:*)
+ echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
+ exit ;;
+ ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
+ echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id
+ exit ;; # Note that: echo "'`uname -s`'" gives 'AIX '
+ i*86:AIX:*:*)
+ echo i386-ibm-aix
+ exit ;;
+ ia64:AIX:*:*)
+ if [ -x /usr/bin/oslevel ] ; then
+ IBM_REV=`/usr/bin/oslevel`
+ else
+ IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+ fi
+ echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
+ exit ;;
+ *:AIX:2:3)
+ if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #include <sys/systemcfg.h>
+
+ main()
+ {
+ if (!__power_pc())
+ exit(1);
+ puts("powerpc-ibm-aix3.2.5");
+ exit(0);
+ }
+EOF
+ if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
+ then
+ echo "$SYSTEM_NAME"
+ else
+ echo rs6000-ibm-aix3.2.5
+ fi
+ elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
+ echo rs6000-ibm-aix3.2.4
+ else
+ echo rs6000-ibm-aix3.2
+ fi
+ exit ;;
+ *:AIX:*:[45])
+ IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
+ if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
+ IBM_ARCH=rs6000
+ else
+ IBM_ARCH=powerpc
+ fi
+ if [ -x /usr/bin/oslevel ] ; then
+ IBM_REV=`/usr/bin/oslevel`
+ else
+ IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+ fi
+ echo ${IBM_ARCH}-ibm-aix${IBM_REV}
+ exit ;;
+ *:AIX:*:*)
+ echo rs6000-ibm-aix
+ exit ;;
+ ibmrt:4.4BSD:*|romp-ibm:BSD:*)
+ echo romp-ibm-bsd4.4
+ exit ;;
+ ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and
+ echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to
+ exit ;; # report: romp-ibm BSD 4.3
+ *:BOSX:*:*)
+ echo rs6000-bull-bosx
+ exit ;;
+ DPX/2?00:B.O.S.:*:*)
+ echo m68k-bull-sysv3
+ exit ;;
+ 9000/[34]??:4.3bsd:1.*:*)
+ echo m68k-hp-bsd
+ exit ;;
+ hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
+ echo m68k-hp-bsd4.4
+ exit ;;
+ 9000/[34678]??:HP-UX:*:*)
+ HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+ case "${UNAME_MACHINE}" in
+ 9000/31? ) HP_ARCH=m68000 ;;
+ 9000/[34]?? ) HP_ARCH=m68k ;;
+ 9000/[678][0-9][0-9])
+ if [ -x /usr/bin/getconf ]; then
+ sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
+ sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
+ case "${sc_cpu_version}" in
+ 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
+ 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+ 532) # CPU_PA_RISC2_0
+ case "${sc_kernel_bits}" in
+ 32) HP_ARCH="hppa2.0n" ;;
+ 64) HP_ARCH="hppa2.0w" ;;
+ '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20
+ esac ;;
+ esac
+ fi
+ if [ "${HP_ARCH}" = "" ]; then
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+
+ #define _HPUX_SOURCE
+ #include <stdlib.h>
+ #include <unistd.h>
+
+ int main ()
+ {
+ #if defined(_SC_KERNEL_BITS)
+ long bits = sysconf(_SC_KERNEL_BITS);
+ #endif
+ long cpu = sysconf (_SC_CPU_VERSION);
+
+ switch (cpu)
+ {
+ case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
+ case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
+ case CPU_PA_RISC2_0:
+ #if defined(_SC_KERNEL_BITS)
+ switch (bits)
+ {
+ case 64: puts ("hppa2.0w"); break;
+ case 32: puts ("hppa2.0n"); break;
+ default: puts ("hppa2.0"); break;
+ } break;
+ #else /* !defined(_SC_KERNEL_BITS) */
+ puts ("hppa2.0"); break;
+ #endif
+ default: puts ("hppa1.0"); break;
+ }
+ exit (0);
+ }
+EOF
+ (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
+ test -z "$HP_ARCH" && HP_ARCH=hppa
+ fi ;;
+ esac
+ if [ ${HP_ARCH} = "hppa2.0w" ]
+ then
+ eval $set_cc_for_build
+
+ # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
+ # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler
+ # generating 64-bit code. GNU and HP use different nomenclature:
+ #
+ # $ CC_FOR_BUILD=cc ./config.guess
+ # => hppa2.0w-hp-hpux11.23
+ # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
+ # => hppa64-hp-hpux11.23
+
+ if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
+ grep __LP64__ >/dev/null
+ then
+ HP_ARCH="hppa2.0w"
+ else
+ HP_ARCH="hppa64"
+ fi
+ fi
+ echo ${HP_ARCH}-hp-hpux${HPUX_REV}
+ exit ;;
+ ia64:HP-UX:*:*)
+ HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+ echo ia64-hp-hpux${HPUX_REV}
+ exit ;;
+ 3050*:HI-UX:*:*)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #include <unistd.h>
+ int
+ main ()
+ {
+ long cpu = sysconf (_SC_CPU_VERSION);
+ /* The order matters, because CPU_IS_HP_MC68K erroneously returns
+ true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct
+ results, however. */
+ if (CPU_IS_PA_RISC (cpu))
+ {
+ switch (cpu)
+ {
+ case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
+ case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
+ case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
+ default: puts ("hppa-hitachi-hiuxwe2"); break;
+ }
+ }
+ else if (CPU_IS_HP_MC68K (cpu))
+ puts ("m68k-hitachi-hiuxwe2");
+ else puts ("unknown-hitachi-hiuxwe2");
+ exit (0);
+ }
+EOF
+ $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
+ { echo "$SYSTEM_NAME"; exit; }
+ echo unknown-hitachi-hiuxwe2
+ exit ;;
+ 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
+ echo hppa1.1-hp-bsd
+ exit ;;
+ 9000/8??:4.3bsd:*:*)
+ echo hppa1.0-hp-bsd
+ exit ;;
+ *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
+ echo hppa1.0-hp-mpeix
+ exit ;;
+ hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
+ echo hppa1.1-hp-osf
+ exit ;;
+ hp8??:OSF1:*:*)
+ echo hppa1.0-hp-osf
+ exit ;;
+ i*86:OSF1:*:*)
+ if [ -x /usr/sbin/sysversion ] ; then
+ echo ${UNAME_MACHINE}-unknown-osf1mk
+ else
+ echo ${UNAME_MACHINE}-unknown-osf1
+ fi
+ exit ;;
+ parisc*:Lites*:*:*)
+ echo hppa1.1-hp-lites
+ exit ;;
+ C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
+ echo c1-convex-bsd
+ exit ;;
+ C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
+ if getsysinfo -f scalar_acc
+ then echo c32-convex-bsd
+ else echo c2-convex-bsd
+ fi
+ exit ;;
+ C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
+ echo c34-convex-bsd
+ exit ;;
+ C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
+ echo c38-convex-bsd
+ exit ;;
+ C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
+ echo c4-convex-bsd
+ exit ;;
+ CRAY*Y-MP:*:*:*)
+ echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*[A-Z]90:*:*:*)
+ echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
+ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
+ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
+ -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*TS:*:*:*)
+ echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*T3E:*:*:*)
+ echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*SV1:*:*:*)
+ echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ *:UNICOS/mp:*:*)
+ echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
+ FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+ FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+ FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
+ echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+ exit ;;
+ 5000:UNIX_System_V:4.*:*)
+ FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+ FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+ echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+ exit ;;
+ i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
+ echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
+ exit ;;
+ sparc*:BSD/OS:*:*)
+ echo sparc-unknown-bsdi${UNAME_RELEASE}
+ exit ;;
+ *:BSD/OS:*:*)
+ echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
+ exit ;;
+ *:FreeBSD:*:*)
+ echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
+ exit ;;
+ i*:CYGWIN*:*)
+ echo ${UNAME_MACHINE}-pc-cygwin
+ exit ;;
+ i*:MINGW*:*)
+ echo ${UNAME_MACHINE}-pc-mingw32
+ exit ;;
+ i*:windows32*:*)
+ # uname -m includes "-pc" on this system.
+ echo ${UNAME_MACHINE}-mingw32
+ exit ;;
+ i*:PW*:*)
+ echo ${UNAME_MACHINE}-pc-pw32
+ exit ;;
+ x86:Interix*:[345]*)
+ echo i586-pc-interix${UNAME_RELEASE}|sed -e 's/\..*//'
+ exit ;;
+ [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
+ echo i${UNAME_MACHINE}-pc-mks
+ exit ;;
+ i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
+ # How do we know it's Interix rather than the generic POSIX subsystem?
+ # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
+ # UNAME_MACHINE based on the output of uname instead of i386?
+ echo i586-pc-interix
+ exit ;;
+ i*:UWIN*:*)
+ echo ${UNAME_MACHINE}-pc-uwin
+ exit ;;
+ amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
+ echo x86_64-unknown-cygwin
+ exit ;;
+ p*:CYGWIN*:*)
+ echo powerpcle-unknown-cygwin
+ exit ;;
+ prep*:SunOS:5.*:*)
+ echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ *:GNU:*:*)
+ # the GNU system
+ echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
+ exit ;;
+ *:GNU/*:*:*)
+ # other systems with GNU libc and userland
+ echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu
+ exit ;;
+ i*86:Minix:*:*)
+ echo ${UNAME_MACHINE}-pc-minix
+ exit ;;
+ arm*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ cris:Linux:*:*)
+ echo cris-axis-linux-gnu
+ exit ;;
+ crisv32:Linux:*:*)
+ echo crisv32-axis-linux-gnu
+ exit ;;
+ frv:Linux:*:*)
+ echo frv-unknown-linux-gnu
+ exit ;;
+ ia64:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ m32r*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ m68*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ mips:Linux:*:*)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #undef CPU
+ #undef mips
+ #undef mipsel
+ #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+ CPU=mipsel
+ #else
+ #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+ CPU=mips
+ #else
+ CPU=
+ #endif
+ #endif
+EOF
+ eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '/^CPU/{s: ::g;p;}'`"
+ test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+ ;;
+ mips64:Linux:*:*)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #undef CPU
+ #undef mips64
+ #undef mips64el
+ #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+ CPU=mips64el
+ #else
+ #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+ CPU=mips64
+ #else
+ CPU=
+ #endif
+ #endif
+EOF
+ eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '/^CPU/{s: ::g;p;}'`"
+ test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+ ;;
+ or32:Linux:*:*)
+ echo or32-unknown-linux-gnu
+ exit ;;
+ ppc:Linux:*:*)
+ echo powerpc-unknown-linux-gnu
+ exit ;;
+ ppc64:Linux:*:*)
+ echo powerpc64-unknown-linux-gnu
+ exit ;;
+ alpha:Linux:*:*)
+ case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
+ EV5) UNAME_MACHINE=alphaev5 ;;
+ EV56) UNAME_MACHINE=alphaev56 ;;
+ PCA56) UNAME_MACHINE=alphapca56 ;;
+ PCA57) UNAME_MACHINE=alphapca56 ;;
+ EV6) UNAME_MACHINE=alphaev6 ;;
+ EV67) UNAME_MACHINE=alphaev67 ;;
+ EV68*) UNAME_MACHINE=alphaev68 ;;
+ esac
+ objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null
+ if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
+ echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
+ exit ;;
+ parisc:Linux:*:* | hppa:Linux:*:*)
+ # Look for CPU level
+ case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
+ PA7*) echo hppa1.1-unknown-linux-gnu ;;
+ PA8*) echo hppa2.0-unknown-linux-gnu ;;
+ *) echo hppa-unknown-linux-gnu ;;
+ esac
+ exit ;;
+ parisc64:Linux:*:* | hppa64:Linux:*:*)
+ echo hppa64-unknown-linux-gnu
+ exit ;;
+ s390:Linux:*:* | s390x:Linux:*:*)
+ echo ${UNAME_MACHINE}-ibm-linux
+ exit ;;
+ sh64*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ sh*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ sparc:Linux:*:* | sparc64:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-gnu
+ exit ;;
+ vax:Linux:*:*)
+ echo ${UNAME_MACHINE}-dec-linux-gnu
+ exit ;;
+ x86_64:Linux:*:*)
+ echo x86_64-unknown-linux-gnu
+ exit ;;
+ i*86:Linux:*:*)
+ # The BFD linker knows what the default object file format is, so
+ # first see if it will tell us. cd to the root directory to prevent
+ # problems with other programs or directories called `ld' in the path.
+ # Set LC_ALL=C to ensure ld outputs messages in English.
+ ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \
+ | sed -ne '/supported targets:/!d
+ s/[ ][ ]*/ /g
+ s/.*supported targets: *//
+ s/ .*//
+ p'`
+ case "$ld_supported_targets" in
+ elf32-i386)
+ TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu"
+ ;;
+ a.out-i386-linux)
+ echo "${UNAME_MACHINE}-pc-linux-gnuaout"
+ exit ;;
+ coff-i386)
+ echo "${UNAME_MACHINE}-pc-linux-gnucoff"
+ exit ;;
+ "")
+ # Either a pre-BFD a.out linker (linux-gnuoldld) or
+ # one that does not give us useful --help.
+ echo "${UNAME_MACHINE}-pc-linux-gnuoldld"
+ exit ;;
+ esac
+ # Determine whether the default compiler is a.out or elf
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #include <features.h>
+ #ifdef __ELF__
+ # ifdef __GLIBC__
+ # if __GLIBC__ >= 2
+ LIBC=gnu
+ # else
+ LIBC=gnulibc1
+ # endif
+ # else
+ LIBC=gnulibc1
+ # endif
+ #else
+ #if defined(__INTEL_COMPILER) || defined(__PGI)
+ LIBC=gnu
+ #else
+ LIBC=gnuaout
+ #endif
+ #endif
+ #ifdef __dietlibc__
+ LIBC=dietlibc
+ #endif
+EOF
+ eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '/^LIBC/{s: ::g;p;}'`"
+ test x"${LIBC}" != x && {
+ echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
+ exit
+ }
+ test x"${TENTATIVE}" != x && { echo "${TENTATIVE}"; exit; }
+ ;;
+ i*86:DYNIX/ptx:4*:*)
+ # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
+ # earlier versions are messed up and put the nodename in both
+ # sysname and nodename.
+ echo i386-sequent-sysv4
+ exit ;;
+ i*86:UNIX_SV:4.2MP:2.*)
+ # Unixware is an offshoot of SVR4, but it has its own version
+ # number series starting with 2...
+ # I am not positive that other SVR4 systems won't match this,
+ # I just have to hope. -- rms.
+ # Use sysv4.2uw... so that sysv4* matches it.
+ echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
+ exit ;;
+ i*86:OS/2:*:*)
+ # If we were able to find `uname', then EMX Unix compatibility
+ # is probably installed.
+ echo ${UNAME_MACHINE}-pc-os2-emx
+ exit ;;
+ i*86:XTS-300:*:STOP)
+ echo ${UNAME_MACHINE}-unknown-stop
+ exit ;;
+ i*86:atheos:*:*)
+ echo ${UNAME_MACHINE}-unknown-atheos
+ exit ;;
+ i*86:syllable:*:*)
+ echo ${UNAME_MACHINE}-pc-syllable
+ exit ;;
+ i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
+ echo i386-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ i*86:*DOS:*:*)
+ echo ${UNAME_MACHINE}-pc-msdosdjgpp
+ exit ;;
+ i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
+ UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
+ if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
+ echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
+ else
+ echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
+ fi
+ exit ;;
+ i*86:*:5:[678]*)
+ # UnixWare 7.x, OpenUNIX and OpenServer 6.
+ case `/bin/uname -X | grep "^Machine"` in
+ *486*) UNAME_MACHINE=i486 ;;
+ *Pentium) UNAME_MACHINE=i586 ;;
+ *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
+ esac
+ echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
+ exit ;;
+ i*86:*:3.2:*)
+ if test -f /usr/options/cb.name; then
+ UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
+ echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
+ elif /bin/uname -X 2>/dev/null >/dev/null ; then
+ UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
+ (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
+ (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
+ && UNAME_MACHINE=i586
+ (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
+ && UNAME_MACHINE=i686
+ (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
+ && UNAME_MACHINE=i686
+ echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
+ else
+ echo ${UNAME_MACHINE}-pc-sysv32
+ fi
+ exit ;;
+ pc:*:*:*)
+ # Left here for compatibility:
+ # uname -m prints for DJGPP always 'pc', but it prints nothing about
+ # the processor, so we play safe by assuming i386.
+ echo i386-pc-msdosdjgpp
+ exit ;;
+ Intel:Mach:3*:*)
+ echo i386-pc-mach3
+ exit ;;
+ paragon:*:*:*)
+ echo i860-intel-osf1
+ exit ;;
+ i860:*:4.*:*) # i860-SVR4
+ if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
+ echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
+ else # Add other i860-SVR4 vendors below as they are discovered.
+ echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4
+ fi
+ exit ;;
+ mini*:CTIX:SYS*5:*)
+ # "miniframe"
+ echo m68010-convergent-sysv
+ exit ;;
+ mc68k:UNIX:SYSTEM5:3.51m)
+ echo m68k-convergent-sysv
+ exit ;;
+ M680?0:D-NIX:5.3:*)
+ echo m68k-diab-dnix
+ exit ;;
+ M68*:*:R3V[5678]*:*)
+ test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
+ 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
+ OS_REL=''
+ test -r /etc/.relid \
+ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+ /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+ && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+ /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+ 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
+ /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+ && { echo i486-ncr-sysv4; exit; } ;;
+ m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
+ echo m68k-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ mc68030:UNIX_System_V:4.*:*)
+ echo m68k-atari-sysv4
+ exit ;;
+ TSUNAMI:LynxOS:2.*:*)
+ echo sparc-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ rs6000:LynxOS:2.*:*)
+ echo rs6000-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*)
+ echo powerpc-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ SM[BE]S:UNIX_SV:*:*)
+ echo mips-dde-sysv${UNAME_RELEASE}
+ exit ;;
+ RM*:ReliantUNIX-*:*:*)
+ echo mips-sni-sysv4
+ exit ;;
+ RM*:SINIX-*:*:*)
+ echo mips-sni-sysv4
+ exit ;;
+ *:SINIX-*:*:*)
+ if uname -p 2>/dev/null >/dev/null ; then
+ UNAME_MACHINE=`(uname -p) 2>/dev/null`
+ echo ${UNAME_MACHINE}-sni-sysv4
+ else
+ echo ns32k-sni-sysv
+ fi
+ exit ;;
+ PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
+ # says <Richard.M.Bartel at ccMail.Census.GOV>
+ echo i586-unisys-sysv4
+ exit ;;
+ *:UNIX_System_V:4*:FTX*)
+ # From Gerald Hewes <hewes at openmarket.com>.
+ # How about differentiating between stratus architectures? -djm
+ echo hppa1.1-stratus-sysv4
+ exit ;;
+ *:*:*:FTX*)
+ # From seanf at swdc.stratus.com.
+ echo i860-stratus-sysv4
+ exit ;;
+ i*86:VOS:*:*)
+ # From Paul.Green at stratus.com.
+ echo ${UNAME_MACHINE}-stratus-vos
+ exit ;;
+ *:VOS:*:*)
+ # From Paul.Green at stratus.com.
+ echo hppa1.1-stratus-vos
+ exit ;;
+ mc68*:A/UX:*:*)
+ echo m68k-apple-aux${UNAME_RELEASE}
+ exit ;;
+ news*:NEWS-OS:6*:*)
+ echo mips-sony-newsos6
+ exit ;;
+ R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
+ if [ -d /usr/nec ]; then
+ echo mips-nec-sysv${UNAME_RELEASE}
+ else
+ echo mips-unknown-sysv${UNAME_RELEASE}
+ fi
+ exit ;;
+ BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only.
+ echo powerpc-be-beos
+ exit ;;
+ BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only.
+ echo powerpc-apple-beos
+ exit ;;
+ BePC:BeOS:*:*) # BeOS running on Intel PC compatible.
+ echo i586-pc-beos
+ exit ;;
+ SX-4:SUPER-UX:*:*)
+ echo sx4-nec-superux${UNAME_RELEASE}
+ exit ;;
+ SX-5:SUPER-UX:*:*)
+ echo sx5-nec-superux${UNAME_RELEASE}
+ exit ;;
+ SX-6:SUPER-UX:*:*)
+ echo sx6-nec-superux${UNAME_RELEASE}
+ exit ;;
+ Power*:Rhapsody:*:*)
+ echo powerpc-apple-rhapsody${UNAME_RELEASE}
+ exit ;;
+ *:Rhapsody:*:*)
+ echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
+ exit ;;
+ *:Darwin:*:*)
+ UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
+ case $UNAME_PROCESSOR in
+ i*86) UNAME_PROCESSOR=i686 ;;
+ unknown) UNAME_PROCESSOR=powerpc ;;
+ esac
+ echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
+ exit ;;
+ *:procnto*:*:* | *:QNX:[0123456789]*:*)
+ UNAME_PROCESSOR=`uname -p`
+ if test "$UNAME_PROCESSOR" = "x86"; then
+ UNAME_PROCESSOR=i386
+ UNAME_MACHINE=pc
+ fi
+ echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
+ exit ;;
+ *:QNX:*:4*)
+ echo i386-pc-qnx
+ exit ;;
+ NSE-?:NONSTOP_KERNEL:*:*)
+ echo nse-tandem-nsk${UNAME_RELEASE}
+ exit ;;
+ NSR-?:NONSTOP_KERNEL:*:*)
+ echo nsr-tandem-nsk${UNAME_RELEASE}
+ exit ;;
+ *:NonStop-UX:*:*)
+ echo mips-compaq-nonstopux
+ exit ;;
+ BS2000:POSIX*:*:*)
+ echo bs2000-siemens-sysv
+ exit ;;
+ DS/*:UNIX_System_V:*:*)
+ echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
+ exit ;;
+ *:Plan9:*:*)
+ # "uname -m" is not consistent, so use $cputype instead. 386
+ # is converted to i386 for consistency with other x86
+ # operating systems.
+ if test "$cputype" = "386"; then
+ UNAME_MACHINE=i386
+ else
+ UNAME_MACHINE="$cputype"
+ fi
+ echo ${UNAME_MACHINE}-unknown-plan9
+ exit ;;
+ *:TOPS-10:*:*)
+ echo pdp10-unknown-tops10
+ exit ;;
+ *:TENEX:*:*)
+ echo pdp10-unknown-tenex
+ exit ;;
+ KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
+ echo pdp10-dec-tops20
+ exit ;;
+ XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
+ echo pdp10-xkl-tops20
+ exit ;;
+ *:TOPS-20:*:*)
+ echo pdp10-unknown-tops20
+ exit ;;
+ *:ITS:*:*)
+ echo pdp10-unknown-its
+ exit ;;
+ SEI:*:*:SEIUX)
+ echo mips-sei-seiux${UNAME_RELEASE}
+ exit ;;
+ *:DragonFly:*:*)
+ echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
+ exit ;;
+ *:*VMS:*:*)
+ UNAME_MACHINE=`(uname -p) 2>/dev/null`
+ case "${UNAME_MACHINE}" in
+ A*) echo alpha-dec-vms ; exit ;;
+ I*) echo ia64-dec-vms ; exit ;;
+ V*) echo vax-dec-vms ; exit ;;
+ esac ;;
+ *:XENIX:*:SysV)
+ echo i386-pc-xenix
+ exit ;;
+ i*86:skyos:*:*)
+ echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
+ exit ;;
+ i*86:rdos:*:*)
+ echo ${UNAME_MACHINE}-pc-rdos
+ exit ;;
+esac
+
+#echo '(No uname command or uname output not recognized.)' 1>&2
+#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2
+
+eval $set_cc_for_build
+cat >$dummy.c <<EOF
+#ifdef _SEQUENT_
+# include <sys/types.h>
+# include <sys/utsname.h>
+#endif
+main ()
+{
+#if defined (sony)
+#if defined (MIPSEB)
+ /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed,
+ I don't know.... */
+ printf ("mips-sony-bsd\n"); exit (0);
+#else
+#include <sys/param.h>
+ printf ("m68k-sony-newsos%s\n",
+#ifdef NEWSOS4
+ "4"
+#else
+ ""
+#endif
+ ); exit (0);
+#endif
+#endif
+
+#if defined (__arm) && defined (__acorn) && defined (__unix)
+ printf ("arm-acorn-riscix\n"); exit (0);
+#endif
+
+#if defined (hp300) && !defined (hpux)
+ printf ("m68k-hp-bsd\n"); exit (0);
+#endif
+
+#if defined (NeXT)
+#if !defined (__ARCHITECTURE__)
+#define __ARCHITECTURE__ "m68k"
+#endif
+ int version;
+ version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
+ if (version < 4)
+ printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
+ else
+ printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
+ exit (0);
+#endif
+
+#if defined (MULTIMAX) || defined (n16)
+#if defined (UMAXV)
+ printf ("ns32k-encore-sysv\n"); exit (0);
+#else
+#if defined (CMU)
+ printf ("ns32k-encore-mach\n"); exit (0);
+#else
+ printf ("ns32k-encore-bsd\n"); exit (0);
+#endif
+#endif
+#endif
+
+#if defined (__386BSD__)
+ printf ("i386-pc-bsd\n"); exit (0);
+#endif
+
+#if defined (sequent)
+#if defined (i386)
+ printf ("i386-sequent-dynix\n"); exit (0);
+#endif
+#if defined (ns32000)
+ printf ("ns32k-sequent-dynix\n"); exit (0);
+#endif
+#endif
+
+#if defined (_SEQUENT_)
+ struct utsname un;
+
+ uname(&un);
+
+ if (strncmp(un.version, "V2", 2) == 0) {
+ printf ("i386-sequent-ptx2\n"); exit (0);
+ }
+ if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
+ printf ("i386-sequent-ptx1\n"); exit (0);
+ }
+ printf ("i386-sequent-ptx\n"); exit (0);
+
+#endif
+
+#if defined (vax)
+# if !defined (ultrix)
+# include <sys/param.h>
+# if defined (BSD)
+# if BSD == 43
+ printf ("vax-dec-bsd4.3\n"); exit (0);
+# else
+# if BSD == 199006
+ printf ("vax-dec-bsd4.3reno\n"); exit (0);
+# else
+ printf ("vax-dec-bsd\n"); exit (0);
+# endif
+# endif
+# else
+ printf ("vax-dec-bsd\n"); exit (0);
+# endif
+# else
+ printf ("vax-dec-ultrix\n"); exit (0);
+# endif
+#endif
+
+#if defined (alliant) && defined (i860)
+ printf ("i860-alliant-bsd\n"); exit (0);
+#endif
+
+ exit (1);
+}
+EOF
+
+$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
+ { echo "$SYSTEM_NAME"; exit; }
+
+# Apollos put the system type in the environment.
+
+test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }
+
+# Convex versions that predate uname can use getsysinfo(1)
+
+if [ -x /usr/convex/getsysinfo ]
+then
+ case `getsysinfo -f cpu_type` in
+ c1*)
+ echo c1-convex-bsd
+ exit ;;
+ c2*)
+ if getsysinfo -f scalar_acc
+ then echo c32-convex-bsd
+ else echo c2-convex-bsd
+ fi
+ exit ;;
+ c34*)
+ echo c34-convex-bsd
+ exit ;;
+ c38*)
+ echo c38-convex-bsd
+ exit ;;
+ c4*)
+ echo c4-convex-bsd
+ exit ;;
+ esac
+fi
+
+cat >&2 <<EOF
+$0: unable to guess system type
+
+This script, last modified $timestamp, has failed to recognize
+the operating system you are using. It is advised that you
+download the most up to date version of the config scripts from
+
+ http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.guess
+and
+ http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.sub
+
+If the version you run ($0) is already up to date, please
+send the following data and any information you think might be
+pertinent to <config-patches at gnu.org> in order to provide the needed
+information to handle your system.
+
+config.guess timestamp = $timestamp
+
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
+/bin/uname -X = `(/bin/uname -X) 2>/dev/null`
+
+hostinfo = `(hostinfo) 2>/dev/null`
+/bin/universe = `(/bin/universe) 2>/dev/null`
+/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null`
+/bin/arch = `(/bin/arch) 2>/dev/null`
+/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
+
+UNAME_MACHINE = ${UNAME_MACHINE}
+UNAME_RELEASE = ${UNAME_RELEASE}
+UNAME_SYSTEM = ${UNAME_SYSTEM}
+UNAME_VERSION = ${UNAME_VERSION}
+EOF
+
+exit 1
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/jpeg-6c/config.sub b/jpeg-6c/config.sub
new file mode 100644
index 0000000..2851647
--- /dev/null
+++ b/jpeg-6c/config.sub
@@ -0,0 +1,1599 @@
+#! /bin/sh
+# Configuration validation subroutine script.
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+# 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
+
+timestamp='2005-12-11'
+
+# This file is (in principle) common to ALL GNU software.
+# The presence of a machine in this file suggests that SOME GNU software
+# can handle that machine. It does not imply ALL GNU software can.
+#
+# This file 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
+# 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, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
+# 02110-1301, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+
+# Please send patches to <config-patches at gnu.org>. Submit a context
+# diff and a properly formatted ChangeLog entry.
+#
+# Configuration subroutine to validate and canonicalize a configuration type.
+# Supply the specified configuration type as an argument.
+# If it is invalid, we print an error message on stderr and exit with code 1.
+# Otherwise, we print the canonical config type on stdout and succeed.
+
+# This file is supposed to be the same for all GNU packages
+# and recognize all the CPU types, system types and aliases
+# that are meaningful with *any* GNU software.
+# Each package is responsible for reporting which valid configurations
+# it does not support. The user should be able to distinguish
+# a failure to support a valid configuration from a meaningless
+# configuration.
+
+# The goal of this file is to map all the various variations of a given
+# machine specification into a single specification in the form:
+# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
+# or in some cases, the newer four-part form:
+# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
+# It is wrong to echo any other type of specification.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION] CPU-MFR-OPSYS
+ $0 [OPTION] ALIAS
+
+Canonicalize a configuration name.
+
+Operation modes:
+ -h, --help print this help, then exit
+ -t, --time-stamp print date of last modification, then exit
+ -v, --version print version number, then exit
+
+Report bugs and patches to <config-patches at gnu.org>."
+
+version="\
+GNU config.sub ($timestamp)
+
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
+Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions. There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+ case $1 in
+ --time-stamp | --time* | -t )
+ echo "$timestamp" ; exit ;;
+ --version | -v )
+ echo "$version" ; exit ;;
+ --help | --h* | -h )
+ echo "$usage"; exit ;;
+ -- ) # Stop option processing
+ shift; break ;;
+ - ) # Use stdin as input.
+ break ;;
+ -* )
+ echo "$me: invalid option $1$help"
+ exit 1 ;;
+
+ *local*)
+ # First pass through any local machine types.
+ echo $1
+ exit ;;
+
+ * )
+ break ;;
+ esac
+done
+
+case $# in
+ 0) echo "$me: missing argument$help" >&2
+ exit 1;;
+ 1) ;;
+ *) echo "$me: too many arguments$help" >&2
+ exit 1;;
+esac
+
+# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
+# Here we must recognize all the valid KERNEL-OS combinations.
+maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
+case $maybe_os in
+ nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \
+ uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \
+ storm-chaos* | os2-emx* | rtmk-nova*)
+ os=-$maybe_os
+ basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
+ ;;
+ *)
+ basic_machine=`echo $1 | sed 's/-[^-]*$//'`
+ if [ $basic_machine != $1 ]
+ then os=`echo $1 | sed 's/.*-/-/'`
+ else os=; fi
+ ;;
+esac
+
+### Let's recognize common machines as not being operating systems so
+### that things like config.sub decstation-3100 work. We also
+### recognize some manufacturers as not being operating systems, so we
+### can provide default operating systems below.
+case $os in
+ -sun*os*)
+ # Prevent following clause from handling this invalid input.
+ ;;
+ -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
+ -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
+ -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
+ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
+ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
+ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
+ -apple | -axis | -knuth | -cray)
+ os=
+ basic_machine=$1
+ ;;
+ -sim | -cisco | -oki | -wec | -winbond)
+ os=
+ basic_machine=$1
+ ;;
+ -scout)
+ ;;
+ -wrs)
+ os=-vxworks
+ basic_machine=$1
+ ;;
+ -chorusos*)
+ os=-chorusos
+ basic_machine=$1
+ ;;
+ -chorusrdb)
+ os=-chorusrdb
+ basic_machine=$1
+ ;;
+ -hiux*)
+ os=-hiuxwe2
+ ;;
+ -sco6)
+ os=-sco5v6
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco5)
+ os=-sco3.2v5
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco4)
+ os=-sco3.2v4
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco3.2.[4-9]*)
+ os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco3.2v[4-9]*)
+ # Don't forget version if it is 3.2v4 or newer.
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco5v6*)
+ # Don't forget version if it is 3.2v4 or newer.
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco*)
+ os=-sco3.2v2
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -udk*)
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -isc)
+ os=-isc2.2
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -clix*)
+ basic_machine=clipper-intergraph
+ ;;
+ -isc*)
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -lynx*)
+ os=-lynxos
+ ;;
+ -ptx*)
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
+ ;;
+ -windowsnt*)
+ os=`echo $os | sed -e 's/windowsnt/winnt/'`
+ ;;
+ -psos*)
+ os=-psos
+ ;;
+ -mint | -mint[0-9]*)
+ basic_machine=m68k-atari
+ os=-mint
+ ;;
+esac
+
+# Decode aliases for certain CPU-COMPANY combinations.
+case $basic_machine in
+ # Recognize the basic CPU types without company name.
+ # Some are omitted here because they have special meanings below.
+ 1750a | 580 \
+ | a29k \
+ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
+ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
+ | am33_2.0 \
+ | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \
+ | bfin \
+ | c4x | clipper \
+ | d10v | d30v | dlx | dsp16xx \
+ | fr30 | frv \
+ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
+ | i370 | i860 | i960 | ia64 \
+ | ip2k | iq2000 \
+ | m32r | m32rle | m68000 | m68k | m88k | maxq | mcore \
+ | mips | mipsbe | mipseb | mipsel | mipsle \
+ | mips16 \
+ | mips64 | mips64el \
+ | mips64vr | mips64vrel \
+ | mips64orion | mips64orionel \
+ | mips64vr4100 | mips64vr4100el \
+ | mips64vr4300 | mips64vr4300el \
+ | mips64vr5000 | mips64vr5000el \
+ | mips64vr5900 | mips64vr5900el \
+ | mipsisa32 | mipsisa32el \
+ | mipsisa32r2 | mipsisa32r2el \
+ | mipsisa64 | mipsisa64el \
+ | mipsisa64r2 | mipsisa64r2el \
+ | mipsisa64sb1 | mipsisa64sb1el \
+ | mipsisa64sr71k | mipsisa64sr71kel \
+ | mipstx39 | mipstx39el \
+ | mn10200 | mn10300 \
+ | mt \
+ | msp430 \
+ | ns16k | ns32k \
+ | or32 \
+ | pdp10 | pdp11 | pj | pjl \
+ | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
+ | pyramid \
+ | sh | sh[1234] | sh[24]a | sh[23]e | sh[34]eb | shbe | shle | sh[1234]le | sh3ele \
+ | sh64 | sh64le \
+ | sparc | sparc64 | sparc64b | sparc86x | sparclet | sparclite \
+ | sparcv8 | sparcv9 | sparcv9b \
+ | strongarm \
+ | tahoe | thumb | tic4x | tic80 | tron \
+ | v850 | v850e \
+ | we32k \
+ | x86 | xscale | xscalee[bl] | xstormy16 | xtensa \
+ | z8k)
+ basic_machine=$basic_machine-unknown
+ ;;
+ m32c)
+ basic_machine=$basic_machine-unknown
+ ;;
+ m6811 | m68hc11 | m6812 | m68hc12)
+ # Motorola 68HC11/12.
+ basic_machine=$basic_machine-unknown
+ os=-none
+ ;;
+ m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
+ ;;
+ ms1)
+ basic_machine=mt-unknown
+ ;;
+
+ # We use `pc' rather than `unknown'
+ # because (1) that's what they normally are, and
+ # (2) the word "unknown" tends to confuse beginning users.
+ i*86 | x86_64)
+ basic_machine=$basic_machine-pc
+ ;;
+ # Object if more than one company name word.
+ *-*-*)
+ echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+ exit 1
+ ;;
+ # Recognize the basic CPU types with company name.
+ 580-* \
+ | a29k-* \
+ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
+ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
+ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
+ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \
+ | avr-* \
+ | bfin-* | bs2000-* \
+ | c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \
+ | clipper-* | craynv-* | cydra-* \
+ | d10v-* | d30v-* | dlx-* \
+ | elxsi-* \
+ | f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \
+ | h8300-* | h8500-* \
+ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
+ | i*86-* | i860-* | i960-* | ia64-* \
+ | ip2k-* | iq2000-* \
+ | m32r-* | m32rle-* \
+ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
+ | m88110-* | m88k-* | maxq-* | mcore-* \
+ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
+ | mips16-* \
+ | mips64-* | mips64el-* \
+ | mips64vr-* | mips64vrel-* \
+ | mips64orion-* | mips64orionel-* \
+ | mips64vr4100-* | mips64vr4100el-* \
+ | mips64vr4300-* | mips64vr4300el-* \
+ | mips64vr5000-* | mips64vr5000el-* \
+ | mips64vr5900-* | mips64vr5900el-* \
+ | mipsisa32-* | mipsisa32el-* \
+ | mipsisa32r2-* | mipsisa32r2el-* \
+ | mipsisa64-* | mipsisa64el-* \
+ | mipsisa64r2-* | mipsisa64r2el-* \
+ | mipsisa64sb1-* | mipsisa64sb1el-* \
+ | mipsisa64sr71k-* | mipsisa64sr71kel-* \
+ | mipstx39-* | mipstx39el-* \
+ | mmix-* \
+ | mt-* \
+ | msp430-* \
+ | none-* | np1-* | ns16k-* | ns32k-* \
+ | orion-* \
+ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
+ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
+ | pyramid-* \
+ | romp-* | rs6000-* \
+ | sh-* | sh[1234]-* | sh[24]a-* | sh[23]e-* | sh[34]eb-* | shbe-* \
+ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
+ | sparc-* | sparc64-* | sparc64b-* | sparc86x-* | sparclet-* \
+ | sparclite-* \
+ | sparcv8-* | sparcv9-* | sparcv9b-* | strongarm-* | sv1-* | sx?-* \
+ | tahoe-* | thumb-* \
+ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
+ | tron-* \
+ | v850-* | v850e-* | vax-* \
+ | we32k-* \
+ | x86-* | x86_64-* | xps100-* | xscale-* | xscalee[bl]-* \
+ | xstormy16-* | xtensa-* \
+ | ymp-* \
+ | z8k-*)
+ ;;
+ m32c-*)
+ ;;
+ # Recognize the various machine names and aliases which stand
+ # for a CPU type and a company and sometimes even an OS.
+ 386bsd)
+ basic_machine=i386-unknown
+ os=-bsd
+ ;;
+ 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
+ basic_machine=m68000-att
+ ;;
+ 3b*)
+ basic_machine=we32k-att
+ ;;
+ a29khif)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ abacus)
+ basic_machine=abacus-unknown
+ ;;
+ adobe68k)
+ basic_machine=m68010-adobe
+ os=-scout
+ ;;
+ alliant | fx80)
+ basic_machine=fx80-alliant
+ ;;
+ altos | altos3068)
+ basic_machine=m68k-altos
+ ;;
+ am29k)
+ basic_machine=a29k-none
+ os=-bsd
+ ;;
+ amd64)
+ basic_machine=x86_64-pc
+ ;;
+ amd64-*)
+ basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ amdahl)
+ basic_machine=580-amdahl
+ os=-sysv
+ ;;
+ amiga | amiga-*)
+ basic_machine=m68k-unknown
+ ;;
+ amigaos | amigados)
+ basic_machine=m68k-unknown
+ os=-amigaos
+ ;;
+ amigaunix | amix)
+ basic_machine=m68k-unknown
+ os=-sysv4
+ ;;
+ apollo68)
+ basic_machine=m68k-apollo
+ os=-sysv
+ ;;
+ apollo68bsd)
+ basic_machine=m68k-apollo
+ os=-bsd
+ ;;
+ aux)
+ basic_machine=m68k-apple
+ os=-aux
+ ;;
+ balance)
+ basic_machine=ns32k-sequent
+ os=-dynix
+ ;;
+ c90)
+ basic_machine=c90-cray
+ os=-unicos
+ ;;
+ convex-c1)
+ basic_machine=c1-convex
+ os=-bsd
+ ;;
+ convex-c2)
+ basic_machine=c2-convex
+ os=-bsd
+ ;;
+ convex-c32)
+ basic_machine=c32-convex
+ os=-bsd
+ ;;
+ convex-c34)
+ basic_machine=c34-convex
+ os=-bsd
+ ;;
+ convex-c38)
+ basic_machine=c38-convex
+ os=-bsd
+ ;;
+ cray | j90)
+ basic_machine=j90-cray
+ os=-unicos
+ ;;
+ craynv)
+ basic_machine=craynv-cray
+ os=-unicosmp
+ ;;
+ cr16c)
+ basic_machine=cr16c-unknown
+ os=-elf
+ ;;
+ crds | unos)
+ basic_machine=m68k-crds
+ ;;
+ crisv32 | crisv32-* | etraxfs*)
+ basic_machine=crisv32-axis
+ ;;
+ cris | cris-* | etrax*)
+ basic_machine=cris-axis
+ ;;
+ crx)
+ basic_machine=crx-unknown
+ os=-elf
+ ;;
+ da30 | da30-*)
+ basic_machine=m68k-da30
+ ;;
+ decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
+ basic_machine=mips-dec
+ ;;
+ decsystem10* | dec10*)
+ basic_machine=pdp10-dec
+ os=-tops10
+ ;;
+ decsystem20* | dec20*)
+ basic_machine=pdp10-dec
+ os=-tops20
+ ;;
+ delta | 3300 | motorola-3300 | motorola-delta \
+ | 3300-motorola | delta-motorola)
+ basic_machine=m68k-motorola
+ ;;
+ delta88)
+ basic_machine=m88k-motorola
+ os=-sysv3
+ ;;
+ djgpp)
+ basic_machine=i586-pc
+ os=-msdosdjgpp
+ ;;
+ dpx20 | dpx20-*)
+ basic_machine=rs6000-bull
+ os=-bosx
+ ;;
+ dpx2* | dpx2*-bull)
+ basic_machine=m68k-bull
+ os=-sysv3
+ ;;
+ ebmon29k)
+ basic_machine=a29k-amd
+ os=-ebmon
+ ;;
+ elxsi)
+ basic_machine=elxsi-elxsi
+ os=-bsd
+ ;;
+ encore | umax | mmax)
+ basic_machine=ns32k-encore
+ ;;
+ es1800 | OSE68k | ose68k | ose | OSE)
+ basic_machine=m68k-ericsson
+ os=-ose
+ ;;
+ fx2800)
+ basic_machine=i860-alliant
+ ;;
+ genix)
+ basic_machine=ns32k-ns
+ ;;
+ gmicro)
+ basic_machine=tron-gmicro
+ os=-sysv
+ ;;
+ go32)
+ basic_machine=i386-pc
+ os=-go32
+ ;;
+ h3050r* | hiux*)
+ basic_machine=hppa1.1-hitachi
+ os=-hiuxwe2
+ ;;
+ h8300hms)
+ basic_machine=h8300-hitachi
+ os=-hms
+ ;;
+ h8300xray)
+ basic_machine=h8300-hitachi
+ os=-xray
+ ;;
+ h8500hms)
+ basic_machine=h8500-hitachi
+ os=-hms
+ ;;
+ harris)
+ basic_machine=m88k-harris
+ os=-sysv3
+ ;;
+ hp300-*)
+ basic_machine=m68k-hp
+ ;;
+ hp300bsd)
+ basic_machine=m68k-hp
+ os=-bsd
+ ;;
+ hp300hpux)
+ basic_machine=m68k-hp
+ os=-hpux
+ ;;
+ hp3k9[0-9][0-9] | hp9[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hp9k2[0-9][0-9] | hp9k31[0-9])
+ basic_machine=m68000-hp
+ ;;
+ hp9k3[2-9][0-9])
+ basic_machine=m68k-hp
+ ;;
+ hp9k6[0-9][0-9] | hp6[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hp9k7[0-79][0-9] | hp7[0-79][0-9])
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k78[0-9] | hp78[0-9])
+ # FIXME: really hppa2.0-hp
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
+ # FIXME: really hppa2.0-hp
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[0-9][13679] | hp8[0-9][13679])
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[0-9][0-9] | hp8[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hppa-next)
+ os=-nextstep3
+ ;;
+ hppaosf)
+ basic_machine=hppa1.1-hp
+ os=-osf
+ ;;
+ hppro)
+ basic_machine=hppa1.1-hp
+ os=-proelf
+ ;;
+ i370-ibm* | ibm*)
+ basic_machine=i370-ibm
+ ;;
+# I'm not sure what "Sysv32" means. Should this be sysv3.2?
+ i*86v32)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-sysv32
+ ;;
+ i*86v4*)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-sysv4
+ ;;
+ i*86v)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-sysv
+ ;;
+ i*86sol2)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-solaris2
+ ;;
+ i386mach)
+ basic_machine=i386-mach
+ os=-mach
+ ;;
+ i386-vsta | vsta)
+ basic_machine=i386-unknown
+ os=-vsta
+ ;;
+ iris | iris4d)
+ basic_machine=mips-sgi
+ case $os in
+ -irix*)
+ ;;
+ *)
+ os=-irix4
+ ;;
+ esac
+ ;;
+ isi68 | isi)
+ basic_machine=m68k-isi
+ os=-sysv
+ ;;
+ m88k-omron*)
+ basic_machine=m88k-omron
+ ;;
+ magnum | m3230)
+ basic_machine=mips-mips
+ os=-sysv
+ ;;
+ merlin)
+ basic_machine=ns32k-utek
+ os=-sysv
+ ;;
+ mingw32)
+ basic_machine=i386-pc
+ os=-mingw32
+ ;;
+ miniframe)
+ basic_machine=m68000-convergent
+ ;;
+ *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
+ basic_machine=m68k-atari
+ os=-mint
+ ;;
+ mips3*-*)
+ basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
+ ;;
+ mips3*)
+ basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
+ ;;
+ monitor)
+ basic_machine=m68k-rom68k
+ os=-coff
+ ;;
+ morphos)
+ basic_machine=powerpc-unknown
+ os=-morphos
+ ;;
+ msdos)
+ basic_machine=i386-pc
+ os=-msdos
+ ;;
+ ms1-*)
+ basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
+ ;;
+ mvs)
+ basic_machine=i370-ibm
+ os=-mvs
+ ;;
+ ncr3000)
+ basic_machine=i486-ncr
+ os=-sysv4
+ ;;
+ netbsd386)
+ basic_machine=i386-unknown
+ os=-netbsd
+ ;;
+ netwinder)
+ basic_machine=armv4l-rebel
+ os=-linux
+ ;;
+ news | news700 | news800 | news900)
+ basic_machine=m68k-sony
+ os=-newsos
+ ;;
+ news1000)
+ basic_machine=m68030-sony
+ os=-newsos
+ ;;
+ news-3600 | risc-news)
+ basic_machine=mips-sony
+ os=-newsos
+ ;;
+ necv70)
+ basic_machine=v70-nec
+ os=-sysv
+ ;;
+ next | m*-next )
+ basic_machine=m68k-next
+ case $os in
+ -nextstep* )
+ ;;
+ -ns2*)
+ os=-nextstep2
+ ;;
+ *)
+ os=-nextstep3
+ ;;
+ esac
+ ;;
+ nh3000)
+ basic_machine=m68k-harris
+ os=-cxux
+ ;;
+ nh[45]000)
+ basic_machine=m88k-harris
+ os=-cxux
+ ;;
+ nindy960)
+ basic_machine=i960-intel
+ os=-nindy
+ ;;
+ mon960)
+ basic_machine=i960-intel
+ os=-mon960
+ ;;
+ nonstopux)
+ basic_machine=mips-compaq
+ os=-nonstopux
+ ;;
+ np1)
+ basic_machine=np1-gould
+ ;;
+ nsr-tandem)
+ basic_machine=nsr-tandem
+ ;;
+ op50n-* | op60c-*)
+ basic_machine=hppa1.1-oki
+ os=-proelf
+ ;;
+ openrisc | openrisc-*)
+ basic_machine=or32-unknown
+ ;;
+ os400)
+ basic_machine=powerpc-ibm
+ os=-os400
+ ;;
+ OSE68000 | ose68000)
+ basic_machine=m68000-ericsson
+ os=-ose
+ ;;
+ os68k)
+ basic_machine=m68k-none
+ os=-os68k
+ ;;
+ pa-hitachi)
+ basic_machine=hppa1.1-hitachi
+ os=-hiuxwe2
+ ;;
+ paragon)
+ basic_machine=i860-intel
+ os=-osf
+ ;;
+ pbd)
+ basic_machine=sparc-tti
+ ;;
+ pbb)
+ basic_machine=m68k-tti
+ ;;
+ pc532 | pc532-*)
+ basic_machine=ns32k-pc532
+ ;;
+ pentium | p5 | k5 | k6 | nexgen | viac3)
+ basic_machine=i586-pc
+ ;;
+ pentiumpro | p6 | 6x86 | athlon | athlon_*)
+ basic_machine=i686-pc
+ ;;
+ pentiumii | pentium2 | pentiumiii | pentium3)
+ basic_machine=i686-pc
+ ;;
+ pentium4)
+ basic_machine=i786-pc
+ ;;
+ pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
+ basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentiumpro-* | p6-* | 6x86-* | athlon-*)
+ basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
+ basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentium4-*)
+ basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pn)
+ basic_machine=pn-gould
+ ;;
+ power) basic_machine=power-ibm
+ ;;
+ ppc) basic_machine=powerpc-unknown
+ ;;
+ ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ppcle | powerpclittle | ppc-le | powerpc-little)
+ basic_machine=powerpcle-unknown
+ ;;
+ ppcle-* | powerpclittle-*)
+ basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ppc64) basic_machine=powerpc64-unknown
+ ;;
+ ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ppc64le | powerpc64little | ppc64-le | powerpc64-little)
+ basic_machine=powerpc64le-unknown
+ ;;
+ ppc64le-* | powerpc64little-*)
+ basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ps2)
+ basic_machine=i386-ibm
+ ;;
+ pw32)
+ basic_machine=i586-unknown
+ os=-pw32
+ ;;
+ rdos)
+ basic_machine=i386-pc
+ os=-rdos
+ ;;
+ rom68k)
+ basic_machine=m68k-rom68k
+ os=-coff
+ ;;
+ rm[46]00)
+ basic_machine=mips-siemens
+ ;;
+ rtpc | rtpc-*)
+ basic_machine=romp-ibm
+ ;;
+ s390 | s390-*)
+ basic_machine=s390-ibm
+ ;;
+ s390x | s390x-*)
+ basic_machine=s390x-ibm
+ ;;
+ sa29200)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ sb1)
+ basic_machine=mipsisa64sb1-unknown
+ ;;
+ sb1el)
+ basic_machine=mipsisa64sb1el-unknown
+ ;;
+ sei)
+ basic_machine=mips-sei
+ os=-seiux
+ ;;
+ sequent)
+ basic_machine=i386-sequent
+ ;;
+ sh)
+ basic_machine=sh-hitachi
+ os=-hms
+ ;;
+ sh64)
+ basic_machine=sh64-unknown
+ ;;
+ sparclite-wrs | simso-wrs)
+ basic_machine=sparclite-wrs
+ os=-vxworks
+ ;;
+ sps7)
+ basic_machine=m68k-bull
+ os=-sysv2
+ ;;
+ spur)
+ basic_machine=spur-unknown
+ ;;
+ st2000)
+ basic_machine=m68k-tandem
+ ;;
+ stratus)
+ basic_machine=i860-stratus
+ os=-sysv4
+ ;;
+ sun2)
+ basic_machine=m68000-sun
+ ;;
+ sun2os3)
+ basic_machine=m68000-sun
+ os=-sunos3
+ ;;
+ sun2os4)
+ basic_machine=m68000-sun
+ os=-sunos4
+ ;;
+ sun3os3)
+ basic_machine=m68k-sun
+ os=-sunos3
+ ;;
+ sun3os4)
+ basic_machine=m68k-sun
+ os=-sunos4
+ ;;
+ sun4os3)
+ basic_machine=sparc-sun
+ os=-sunos3
+ ;;
+ sun4os4)
+ basic_machine=sparc-sun
+ os=-sunos4
+ ;;
+ sun4sol2)
+ basic_machine=sparc-sun
+ os=-solaris2
+ ;;
+ sun3 | sun3-*)
+ basic_machine=m68k-sun
+ ;;
+ sun4)
+ basic_machine=sparc-sun
+ ;;
+ sun386 | sun386i | roadrunner)
+ basic_machine=i386-sun
+ ;;
+ sv1)
+ basic_machine=sv1-cray
+ os=-unicos
+ ;;
+ symmetry)
+ basic_machine=i386-sequent
+ os=-dynix
+ ;;
+ t3e)
+ basic_machine=alphaev5-cray
+ os=-unicos
+ ;;
+ t90)
+ basic_machine=t90-cray
+ os=-unicos
+ ;;
+ tic54x | c54x*)
+ basic_machine=tic54x-unknown
+ os=-coff
+ ;;
+ tic55x | c55x*)
+ basic_machine=tic55x-unknown
+ os=-coff
+ ;;
+ tic6x | c6x*)
+ basic_machine=tic6x-unknown
+ os=-coff
+ ;;
+ tx39)
+ basic_machine=mipstx39-unknown
+ ;;
+ tx39el)
+ basic_machine=mipstx39el-unknown
+ ;;
+ toad1)
+ basic_machine=pdp10-xkl
+ os=-tops20
+ ;;
+ tower | tower-32)
+ basic_machine=m68k-ncr
+ ;;
+ tpf)
+ basic_machine=s390x-ibm
+ os=-tpf
+ ;;
+ udi29k)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ ultra3)
+ basic_machine=a29k-nyu
+ os=-sym1
+ ;;
+ v810 | necv810)
+ basic_machine=v810-nec
+ os=-none
+ ;;
+ vaxv)
+ basic_machine=vax-dec
+ os=-sysv
+ ;;
+ vms)
+ basic_machine=vax-dec
+ os=-vms
+ ;;
+ vpp*|vx|vx-*)
+ basic_machine=f301-fujitsu
+ ;;
+ vxworks960)
+ basic_machine=i960-wrs
+ os=-vxworks
+ ;;
+ vxworks68)
+ basic_machine=m68k-wrs
+ os=-vxworks
+ ;;
+ vxworks29k)
+ basic_machine=a29k-wrs
+ os=-vxworks
+ ;;
+ w65*)
+ basic_machine=w65-wdc
+ os=-none
+ ;;
+ w89k-*)
+ basic_machine=hppa1.1-winbond
+ os=-proelf
+ ;;
+ xbox)
+ basic_machine=i686-pc
+ os=-mingw32
+ ;;
+ xps | xps100)
+ basic_machine=xps100-honeywell
+ ;;
+ ymp)
+ basic_machine=ymp-cray
+ os=-unicos
+ ;;
+ z8k-*-coff)
+ basic_machine=z8k-unknown
+ os=-sim
+ ;;
+ none)
+ basic_machine=none-none
+ os=-none
+ ;;
+
+# Here we handle the default manufacturer of certain CPU types. It is in
+# some cases the only manufacturer, in others, it is the most popular.
+ w89k)
+ basic_machine=hppa1.1-winbond
+ ;;
+ op50n)
+ basic_machine=hppa1.1-oki
+ ;;
+ op60c)
+ basic_machine=hppa1.1-oki
+ ;;
+ romp)
+ basic_machine=romp-ibm
+ ;;
+ mmix)
+ basic_machine=mmix-knuth
+ ;;
+ rs6000)
+ basic_machine=rs6000-ibm
+ ;;
+ vax)
+ basic_machine=vax-dec
+ ;;
+ pdp10)
+ # there are many clones, so DEC is not a safe bet
+ basic_machine=pdp10-unknown
+ ;;
+ pdp11)
+ basic_machine=pdp11-dec
+ ;;
+ we32k)
+ basic_machine=we32k-att
+ ;;
+ sh[1234] | sh[24]a | sh[34]eb | sh[1234]le | sh[23]ele)
+ basic_machine=sh-unknown
+ ;;
+ sparc | sparcv8 | sparcv9 | sparcv9b)
+ basic_machine=sparc-sun
+ ;;
+ cydra)
+ basic_machine=cydra-cydrome
+ ;;
+ orion)
+ basic_machine=orion-highlevel
+ ;;
+ orion105)
+ basic_machine=clipper-highlevel
+ ;;
+ mac | mpw | mac-mpw)
+ basic_machine=m68k-apple
+ ;;
+ pmac | pmac-mpw)
+ basic_machine=powerpc-apple
+ ;;
+ *-unknown)
+ # Make sure to match an already-canonicalized machine name.
+ ;;
+ *)
+ echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+ exit 1
+ ;;
+esac
+
+# Here we canonicalize certain aliases for manufacturers.
+case $basic_machine in
+ *-digital*)
+ basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
+ ;;
+ *-commodore*)
+ basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
+ ;;
+ *)
+ ;;
+esac
+
+# Decode manufacturer-specific aliases for certain operating systems.
+
+if [ x"$os" != x"" ]
+then
+case $os in
+ # First match some system type aliases
+ # that might get confused with valid system types.
+ # -solaris* is a basic system type, with this one exception.
+ -solaris1 | -solaris1.*)
+ os=`echo $os | sed -e 's|solaris1|sunos4|'`
+ ;;
+ -solaris)
+ os=-solaris2
+ ;;
+ -svr4*)
+ os=-sysv4
+ ;;
+ -unixware*)
+ os=-sysv4.2uw
+ ;;
+ -gnu/linux*)
+ os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
+ ;;
+ # First accept the basic system types.
+ # The portable systems comes first.
+ # Each alternative MUST END IN A *, to match a version number.
+ # -sysv* is not here because it comes later, after sysvr4.
+ -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
+ | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\
+ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \
+ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
+ | -aos* \
+ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
+ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
+ | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* | -openbsd* \
+ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
+ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
+ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
+ | -chorusos* | -chorusrdb* \
+ | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
+ | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \
+ | -uxpv* | -beos* | -mpeix* | -udk* \
+ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
+ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
+ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
+ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
+ | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
+ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
+ | -skyos* | -haiku* | -rdos*)
+ # Remember, each alternative MUST END IN *, to match a version number.
+ ;;
+ -qnx*)
+ case $basic_machine in
+ x86-* | i*86-*)
+ ;;
+ *)
+ os=-nto$os
+ ;;
+ esac
+ ;;
+ -nto-qnx*)
+ ;;
+ -nto*)
+ os=`echo $os | sed -e 's|nto|nto-qnx|'`
+ ;;
+ -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
+ | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
+ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
+ ;;
+ -mac*)
+ os=`echo $os | sed -e 's|mac|macos|'`
+ ;;
+ -linux-dietlibc)
+ os=-linux-dietlibc
+ ;;
+ -linux*)
+ os=`echo $os | sed -e 's|linux|linux-gnu|'`
+ ;;
+ -sunos5*)
+ os=`echo $os | sed -e 's|sunos5|solaris2|'`
+ ;;
+ -sunos6*)
+ os=`echo $os | sed -e 's|sunos6|solaris3|'`
+ ;;
+ -opened*)
+ os=-openedition
+ ;;
+ -os400*)
+ os=-os400
+ ;;
+ -wince*)
+ os=-wince
+ ;;
+ -osfrose*)
+ os=-osfrose
+ ;;
+ -osf*)
+ os=-osf
+ ;;
+ -utek*)
+ os=-bsd
+ ;;
+ -dynix*)
+ os=-bsd
+ ;;
+ -acis*)
+ os=-aos
+ ;;
+ -atheos*)
+ os=-atheos
+ ;;
+ -syllable*)
+ os=-syllable
+ ;;
+ -386bsd)
+ os=-bsd
+ ;;
+ -ctix* | -uts*)
+ os=-sysv
+ ;;
+ -nova*)
+ os=-rtmk-nova
+ ;;
+ -ns2 )
+ os=-nextstep2
+ ;;
+ -nsk*)
+ os=-nsk
+ ;;
+ # Preserve the version number of sinix5.
+ -sinix5.*)
+ os=`echo $os | sed -e 's|sinix|sysv|'`
+ ;;
+ -sinix*)
+ os=-sysv4
+ ;;
+ -tpf*)
+ os=-tpf
+ ;;
+ -triton*)
+ os=-sysv3
+ ;;
+ -oss*)
+ os=-sysv3
+ ;;
+ -svr4)
+ os=-sysv4
+ ;;
+ -svr3)
+ os=-sysv3
+ ;;
+ -sysvr4)
+ os=-sysv4
+ ;;
+ # This must come after -sysvr4.
+ -sysv*)
+ ;;
+ -ose*)
+ os=-ose
+ ;;
+ -es1800*)
+ os=-ose
+ ;;
+ -xenix)
+ os=-xenix
+ ;;
+ -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+ os=-mint
+ ;;
+ -aros*)
+ os=-aros
+ ;;
+ -kaos*)
+ os=-kaos
+ ;;
+ -zvmoe)
+ os=-zvmoe
+ ;;
+ -none)
+ ;;
+ *)
+ # Get rid of the `-' at the beginning of $os.
+ os=`echo $os | sed 's/[^-]*-//'`
+ echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
+ exit 1
+ ;;
+esac
+else
+
+# Here we handle the default operating systems that come with various machines.
+# The value should be what the vendor currently ships out the door with their
+# machine or put another way, the most popular os provided with the machine.
+
+# Note that if you're going to try to match "-MANUFACTURER" here (say,
+# "-sun"), then you have to tell the case statement up towards the top
+# that MANUFACTURER isn't an operating system. Otherwise, code above
+# will signal an error saying that MANUFACTURER isn't an operating
+# system, and we'll never get to this point.
+
+case $basic_machine in
+ *-acorn)
+ os=-riscix1.2
+ ;;
+ arm*-rebel)
+ os=-linux
+ ;;
+ arm*-semi)
+ os=-aout
+ ;;
+ c4x-* | tic4x-*)
+ os=-coff
+ ;;
+ # This must come before the *-dec entry.
+ pdp10-*)
+ os=-tops20
+ ;;
+ pdp11-*)
+ os=-none
+ ;;
+ *-dec | vax-*)
+ os=-ultrix4.2
+ ;;
+ m68*-apollo)
+ os=-domain
+ ;;
+ i386-sun)
+ os=-sunos4.0.2
+ ;;
+ m68000-sun)
+ os=-sunos3
+ # This also exists in the configure program, but was not the
+ # default.
+ # os=-sunos4
+ ;;
+ m68*-cisco)
+ os=-aout
+ ;;
+ mips*-cisco)
+ os=-elf
+ ;;
+ mips*-*)
+ os=-elf
+ ;;
+ or32-*)
+ os=-coff
+ ;;
+ *-tti) # must be before sparc entry or we get the wrong os.
+ os=-sysv3
+ ;;
+ sparc-* | *-sun)
+ os=-sunos4.1.1
+ ;;
+ *-be)
+ os=-beos
+ ;;
+ *-haiku)
+ os=-haiku
+ ;;
+ *-ibm)
+ os=-aix
+ ;;
+ *-knuth)
+ os=-mmixware
+ ;;
+ *-wec)
+ os=-proelf
+ ;;
+ *-winbond)
+ os=-proelf
+ ;;
+ *-oki)
+ os=-proelf
+ ;;
+ *-hp)
+ os=-hpux
+ ;;
+ *-hitachi)
+ os=-hiux
+ ;;
+ i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
+ os=-sysv
+ ;;
+ *-cbm)
+ os=-amigaos
+ ;;
+ *-dg)
+ os=-dgux
+ ;;
+ *-dolphin)
+ os=-sysv3
+ ;;
+ m68k-ccur)
+ os=-rtu
+ ;;
+ m88k-omron*)
+ os=-luna
+ ;;
+ *-next )
+ os=-nextstep
+ ;;
+ *-sequent)
+ os=-ptx
+ ;;
+ *-crds)
+ os=-unos
+ ;;
+ *-ns)
+ os=-genix
+ ;;
+ i370-*)
+ os=-mvs
+ ;;
+ *-next)
+ os=-nextstep3
+ ;;
+ *-gould)
+ os=-sysv
+ ;;
+ *-highlevel)
+ os=-bsd
+ ;;
+ *-encore)
+ os=-bsd
+ ;;
+ *-sgi)
+ os=-irix
+ ;;
+ *-siemens)
+ os=-sysv4
+ ;;
+ *-masscomp)
+ os=-rtu
+ ;;
+ f30[01]-fujitsu | f700-fujitsu)
+ os=-uxpv
+ ;;
+ *-rom68k)
+ os=-coff
+ ;;
+ *-*bug)
+ os=-coff
+ ;;
+ *-apple)
+ os=-macos
+ ;;
+ *-atari*)
+ os=-mint
+ ;;
+ *)
+ os=-none
+ ;;
+esac
+fi
+
+# Here we handle the case where we know the os, and the CPU type, but not the
+# manufacturer. We pick the logical manufacturer.
+vendor=unknown
+case $basic_machine in
+ *-unknown)
+ case $os in
+ -riscix*)
+ vendor=acorn
+ ;;
+ -sunos*)
+ vendor=sun
+ ;;
+ -aix*)
+ vendor=ibm
+ ;;
+ -beos*)
+ vendor=be
+ ;;
+ -hpux*)
+ vendor=hp
+ ;;
+ -mpeix*)
+ vendor=hp
+ ;;
+ -hiux*)
+ vendor=hitachi
+ ;;
+ -unos*)
+ vendor=crds
+ ;;
+ -dgux*)
+ vendor=dg
+ ;;
+ -luna*)
+ vendor=omron
+ ;;
+ -genix*)
+ vendor=ns
+ ;;
+ -mvs* | -opened*)
+ vendor=ibm
+ ;;
+ -os400*)
+ vendor=ibm
+ ;;
+ -ptx*)
+ vendor=sequent
+ ;;
+ -tpf*)
+ vendor=ibm
+ ;;
+ -vxsim* | -vxworks* | -windiss*)
+ vendor=wrs
+ ;;
+ -aux*)
+ vendor=apple
+ ;;
+ -hms*)
+ vendor=hitachi
+ ;;
+ -mpw* | -macos*)
+ vendor=apple
+ ;;
+ -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+ vendor=atari
+ ;;
+ -vos*)
+ vendor=stratus
+ ;;
+ esac
+ basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
+ ;;
+esac
+
+echo $basic_machine$os
+exit
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/jpeg-6c/configure b/jpeg-6c/configure
new file mode 100755
index 0000000..35c9db5
--- /dev/null
+++ b/jpeg-6c/configure
@@ -0,0 +1,2011 @@
+#! /bin/sh
+
+# Guess values for system-dependent variables and create Makefiles.
+# Generated automatically using autoconf version 2.12
+# Copyright (C) 1992, 93, 94, 95, 96 Free Software Foundation, Inc.
+#
+# This configure script is free software; the Free Software Foundation
+# gives unlimited permission to copy, distribute and modify it.
+
+# Defaults:
+ac_help=
+ac_default_prefix=/usr/local
+# Any additions from configure.in:
+ac_help="$ac_help
+ --enable-shared build shared library using GNU libtool"
+ac_help="$ac_help
+ --enable-static build static library using GNU libtool"
+ac_help="$ac_help
+ --enable-maxmem[=N] enable use of temp files, set max mem usage to N MB"
+ac_help="$ac_help
+"
+
+# Initialize some variables set by options.
+# The variables have the same names as the options, with
+# dashes changed to underlines.
+build=NONE
+cache_file=./config.cache
+exec_prefix=NONE
+host=NONE
+no_create=
+nonopt=NONE
+no_recursion=
+prefix=NONE
+program_prefix=NONE
+program_suffix=NONE
+program_transform_name=s,x,x,
+silent=
+site=
+srcdir=
+target=NONE
+verbose=
+x_includes=NONE
+x_libraries=NONE
+bindir='${exec_prefix}/bin'
+sbindir='${exec_prefix}/sbin'
+libexecdir='${exec_prefix}/libexec'
+datadir='${prefix}/share'
+sysconfdir='${prefix}/etc'
+sharedstatedir='${prefix}/com'
+localstatedir='${prefix}/var'
+libdir='${exec_prefix}/lib'
+includedir='${prefix}/include'
+oldincludedir='/usr/include'
+infodir='${prefix}/info'
+mandir='${prefix}/man'
+
+# Initialize some other variables.
+subdirs=
+MFLAGS= MAKEFLAGS=
+# Maximum number of lines to put in a shell here document.
+ac_max_here_lines=12
+
+ac_prev=
+for ac_option
+do
+
+ # If the previous option needs an argument, assign it.
+ if test -n "$ac_prev"; then
+ eval "$ac_prev=\$ac_option"
+ ac_prev=
+ continue
+ fi
+
+ case "$ac_option" in
+ -*=*) ac_optarg=`echo "$ac_option" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
+ *) ac_optarg= ;;
+ esac
+
+ # Accept the important Cygnus configure options, so we can diagnose typos.
+
+ case "$ac_option" in
+
+ -bindir | --bindir | --bindi | --bind | --bin | --bi)
+ ac_prev=bindir ;;
+ -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
+ bindir="$ac_optarg" ;;
+
+ -build | --build | --buil | --bui | --bu)
+ ac_prev=build ;;
+ -build=* | --build=* | --buil=* | --bui=* | --bu=*)
+ build="$ac_optarg" ;;
+
+ -cache-file | --cache-file | --cache-fil | --cache-fi \
+ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
+ ac_prev=cache_file ;;
+ -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
+ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
+ cache_file="$ac_optarg" ;;
+
+ -datadir | --datadir | --datadi | --datad | --data | --dat | --da)
+ ac_prev=datadir ;;
+ -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
+ | --da=*)
+ datadir="$ac_optarg" ;;
+
+ -disable-* | --disable-*)
+ ac_feature=`echo $ac_option|sed -e 's/-*disable-//'`
+ # Reject names that are not valid shell variable names.
+ if test -n "`echo $ac_feature| sed 's/[-a-zA-Z0-9_]//g'`"; then
+ { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; }
+ fi
+ ac_feature=`echo $ac_feature| sed 's/-/_/g'`
+ eval "enable_${ac_feature}=no" ;;
+
+ -enable-* | --enable-*)
+ ac_feature=`echo $ac_option|sed -e 's/-*enable-//' -e 's/=.*//'`
+ # Reject names that are not valid shell variable names.
+ if test -n "`echo $ac_feature| sed 's/[-_a-zA-Z0-9]//g'`"; then
+ { echo "configure: error: $ac_feature: invalid feature name" 1>&2; exit 1; }
+ fi
+ ac_feature=`echo $ac_feature| sed 's/-/_/g'`
+ case "$ac_option" in
+ *=*) ;;
+ *) ac_optarg=yes ;;
+ esac
+ eval "enable_${ac_feature}='$ac_optarg'" ;;
+
+ -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
+ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
+ | --exec | --exe | --ex)
+ ac_prev=exec_prefix ;;
+ -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
+ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
+ | --exec=* | --exe=* | --ex=*)
+ exec_prefix="$ac_optarg" ;;
+
+ -gas | --gas | --ga | --g)
+ # Obsolete; use --with-gas.
+ with_gas=yes ;;
+
+ -help | --help | --hel | --he)
+ # Omit some internal or obsolete options to make the list less imposing.
+ # This message is too long to be a string in the A/UX 3.1 sh.
+ cat << EOF
+Usage: configure [options] [host]
+Options: [defaults in brackets after descriptions]
+Configuration:
+ --cache-file=FILE cache test results in FILE
+ --help print this message
+ --no-create do not create output files
+ --quiet, --silent do not print \`checking...' messages
+ --version print the version of autoconf that created configure
+Directory and file names:
+ --prefix=PREFIX install architecture-independent files in PREFIX
+ [$ac_default_prefix]
+ --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX
+ [same as prefix]
+ --bindir=DIR user executables in DIR [EPREFIX/bin]
+ --sbindir=DIR system admin executables in DIR [EPREFIX/sbin]
+ --libexecdir=DIR program executables in DIR [EPREFIX/libexec]
+ --datadir=DIR read-only architecture-independent data in DIR
+ [PREFIX/share]
+ --sysconfdir=DIR read-only single-machine data in DIR [PREFIX/etc]
+ --sharedstatedir=DIR modifiable architecture-independent data in DIR
+ [PREFIX/com]
+ --localstatedir=DIR modifiable single-machine data in DIR [PREFIX/var]
+ --libdir=DIR object code libraries in DIR [EPREFIX/lib]
+ --includedir=DIR C header files in DIR [PREFIX/include]
+ --oldincludedir=DIR C header files for non-gcc in DIR [/usr/include]
+ --infodir=DIR info documentation in DIR [PREFIX/info]
+ --mandir=DIR man documentation in DIR [PREFIX/man]
+ --srcdir=DIR find the sources in DIR [configure dir or ..]
+ --program-prefix=PREFIX prepend PREFIX to installed program names
+ --program-suffix=SUFFIX append SUFFIX to installed program names
+ --program-transform-name=PROGRAM
+ run sed PROGRAM on installed program names
+EOF
+ cat << EOF
+Host type:
+ --build=BUILD configure for building on BUILD [BUILD=HOST]
+ --host=HOST configure for HOST [guessed]
+ --target=TARGET configure for TARGET [TARGET=HOST]
+Features and packages:
+ --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no)
+ --enable-FEATURE[=ARG] include FEATURE [ARG=yes]
+ --with-PACKAGE[=ARG] use PACKAGE [ARG=yes]
+ --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no)
+ --x-includes=DIR X include files are in DIR
+ --x-libraries=DIR X library files are in DIR
+EOF
+ if test -n "$ac_help"; then
+ echo "--enable and --with options recognized:$ac_help"
+ fi
+ exit 0 ;;
+
+ -host | --host | --hos | --ho)
+ ac_prev=host ;;
+ -host=* | --host=* | --hos=* | --ho=*)
+ host="$ac_optarg" ;;
+
+ -includedir | --includedir | --includedi | --included | --include \
+ | --includ | --inclu | --incl | --inc)
+ ac_prev=includedir ;;
+ -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
+ | --includ=* | --inclu=* | --incl=* | --inc=*)
+ includedir="$ac_optarg" ;;
+
+ -infodir | --infodir | --infodi | --infod | --info | --inf)
+ ac_prev=infodir ;;
+ -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
+ infodir="$ac_optarg" ;;
+
+ -libdir | --libdir | --libdi | --libd)
+ ac_prev=libdir ;;
+ -libdir=* | --libdir=* | --libdi=* | --libd=*)
+ libdir="$ac_optarg" ;;
+
+ -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
+ | --libexe | --libex | --libe)
+ ac_prev=libexecdir ;;
+ -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
+ | --libexe=* | --libex=* | --libe=*)
+ libexecdir="$ac_optarg" ;;
+
+ -localstatedir | --localstatedir | --localstatedi | --localstated \
+ | --localstate | --localstat | --localsta | --localst \
+ | --locals | --local | --loca | --loc | --lo)
+ ac_prev=localstatedir ;;
+ -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
+ | --localstate=* | --localstat=* | --localsta=* | --localst=* \
+ | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
+ localstatedir="$ac_optarg" ;;
+
+ -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
+ ac_prev=mandir ;;
+ -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
+ mandir="$ac_optarg" ;;
+
+ -nfp | --nfp | --nf)
+ # Obsolete; use --without-fp.
+ with_fp=no ;;
+
+ -no-create | --no-create | --no-creat | --no-crea | --no-cre \
+ | --no-cr | --no-c)
+ no_create=yes ;;
+
+ -no-recursion | --no-recursion | --no-recursio | --no-recursi \
+ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
+ no_recursion=yes ;;
+
+ -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
+ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
+ | --oldin | --oldi | --old | --ol | --o)
+ ac_prev=oldincludedir ;;
+ -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
+ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
+ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
+ oldincludedir="$ac_optarg" ;;
+
+ -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+ ac_prev=prefix ;;
+ -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
+ prefix="$ac_optarg" ;;
+
+ -program-prefix | --program-prefix | --program-prefi | --program-pref \
+ | --program-pre | --program-pr | --program-p)
+ ac_prev=program_prefix ;;
+ -program-prefix=* | --program-prefix=* | --program-prefi=* \
+ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
+ program_prefix="$ac_optarg" ;;
+
+ -program-suffix | --program-suffix | --program-suffi | --program-suff \
+ | --program-suf | --program-su | --program-s)
+ ac_prev=program_suffix ;;
+ -program-suffix=* | --program-suffix=* | --program-suffi=* \
+ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
+ program_suffix="$ac_optarg" ;;
+
+ -program-transform-name | --program-transform-name \
+ | --program-transform-nam | --program-transform-na \
+ | --program-transform-n | --program-transform- \
+ | --program-transform | --program-transfor \
+ | --program-transfo | --program-transf \
+ | --program-trans | --program-tran \
+ | --progr-tra | --program-tr | --program-t)
+ ac_prev=program_transform_name ;;
+ -program-transform-name=* | --program-transform-name=* \
+ | --program-transform-nam=* | --program-transform-na=* \
+ | --program-transform-n=* | --program-transform-=* \
+ | --program-transform=* | --program-transfor=* \
+ | --program-transfo=* | --program-transf=* \
+ | --program-trans=* | --program-tran=* \
+ | --progr-tra=* | --program-tr=* | --program-t=*)
+ program_transform_name="$ac_optarg" ;;
+
+ -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+ | -silent | --silent | --silen | --sile | --sil)
+ silent=yes ;;
+
+ -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
+ ac_prev=sbindir ;;
+ -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
+ | --sbi=* | --sb=*)
+ sbindir="$ac_optarg" ;;
+
+ -sharedstatedir | --sharedstatedir | --sharedstatedi \
+ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
+ | --sharedst | --shareds | --shared | --share | --shar \
+ | --sha | --sh)
+ ac_prev=sharedstatedir ;;
+ -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
+ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
+ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
+ | --sha=* | --sh=*)
+ sharedstatedir="$ac_optarg" ;;
+
+ -site | --site | --sit)
+ ac_prev=site ;;
+ -site=* | --site=* | --sit=*)
+ site="$ac_optarg" ;;
+
+ -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
+ ac_prev=srcdir ;;
+ -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
+ srcdir="$ac_optarg" ;;
+
+ -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
+ | --syscon | --sysco | --sysc | --sys | --sy)
+ ac_prev=sysconfdir ;;
+ -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
+ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
+ sysconfdir="$ac_optarg" ;;
+
+ -target | --target | --targe | --targ | --tar | --ta | --t)
+ ac_prev=target ;;
+ -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
+ target="$ac_optarg" ;;
+
+ -v | -verbose | --verbose | --verbos | --verbo | --verb)
+ verbose=yes ;;
+
+ -version | --version | --versio | --versi | --vers)
+ echo "configure generated by autoconf version 2.12"
+ exit 0 ;;
+
+ -with-* | --with-*)
+ ac_package=`echo $ac_option|sed -e 's/-*with-//' -e 's/=.*//'`
+ # Reject names that are not valid shell variable names.
+ if test -n "`echo $ac_package| sed 's/[-_a-zA-Z0-9]//g'`"; then
+ { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; }
+ fi
+ ac_package=`echo $ac_package| sed 's/-/_/g'`
+ case "$ac_option" in
+ *=*) ;;
+ *) ac_optarg=yes ;;
+ esac
+ eval "with_${ac_package}='$ac_optarg'" ;;
+
+ -without-* | --without-*)
+ ac_package=`echo $ac_option|sed -e 's/-*without-//'`
+ # Reject names that are not valid shell variable names.
+ if test -n "`echo $ac_package| sed 's/[-a-zA-Z0-9_]//g'`"; then
+ { echo "configure: error: $ac_package: invalid package name" 1>&2; exit 1; }
+ fi
+ ac_package=`echo $ac_package| sed 's/-/_/g'`
+ eval "with_${ac_package}=no" ;;
+
+ --x)
+ # Obsolete; use --with-x.
+ with_x=yes ;;
+
+ -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
+ | --x-incl | --x-inc | --x-in | --x-i)
+ ac_prev=x_includes ;;
+ -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
+ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
+ x_includes="$ac_optarg" ;;
+
+ -x-libraries | --x-libraries | --x-librarie | --x-librari \
+ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
+ ac_prev=x_libraries ;;
+ -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
+ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
+ x_libraries="$ac_optarg" ;;
+
+ -*) { echo "configure: error: $ac_option: invalid option; use --help to show usage" 1>&2; exit 1; }
+ ;;
+
+ *=*)
+ varname=`echo "$ac_option"|sed -e 's/=.*//'`
+ # Reject names that aren't valid shell variable names.
+ if test -n "`echo $varname| sed 's/[a-zA-Z0-9_]//g'`"; then
+ { echo "configure: error: $varname: invalid shell variable name" 1>&2; exit 1; }
+ fi
+ val="`echo "$ac_option"|sed 's/[^=]*=//'`"
+ test -n "$verbose" && echo " setting shell variable $varname to $val"
+ eval "$varname='$val'"
+ eval "export $varname" ;;
+
+ *)
+ if test -n "`echo $ac_option| sed 's/[-a-z0-9.]//g'`"; then
+ echo "configure: warning: $ac_option: invalid host type" 1>&2
+ fi
+ if test "x$nonopt" != xNONE; then
+ { echo "configure: error: can only configure for one host and one target at a time" 1>&2; exit 1; }
+ fi
+ nonopt="$ac_option"
+ ;;
+
+ esac
+done
+
+if test -n "$ac_prev"; then
+ { echo "configure: error: missing argument to --`echo $ac_prev | sed 's/_/-/g'`" 1>&2; exit 1; }
+fi
+
+trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15
+
+# File descriptor usage:
+# 0 standard input
+# 1 file creation
+# 2 errors and warnings
+# 3 some systems may open it to /dev/tty
+# 4 used on the Kubota Titan
+# 6 checking for... messages and results
+# 5 compiler messages saved in config.log
+if test "$silent" = yes; then
+ exec 6>/dev/null
+else
+ exec 6>&1
+fi
+exec 5>./config.log
+
+echo "\
+This file contains any messages produced by compilers while
+running configure, to aid debugging if configure makes a mistake.
+" 1>&5
+
+# Strip out --no-create and --no-recursion so they do not pile up.
+# Also quote any args containing shell metacharacters.
+ac_configure_args=
+for ac_arg
+do
+ case "$ac_arg" in
+ -no-create | --no-create | --no-creat | --no-crea | --no-cre \
+ | --no-cr | --no-c) ;;
+ -no-recursion | --no-recursion | --no-recursio | --no-recursi \
+ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) ;;
+ *" "*|*" "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?]*)
+ ac_configure_args="$ac_configure_args '$ac_arg'" ;;
+ *) ac_configure_args="$ac_configure_args $ac_arg" ;;
+ esac
+done
+
+# NLS nuisances.
+# Only set these to C if already set. These must not be set unconditionally
+# because not all systems understand e.g. LANG=C (notably SCO).
+# Fixing LC_MESSAGES prevents Solaris sh from translating var values in `set'!
+# Non-C LC_CTYPE values break the ctype check.
+if test "${LANG+set}" = set; then LANG=C; export LANG; fi
+if test "${LC_ALL+set}" = set; then LC_ALL=C; export LC_ALL; fi
+if test "${LC_MESSAGES+set}" = set; then LC_MESSAGES=C; export LC_MESSAGES; fi
+if test "${LC_CTYPE+set}" = set; then LC_CTYPE=C; export LC_CTYPE; fi
+
+# confdefs.h avoids OS command line length limits that DEFS can exceed.
+rm -rf conftest* confdefs.h
+# AIX cpp loses on an empty file, so make sure it contains at least a newline.
+echo > confdefs.h
+
+# A filename unique to this package, relative to the directory that
+# configure is in, which we can look for to find out if srcdir is correct.
+ac_unique_file=jcmaster.c
+
+# Find the source files, if location was not specified.
+if test -z "$srcdir"; then
+ ac_srcdir_defaulted=yes
+ # Try the directory containing this script, then its parent.
+ ac_prog=$0
+ ac_confdir=`echo $ac_prog|sed 's%/[^/][^/]*$%%'`
+ test "x$ac_confdir" = "x$ac_prog" && ac_confdir=.
+ srcdir=$ac_confdir
+ if test ! -r $srcdir/$ac_unique_file; then
+ srcdir=..
+ fi
+else
+ ac_srcdir_defaulted=no
+fi
+if test ! -r $srcdir/$ac_unique_file; then
+ if test "$ac_srcdir_defaulted" = yes; then
+ { echo "configure: error: can not find sources in $ac_confdir or .." 1>&2; exit 1; }
+ else
+ { echo "configure: error: can not find sources in $srcdir" 1>&2; exit 1; }
+ fi
+fi
+srcdir=`echo "${srcdir}" | sed 's%\([^/]\)/*$%\1%'`
+
+# Prefer explicitly selected file to automatically selected ones.
+if test -z "$CONFIG_SITE"; then
+ if test "x$prefix" != xNONE; then
+ CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site"
+ else
+ CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site"
+ fi
+fi
+for ac_site_file in $CONFIG_SITE; do
+ if test -r "$ac_site_file"; then
+ echo "loading site script $ac_site_file"
+ . "$ac_site_file"
+ fi
+done
+
+
+ac_ext=c
+# CFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
+ac_link='${CC-cc} -o conftest $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
+cross_compiling=$ac_cv_prog_cc_cross
+
+if (echo "testing\c"; echo 1,2,3) | grep c >/dev/null; then
+ # Stardent Vistra SVR4 grep lacks -e, says ghazi at caip.rutgers.edu.
+ if (echo -n testing; echo 1,2,3) | sed s/-n/xn/ | grep xn >/dev/null; then
+ ac_n= ac_c='
+' ac_t=' '
+ else
+ ac_n=-n ac_c= ac_t=
+ fi
+else
+ ac_n= ac_c='\c' ac_t=
+fi
+
+
+
+# Extract the first word of "gcc", so it can be a program name with args.
+set dummy gcc; ac_word=$2
+echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
+echo "configure:538: checking for $ac_word" >&5
+if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
+ echo $ac_n "(cached) $ac_c" 1>&6
+else
+ if test -n "$CC"; then
+ ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+ IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS="${IFS}:"
+ for ac_dir in $PATH; do
+ test -z "$ac_dir" && ac_dir=.
+ if test -f $ac_dir/$ac_word; then
+ ac_cv_prog_CC="gcc"
+ break
+ fi
+ done
+ IFS="$ac_save_ifs"
+fi
+fi
+CC="$ac_cv_prog_CC"
+if test -n "$CC"; then
+ echo "$ac_t""$CC" 1>&6
+else
+ echo "$ac_t""no" 1>&6
+fi
+
+if test -z "$CC"; then
+ # Extract the first word of "cc", so it can be a program name with args.
+set dummy cc; ac_word=$2
+echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
+echo "configure:567: checking for $ac_word" >&5
+if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
+ echo $ac_n "(cached) $ac_c" 1>&6
+else
+ if test -n "$CC"; then
+ ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+ IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS="${IFS}:"
+ ac_prog_rejected=no
+ for ac_dir in $PATH; do
+ test -z "$ac_dir" && ac_dir=.
+ if test -f $ac_dir/$ac_word; then
+ if test "$ac_dir/$ac_word" = "/usr/ucb/cc"; then
+ ac_prog_rejected=yes
+ continue
+ fi
+ ac_cv_prog_CC="cc"
+ break
+ fi
+ done
+ IFS="$ac_save_ifs"
+if test $ac_prog_rejected = yes; then
+ # We found a bogon in the path, so make sure we never use it.
+ set dummy $ac_cv_prog_CC
+ shift
+ if test $# -gt 0; then
+ # We chose a different compiler from the bogus one.
+ # However, it has the same basename, so the bogon will be chosen
+ # first if we set CC to just the basename; use the full file name.
+ shift
+ set dummy "$ac_dir/$ac_word" "$@"
+ shift
+ ac_cv_prog_CC="$@"
+ fi
+fi
+fi
+fi
+CC="$ac_cv_prog_CC"
+if test -n "$CC"; then
+ echo "$ac_t""$CC" 1>&6
+else
+ echo "$ac_t""no" 1>&6
+fi
+
+ test -z "$CC" && { echo "configure: error: no acceptable cc found in \$PATH" 1>&2; exit 1; }
+fi
+
+echo $ac_n "checking whether the C compiler ($CC $CFLAGS $LDFLAGS) works""... $ac_c" 1>&6
+echo "configure:615: checking whether the C compiler ($CC $CFLAGS $LDFLAGS) works" >&5
+
+ac_ext=c
+# CFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
+ac_link='${CC-cc} -o conftest $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
+cross_compiling=$ac_cv_prog_cc_cross
+
+cat > conftest.$ac_ext <<EOF
+#line 625 "configure"
+#include "confdefs.h"
+main(){return(0);}
+EOF
+if { (eval echo configure:629: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest; then
+ ac_cv_prog_cc_works=yes
+ # If we can't run a trivial program, we are probably using a cross compiler.
+ if (./conftest; exit) 2>/dev/null; then
+ ac_cv_prog_cc_cross=no
+ else
+ ac_cv_prog_cc_cross=yes
+ fi
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ ac_cv_prog_cc_works=no
+fi
+rm -fr conftest*
+
+echo "$ac_t""$ac_cv_prog_cc_works" 1>&6
+if test $ac_cv_prog_cc_works = no; then
+ { echo "configure: error: installation or configuration problem: C compiler cannot create executables." 1>&2; exit 1; }
+fi
+echo $ac_n "checking whether the C compiler ($CC $CFLAGS $LDFLAGS) is a cross-compiler""... $ac_c" 1>&6
+echo "configure:649: checking whether the C compiler ($CC $CFLAGS $LDFLAGS) is a cross-compiler" >&5
+echo "$ac_t""$ac_cv_prog_cc_cross" 1>&6
+cross_compiling=$ac_cv_prog_cc_cross
+
+echo $ac_n "checking whether we are using GNU C""... $ac_c" 1>&6
+echo "configure:654: checking whether we are using GNU C" >&5
+if eval "test \"`echo '$''{'ac_cv_prog_gcc'+set}'`\" = set"; then
+ echo $ac_n "(cached) $ac_c" 1>&6
+else
+ cat > conftest.c <<EOF
+#ifdef __GNUC__
+ yes;
+#endif
+EOF
+if { ac_try='${CC-cc} -E conftest.c'; { (eval echo configure:663: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }; } | egrep yes >/dev/null 2>&1; then
+ ac_cv_prog_gcc=yes
+else
+ ac_cv_prog_gcc=no
+fi
+fi
+
+echo "$ac_t""$ac_cv_prog_gcc" 1>&6
+
+if test $ac_cv_prog_gcc = yes; then
+ GCC=yes
+ test "${CFLAGS+set}" = set || CFLAGS="-O2"
+else
+ GCC=
+ test "${CFLAGS+set}" = set || CFLAGS="-O"
+fi
+
+echo $ac_n "checking how to run the C preprocessor""... $ac_c" 1>&6
+echo "configure:681: checking how to run the C preprocessor" >&5
+# On Suns, sometimes $CPP names a directory.
+if test -n "$CPP" && test -d "$CPP"; then
+ CPP=
+fi
+if test -z "$CPP"; then
+if eval "test \"`echo '$''{'ac_cv_prog_CPP'+set}'`\" = set"; then
+ echo $ac_n "(cached) $ac_c" 1>&6
+else
+ # This must be in double quotes, not single quotes, because CPP may get
+ # substituted into the Makefile and "${CC-cc}" will confuse make.
+ CPP="${CC-cc} -E"
+ # On the NeXT, cc -E runs the code through the compiler's parser,
+ # not just through cpp.
+ cat > conftest.$ac_ext <<EOF
+#line 696 "configure"
+#include "confdefs.h"
+#include <assert.h>
+Syntax Error
+EOF
+ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+{ (eval echo configure:702: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ac_err=`grep -v '^ *+' conftest.out`
+if test -z "$ac_err"; then
+ :
+else
+ echo "$ac_err" >&5
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ CPP="${CC-cc} -E -traditional-cpp"
+ cat > conftest.$ac_ext <<EOF
+#line 713 "configure"
+#include "confdefs.h"
+#include <assert.h>
+Syntax Error
+EOF
+ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+{ (eval echo configure:719: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ac_err=`grep -v '^ *+' conftest.out`
+if test -z "$ac_err"; then
+ :
+else
+ echo "$ac_err" >&5
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ CPP=/lib/cpp
+fi
+rm -f conftest*
+fi
+rm -f conftest*
+ ac_cv_prog_CPP="$CPP"
+fi
+ CPP="$ac_cv_prog_CPP"
+else
+ ac_cv_prog_CPP="$CPP"
+fi
+echo "$ac_t""$CPP" 1>&6
+
+echo $ac_n "checking for function prototypes""... $ac_c" 1>&6
+echo "configure:742: checking for function prototypes" >&5
+if eval "test \"`echo '$''{'ijg_cv_have_prototypes'+set}'`\" = set"; then
+ echo $ac_n "(cached) $ac_c" 1>&6
+else
+ cat > conftest.$ac_ext <<EOF
+#line 747 "configure"
+#include "confdefs.h"
+
+int testfunction (int arg1, int * arg2); /* check prototypes */
+struct methods_struct { /* check method-pointer declarations */
+ int (*error_exit) (char *msgtext);
+ int (*trace_message) (char *msgtext);
+ int (*another_method) (void);
+};
+int testfunction (int arg1, int * arg2) /* check definitions */
+{ return arg2[arg1]; }
+int test2function (void) /* check void arg list */
+{ return 0; }
+
+int main() {
+
+; return 0; }
+EOF
+if { (eval echo configure:765: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+ rm -rf conftest*
+ ijg_cv_have_prototypes=yes
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ ijg_cv_have_prototypes=no
+fi
+rm -f conftest*
+fi
+
+echo "$ac_t""$ijg_cv_have_prototypes" 1>&6
+if test $ijg_cv_have_prototypes = yes; then
+ cat >> confdefs.h <<\EOF
+#define HAVE_PROTOTYPES
+EOF
+
+else
+ echo Your compiler does not seem to know about function prototypes.
+ echo Perhaps it needs a special switch to enable ANSI C mode.
+ echo If so, we recommend running configure like this:
+ echo " ./configure CC='cc -switch'"
+ echo where -switch is the proper switch.
+fi
+ac_safe=`echo "stddef.h" | sed 'y%./+-%__p_%'`
+echo $ac_n "checking for stddef.h""... $ac_c" 1>&6
+echo "configure:792: checking for stddef.h" >&5
+if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+ echo $ac_n "(cached) $ac_c" 1>&6
+else
+ cat > conftest.$ac_ext <<EOF
+#line 797 "configure"
+#include "confdefs.h"
+#include <stddef.h>
+EOF
+ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+{ (eval echo configure:802: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ac_err=`grep -v '^ *+' conftest.out`
+if test -z "$ac_err"; then
+ rm -rf conftest*
+ eval "ac_cv_header_$ac_safe=yes"
+else
+ echo "$ac_err" >&5
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ eval "ac_cv_header_$ac_safe=no"
+fi
+rm -f conftest*
+fi
+if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then
+ echo "$ac_t""yes" 1>&6
+ cat >> confdefs.h <<\EOF
+#define HAVE_STDDEF_H
+EOF
+
+else
+ echo "$ac_t""no" 1>&6
+fi
+
+ac_safe=`echo "stdlib.h" | sed 'y%./+-%__p_%'`
+echo $ac_n "checking for stdlib.h""... $ac_c" 1>&6
+echo "configure:828: checking for stdlib.h" >&5
+if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+ echo $ac_n "(cached) $ac_c" 1>&6
+else
+ cat > conftest.$ac_ext <<EOF
+#line 833 "configure"
+#include "confdefs.h"
+#include <stdlib.h>
+EOF
+ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+{ (eval echo configure:838: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ac_err=`grep -v '^ *+' conftest.out`
+if test -z "$ac_err"; then
+ rm -rf conftest*
+ eval "ac_cv_header_$ac_safe=yes"
+else
+ echo "$ac_err" >&5
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ eval "ac_cv_header_$ac_safe=no"
+fi
+rm -f conftest*
+fi
+if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then
+ echo "$ac_t""yes" 1>&6
+ cat >> confdefs.h <<\EOF
+#define HAVE_STDLIB_H
+EOF
+
+else
+ echo "$ac_t""no" 1>&6
+fi
+
+ac_safe=`echo "string.h" | sed 'y%./+-%__p_%'`
+echo $ac_n "checking for string.h""... $ac_c" 1>&6
+echo "configure:864: checking for string.h" >&5
+if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+ echo $ac_n "(cached) $ac_c" 1>&6
+else
+ cat > conftest.$ac_ext <<EOF
+#line 869 "configure"
+#include "confdefs.h"
+#include <string.h>
+EOF
+ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+{ (eval echo configure:874: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ac_err=`grep -v '^ *+' conftest.out`
+if test -z "$ac_err"; then
+ rm -rf conftest*
+ eval "ac_cv_header_$ac_safe=yes"
+else
+ echo "$ac_err" >&5
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ eval "ac_cv_header_$ac_safe=no"
+fi
+rm -f conftest*
+fi
+if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then
+ echo "$ac_t""yes" 1>&6
+ :
+else
+ echo "$ac_t""no" 1>&6
+cat >> confdefs.h <<\EOF
+#define NEED_BSD_STRINGS
+EOF
+
+fi
+
+echo $ac_n "checking for size_t""... $ac_c" 1>&6
+echo "configure:900: checking for size_t" >&5
+cat > conftest.$ac_ext <<EOF
+#line 902 "configure"
+#include "confdefs.h"
+
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+#include <stdio.h>
+#ifdef NEED_BSD_STRINGS
+#include <strings.h>
+#else
+#include <string.h>
+#endif
+typedef size_t my_size_t;
+
+int main() {
+ my_size_t foovar;
+; return 0; }
+EOF
+if { (eval echo configure:923: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+ rm -rf conftest*
+ ijg_size_t_ok=yes
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ ijg_size_t_ok="not ANSI, perhaps it is in sys/types.h"
+fi
+rm -f conftest*
+echo "$ac_t""$ijg_size_t_ok" 1>&6
+if test "$ijg_size_t_ok" != yes; then
+ac_safe=`echo "sys/types.h" | sed 'y%./+-%__p_%'`
+echo $ac_n "checking for sys/types.h""... $ac_c" 1>&6
+echo "configure:937: checking for sys/types.h" >&5
+if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+ echo $ac_n "(cached) $ac_c" 1>&6
+else
+ cat > conftest.$ac_ext <<EOF
+#line 942 "configure"
+#include "confdefs.h"
+#include <sys/types.h>
+EOF
+ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+{ (eval echo configure:947: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ac_err=`grep -v '^ *+' conftest.out`
+if test -z "$ac_err"; then
+ rm -rf conftest*
+ eval "ac_cv_header_$ac_safe=yes"
+else
+ echo "$ac_err" >&5
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ eval "ac_cv_header_$ac_safe=no"
+fi
+rm -f conftest*
+fi
+if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then
+ echo "$ac_t""yes" 1>&6
+ cat >> confdefs.h <<\EOF
+#define NEED_SYS_TYPES_H
+EOF
+
+cat > conftest.$ac_ext <<EOF
+#line 968 "configure"
+#include "confdefs.h"
+#include <sys/types.h>
+EOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+ egrep "size_t" >/dev/null 2>&1; then
+ rm -rf conftest*
+ ijg_size_t_ok="size_t is in sys/types.h"
+else
+ rm -rf conftest*
+ ijg_size_t_ok=no
+fi
+rm -f conftest*
+
+else
+ echo "$ac_t""no" 1>&6
+ijg_size_t_ok=no
+fi
+
+echo "$ac_t""$ijg_size_t_ok" 1>&6
+if test "$ijg_size_t_ok" = no; then
+ echo Type size_t is not defined in any of the usual places.
+ echo Try putting '"typedef unsigned int size_t;"' in jconfig.h.
+fi
+fi
+echo $ac_n "checking for type unsigned char""... $ac_c" 1>&6
+echo "configure:994: checking for type unsigned char" >&5
+cat > conftest.$ac_ext <<EOF
+#line 996 "configure"
+#include "confdefs.h"
+
+int main() {
+ unsigned char un_char;
+; return 0; }
+EOF
+if { (eval echo configure:1003: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+ rm -rf conftest*
+ echo "$ac_t""yes" 1>&6
+cat >> confdefs.h <<\EOF
+#define HAVE_UNSIGNED_CHAR
+EOF
+
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ echo "$ac_t""no" 1>&6
+fi
+rm -f conftest*
+echo $ac_n "checking for type unsigned short""... $ac_c" 1>&6
+echo "configure:1018: checking for type unsigned short" >&5
+cat > conftest.$ac_ext <<EOF
+#line 1020 "configure"
+#include "confdefs.h"
+
+int main() {
+ unsigned short un_short;
+; return 0; }
+EOF
+if { (eval echo configure:1027: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+ rm -rf conftest*
+ echo "$ac_t""yes" 1>&6
+cat >> confdefs.h <<\EOF
+#define HAVE_UNSIGNED_SHORT
+EOF
+
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ echo "$ac_t""no" 1>&6
+fi
+rm -f conftest*
+echo $ac_n "checking for type void""... $ac_c" 1>&6
+echo "configure:1042: checking for type void" >&5
+cat > conftest.$ac_ext <<EOF
+#line 1044 "configure"
+#include "confdefs.h"
+
+/* Caution: a C++ compiler will insist on valid prototypes */
+typedef void * void_ptr; /* check void * */
+#ifdef HAVE_PROTOTYPES /* check ptr to function returning void */
+typedef void (*void_func) (int a, int b);
+#else
+typedef void (*void_func) ();
+#endif
+
+#ifdef HAVE_PROTOTYPES /* check void function result */
+void test3function (void_ptr arg1, void_func arg2)
+#else
+void test3function (arg1, arg2)
+ void_ptr arg1;
+ void_func arg2;
+#endif
+{
+ char * locptr = (char *) arg1; /* check casting to and from void * */
+ arg1 = (void *) locptr;
+ (*arg2) (1, 2); /* check call of fcn returning void */
+}
+
+int main() {
+
+; return 0; }
+EOF
+if { (eval echo configure:1072: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+ rm -rf conftest*
+ echo "$ac_t""yes" 1>&6
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ echo "$ac_t""no" 1>&6
+cat >> confdefs.h <<\EOF
+#define void char
+EOF
+
+fi
+rm -f conftest*
+
+echo $ac_n "checking for working const""... $ac_c" 1>&6
+echo "configure:1088: checking for working const" >&5
+if eval "test \"`echo '$''{'ac_cv_c_const'+set}'`\" = set"; then
+ echo $ac_n "(cached) $ac_c" 1>&6
+else
+ cat > conftest.$ac_ext <<EOF
+#line 1093 "configure"
+#include "confdefs.h"
+
+int main() {
+
+/* Ultrix mips cc rejects this. */
+typedef int charset[2]; const charset x;
+/* SunOS 4.1.1 cc rejects this. */
+char const *const *ccp;
+char **p;
+/* NEC SVR4.0.2 mips cc rejects this. */
+struct point {int x, y;};
+static struct point const zero = {0,0};
+/* AIX XL C 1.02.0.0 rejects this.
+ It does not let you subtract one const X* pointer from another in an arm
+ of an if-expression whose if-part is not a constant expression */
+const char *g = "string";
+ccp = &g + (g ? g-g : 0);
+/* HPUX 7.0 cc rejects these. */
+++ccp;
+p = (char**) ccp;
+ccp = (char const *const *) p;
+{ /* SCO 3.2v4 cc rejects this. */
+ char *t;
+ char const *s = 0 ? (char *) 0 : (char const *) 0;
+
+ *t++ = 0;
+}
+{ /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */
+ int x[] = {25, 17};
+ const int *foo = &x[0];
+ ++foo;
+}
+{ /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */
+ typedef const int *iptr;
+ iptr p = 0;
+ ++p;
+}
+{ /* AIX XL C 1.02.0.0 rejects this saying
+ "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */
+ struct s { int j; const int *ap[3]; };
+ struct s *b; b->j = 5;
+}
+{ /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
+ const int foo = 10;
+}
+
+; return 0; }
+EOF
+if { (eval echo configure:1142: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+ rm -rf conftest*
+ ac_cv_c_const=yes
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ ac_cv_c_const=no
+fi
+rm -f conftest*
+fi
+
+echo "$ac_t""$ac_cv_c_const" 1>&6
+if test $ac_cv_c_const = no; then
+ cat >> confdefs.h <<\EOF
+#define const
+EOF
+
+fi
+
+echo $ac_n "checking for inline""... $ac_c" 1>&6
+echo "configure:1163: checking for inline" >&5
+ijg_cv_inline=""
+cat > conftest.$ac_ext <<EOF
+#line 1166 "configure"
+#include "confdefs.h"
+
+int main() {
+} __inline__ int foo() { return 0; }
+int bar() { return foo();
+; return 0; }
+EOF
+if { (eval echo configure:1174: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+ rm -rf conftest*
+ ijg_cv_inline="__inline__"
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ cat > conftest.$ac_ext <<EOF
+#line 1182 "configure"
+#include "confdefs.h"
+
+int main() {
+} __inline int foo() { return 0; }
+int bar() { return foo();
+; return 0; }
+EOF
+if { (eval echo configure:1190: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+ rm -rf conftest*
+ ijg_cv_inline="__inline"
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ cat > conftest.$ac_ext <<EOF
+#line 1198 "configure"
+#include "confdefs.h"
+
+int main() {
+} inline int foo() { return 0; }
+int bar() { return foo();
+; return 0; }
+EOF
+if { (eval echo configure:1206: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+ rm -rf conftest*
+ ijg_cv_inline="inline"
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+fi
+rm -f conftest*
+fi
+rm -f conftest*
+fi
+rm -f conftest*
+echo "$ac_t""$ijg_cv_inline" 1>&6
+cat >> confdefs.h <<EOF
+#define INLINE $ijg_cv_inline
+EOF
+
+echo $ac_n "checking for broken incomplete types""... $ac_c" 1>&6
+echo "configure:1224: checking for broken incomplete types" >&5
+cat > conftest.$ac_ext <<EOF
+#line 1226 "configure"
+#include "confdefs.h"
+ typedef struct undefined_structure * undef_struct_ptr;
+int main() {
+
+; return 0; }
+EOF
+if { (eval echo configure:1233: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+ rm -rf conftest*
+ echo "$ac_t""ok" 1>&6
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ echo "$ac_t""broken" 1>&6
+cat >> confdefs.h <<\EOF
+#define INCOMPLETE_TYPES_BROKEN
+EOF
+
+fi
+rm -f conftest*
+echo $ac_n "checking for short external names""... $ac_c" 1>&6
+echo "configure:1248: checking for short external names" >&5
+cat > conftest.$ac_ext <<EOF
+#line 1250 "configure"
+#include "confdefs.h"
+
+int possibly_duplicate_function () { return 0; }
+int possibly_dupli_function () { return 1; }
+
+int main() {
+
+; return 0; }
+EOF
+if { (eval echo configure:1260: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest; then
+ rm -rf conftest*
+ echo "$ac_t""ok" 1>&6
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ echo "$ac_t""short" 1>&6
+cat >> confdefs.h <<\EOF
+#define NEED_SHORT_EXTERNAL_NAMES
+EOF
+
+fi
+rm -f conftest*
+echo $ac_n "checking to see if char is signed""... $ac_c" 1>&6
+echo "configure:1275: checking to see if char is signed" >&5
+if test "$cross_compiling" = yes; then
+ echo Assuming that char is signed on target machine.
+echo If it is unsigned, this will be a little bit inefficient.
+
+else
+ cat > conftest.$ac_ext <<EOF
+#line 1282 "configure"
+#include "confdefs.h"
+
+#ifdef HAVE_PROTOTYPES
+int is_char_signed (int arg)
+#else
+int is_char_signed (arg)
+ int arg;
+#endif
+{
+ if (arg == 189) { /* expected result for unsigned char */
+ return 0; /* type char is unsigned */
+ }
+ else if (arg != -67) { /* expected result for signed char */
+ printf("Hmm, it seems 'char' is not eight bits wide on your machine.\n");
+ printf("I fear the JPEG software will not work at all.\n\n");
+ }
+ return 1; /* assume char is signed otherwise */
+}
+char signed_char_check = (char) (-67);
+main() {
+ exit(is_char_signed((int) signed_char_check));
+}
+EOF
+if { (eval echo configure:1306: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest && (./conftest; exit) 2>/dev/null
+then
+ echo "$ac_t""no" 1>&6
+cat >> confdefs.h <<\EOF
+#define CHAR_IS_UNSIGNED
+EOF
+
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -fr conftest*
+ echo "$ac_t""yes" 1>&6
+fi
+rm -fr conftest*
+fi
+
+echo $ac_n "checking to see if right shift is signed""... $ac_c" 1>&6
+echo "configure:1323: checking to see if right shift is signed" >&5
+if test "$cross_compiling" = yes; then
+ echo "$ac_t""Assuming that right shift is signed on target machine." 1>&6
+else
+ cat > conftest.$ac_ext <<EOF
+#line 1328 "configure"
+#include "confdefs.h"
+
+#ifdef HAVE_PROTOTYPES
+int is_shifting_signed (long arg)
+#else
+int is_shifting_signed (arg)
+ long arg;
+#endif
+/* See whether right-shift on a long is signed or not. */
+{
+ long res = arg >> 4;
+
+ if (res == -0x7F7E80CL) { /* expected result for signed shift */
+ return 1; /* right shift is signed */
+ }
+ /* see if unsigned-shift hack will fix it. */
+ /* we can't just test exact value since it depends on width of long... */
+ res |= (~0L) << (32-4);
+ if (res == -0x7F7E80CL) { /* expected result now? */
+ return 0; /* right shift is unsigned */
+ }
+ printf("Right shift isn't acting as I expect it to.\n");
+ printf("I fear the JPEG software will not work at all.\n\n");
+ return 0; /* try it with unsigned anyway */
+}
+main() {
+ exit(is_shifting_signed(-0x7F7E80B1L));
+}
+EOF
+if { (eval echo configure:1358: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest && (./conftest; exit) 2>/dev/null
+then
+ echo "$ac_t""no" 1>&6
+cat >> confdefs.h <<\EOF
+#define RIGHT_SHIFT_IS_UNSIGNED
+EOF
+
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -fr conftest*
+ echo "$ac_t""yes" 1>&6
+fi
+rm -fr conftest*
+fi
+
+echo $ac_n "checking to see if fopen accepts b spec""... $ac_c" 1>&6
+echo "configure:1375: checking to see if fopen accepts b spec" >&5
+if test "$cross_compiling" = yes; then
+ echo "$ac_t""Assuming that it does." 1>&6
+else
+ cat > conftest.$ac_ext <<EOF
+#line 1380 "configure"
+#include "confdefs.h"
+
+#include <stdio.h>
+main() {
+ if (fopen("conftestdata", "wb") != NULL)
+ exit(0);
+ exit(1);
+}
+EOF
+if { (eval echo configure:1390: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest && (./conftest; exit) 2>/dev/null
+then
+ echo "$ac_t""yes" 1>&6
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -fr conftest*
+ echo "$ac_t""no" 1>&6
+cat >> confdefs.h <<\EOF
+#define DONT_USE_B_MODE
+EOF
+
+fi
+rm -fr conftest*
+fi
+
+ac_aux_dir=
+for ac_dir in $srcdir $srcdir/.. $srcdir/../..; do
+ if test -f $ac_dir/install-sh; then
+ ac_aux_dir=$ac_dir
+ ac_install_sh="$ac_aux_dir/install-sh -c"
+ break
+ elif test -f $ac_dir/install.sh; then
+ ac_aux_dir=$ac_dir
+ ac_install_sh="$ac_aux_dir/install.sh -c"
+ break
+ fi
+done
+if test -z "$ac_aux_dir"; then
+ { echo "configure: error: can not find install-sh or install.sh in $srcdir $srcdir/.. $srcdir/../.." 1>&2; exit 1; }
+fi
+ac_config_guess=$ac_aux_dir/config.guess
+ac_config_sub=$ac_aux_dir/config.sub
+ac_configure=$ac_aux_dir/configure # This should be Cygnus configure.
+
+# Find a good install program. We prefer a C program (faster),
+# so one script is as good as another. But avoid the broken or
+# incompatible versions:
+# SysV /etc/install, /usr/sbin/install
+# SunOS /usr/etc/install
+# IRIX /sbin/install
+# AIX /bin/install
+# AFS /usr/afsws/bin/install, which mishandles nonexistent args
+# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff"
+# ./install, which can be erroneously created by make from ./install.sh.
+echo $ac_n "checking for a BSD compatible install""... $ac_c" 1>&6
+echo "configure:1436: checking for a BSD compatible install" >&5
+if test -z "$INSTALL"; then
+if eval "test \"`echo '$''{'ac_cv_path_install'+set}'`\" = set"; then
+ echo $ac_n "(cached) $ac_c" 1>&6
+else
+ IFS="${IFS= }"; ac_save_IFS="$IFS"; IFS="${IFS}:"
+ for ac_dir in $PATH; do
+ # Account for people who put trailing slashes in PATH elements.
+ case "$ac_dir/" in
+ /|./|.//|/etc/*|/usr/sbin/*|/usr/etc/*|/sbin/*|/usr/afsws/bin/*|/usr/ucb/*) ;;
+ *)
+ # OSF1 and SCO ODT 3.0 have their own names for install.
+ for ac_prog in ginstall installbsd scoinst install; do
+ if test -f $ac_dir/$ac_prog; then
+ if test $ac_prog = install &&
+ grep dspmsg $ac_dir/$ac_prog >/dev/null 2>&1; then
+ # AIX install. It has an incompatible calling convention.
+ # OSF/1 installbsd also uses dspmsg, but is usable.
+ :
+ else
+ ac_cv_path_install="$ac_dir/$ac_prog -c"
+ break 2
+ fi
+ fi
+ done
+ ;;
+ esac
+ done
+ IFS="$ac_save_IFS"
+
+fi
+ if test "${ac_cv_path_install+set}" = set; then
+ INSTALL="$ac_cv_path_install"
+ else
+ # As a last resort, use the slow shell script. We don't cache a
+ # path for INSTALL within a source directory, because that will
+ # break other packages using the cache if that directory is
+ # removed, or if the path is relative.
+ INSTALL="$ac_install_sh"
+ fi
+fi
+echo "$ac_t""$INSTALL" 1>&6
+
+# Use test -z because SunOS4 sh mishandles braces in ${var-val}.
+# It thinks the first close brace ends the variable substitution.
+test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}'
+
+test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644'
+
+# Extract the first word of "ranlib", so it can be a program name with args.
+set dummy ranlib; ac_word=$2
+echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
+echo "configure:1488: checking for $ac_word" >&5
+if eval "test \"`echo '$''{'ac_cv_prog_RANLIB'+set}'`\" = set"; then
+ echo $ac_n "(cached) $ac_c" 1>&6
+else
+ if test -n "$RANLIB"; then
+ ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
+else
+ IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS="${IFS}:"
+ for ac_dir in $PATH; do
+ test -z "$ac_dir" && ac_dir=.
+ if test -f $ac_dir/$ac_word; then
+ ac_cv_prog_RANLIB="ranlib"
+ break
+ fi
+ done
+ IFS="$ac_save_ifs"
+ test -z "$ac_cv_prog_RANLIB" && ac_cv_prog_RANLIB=":"
+fi
+fi
+RANLIB="$ac_cv_prog_RANLIB"
+if test -n "$RANLIB"; then
+ echo "$ac_t""$RANLIB" 1>&6
+else
+ echo "$ac_t""no" 1>&6
+fi
+
+
+# Decide whether to use libtool,
+# and if so whether to build shared, static, or both flavors of library.
+LTSHARED="no"
+# Check whether --enable-shared or --disable-shared was given.
+if test "${enable_shared+set}" = set; then
+ enableval="$enable_shared"
+ LTSHARED="$enableval"
+fi
+
+LTSTATIC="no"
+# Check whether --enable-static or --disable-static was given.
+if test "${enable_static+set}" = set; then
+ enableval="$enable_static"
+ LTSTATIC="$enableval"
+fi
+
+if test "x$LTSHARED" != xno -o "x$LTSTATIC" != xno; then
+ USELIBTOOL="yes"
+ LIBTOOL="./libtool"
+ O="lo"
+ A="la"
+ LN='$(LIBTOOL) --mode=link $(CC)'
+ INSTALL_LIB='$(LIBTOOL) --mode=install ${INSTALL}'
+ INSTALL_PROGRAM="\$(LIBTOOL) --mode=install $INSTALL_PROGRAM"
+else
+ USELIBTOOL="no"
+ LIBTOOL=""
+ O="o"
+ A="a"
+ LN='$(CC)'
+ INSTALL_LIB="$INSTALL_DATA"
+fi
+
+
+
+
+
+
+# Configure libtool if needed.
+if test $USELIBTOOL = yes; then
+ disable_shared=
+ disable_static=
+ if test "x$LTSHARED" = xno; then
+ disable_shared="--disable-shared"
+ fi
+ if test "x$LTSTATIC" = xno; then
+ disable_static="--disable-static"
+ fi
+ $srcdir/ltconfig $disable_shared $disable_static $srcdir/ltmain.sh
+fi
+
+# Select memory manager depending on user input.
+# If no "-enable-maxmem", use jmemnobs
+MEMORYMGR='jmemnobs.$(O)'
+MAXMEM="no"
+# Check whether --enable-maxmem or --disable-maxmem was given.
+if test "${enable_maxmem+set}" = set; then
+ enableval="$enable_maxmem"
+ MAXMEM="$enableval"
+fi
+
+# support --with-maxmem for backwards compatibility with IJG V5.
+# Check whether --with-maxmem or --without-maxmem was given.
+if test "${with_maxmem+set}" = set; then
+ withval="$with_maxmem"
+ MAXMEM="$withval"
+fi
+
+if test "x$MAXMEM" = xyes; then
+ MAXMEM=1
+fi
+if test "x$MAXMEM" != xno; then
+ if test -n "`echo $MAXMEM | sed 's/[0-9]//g'`"; then
+ { echo "configure: error: non-numeric argument to --enable-maxmem" 1>&2; exit 1; }
+ fi
+ DEFAULTMAXMEM=`expr $MAXMEM \* 1048576`
+cat >> confdefs.h <<EOF
+#define DEFAULT_MAX_MEM ${DEFAULTMAXMEM}
+EOF
+
+echo $ac_n "checking for 'tmpfile()'""... $ac_c" 1>&6
+echo "configure:1596: checking for 'tmpfile()'" >&5
+cat > conftest.$ac_ext <<EOF
+#line 1598 "configure"
+#include "confdefs.h"
+#include <stdio.h>
+int main() {
+ FILE * tfile = tmpfile();
+; return 0; }
+EOF
+if { (eval echo configure:1605: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest; then
+ rm -rf conftest*
+ echo "$ac_t""yes" 1>&6
+MEMORYMGR='jmemansi.$(O)'
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ echo "$ac_t""no" 1>&6
+MEMORYMGR='jmemname.$(O)'
+cat >> confdefs.h <<\EOF
+#define NEED_SIGNAL_CATCHER
+EOF
+
+echo $ac_n "checking for 'mktemp()'""... $ac_c" 1>&6
+echo "configure:1620: checking for 'mktemp()'" >&5
+cat > conftest.$ac_ext <<EOF
+#line 1622 "configure"
+#include "confdefs.h"
+
+int main() {
+ char fname[80]; mktemp(fname);
+; return 0; }
+EOF
+if { (eval echo configure:1629: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest; then
+ rm -rf conftest*
+ echo "$ac_t""yes" 1>&6
+else
+ echo "configure: failed program was:" >&5
+ cat conftest.$ac_ext >&5
+ rm -rf conftest*
+ echo "$ac_t""no" 1>&6
+cat >> confdefs.h <<\EOF
+#define NO_MKTEMP
+EOF
+
+fi
+rm -f conftest*
+fi
+rm -f conftest*
+fi
+
+
+# Extract the library version ID from jpeglib.h.
+echo $ac_n "checking libjpeg version number""... $ac_c" 1>&6
+echo "configure:1650: checking libjpeg version number" >&5
+JPEG_LIB_VERSION=`sed -e '/^#define JPEG_LIB_VERSION/!d' -e 's/^[^0-9]*\([0-9][0-9]*\).*$/\1/' $srcdir/jpeglib.h`
+echo "$ac_t""$JPEG_LIB_VERSION" 1>&6
+
+
+# Prepare to massage makefile.cfg correctly.
+if test $ijg_cv_have_prototypes = yes; then
+ A2K_DEPS=""
+ COM_A2K="# "
+else
+ A2K_DEPS="ansi2knr"
+ COM_A2K=""
+fi
+
+
+# ansi2knr needs -DBSD if string.h is missing
+if test $ac_cv_header_string_h = no; then
+ ANSI2KNRFLAGS="-DBSD"
+else
+ ANSI2KNRFLAGS=""
+fi
+
+# Substitutions to enable or disable libtool-related stuff
+if test $USELIBTOOL = yes -a $ijg_cv_have_prototypes = yes; then
+ COM_LT=""
+else
+ COM_LT="# "
+fi
+
+if test "x$LTSHARED" != xno; then
+ FORCE_INSTALL_LIB="install-lib"
+else
+ FORCE_INSTALL_LIB=""
+fi
+
+# Set up -I directives
+if test "x$srcdir" = x.; then
+ INCLUDEFLAGS='-I$(srcdir)'
+else
+ INCLUDEFLAGS='-I. -I$(srcdir)'
+fi
+
+trap '' 1 2 15
+
+trap 'rm -fr conftest* confdefs* core core.* *.core $ac_clean_files; exit 1' 1 2 15
+
+test "x$prefix" = xNONE && prefix=$ac_default_prefix
+# Let make expand exec_prefix.
+test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
+
+# Any assignment to VPATH causes Sun make to only execute
+# the first set of double-colon rules, so remove it if not needed.
+# If there is a colon in the path, we need to keep it.
+if test "x$srcdir" = x.; then
+ ac_vpsub='/^[ ]*VPATH[ ]*=[^:]*$/d'
+fi
+
+trap 'rm -f $CONFIG_STATUS conftest*; exit 1' 1 2 15
+
+DEFS=-DHAVE_CONFIG_H
+
+# Without the "./", some shells look in PATH for config.status.
+: ${CONFIG_STATUS=./config.status}
+
+echo creating $CONFIG_STATUS
+rm -f $CONFIG_STATUS
+cat > $CONFIG_STATUS <<EOF
+#! /bin/sh
+# Generated automatically by configure.
+# Run this file to recreate the current configuration.
+# This directory was configured as follows,
+# on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+#
+# $0 $ac_configure_args
+#
+# Compiler output produced by configure, useful for debugging
+# configure, is in ./config.log if it exists.
+
+ac_cs_usage="Usage: $CONFIG_STATUS [--recheck] [--version] [--help]"
+for ac_option
+do
+ case "\$ac_option" in
+ -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
+ echo "running \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion"
+ exec \${CONFIG_SHELL-/bin/sh} $0 $ac_configure_args --no-create --no-recursion ;;
+ -version | --version | --versio | --versi | --vers | --ver | --ve | --v)
+ echo "$CONFIG_STATUS generated by autoconf version 2.12"
+ exit 0 ;;
+ -help | --help | --hel | --he | --h)
+ echo "\$ac_cs_usage"; exit 0 ;;
+ *) echo "\$ac_cs_usage"; exit 1 ;;
+ esac
+done
+
+ac_given_srcdir=$srcdir
+ac_given_INSTALL="$INSTALL"
+
+trap 'rm -fr `echo "Makefile:makefile.cfg jconfig.h:jconfig.cfg" | sed "s/:[^ ]*//g"` conftest*; exit 1' 1 2 15
+EOF
+cat >> $CONFIG_STATUS <<EOF
+
+# Protect against being on the right side of a sed subst in config.status.
+sed 's/%@/@@/; s/@%/@@/; s/%g\$/@g/; /@g\$/s/[\\\\&%]/\\\\&/g;
+ s/@@/%@/; s/@@/@%/; s/@g\$/%g/' > conftest.subs <<\\CEOF
+$ac_vpsub
+$extrasub
+s%@CFLAGS@%$CFLAGS%g
+s%@CPPFLAGS@%$CPPFLAGS%g
+s%@CXXFLAGS@%$CXXFLAGS%g
+s%@DEFS@%$DEFS%g
+s%@LDFLAGS@%$LDFLAGS%g
+s%@LIBS@%$LIBS%g
+s%@exec_prefix@%$exec_prefix%g
+s%@prefix@%$prefix%g
+s%@program_transform_name@%$program_transform_name%g
+s%@bindir@%$bindir%g
+s%@sbindir@%$sbindir%g
+s%@libexecdir@%$libexecdir%g
+s%@datadir@%$datadir%g
+s%@sysconfdir@%$sysconfdir%g
+s%@sharedstatedir@%$sharedstatedir%g
+s%@localstatedir@%$localstatedir%g
+s%@libdir@%$libdir%g
+s%@includedir@%$includedir%g
+s%@oldincludedir@%$oldincludedir%g
+s%@infodir@%$infodir%g
+s%@mandir@%$mandir%g
+s%@CC@%$CC%g
+s%@CPP@%$CPP%g
+s%@INSTALL_PROGRAM@%$INSTALL_PROGRAM%g
+s%@INSTALL_DATA@%$INSTALL_DATA%g
+s%@RANLIB@%$RANLIB%g
+s%@LIBTOOL@%$LIBTOOL%g
+s%@O@%$O%g
+s%@A@%$A%g
+s%@LN@%$LN%g
+s%@INSTALL_LIB@%$INSTALL_LIB%g
+s%@MEMORYMGR@%$MEMORYMGR%g
+s%@JPEG_LIB_VERSION@%$JPEG_LIB_VERSION%g
+s%@A2K_DEPS@%$A2K_DEPS%g
+s%@COM_A2K@%$COM_A2K%g
+s%@ANSI2KNRFLAGS@%$ANSI2KNRFLAGS%g
+s%@COM_LT@%$COM_LT%g
+s%@FORCE_INSTALL_LIB@%$FORCE_INSTALL_LIB%g
+s%@INCLUDEFLAGS@%$INCLUDEFLAGS%g
+
+CEOF
+EOF
+
+cat >> $CONFIG_STATUS <<\EOF
+
+# Split the substitutions into bite-sized pieces for seds with
+# small command number limits, like on Digital OSF/1 and HP-UX.
+ac_max_sed_cmds=90 # Maximum number of lines to put in a sed script.
+ac_file=1 # Number of current file.
+ac_beg=1 # First line for current file.
+ac_end=$ac_max_sed_cmds # Line after last line for current file.
+ac_more_lines=:
+ac_sed_cmds=""
+while $ac_more_lines; do
+ if test $ac_beg -gt 1; then
+ sed "1,${ac_beg}d; ${ac_end}q" conftest.subs > conftest.s$ac_file
+ else
+ sed "${ac_end}q" conftest.subs > conftest.s$ac_file
+ fi
+ if test ! -s conftest.s$ac_file; then
+ ac_more_lines=false
+ rm -f conftest.s$ac_file
+ else
+ if test -z "$ac_sed_cmds"; then
+ ac_sed_cmds="sed -f conftest.s$ac_file"
+ else
+ ac_sed_cmds="$ac_sed_cmds | sed -f conftest.s$ac_file"
+ fi
+ ac_file=`expr $ac_file + 1`
+ ac_beg=$ac_end
+ ac_end=`expr $ac_end + $ac_max_sed_cmds`
+ fi
+done
+if test -z "$ac_sed_cmds"; then
+ ac_sed_cmds=cat
+fi
+EOF
+
+cat >> $CONFIG_STATUS <<EOF
+
+CONFIG_FILES=\${CONFIG_FILES-"Makefile:makefile.cfg"}
+EOF
+cat >> $CONFIG_STATUS <<\EOF
+for ac_file in .. $CONFIG_FILES; do if test "x$ac_file" != x..; then
+ # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
+ case "$ac_file" in
+ *:*) ac_file_in=`echo "$ac_file"|sed 's%[^:]*:%%'`
+ ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;;
+ *) ac_file_in="${ac_file}.in" ;;
+ esac
+
+ # Adjust a relative srcdir, top_srcdir, and INSTALL for subdirectories.
+
+ # Remove last slash and all that follows it. Not all systems have dirname.
+ ac_dir=`echo $ac_file|sed 's%/[^/][^/]*$%%'`
+ if test "$ac_dir" != "$ac_file" && test "$ac_dir" != .; then
+ # The file is in a subdirectory.
+ test ! -d "$ac_dir" && mkdir "$ac_dir"
+ ac_dir_suffix="/`echo $ac_dir|sed 's%^\./%%'`"
+ # A "../" for each directory in $ac_dir_suffix.
+ ac_dots=`echo $ac_dir_suffix|sed 's%/[^/]*%../%g'`
+ else
+ ac_dir_suffix= ac_dots=
+ fi
+
+ case "$ac_given_srcdir" in
+ .) srcdir=.
+ if test -z "$ac_dots"; then top_srcdir=.
+ else top_srcdir=`echo $ac_dots|sed 's%/$%%'`; fi ;;
+ /*) srcdir="$ac_given_srcdir$ac_dir_suffix"; top_srcdir="$ac_given_srcdir" ;;
+ *) # Relative path.
+ srcdir="$ac_dots$ac_given_srcdir$ac_dir_suffix"
+ top_srcdir="$ac_dots$ac_given_srcdir" ;;
+ esac
+
+ case "$ac_given_INSTALL" in
+ [/$]*) INSTALL="$ac_given_INSTALL" ;;
+ *) INSTALL="$ac_dots$ac_given_INSTALL" ;;
+ esac
+
+ echo creating "$ac_file"
+ rm -f "$ac_file"
+ configure_input="Generated automatically from `echo $ac_file_in|sed 's%.*/%%'` by configure."
+ case "$ac_file" in
+ *Makefile*) ac_comsub="1i\\
+# $configure_input" ;;
+ *) ac_comsub= ;;
+ esac
+
+ ac_file_inputs=`echo $ac_file_in|sed -e "s%^%$ac_given_srcdir/%" -e "s%:% $ac_given_srcdir/%g"`
+ sed -e "$ac_comsub
+s%@configure_input@%$configure_input%g
+s%@srcdir@%$srcdir%g
+s%@top_srcdir@%$top_srcdir%g
+s%@INSTALL@%$INSTALL%g
+" $ac_file_inputs | (eval "$ac_sed_cmds") > $ac_file
+fi; done
+rm -f conftest.s*
+
+# These sed commands are passed to sed as "A NAME B NAME C VALUE D", where
+# NAME is the cpp macro being defined and VALUE is the value it is being given.
+#
+# ac_d sets the value in "#define NAME VALUE" lines.
+ac_dA='s%^\([ ]*\)#\([ ]*define[ ][ ]*\)'
+ac_dB='\([ ][ ]*\)[^ ]*%\1#\2'
+ac_dC='\3'
+ac_dD='%g'
+# ac_u turns "#undef NAME" with trailing blanks into "#define NAME VALUE".
+ac_uA='s%^\([ ]*\)#\([ ]*\)undef\([ ][ ]*\)'
+ac_uB='\([ ]\)%\1#\2define\3'
+ac_uC=' '
+ac_uD='\4%g'
+# ac_e turns "#undef NAME" without trailing blanks into "#define NAME VALUE".
+ac_eA='s%^\([ ]*\)#\([ ]*\)undef\([ ][ ]*\)'
+ac_eB='$%\1#\2define\3'
+ac_eC=' '
+ac_eD='%g'
+
+if test "${CONFIG_HEADERS+set}" != set; then
+EOF
+cat >> $CONFIG_STATUS <<EOF
+ CONFIG_HEADERS="jconfig.h:jconfig.cfg"
+EOF
+cat >> $CONFIG_STATUS <<\EOF
+fi
+for ac_file in .. $CONFIG_HEADERS; do if test "x$ac_file" != x..; then
+ # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
+ case "$ac_file" in
+ *:*) ac_file_in=`echo "$ac_file"|sed 's%[^:]*:%%'`
+ ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;;
+ *) ac_file_in="${ac_file}.in" ;;
+ esac
+
+ echo creating $ac_file
+
+ rm -f conftest.frag conftest.in conftest.out
+ ac_file_inputs=`echo $ac_file_in|sed -e "s%^%$ac_given_srcdir/%" -e "s%:% $ac_given_srcdir/%g"`
+ cat $ac_file_inputs > conftest.in
+
+EOF
+
+# Transform confdefs.h into a sed script conftest.vals that substitutes
+# the proper values into config.h.in to produce config.h. And first:
+# Protect against being on the right side of a sed subst in config.status.
+# Protect against being in an unquoted here document in config.status.
+rm -f conftest.vals
+cat > conftest.hdr <<\EOF
+s/[\\&%]/\\&/g
+s%[\\$`]%\\&%g
+s%#define \([A-Za-z_][A-Za-z0-9_]*\) *\(.*\)%${ac_dA}\1${ac_dB}\1${ac_dC}\2${ac_dD}%gp
+s%ac_d%ac_u%gp
+s%ac_u%ac_e%gp
+EOF
+sed -n -f conftest.hdr confdefs.h > conftest.vals
+rm -f conftest.hdr
+
+# This sed command replaces #undef with comments. This is necessary, for
+# example, in the case of _POSIX_SOURCE, which is predefined and required
+# on some systems where configure will not decide to define it.
+cat >> conftest.vals <<\EOF
+EOF
+
+# Break up conftest.vals because some shells have a limit on
+# the size of here documents, and old seds have small limits too.
+
+rm -f conftest.tail
+while :
+do
+ ac_lines=`grep -c . conftest.vals`
+ # grep -c gives empty output for an empty file on some AIX systems.
+ if test -z "$ac_lines" || test "$ac_lines" -eq 0; then break; fi
+ # Write a limited-size here document to conftest.frag.
+ echo ' cat > conftest.frag <<CEOF' >> $CONFIG_STATUS
+ sed ${ac_max_here_lines}q conftest.vals >> $CONFIG_STATUS
+ echo 'CEOF
+ sed -f conftest.frag conftest.in > conftest.out
+ rm -f conftest.in
+ mv conftest.out conftest.in
+' >> $CONFIG_STATUS
+ sed 1,${ac_max_here_lines}d conftest.vals > conftest.tail
+ rm -f conftest.vals
+ mv conftest.tail conftest.vals
+done
+rm -f conftest.vals
+
+cat >> $CONFIG_STATUS <<\EOF
+ rm -f conftest.frag conftest.h
+ echo "/* $ac_file. Generated automatically by configure. */" > conftest.h
+ cat conftest.in >> conftest.h
+ rm -f conftest.in
+ if cmp -s $ac_file conftest.h 2>/dev/null; then
+ echo "$ac_file is unchanged"
+ rm -f conftest.h
+ else
+ # Remove last slash and all that follows it. Not all systems have dirname.
+ ac_dir=`echo $ac_file|sed 's%/[^/][^/]*$%%'`
+ if test "$ac_dir" != "$ac_file" && test "$ac_dir" != .; then
+ # The file is in a subdirectory.
+ test ! -d "$ac_dir" && mkdir "$ac_dir"
+ fi
+ rm -f $ac_file
+ mv conftest.h $ac_file
+ fi
+fi; done
+
+EOF
+cat >> $CONFIG_STATUS <<EOF
+
+EOF
+cat >> $CONFIG_STATUS <<\EOF
+
+exit 0
+EOF
+chmod +x $CONFIG_STATUS
+rm -fr confdefs* $ac_clean_files
+test "$no_create" = yes || ${CONFIG_SHELL-/bin/sh} $CONFIG_STATUS || exit 1
+
diff --git a/jpeg-6c/djpeg.1 b/jpeg-6c/djpeg.1
new file mode 100644
index 0000000..11beb6a
--- /dev/null
+++ b/jpeg-6c/djpeg.1
@@ -0,0 +1,253 @@
+.TH DJPEG 1 "22 August 1997"
+.SH NAME
+djpeg \- decompress a JPEG file to an image file
+.SH SYNOPSIS
+.B djpeg
+[
+.I options
+]
+[
+.I filename
+]
+.LP
+.SH DESCRIPTION
+.LP
+.B djpeg
+decompresses the named JPEG file, or the standard input if no file is named,
+and produces an image file on the standard output. PBMPLUS (PPM/PGM), BMP,
+GIF, Targa, or RLE (Utah Raster Toolkit) output format can be selected.
+(RLE is supported only if the URT library is available.)
+.SH OPTIONS
+All switch names may be abbreviated; for example,
+.B \-grayscale
+may be written
+.B \-gray
+or
+.BR \-gr .
+Most of the "basic" switches can be abbreviated to as little as one letter.
+Upper and lower case are equivalent (thus
+.B \-BMP
+is the same as
+.BR \-bmp ).
+British spellings are also accepted (e.g.,
+.BR \-greyscale ),
+though for brevity these are not mentioned below.
+.PP
+The basic switches are:
+.TP
+.BI \-colors " N"
+Reduce image to at most N colors. This reduces the number of colors used in
+the output image, so that it can be displayed on a colormapped display or
+stored in a colormapped file format. For example, if you have an 8-bit
+display, you'd need to reduce to 256 or fewer colors.
+.TP
+.BI \-quantize " N"
+Same as
+.BR \-colors .
+.B \-colors
+is the recommended name,
+.B \-quantize
+is provided only for backwards compatibility.
+.TP
+.B \-fast
+Select recommended processing options for fast, low quality output. (The
+default options are chosen for highest quality output.) Currently, this is
+equivalent to \fB\-dct fast \-nosmooth \-onepass \-dither ordered\fR.
+.TP
+.B \-grayscale
+Force gray-scale output even if JPEG file is color. Useful for viewing on
+monochrome displays; also,
+.B djpeg
+runs noticeably faster in this mode.
+.TP
+.BI \-scale " M/N"
+Scale the output image by a factor M/N. Currently the scale factor must be
+1/1, 1/2, 1/4, or 1/8. Scaling is handy if the image is larger than your
+screen; also,
+.B djpeg
+runs much faster when scaling down the output.
+.TP
+.B \-bmp
+Select BMP output format (Windows flavor). 8-bit colormapped format is
+emitted if
+.B \-colors
+or
+.B \-grayscale
+is specified, or if the JPEG file is gray-scale; otherwise, 24-bit full-color
+format is emitted.
+.TP
+.B \-gif
+Select GIF output format. Since GIF does not support more than 256 colors,
+.B \-colors 256
+is assumed (unless you specify a smaller number of colors).
+.TP
+.B \-os2
+Select BMP output format (OS/2 1.x flavor). 8-bit colormapped format is
+emitted if
+.B \-colors
+or
+.B \-grayscale
+is specified, or if the JPEG file is gray-scale; otherwise, 24-bit full-color
+format is emitted.
+.TP
+.B \-pnm
+Select PBMPLUS (PPM/PGM) output format (this is the default format).
+PGM is emitted if the JPEG file is gray-scale or if
+.B \-grayscale
+is specified; otherwise PPM is emitted.
+.TP
+.B \-rle
+Select RLE output format. (Requires URT library.)
+.TP
+.B \-targa
+Select Targa output format. Gray-scale format is emitted if the JPEG file is
+gray-scale or if
+.B \-grayscale
+is specified; otherwise, colormapped format is emitted if
+.B \-colors
+is specified; otherwise, 24-bit full-color format is emitted.
+.PP
+Switches for advanced users:
+.TP
+.B \-dct int
+Use integer DCT method (default).
+.TP
+.B \-dct fast
+Use fast integer DCT (less accurate).
+.TP
+.B \-dct float
+Use floating-point DCT method.
+The float method is very slightly more accurate than the int method, but is
+much slower unless your machine has very fast floating-point hardware. Also
+note that results of the floating-point method may vary slightly across
+machines, while the integer methods should give the same results everywhere.
+The fast integer method is much less accurate than the other two.
+.TP
+.B \-dither fs
+Use Floyd-Steinberg dithering in color quantization.
+.TP
+.B \-dither ordered
+Use ordered dithering in color quantization.
+.TP
+.B \-dither none
+Do not use dithering in color quantization.
+By default, Floyd-Steinberg dithering is applied when quantizing colors; this
+is slow but usually produces the best results. Ordered dither is a compromise
+between speed and quality; no dithering is fast but usually looks awful. Note
+that these switches have no effect unless color quantization is being done.
+Ordered dither is only available in
+.B \-onepass
+mode.
+.TP
+.BI \-map " file"
+Quantize to the colors used in the specified image file. This is useful for
+producing multiple files with identical color maps, or for forcing a
+predefined set of colors to be used. The
+.I file
+must be a GIF or PPM file. This option overrides
+.B \-colors
+and
+.BR \-onepass .
+.TP
+.B \-nosmooth
+Use a faster, lower-quality upsampling routine.
+.TP
+.B \-onepass
+Use one-pass instead of two-pass color quantization. The one-pass method is
+faster and needs less memory, but it produces a lower-quality image.
+.B \-onepass
+is ignored unless you also say
+.B \-colors
+.IR N .
+Also, the one-pass method is always used for gray-scale output (the two-pass
+method is no improvement then).
+.TP
+.BI \-maxmemory " N"
+Set limit for amount of memory to use in processing large images. Value is
+in thousands of bytes, or millions of bytes if "M" is attached to the
+number. For example,
+.B \-max 4m
+selects 4000000 bytes. If more space is needed, temporary files will be used.
+.TP
+.BI \-outfile " name"
+Send output image to the named file, not to standard output.
+.TP
+.B \-verbose
+Enable debug printout. More
+.BR \-v 's
+give more output. Also, version information is printed at startup.
+.TP
+.B \-debug
+Same as
+.BR \-verbose .
+.SH EXAMPLES
+.LP
+This example decompresses the JPEG file foo.jpg, quantizes it to
+256 colors, and saves the output in 8-bit BMP format in foo.bmp:
+.IP
+.B djpeg \-colors 256 \-bmp
+.I foo.jpg
+.B >
+.I foo.bmp
+.SH HINTS
+To get a quick preview of an image, use the
+.B \-grayscale
+and/or
+.B \-scale
+switches.
+.B \-grayscale \-scale 1/8
+is the fastest case.
+.PP
+Several options are available that trade off image quality to gain speed.
+.B \-fast
+turns on the recommended settings.
+.PP
+.B \-dct fast
+and/or
+.B \-nosmooth
+gain speed at a small sacrifice in quality.
+When producing a color-quantized image,
+.B \-onepass \-dither ordered
+is fast but much lower quality than the default behavior.
+.B \-dither none
+may give acceptable results in two-pass mode, but is seldom tolerable in
+one-pass mode.
+.PP
+If you are fortunate enough to have very fast floating point hardware,
+\fB\-dct float\fR may be even faster than \fB\-dct fast\fR. But on most
+machines \fB\-dct float\fR is slower than \fB\-dct int\fR; in this case it is
+not worth using, because its theoretical accuracy advantage is too small to be
+significant in practice.
+.SH ENVIRONMENT
+.TP
+.B JPEGMEM
+If this environment variable is set, its value is the default memory limit.
+The value is specified as described for the
+.B \-maxmemory
+switch.
+.B JPEGMEM
+overrides the default value specified when the program was compiled, and
+itself is overridden by an explicit
+.BR \-maxmemory .
+.SH SEE ALSO
+.BR cjpeg (1),
+.BR jpegtran (1),
+.BR rdjpgcom (1),
+.BR wrjpgcom (1)
+.br
+.BR ppm (5),
+.BR pgm (5)
+.br
+Wallace, Gregory K. "The JPEG Still Picture Compression Standard",
+Communications of the ACM, April 1991 (vol. 34, no. 4), pp. 30-44.
+.SH AUTHOR
+Independent JPEG Group
+.SH BUGS
+Arithmetic coding is not supported for legal reasons.
+.PP
+To avoid the Unisys LZW patent,
+.B djpeg
+produces uncompressed GIF files. These are larger than they should be, but
+are readable by standard GIF decoders.
+.PP
+Still not as fast as we'd like.
diff --git a/jpeg-6c/djpeg.c b/jpeg-6c/djpeg.c
new file mode 100644
index 0000000..8c3eb17
--- /dev/null
+++ b/jpeg-6c/djpeg.c
@@ -0,0 +1,630 @@
+/*
+ * djpeg.c
+ *
+ * Copyright (C) 1991-1997, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a command-line user interface for the JPEG decompressor.
+ * It should work on any system with Unix- or MS-DOS-style command lines.
+ *
+ * Two different command line styles are permitted, depending on the
+ * compile-time switch TWO_FILE_COMMANDLINE:
+ * djpeg [options] inputfile outputfile
+ * djpeg [options] [inputfile]
+ * In the second style, output is always to standard output, which you'd
+ * normally redirect to a file or pipe to some other program. Input is
+ * either from a named file or from standard input (typically redirected).
+ * The second style is convenient on Unix but is unhelpful on systems that
+ * don't support pipes. Also, you MUST use the first style if your system
+ * doesn't do binary I/O to stdin/stdout.
+ * To simplify script writing, the "-outfile" switch is provided. The syntax
+ * djpeg [options] -outfile outputfile inputfile
+ * works regardless of which command line style is used.
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+#include "jversion.h" /* for version message */
+
+#include <ctype.h> /* to declare isprint() */
+
+#ifdef USE_CCOMMAND /* command-line reader for Macintosh */
+#ifdef __MWERKS__
+#include <SIOUX.h> /* Metrowerks needs this */
+#include <console.h> /* ... and this */
+#endif
+#ifdef THINK_C
+#include <console.h> /* Think declares it here */
+#endif
+#endif
+
+
+/* Create the add-on message string table. */
+
+#define JMESSAGE(code,string) string ,
+
+static const char * const cdjpeg_message_table[] = {
+#include "cderror.h"
+ NULL
+};
+
+
+/*
+ * This list defines the known output image formats
+ * (not all of which need be supported by a given version).
+ * You can change the default output format by defining DEFAULT_FMT;
+ * indeed, you had better do so if you undefine PPM_SUPPORTED.
+ */
+
+typedef enum {
+ FMT_BMP, /* BMP format (Windows flavor) */
+ FMT_GIF, /* GIF format */
+ FMT_OS2, /* BMP format (OS/2 flavor) */
+ FMT_PPM, /* PPM/PGM (PBMPLUS formats) */
+ FMT_PPMW, /* PPM/PGM 12/16 bit (PBMPLUS formats) */
+ FMT_RLE, /* RLE format */
+ FMT_TARGA, /* Targa format */
+ FMT_TIFF /* TIFF format */
+} IMAGE_FORMATS;
+
+#ifndef DEFAULT_FMT /* so can override from CFLAGS in Makefile */
+#define DEFAULT_FMT FMT_PPM
+#endif
+
+static IMAGE_FORMATS requested_fmt;
+
+
+/*
+ * Argument-parsing code.
+ * The switch parser is designed to be useful with DOS-style command line
+ * syntax, ie, intermixed switches and file names, where only the switches
+ * to the left of a given file name affect processing of that file.
+ * The main program in this file doesn't actually use this capability...
+ */
+
+
+static const char * progname; /* program name for error messages */
+static char * outfilename; /* for -outfile switch */
+
+
+LOCAL(void)
+usage (void)
+/* complain about bad command line */
+{
+ fprintf(stderr, "usage: %s [switches] ", progname);
+#ifdef TWO_FILE_COMMANDLINE
+ fprintf(stderr, "inputfile outputfile\n");
+#else
+ fprintf(stderr, "[inputfile]\n");
+#endif
+
+ fprintf(stderr, "Switches (names may be abbreviated):\n");
+ fprintf(stderr, " -colors N Reduce image to no more than N colors\n");
+ fprintf(stderr, " -fast Fast, low-quality processing\n");
+ fprintf(stderr, " -grayscale Force grayscale output\n");
+#ifdef IDCT_SCALING_SUPPORTED
+ fprintf(stderr, " -scale M/N Scale output image by fraction M/N, eg, 1/8\n");
+#endif
+#ifdef BMP_SUPPORTED
+ fprintf(stderr, " -bmp Select BMP output format (Windows style)%s\n",
+ (DEFAULT_FMT == FMT_BMP ? " (default)" : ""));
+#endif
+#ifdef GIF_SUPPORTED
+ fprintf(stderr, " -gif Select GIF output format%s\n",
+ (DEFAULT_FMT == FMT_GIF ? " (default)" : ""));
+#endif
+#ifdef BMP_SUPPORTED
+ fprintf(stderr, " -os2 Select BMP output format (OS/2 style)%s\n",
+ (DEFAULT_FMT == FMT_OS2 ? " (default)" : ""));
+#endif
+#ifdef PPM_SUPPORTED
+ fprintf(stderr, " -pnm Select PBMPLUS (PPM/PGM) output format%s\n",
+ (DEFAULT_FMT == FMT_PPM ? " (default)" : ""));
+ fprintf(stderr, " -widepnm Select PBMPLUS (PPM/PGM) 12/16 bit output format\n");
+#endif
+#ifdef RLE_SUPPORTED
+ fprintf(stderr, " -rle Select Utah RLE output format%s\n",
+ (DEFAULT_FMT == FMT_RLE ? " (default)" : ""));
+#endif
+#ifdef TARGA_SUPPORTED
+ fprintf(stderr, " -targa Select Targa output format%s\n",
+ (DEFAULT_FMT == FMT_TARGA ? " (default)" : ""));
+#endif
+ fprintf(stderr, "Switches for advanced users:\n");
+#ifdef DCT_ISLOW_SUPPORTED
+ fprintf(stderr, " -dct int Use integer DCT method%s\n",
+ (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+ fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n",
+ (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ fprintf(stderr, " -dct float Use floating-point DCT method%s\n",
+ (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
+#endif
+ fprintf(stderr, " -dither fs Use F-S dithering (default)\n");
+ fprintf(stderr, " -dither none Don't use dithering in quantization\n");
+ fprintf(stderr, " -dither ordered Use ordered dither (medium speed, quality)\n");
+#ifdef QUANT_2PASS_SUPPORTED
+ fprintf(stderr, " -map FILE Map to colors used in named image file\n");
+#endif
+ fprintf(stderr, " -nosmooth Don't use high-quality upsampling\n");
+#ifdef QUANT_1PASS_SUPPORTED
+ fprintf(stderr, " -onepass Use 1-pass quantization (fast, low quality)\n");
+#endif
+ fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
+ fprintf(stderr, " -outfile name Specify name for output file\n");
+ fprintf(stderr, " -verbose or -debug Emit debug output\n");
+ exit(EXIT_FAILURE);
+}
+
+
+LOCAL(int)
+parse_switches (j_decompress_ptr cinfo, int argc, char **argv,
+ int last_file_arg_seen, boolean for_real)
+/* Parse optional switches.
+ * Returns argv[] index of first file-name argument (== argc if none).
+ * Any file names with indexes <= last_file_arg_seen are ignored;
+ * they have presumably been processed in a previous iteration.
+ * (Pass 0 for last_file_arg_seen on the first or only iteration.)
+ * for_real is FALSE on the first (dummy) pass; we may skip any expensive
+ * processing.
+ */
+{
+ int argn;
+ char * arg;
+
+ /* Set up default JPEG parameters. */
+ requested_fmt = DEFAULT_FMT; /* set default output file format */
+ outfilename = NULL;
+ cinfo->err->trace_level = 0;
+
+ /* Scan command line options, adjust parameters */
+
+ for (argn = 1; argn < argc; argn++) {
+ arg = argv[argn];
+ if (*arg != '-') {
+ /* Not a switch, must be a file name argument */
+ if (argn <= last_file_arg_seen) {
+ outfilename = NULL; /* -outfile applies to just one input file */
+ continue; /* ignore this name if previously processed */
+ }
+ break; /* else done parsing switches */
+ }
+ arg++; /* advance past switch marker character */
+
+ if (keymatch(arg, "bmp", 1)) {
+ /* BMP output format. */
+ requested_fmt = FMT_BMP;
+
+ } else if (keymatch(arg, "colors", 1) || keymatch(arg, "colours", 1) ||
+ keymatch(arg, "quantize", 1) || keymatch(arg, "quantise", 1)) {
+ /* Do color quantization. */
+ int val;
+
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (sscanf(argv[argn], "%d", &val) != 1)
+ usage();
+ cinfo->desired_number_of_colors = val;
+ cinfo->quantize_colors = TRUE;
+
+ } else if (keymatch(arg, "dct", 2)) {
+ /* Select IDCT algorithm. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (keymatch(argv[argn], "int", 1)) {
+ cinfo->dct_method = JDCT_ISLOW;
+ } else if (keymatch(argv[argn], "fast", 2)) {
+ cinfo->dct_method = JDCT_IFAST;
+ } else if (keymatch(argv[argn], "float", 2)) {
+ cinfo->dct_method = JDCT_FLOAT;
+ } else
+ usage();
+
+ } else if (keymatch(arg, "dither", 2)) {
+ /* Select dithering algorithm. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (keymatch(argv[argn], "fs", 2)) {
+ cinfo->dither_mode = JDITHER_FS;
+ } else if (keymatch(argv[argn], "none", 2)) {
+ cinfo->dither_mode = JDITHER_NONE;
+ } else if (keymatch(argv[argn], "ordered", 2)) {
+ cinfo->dither_mode = JDITHER_ORDERED;
+ } else
+ usage();
+
+ } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
+ /* Enable debug printouts. */
+ /* On first -d, print version identification */
+ static boolean printed_version = FALSE;
+
+ if (! printed_version) {
+ fprintf(stderr, "Independent JPEG Group's DJPEG, version %s\n%s\n",
+ JVERSION, JCOPYRIGHT);
+ printed_version = TRUE;
+ }
+ cinfo->err->trace_level++;
+
+ } else if (keymatch(arg, "fast", 1)) {
+ /* Select recommended processing options for quick-and-dirty output. */
+ cinfo->two_pass_quantize = FALSE;
+ cinfo->dither_mode = JDITHER_ORDERED;
+ if (! cinfo->quantize_colors) /* don't override an earlier -colors */
+ cinfo->desired_number_of_colors = 216;
+ cinfo->dct_method = JDCT_FASTEST;
+ cinfo->do_fancy_upsampling = FALSE;
+
+ } else if (keymatch(arg, "gif", 1)) {
+ /* GIF output format. */
+ requested_fmt = FMT_GIF;
+
+ } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
+ /* Force monochrome output. */
+ cinfo->out_color_space = JCS_GRAYSCALE;
+
+ } else if (keymatch(arg, "map", 3)) {
+ /* Quantize to a color map taken from an input file. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (for_real) { /* too expensive to do twice! */
+#ifdef QUANT_2PASS_SUPPORTED /* otherwise can't quantize to supplied map */
+ FILE * mapfile;
+
+ if ((mapfile = fopen(argv[argn], READ_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
+ exit(EXIT_FAILURE);
+ }
+ read_color_map(cinfo, mapfile);
+ fclose(mapfile);
+ cinfo->quantize_colors = TRUE;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ }
+
+ } else if (keymatch(arg, "maxmemory", 3)) {
+ /* Maximum memory in Kb (or Mb with 'm'). */
+ long lval;
+ char ch = 'x';
+
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
+ usage();
+ if (ch == 'm' || ch == 'M')
+ lval *= 1000L;
+ cinfo->mem->max_memory_to_use = lval * 1000L;
+
+ } else if (keymatch(arg, "nosmooth", 3)) {
+ /* Suppress fancy upsampling */
+ cinfo->do_fancy_upsampling = FALSE;
+
+ } else if (keymatch(arg, "onepass", 3)) {
+ /* Use fast one-pass quantization. */
+ cinfo->two_pass_quantize = FALSE;
+
+ } else if (keymatch(arg, "os2", 3)) {
+ /* BMP output format (OS/2 flavor). */
+ requested_fmt = FMT_OS2;
+
+ } else if (keymatch(arg, "outfile", 4)) {
+ /* Set output file name. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ outfilename = argv[argn]; /* save it away for later use */
+
+ } else if (keymatch(arg, "pnm", 1) || keymatch(arg, "ppm", 1)) {
+ /* PPM/PGM output format. */
+ requested_fmt = FMT_PPM;
+
+ } else if (keymatch(arg, "widepnm", 1) || keymatch(arg, "wideppm", 1)) {
+ /* PPM/PGM 12/16 bit output format. */
+ requested_fmt = FMT_PPMW;
+
+ } else if (keymatch(arg, "rle", 1)) {
+ /* RLE output format. */
+ requested_fmt = FMT_RLE;
+
+ } else if (keymatch(arg, "scale", 1)) {
+ /* Scale the output image by a fraction M/N. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (sscanf(argv[argn], "%d/%d",
+ &cinfo->scale_num, &cinfo->scale_denom) != 2)
+ usage();
+
+ } else if (keymatch(arg, "targa", 1)) {
+ /* Targa output format. */
+ requested_fmt = FMT_TARGA;
+
+ } else {
+ usage(); /* bogus switch */
+ }
+ }
+
+ return argn; /* return index of next arg (file name) */
+}
+
+
+/*
+ * Marker processor for COM and interesting APPn markers.
+ * This replaces the library's built-in processor, which just skips the marker.
+ * We want to print out the marker as text, to the extent possible.
+ * Note this code relies on a non-suspending data source.
+ */
+
+LOCAL(unsigned int)
+jpeg_getc (j_decompress_ptr cinfo)
+/* Read next byte */
+{
+ struct jpeg_source_mgr * datasrc = cinfo->src;
+
+ if (datasrc->bytes_in_buffer == 0) {
+ if (! (*datasrc->fill_input_buffer) (cinfo))
+ ERREXIT(cinfo, JERR_CANT_SUSPEND);
+ }
+ datasrc->bytes_in_buffer--;
+ return GETJOCTET(*datasrc->next_input_byte++);
+}
+
+
+METHODDEF(boolean)
+print_text_marker (j_decompress_ptr cinfo)
+{
+ boolean traceit = (cinfo->err->trace_level >= 1);
+ 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 */
+
+ if (traceit) {
+ if (cinfo->unread_marker == JPEG_COM)
+ fprintf(stderr, "Comment, length %ld:\n", (long) length);
+ else /* assume it is an APPn otherwise */
+ fprintf(stderr, "APP%d, length %ld:\n",
+ cinfo->unread_marker - JPEG_APP0, (long) length);
+ }
+
+ while (--length >= 0) {
+ ch = jpeg_getc(cinfo);
+ if (traceit) {
+ /* 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 newline.
+ */
+ if (ch == '\r') {
+ fprintf(stderr, "\n");
+ } else if (ch == '\n') {
+ if (lastch != '\r')
+ fprintf(stderr, "\n");
+ } else if (ch == '\\') {
+ fprintf(stderr, "\\\\");
+ } else if (isprint(ch)) {
+ putc(ch, stderr);
+ } else {
+ fprintf(stderr, "\\%03o", ch);
+ }
+ lastch = ch;
+ }
+ }
+
+ if (traceit)
+ fprintf(stderr, "\n");
+
+ return TRUE;
+}
+
+
+/*
+ * The main program.
+ */
+
+int
+main (int argc, char **argv)
+{
+ struct jpeg_decompress_struct cinfo;
+ struct jpeg_error_mgr jerr;
+#ifdef PROGRESS_REPORT
+ struct cdjpeg_progress_mgr progress;
+#endif
+ int file_index;
+ djpeg_dest_ptr dest_mgr = NULL;
+ FILE * input_file;
+ FILE * output_file;
+ JDIMENSION num_scanlines;
+
+ /* On Mac, fetch a command line. */
+#ifdef USE_CCOMMAND
+ argc = ccommand(&argv);
+#endif
+
+ progname = argv[0];
+ if (progname == NULL || progname[0] == 0)
+ progname = "djpeg"; /* in case C library doesn't provide it */
+
+ /* Initialize the JPEG decompression object with default error handling. */
+ cinfo.err = jpeg_std_error(&jerr);
+ jpeg_create_decompress(&cinfo);
+ /* Add some application-specific error messages (from cderror.h) */
+ jerr.addon_message_table = cdjpeg_message_table;
+ jerr.first_addon_message = JMSG_FIRSTADDONCODE;
+ jerr.last_addon_message = JMSG_LASTADDONCODE;
+
+ /* Insert custom marker processor for COM and APP12.
+ * APP12 is used by some digital camera makers for textual info,
+ * so we provide the ability to display it as text.
+ * If you like, additional APPn marker types can be selected for display,
+ * but don't try to override APP0 or APP14 this way (see libjpeg.doc).
+ */
+ jpeg_set_marker_processor(&cinfo, JPEG_COM, print_text_marker);
+ jpeg_set_marker_processor(&cinfo, JPEG_APP0+12, print_text_marker);
+
+ /* Now safe to enable signal catcher. */
+#ifdef NEED_SIGNAL_CATCHER
+ enable_signal_catcher((j_common_ptr) &cinfo);
+#endif
+
+ /* Scan command line to find file names. */
+ /* It is convenient to use just one switch-parsing routine, but the switch
+ * values read here are ignored; we will rescan the switches after opening
+ * the input file.
+ * (Exception: tracing level set here controls verbosity for COM markers
+ * found during jpeg_read_header...)
+ */
+
+ file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
+
+#ifdef TWO_FILE_COMMANDLINE
+ /* Must have either -outfile switch or explicit output file name */
+ if (outfilename == NULL) {
+ if (file_index != argc-2) {
+ fprintf(stderr, "%s: must name one input and one output file\n",
+ progname);
+ usage();
+ }
+ outfilename = argv[file_index+1];
+ } else {
+ if (file_index != argc-1) {
+ fprintf(stderr, "%s: must name one input and one output file\n",
+ progname);
+ usage();
+ }
+ }
+#else
+ /* Unix style: expect zero or one file name */
+ if (file_index < argc-1) {
+ fprintf(stderr, "%s: only one input file\n", progname);
+ usage();
+ }
+#endif /* TWO_FILE_COMMANDLINE */
+
+ /* Open the input file. */
+ if (file_index < argc) {
+ if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ /* default input file is stdin */
+ input_file = read_stdin();
+ }
+
+ /* Open the output file. */
+ if (outfilename != NULL) {
+ if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ /* default output file is stdout */
+ output_file = write_stdout();
+ }
+
+#ifdef PROGRESS_REPORT
+ start_progress_monitor((j_common_ptr) &cinfo, &progress);
+#endif
+
+ /* Specify data source for decompression */
+ jpeg_stdio_src(&cinfo, input_file);
+
+ /* Read file header, set default decompression parameters */
+ (void) jpeg_read_header(&cinfo, TRUE);
+
+ /* Adjust default decompression parameters by re-parsing the options */
+ file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
+
+ /* Initialize the output module now to let it override any crucial
+ * option settings (for instance, GIF wants to force color quantization).
+ */
+ cinfo.data_precision_other = 8;
+ cinfo.shft = 0;
+ switch (requested_fmt) {
+#ifdef BMP_SUPPORTED
+ case FMT_BMP:
+ dest_mgr = jinit_write_bmp(&cinfo, FALSE);
+ break;
+ case FMT_OS2:
+ dest_mgr = jinit_write_bmp(&cinfo, TRUE);
+ break;
+#endif
+#ifdef GIF_SUPPORTED
+ case FMT_GIF:
+ dest_mgr = jinit_write_gif(&cinfo);
+ break;
+#endif
+#ifdef PPM_SUPPORTED
+ case FMT_PPMW:
+ cinfo.data_precision_other = cinfo.data_precision;
+ case FMT_PPM:
+ dest_mgr = jinit_write_ppm(&cinfo);
+ break;
+#endif
+#ifdef RLE_SUPPORTED
+ case FMT_RLE:
+ dest_mgr = jinit_write_rle(&cinfo);
+ break;
+#endif
+#ifdef TARGA_SUPPORTED
+ case FMT_TARGA:
+ dest_mgr = jinit_write_targa(&cinfo);
+ break;
+#endif
+ default:
+ ERREXIT(&cinfo, JERR_UNSUPPORTED_FORMAT);
+ break;
+ }
+ if (cinfo.data_precision_other <= 8)
+ if (cinfo.process != JPROC_LOSSLESS) /* Lossless scales itself. */
+ cinfo.shft = cinfo.data_precision - cinfo.data_precision_other;
+ dest_mgr->output_file = output_file;
+
+ /* Start decompressor */
+ (void) jpeg_start_decompress(&cinfo);
+
+ /* Write output file header */
+ (*dest_mgr->start_output) (&cinfo, dest_mgr);
+
+ /* Process data */
+ while (cinfo.output_scanline < cinfo.output_height) {
+ num_scanlines = jpeg_read_scanlines(&cinfo,(JSAMPARRAY) dest_mgr->buffer,
+ dest_mgr->buffer_height);
+ (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
+ }
+
+#ifdef PROGRESS_REPORT
+ /* Hack: count final pass as done in case finish_output does an extra pass.
+ * The library won't have updated completed_passes.
+ */
+ progress.pub.completed_passes = progress.pub.total_passes;
+#endif
+
+ /* Finish decompression and release memory.
+ * I must do it in this order because output module has allocated memory
+ * of lifespan JPOOL_IMAGE; it needs to finish before releasing memory.
+ */
+ (*dest_mgr->finish_output) (&cinfo, dest_mgr);
+ (void) jpeg_finish_decompress(&cinfo);
+ jpeg_destroy_decompress(&cinfo);
+
+ /* Close files, if we opened them */
+ if (input_file != stdin)
+ fclose(input_file);
+ if (output_file != stdout)
+ fclose(output_file);
+
+#ifdef PROGRESS_REPORT
+ end_progress_monitor((j_common_ptr) &cinfo);
+#endif
+
+ /* All done. */
+ exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
+ return 0; /* suppress no-return-value warnings */
+}
diff --git a/jpeg-6c/example.c b/jpeg-6c/example.c
new file mode 100644
index 0000000..7fc354f
--- /dev/null
+++ b/jpeg-6c/example.c
@@ -0,0 +1,433 @@
+/*
+ * example.c
+ *
+ * This file illustrates how to use the IJG code as a subroutine library
+ * to read or write JPEG image files. You should look at this code in
+ * conjunction with the documentation file libjpeg.doc.
+ *
+ * This code will not do anything useful as-is, but it may be helpful as a
+ * skeleton for constructing routines that call the JPEG library.
+ *
+ * We present these routines in the same coding style used in the JPEG code
+ * (ANSI function definitions, etc); but you are of course free to code your
+ * routines in a different style if you prefer.
+ */
+
+#include <stdio.h>
+
+/*
+ * Include file for users of JPEG library.
+ * You will need to have included system headers that define at least
+ * the typedefs FILE and size_t before you can include jpeglib.h.
+ * (stdio.h is sufficient on ANSI-conforming systems.)
+ * You may also wish to include "jerror.h".
+ */
+
+#include "jpeglib.h"
+
+/*
+ * <setjmp.h> is used for the optional error recovery mechanism shown in
+ * the second part of the example.
+ */
+
+#include <setjmp.h>
+
+
+
+/******************** JPEG COMPRESSION SAMPLE INTERFACE *******************/
+
+/* This half of the example shows how to feed data into the JPEG compressor.
+ * We present a minimal version that does not worry about refinements such
+ * as error recovery (the JPEG code will just exit() if it gets an error).
+ */
+
+
+/*
+ * IMAGE DATA FORMATS:
+ *
+ * The standard input image format is a rectangular array of pixels, with
+ * each pixel having the same number of "component" values (color channels).
+ * Each pixel row is an array of JSAMPLEs (which typically are unsigned chars).
+ * If you are working with color data, then the color values for each pixel
+ * must be adjacent in the row; for example, R,G,B,R,G,B,R,G,B,... for 24-bit
+ * RGB color.
+ *
+ * For this example, we'll assume that this data structure matches the way
+ * our application has stored the image in memory, so we can just pass a
+ * pointer to our image buffer. In particular, let's say that the image is
+ * RGB color and is described by:
+ */
+
+extern JSAMPLE * image_buffer; /* Points to large array of R,G,B-order data */
+extern int image_height; /* Number of rows in image */
+extern int image_width; /* Number of columns in image */
+
+
+/*
+ * Sample routine for JPEG compression. We assume that the target file name
+ * and a compression quality factor are passed in.
+ */
+
+GLOBAL(void)
+write_JPEG_file (char * filename, int quality)
+{
+ /* This struct contains the JPEG compression parameters and pointers to
+ * working space (which is allocated as needed by the JPEG library).
+ * It is possible to have several such structures, representing multiple
+ * compression/decompression processes, in existence at once. We refer
+ * to any one struct (and its associated working data) as a "JPEG object".
+ */
+ struct jpeg_compress_struct cinfo;
+ /* This struct represents a JPEG error handler. It is declared separately
+ * because applications often want to supply a specialized error handler
+ * (see the second half of this file for an example). But here we just
+ * take the easy way out and use the standard error handler, which will
+ * print a message on stderr and call exit() if compression fails.
+ * Note that this struct must live as long as the main JPEG parameter
+ * struct, to avoid dangling-pointer problems.
+ */
+ struct jpeg_error_mgr jerr;
+ /* More stuff */
+ FILE * outfile; /* target file */
+ JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
+ int row_stride; /* physical row width in image buffer */
+
+ /* Step 1: allocate and initialize JPEG compression object */
+
+ /* We have to set up the error handler first, in case the initialization
+ * step fails. (Unlikely, but it could happen if you are out of memory.)
+ * This routine fills in the contents of struct jerr, and returns jerr's
+ * address which we place into the link field in cinfo.
+ */
+ cinfo.err = jpeg_std_error(&jerr);
+ /* Now we can initialize the JPEG compression object. */
+ jpeg_create_compress(&cinfo);
+
+ /* Step 2: specify data destination (eg, a file) */
+ /* Note: steps 2 and 3 can be done in either order. */
+
+ /* Here we use the library-supplied code to send compressed data to a
+ * stdio stream. You can also write your own code to do something else.
+ * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
+ * requires it in order to write binary files.
+ */
+ if ((outfile = fopen(filename, "wb")) == NULL) {
+ fprintf(stderr, "can't open %s\n", filename);
+ exit(1);
+ }
+ jpeg_stdio_dest(&cinfo, outfile);
+
+ /* Step 3: set parameters for compression */
+
+ /* First we supply a description of the input image.
+ * Four fields of the cinfo struct must be filled in:
+ */
+ cinfo.image_width = image_width; /* image width and height, in pixels */
+ cinfo.image_height = image_height;
+ cinfo.input_components = 3; /* # of color components per pixel */
+ cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
+ /* Now use the library's routine to set default compression parameters.
+ * (You must set at least cinfo.in_color_space before calling this,
+ * since the defaults depend on the source color space.)
+ */
+ jpeg_set_defaults(&cinfo);
+ /* Now you can set any non-default parameters you wish to.
+ * Here we just illustrate the use of quality (quantization table) scaling:
+ */
+ jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
+
+ /* Step 4: Start compressor */
+
+ /* TRUE ensures that we will write a complete interchange-JPEG file.
+ * Pass TRUE unless you are very sure of what you're doing.
+ */
+ jpeg_start_compress(&cinfo, TRUE);
+
+ /* Step 5: while (scan lines remain to be written) */
+ /* jpeg_write_scanlines(...); */
+
+ /* Here we use the library's state variable cinfo.next_scanline as the
+ * loop counter, so that we don't have to keep track ourselves.
+ * To keep things simple, we pass one scanline per call; you can pass
+ * more if you wish, though.
+ */
+ row_stride = image_width * 3; /* JSAMPLEs per row in image_buffer */
+
+ while (cinfo.next_scanline < cinfo.image_height) {
+ /* jpeg_write_scanlines expects an array of pointers to scanlines.
+ * Here the array is only one element long, but you could pass
+ * more than one scanline at a time if that's more convenient.
+ */
+ row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
+ (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
+ }
+
+ /* Step 6: Finish compression */
+
+ jpeg_finish_compress(&cinfo);
+ /* After finish_compress, we can close the output file. */
+ fclose(outfile);
+
+ /* Step 7: release JPEG compression object */
+
+ /* This is an important step since it will release a good deal of memory. */
+ jpeg_destroy_compress(&cinfo);
+
+ /* And we're done! */
+}
+
+
+/*
+ * SOME FINE POINTS:
+ *
+ * In the above loop, we ignored the return value of jpeg_write_scanlines,
+ * which is the number of scanlines actually written. We could get away
+ * with this because we were only relying on the value of cinfo.next_scanline,
+ * which will be incremented correctly. If you maintain additional loop
+ * variables then you should be careful to increment them properly.
+ * Actually, for output to a stdio stream you needn't worry, because
+ * then jpeg_write_scanlines will write all the lines passed (or else exit
+ * with a fatal error). Partial writes can only occur if you use a data
+ * destination module that can demand suspension of the compressor.
+ * (If you don't know what that's for, you don't need it.)
+ *
+ * If the compressor requires full-image buffers (for entropy-coding
+ * optimization or a multi-scan JPEG file), it will create temporary
+ * files for anything that doesn't fit within the maximum-memory setting.
+ * (Note that temp files are NOT needed if you use the default parameters.)
+ * On some systems you may need to set up a signal handler to ensure that
+ * temporary files are deleted if the program is interrupted. See libjpeg.doc.
+ *
+ * Scanlines MUST be supplied in top-to-bottom order if you want your JPEG
+ * files to be compatible with everyone else's. If you cannot readily read
+ * your data in that order, you'll need an intermediate array to hold the
+ * image. See rdtarga.c or rdbmp.c for examples of handling bottom-to-top
+ * source data using the JPEG code's internal virtual-array mechanisms.
+ */
+
+
+
+/******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/
+
+/* This half of the example shows how to read data from the JPEG decompressor.
+ * It's a bit more refined than the above, in that we show:
+ * (a) how to modify the JPEG library's standard error-reporting behavior;
+ * (b) how to allocate workspace using the library's memory manager.
+ *
+ * Just to make this example a little different from the first one, we'll
+ * assume that we do not intend to put the whole image into an in-memory
+ * buffer, but to send it line-by-line someplace else. We need a one-
+ * scanline-high JSAMPLE array as a work buffer, and we will let the JPEG
+ * memory manager allocate it for us. This approach is actually quite useful
+ * because we don't need to remember to deallocate the buffer separately: it
+ * will go away automatically when the JPEG object is cleaned up.
+ */
+
+
+/*
+ * ERROR HANDLING:
+ *
+ * The JPEG library's standard error handler (jerror.c) is divided into
+ * several "methods" which you can override individually. This lets you
+ * adjust the behavior without duplicating a lot of code, which you might
+ * have to update with each future release.
+ *
+ * Our example here shows how to override the "error_exit" method so that
+ * control is returned to the library's caller when a fatal error occurs,
+ * rather than calling exit() as the standard error_exit method does.
+ *
+ * We use C's setjmp/longjmp facility to return control. This means that the
+ * routine which calls the JPEG library must first execute a setjmp() call to
+ * establish the return point. We want the replacement error_exit to do a
+ * longjmp(). But we need to make the setjmp buffer accessible to the
+ * error_exit routine. To do this, we make a private extension of the
+ * standard JPEG error handler object. (If we were using C++, we'd say we
+ * were making a subclass of the regular error handler.)
+ *
+ * Here's the extended error handler struct:
+ */
+
+struct my_error_mgr {
+ struct jpeg_error_mgr pub; /* "public" fields */
+
+ jmp_buf setjmp_buffer; /* for return to caller */
+};
+
+typedef struct my_error_mgr * my_error_ptr;
+
+/*
+ * Here's the routine that will replace the standard error_exit method:
+ */
+
+METHODDEF(void)
+my_error_exit (j_common_ptr cinfo)
+{
+ /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
+ my_error_ptr myerr = (my_error_ptr) cinfo->err;
+
+ /* Always display the message. */
+ /* We could postpone this until after returning, if we chose. */
+ (*cinfo->err->output_message) (cinfo);
+
+ /* Return control to the setjmp point */
+ longjmp(myerr->setjmp_buffer, 1);
+}
+
+
+/*
+ * Sample routine for JPEG decompression. We assume that the source file name
+ * is passed in. We want to return 1 on success, 0 on error.
+ */
+
+
+GLOBAL(int)
+read_JPEG_file (char * filename)
+{
+ /* This struct contains the JPEG decompression parameters and pointers to
+ * working space (which is allocated as needed by the JPEG library).
+ */
+ struct jpeg_decompress_struct cinfo;
+ /* We use our private extension JPEG error handler.
+ * Note that this struct must live as long as the main JPEG parameter
+ * struct, to avoid dangling-pointer problems.
+ */
+ struct my_error_mgr jerr;
+ /* More stuff */
+ FILE * infile; /* source file */
+ JSAMPARRAY buffer; /* Output row buffer */
+ int row_stride; /* physical row width in output buffer */
+
+ /* In this example we want to open the input file before doing anything else,
+ * so that the setjmp() error recovery below can assume the file is open.
+ * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
+ * requires it in order to read binary files.
+ */
+
+ if ((infile = fopen(filename, "rb")) == NULL) {
+ fprintf(stderr, "can't open %s\n", filename);
+ return 0;
+ }
+
+ /* Step 1: allocate and initialize JPEG decompression object */
+
+ /* We set up the normal JPEG error routines, then override error_exit. */
+ cinfo.err = jpeg_std_error(&jerr.pub);
+ jerr.pub.error_exit = my_error_exit;
+ /* Establish the setjmp return context for my_error_exit to use. */
+ if (setjmp(jerr.setjmp_buffer)) {
+ /* If we get here, the JPEG code has signaled an error.
+ * We need to clean up the JPEG object, close the input file, and return.
+ */
+ jpeg_destroy_decompress(&cinfo);
+ fclose(infile);
+ return 0;
+ }
+ /* Now we can initialize the JPEG decompression object. */
+ jpeg_create_decompress(&cinfo);
+
+ /* Step 2: specify data source (eg, a file) */
+
+ jpeg_stdio_src(&cinfo, infile);
+
+ /* Step 3: read file parameters with jpeg_read_header() */
+
+ (void) jpeg_read_header(&cinfo, TRUE);
+ /* We can ignore the return value from jpeg_read_header since
+ * (a) suspension is not possible with the stdio data source, and
+ * (b) we passed TRUE to reject a tables-only JPEG file as an error.
+ * See libjpeg.doc for more info.
+ */
+
+ /* Step 4: set parameters for decompression */
+
+ /* In this example, we don't need to change any of the defaults set by
+ * jpeg_read_header(), so we do nothing here.
+ */
+
+ /* Step 5: Start decompressor */
+
+ (void) jpeg_start_decompress(&cinfo);
+ /* We can ignore the return value since suspension is not possible
+ * with the stdio data source.
+ */
+
+ /* We may need to do some setup of our own at this point before reading
+ * the data. After jpeg_start_decompress() we have the correct scaled
+ * output image dimensions available, as well as the output colormap
+ * if we asked for color quantization.
+ * In this example, we need to make an output work buffer of the right size.
+ */
+ /* JSAMPLEs per row in output buffer */
+ row_stride = cinfo.output_width * cinfo.output_components;
+ /* Make a one-row-high sample array that will go away when done with image */
+ buffer = (*cinfo.mem->alloc_sarray)
+ ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
+
+ /* Step 6: while (scan lines remain to be read) */
+ /* jpeg_read_scanlines(...); */
+
+ /* Here we use the library's state variable cinfo.output_scanline as the
+ * loop counter, so that we don't have to keep track ourselves.
+ */
+ while (cinfo.output_scanline < cinfo.output_height) {
+ /* jpeg_read_scanlines expects an array of pointers to scanlines.
+ * Here the array is only one element long, but you could ask for
+ * more than one scanline at a time if that's more convenient.
+ */
+ (void) jpeg_read_scanlines(&cinfo, buffer, 1);
+ /* Assume put_scanline_someplace wants a pointer and sample count. */
+ put_scanline_someplace(buffer[0], row_stride);
+ }
+
+ /* Step 7: Finish decompression */
+
+ (void) jpeg_finish_decompress(&cinfo);
+ /* We can ignore the return value since suspension is not possible
+ * with the stdio data source.
+ */
+
+ /* Step 8: Release JPEG decompression object */
+
+ /* This is an important step since it will release a good deal of memory. */
+ jpeg_destroy_decompress(&cinfo);
+
+ /* After finish_decompress, we can close the input file.
+ * Here we postpone it until after no more JPEG errors are possible,
+ * so as to simplify the setjmp error logic above. (Actually, I don't
+ * think that jpeg_destroy can do an error exit, but why assume anything...)
+ */
+ fclose(infile);
+
+ /* At this point you may want to check to see whether any corrupt-data
+ * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
+ */
+
+ /* And we're done! */
+ return 1;
+}
+
+
+/*
+ * SOME FINE POINTS:
+ *
+ * In the above code, we ignored the return value of jpeg_read_scanlines,
+ * which is the number of scanlines actually read. We could get away with
+ * this because we asked for only one line at a time and we weren't using
+ * a suspending data source. See libjpeg.doc for more info.
+ *
+ * We cheated a bit by calling alloc_sarray() after jpeg_start_decompress();
+ * we should have done it beforehand to ensure that the space would be
+ * counted against the JPEG max_memory setting. In some systems the above
+ * code would risk an out-of-memory error. However, in general we don't
+ * know the output image dimensions before jpeg_start_decompress(), unless we
+ * call jpeg_calc_output_dimensions(). See libjpeg.doc for more about this.
+ *
+ * Scanlines are returned in the same order as they appear in the JPEG file,
+ * which is standardly top-to-bottom. If you must emit data bottom-to-top,
+ * you can use one of the virtual arrays provided by the JPEG memory manager
+ * to invert the data. See wrbmp.c for an example.
+ *
+ * As with compression, some operating modes may require temporary files.
+ * On some systems you may need to set up a signal handler to ensure that
+ * temporary files are deleted if the program is interrupted. See libjpeg.doc.
+ */
diff --git a/jpeg-6c/filelist.doc b/jpeg-6c/filelist.doc
new file mode 100644
index 0000000..9ba88e0
--- /dev/null
+++ b/jpeg-6c/filelist.doc
@@ -0,0 +1,239 @@
+IJG JPEG LIBRARY: FILE LIST
+
+Copyright (C) 1994-1997, Thomas G. Lane.
+This file is part of the Independent JPEG Group's software.
+For conditions of distribution and use, see the accompanying README file.
+
+
+Here is a road map to the files in the IJG JPEG distribution. The
+distribution includes the JPEG library proper, plus two application
+programs ("cjpeg" and "djpeg") which use the library to convert JPEG
+files to and from some other popular image formats. A third application
+"jpegtran" uses the library to do lossless conversion between different
+variants of JPEG. There are also two stand-alone applications,
+"rdjpgcom" and "wrjpgcom".
+
+
+THE JPEG LIBRARY
+================
+
+Include files:
+
+jpeglib.h JPEG library's exported data and function declarations.
+jconfig.h Configuration declarations. Note: this file is not present
+ in the distribution; it is generated during installation.
+jmorecfg.h Additional configuration declarations; need not be changed
+ for a standard installation.
+jerror.h Declares JPEG library's error and trace message codes.
+jinclude.h Central include file used by all IJG .c files to reference
+ system include files.
+jpegint.h JPEG library's internal data structures.
+jlossls.h JPEG library's lossless codec data structures.
+jlossy.h JPEG library's lossy codec structures.
+jchuff.h Private declarations for Huffman encoder modules.
+jdhuff.h Private declarations for Huffman decoder modules.
+jdct.h Private declarations for forward & reverse DCT subsystems.
+jmemsys.h Private declarations for memory management subsystem.
+jversion.h Version information.
+
+Applications using the library should include jpeglib.h (which in turn
+includes jconfig.h and jmorecfg.h). Optionally, jerror.h may be included
+if the application needs to reference individual JPEG error codes. The
+other include files are intended for internal use and would not normally
+be included by an application program. (cjpeg/djpeg/etc do use jinclude.h,
+since its function is to improve portability of the whole IJG distribution.
+Most other applications will directly include the system include files they
+want, and hence won't need jinclude.h.)
+
+
+C source code files:
+
+These files contain most of the functions intended to be called directly by
+an application program:
+
+jcapimin.c Application program interface: core routines for compression.
+jcapistd.c Application program interface: standard compression.
+jdapimin.c Application program interface: core routines for decompression.
+jdapistd.c Application program interface: standard decompression.
+jcomapi.c Application program interface routines common to compression
+ and decompression.
+jcparam.c Compression parameter setting helper routines.
+jctrans.c API and library routines for transcoding compression.
+jdtrans.c API and library routines for transcoding decompression.
+
+Compression side of the library:
+
+jcinit.c Initialization: determines which other modules to use.
+jcmaster.c Master control: setup and inter-pass sequencing logic.
+jcmainct.c Main buffer controller (preprocessor => JPEG compressor).
+jchuff.c Codec-independent Huffman entropy encoding routines.
+jcprepct.c Preprocessor buffer controller.
+jccolor.c Color space conversion.
+jcsample.c Downsampling.
+jcmarker.c JPEG marker writing.
+jdatadst.c Data destination manager for stdio output.
+
+Lossy (DCT) codec:
+
+jlossy.c Lossy compressor proper.
+jccoefct.c Buffer controller for DCT coefficient buffer.
+jcdctmgr.c DCT manager (DCT implementation selection & control).
+jfdctint.c Forward DCT using slow-but-accurate integer method.
+jfdctfst.c Forward DCT using faster, less accurate integer method.
+jfdctflt.c Forward DCT using floating-point arithmetic.
+jcshuff.c Huffman entropy coding for sequential JPEG.
+jcphuff.c Huffman entropy coding for progressive JPEG.
+
+Lossless (spatial) codec:
+
+jclossls.c Lossless compressor proper.
+jcdiffct.c Buffer controller for difference buffer.
+jcscale.c Point transformation.
+jcpred.c Sample predictor and differencer.
+jclhuff.c Huffman entropy encoding for lossless JPEG.
+
+Decompression side of the library:
+
+jdmaster.c Master control: determines which other modules to use.
+jdinput.c Input controller: controls input processing modules.
+jdmainct.c Main buffer controller (JPEG decompressor => postprocessor).
+jdhuff.c Codec-independent Huffman entropy decoding routines.
+jdpostct.c Postprocessor buffer controller.
+jdmarker.c JPEG marker reading.
+jdsample.c Upsampling.
+jdcolor.c Color space conversion.
+jdmerge.c Merged upsampling/color conversion (faster, lower quality).
+jquant1.c One-pass color quantization using a fixed-spacing colormap.
+jquant2.c Two-pass color quantization using a custom-generated colormap.
+ Also handles one-pass quantization to an externally given map.
+jdatasrc.c Data source manager for stdio input.
+
+Lossy (DCT) codec:
+
+jdlossy.c Lossy decompressor proper.
+jdcoefct.c Buffer controller for DCT coefficient buffer.
+jdshuff.c Huffman entropy decoding for sequential JPEG.
+jdphuff.c Huffman entropy decoding for progressive JPEG.
+jddctmgr.c IDCT manager (IDCT implementation selection & control).
+jidctint.c Inverse DCT using slow-but-accurate integer method.
+jidctfst.c Inverse DCT using faster, less accurate integer method.
+jidctflt.c Inverse DCT using floating-point arithmetic.
+jidctred.c Inverse DCTs with reduced-size outputs.
+
+Lossless (spatial) codec:
+
+jdlossls.c Lossless decompressor proper.
+jddiffct.c Buffer controller for difference buffers.
+jdlhuff.c Huffman entropy decoding for lossless JPEG.
+jdpred.c Sample predictor and undifferencer.
+jdscale.c Point transformation, sample size scaling.
+
+Support files for both compression and decompression:
+
+jerror.c Standard error handling routines (application replaceable).
+jmemmgr.c System-independent (more or less) memory management code.
+jcodec.c Codec-independent utility routines.
+jutils.c Miscellaneous utility routines.
+
+jmemmgr.c relies on a system-dependent memory management module. The IJG
+distribution includes the following implementations of the system-dependent
+module:
+
+jmemnobs.c "No backing store": assumes adequate virtual memory exists.
+jmemansi.c Makes temporary files with ANSI-standard routine tmpfile().
+jmemname.c Makes temporary files with program-generated file names.
+jmemdos.c Custom implementation for MS-DOS (16-bit environment only):
+ can use extended and expanded memory as well as temp files.
+jmemmac.c Custom implementation for Apple Macintosh.
+
+Exactly one of the system-dependent modules should be configured into an
+installed JPEG library (see install.doc for hints about which one to use).
+On unusual systems you may find it worthwhile to make a special
+system-dependent memory manager.
+
+
+Non-C source code files:
+
+jmemdosa.asm 80x86 assembly code support for jmemdos.c; used only in
+ MS-DOS-specific configurations of the JPEG library.
+
+
+CJPEG/DJPEG/JPEGTRAN
+====================
+
+Include files:
+
+cdjpeg.h Declarations shared by cjpeg/djpeg/jpegtran modules.
+cderror.h Additional error and trace message codes for cjpeg et al.
+transupp.h Declarations for jpegtran support routines in transupp.c.
+
+C source code files:
+
+cjpeg.c Main program for cjpeg.
+djpeg.c Main program for djpeg.
+jpegtran.c Main program for jpegtran.
+cdjpeg.c Utility routines used by all three programs.
+rdcolmap.c Code to read a colormap file for djpeg's "-map" switch.
+rdswitch.c Code to process some of cjpeg's more complex switches.
+ Also used by jpegtran.
+transupp.c Support code for jpegtran: lossless image manipulations.
+
+Image file reader modules for cjpeg:
+
+rdbmp.c BMP file input.
+rdgif.c GIF file input (now just a stub).
+rdppm.c PPM/PGM file input.
+rdrle.c Utah RLE file input.
+rdtarga.c Targa file input.
+
+Image file writer modules for djpeg:
+
+wrbmp.c BMP file output.
+wrgif.c GIF file output (a mere shadow of its former self).
+wrppm.c PPM/PGM file output.
+wrrle.c Utah RLE file output.
+wrtarga.c Targa file output.
+
+
+RDJPGCOM/WRJPGCOM
+=================
+
+C source code files:
+
+rdjpgcom.c Stand-alone rdjpgcom application.
+wrjpgcom.c Stand-alone wrjpgcom application.
+
+These programs do not depend on the IJG library. They do use
+jconfig.h and jinclude.h, only to improve portability.
+
+
+ADDITIONAL FILES
+================
+
+Documentation (see README for a guide to the documentation files):
+
+README Master documentation file.
+*.doc Other documentation files.
+*.1 Documentation in Unix man page format.
+change.log Version-to-version change highlights.
+example.c Sample code for calling JPEG library.
+
+Configuration/installation files and programs (see install.doc for more info):
+
+configure Unix shell script to perform automatic configuration.
+ltconfig Support scripts for configure (from GNU libtool).
+ltmain.sh
+config.guess
+config.sub
+install-sh Install shell script for those Unix systems lacking one.
+ckconfig.c Program to generate jconfig.h on non-Unix systems.
+jconfig.doc Template for making jconfig.h by hand.
+makefile.* Sample makefiles for particular systems.
+jconfig.* Sample jconfig.h for particular systems.
+ansi2knr.c De-ANSIfier for pre-ANSI C compilers (courtesy of
+ L. Peter Deutsch and Aladdin Enterprises).
+
+Test files (see install.doc for test procedure):
+
+test*.* Source and comparison files for confidence test.
+ These are binary image files, NOT text files.
diff --git a/jpeg-6c/install-sh b/jpeg-6c/install-sh
new file mode 100644
index 0000000..e843669
--- /dev/null
+++ b/jpeg-6c/install-sh
@@ -0,0 +1,250 @@
+#!/bin/sh
+#
+# install - install a program, script, or datafile
+# This comes from X11R5 (mit/util/scripts/install.sh).
+#
+# Copyright 1991 by the Massachusetts Institute of Technology
+#
+# Permission to use, copy, modify, distribute, and sell this software and its
+# documentation for any purpose is hereby granted without fee, provided that
+# the above copyright notice appear in all copies and that both that
+# copyright notice and this permission notice appear in supporting
+# documentation, and that the name of M.I.T. not be used in advertising or
+# publicity pertaining to distribution of the software without specific,
+# written prior permission. M.I.T. makes no representations about the
+# suitability of this software for any purpose. It is provided "as is"
+# without express or implied warranty.
+#
+# Calling this script install-sh is preferred over install.sh, to prevent
+# `make' implicit rules from creating a file called install from it
+# when there is no Makefile.
+#
+# This script is compatible with the BSD install script, but was written
+# from scratch. It can only install one file at a time, a restriction
+# shared with many OS's install programs.
+
+
+# set DOITPROG to echo to test this script
+
+# Don't use :- since 4.3BSD and earlier shells don't like it.
+doit="${DOITPROG-}"
+
+
+# put in absolute paths if you don't have them in your path; or use env. vars.
+
+mvprog="${MVPROG-mv}"
+cpprog="${CPPROG-cp}"
+chmodprog="${CHMODPROG-chmod}"
+chownprog="${CHOWNPROG-chown}"
+chgrpprog="${CHGRPPROG-chgrp}"
+stripprog="${STRIPPROG-strip}"
+rmprog="${RMPROG-rm}"
+mkdirprog="${MKDIRPROG-mkdir}"
+
+transformbasename=""
+transform_arg=""
+instcmd="$mvprog"
+chmodcmd="$chmodprog 0755"
+chowncmd=""
+chgrpcmd=""
+stripcmd=""
+rmcmd="$rmprog -f"
+mvcmd="$mvprog"
+src=""
+dst=""
+dir_arg=""
+
+while [ x"$1" != x ]; do
+ case $1 in
+ -c) instcmd="$cpprog"
+ shift
+ continue;;
+
+ -d) dir_arg=true
+ shift
+ continue;;
+
+ -m) chmodcmd="$chmodprog $2"
+ shift
+ shift
+ continue;;
+
+ -o) chowncmd="$chownprog $2"
+ shift
+ shift
+ continue;;
+
+ -g) chgrpcmd="$chgrpprog $2"
+ shift
+ shift
+ continue;;
+
+ -s) stripcmd="$stripprog"
+ shift
+ continue;;
+
+ -t=*) transformarg=`echo $1 | sed 's/-t=//'`
+ shift
+ continue;;
+
+ -b=*) transformbasename=`echo $1 | sed 's/-b=//'`
+ shift
+ continue;;
+
+ *) if [ x"$src" = x ]
+ then
+ src=$1
+ else
+ # this colon is to work around a 386BSD /bin/sh bug
+ :
+ dst=$1
+ fi
+ shift
+ continue;;
+ esac
+done
+
+if [ x"$src" = x ]
+then
+ echo "install: no input file specified"
+ exit 1
+else
+ true
+fi
+
+if [ x"$dir_arg" != x ]; then
+ dst=$src
+ src=""
+
+ if [ -d $dst ]; then
+ instcmd=:
+ else
+ instcmd=mkdir
+ fi
+else
+
+# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
+# might cause directories to be created, which would be especially bad
+# if $src (and thus $dsttmp) contains '*'.
+
+ if [ -f $src -o -d $src ]
+ then
+ true
+ else
+ echo "install: $src does not exist"
+ exit 1
+ fi
+
+ if [ x"$dst" = x ]
+ then
+ echo "install: no destination specified"
+ exit 1
+ else
+ true
+ fi
+
+# If destination is a directory, append the input filename; if your system
+# does not like double slashes in filenames, you may need to add some logic
+
+ if [ -d $dst ]
+ then
+ dst="$dst"/`basename $src`
+ else
+ true
+ fi
+fi
+
+## this sed command emulates the dirname command
+dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
+
+# Make sure that the destination directory exists.
+# this part is taken from Noah Friedman's mkinstalldirs script
+
+# Skip lots of stat calls in the usual case.
+if [ ! -d "$dstdir" ]; then
+defaultIFS='
+'
+IFS="${IFS-${defaultIFS}}"
+
+oIFS="${IFS}"
+# Some sh's can't handle IFS=/ for some reason.
+IFS='%'
+set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'`
+IFS="${oIFS}"
+
+pathcomp=''
+
+while [ $# -ne 0 ] ; do
+ pathcomp="${pathcomp}${1}"
+ shift
+
+ if [ ! -d "${pathcomp}" ] ;
+ then
+ $mkdirprog "${pathcomp}"
+ else
+ true
+ fi
+
+ pathcomp="${pathcomp}/"
+done
+fi
+
+if [ x"$dir_arg" != x ]
+then
+ $doit $instcmd $dst &&
+
+ if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi &&
+ if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi &&
+ if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi &&
+ if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi
+else
+
+# If we're going to rename the final executable, determine the name now.
+
+ if [ x"$transformarg" = x ]
+ then
+ dstfile=`basename $dst`
+ else
+ dstfile=`basename $dst $transformbasename |
+ sed $transformarg`$transformbasename
+ fi
+
+# don't allow the sed command to completely eliminate the filename
+
+ if [ x"$dstfile" = x ]
+ then
+ dstfile=`basename $dst`
+ else
+ true
+ fi
+
+# Make a temp file name in the proper directory.
+
+ dsttmp=$dstdir/#inst.$$#
+
+# Move or copy the file name to the temp name
+
+ $doit $instcmd $src $dsttmp &&
+
+ trap "rm -f ${dsttmp}" 0 &&
+
+# and set any options; do chmod last to preserve setuid bits
+
+# If any of these fail, we abort the whole thing. If we want to
+# ignore errors from any of these, just make sure not to ignore
+# errors from the above "$doit $instcmd $src $dsttmp" command.
+
+ if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi &&
+ if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi &&
+ if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi &&
+ if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi &&
+
+# Now rename the file to the real destination.
+
+ $doit $rmcmd -f $dstdir/$dstfile &&
+ $doit $mvcmd $dsttmp $dstdir/$dstfile
+
+fi &&
+
+
+exit 0
diff --git a/jpeg-6c/install.doc b/jpeg-6c/install.doc
new file mode 100644
index 0000000..76f957e
--- /dev/null
+++ b/jpeg-6c/install.doc
@@ -0,0 +1,1064 @@
+INSTALLATION INSTRUCTIONS for the Independent JPEG Group's JPEG software
+
+Copyright (C) 1991-1998, Thomas G. Lane.
+This file is part of the Independent JPEG Group's software.
+For conditions of distribution and use, see the accompanying README file.
+
+
+This file explains how to configure and install the IJG software. We have
+tried to make this software extremely portable and flexible, so that it can be
+adapted to almost any environment. The downside of this decision is that the
+installation process is complicated. We have provided shortcuts to simplify
+the task on common systems. But in any case, you will need at least a little
+familiarity with C programming and program build procedures for your system.
+
+If you are only using this software as part of a larger program, the larger
+program's installation procedure may take care of configuring the IJG code.
+For example, Ghostscript's installation script will configure the IJG code.
+You don't need to read this file if you just want to compile Ghostscript.
+
+If you are on a Unix machine, you may not need to read this file at all.
+Try doing
+ ./configure
+ make
+ make test
+If that doesn't complain, do
+ make install
+(better do "make -n install" first to see if the makefile will put the files
+where you want them). Read further if you run into snags or want to customize
+the code for your system.
+
+
+TABLE OF CONTENTS
+-----------------
+
+Before you start
+Configuring the software:
+ using the automatic "configure" script
+ using one of the supplied jconfig and makefile files
+ by hand
+Building the software
+Testing the software
+Installing the software
+Optional stuff
+Optimization
+Hints for specific systems
+
+
+BEFORE YOU START
+================
+
+Before installing the software you must unpack the distributed source code.
+Since you are reading this file, you have probably already succeeded in this
+task. However, there is a potential for error if you needed to convert the
+files to the local standard text file format (for example, if you are on
+MS-DOS you may have converted LF end-of-line to CR/LF). You must apply
+such conversion to all the files EXCEPT those whose names begin with "test".
+The test files contain binary data; if you change them in any way then the
+self-test will give bad results.
+
+Please check the last section of this file to see if there are hints for the
+specific machine or compiler you are using.
+
+
+CONFIGURING THE SOFTWARE
+========================
+
+To configure the IJG code for your system, you need to create two files:
+ * jconfig.h: contains values for system-dependent #define symbols.
+ * Makefile: controls the compilation process.
+(On a non-Unix machine, you may create "project files" or some other
+substitute for a Makefile. jconfig.h is needed in any environment.)
+
+We provide three different ways to generate these files:
+ * On a Unix system, you can just run the "configure" script.
+ * We provide sample jconfig files and makefiles for popular machines;
+ if your machine matches one of the samples, just copy the right sample
+ files to jconfig.h and Makefile.
+ * If all else fails, read the instructions below and make your own files.
+
+
+Configuring the software using the automatic "configure" script
+---------------------------------------------------------------
+
+If you are on a Unix machine, you can just type
+ ./configure
+and let the configure script construct appropriate configuration files.
+If you're using "csh" on an old version of System V, you might need to type
+ sh configure
+instead to prevent csh from trying to execute configure itself.
+Expect configure to run for a few minutes, particularly on slower machines;
+it works by compiling a series of test programs.
+
+Configure was created with GNU Autoconf and it follows the usual conventions
+for GNU configure scripts. It makes a few assumptions that you may want to
+override. You can do this by providing optional switches to configure:
+
+* If you want to build libjpeg as a shared library, say
+ ./configure --enable-shared
+To get both shared and static libraries, say
+ ./configure --enable-shared --enable-static
+Note that these switches invoke GNU libtool to take care of system-dependent
+shared library building methods. If things don't work this way, please try
+running configure without either switch; that should build a static library
+without using libtool. If that works, your problem is probably with libtool
+not with the IJG code. libtool is fairly new and doesn't support all flavors
+of Unix yet. (You might be able to find a newer version of libtool than the
+one included with libjpeg; see ftp.gnu.org. Report libtool problems to
+bug-libtool at gnu.org.)
+
+* Configure will use gcc (GNU C compiler) if it's available, otherwise cc.
+To force a particular compiler to be selected, use the CC option, for example
+ ./configure CC='cc'
+The same method can be used to include any unusual compiler switches.
+For example, on HP-UX you probably want to say
+ ./configure CC='cc -Aa'
+to get HP's compiler to run in ANSI mode.
+
+* The default CFLAGS setting is "-O" for non-gcc compilers, "-O2" for gcc.
+You can override this by saying, for example,
+ ./configure CFLAGS='-g'
+if you want to compile with debugging support.
+
+* Configure will set up the makefile so that "make install" will install files
+into /usr/local/bin, /usr/local/man, etc. You can specify an installation
+prefix other than "/usr/local" by giving configure the option "--prefix=PATH".
+
+* If you don't have a lot of swap space, you may need to enable the IJG
+software's internal virtual memory mechanism. To do this, give the option
+"--enable-maxmem=N" where N is the default maxmemory limit in megabytes.
+This is discussed in more detail under "Selecting a memory manager", below.
+You probably don't need to worry about this on reasonably-sized Unix machines,
+unless you plan to process very large images.
+
+Configure has some other features that are useful if you are cross-compiling
+or working in a network of multiple machine types; but if you need those
+features, you probably already know how to use them.
+
+
+Configuring the software using one of the supplied jconfig and makefile files
+-----------------------------------------------------------------------------
+
+If you have one of these systems, you can just use the provided configuration
+files:
+
+Makefile jconfig file System and/or compiler
+
+makefile.manx jconfig.manx Amiga, Manx Aztec C
+makefile.sas jconfig.sas Amiga, SAS C
+makeproj.mac jconfig.mac Apple Macintosh, Metrowerks CodeWarrior
+makefile.osx jconfig.osx Apple Darwin(OSX)
+mak*jpeg.st jconfig.st Atari ST/STE/TT, Pure C or Turbo C
+makefile.bcc jconfig.bcc MS-DOS or OS/2, Borland C
+makefile.dj jconfig.dj MS-DOS, DJGPP (Delorie's port of GNU C)
+makefile.mc6 jconfig.mc6 MS-DOS, Microsoft C (16-bit only)
+makefile.wat jconfig.wat MS-DOS, OS/2, or Windows NT, Watcom C
+makefile.vc jconfig.vc Windows NT/95, MS Visual C++
+make*.ds jconfig.vc Windows NT/95, MS Developer Studio
+makefile.mms jconfig.vms Digital VMS, with MMS software
+makefile.vms jconfig.vms Digital VMS, without MMS software
+
+Copy the proper jconfig file to jconfig.h and the makefile to Makefile (or
+whatever your system uses as the standard makefile name). For more info see
+the appropriate system-specific hints section near the end of this file.
+
+
+Configuring the software by hand
+--------------------------------
+
+First, generate a jconfig.h file. If you are moderately familiar with C,
+the comments in jconfig.doc should be enough information to do this; just
+copy jconfig.doc to jconfig.h and edit it appropriately. Otherwise, you may
+prefer to use the ckconfig.c program. You will need to compile and execute
+ckconfig.c by hand --- we hope you know at least enough to do that.
+ckconfig.c may not compile the first try (in fact, the whole idea is for it
+to fail if anything is going to). If you get compile errors, fix them by
+editing ckconfig.c according to the directions given in ckconfig.c. Once
+you get it to run, it will write a suitable jconfig.h file, and will also
+print out some advice about which makefile to use.
+
+You may also want to look at the canned jconfig files, if there is one for a
+system similar to yours.
+
+Second, select a makefile and copy it to Makefile (or whatever your system
+uses as the standard makefile name). The most generic makefiles we provide
+are
+ makefile.ansi: if your C compiler supports function prototypes
+ makefile.unix: if not.
+(You have function prototypes if ckconfig.c put "#define HAVE_PROTOTYPES"
+in jconfig.h.) You may want to start from one of the other makefiles if
+there is one for a system similar to yours.
+
+Look over the selected Makefile and adjust options as needed. In particular
+you may want to change the CC and CFLAGS definitions. For instance, if you
+are using GCC, set CC=gcc. If you had to use any compiler switches to get
+ckconfig.c to work, make sure the same switches are in CFLAGS.
+
+If you are on a system that doesn't use makefiles, you'll need to set up
+project files (or whatever you do use) to compile all the source files and
+link them into executable files cjpeg, djpeg, jpegtran, rdjpgcom, and wrjpgcom.
+See the file lists in any of the makefiles to find out which files go into
+each program. Note that the provided makefiles all make a "library" file
+libjpeg first, but you don't have to do that if you don't want to; the file
+lists identify which source files are actually needed for compression,
+decompression, or both. As a last resort, you can make a batch script that
+just compiles everything and links it all together; makefile.vms is an example
+of this (it's for VMS systems that have no make-like utility).
+
+Here are comments about some specific configuration decisions you'll
+need to make:
+
+Command line style
+------------------
+
+These programs can use a Unix-like command line style which supports
+redirection and piping, like this:
+ cjpeg inputfile >outputfile
+ cjpeg <inputfile >outputfile
+ source program | cjpeg >outputfile
+The simpler "two file" command line style is just
+ cjpeg inputfile outputfile
+You may prefer the two-file style, particularly if you don't have pipes.
+
+You MUST use two-file style on any system that doesn't cope well with binary
+data fed through stdin/stdout; this is true for some MS-DOS compilers, for
+example. If you're not on a Unix system, it's safest to assume you need
+two-file style. (But if your compiler provides either the Posix-standard
+fdopen() library routine or a Microsoft-compatible setmode() routine, you
+can safely use the Unix command line style, by defining USE_FDOPEN or
+USE_SETMODE respectively.)
+
+To use the two-file style, make jconfig.h say "#define TWO_FILE_COMMANDLINE".
+
+Selecting a memory manager
+--------------------------
+
+The IJG code is capable of working on images that are too big to fit in main
+memory; data is swapped out to temporary files as necessary. However, the
+code to do this is rather system-dependent. We provide five different
+memory managers:
+
+* jmemansi.c This version uses the ANSI-standard library routine tmpfile(),
+ which not all non-ANSI systems have. On some systems
+ tmpfile() may put the temporary file in a non-optimal
+ location; if you don't like what it does, use jmemname.c.
+
+* jmemname.c This version creates named temporary files. For anything
+ except a Unix machine, you'll need to configure the
+ select_file_name() routine appropriately; see the comments
+ near the head of jmemname.c. If you use this version, define
+ NEED_SIGNAL_CATCHER in jconfig.h to make sure the temp files
+ are removed if the program is aborted.
+
+* jmemnobs.c (That stands for No Backing Store :-).) This will compile on
+ almost any system, but it assumes you have enough main memory
+ or virtual memory to hold the biggest images you work with.
+
+* jmemdos.c This should be used with most 16-bit MS-DOS compilers.
+ See the system-specific notes about MS-DOS for more info.
+ IMPORTANT: if you use this, define USE_MSDOS_MEMMGR in
+ jconfig.h, and include the assembly file jmemdosa.asm in the
+ programs. The supplied makefiles and jconfig files for
+ 16-bit MS-DOS compilers already do both.
+
+* jmemmac.c Custom version for Apple Macintosh; see the system-specific
+ notes for Macintosh for more info.
+
+To use a particular memory manager, change the SYSDEPMEM variable in your
+makefile to equal the corresponding object file name (for example, jmemansi.o
+or jmemansi.obj for jmemansi.c).
+
+If you have plenty of (real or virtual) main memory, just use jmemnobs.c.
+"Plenty" means about ten bytes for every pixel in the largest images
+you plan to process, so a lot of systems don't meet this criterion.
+If yours doesn't, try jmemansi.c first. If that doesn't compile, you'll have
+to use jmemname.c; be sure to adjust select_file_name() for local conditions.
+You may also need to change unlink() to remove() in close_backing_store().
+
+Except with jmemnobs.c or jmemmac.c, you need to adjust the DEFAULT_MAX_MEM
+setting to a reasonable value for your system (either by adding a #define for
+DEFAULT_MAX_MEM to jconfig.h, or by adding a -D switch to the Makefile).
+This value limits the amount of data space the program will attempt to
+allocate. Code and static data space isn't counted, so the actual memory
+needs for cjpeg or djpeg are typically 100 to 150Kb more than the max-memory
+setting. Larger max-memory settings reduce the amount of I/O needed to
+process a large image, but too large a value can result in "insufficient
+memory" failures. On most Unix machines (and other systems with virtual
+memory), just set DEFAULT_MAX_MEM to several million and forget it. At the
+other end of the spectrum, for MS-DOS machines you probably can't go much
+above 300K to 400K. (On MS-DOS the value refers to conventional memory only.
+Extended/expanded memory is handled separately by jmemdos.c.)
+
+
+BUILDING THE SOFTWARE
+=====================
+
+Now you should be able to compile the software. Just say "make" (or
+whatever's necessary to start the compilation). Have a cup of coffee.
+
+Here are some things that could go wrong:
+
+If your compiler complains about undefined structures, you should be able to
+shut it up by putting "#define INCOMPLETE_TYPES_BROKEN" in jconfig.h.
+
+If you have trouble with missing system include files or inclusion of the
+wrong ones, read jinclude.h. This shouldn't happen if you used configure
+or ckconfig.c to set up jconfig.h.
+
+There are a fair number of routines that do not use all of their parameters;
+some compilers will issue warnings about this, which you can ignore. There
+are also a few configuration checks that may give "unreachable code" warnings.
+Any other warning deserves investigation.
+
+If you don't have a getenv() library routine, define NO_GETENV.
+
+Also see the system-specific hints, below.
+
+
+TESTING THE SOFTWARE
+====================
+
+As a quick test of functionality we've included a small sample image in
+several forms:
+ testorig.jpg Starting point for the djpeg tests.
+ testimg.ppm The output of djpeg testorig.jpg
+ testimg.bmp The output of djpeg -bmp -colors 256 testorig.jpg
+ testimg.jpg The output of cjpeg testimg.ppm
+ testprog.jpg Progressive-mode equivalent of testorig.jpg.
+ testimgp.jpg The output of cjpeg -progressive -optimize testimg.ppm
+(The first- and second-generation .jpg files aren't identical since JPEG is
+lossy.) If you can generate duplicates of the testimg* files then you
+probably have working programs.
+
+With most of the makefiles, "make test" will perform the necessary
+comparisons.
+
+If you're using a makefile that doesn't provide the test option, run djpeg
+and cjpeg by hand and compare the output files to testimg* with whatever
+binary file comparison tool you have. The files should be bit-for-bit
+identical.
+
+If the programs complain "MAX_ALLOC_CHUNK is wrong, please fix", then you
+need to reduce MAX_ALLOC_CHUNK to a value that fits in type size_t.
+Try adding "#define MAX_ALLOC_CHUNK 65520L" to jconfig.h. A less likely
+configuration error is "ALIGN_TYPE is wrong, please fix": defining ALIGN_TYPE
+as long should take care of that one.
+
+If the cjpeg test run fails with "Missing Huffman code table entry", it's a
+good bet that you needed to define RIGHT_SHIFT_IS_UNSIGNED. Go back to the
+configuration step and run ckconfig.c. (This is a good plan for any other
+test failure, too.)
+
+If you are using Unix (one-file) command line style on a non-Unix system,
+it's a good idea to check that binary I/O through stdin/stdout actually
+works. You should get the same results from "djpeg <testorig.jpg >out.ppm"
+as from "djpeg -outfile out.ppm testorig.jpg". Note that the makefiles all
+use the latter style and therefore do not exercise stdin/stdout! If this
+check fails, try recompiling with USE_SETMODE or USE_FDOPEN defined.
+If it still doesn't work, better use two-file style.
+
+If you chose a memory manager other than jmemnobs.c, you should test that
+temporary-file usage works. Try "djpeg -bmp -colors 256 -max 0 testorig.jpg"
+and make sure its output matches testimg.bmp. If you have any really large
+images handy, try compressing them with -optimize and/or decompressing with
+-colors 256 to make sure your DEFAULT_MAX_MEM setting is not too large.
+
+NOTE: this is far from an exhaustive test of the JPEG software; some modules,
+such as 1-pass color quantization, are not exercised at all. It's just a
+quick test to give you some confidence that you haven't missed something
+major.
+
+
+INSTALLING THE SOFTWARE
+=======================
+
+Once you're done with the above steps, you can install the software by
+copying the executable files (cjpeg, djpeg, jpegtran, rdjpgcom, and wrjpgcom)
+to wherever you normally install programs. On Unix systems, you'll also want
+to put the man pages (cjpeg.1, djpeg.1, jpegtran.1, rdjpgcom.1, wrjpgcom.1)
+in the man-page directory. The pre-fab makefiles don't support this step
+since there's such a wide variety of installation procedures on different
+systems.
+
+If you generated a Makefile with the "configure" script, you can just say
+ make install
+to install the programs and their man pages into the standard places.
+(You'll probably need to be root to do this.) We recommend first saying
+ make -n install
+to see where configure thought the files should go. You may need to edit
+the Makefile, particularly if your system's conventions for man page
+filenames don't match what configure expects.
+
+If you want to install the IJG library itself, for use in compiling other
+programs besides ours, then you need to put the four include files
+ jpeglib.h jerror.h jconfig.h jmorecfg.h
+into your include-file directory, and put the library file libjpeg.a
+(extension may vary depending on system) wherever library files go.
+If you generated a Makefile with "configure", it will do what it thinks
+is the right thing if you say
+ make install-lib
+
+
+OPTIONAL STUFF
+==============
+
+Progress monitor:
+
+If you like, you can #define PROGRESS_REPORT (in jconfig.h) to enable display
+of percent-done progress reports. The routine provided in cdjpeg.c merely
+prints percentages to stderr, but you can customize it to do something
+fancier.
+
+Utah RLE file format support:
+
+We distribute the software with support for RLE image files (Utah Raster
+Toolkit format) disabled, because the RLE support won't compile without the
+Utah library. If you have URT version 3.1 or later, you can enable RLE
+support as follows:
+ 1. #define RLE_SUPPORTED in jconfig.h.
+ 2. Add a -I option to CFLAGS in the Makefile for the directory
+ containing the URT .h files (typically the "include"
+ subdirectory of the URT distribution).
+ 3. Add -L... -lrle to LDLIBS in the Makefile, where ... specifies
+ the directory containing the URT "librle.a" file (typically the
+ "lib" subdirectory of the URT distribution).
+
+Support for 12-bit-deep pixel data:
+
+The JPEG standard allows either 8-bit or 12-bit data precision. (For color,
+this means 8 or 12 bits per channel, of course.) If you need to work with
+deeper than 8-bit data, you can compile the IJG code for 12-bit operation.
+To do so:
+ 1. In jmorecfg.h, define BITS_IN_JSAMPLE as 12 rather than 8.
+ 2. In jconfig.h, undefine BMP_SUPPORTED, RLE_SUPPORTED, and TARGA_SUPPORTED,
+ because the code for those formats doesn't handle 12-bit data and won't
+ even compile. (The PPM code does work, as explained below. The GIF
+ code works too; it scales 8-bit GIF data to and from 12-bit depth
+ automatically.)
+ 3. Compile. Don't expect "make test" to pass, since the supplied test
+ files are for 8-bit data.
+
+Currently, 12-bit support does not work on 16-bit-int machines.
+
+Note that a 12-bit version will not read 8-bit JPEG files, nor vice versa;
+so you'll want to keep around a regular 8-bit compilation as well.
+(Run-time selection of data depth, to allow a single copy that does both,
+is possible but would probably slow things down considerably; it's very low
+on our to-do list.)
+
+The PPM reader (rdppm.c) can read 12-bit data from either text-format or
+binary-format PPM and PGM files. Binary-format PPM/PGM files which have a
+maxval greater than 255 are assumed to use 2 bytes per sample, LSB first
+(little-endian order). As of early 1995, 2-byte binary format is not
+officially supported by the PBMPLUS library, but it is expected that a
+future release of PBMPLUS will support it. Note that the PPM reader will
+read files of any maxval regardless of the BITS_IN_JSAMPLE setting; incoming
+data is automatically rescaled to either maxval=255 or maxval=4095 as
+appropriate for the cjpeg bit depth.
+
+The PPM writer (wrppm.c) will normally write 2-byte binary PPM or PGM
+format, maxval 4095, when compiled with BITS_IN_JSAMPLE=12. Since this
+format is not yet widely supported, you can disable it by compiling wrppm.c
+with PPM_NORAWWORD defined; then the data is scaled down to 8 bits to make a
+standard 1-byte/sample PPM or PGM file. (Yes, this means still another copy
+of djpeg to keep around. But hopefully you won't need it for very long.
+Poskanzer's supposed to get that new PBMPLUS release out Real Soon Now.)
+
+Of course, if you are working with 12-bit data, you probably have it stored
+in some other, nonstandard format. In that case you'll probably want to
+write your own I/O modules to read and write your format.
+
+Note that a 12-bit version of cjpeg always runs in "-optimize" mode, in
+order to generate valid Huffman tables. This is necessary because our
+default Huffman tables only cover 8-bit data.
+
+Removing code:
+
+If you need to make a smaller version of the JPEG software, some optional
+functions can be removed at compile time. See the xxx_SUPPORTED #defines in
+jconfig.h and jmorecfg.h. If at all possible, we recommend that you leave in
+decoder support for all valid JPEG files, to ensure that you can read anyone's
+output. Taking out support for image file formats that you don't use is the
+most painless way to make the programs smaller. Another possibility is to
+remove some of the DCT methods: in particular, the "IFAST" method may not be
+enough faster than the others to be worth keeping on your machine. (If you
+do remove ISLOW or IFAST, be sure to redefine JDCT_DEFAULT or JDCT_FASTEST
+to a supported method, by adding a #define in jconfig.h.)
+
+
+OPTIMIZATION
+============
+
+Unless you own a Cray, you'll probably be interested in making the JPEG
+software go as fast as possible. This section covers some machine-dependent
+optimizations you may want to try. We suggest that before trying any of
+this, you first get the basic installation to pass the self-test step.
+Repeat the self-test after any optimization to make sure that you haven't
+broken anything.
+
+The integer DCT routines perform a lot of multiplications. These
+multiplications must yield 32-bit results, but none of their input values
+are more than 16 bits wide. On many machines, notably the 680x0 and 80x86
+CPUs, a 16x16=>32 bit multiply instruction is faster than a full 32x32=>32
+bit multiply. Unfortunately there is no portable way to specify such a
+multiplication in C, but some compilers can generate one when you use the
+right combination of casts. See the MULTIPLYxxx macro definitions in
+jdct.h. If your compiler makes "int" be 32 bits and "short" be 16 bits,
+defining SHORTxSHORT_32 is fairly likely to work. When experimenting with
+alternate definitions, be sure to test not only whether the code still works
+(use the self-test), but also whether it is actually faster --- on some
+compilers, alternate definitions may compute the right answer, yet be slower
+than the default. Timing cjpeg on a large PGM (grayscale) input file is the
+best way to check this, as the DCT will be the largest fraction of the runtime
+in that mode. (Note: some of the distributed compiler-specific jconfig files
+already contain #define switches to select appropriate MULTIPLYxxx
+definitions.)
+
+If your machine has sufficiently fast floating point hardware, you may find
+that the float DCT method is faster than the integer DCT methods, even
+after tweaking the integer multiply macros. In that case you may want to
+make the float DCT be the default method. (The only objection to this is
+that float DCT results may vary slightly across machines.) To do that, add
+"#define JDCT_DEFAULT JDCT_FLOAT" to jconfig.h. Even if you don't change
+the default, you should redefine JDCT_FASTEST, which is the method selected
+by djpeg's -fast switch. Don't forget to update the documentation files
+(usage.doc and/or cjpeg.1, djpeg.1) to agree with what you've done.
+
+If access to "short" arrays is slow on your machine, it may be a win to
+define type JCOEF as int rather than short. This will cost a good deal of
+memory though, particularly in some multi-pass modes, so don't do it unless
+you have memory to burn and short is REALLY slow.
+
+If your compiler can compile function calls in-line, make sure the INLINE
+macro in jmorecfg.h is defined as the keyword that marks a function
+inline-able. Some compilers have a switch that tells the compiler to inline
+any function it thinks is profitable (e.g., -finline-functions for gcc).
+Enabling such a switch is likely to make the compiled code bigger but faster.
+
+In general, it's worth trying the maximum optimization level of your compiler,
+and experimenting with any optional optimizations such as loop unrolling.
+(Unfortunately, far too many compilers have optimizer bugs ... be prepared to
+back off if the code fails self-test.) If you do any experimentation along
+these lines, please report the optimal settings to jpeg-info at uunet.uu.net so
+we can mention them in future releases. Be sure to specify your machine and
+compiler version.
+
+
+HINTS FOR SPECIFIC SYSTEMS
+==========================
+
+We welcome reports on changes needed for systems not mentioned here. Submit
+'em to jpeg-info at uunet.uu.net. Also, if configure or ckconfig.c is wrong
+about how to configure the JPEG software for your system, please let us know.
+
+
+Acorn RISC OS:
+
+(Thanks to Simon Middleton for these hints on compiling with Desktop C.)
+After renaming the files according to Acorn conventions, take a copy of
+makefile.ansi, change all occurrences of 'libjpeg.a' to 'libjpeg.o' and
+change these definitions as indicated:
+
+CFLAGS= -throwback -IC: -Wn
+LDLIBS=C:o.Stubs
+SYSDEPMEM=jmemansi.o
+LN=Link
+AR=LibFile -c -o
+
+Also add a new line '.c.o:; $(cc) $< $(cflags) -c -o $@'. Remove the
+lines '$(RM) libjpeg.o' and '$(AR2) libjpeg.o' and the 'jconfig.h'
+dependency section.
+
+Copy jconfig.doc to jconfig.h. Edit jconfig.h to define TWO_FILE_COMMANDLINE
+and CHAR_IS_UNSIGNED.
+
+Run the makefile using !AMU not !Make. If you want to use the 'clean' and
+'test' makefile entries then you will have to fiddle with the syntax a bit
+and rename the test files.
+
+
+Amiga:
+
+SAS C 6.50 reportedly is too buggy to compile the IJG code properly.
+A patch to update to 6.51 is available from SAS or AmiNet FTP sites.
+
+The supplied config files are set up to use jmemname.c as the memory
+manager, with temporary files being created on the device named by
+"JPEGTMP:".
+
+
+Atari ST/STE/TT:
+
+Copy the project files makcjpeg.st, makdjpeg.st, maktjpeg.st, and makljpeg.st
+to cjpeg.prj, djpeg.prj, jpegtran.prj, and libjpeg.prj respectively. The
+project files should work as-is with Pure C. For Turbo C, change library
+filenames "pc..." to "tc..." in each project file. Note that libjpeg.prj
+selects jmemansi.c as the recommended memory manager. You'll probably want to
+adjust the DEFAULT_MAX_MEM setting --- you want it to be a couple hundred K
+less than your normal free memory. Put "#define DEFAULT_MAX_MEM nnnn" into
+jconfig.h to do this.
+
+To use the 68881/68882 coprocessor for the floating point DCT, add the
+compiler option "-8" to the project files and replace pcfltlib.lib with
+pc881lib.lib in cjpeg.prj and djpeg.prj. Or if you don't have a
+coprocessor, you may prefer to remove the float DCT code by undefining
+DCT_FLOAT_SUPPORTED in jmorecfg.h (since without a coprocessor, the float
+code will be too slow to be useful). In that case, you can delete
+pcfltlib.lib from the project files.
+
+Note that you must make libjpeg.lib before making cjpeg.ttp, djpeg.ttp,
+or jpegtran.ttp. You'll have to perform the self-test by hand.
+
+We haven't bothered to include project files for rdjpgcom and wrjpgcom.
+Those source files should just be compiled by themselves; they don't
+depend on the JPEG library.
+
+There is a bug in some older versions of the Turbo C library which causes the
+space used by temporary files created with "tmpfile()" not to be freed after
+an abnormal program exit. If you check your disk afterwards, you will find
+cluster chains that are allocated but not used by a file. This should not
+happen in cjpeg/djpeg/jpegtran, since we enable a signal catcher to explicitly
+close temp files before exiting. But if you use the JPEG library with your
+own code, be sure to supply a signal catcher, or else use a different
+system-dependent memory manager.
+
+
+Cray:
+
+Should you be so fortunate as to be running JPEG on a Cray YMP, there is a
+compiler bug in old versions of Cray's Standard C (prior to 3.1). If you
+still have an old compiler, you'll need to insert a line reading
+"#pragma novector" just before the loop
+ for (i = 1; i <= (int) htbl->bits[l]; i++)
+ huffsize[p++] = (char) l;
+in fix_huff_tbl (in V5beta1, line 204 of jchuff.c and line 176 of jdhuff.c).
+[This bug may or may not still occur with the current IJG code, but it's
+probably a dead issue anyway...]
+
+
+HP-UX:
+
+If you have HP-UX 7.05 or later with the "software development" C compiler,
+you should run the compiler in ANSI mode. If using the configure script,
+say
+ ./configure CC='cc -Aa'
+(or -Ae if you prefer). If configuring by hand, use makefile.ansi and add
+"-Aa" to the CFLAGS line in the makefile.
+
+If you have a pre-7.05 system, or if you are using the non-ANSI C compiler
+delivered with a minimum HP-UX system, then you must use makefile.unix
+(and do NOT add -Aa); or just run configure without the CC option.
+
+On HP 9000 series 800 machines, the HP C compiler is buggy in revisions prior
+to A.08.07. If you get complaints about "not a typedef name", you'll have to
+use makefile.unix, or run configure without the CC option.
+
+
+Macintosh, generic comments:
+
+The supplied user-interface files (cjpeg.c, djpeg.c, etc) are set up to
+provide a Unix-style command line interface. You can use this interface on
+the Mac by means of the ccommand() library routine provided by Metrowerks
+CodeWarrior or Think C. This is only appropriate for testing the library,
+however; to make a user-friendly equivalent of cjpeg/djpeg you'd really want
+to develop a Mac-style user interface. There isn't a complete example
+available at the moment, but there are some helpful starting points:
+1. Sam Bushell's free "To JPEG" applet provides drag-and-drop conversion to
+JPEG under System 7 and later. This only illustrates how to use the
+compression half of the library, but it does a very nice job of that part.
+The CodeWarrior source code is available from http://www.pobox.com/~jsam.
+2. Jim Brunner prepared a Mac-style user interface for both compression and
+decompression. Unfortunately, it hasn't been updated since IJG v4, and
+the library's API has changed considerably since then. Still it may be of
+some help, particularly as a guide to compiling the IJG code under Think C.
+Jim's code is available from the Info-Mac archives, at sumex-aim.stanford.edu
+or mirrors thereof; see file /info-mac/dev/src/jpeg-convert-c.hqx.
+
+jmemmac.c is the recommended memory manager back end for Macintosh. It uses
+NewPtr/DisposePtr instead of malloc/free, and has a Mac-specific
+implementation of jpeg_mem_available(). It also creates temporary files that
+follow Mac conventions. (That part of the code relies on System-7-or-later OS
+functions. See the comments in jmemmac.c if you need to run it on System 6.)
+NOTE that USE_MAC_MEMMGR must be defined in jconfig.h to use jmemmac.c.
+
+You can also use jmemnobs.c, if you don't care about handling images larger
+than available memory. If you use any memory manager back end other than
+jmemmac.c, we recommend replacing "malloc" and "free" by "NewPtr" and
+"DisposePtr", because Mac C libraries often have peculiar implementations of
+malloc/free. (For instance, free() may not return the freed space to the
+Mac Memory Manager. This is undesirable for the IJG code because jmemmgr.c
+already clumps space requests.)
+
+
+Macintosh, Metrowerks CodeWarrior:
+
+The Unix-command-line-style interface can be used by defining USE_CCOMMAND.
+You'll also need to define TWO_FILE_COMMANDLINE to avoid stdin/stdout.
+This means that when using the cjpeg/djpeg programs, you'll have to type the
+input and output file names in the "Arguments" text-edit box, rather than
+using the file radio buttons. (Perhaps USE_FDOPEN or USE_SETMODE would
+eliminate the problem, but I haven't heard from anyone who's tried it.)
+
+On 680x0 Macs, Metrowerks defines type "double" as a 10-byte IEEE extended
+float. jmemmgr.c won't like this: it wants sizeof(ALIGN_TYPE) to be a power
+of 2. Add "#define ALIGN_TYPE long" to jconfig.h to eliminate the complaint.
+
+The supplied configuration file jconfig.mac can be used for your jconfig.h;
+it includes all the recommended symbol definitions. If you have AppleScript
+installed, you can run the supplied script makeproj.mac to create CodeWarrior
+project files for the library and the testbed applications, then build the
+library and applications. (Thanks to Dan Sears and Don Agro for this nifty
+hack, which saves us from trying to maintain CodeWarrior project files as part
+of the IJG distribution...)
+
+
+Macintosh, Think C:
+
+The documentation in Jim Brunner's "JPEG Convert" source code (see above)
+includes detailed build instructions for Think C; it's probably somewhat
+out of date for the current release, but may be helpful.
+
+If you want to build the minimal command line version, proceed as follows.
+You'll have to prepare project files for the programs; we don't include any
+in the distribution since they are not text files. Use the file lists in
+any of the supplied makefiles as a guide. Also add the ANSI and Unix C
+libraries in a separate segment. You may need to divide the JPEG files into
+more than one segment; we recommend dividing compression and decompression
+modules. Define USE_CCOMMAND in jconfig.h so that the ccommand() routine is
+called. You must also define TWO_FILE_COMMANDLINE because stdin/stdout
+don't handle binary data correctly.
+
+On 680x0 Macs, Think C defines type "double" as a 12-byte IEEE extended float.
+jmemmgr.c won't like this: it wants sizeof(ALIGN_TYPE) to be a power of 2.
+Add "#define ALIGN_TYPE long" to jconfig.h to eliminate the complaint.
+
+jconfig.mac should work as a jconfig.h configuration file for Think C,
+but the makeproj.mac AppleScript script is specific to CodeWarrior. Sorry.
+
+
+MIPS R3000:
+
+MIPS's cc version 1.31 has a rather nasty optimization bug. Don't use -O
+if you have that compiler version. (Use "cc -V" to check the version.)
+Note that the R3000 chip is found in workstations from DEC and others.
+
+
+MS-DOS, generic comments for 16-bit compilers:
+
+The IJG code is designed to work well in 80x86 "small" or "medium" memory
+models (i.e., data pointers are 16 bits unless explicitly declared "far";
+code pointers can be either size). You may be able to use small model to
+compile cjpeg or djpeg by itself, but you will probably have to use medium
+model for any larger application. This won't make much difference in
+performance. You *will* take a noticeable performance hit if you use a
+large-data memory model, and you should avoid "huge" model if at all
+possible. Be sure that NEED_FAR_POINTERS is defined in jconfig.h if you use
+a small-data memory model; be sure it is NOT defined if you use a large-data
+model. (The supplied makefiles and jconfig files for Borland and Microsoft C
+compile in medium model and define NEED_FAR_POINTERS.)
+
+The DOS-specific memory manager, jmemdos.c, should be used if possible.
+It needs some assembly-code routines which are in jmemdosa.asm; make sure
+your makefile assembles that file and includes it in the library. If you
+don't have a suitable assembler, you can get pre-assembled object files for
+jmemdosa by FTP from ftp.uu.net:/graphics/jpeg/jdosaobj.zip. (DOS-oriented
+distributions of the IJG source code often include these object files.)
+
+When using jmemdos.c, jconfig.h must define USE_MSDOS_MEMMGR and must set
+MAX_ALLOC_CHUNK to less than 64K (65520L is a typical value). If your
+C library's far-heap malloc() can't allocate blocks that large, reduce
+MAX_ALLOC_CHUNK to whatever it can handle.
+
+If you can't use jmemdos.c for some reason --- for example, because you
+don't have an assembler to assemble jmemdosa.asm --- you'll have to fall
+back to jmemansi.c or jmemname.c. You'll probably still need to set
+MAX_ALLOC_CHUNK in jconfig.h, because most DOS C libraries won't malloc()
+more than 64K at a time. IMPORTANT: if you use jmemansi.c or jmemname.c,
+you will have to compile in a large-data memory model in order to get the
+right stdio library. Too bad.
+
+wrjpgcom needs to be compiled in large model, because it malloc()s a 64KB
+work area to hold the comment text. If your C library's malloc can't
+handle that, reduce MAX_COM_LENGTH as necessary in wrjpgcom.c.
+
+Most MS-DOS compilers treat stdin/stdout as text files, so you must use
+two-file command line style. But if your compiler has either fdopen() or
+setmode(), you can use one-file style if you like. To do this, define
+USE_SETMODE or USE_FDOPEN so that stdin/stdout will be set to binary mode.
+(USE_SETMODE seems to work with more DOS compilers than USE_FDOPEN.) You
+should test that I/O through stdin/stdout produces the same results as I/O
+to explicitly named files... the "make test" procedures in the supplied
+makefiles do NOT use stdin/stdout.
+
+
+MS-DOS, generic comments for 32-bit compilers:
+
+None of the above comments about memory models apply if you are using a
+32-bit flat-memory-space environment, such as DJGPP or Watcom C. (And you
+should use one if you have it, as performance will be much better than
+8086-compatible code!) For flat-memory-space compilers, do NOT define
+NEED_FAR_POINTERS, and do NOT use jmemdos.c. Use jmemnobs.c if the
+environment supplies adequate virtual memory, otherwise use jmemansi.c or
+jmemname.c.
+
+You'll still need to be careful about binary I/O through stdin/stdout.
+See the last paragraph of the previous section.
+
+
+MS-DOS, Borland C:
+
+Be sure to convert all the source files to DOS text format (CR/LF newlines).
+Although Borland C will often work OK with unmodified Unix (LF newlines)
+source files, sometimes it will give bogus compile errors.
+"Illegal character '#'" is the most common such error. (This is true with
+Borland C 3.1, but perhaps is fixed in newer releases.)
+
+If you want one-file command line style, just undefine TWO_FILE_COMMANDLINE.
+jconfig.bcc already includes #define USE_SETMODE to make this work.
+(fdopen does not work correctly.)
+
+
+MS-DOS, Microsoft C:
+
+makefile.mc6 works with Microsoft C, DOS Visual C++, etc. It should only
+be used if you want to build a 16-bit (small or medium memory model) program.
+
+If you want one-file command line style, just undefine TWO_FILE_COMMANDLINE.
+jconfig.mc6 already includes #define USE_SETMODE to make this work.
+(fdopen does not work correctly.)
+
+Note that this makefile assumes that the working copy of itself is called
+"makefile". If you want to call it something else, say "makefile.mak",
+be sure to adjust the dependency line that reads "$(RFILE) : makefile".
+Otherwise the make will fail because it doesn't know how to create "makefile".
+Worse, some releases of Microsoft's make utilities give an incorrect error
+message in this situation.
+
+Old versions of MS C fail with an "out of macro expansion space" error
+because they can't cope with the macro TRACEMS8 (defined in jerror.h).
+If this happens to you, the easiest solution is to change TRACEMS8 to
+expand to nothing. You'll lose the ability to dump out JPEG coefficient
+tables with djpeg -debug -debug, but at least you can compile.
+
+Original MS C 6.0 is very buggy; it compiles incorrect code unless you turn
+off optimization entirely (remove -O from CFLAGS). 6.00A is better, but it
+still generates bad code if you enable loop optimizations (-Ol or -Ox).
+
+MS C 8.0 crashes when compiling jquant1.c with optimization switch /Oo ...
+which is on by default. To work around this bug, compile that one file
+with /Oo-.
+
+
+Microsoft Windows (all versions), generic comments:
+
+Some Windows system include files define typedef boolean as "unsigned char".
+The IJG code also defines typedef boolean, but we make it "int" by default.
+This doesn't affect the IJG programs because we don't import those Windows
+include files. But if you use the JPEG library in your own program, and some
+of your program's files import one definition of boolean while some import the
+other, you can get all sorts of mysterious problems. A good preventive step
+is to make the IJG library use "unsigned char" for boolean. To do that,
+add something like this to your jconfig.h file:
+ /* Define "boolean" as unsigned char, not int, per Windows custom */
+ #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
+ typedef unsigned char boolean;
+ #endif
+ #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
+(This is already in jconfig.vc, by the way.)
+
+windef.h contains the declarations
+ #define far
+ #define FAR far
+Since jmorecfg.h tries to define FAR as empty, you may get a compiler
+warning if you include both jpeglib.h and windef.h (which windows.h
+includes). To suppress the warning, you can put "#ifndef FAR"/"#endif"
+around the line "#define FAR" in jmorecfg.h.
+
+When using the library in a Windows application, you will almost certainly
+want to modify or replace the error handler module jerror.c, since our
+default error handler does a couple of inappropriate things:
+ 1. it tries to write error and warning messages on stderr;
+ 2. in event of a fatal error, it exits by calling exit().
+
+A simple stopgap solution for problem 1 is to replace the line
+ fprintf(stderr, "%s\n", buffer);
+(in output_message in jerror.c) with
+ MessageBox(GetActiveWindow(),buffer,"JPEG Error",MB_OK|MB_ICONERROR);
+It's highly recommended that you at least do that much, since otherwise
+error messages will disappear into nowhere. (Beginning with IJG v6b, this
+code is already present in jerror.c; just define USE_WINDOWS_MESSAGEBOX in
+jconfig.h to enable it.)
+
+The proper solution for problem 2 is to return control to your calling
+application after a library error. This can be done with the setjmp/longjmp
+technique discussed in libjpeg.doc and illustrated in example.c. (NOTE:
+some older Windows C compilers provide versions of setjmp/longjmp that
+don't actually work under Windows. You may need to use the Windows system
+functions Catch and Throw instead.)
+
+The recommended memory manager under Windows is jmemnobs.c; in other words,
+let Windows do any virtual memory management needed. You should NOT use
+jmemdos.c nor jmemdosa.asm under Windows.
+
+For Windows 3.1, we recommend compiling in medium or large memory model;
+for newer Windows versions, use a 32-bit flat memory model. (See the MS-DOS
+sections above for more info about memory models.) In the 16-bit memory
+models only, you'll need to put
+ #define MAX_ALLOC_CHUNK 65520L /* Maximum request to malloc() */
+into jconfig.h to limit allocation chunks to 64Kb. (Without that, you'd
+have to use huge memory model, which slows things down unnecessarily.)
+jmemnobs.c works without modification in large or flat memory models, but to
+use medium model, you need to modify its jpeg_get_large and jpeg_free_large
+routines to allocate far memory. In any case, you might like to replace
+its calls to malloc and free with direct calls on Windows memory allocation
+functions.
+
+You may also want to modify jdatasrc.c and jdatadst.c to use Windows file
+operations rather than fread/fwrite. This is only necessary if your C
+compiler doesn't provide a competent implementation of C stdio functions.
+
+You might want to tweak the RGB_xxx macros in jmorecfg.h so that the library
+will accept or deliver color pixels in BGR sample order, not RGB; BGR order
+is usually more convenient under Windows. Note that this change will break
+the sample applications cjpeg/djpeg, but the library itself works fine.
+
+
+Many people want to convert the IJG library into a DLL. This is reasonably
+straightforward, but watch out for the following:
+
+ 1. Don't try to compile as a DLL in small or medium memory model; use
+large model, or even better, 32-bit flat model. Many places in the IJG code
+assume the address of a local variable is an ordinary (not FAR) pointer;
+that isn't true in a medium-model DLL.
+
+ 2. Microsoft C cannot pass file pointers between applications and DLLs.
+(See Microsoft Knowledge Base, PSS ID Number Q50336.) So jdatasrc.c and
+jdatadst.c don't work if you open a file in your application and then pass
+the pointer to the DLL. One workaround is to make jdatasrc.c/jdatadst.c
+part of your main application rather than part of the DLL.
+
+ 3. You'll probably need to modify the macros GLOBAL() and EXTERN() to
+attach suitable linkage keywords to the exported routine names. Similarly,
+you'll want to modify METHODDEF() and JMETHOD() to ensure function pointers
+are declared in a way that lets application routines be called back through
+the function pointers. These macros are in jmorecfg.h. Typical definitions
+for a 16-bit DLL are:
+ #define GLOBAL(type) type _far _pascal _loadds _export
+ #define EXTERN(type) extern type _far _pascal _loadds
+ #define METHODDEF(type) static type _far _pascal
+ #define JMETHOD(type,methodname,arglist) \
+ type (_far _pascal *methodname) arglist
+For a 32-bit DLL you may want something like
+ #define GLOBAL(type) __declspec(dllexport) type
+ #define EXTERN(type) extern __declspec(dllexport) type
+Although not all the GLOBAL routines are actually intended to be called by
+the application, the performance cost of making them all DLL entry points is
+negligible.
+
+The unmodified IJG library presents a very C-specific application interface,
+so the resulting DLL is only usable from C or C++ applications. There has
+been some talk of writing wrapper code that would present a simpler interface
+usable from other languages, such as Visual Basic. This is on our to-do list
+but hasn't been very high priority --- any volunteers out there?
+
+
+Microsoft Windows, Borland C:
+
+The provided jconfig.bcc should work OK in a 32-bit Windows environment,
+but you'll need to tweak it in a 16-bit environment (you'd need to define
+NEED_FAR_POINTERS and MAX_ALLOC_CHUNK). Beware that makefile.bcc will need
+alteration if you want to use it for Windows --- in particular, you should
+use jmemnobs.c not jmemdos.c under Windows.
+
+Borland C++ 4.5 fails with an internal compiler error when trying to compile
+jdmerge.c in 32-bit mode. If enough people complain, perhaps Borland will fix
+it. In the meantime, the simplest known workaround is to add a redundant
+definition of the variable range_limit in h2v1_merged_upsample(), at the head
+of the block that handles odd image width (about line 268 in v6 jdmerge.c):
+ /* If image width is odd, do the last output column separately */
+ if (cinfo->output_width & 1) {
+ register JSAMPLE * range_limit = cinfo->sample_range_limit; /* ADD THIS */
+ cb = GETJSAMPLE(*inptr1);
+Pretty bizarre, especially since the very similar routine h2v2_merged_upsample
+doesn't trigger the bug.
+Recent reports suggest that this bug does not occur with "bcc32a" (the
+Pentium-optimized version of the compiler).
+
+Another report from a user of Borland C 4.5 was that incorrect code (leading
+to a color shift in processed images) was produced if any of the following
+optimization switch combinations were used:
+ -Ot -Og
+ -Ot -Op
+ -Ot -Om
+So try backing off on optimization if you see such a problem. (Are there
+several different releases all numbered "4.5"??)
+
+
+Microsoft Windows, Microsoft Visual C++:
+
+jconfig.vc should work OK with any Microsoft compiler for a 32-bit memory
+model. makefile.vc is intended for command-line use. (If you are using
+the Developer Studio environment, you may prefer the DevStudio project
+files; see below.)
+
+Some users feel that it's easier to call the library from C++ code if you
+force VC++ to treat the library as C++ code, which you can do by renaming
+all the *.c files to *.cpp (and adjusting the makefile to match). This
+avoids the need to put extern "C" { ... } around #include "jpeglib.h" in
+your C++ application.
+
+
+Microsoft Windows, Microsoft Developer Studio:
+
+We include makefiles that should work as project files in DevStudio 4.2 or
+later. There is a library makefile that builds the IJG library as a static
+Win32 library, and an application makefile that builds the sample applications
+as Win32 console applications. (Even if you only want the library, we
+recommend building the applications so that you can run the self-test.)
+
+To use:
+1. Copy jconfig.vc to jconfig.h, makelib.ds to jpeg.mak, and
+ makeapps.ds to apps.mak. (Note that the renaming is critical!)
+2. Click on the .mak files to construct project workspaces.
+ (If you are using DevStudio more recent than 4.2, you'll probably
+ get a message saying that the makefiles are being updated.)
+3. Build the library project, then the applications project.
+4. Move the application .exe files from `app`\Release to an
+ appropriate location on your path.
+5. To perform the self-test, execute the command line
+ NMAKE /f makefile.vc test
+
+
+OS/2, Borland C++:
+
+Watch out for optimization bugs in older Borland compilers; you may need
+to back off the optimization switch settings. See the comments in
+makefile.bcc.
+
+
+SGI:
+
+On some SGI systems, you may need to set "AR2= ar -ts" in the Makefile.
+If you are using configure, you can do this by saying
+ ./configure RANLIB='ar -ts'
+This change is not needed on all SGIs. Use it only if the make fails at the
+stage of linking the completed programs.
+
+On the MIPS R4000 architecture (Indy, etc.), the compiler option "-mips2"
+reportedly speeds up the float DCT method substantially, enough to make it
+faster than the default int method (but still slower than the fast int
+method). If you use -mips2, you may want to alter the default DCT method to
+be float. To do this, put "#define JDCT_DEFAULT JDCT_FLOAT" in jconfig.h.
+
+
+VMS:
+
+On an Alpha/VMS system with MMS, be sure to use the "/Marco=Alpha=1"
+qualifier with MMS when building the JPEG package.
+
+VAX/VMS v5.5-1 may have problems with the test step of the build procedure
+reporting differences when it compares the original and test images. If the
+error points to the last block of the files, it is most likely bogus and may
+be safely ignored. It seems to be because the files are Stream_LF and
+Backup/Compare has difficulty with the (presumably) null padded files.
+This problem was not observed on VAX/VMS v6.1 or AXP/VMS v6.1.
\ No newline at end of file
diff --git a/jpeg-6c/jcapimin.c b/jpeg-6c/jcapimin.c
new file mode 100644
index 0000000..783d0a8
--- /dev/null
+++ b/jpeg-6c/jcapimin.c
@@ -0,0 +1,283 @@
+/*
+ * jcapimin.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains application interface code for the compression half
+ * of the JPEG library. These are the "minimum" API routines that may be
+ * needed in either the normal full-compression case or the transcoding-only
+ * case.
+ *
+ * Most of the routines intended to be called directly by an application
+ * are in this file or in jcapistd.c. But also see jcparam.c for
+ * parameter-setup helper routines, jcomapi.c for routines shared by
+ * compression and decompression, and jctrans.c for the transcoding case.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Initialization of a JPEG compression object.
+ * The error manager must already be set up (in case memory manager fails).
+ */
+
+GLOBAL(void)
+jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
+{
+ int i;
+
+ /* Guard against version mismatches between library and caller. */
+ cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
+ if (version != JPEG_LIB_VERSION)
+ ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
+ if (structsize != SIZEOF(struct jpeg_compress_struct))
+ ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
+ (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
+
+ /* For debugging purposes, we zero the whole master structure.
+ * But the application has already set the err pointer, and may have set
+ * client_data, so we have to save and restore those fields.
+ * Note: if application hasn't set client_data, tools like Purify may
+ * complain here.
+ */
+ {
+ struct jpeg_error_mgr * err = cinfo->err;
+ void * client_data = cinfo->client_data; /* ignore Purify complaint here */
+ MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
+ cinfo->err = err;
+ cinfo->client_data = client_data;
+ }
+ cinfo->is_decompressor = FALSE;
+
+ /* Initialize a memory manager instance for this object */
+ jinit_memory_mgr((j_common_ptr) cinfo);
+
+ /* Zero out pointers to permanent structures. */
+ cinfo->progress = NULL;
+ cinfo->dest = NULL;
+
+ cinfo->comp_info = NULL;
+
+ for (i = 0; i < NUM_QUANT_TBLS; i++)
+ cinfo->quant_tbl_ptrs[i] = NULL;
+
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ cinfo->dc_huff_tbl_ptrs[i] = NULL;
+ cinfo->ac_huff_tbl_ptrs[i] = NULL;
+ }
+
+ cinfo->script_space = NULL;
+
+ cinfo->input_gamma = 1.0; /* in case application forgets */
+ cinfo->data_precision = 8; /* defaults for backward compatibility */
+ cinfo->data_precision_other =8;
+
+ /* OK, I'm ready */
+ cinfo->global_state = CSTATE_START;
+}
+
+
+/*
+ * Destruction of a JPEG compression object
+ */
+
+GLOBAL(void)
+jpeg_destroy_compress (j_compress_ptr cinfo)
+{
+ jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
+}
+
+
+/*
+ * Abort processing of a JPEG compression operation,
+ * but don't destroy the object itself.
+ */
+
+GLOBAL(void)
+jpeg_abort_compress (j_compress_ptr cinfo)
+{
+ jpeg_abort((j_common_ptr) cinfo); /* use common routine */
+}
+
+
+/*
+ * Forcibly suppress or un-suppress all quantization and Huffman tables.
+ * Marks all currently defined tables as already written (if suppress)
+ * or not written (if !suppress). This will control whether they get emitted
+ * by a subsequent jpeg_start_compress call.
+ *
+ * This routine is exported for use by applications that want to produce
+ * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
+ * since it is called by jpeg_start_compress, we put it here --- otherwise
+ * jcparam.o would be linked whether the application used it or not.
+ */
+
+GLOBAL(void)
+jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
+{
+ int i;
+ JQUANT_TBL * qtbl;
+ JHUFF_TBL * htbl;
+
+ for (i = 0; i < NUM_QUANT_TBLS; i++) {
+ if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
+ qtbl->sent_table = suppress;
+ }
+
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
+ htbl->sent_table = suppress;
+ if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
+ htbl->sent_table = suppress;
+ }
+}
+
+
+/*
+ * Finish JPEG compression.
+ *
+ * If a multipass operating mode was selected, this may do a great deal of
+ * work including most of the actual output.
+ */
+
+GLOBAL(void)
+jpeg_finish_compress (j_compress_ptr cinfo)
+{
+ JDIMENSION iMCU_row;
+
+ if (cinfo->global_state == CSTATE_SCANNING ||
+ cinfo->global_state == CSTATE_RAW_OK) {
+ /* Terminate first pass */
+ if (cinfo->next_scanline < cinfo->image_height)
+ ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
+ (*cinfo->master->finish_pass) (cinfo);
+ } else if (cinfo->global_state != CSTATE_WRCOEFS)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ /* Perform any remaining passes */
+ while (! cinfo->master->is_last_pass) {
+ (*cinfo->master->prepare_for_pass) (cinfo);
+ for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) iMCU_row;
+ cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+ /* We bypass the main controller and invoke coef controller directly;
+ * all work is being done from the coefficient buffer.
+ */
+ if (! (*cinfo->codec->compress_data) (cinfo, (JSAMPIMAGE16) NULL))
+ ERREXIT(cinfo, JERR_CANT_SUSPEND);
+ }
+ (*cinfo->master->finish_pass) (cinfo);
+ }
+ /* Write EOI, do final cleanup */
+ (*cinfo->marker->write_file_trailer) (cinfo);
+ (*cinfo->dest->term_destination) (cinfo);
+ /* We can use jpeg_abort to release memory and reset global_state */
+ jpeg_abort((j_common_ptr) cinfo);
+}
+
+
+/*
+ * Write a special marker.
+ * This is only recommended for writing COM or APPn markers.
+ * Must be called after jpeg_start_compress() and before
+ * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
+ */
+
+GLOBAL(void)
+jpeg_write_marker (j_compress_ptr cinfo, int marker,
+ const JOCTET *dataptr, unsigned int datalen)
+{
+ JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
+
+ if (cinfo->next_scanline != 0 ||
+ (cinfo->global_state != CSTATE_SCANNING &&
+ cinfo->global_state != CSTATE_RAW_OK &&
+ cinfo->global_state != CSTATE_WRCOEFS))
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
+ write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
+ while (datalen--) {
+ (*write_marker_byte) (cinfo, *dataptr);
+ dataptr++;
+ }
+}
+
+/* Same, but piecemeal. */
+
+GLOBAL(void)
+jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
+{
+ if (cinfo->next_scanline != 0 ||
+ (cinfo->global_state != CSTATE_SCANNING &&
+ cinfo->global_state != CSTATE_RAW_OK &&
+ cinfo->global_state != CSTATE_WRCOEFS))
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
+}
+
+GLOBAL(void)
+jpeg_write_m_byte (j_compress_ptr cinfo, int val)
+{
+ (*cinfo->marker->write_marker_byte) (cinfo, val);
+}
+
+
+/*
+ * Alternate compression function: just write an abbreviated table file.
+ * Before calling this, all parameters and a data destination must be set up.
+ *
+ * To produce a pair of files containing abbreviated tables and abbreviated
+ * image data, one would proceed as follows:
+ *
+ * initialize JPEG object
+ * set JPEG parameters
+ * set destination to table file
+ * jpeg_write_tables(cinfo);
+ * set destination to image file
+ * jpeg_start_compress(cinfo, FALSE);
+ * write data...
+ * jpeg_finish_compress(cinfo);
+ *
+ * jpeg_write_tables has the side effect of marking all tables written
+ * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
+ * will not re-emit the tables unless it is passed write_all_tables=TRUE.
+ */
+
+GLOBAL(void)
+jpeg_write_tables (j_compress_ptr cinfo)
+{
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ /* (Re)initialize error mgr and destination modules */
+ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
+ (*cinfo->dest->init_destination) (cinfo);
+ /* Initialize the marker writer ... bit of a crock to do it here. */
+ jinit_marker_writer(cinfo);
+ /* Write them tables! */
+ (*cinfo->marker->write_tables_only) (cinfo);
+ /* And clean up. */
+ (*cinfo->dest->term_destination) (cinfo);
+ /*
+ * In library releases up through v6a, we called jpeg_abort() here to free
+ * any working memory allocated by the destination manager and marker
+ * writer. Some applications had a problem with that: they allocated space
+ * of their own from the library memory manager, and didn't want it to go
+ * away during write_tables. So now we do nothing. This will cause a
+ * memory leak if an app calls write_tables repeatedly without doing a full
+ * compression cycle or otherwise resetting the JPEG object. However, that
+ * seems less bad than unexpectedly freeing memory in the normal case.
+ * An app that prefers the old behavior can call jpeg_abort for itself after
+ * each call to jpeg_write_tables().
+ */
+}
diff --git a/jpeg-6c/jcapistd.c b/jpeg-6c/jcapistd.c
new file mode 100644
index 0000000..571365b
--- /dev/null
+++ b/jpeg-6c/jcapistd.c
@@ -0,0 +1,198 @@
+/*
+ * jcapistd.c
+ *
+ * Copyright (C) 1994-1996, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+* This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains application interface code for the compression half
+ * of the JPEG library. These are the "standard" API routines that are
+ * used in the normal full-compression case. They are not used by a
+ * transcoding-only application. Note that if an application links in
+ * jpeg_start_compress, it will end up linking in the entire compressor.
+ * We thus must separate this file from jcapimin.c to avoid linking the
+ * whole compression library into a transcoder.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Compression initialization.
+ * Before calling this, all parameters and a data destination must be set up.
+ *
+ * We require a write_all_tables parameter as a failsafe check when writing
+ * multiple datastreams from the same compression object. Since prior runs
+ * will have left all the tables marked sent_table=TRUE, a subsequent run
+ * would emit an abbreviated stream (no tables) by default. This may be what
+ * is wanted, but for safety's sake it should not be the default behavior:
+ * programmers should have to make a deliberate choice to emit abbreviated
+ * images. Therefore the documentation and examples should encourage people
+ * to pass write_all_tables=TRUE; then it will take active thought to do the
+ * wrong thing.
+ */
+
+GLOBAL(void)
+jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
+{
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ if (write_all_tables)
+ jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
+
+ /* (Re)initialize error mgr and destination modules */
+ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
+ (*cinfo->dest->init_destination) (cinfo);
+ /* Perform master selection of active modules */
+ jinit_compress_master(cinfo);
+ /* Set up for the first pass */
+ (*cinfo->master->prepare_for_pass) (cinfo);
+ /* Ready for application to drive first pass through jpeg_write_scanlines
+ * or jpeg_write_raw_data.
+ */
+ cinfo->next_scanline = 0;
+ cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
+}
+
+
+/*
+ * Write some scanlines of data to the JPEG compressor.
+ *
+ * The return value will be the number of lines actually written.
+ * This should be less than the supplied num_lines only in case that
+ * the data destination module has requested suspension of the compressor,
+ * or if more than image_height scanlines are passed in.
+ *
+ * Note: we warn about excess calls to jpeg_write_scanlines() since
+ * this likely signals an application programmer error. However,
+ * excess scanlines passed in the last valid call are *silently* ignored,
+ * so that the application need not adjust num_lines for end-of-image
+ * when using a multiple-scanline buffer.
+ */
+
+GLOBAL(JDIMENSION)
+jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
+ JDIMENSION num_lines)
+{
+ JDIMENSION row_ctr, rows_left;
+
+ if (cinfo->global_state != CSTATE_SCANNING)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ if (cinfo->next_scanline >= cinfo->image_height)
+ WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->next_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->image_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+
+ /* Give master control module another chance if this is first call to
+ * jpeg_write_scanlines. This lets output of the frame/scan headers be
+ * delayed so that application can write COM, etc, markers between
+ * jpeg_start_compress and jpeg_write_scanlines.
+ */
+ if (cinfo->master->call_pass_startup)
+ (*cinfo->master->pass_startup) (cinfo);
+
+ /* Ignore any extra scanlines at bottom of image. */
+ rows_left = cinfo->image_height - cinfo->next_scanline;
+ if (num_lines > rows_left)
+ num_lines = rows_left;
+
+ row_ctr = 0;
+ (*cinfo->mainp->process_data) (cinfo, scanlines, &row_ctr, num_lines);
+ cinfo->next_scanline += row_ctr;
+ return row_ctr;
+}
+
+
+/*
+ * Alternate entry point to write raw data.
+ * Processes exactly one iMCU row per call, unless suspended.
+ */
+
+GLOBAL(JDIMENSION)
+jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
+ JDIMENSION num_lines)
+{
+ JDIMENSION lines_per_iMCU_row;
+ register JDIMENSION width, line, col;
+ register JSAMPLE16 *temp_buf_ptr;
+ register JSAMPLE *in_buf_row_ptr;
+ int cmp;
+
+ if (cinfo->global_state != CSTATE_RAW_OK)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ if (cinfo->next_scanline >= cinfo->image_height) {
+ WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+ return 0;
+ }
+
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->next_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->image_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+
+ /* Give master control module another chance if this is first call to
+ * jpeg_write_raw_data. This lets output of the frame/scan headers be
+ * delayed so that application can write COM, etc, markers between
+ * jpeg_start_compress and jpeg_write_raw_data.
+ */
+ if (cinfo->master->call_pass_startup)
+ (*cinfo->master->pass_startup) (cinfo);
+
+ /* Verify that at least one iMCU row has been passed. */
+ lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->data_unit;
+ if (num_lines < lines_per_iMCU_row)
+ ERREXIT(cinfo, JERR_BUFFER_SIZE);
+
+ if (cinfo->data_precision_other > 8) {
+ /* Directly compress the row if short. */
+ if (! (*cinfo->codec->compress_data) (cinfo, (JSAMPIMAGE16)data)) {
+ /* If compressor did not consume the whole row, suspend processing. */
+ return 0;
+ }
+ } else {
+ /* 8 or less, time for buffering. */
+ if (cinfo->raw_data_buffer == NULL) { /* Not output suspension */
+ /* Allocate space for image array and copy the data if */
+ cinfo->raw_data_buffer = (JSAMPIMAGE16)cinfo->mem->alloc_small((j_common_ptr)cinfo, JPOOL_IMAGE_BUF,
+ (size_t) (cinfo->num_components));
+ for (cmp = 0; cmp < cinfo->num_components; cmp++) {
+ /* Allocate space for JSAMPARRAY16 arrays */
+ width = (JDIMENSION) (((long) cinfo->comp_info[cmp].width_in_data_units * cinfo->data_unit *
+ cinfo->max_h_samp_factor) / cinfo->comp_info[cmp].h_samp_factor);
+
+ /* (((cinfo->comp_info[cmp].h_samp_factor*cinfo->image_height)/DCTSIZE);*/
+ cinfo->raw_data_buffer[cmp] = (JSAMPARRAY16)(cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE_BUF,
+ width * SIZEOF(JSAMPLE16), (JDIMENSION) num_lines);
+ for (line = 0; line < num_lines; line++) {
+ temp_buf_ptr = cinfo->raw_data_buffer[cmp][line];
+ in_buf_row_ptr = data[cmp][line];
+ for (col = 0; col < width; col++)
+ *temp_buf_ptr++ = (JSAMPLE16) *in_buf_row_ptr++;
+ }
+ }
+ }
+ if (! (*cinfo->codec->compress_data) (cinfo, cinfo->raw_data_buffer))
+ /* If compressor did not consume the whole row, suspend processing,
+ and keep the buffer. */
+ return 0;
+ /* Free the buffer */
+ cinfo->mem->free_pool ((j_common_ptr)cinfo, JPOOL_IMAGE_BUF);
+ cinfo->raw_data_buffer = NULL;
+ }
+
+ /* OK, we processed one iMCU row. */
+ cinfo->next_scanline += lines_per_iMCU_row;
+ return lines_per_iMCU_row;
+}
diff --git a/jpeg-6c/jccoefct.c b/jpeg-6c/jccoefct.c
new file mode 100644
index 0000000..b47a5cf
--- /dev/null
+++ b/jpeg-6c/jccoefct.c
@@ -0,0 +1,455 @@
+/*
+ * jccoefct.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the coefficient buffer controller for compression.
+ * This controller is the top level of the JPEG compressor proper.
+ * The coefficient buffer lies between forward-DCT and entropy encoding steps.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h" /* Private declarations for lossy codec */
+
+
+/* We use a full-image coefficient buffer when doing Huffman optimization,
+ * and also for writing multiple-scan JPEG files. In all cases, the DCT
+ * step is run during the first pass, and subsequent passes need only read
+ * the buffered coefficients.
+ */
+#ifdef ENTROPY_OPT_SUPPORTED
+#define FULL_COEF_BUFFER_SUPPORTED
+#else
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+#define FULL_COEF_BUFFER_SUPPORTED
+#endif
+#endif
+
+
+/* Private buffer controller object */
+
+typedef struct {
+ JDIMENSION iMCU_row_num; /* iMCU row # within image */
+ JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
+ int MCU_vert_offset; /* counts MCU rows within iMCU row */
+ int MCU_rows_per_iMCU_row; /* number of such rows needed */
+
+ /* For single-pass compression, it's sufficient to buffer just one MCU
+ * (although this may prove a bit slow in practice). We allocate a
+ * workspace of C_MAX_DATA_UNITS_IN_MCU coefficient blocks, and reuse it for
+ * each MCU constructed and sent. (On 80x86, the workspace is FAR even
+ * though it's not really very big; this is to keep the module interfaces
+ * unchanged when a large coefficient buffer is necessary.)
+ * In multi-pass modes, this array points to the current MCU's blocks
+ * within the virtual arrays.
+ */
+ JBLOCKROW MCU_buffer[C_MAX_DATA_UNITS_IN_MCU];
+
+ /* In multi-pass modes, we need a virtual block array for each component. */
+ jvirt_barray_ptr whole_image[MAX_COMPONENTS];
+} c_coef_controller;
+
+typedef c_coef_controller * c_coef_ptr;
+
+
+/* Forward declarations */
+METHODDEF(boolean) compress_data
+ JPP((j_compress_ptr cinfo, JSAMPIMAGE16 input_buf));
+#ifdef FULL_COEF_BUFFER_SUPPORTED
+METHODDEF(boolean) compress_first_pass
+ JPP((j_compress_ptr cinfo, JSAMPIMAGE16 input_buf));
+METHODDEF(boolean) compress_output
+ JPP((j_compress_ptr cinfo, JSAMPIMAGE16 input_buf));
+#endif
+
+
+LOCAL(void)
+start_iMCU_row (j_compress_ptr cinfo)
+/* Reset within-iMCU-row counters for a new row */
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+ * But at the bottom of the image, process only what's left.
+ */
+ if (cinfo->comps_in_scan > 1) {
+ coef->MCU_rows_per_iMCU_row = 1;
+ } else {
+ if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
+ else
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
+ }
+
+ coef->mcu_ctr = 0;
+ coef->MCU_vert_offset = 0;
+}
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF(void)
+start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+
+ coef->iMCU_row_num = 0;
+ start_iMCU_row(cinfo);
+
+ switch (pass_mode) {
+ case JBUF_PASS_THRU:
+ if (coef->whole_image[0] != NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ lossyc->pub.compress_data = compress_data;
+ break;
+#ifdef FULL_COEF_BUFFER_SUPPORTED
+ case JBUF_SAVE_AND_PASS:
+ if (coef->whole_image[0] == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ lossyc->pub.compress_data = compress_first_pass;
+ break;
+ case JBUF_CRANK_DEST:
+ if (coef->whole_image[0] == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ lossyc->pub.compress_data = compress_output;
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ break;
+ }
+}
+
+
+/*
+ * Process some data in the single-pass case.
+ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
+ * per call, ie, v_samp_factor block rows for each component in the image.
+ * Returns TRUE if the iMCU row is completed, FALSE if suspended.
+ *
+ * NB: input_buf contains a plane for each component in image,
+ * which we index according to the component's SOF position.
+ */
+
+METHODDEF(boolean)
+compress_data (j_compress_ptr cinfo, JSAMPIMAGE16 input_buf)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ int blkn, bi, ci, yindex, yoffset, blockcnt;
+ JDIMENSION ypos, xpos;
+ jpeg_component_info *compptr;
+
+ /* Loop to write as much as one whole iMCU row */
+ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
+ yoffset++) {
+ for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
+ MCU_col_num++) {
+ /* Determine where data comes from in input_buf and do the DCT thing.
+ * Each call on forward_DCT processes a horizontal row of DCT blocks
+ * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
+ * sequentially. Dummy blocks at the right or bottom edge are filled in
+ * specially. The data in them does not matter for image reconstruction,
+ * so we fill them with values that will encode to the smallest amount of
+ * data, viz: all zeroes in the AC entries, DC entries equal to previous
+ * block's DC value. (Thanks to Thomas Kinsman for this idea.)
+ */
+ blkn = 0;
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
+ : compptr->last_col_width;
+ xpos = MCU_col_num * compptr->MCU_sample_width;
+ ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ if (coef->iMCU_row_num < last_iMCU_row ||
+ yoffset+yindex < compptr->last_row_height) {
+ (*lossyc->fdct_forward_DCT) (cinfo, compptr,
+ input_buf[compptr->component_index],
+ coef->MCU_buffer[blkn],
+ ypos, xpos, (JDIMENSION) blockcnt);
+ if (blockcnt < compptr->MCU_width) {
+ /* Create some dummy blocks at the right edge of the image. */
+ jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
+ (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
+ for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
+ coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
+ }
+ }
+ } else {
+ /* Create a row of dummy blocks at the bottom of the image. */
+ jzero_far((void FAR *) coef->MCU_buffer[blkn],
+ compptr->MCU_width * SIZEOF(JBLOCK));
+ for (bi = 0; bi < compptr->MCU_width; bi++) {
+ coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
+ }
+ }
+ blkn += compptr->MCU_width;
+ ypos += DCTSIZE;
+ }
+ }
+ /* Try to write the MCU. In event of a suspension failure, we will
+ * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
+ */
+ if (! (*lossyc->entropy_encode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->mcu_ctr = MCU_col_num;
+ return FALSE;
+ }
+ }
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ coef->mcu_ctr = 0;
+ }
+ /* Completed the iMCU row, advance counters for next one */
+ coef->iMCU_row_num++;
+ start_iMCU_row(cinfo);
+ return TRUE;
+}
+
+
+#ifdef FULL_COEF_BUFFER_SUPPORTED
+
+/*
+ * Process some data in the first pass of a multi-pass case.
+ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
+ * per call, ie, v_samp_factor block rows for each component in the image.
+ * This amount of data is read from the source buffer, DCT'd and quantized,
+ * and saved into the virtual arrays. We also generate suitable dummy blocks
+ * as needed at the right and lower edges. (The dummy blocks are constructed
+ * in the virtual arrays, which have been padded appropriately.) This makes
+ * it possible for subsequent passes not to worry about real vs. dummy blocks.
+ *
+ * We must also emit the data to the entropy encoder. This is conveniently
+ * done by calling compress_output() after we've loaded the current strip
+ * of the virtual arrays.
+ *
+ * NB: input_buf contains a plane for each component in image. All
+ * components are DCT'd and loaded into the virtual arrays in this pass.
+ * However, it may be that only a subset of the components are emitted to
+ * the entropy encoder during this first pass; be careful about looking
+ * at the scan-dependent variables (MCU dimensions, etc).
+ */
+
+METHODDEF(boolean)
+compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE16 input_buf)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION blocks_across, MCUs_across, MCUindex;
+ int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
+ JCOEF lastDC;
+ jpeg_component_info *compptr;
+ JBLOCKARRAY buffer;
+ JBLOCKROW thisblockrow, lastblockrow;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Align the virtual buffer for this component. */
+ buffer = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[ci],
+ coef->iMCU_row_num * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ /* Count non-dummy DCT block rows in this iMCU row. */
+ if (coef->iMCU_row_num < last_iMCU_row)
+ block_rows = compptr->v_samp_factor;
+ else {
+ /* NB: can't use last_row_height here, since may not be set! */
+ block_rows = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ }
+ blocks_across = compptr->width_in_data_units;
+ h_samp_factor = compptr->h_samp_factor;
+ /* Count number of dummy blocks to be added at the right margin. */
+ ndummy = (int) (blocks_across % h_samp_factor);
+ if (ndummy > 0)
+ ndummy = h_samp_factor - ndummy;
+ /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
+ * on forward_DCT processes a complete horizontal row of DCT blocks.
+ */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+ thisblockrow = buffer[block_row];
+ (*lossyc->fdct_forward_DCT) (cinfo, compptr,
+ input_buf[ci], thisblockrow,
+ (JDIMENSION) (block_row * DCTSIZE),
+ (JDIMENSION) 0, blocks_across);
+ if (ndummy > 0) {
+ /* Create dummy blocks at the right edge of the image. */
+ thisblockrow += blocks_across; /* => first dummy block */
+ jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
+ lastDC = thisblockrow[-1][0];
+ for (bi = 0; bi < ndummy; bi++) {
+ thisblockrow[bi][0] = lastDC;
+ }
+ }
+ }
+ /* If at end of image, create dummy block rows as needed.
+ * The tricky part here is that within each MCU, we want the DC values
+ * of the dummy blocks to match the last real block's DC value.
+ * This squeezes a few more bytes out of the resulting file...
+ */
+ if (coef->iMCU_row_num == last_iMCU_row) {
+ blocks_across += ndummy; /* include lower right corner */
+ MCUs_across = blocks_across / h_samp_factor;
+ for (block_row = block_rows; block_row < compptr->v_samp_factor;
+ block_row++) {
+ thisblockrow = buffer[block_row];
+ lastblockrow = buffer[block_row-1];
+ jzero_far((void FAR *) thisblockrow,
+ (size_t) (blocks_across * SIZEOF(JBLOCK)));
+ for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
+ lastDC = lastblockrow[h_samp_factor-1][0];
+ for (bi = 0; bi < h_samp_factor; bi++) {
+ thisblockrow[bi][0] = lastDC;
+ }
+ thisblockrow += h_samp_factor; /* advance to next MCU in row */
+ lastblockrow += h_samp_factor;
+ }
+ }
+ }
+ }
+ /* NB: compress_output will increment iMCU_row_num if successful.
+ * A suspension return will result in redoing all the work above next time.
+ */
+
+ /* Emit data to the entropy encoder, sharing code with subsequent passes */
+ return compress_output(cinfo, input_buf);
+}
+
+
+/*
+ * Process some data in subsequent passes of a multi-pass case.
+ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
+ * per call, ie, v_samp_factor block rows for each component in the scan.
+ * The data is obtained from the virtual arrays and fed to the entropy coder.
+ * Returns TRUE if the iMCU row is completed, FALSE if suspended.
+ *
+ * NB: input_buf is ignored; it is likely to be a NULL pointer.
+ */
+
+METHODDEF(boolean)
+compress_output (j_compress_ptr cinfo, JSAMPIMAGE16 input_buf)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ int blkn, ci, xindex, yindex, yoffset;
+ JDIMENSION start_col;
+ JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
+ JBLOCKROW buffer_ptr;
+ jpeg_component_info *compptr;
+
+ /* Align the virtual buffers for the components used in this scan.
+ * NB: during first pass, this is safe only because the buffers will
+ * already be aligned properly, so jmemmgr.c won't need to do any I/O.
+ */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ buffer[ci] = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
+ coef->iMCU_row_num * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ }
+
+ /* Loop to process one whole iMCU row */
+ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
+ yoffset++) {
+ for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
+ MCU_col_num++) {
+ /* Construct list of pointers to DCT blocks belonging to this MCU */
+ blkn = 0; /* index of current DCT block within MCU */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ start_col = MCU_col_num * compptr->MCU_width;
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
+ for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
+ coef->MCU_buffer[blkn++] = buffer_ptr++;
+ }
+ }
+ }
+ /* Try to write the MCU. */
+ if (! (*lossyc->entropy_encode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->mcu_ctr = MCU_col_num;
+ return FALSE;
+ }
+ }
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ coef->mcu_ctr = 0;
+ }
+ /* Completed the iMCU row, advance counters for next one */
+ coef->iMCU_row_num++;
+ start_iMCU_row(cinfo);
+ return TRUE;
+}
+
+#endif /* FULL_COEF_BUFFER_SUPPORTED */
+
+
+/*
+ * Initialize coefficient buffer controller.
+ */
+
+GLOBAL(void)
+jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ c_coef_ptr coef;
+
+ coef = (c_coef_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(c_coef_controller));
+ lossyc->coef_private = (struct jpeg_c_coef_controller *) coef;
+ lossyc->coef_start_pass = start_pass_coef;
+
+ /* Create the coefficient buffer. */
+ if (need_full_buffer) {
+#ifdef FULL_COEF_BUFFER_SUPPORTED
+ /* Allocate a full-image virtual array for each component, */
+ /* padded to a multiple of samp_factor DCT blocks in each direction. */
+ int ci;
+ jpeg_component_info *compptr;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JSAMPLE16),
+ (JDIMENSION) jround_up((long) compptr->height_in_data_units,
+ (long) compptr->v_samp_factor),
+ (JDIMENSION) compptr->v_samp_factor);
+ }
+#else
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+#endif
+ } else {
+ /* We only need a single-MCU buffer. */
+ JBLOCKROW buffer;
+ int i;
+
+ buffer = (JBLOCKROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ C_MAX_DATA_UNITS_IN_MCU * SIZEOF(JBLOCK));
+ for (i = 0; i < C_MAX_DATA_UNITS_IN_MCU; i++) {
+ coef->MCU_buffer[i] = buffer + i;
+ }
+ coef->whole_image[0] = NULL; /* flag for no virtual arrays */
+ }
+}
diff --git a/jpeg-6c/jccolor.c b/jpeg-6c/jccolor.c
new file mode 100644
index 0000000..46d0cb7
--- /dev/null
+++ b/jpeg-6c/jccolor.c
@@ -0,0 +1,644 @@
+/*
+ * jccolor.c
+ *
+ * Copyright (C) 1991-1996, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains input colorspace conversion routines.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_color_converter pub; /* public fields */
+
+ /* Private state for RGB->YCC conversion */
+ INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
+} my_color_converter;
+
+typedef my_color_converter * my_cconvert_ptr;
+
+
+/**************** RGB -> YCbCr conversion: most common case **************/
+
+/*
+ * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
+ * normalized to the range 0..cinfo->maxjsample rather than -0.5 .. 0.5.
+ * The conversion equations to be implemented are therefore
+ * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
+ * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + cinfo->centerjsample
+ * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + cinfo->centerjsample
+ * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
+ * Note: older versions of the IJG code used a zero offset of cinfo->maxjsample/2,
+ * rather than cinfo->centerjsample, for Cb and Cr. This gave equal positive and
+ * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
+ * were not represented exactly. Now we sacrifice exact representation of
+ * maximum red and maximum blue in order to get exact grayscales.
+ *
+ * To avoid floating-point arithmetic, we represent the fractional constants
+ * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
+ * the products by 2^16, with appropriate rounding, to get the correct answer.
+ *
+ * For even more speed, we avoid doing any multiplications in the inner loop
+ * by precalculating the constants times R,G,B for all possible values.
+ * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
+ * for 12-bit samples it is still acceptable. It's not very reasonable for
+ * 16-bit samples, but if you want lossless storage you shouldn't be changing
+ * colorspace anyway.
+ * The cinfo->centerjsample offsets and the rounding fudge-factor of 0.5 are included
+ * in the tables to save adding them separately in the inner loop.
+ */
+
+#define SCALEBITS 16 /* speediest right-shift on some machines */
+#define CBCR_OFFSET ((INT32) cinfo->centerjsample << SCALEBITS)
+#define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
+#define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
+
+/* We allocate one big table and divide it up into eight parts, instead of
+ * doing eight alloc_small requests. This lets us use a single table base
+ * address, which can be held in a register in the inner loops on many
+ * machines (more than can hold all eight addresses, anyway).
+ */
+
+#define R_Y_OFF 0 /* offset to R => Y section */
+#define G_Y_OFF (1*(cinfo->maxjsample+1)) /* offset to G => Y section */
+#define B_Y_OFF (2*(cinfo->maxjsample+1)) /* etc. */
+#define R_CB_OFF (3*(cinfo->maxjsample+1))
+#define G_CB_OFF (4*(cinfo->maxjsample+1))
+#define B_CB_OFF (5*(cinfo->maxjsample+1))
+#define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
+#define G_CR_OFF (6*(cinfo->maxjsample+1))
+#define B_CR_OFF (7*(cinfo->maxjsample+1))
+#define TABLE_SIZE (8*(cinfo->maxjsample+1))
+
+
+/*
+ * Initialize for RGB->YCC colorspace conversion.
+ */
+
+METHODDEF(void)
+rgb_ycc_start (j_compress_ptr cinfo)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ INT32 * rgb_ycc_tab;
+ INT32 i;
+
+ /* Allocate and fill in the conversion tables. */
+ cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (TABLE_SIZE * SIZEOF(INT32)));
+
+ for (i = 0; i <= cinfo->maxjsample; i++) {
+ rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
+ rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
+ rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
+ rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
+ rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
+ /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
+ * This ensures that the maximum output will round to cinfo->maxjsample
+ * not cinfo->maxjsample+1, and thus that we don't have to range-limit.
+ */
+ rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
+/* B=>Cb and R=>Cr tables are the same
+ rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
+*/
+ rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
+ rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
+ }
+}
+
+
+/*
+ * Convert some rows of samples to the JPEG colorspace.
+ *
+ * Note that we change from the application's interleaved-pixel format
+ * to our internal noninterleaved, one-plane-per-component format.
+ * The input buffer is therefore three times as wide as the output buffer.
+ *
+ * A starting row offset is provided only for the output buffer. The caller
+ * can easily adjust the passed input_buf value to accommodate any row
+ * offset required on that side.
+ */
+
+METHODDEF(void)
+rgb_ycc_convert8 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int r, g, b;
+ register INT32 * ctab = cconvert->rgb_ycc_tab;
+ register JSAMPROW inptr;
+ register JSAMPROW16 outptr0, outptr1, outptr2;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ inptr = *input_buf++;
+ outptr0 = output_buf[0][output_row];
+ outptr1 = output_buf[1][output_row];
+ outptr2 = output_buf[2][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ r = GETJSAMPLE(inptr[RGB_RED]);
+ g = GETJSAMPLE(inptr[RGB_GREEN]);
+ b = GETJSAMPLE(inptr[RGB_BLUE]);
+ inptr += RGB_PIXELSIZE;
+ /* If the inputs are 0..cinfo->maxjsample, the outputs of these equations
+ * must be too; we do not need an explicit range-limiting operation.
+ * Hence the value being shifted is never negative, and we don't
+ * need the general RIGHT_SHIFT macro.
+ */
+ /* Y */
+ outptr0[col] = (JSAMPLE16)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ /* Cb */
+ outptr1[col] = (JSAMPLE16)
+ ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+ >> SCALEBITS);
+ /* Cr */
+ outptr2[col] = (JSAMPLE16)
+ ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
+ >> SCALEBITS);
+ }
+ }
+}
+
+METHODDEF(void)
+rgb_ycc_convert16 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int r, g, b;
+ register INT32 * ctab = cconvert->rgb_ycc_tab;
+ register JSAMPROW16 inptr;
+ register JSAMPROW16 outptr0, outptr1, outptr2;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ inptr = (JSAMPROW16)*input_buf++;
+ outptr0 = output_buf[0][output_row];
+ outptr1 = output_buf[1][output_row];
+ outptr2 = output_buf[2][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ r = GETJSAMPLE(inptr[RGB_RED]);
+ g = GETJSAMPLE(inptr[RGB_GREEN]);
+ b = GETJSAMPLE(inptr[RGB_BLUE]);
+ inptr += RGB_PIXELSIZE;
+ /* If the inputs are 0..cinfo->maxjsample, the outputs of these equations
+ * must be too; we do not need an explicit range-limiting operation.
+ * Hence the value being shifted is never negative, and we don't
+ * need the general RIGHT_SHIFT macro.
+ */
+ /* Y */
+ outptr0[col] = (JSAMPLE16)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ /* Cb */
+ outptr1[col] = (JSAMPLE16)
+ ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+ >> SCALEBITS);
+ /* Cr */
+ outptr2[col] = (JSAMPLE16)
+ ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
+ >> SCALEBITS);
+ }
+ }
+}
+
+/**************** Cases other than RGB -> YCbCr **************/
+
+
+/*
+ * Convert some rows of samples to the JPEG colorspace.
+ * This version handles RGB->grayscale conversion, which is the same
+ * as the RGB->Y portion of RGB->YCbCr.
+ * We assume rgb_ycc_start has been called (we only use the Y tables).
+ */
+
+METHODDEF(void)
+rgb_gray_convert8 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int r, g, b;
+ register INT32 * ctab = cconvert->rgb_ycc_tab;
+ register JSAMPROW inptr;
+ register JSAMPROW16 outptr;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ inptr = *input_buf++;
+ outptr = output_buf[0][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ r = GETJSAMPLE(inptr[RGB_RED]);
+ g = GETJSAMPLE(inptr[RGB_GREEN]);
+ b = GETJSAMPLE(inptr[RGB_BLUE]);
+ inptr += RGB_PIXELSIZE;
+ /* Y */
+ outptr[col] = (JSAMPLE16)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ }
+ }
+}
+
+METHODDEF(void)
+rgb_gray_convert16 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int r, g, b;
+ register INT32 * ctab = cconvert->rgb_ycc_tab;
+ register JSAMPROW16 inptr;
+ register JSAMPROW16 outptr;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ inptr = (JSAMPROW16)*input_buf++;
+ outptr = output_buf[0][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ r = GETJSAMPLE(inptr[RGB_RED]);
+ g = GETJSAMPLE(inptr[RGB_GREEN]);
+ b = GETJSAMPLE(inptr[RGB_BLUE]);
+ inptr += RGB_PIXELSIZE;
+ /* Y */
+ outptr[col] = (JSAMPLE16)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ }
+ }
+}
+
+
+/*
+ * Convert some rows of samples to the JPEG colorspace.
+ * This version handles Adobe-style CMYK->YCCK conversion,
+ * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
+ * conversion as above, while passing K (black) unchanged.
+ * We assume rgb_ycc_start has been called.
+ */
+
+METHODDEF(void)
+cmyk_ycck_convert8 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int r, g, b;
+ register INT32 * ctab = cconvert->rgb_ycc_tab;
+ register JSAMPROW inptr;
+ register JSAMPROW16 outptr0, outptr1, outptr2, outptr3;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ inptr = *input_buf++;
+ outptr0 = output_buf[0][output_row];
+ outptr1 = output_buf[1][output_row];
+ outptr2 = output_buf[2][output_row];
+ outptr3 = output_buf[3][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ r = cinfo->maxjsample - GETJSAMPLE(inptr[0]);
+ g = cinfo->maxjsample - GETJSAMPLE(inptr[1]);
+ b = cinfo->maxjsample - GETJSAMPLE(inptr[2]);
+ /* K passes through as-is */
+ outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
+ inptr += 4;
+ /* If the inputs are 0..cinfo->maxjsample, the outputs of these equations
+ * must be too; we do not need an explicit range-limiting operation.
+ * Hence the value being shifted is never negative, and we don't
+ * need the general RIGHT_SHIFT macro.
+ */
+ /* Y */
+ outptr0[col] = (JSAMPLE16)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ /* Cb */
+ outptr1[col] = (JSAMPLE16)
+ ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+ >> SCALEBITS);
+ /* Cr */
+ outptr2[col] = (JSAMPLE16)
+ ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
+ >> SCALEBITS);
+ }
+ }
+}
+
+METHODDEF(void)
+cmyk_ycck_convert16 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int r, g, b;
+ register INT32 * ctab = cconvert->rgb_ycc_tab;
+ register JSAMPROW16 inptr;
+ register JSAMPROW16 outptr0, outptr1, outptr2, outptr3;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ inptr = (JSAMPROW16)*input_buf++;
+ outptr0 = output_buf[0][output_row];
+ outptr1 = output_buf[1][output_row];
+ outptr2 = output_buf[2][output_row];
+ outptr3 = output_buf[3][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ r = cinfo->maxjsample - GETJSAMPLE(inptr[0]);
+ g = cinfo->maxjsample - GETJSAMPLE(inptr[1]);
+ b = cinfo->maxjsample - GETJSAMPLE(inptr[2]);
+ /* K passes through as-is */
+ outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
+ inptr += 4;
+ /* If the inputs are 0..cinfo->maxjsample, the outputs of these equations
+ * must be too; we do not need an explicit range-limiting operation.
+ * Hence the value being shifted is never negative, and we don't
+ * need the general RIGHT_SHIFT macro.
+ */
+ /* Y */
+ outptr0[col] = (JSAMPLE16)
+ ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+ >> SCALEBITS);
+ /* Cb */
+ outptr1[col] = (JSAMPLE16)
+ ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+ >> SCALEBITS);
+ /* Cr */
+ outptr2[col] = (JSAMPLE16)
+ ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
+ >> SCALEBITS);
+ }
+ }
+}
+
+
+/*
+ * Convert some rows of samples to the JPEG colorspace.
+ * This version handles grayscale output with no conversion.
+ * The source can be either plain grayscale or YCbCr (since Y == gray).
+ */
+
+METHODDEF(void)
+grayscale_convert8 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ register JSAMPROW inptr;
+ register JSAMPROW16 outptr;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+ int instride = cinfo->input_components;
+
+ while (--num_rows >= 0) {
+ inptr = *input_buf++;
+ outptr = output_buf[0][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
+ inptr += instride;
+ }
+ }
+}
+
+METHODDEF(void)
+grayscale_convert16 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ register JSAMPROW16 inptr;
+ register JSAMPROW16 outptr;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->image_width;
+ int instride = cinfo->input_components;
+
+ while (--num_rows >= 0) {
+ inptr = (JSAMPROW16)*input_buf++;
+ outptr = output_buf[0][output_row];
+ output_row++;
+ for (col = 0; col < num_cols; col++) {
+ outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
+ inptr += instride;
+ }
+ }
+}
+
+
+/*
+ * Convert some rows of samples to the JPEG colorspace.
+ * This version handles multi-component colorspaces without conversion.
+ * We assume input_components == num_components.
+ */
+
+METHODDEF(void)
+null_convert8 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ register JSAMPROW inptr;
+ register JSAMPROW16 outptr;
+ register JDIMENSION col;
+ register int ci;
+ int nc = cinfo->num_components;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ /* It seems fastest to make a separate pass for each component. */
+ for (ci = 0; ci < nc; ci++) {
+ inptr = *input_buf;
+ outptr = output_buf[ci][output_row];
+ for (col = 0; col < num_cols; col++) {
+ outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
+ inptr += nc;
+ }
+ }
+ input_buf++;
+ output_row++;
+ }
+}
+
+METHODDEF(void)
+null_convert16 (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows)
+{
+ register JSAMPROW16 inptr;
+ register JSAMPROW16 outptr;
+ register JDIMENSION col;
+ register int ci;
+ int nc = cinfo->num_components;
+ JDIMENSION num_cols = cinfo->image_width;
+
+ while (--num_rows >= 0) {
+ /* It seems fastest to make a separate pass for each component. */
+ for (ci = 0; ci < nc; ci++) {
+ inptr = (JSAMPROW16)*input_buf;
+ outptr = output_buf[ci][output_row];
+ for (col = 0; col < num_cols; col++) {
+ outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
+ inptr += nc;
+ }
+ }
+ input_buf++;
+ output_row++;
+ }
+}
+
+
+/*
+ * Empty method for start_pass.
+ */
+
+METHODDEF(void)
+null_method (j_compress_ptr cinfo)
+{
+ /* no work needed */
+}
+
+
+/*
+ * Module initialization routine for input colorspace conversion.
+ */
+
+GLOBAL(void)
+jinit_color_converter (j_compress_ptr cinfo)
+{
+ my_cconvert_ptr cconvert;
+ boolean inp8 = FALSE;
+
+ if (cinfo->data_precision_other <= 8) inp8 = TRUE;
+
+ cconvert = (my_cconvert_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_color_converter));
+ cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
+ /* set start_pass to null method until we find out differently */
+ cconvert->pub.start_pass = null_method;
+
+ /* Make sure input_components agrees with in_color_space */
+ switch (cinfo->in_color_space) {
+ case JCS_GRAYSCALE:
+ if (cinfo->input_components != 1)
+ ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+ break;
+
+ case JCS_RGB:
+#if RGB_PIXELSIZE != 3
+ if (cinfo->input_components != RGB_PIXELSIZE)
+ ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+ break;
+#endif /* else share code with YCbCr */
+
+ case JCS_YCbCr:
+ if (cinfo->input_components != 3)
+ ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+ break;
+
+ case JCS_CMYK:
+ case JCS_YCCK:
+ if (cinfo->input_components != 4)
+ ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+ break;
+
+ default: /* JCS_UNKNOWN can be anything */
+ if (cinfo->input_components < 1)
+ ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+ break;
+ }
+
+ /* Check num_components, set conversion method based on requested space */
+ switch (cinfo->jpeg_color_space) {
+ case JCS_GRAYSCALE:
+ if (cinfo->num_components != 1)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ if (cinfo->in_color_space == JCS_GRAYSCALE) {
+ if (inp8) cconvert->pub.color_convert = grayscale_convert8;
+ else cconvert->pub.color_convert = grayscale_convert16; }
+ else if (cinfo->in_color_space == JCS_RGB) {
+ cconvert->pub.start_pass = rgb_ycc_start;
+ if (inp8) cconvert->pub.color_convert = rgb_gray_convert8;
+ else cconvert->pub.color_convert = rgb_gray_convert16;
+ } else if (cinfo->in_color_space == JCS_YCbCr) {
+ if (inp8) cconvert->pub.color_convert = grayscale_convert8;
+ else cconvert->pub.color_convert = grayscale_convert16; }
+ else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_RGB:
+ if (cinfo->num_components != 3)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
+ if (inp8) cconvert->pub.color_convert = null_convert8;
+ else cconvert->pub.color_convert = null_convert16; }
+ else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_YCbCr:
+ if (cinfo->num_components != 3)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ if (cinfo->in_color_space == JCS_RGB) {
+ cconvert->pub.start_pass = rgb_ycc_start;
+ if (inp8) cconvert->pub.color_convert = rgb_ycc_convert8;
+ else cconvert->pub.color_convert = rgb_ycc_convert16;
+ } else if (cinfo->in_color_space == JCS_YCbCr) {
+ if (inp8) cconvert->pub.color_convert = null_convert8;
+ else cconvert->pub.color_convert = null_convert16; }
+ else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_CMYK:
+ if (cinfo->num_components != 4)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ if (cinfo->in_color_space == JCS_CMYK) {
+ if (inp8) cconvert->pub.color_convert = null_convert8;
+ else cconvert->pub.color_convert = null_convert16; }
+ else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_YCCK:
+ if (cinfo->num_components != 4)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ if (cinfo->in_color_space == JCS_CMYK) {
+ cconvert->pub.start_pass = rgb_ycc_start;
+ if (inp8) cconvert->pub.color_convert = cmyk_ycck_convert8;
+ else cconvert->pub.color_convert = cmyk_ycck_convert16;
+ } else if (cinfo->in_color_space == JCS_YCCK) {
+ if (inp8) cconvert->pub.color_convert = null_convert8;
+ else cconvert->pub.color_convert = null_convert16; }
+ else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ default: /* allow null conversion of JCS_UNKNOWN */
+ if (cinfo->jpeg_color_space != cinfo->in_color_space ||
+ cinfo->num_components != cinfo->input_components)
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ if (inp8) cconvert->pub.color_convert = null_convert8;
+ else cconvert->pub.color_convert = null_convert16;
+ break;
+ }
+}
diff --git a/jpeg-6c/jcdctmgr.c b/jpeg-6c/jcdctmgr.c
new file mode 100644
index 0000000..c789032
--- /dev/null
+++ b/jpeg-6c/jcdctmgr.c
@@ -0,0 +1,394 @@
+/*
+ * jcdctmgr.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the forward-DCT management logic.
+ * This code selects a particular DCT implementation to be used,
+ * and it performs related housekeeping chores including coefficient
+ * quantization.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h" /* Private declarations for lossy codec */
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+
+/* Private subobject for this module */
+
+typedef struct {
+ /* Pointer to the DCT routine actually in use */
+ forward_DCT_method_ptr do_dct;
+
+ /* The actual post-DCT divisors --- not identical to the quant table
+ * entries, because of scaling (especially for an unnormalized DCT).
+ * Each table is given in normal array order.
+ */
+ DCTELEM * divisors[NUM_QUANT_TBLS];
+
+#ifdef DCT_FLOAT_SUPPORTED
+ /* Same as above for the floating-point case. */
+ float_DCT_method_ptr do_float_dct;
+ FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
+#endif
+} fdct_controller;
+
+typedef fdct_controller * fdct_ptr;
+
+
+/*
+ * Initialize for a processing pass.
+ * Verify that all referenced Q-tables are present, and set up
+ * the divisor table for each one.
+ * In the current implementation, DCT of all components is done during
+ * the first pass, even if only some components will be output in the
+ * first scan. Hence all components should be examined here.
+ */
+
+METHODDEF(void)
+start_pass_fdctmgr (j_compress_ptr cinfo)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ fdct_ptr fdct = (fdct_ptr) lossyc->fdct_private;
+ int ci, qtblno, i;
+ jpeg_component_info *compptr;
+ JQUANT_TBL * qtbl;
+ DCTELEM * dtbl;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ qtblno = compptr->quant_tbl_no;
+ /* Make sure specified quantization table is present */
+ if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
+ cinfo->quant_tbl_ptrs[qtblno] == NULL)
+ ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
+ qtbl = cinfo->quant_tbl_ptrs[qtblno];
+ /* Compute divisors for this quant table */
+ /* We may do this more than once for same table, but it's not a big deal */
+ switch (cinfo->dct_method) {
+#ifdef DCT_ISLOW_SUPPORTED
+ case JDCT_ISLOW:
+ /* For LL&M IDCT method, divisors are equal to raw quantization
+ * coefficients multiplied by 8 (to counteract scaling).
+ */
+ if (fdct->divisors[qtblno] == NULL) {
+ fdct->divisors[qtblno] = (DCTELEM *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ DCTSIZE2 * SIZEOF(DCTELEM));
+ }
+ dtbl = fdct->divisors[qtblno];
+ for (i = 0; i < DCTSIZE2; i++) {
+ dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
+ }
+ break;
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+ case JDCT_IFAST:
+ {
+ /* For AA&N IDCT method, divisors are equal to quantization
+ * coefficients scaled by scalefactor[row]*scalefactor[col], where
+ * scalefactor[0] = 1
+ * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
+ * We apply a further scale factor of 8.
+ */
+#define CONST_BITS 14
+ static const INT16 aanscales[DCTSIZE2] = {
+ /* precomputed values scaled up by 14 bits */
+ 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
+ 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
+ 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
+ 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
+ 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
+ 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
+ 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
+ 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
+ };
+ SHIFT_TEMPS
+
+ if (fdct->divisors[qtblno] == NULL) {
+ fdct->divisors[qtblno] = (DCTELEM *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ DCTSIZE2 * SIZEOF(DCTELEM));
+ }
+ dtbl = fdct->divisors[qtblno];
+ for (i = 0; i < DCTSIZE2; i++) {
+ dtbl[i] = (DCTELEM)
+ DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
+ (INT32) aanscales[i]),
+ CONST_BITS-3);
+ }
+ }
+ break;
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ case JDCT_FLOAT:
+ {
+ /* For float AA&N IDCT method, divisors are equal to quantization
+ * coefficients scaled by scalefactor[row]*scalefactor[col], where
+ * scalefactor[0] = 1
+ * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
+ * We apply a further scale factor of 8.
+ * What's actually stored is 1/divisor so that the inner loop can
+ * use a multiplication rather than a division.
+ */
+ FAST_FLOAT * fdtbl;
+ int row, col;
+ static const double aanscalefactor[DCTSIZE] = {
+ 1.0, 1.387039845, 1.306562965, 1.175875602,
+ 1.0, 0.785694958, 0.541196100, 0.275899379
+ };
+
+ if (fdct->float_divisors[qtblno] == NULL) {
+ fdct->float_divisors[qtblno] = (FAST_FLOAT *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ DCTSIZE2 * SIZEOF(FAST_FLOAT));
+ }
+ fdtbl = fdct->float_divisors[qtblno];
+ i = 0;
+ for (row = 0; row < DCTSIZE; row++) {
+ for (col = 0; col < DCTSIZE; col++) {
+ fdtbl[i] = (FAST_FLOAT)
+ (1.0 / (((double) qtbl->quantval[i] *
+ aanscalefactor[row] * aanscalefactor[col] * 8.0)));
+ i++;
+ }
+ }
+ }
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ break;
+ }
+ }
+}
+
+
+/*
+ * Perform forward DCT on one or more blocks of a component.
+ *
+ * The input samples are taken from the sample_data[] array starting at
+ * position start_row/start_col, and moving to the right for any additional
+ * blocks. The quantized coefficients are returned in coef_blocks[].
+ */
+
+METHODDEF(void)
+forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 sample_data, JBLOCKROW coef_blocks,
+ JDIMENSION start_row, JDIMENSION start_col,
+ JDIMENSION num_blocks)
+/* This version is used for integer DCT implementations. */
+{
+ /* This routine is heavily used, so it's worth coding it tightly. */
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ fdct_ptr fdct = (fdct_ptr) lossyc->fdct_private;
+ forward_DCT_method_ptr do_dct = fdct->do_dct;
+ DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
+ DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
+ JDIMENSION bi;
+ boolean jpeg8 = FALSE;
+
+ if (cinfo->data_precision <= 8) jpeg8 = TRUE;
+
+ sample_data += start_row; /* fold in the vertical offset once */
+
+ for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
+ /* Load data into workspace, applying unsigned->signed conversion */
+ { register DCTELEM *workspaceptr;
+ register JSAMPROW16 elemptr;
+ register int elemr;
+
+ workspaceptr = workspace;
+ for (elemr = 0; elemr < DCTSIZE; elemr++) {
+ elemptr = sample_data[elemr] + start_col;
+#if DCTSIZE == 8 /* unroll the inner loop */
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+#else
+ { register int elemc;
+ for (elemc = DCTSIZE; elemc > 0; elemc--) {
+ *workspaceptr++ = GETJSAMPLE(*elemptr++) - cinfo->centerjsample;
+ }
+ }
+#endif
+ }
+ }
+
+ /* Perform the DCT */
+ (*do_dct) (workspace, jpeg8);
+
+ /* Quantize/descale the coefficients, and store into coef_blocks[] */
+ { register DCTELEM temp, qval;
+ register int i;
+ register JCOEFPTR output_ptr = coef_blocks[bi];
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ qval = divisors[i];
+ temp = workspace[i];
+ /* Divide the coefficient value by qval, ensuring proper rounding.
+ * Since C does not specify the direction of rounding for negative
+ * quotients, we have to force the dividend positive for portability.
+ *
+ * In most files, at least half of the output values will be zero
+ * (at default quantization settings, more like three-quarters...)
+ * so we should ensure that this case is fast. On many machines,
+ * a comparison is enough cheaper than a divide to make a special test
+ * a win. Since both inputs will be nonnegative, we need only test
+ * for a < b to discover whether a/b is 0.
+ * If your machine's division is fast enough, define FAST_DIVIDE.
+ */
+#ifdef FAST_DIVIDE
+#define DIVIDE_BY(a,b) a /= b
+#else
+#define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
+#endif
+ if (temp < 0) {
+ temp = -temp;
+ temp += qval>>1; /* for rounding */
+ DIVIDE_BY(temp, qval);
+ temp = -temp;
+ } else {
+ temp += qval>>1; /* for rounding */
+ DIVIDE_BY(temp, qval);
+ }
+ output_ptr[i] = (JCOEF) temp;
+ }
+ }
+ }
+}
+
+
+#ifdef DCT_FLOAT_SUPPORTED
+
+METHODDEF(void)
+forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 sample_data, JBLOCKROW coef_blocks,
+ JDIMENSION start_row, JDIMENSION start_col,
+ JDIMENSION num_blocks)
+/* This version is used for floating-point DCT implementations. */
+{
+ /* This routine is heavily used, so it's worth coding it tightly. */
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ fdct_ptr fdct = (fdct_ptr) lossyc->fdct_private;
+ float_DCT_method_ptr do_dct = fdct->do_float_dct;
+ FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
+ FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
+ JDIMENSION bi;
+
+ sample_data += start_row; /* fold in the vertical offset once */
+
+ for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
+ /* Load data into workspace, applying unsigned->signed conversion */
+ { register FAST_FLOAT *workspaceptr;
+ register JSAMPROW16 elemptr;
+ register int elemr;
+
+ workspaceptr = workspace;
+ for (elemr = 0; elemr < DCTSIZE; elemr++) {
+ elemptr = sample_data[elemr] + start_col;
+#if DCTSIZE == 8 /* unroll the inner loop */
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+#else
+ { register int elemc;
+ for (elemc = DCTSIZE; elemc > 0; elemc--) {
+ *workspaceptr++ = (FAST_FLOAT)
+ (GETJSAMPLE(*elemptr++) - cinfo->centerjsample);
+ }
+ }
+#endif
+ }
+ }
+
+ /* Perform the DCT */
+ (*do_dct) (workspace);
+
+ /* Quantize/descale the coefficients, and store into coef_blocks[] */
+ { register FAST_FLOAT temp;
+ register int i;
+ register JCOEFPTR output_ptr = coef_blocks[bi];
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ /* Apply the quantization and scaling factor */
+ temp = workspace[i] * divisors[i];
+ /* Round to nearest integer.
+ * Since C does not specify the direction of rounding for negative
+ * quotients, we have to force the dividend positive for portability.
+ * The maximum coefficient size is +-16K (for 12-bit data), so this
+ * code should work for either 16-bit or 32-bit ints.
+ */
+ output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
+ }
+ }
+ }
+}
+
+#endif /* DCT_FLOAT_SUPPORTED */
+
+
+/*
+ * Initialize FDCT manager.
+ */
+
+GLOBAL(void)
+jinit_forward_dct (j_compress_ptr cinfo)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ fdct_ptr fdct;
+ int i;
+
+ fdct = (fdct_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(fdct_controller));
+ lossyc->fdct_private = (struct jpeg_forward_dct *) fdct;
+ lossyc->fdct_start_pass = start_pass_fdctmgr;
+
+ switch (cinfo->dct_method) {
+#ifdef DCT_ISLOW_SUPPORTED
+ case JDCT_ISLOW:
+ lossyc->fdct_forward_DCT = forward_DCT;
+ fdct->do_dct = jpeg_fdct_islow;
+ break;
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+ case JDCT_IFAST:
+ lossyc->fdct_forward_DCT = forward_DCT;
+ fdct->do_dct = jpeg_fdct_ifast;
+ break;
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ case JDCT_FLOAT:
+ lossyc->fdct_forward_DCT = forward_DCT_float;
+ fdct->do_float_dct = jpeg_fdct_float;
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ break;
+ }
+
+ /* Mark divisor tables unallocated */
+ for (i = 0; i < NUM_QUANT_TBLS; i++) {
+ fdct->divisors[i] = NULL;
+#ifdef DCT_FLOAT_SUPPORTED
+ fdct->float_divisors[i] = NULL;
+#endif
+ }
+}
diff --git a/jpeg-6c/jcdiffct.c b/jpeg-6c/jcdiffct.c
new file mode 100644
index 0000000..e83c59b
--- /dev/null
+++ b/jpeg-6c/jcdiffct.c
@@ -0,0 +1,410 @@
+/*
+ * jcdiffct.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the difference buffer controller for compression.
+ * This controller is the top level of the lossless JPEG compressor proper.
+ * The difference buffer lies between prediction/differencing and entropy
+ * encoding.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossls.h" /* Private declarations for lossless codec */
+
+
+#ifdef C_LOSSLESS_SUPPORTED
+
+/* We use a full-image sample buffer when doing Huffman optimization,
+ * and also for writing multiple-scan JPEG files. In all cases, the
+ * full-image buffer is filled during the first pass, and the scaling,
+ * prediction and differencing steps are run during subsequent passes.
+ */
+#ifdef ENTROPY_OPT_SUPPORTED
+#define FULL_SAMP_BUFFER_SUPPORTED
+#else
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+#define FULL_SAMP_BUFFER_SUPPORTED
+#endif
+#endif
+
+
+/* Private buffer controller object */
+
+typedef struct {
+ JDIMENSION iMCU_row_num; /* iMCU row # within image */
+ JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
+ int MCU_vert_offset; /* counts MCU rows within iMCU row */
+ int MCU_rows_per_iMCU_row; /* number of such rows needed */
+
+ JSAMPROW16 cur_row[MAX_COMPONENTS]; /* row of point transformed samples */
+ JSAMPROW16 prev_row[MAX_COMPONENTS]; /* previous row of Pt'd samples */
+ JDIFFARRAY diff_buf[MAX_COMPONENTS]; /* iMCU row of differences */
+
+ /* In multi-pass modes, we need a virtual sample array for each component. */
+ jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
+} c_diff_controller;
+
+typedef c_diff_controller * c_diff_ptr;
+
+
+/* Forward declarations */
+METHODDEF(boolean) compress_data
+ JPP((j_compress_ptr cinfo, JSAMPIMAGE16 input_buf));
+#ifdef FULL_SAMP_BUFFER_SUPPORTED
+METHODDEF(boolean) compress_first_pass
+ JPP((j_compress_ptr cinfo, JSAMPIMAGE16 input_buf));
+METHODDEF(boolean) compress_output
+ JPP((j_compress_ptr cinfo, JSAMPIMAGE16 input_buf));
+#endif
+
+
+LOCAL(void)
+start_iMCU_row (j_compress_ptr cinfo)
+/* Reset within-iMCU-row counters for a new row */
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ c_diff_ptr diff = (c_diff_ptr) losslsc->diff_private;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+ * But at the bottom of the image, process only what's left.
+ */
+ if (cinfo->comps_in_scan > 1) {
+ diff->MCU_rows_per_iMCU_row = 1;
+ } else {
+ if (diff->iMCU_row_num < (cinfo->total_iMCU_rows-1))
+ diff->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
+ else
+ diff->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
+ }
+
+ diff->mcu_ctr = 0;
+ diff->MCU_vert_offset = 0;
+}
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF(void)
+start_pass_diff (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ c_diff_ptr diff = (c_diff_ptr) losslsc->diff_private;
+
+ diff->iMCU_row_num = 0;
+ start_iMCU_row(cinfo);
+
+ switch (pass_mode) {
+ case JBUF_PASS_THRU:
+ if (diff->whole_image[0] != NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ losslsc->pub.compress_data = compress_data;
+ break;
+#ifdef FULL_SAMP_BUFFER_SUPPORTED
+ case JBUF_SAVE_AND_PASS:
+ if (diff->whole_image[0] == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ losslsc->pub.compress_data = compress_first_pass;
+ break;
+ case JBUF_CRANK_DEST:
+ if (diff->whole_image[0] == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ losslsc->pub.compress_data = compress_output;
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ break;
+ }
+}
+
+
+#define SWAP_ROWS(rowa,rowb) {JSAMPROW16 temp; temp=rowa; rowa=rowb; rowb=temp;}
+
+/*
+ * Process some data in the single-pass case.
+ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
+ * per call, ie, v_samp_factor rows for each component in the image.
+ * Returns TRUE if the iMCU row is completed, FALSE if suspended.
+ *
+ * NB: input_buf contains a plane for each component in image,
+ * which we index according to the component's SOF position.
+ */
+
+METHODDEF(boolean)
+compress_data (j_compress_ptr cinfo, JSAMPIMAGE16 input_buf)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ c_diff_ptr diff = (c_diff_ptr) losslsc->diff_private;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION MCU_count; /* number of MCUs encoded */
+/* JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;*/
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ int comp, ci, yoffset, samp_row, samp_rows, samps_across;
+ jpeg_component_info *compptr;
+
+ /* Loop to write as much as one whole iMCU row */
+ for (yoffset = diff->MCU_vert_offset; yoffset < diff->MCU_rows_per_iMCU_row;
+ yoffset++) {
+
+ MCU_col_num = diff->mcu_ctr;
+
+ /* Scale and predict each scanline of the MCU-row separately.
+ *
+ * Note: We only do this if we are at the start of a MCU-row, ie,
+ * we don't want to reprocess a row suspended by the output.
+ */
+ if (MCU_col_num == 0) {
+ for (comp = 0; comp < cinfo->comps_in_scan; comp++) {
+ compptr = cinfo->cur_comp_info[comp];
+ ci = compptr->component_index;
+ if (diff->iMCU_row_num < last_iMCU_row)
+ samp_rows = compptr->v_samp_factor;
+ else {
+ /* NB: can't use last_row_height here, since may not be set! */
+ samp_rows = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
+ if (samp_rows == 0) samp_rows = compptr->v_samp_factor;
+ else {
+ /* Fill dummy difference rows at the bottom edge with zeros, which
+ * will encode to the smallest amount of data.
+ */
+ for (samp_row = samp_rows; samp_row < compptr->v_samp_factor;
+ samp_row++)
+ MEMZERO(diff->diff_buf[ci][samp_row],
+ jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JDIFF));
+ }
+ }
+ samps_across = compptr->width_in_data_units;
+
+ for (samp_row = 0; samp_row < samp_rows; samp_row++) {
+ (*losslsc->scaler_scale) (cinfo,
+ input_buf[ci][samp_row],
+ diff->cur_row[ci], samps_across);
+ (*losslsc->predict_difference[ci]) (cinfo, ci,
+ diff->cur_row[ci],
+ diff->prev_row[ci],
+ diff->diff_buf[ci][samp_row],
+ samps_across);
+ SWAP_ROWS(diff->cur_row[ci], diff->prev_row[ci]);
+ }
+ }
+ }
+
+ /* Try to write the MCU-row (or remaining portion of suspended MCU-row). */
+ MCU_count =
+ (*losslsc->entropy_encode_mcus) (cinfo,
+ diff->diff_buf, yoffset, MCU_col_num,
+ cinfo->MCUs_per_row - MCU_col_num);
+ if (MCU_count != cinfo->MCUs_per_row - MCU_col_num) {
+ /* Suspension forced; update state counters and exit */
+ diff->MCU_vert_offset = yoffset;
+ diff->mcu_ctr += MCU_col_num;
+ return FALSE;
+ }
+
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ diff->mcu_ctr = 0;
+ }
+
+ /* Completed the iMCU row, advance counters for next one */
+ diff->iMCU_row_num++;
+ start_iMCU_row(cinfo);
+ return TRUE;
+}
+
+
+#ifdef FULL_SAMP_BUFFER_SUPPORTED
+
+/*
+ * Process some data in the first pass of a multi-pass case.
+ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
+ * per call, ie, v_samp_factor rows for each component in the image.
+ * This amount of data is read from the source buffer and saved into the
+ * virtual arrays.
+ *
+ * We must also emit the data to the compressor. This is conveniently
+ * done by calling compress_output() after we've loaded the current strip
+ * of the virtual arrays.
+ *
+ * NB: input_buf contains a plane for each component in image. All components
+ * are loaded into the virtual arrays in this pass. However, it may be that
+ * only a subset of the components are emitted to the compressor during
+ * this first pass; be careful about looking at the scan-dependent variables
+ * (MCU dimensions, etc).
+ */
+
+METHODDEF(boolean)
+compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE16 input_buf)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ c_diff_ptr diff = (c_diff_ptr) losslsc->diff_private;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION samps_across;
+ int ci, samp_row, samp_rows;
+ JSAMPARRAY16 buffer[MAX_COMPONENTS];
+ jpeg_component_info *compptr;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Align the virtual buffers for this component. */
+ buffer[ci] = (JSAMPARRAY16)(*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, diff->whole_image[ci],
+ diff->iMCU_row_num * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+
+ /* Count non-dummy sample rows in this iMCU row. */
+ if (diff->iMCU_row_num < last_iMCU_row)
+ samp_rows = compptr->v_samp_factor;
+ else {
+ /* NB: can't use last_row_height here, since may not be set! */
+ samp_rows = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
+ if (samp_rows == 0) samp_rows = compptr->v_samp_factor;
+ }
+ samps_across = compptr->width_in_data_units;
+
+ /* Perform point transform scaling and prediction/differencing for all
+ * non-dummy rows in this iMCU row. Each call on these functions
+ * process a complete row of samples.
+ */
+ for (samp_row = 0; samp_row < samp_rows; samp_row++) {
+ MEMCOPY(buffer[ci][samp_row], input_buf[ci][samp_row],
+ samps_across * SIZEOF(JSAMPLE16));
+ }
+ }
+
+ /* NB: compress_output will increment iMCU_row_num if successful.
+ * A suspension return will result in redoing all the work above next time.
+ */
+
+ /* Emit data to the compressor, sharing code with subsequent passes */
+ return compress_output(cinfo, input_buf);
+}
+
+
+/*
+ * Process some data in subsequent passes of a multi-pass case.
+ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
+ * per call, ie, v_samp_factor rows for each component in the scan.
+ * The data is obtained from the virtual arrays and fed to the compressor.
+ * Returns TRUE if the iMCU row is completed, FALSE if suspended.
+ *
+ * NB: input_buf is ignored; it is likely to be a NULL pointer.
+ */
+
+METHODDEF(boolean)
+compress_output (j_compress_ptr cinfo, JSAMPIMAGE16 input_buf)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ c_diff_ptr diff = (c_diff_ptr) losslsc->diff_private;
+/* JDIMENSION MCU_col_num; *//* index of current MCU within row */
+/* JDIMENSION MCU_count;*/ /* number of MCUs encoded */
+ int comp, ci;/*, yoffset;*/
+ JSAMPARRAY16 buffer[MAX_COMPONENTS];
+ jpeg_component_info *compptr;
+
+ /* Align the virtual buffers for the components used in this scan.
+ * NB: during first pass, this is safe only because the buffers will
+ * already be aligned properly, so jmemmgr.c won't need to do any I/O.
+ */
+ for (comp = 0; comp < cinfo->comps_in_scan; comp++) {
+ compptr = cinfo->cur_comp_info[comp];
+ ci = compptr->component_index;
+ buffer[ci] = (JSAMPARRAY16)(*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, diff->whole_image[ci],
+ diff->iMCU_row_num * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ }
+
+ return compress_data(cinfo, buffer);
+}
+
+#endif /* FULL_SAMP_BUFFER_SUPPORTED */
+
+
+/*
+ * Initialize difference buffer controller.
+ */
+
+GLOBAL(void)
+jinit_c_diff_controller (j_compress_ptr cinfo, boolean need_full_buffer)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ c_diff_ptr diff;
+ int ci, row;
+ jpeg_component_info *compptr;
+
+ diff = (c_diff_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(c_diff_controller));
+ losslsc->diff_private = (void *) diff;
+ losslsc->diff_start_pass = start_pass_diff;
+
+ /* Create the prediction row buffers. */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ diff->cur_row[ci] = (JSAMPROW16)*(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units
+ * SIZEOF(JSAMPLE16), (long) compptr->h_samp_factor),
+ (JDIMENSION) 1);
+ diff->prev_row[ci] = (JSAMPROW16)*(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units
+ * SIZEOF(JSAMPLE16), (long) compptr->h_samp_factor),
+ (JDIMENSION) 1);
+ }
+
+ /* Create the difference buffer. */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ diff->diff_buf[ci] = (*cinfo->mem->alloc_darray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JSAMPLE16),
+ (JDIMENSION) compptr->v_samp_factor);
+ /* Prefill difference rows with zeros. We do this because only actual
+ * data is placed in the buffers during prediction/differencing, leaving
+ * any dummy differences at the right edge as zeros, which will encode
+ * to the smallest amount of data.
+ */
+ for (row = 0; row < compptr->v_samp_factor; row++)
+ MEMZERO(diff->diff_buf[ci][row],
+ jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JDIFF));
+ }
+
+ /* Create the sample buffer. */
+ if (need_full_buffer) {
+#ifdef FULL_SAMP_BUFFER_SUPPORTED
+ /* Allocate a full-image virtual array for each component, */
+ /* padded to a multiple of samp_factor differences in each direction. */
+ int ci;
+ jpeg_component_info *compptr;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ diff->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JSAMPLE16),
+ (JDIMENSION) jround_up((long) compptr->height_in_data_units,
+ (long) compptr->v_samp_factor),
+ (JDIMENSION) compptr->v_samp_factor);
+ }
+#else
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+#endif
+ } else
+ diff->whole_image[0] = NULL; /* flag for no virtual arrays */
+}
+
+#endif /* C_LOSSLESS_SUPPORTED */
diff --git a/jpeg-6c/jchuff.c b/jpeg-6c/jchuff.c
new file mode 100644
index 0000000..7a2ec12
--- /dev/null
+++ b/jpeg-6c/jchuff.c
@@ -0,0 +1,273 @@
+/*
+ * jchuff.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains Huffman entropy decoding routines which are shared
+ * by the sequential, progressive and lossless decoders.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jchuff.h" /* Declarations shared with jc*huff.c */
+
+
+/*
+ * Compute the derived values for a Huffman table.
+ * This routine also performs some validation checks on the table.
+ */
+
+GLOBAL(void)
+jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
+ c_derived_tbl ** pdtbl)
+{
+ JHUFF_TBL *htbl;
+ c_derived_tbl *dtbl;
+ int p, i, l, lastp, si, maxsymbol;
+ char huffsize[257];
+ unsigned int huffcode[257];
+ unsigned int code;
+
+ /* Note that huffsize[] and huffcode[] are filled in code-length order,
+ * paralleling the order of the symbols themselves in htbl->huffval[].
+ */
+
+ /* Find the input Huffman table */
+ if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
+ htbl =
+ isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
+ if (htbl == NULL)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
+
+ /* Allocate a workspace if we haven't already done so. */
+ if (*pdtbl == NULL)
+ *pdtbl = (c_derived_tbl *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(c_derived_tbl));
+ dtbl = *pdtbl;
+
+ /* Figure C.1: make table of Huffman code length for each symbol */
+
+ p = 0;
+ for (l = 1; l <= 16; l++) {
+ i = (int) htbl->bits[l];
+ if (i < 0 || p + i > 256) /* protect against table overrun */
+ ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
+ while (i--)
+ huffsize[p++] = (char) l;
+ }
+ huffsize[p] = 0;
+ lastp = p;
+
+ /* Figure C.2: generate the codes themselves */
+ /* We also validate that the counts represent a legal Huffman code tree. */
+
+ code = 0;
+ si = huffsize[0];
+ p = 0;
+ while (huffsize[p]) {
+ while (((int) huffsize[p]) == si) {
+ huffcode[p++] = code;
+ code++;
+ }
+ /* code is now 1 more than the last code used for codelength si; but
+ * it must still fit in si bits, since no code is allowed to be all ones.
+ */
+ if (((INT32) code) >= (((INT32) 1) << si))
+ ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
+ code <<= 1;
+ si++;
+ }
+
+ /* Figure C.3: generate encoding tables */
+ /* These are code and size indexed by symbol value */
+
+ /* Set all codeless symbols to have code length 0;
+ * this lets us detect duplicate VAL entries here, and later
+ * allows emit_bits to detect any attempt to emit such symbols.
+ */
+ MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
+
+ /* This is also a convenient place to check for out-of-range
+ * and duplicated VAL entries. We allow 0..255 for AC symbols
+ * but only 0..16 for DC. (We could constrain them further
+ * based on data depth and mode, but this seems enough.)
+ */
+ maxsymbol = isDC ? 16 : 255;
+
+ for (p = 0; p < lastp; p++) {
+ i = htbl->huffval[p];
+ if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
+ ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
+ dtbl->ehufco[i] = huffcode[p];
+ dtbl->ehufsi[i] = huffsize[p];
+ }
+}
+
+
+/*
+ * Generate the best Huffman code table for the given counts, fill htbl.
+ *
+ * The JPEG standard requires that no symbol be assigned a codeword of all
+ * one bits (so that padding bits added at the end of a compressed segment
+ * can't look like a valid code). Because of the canonical ordering of
+ * codewords, this just means that there must be an unused slot in the
+ * longest codeword length category. Section K.2 of the JPEG spec suggests
+ * reserving such a slot by pretending that symbol 256 is a valid symbol
+ * with count 1. In theory that's not optimal; giving it count zero but
+ * including it in the symbol set anyway should give a better Huffman code.
+ * But the theoretically better code actually seems to come out worse in
+ * practice, because it produces more all-ones bytes (which incur stuffed
+ * zero bytes in the final file). In any case the difference is tiny.
+ *
+ * The JPEG standard requires Huffman codes to be no more than 16 bits long.
+ * If some symbols have a very small but nonzero probability, the Huffman tree
+ * must be adjusted to meet the code length restriction. We currently use
+ * the adjustment method suggested in JPEG section K.2. This method is *not*
+ * optimal; it may not choose the best possible limited-length code. But
+ * typically only very-low-frequency symbols will be given less-than-optimal
+ * lengths, so the code is almost optimal. Experimental comparisons against
+ * an optimal limited-length-code algorithm indicate that the difference is
+ * microscopic --- usually less than a hundredth of a percent of total size.
+ * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
+ */
+
+GLOBAL(void)
+jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
+{
+#define MAX_CLEN 32 /* assumed maximum initial code length */
+ UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
+ int codesize[257]; /* codesize[k] = code length of symbol k */
+ int others[257]; /* next symbol in current branch of tree */
+ int c1, c2;
+ int p, i, j;
+ long v;
+
+ /* This algorithm is explained in section K.2 of the JPEG standard */
+
+ MEMZERO(bits, SIZEOF(bits));
+ MEMZERO(codesize, SIZEOF(codesize));
+ for (i = 0; i < 257; i++)
+ others[i] = -1; /* init links to empty */
+
+ freq[256] = 1; /* make sure 256 has a nonzero count */
+ /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
+ * that no real symbol is given code-value of all ones, because 256
+ * will be placed last in the largest codeword category.
+ */
+
+ /* Huffman's basic algorithm to assign optimal code lengths to symbols */
+
+ for (;;) {
+ /* Find the smallest nonzero frequency, set c1 = its symbol */
+ /* In case of ties, take the larger symbol number */
+ c1 = -1;
+ v = 1000000000L;
+ for (i = 0; i <= 256; i++) {
+ if (freq[i] && freq[i] <= v) {
+ v = freq[i];
+ c1 = i;
+ }
+ }
+
+ /* Find the next smallest nonzero frequency, set c2 = its symbol */
+ /* In case of ties, take the larger symbol number */
+ c2 = -1;
+ v = 1000000000L;
+ for (i = 0; i <= 256; i++) {
+ if (freq[i] && freq[i] <= v && i != c1) {
+ v = freq[i];
+ c2 = i;
+ }
+ }
+
+ /* Done if we've merged everything into one frequency */
+ if (c2 < 0)
+ break;
+
+ /* Else merge the two counts/trees */
+ freq[c1] += freq[c2];
+ freq[c2] = 0;
+
+ /* Increment the codesize of everything in c1's tree branch */
+ codesize[c1]++;
+ while (others[c1] >= 0) {
+ c1 = others[c1];
+ codesize[c1]++;
+ }
+
+ others[c1] = c2; /* chain c2 onto c1's tree branch */
+
+ /* Increment the codesize of everything in c2's tree branch */
+ codesize[c2]++;
+ while (others[c2] >= 0) {
+ c2 = others[c2];
+ codesize[c2]++;
+ }
+ }
+
+ /* Now count the number of symbols of each code length */
+ for (i = 0; i <= 256; i++) {
+ if (codesize[i]) {
+ /* The JPEG standard seems to think that this can't happen, */
+ /* but I'm paranoid... */
+ if (codesize[i] > MAX_CLEN)
+ ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
+
+ bits[codesize[i]]++;
+ }
+ }
+
+ /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
+ * Huffman procedure assigned any such lengths, we must adjust the coding.
+ * Here is what the JPEG spec says about how this next bit works:
+ * Since symbols are paired for the longest Huffman code, the symbols are
+ * removed from this length category two at a time. The prefix for the pair
+ * (which is one bit shorter) is allocated to one of the pair; then,
+ * skipping the BITS entry for that prefix length, a code word from the next
+ * shortest nonzero BITS entry is converted into a prefix for two code words
+ * one bit longer.
+ */
+
+ for (i = MAX_CLEN; i > 16; i--) {
+ while (bits[i] > 0) {
+ j = i - 2; /* find length of new prefix to be used */
+ while (bits[j] == 0)
+ j--;
+
+ bits[i] -= 2; /* remove two symbols */
+ bits[i-1]++; /* one goes in this length */
+ bits[j+1] += 2; /* two new symbols in this length */
+ bits[j]--; /* symbol of this length is now a prefix */
+ }
+ }
+
+ /* Remove the count for the pseudo-symbol 256 from the largest codelength */
+ while (bits[i] == 0) /* find largest codelength still in use */
+ i--;
+ bits[i]--;
+
+ /* Return final symbol counts (only for lengths 0..16) */
+ MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
+
+ /* Return a list of the symbols sorted by code length */
+ /* It's not real clear to me why we don't need to consider the codelength
+ * changes made above, but the JPEG spec seems to think this works.
+ */
+ p = 0;
+ for (i = 1; i <= MAX_CLEN; i++) {
+ for (j = 0; j <= 255; j++) {
+ if (codesize[j] == i) {
+ htbl->huffval[p] = (UINT8) j;
+ p++;
+ }
+ }
+ }
+
+ /* Set sent_table FALSE so updated table will be written to JPEG file. */
+ htbl->sent_table = FALSE;
+}
diff --git a/jpeg-6c/jchuff.h b/jpeg-6c/jchuff.h
new file mode 100644
index 0000000..ca482bb
--- /dev/null
+++ b/jpeg-6c/jchuff.h
@@ -0,0 +1,56 @@
+/*
+ * jchuff.h
+ *
+ * Copyright (C) 1991-1997, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains declarations for Huffman entropy encoding routines
+ * that are shared between the sequential encoder (jchuff.c) and the
+ * progressive encoder (jcphuff.c). No other modules need to see these.
+ */
+
+/* The legal range of a DCT coefficient is
+ * -1024 .. +1023 for 8-bit data;
+ * -16384 .. +16383 for 12-bit data.
+ * -262143 .. +262143 for 16-bit data.
+ * Hence the magnitude should always fit in 10, 14 or 18 bits respectively.
+ */
+
+/*#if BITS_IN_JSAMPLE == 8
+#define MAX_COEF_BITS 10
+#else
+#define MAX_COEF_BITS 14
+#endif*/
+
+/* The legal range of a spatial difference is
+ * -32767 .. +32768.
+ * Hence the magnitude should always fit in 16 bits.
+ */
+
+#define MAX_DIFF_BITS 16
+
+/* Derived data constructed for each Huffman table */
+
+typedef struct {
+ unsigned int ehufco[256]; /* code for each symbol */
+ char ehufsi[256]; /* length of code for each symbol */
+ /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
+} c_derived_tbl;
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_make_c_derived_tbl jMkCDerived
+#define jpeg_gen_optimal_table jGenOptTbl
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+/* Expand a Huffman table definition into the derived format */
+EXTERN(void) jpeg_make_c_derived_tbl
+ JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
+ c_derived_tbl ** pdtbl));
+
+/* Generate an optimal table definition given the specified counts */
+EXTERN(void) jpeg_gen_optimal_table
+ JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
diff --git a/jpeg-6c/jcinit.c b/jpeg-6c/jcinit.c
new file mode 100644
index 0000000..b485a8e
--- /dev/null
+++ b/jpeg-6c/jcinit.c
@@ -0,0 +1,57 @@
+/*
+ * jcinit.c
+ *
+ * Copyright (C) 1991-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains initialization logic for the JPEG compressor.
+ * This routine is in charge of selecting the modules to be executed and
+ * making an initialization call to each one.
+ *
+ * Logically, this code belongs in jcmaster.c. It's split out because
+ * linking this routine implies linking the entire compression library.
+ * For a transcoding-only application, we want to be able to use jcmaster.c
+ * without linking in the whole library.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Master selection of compression modules.
+ * This is done once at the start of processing an image. We determine
+ * which modules will be used and give them appropriate initialization calls.
+ */
+
+GLOBAL(void)
+jinit_compress_master (j_compress_ptr cinfo)
+{
+ /* Initialize master control (includes parameter checking/processing) */
+ jinit_c_master_control(cinfo, FALSE /* full compression */);
+
+ /* Initialize compression codec */
+ jinit_c_codec(cinfo);
+
+ /* Preprocessing */
+ if (! cinfo->raw_data_in) {
+ jinit_color_converter(cinfo);
+ jinit_downsampler(cinfo);
+ jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
+ }
+
+ jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
+
+ jinit_marker_writer(cinfo);
+
+ /* We can now tell the memory manager to allocate virtual arrays. */
+ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
+
+ /* Write the datastream header (SOI) immediately.
+ * Frame and scan headers are postponed till later.
+ * This lets application insert special markers after the SOI.
+ */
+ (*cinfo->marker->write_file_header) (cinfo);
+}
diff --git a/jpeg-6c/jclhuff.c b/jpeg-6c/jclhuff.c
new file mode 100644
index 0000000..b4d588e
--- /dev/null
+++ b/jpeg-6c/jclhuff.c
@@ -0,0 +1,600 @@
+/*
+ * jclhuff.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains Huffman entropy encoding routines for lossless JPEG.
+ *
+ * Much of the complexity here has to do with supporting output suspension.
+ * If the data destination module demands suspension, we want to be able to
+ * back up to the start of the current MCU. To do this, we copy state
+ * variables into local working storage, and update them back to the
+ * permanent JPEG objects only upon successful completion of an MCU.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossls.h" /* Private declarations for lossless codec */
+#include "jchuff.h" /* Declarations shared with jc*huff.c */
+
+
+/* Expanded entropy encoder object for Huffman encoding.
+ *
+ * The savable_state subrecord contains fields that change within an MCU,
+ * but must not be updated permanently until we complete the MCU.
+ */
+
+typedef struct {
+ INT32 put_buffer; /* current bit-accumulation buffer */
+ int put_bits; /* # of bits now in it */
+} savable_state;
+
+/* This macro is to work around compilers with missing or broken
+ * structure assignment. You'll need to fix this code if you have
+ * such a compiler and you change MAX_COMPS_IN_SCAN.
+ */
+
+#ifndef NO_STRUCT_ASSIGN
+#define ASSIGN_STATE(dest,src) ((dest) = (src))
+#else
+#define ASSIGN_STATE(dest,src) \
+ ((dest).put_buffer = (src).put_buffer, \
+ (dest).put_bits = (src).put_bits)
+#endif
+
+
+typedef struct {
+ int ci, yoffset, MCU_width;
+} lhe_input_ptr_info;
+
+
+typedef struct {
+ savable_state saved; /* Bit buffer at start of MCU */
+
+ /* These fields are NOT loaded into local working state. */
+ unsigned int restarts_to_go; /* MCUs left in this restart interval */
+ int next_restart_num; /* next restart number to write (0-7) */
+
+ /* Pointers to derived tables (these workspaces have image lifespan) */
+ c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
+
+ /* Pointers to derived tables to be used for each data unit within an MCU */
+ c_derived_tbl * cur_tbls[C_MAX_DATA_UNITS_IN_MCU];
+
+#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
+ long * count_ptrs[NUM_HUFF_TBLS];
+
+ /* Pointers to stats tables to be used for each data unit within an MCU */
+ long * cur_counts[C_MAX_DATA_UNITS_IN_MCU];
+#endif
+
+ /* Pointers to the proper input difference row for each group of data units
+ * within an MCU. For each component, there are Vi groups of Hi data units.
+ */
+ JDIFFROW input_ptr[C_MAX_DATA_UNITS_IN_MCU];
+
+ /* Number of input pointers in use for the current MCU. This is the sum
+ * of all Vi in the MCU.
+ */
+ int num_input_ptrs;
+
+ /* Information used for positioning the input pointers within the input
+ * difference rows.
+ */
+ lhe_input_ptr_info input_ptr_info[C_MAX_DATA_UNITS_IN_MCU];
+
+ /* Index of the proper input pointer for each data unit within an MCU */
+ int input_ptr_index[C_MAX_DATA_UNITS_IN_MCU];
+
+} lhuff_entropy_encoder;
+
+typedef lhuff_entropy_encoder * lhuff_entropy_ptr;
+
+/* Working state while writing an MCU.
+ * This struct contains all the fields that are needed by subroutines.
+ */
+
+typedef struct {
+ JOCTET * next_output_byte; /* => next byte to write in buffer */
+ size_t free_in_buffer; /* # of byte spaces remaining in buffer */
+ savable_state cur; /* Current bit buffer & DC state */
+ j_compress_ptr cinfo; /* dump_buffer needs access to this */
+} working_state;
+
+
+/* Forward declarations */
+METHODDEF(JDIMENSION) encode_mcus_huff (j_compress_ptr cinfo,
+ JDIFFIMAGE diff_buf,
+ JDIMENSION MCU_row_num,
+ JDIMENSION MCU_col_num,
+ JDIMENSION nMCU);
+METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
+#ifdef ENTROPY_OPT_SUPPORTED
+METHODDEF(JDIMENSION) encode_mcus_gather (j_compress_ptr cinfo,
+ JDIFFIMAGE diff_buf,
+ JDIMENSION MCU_row_num,
+ JDIMENSION MCU_col_num,
+ JDIMENSION nMCU);
+METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
+#endif
+
+
+/*
+ * Initialize for a Huffman-compressed scan.
+ * If gather_statistics is TRUE, we do not output anything during the scan,
+ * just count the Huffman symbols used and generate Huffman code tables.
+ */
+
+METHODDEF(void)
+start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private;
+ int ci, dctbl, sampn, ptrn, yoffset, xoffset;
+ jpeg_component_info * compptr;
+
+ if (gather_statistics) {
+#ifdef ENTROPY_OPT_SUPPORTED
+ losslsc->entropy_encode_mcus = encode_mcus_gather;
+ losslsc->pub.entropy_finish_pass = finish_pass_gather;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ losslsc->entropy_encode_mcus = encode_mcus_huff;
+ losslsc->pub.entropy_finish_pass = finish_pass_huff;
+ }
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ dctbl = compptr->dc_tbl_no;
+ if (gather_statistics) {
+#ifdef ENTROPY_OPT_SUPPORTED
+ /* Check for invalid table indexes */
+ /* (make_c_derived_tbl does this in the other path) */
+ if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
+ /* Allocate and zero the statistics tables */
+ /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
+ if (entropy->count_ptrs[dctbl] == NULL)
+ entropy->count_ptrs[dctbl] = (long *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ 257 * SIZEOF(long));
+ MEMZERO(entropy->count_ptrs[dctbl], 257 * SIZEOF(long));
+#endif
+ } else {
+ /* Compute derived values for Huffman tables */
+ /* We may do this more than once for a table, but it's not expensive */
+ jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
+ & entropy->derived_tbls[dctbl]);
+ }
+ }
+
+ /* Precalculate encoding info for each sample in an MCU of this scan */
+ for (sampn = 0, ptrn = 0; sampn < cinfo->data_units_in_MCU;) {
+ compptr = cinfo->cur_comp_info[cinfo->MCU_membership[sampn]];
+ ci = compptr->component_index;
+ /* ci = cinfo->MCU_membership[sampn];
+ compptr = cinfo->cur_comp_info[ci];*/
+ for (yoffset = 0; yoffset < compptr->MCU_height; yoffset++, ptrn++) {
+ /* Precalculate the setup info for each input pointer */
+ entropy->input_ptr_info[ptrn].ci = ci;
+ entropy->input_ptr_info[ptrn].yoffset = yoffset;
+ entropy->input_ptr_info[ptrn].MCU_width = compptr->MCU_width;
+ for (xoffset = 0; xoffset < compptr->MCU_width; xoffset++, sampn++) {
+ /* Precalculate the input pointer index for each sample */
+ entropy->input_ptr_index[sampn] = ptrn;
+ /* Precalculate which tables to use for each sample */
+ entropy->cur_tbls[sampn] = entropy->derived_tbls[compptr->dc_tbl_no];
+ entropy->cur_counts[sampn] = entropy->count_ptrs[compptr->dc_tbl_no];
+ }
+ }
+ }
+ entropy->num_input_ptrs = ptrn;
+
+ /* Initialize bit buffer to empty */
+ entropy->saved.put_buffer = 0;
+ entropy->saved.put_bits = 0;
+
+ /* Initialize restart stuff */
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num = 0;
+}
+
+
+/* Outputting bytes to the file */
+
+/* Emit a byte, taking 'action' if must suspend. */
+#define emit_byte(state,val,action) \
+ { *(state)->next_output_byte++ = (JOCTET) (val); \
+ if (--(state)->free_in_buffer == 0) \
+ if (! dump_buffer(state)) \
+ { action; } }
+
+
+LOCAL(boolean)
+dump_buffer (working_state * state)
+/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
+{
+ struct jpeg_destination_mgr * dest = state->cinfo->dest;
+
+ if (! (*dest->empty_output_buffer) (state->cinfo))
+ return FALSE;
+ /* After a successful buffer dump, must reset buffer pointers */
+ state->next_output_byte = dest->next_output_byte;
+ state->free_in_buffer = dest->free_in_buffer;
+ return TRUE;
+}
+
+
+/* Outputting bits to the file */
+
+/* Only the right 24 bits of put_buffer are used; the valid bits are
+ * left-justified in this part. At most 16 bits can be passed to emit_bits
+ * in one call, and we never retain more than 7 bits in put_buffer
+ * between calls, so 24 bits are sufficient.
+ */
+
+INLINE
+LOCAL(boolean)
+emit_bits (working_state * state, unsigned int code, int size)
+/* Emit some bits; return TRUE if successful, FALSE if must suspend */
+{
+ /* This routine is heavily used, so it's worth coding tightly. */
+ register INT32 put_buffer = (INT32) code;
+ register int put_bits = state->cur.put_bits;
+
+ /* if size is 0, caller used an invalid Huffman table entry */
+ if (size == 0)
+ ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
+
+ put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
+
+ put_bits += size; /* new number of bits in buffer */
+
+ put_buffer <<= 24 - put_bits; /* align incoming bits */
+
+ put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
+
+ while (put_bits >= 8) {
+ int c = (int) ((put_buffer >> 16) & 0xFF);
+
+ emit_byte(state, c, return FALSE);
+ if (c == 0xFF) { /* need to stuff a zero byte? */
+ emit_byte(state, 0, return FALSE);
+ }
+ put_buffer <<= 8;
+ put_bits -= 8;
+ }
+
+ state->cur.put_buffer = put_buffer; /* update state variables */
+ state->cur.put_bits = put_bits;
+
+ return TRUE;
+}
+
+
+LOCAL(boolean)
+flush_bits (working_state * state)
+{
+ if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
+ return FALSE;
+ state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
+ state->cur.put_bits = 0;
+ return TRUE;
+}
+
+
+/*
+ * Emit a restart marker & resynchronize predictions.
+ */
+
+LOCAL(boolean)
+emit_restart (working_state * state, int restart_num)
+{
+/* int ci;*/
+
+ if (! flush_bits(state))
+ return FALSE;
+
+ emit_byte(state, 0xFF, return FALSE);
+ emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
+
+ /* The restart counter is not updated until we successfully write the MCU. */
+
+ return TRUE;
+}
+
+
+/*
+ * Encode and output one nMCU's worth of Huffman-compressed differences.
+ */
+
+METHODDEF(JDIMENSION)
+encode_mcus_huff (j_compress_ptr cinfo, JDIFFIMAGE diff_buf,
+ JDIMENSION MCU_row_num, JDIMENSION MCU_col_num,
+ JDIMENSION nMCU)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private;
+ working_state state;
+ int mcu_num, sampn, ci, yoffset, MCU_width, ptrn;
+/* jpeg_component_info * compptr;*/
+
+ /* Load up working state */
+ state.next_output_byte = cinfo->dest->next_output_byte;
+ state.free_in_buffer = cinfo->dest->free_in_buffer;
+ ASSIGN_STATE(state.cur, entropy->saved);
+ state.cinfo = cinfo;
+
+ /* Emit restart marker if needed */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! emit_restart(&state, entropy->next_restart_num))
+ return 0;
+ }
+
+ /* Set input pointer locations based on MCU_col_num */
+ for (ptrn = 0; ptrn < entropy->num_input_ptrs; ptrn++) {
+ ci = entropy->input_ptr_info[ptrn].ci;
+ yoffset = entropy->input_ptr_info[ptrn].yoffset;
+ MCU_width = entropy->input_ptr_info[ptrn].MCU_width;
+ entropy->input_ptr[ptrn] =
+ diff_buf[ci][MCU_row_num + yoffset] + (MCU_col_num * MCU_width);
+ }
+
+ for (mcu_num = 0; mcu_num < nMCU; mcu_num++) {
+
+ /* Inner loop handles the samples in the MCU */
+ for (sampn = 0; sampn < cinfo->data_units_in_MCU; sampn++) {
+ register int temp, temp2;/*, temp3;*/
+ register int nbits;
+ c_derived_tbl *dctbl = entropy->cur_tbls[sampn];
+
+ /* Encode the difference per section H.1.2.2 */
+
+ /* Input the sample difference */
+ temp = *entropy->input_ptr[entropy->input_ptr_index[sampn]]++;
+
+ if (temp & 0x8000) { /* instead of temp < 0 */
+ temp = (-temp) & 0x7FFF; /* absolute value, mod 2^16 */
+ if (temp == 0) /* special case: magnitude = 32768 */
+ temp2 = temp = 0x8000;
+ temp2 = ~ temp; /* one's complement of magnitude */
+ } else {
+ temp &= 0x7FFF; /* abs value mod 2^16 */
+ temp2 = temp; /* magnitude */
+ }
+
+ /* Find the number of bits needed for the magnitude of the difference */
+ nbits = 0;
+ while (temp) {
+ nbits++;
+ temp >>= 1;
+ }
+ /* Check for out-of-range difference values.
+ */
+ if (nbits > MAX_DIFF_BITS)
+ ERREXIT(cinfo, JERR_BAD_DIFF);
+
+ /* Emit the Huffman-coded symbol for the number of bits */
+ if (! emit_bits(&state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
+ return mcu_num;
+
+ /* Emit that number of bits of the value, if positive, */
+ /* or the complement of its magnitude, if negative. */
+ if (nbits && /* emit_bits rejects calls with size 0 */
+ nbits != 16) /* special case: no bits should be emitted */
+ if (! emit_bits(&state, (unsigned int) temp2, nbits))
+ return mcu_num;
+ }
+
+ /* Completed MCU, so update state */
+ cinfo->dest->next_output_byte = state.next_output_byte;
+ cinfo->dest->free_in_buffer = state.free_in_buffer;
+ ASSIGN_STATE(entropy->saved, state.cur);
+
+ /* Update restart-interval state too */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num++;
+ entropy->next_restart_num &= 7;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ }
+
+ return nMCU;
+}
+
+
+/*
+ * Finish up at the end of a Huffman-compressed scan.
+ */
+
+METHODDEF(void)
+finish_pass_huff (j_compress_ptr cinfo)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private;
+ working_state state;
+
+ /* Load up working state ... flush_bits needs it */
+ state.next_output_byte = cinfo->dest->next_output_byte;
+ state.free_in_buffer = cinfo->dest->free_in_buffer;
+ ASSIGN_STATE(state.cur, entropy->saved);
+ state.cinfo = cinfo;
+
+ /* Flush out the last data */
+ if (! flush_bits(&state))
+ ERREXIT(cinfo, JERR_CANT_SUSPEND);
+
+ /* Update state */
+ cinfo->dest->next_output_byte = state.next_output_byte;
+ cinfo->dest->free_in_buffer = state.free_in_buffer;
+ ASSIGN_STATE(entropy->saved, state.cur);
+}
+
+
+/*
+ * Huffman coding optimization.
+ *
+ * We first scan the supplied data and count the number of uses of each symbol
+ * that is to be Huffman-coded. (This process MUST agree with the code above.)
+ * Then we build a Huffman coding tree for the observed counts.
+ * Symbols which are not needed at all for the particular image are not
+ * assigned any code, which saves space in the DHT marker as well as in
+ * the compressed data.
+ */
+
+#ifdef ENTROPY_OPT_SUPPORTED
+
+/*
+ * Trial-encode one nMCU's worth of Huffman-compressed differences.
+ * No data is actually output, so no suspension return is possible.
+ */
+
+METHODDEF(JDIMENSION)
+encode_mcus_gather (j_compress_ptr cinfo, JDIFFIMAGE diff_buf,
+ JDIMENSION MCU_row_num, JDIMENSION MCU_col_num,
+ JDIMENSION nMCU)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private;
+ int mcu_num, sampn, ci, yoffset, MCU_width, ptrn;
+/* jpeg_component_info * compptr;*/
+
+ /* Take care of restart intervals if needed */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ /* Update restart state */
+ entropy->restarts_to_go = cinfo->restart_interval;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ /* Set input pointer locations based on MCU_col_num */
+ for (ptrn = 0; ptrn < entropy->num_input_ptrs; ptrn++) {
+ ci = entropy->input_ptr_info[ptrn].ci;
+ yoffset = entropy->input_ptr_info[ptrn].yoffset;
+ MCU_width = entropy->input_ptr_info[ptrn].MCU_width;
+ entropy->input_ptr[ptrn] =
+ diff_buf[ci][MCU_row_num + yoffset] + (MCU_col_num * MCU_width);
+ }
+
+ for (mcu_num = 0; mcu_num < nMCU; mcu_num++) {
+
+ /* Inner loop handles the samples in the MCU */
+ for (sampn = 0; sampn < cinfo->data_units_in_MCU; sampn++) {
+ register int temp;
+ register int nbits;
+/* c_derived_tbl *dctbl = entropy->cur_tbls[sampn];*/
+ long * counts = entropy->cur_counts[sampn];
+
+ /* Encode the difference per section H.1.2.2 */
+
+ /* Input the sample difference */
+ temp = *entropy->input_ptr[entropy->input_ptr_index[sampn]]++;
+
+ if (temp & 0x8000) { /* instead of temp < 0 */
+ temp = (-temp) & 0x7FFF; /* absolute value, mod 2^16 */
+ if (temp == 0) /* special case: magnitude = 32768 */
+ temp = 0x8000;
+ } else
+ temp &= 0x7FFF; /* abs value mod 2^16 */
+
+ /* Find the number of bits needed for the magnitude of the difference */
+ nbits = 0;
+ while (temp) {
+ nbits++;
+ temp >>= 1;
+ }
+ /* Check for out-of-range difference values.
+ */
+ if (nbits > MAX_DIFF_BITS)
+ ERREXIT(cinfo, JERR_BAD_DIFF);
+
+ /* Count the Huffman symbol for the number of bits */
+ counts[nbits]++;
+ }
+ }
+
+ return nMCU;
+}
+
+
+/*
+ * Finish up a statistics-gathering pass and create the new Huffman tables.
+ */
+
+METHODDEF(void)
+finish_pass_gather (j_compress_ptr cinfo)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private;
+ int ci, dctbl;
+ jpeg_component_info * compptr;
+ JHUFF_TBL **htblptr;
+ boolean did_dc[NUM_HUFF_TBLS];
+
+ /* It's important not to apply jpeg_gen_optimal_table more than once
+ * per table, because it clobbers the input frequency counts!
+ */
+ MEMZERO(did_dc, SIZEOF(did_dc));
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ dctbl = compptr->dc_tbl_no;
+ if (! did_dc[dctbl]) {
+ htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
+ if (*htblptr == NULL)
+ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+ jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[dctbl]);
+ did_dc[dctbl] = TRUE;
+ }
+ }
+}
+
+
+#endif /* ENTROPY_OPT_SUPPORTED */
+
+
+METHODDEF(boolean)
+need_optimization_pass (j_compress_ptr cinfo)
+{
+ return TRUE;
+}
+
+
+/*
+ * Module initialization routine for Huffman entropy encoding.
+ */
+
+GLOBAL(void)
+jinit_lhuff_encoder (j_compress_ptr cinfo)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ lhuff_entropy_ptr entropy;
+ int i;
+
+ entropy = (lhuff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(lhuff_entropy_encoder));
+ losslsc->entropy_private = (struct jpeg_entropy_encoder *) entropy;
+ losslsc->pub.entropy_start_pass = start_pass_huff;
+ losslsc->pub.need_optimization_pass = need_optimization_pass;
+
+ /* Mark tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ entropy->derived_tbls[i] = NULL;
+#ifdef ENTROPY_OPT_SUPPORTED
+ entropy->count_ptrs[i] = NULL;
+#endif
+ }
+}
diff --git a/jpeg-6c/jclossls.c b/jpeg-6c/jclossls.c
new file mode 100644
index 0000000..7e8701c
--- /dev/null
+++ b/jpeg-6c/jclossls.c
@@ -0,0 +1,78 @@
+/*
+ * jclossls.c
+ *
+ * Copyright (C) 1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the control logic for the lossless JPEG compressor.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossls.h"
+
+
+#ifdef C_LOSSLESS_SUPPORTED
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF(void)
+start_pass (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+
+ (*losslsc->scaler_start_pass) (cinfo);
+ (*losslsc->predict_start_pass) (cinfo);
+ (*losslsc->diff_start_pass) (cinfo, pass_mode);
+}
+
+
+/*
+ * Initialize the lossless compression codec.
+ * This is called only once, during master selection.
+ */
+
+GLOBAL(void)
+jinit_lossless_c_codec(j_compress_ptr cinfo)
+{
+ j_lossless_c_ptr losslsc;
+
+ /* Create subobject in permanent pool */
+ losslsc = (j_lossless_c_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(jpeg_lossless_c_codec));
+ cinfo->codec = (struct jpeg_c_codec *) losslsc;
+
+ /* Initialize sub-modules */
+
+ /* Scaler */
+ jinit_c_scaler(cinfo);
+
+ /* Differencer */
+ jinit_differencer(cinfo);
+
+ /* Entropy encoding: either Huffman or arithmetic coding. */
+ if (cinfo->arith_code) {
+ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+ } else {
+ jinit_lhuff_encoder(cinfo);
+ }
+
+ /* Need a full-image difference buffer in any multi-pass mode. */
+ jinit_c_diff_controller(cinfo,
+ (boolean) (cinfo->num_scans > 1 ||
+ cinfo->optimize_coding));
+
+ /* Initialize method pointers.
+ *
+ * Note: entropy_start_pass and entropy_finish_pass are assigned in
+ * jclhuff.c and compress_data is assigned in jcdiffct.c.
+ */
+ losslsc->pub.start_pass = start_pass;
+}
+
+#endif /* C_LOSSLESS_SUPPORTED */
diff --git a/jpeg-6c/jclossy.c b/jpeg-6c/jclossy.c
new file mode 100644
index 0000000..173494d
--- /dev/null
+++ b/jpeg-6c/jclossy.c
@@ -0,0 +1,76 @@
+/*
+ * jclossy.c
+ *
+ * Copyright (C) 1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the control logic for the lossy JPEG compressor.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h"
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF(void)
+start_pass (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+
+ (*lossyc->fdct_start_pass) (cinfo);
+ (*lossyc->coef_start_pass) (cinfo, pass_mode);
+}
+
+
+/*
+ * Initialize the lossy compression codec.
+ * This is called only once, during master selection.
+ */
+
+GLOBAL(void)
+jinit_lossy_c_codec (j_compress_ptr cinfo)
+{
+ j_lossy_c_ptr lossyc;
+
+ /* Create subobject in permanent pool */
+ lossyc = (j_lossy_c_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(jpeg_lossy_c_codec));
+ cinfo->codec = (struct jpeg_c_codec *) lossyc;
+
+ /* Initialize sub-modules */
+
+ /* Forward DCT */
+ jinit_forward_dct(cinfo);
+ /* Entropy encoding: either Huffman or arithmetic coding. */
+ if (cinfo->arith_code) {
+ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+ } else {
+ if (cinfo->process == JPROC_PROGRESSIVE) {
+#ifdef C_PROGRESSIVE_SUPPORTED
+ jinit_phuff_encoder(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else
+ jinit_shuff_encoder(cinfo);
+ }
+
+ /* Need a full-image coefficient buffer in any multi-pass mode. */
+ jinit_c_coef_controller(cinfo,
+ (boolean) (cinfo->num_scans > 1 ||
+ cinfo->optimize_coding));
+
+ /* Initialize method pointers.
+ *
+ * Note: entropy_start_pass and entropy_finish_pass are assigned in
+ * jcshuff.c or jcphuff.c and compress_data is assigned in jccoefct.c.
+ */
+ lossyc->pub.start_pass = start_pass;
+}
diff --git a/jpeg-6c/jcmainct.c b/jpeg-6c/jcmainct.c
new file mode 100644
index 0000000..077f308
--- /dev/null
+++ b/jpeg-6c/jcmainct.c
@@ -0,0 +1,297 @@
+/*
+ * jcmainct.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the main buffer controller for compression.
+ * The main buffer lies between the pre-processor and the JPEG
+ * compressor proper; it holds downsampled data in the JPEG colorspace.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Note: currently, there is no operating mode in which a full-image buffer
+ * is needed at this step. If there were, that mode could not be used with
+ * "raw data" input, since this module is bypassed in that case. However,
+ * we've left the code here for possible use in special applications.
+ */
+#undef FULL_MAIN_BUFFER_SUPPORTED
+
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_c_main_controller pub; /* public fields */
+
+ JDIMENSION cur_iMCU_row; /* number of current iMCU row */
+ JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
+ boolean suspended; /* remember if we suspended output */
+ J_BUF_MODE pass_mode; /* current operating mode */
+
+ /* If using just a strip buffer, this points to the entire set of buffers
+ * (we allocate one for each component). In the full-image case, this
+ * points to the currently accessible strips of the virtual arrays.
+ */
+ JSAMPARRAY16 buffer[MAX_COMPONENTS];
+
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+ /* If using full-image storage, this array holds pointers to virtual-array
+ * control blocks for each component. Unused if not full-image storage.
+ */
+ jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
+#endif
+} my_main_controller;
+
+typedef my_main_controller * my_main_ptr;
+
+
+/* Forward declarations */
+METHODDEF(void) process_data_simple_main
+ JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
+ JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+METHODDEF(void) process_data_buffer_main
+ JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
+ JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
+#endif
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF(void)
+start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ my_main_ptr mainp = (my_main_ptr) cinfo->mainp;
+
+ /* Do nothing in raw-data mode. */
+ if (cinfo->raw_data_in)
+ return;
+
+ mainp->cur_iMCU_row = 0; /* initialize counters */
+ mainp->rowgroup_ctr = 0;
+ mainp->suspended = FALSE;
+ mainp->pass_mode = pass_mode; /* save mode for use by process_data */
+
+ switch (pass_mode) {
+ case JBUF_PASS_THRU:
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+ if (mainp->whole_image[0] != NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+#endif
+ mainp->pub.process_data = process_data_simple_main;
+ break;
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+ case JBUF_SAVE_SOURCE:
+ case JBUF_CRANK_DEST:
+ case JBUF_SAVE_AND_PASS:
+ if (mainp->whole_image[0] == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ mainp->pub.process_data = process_data_buffer_main;
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ break;
+ }
+}
+
+
+/*
+ * Process some data.
+ * This routine handles the simple pass-through mode,
+ * where we have only a strip buffer.
+ */
+
+METHODDEF(void)
+process_data_simple_main (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail)
+{
+ my_main_ptr mainp = (my_main_ptr) cinfo->mainp;
+ int data_unit = cinfo->data_unit;
+
+ while (mainp->cur_iMCU_row < cinfo->total_iMCU_rows) {
+ /* Read input data if we haven't filled the main buffer yet */
+ if (mainp->rowgroup_ctr < data_unit)
+ (*cinfo->prep->pre_process_data) (cinfo,
+ input_buf, in_row_ctr, in_rows_avail,
+ mainp->buffer, &mainp->rowgroup_ctr,
+ (JDIMENSION) data_unit);
+
+ /* If we don't have a full iMCU row buffered, return to application for
+ * more data. Note that preprocessor will always pad to fill the iMCU row
+ * at the bottom of the image.
+ */
+ if (mainp->rowgroup_ctr != data_unit)
+ return;
+
+ /* Send the completed row to the compressor */
+ if (! (*cinfo->codec->compress_data) (cinfo, mainp->buffer)) {
+ /* If compressor did not consume the whole row, then we must need to
+ * suspend processing and return to the application. In this situation
+ * we pretend we didn't yet consume the last input row; otherwise, if
+ * it happened to be the last row of the image, the application would
+ * think we were done.
+ */
+ if (! mainp->suspended) {
+ (*in_row_ctr)--;
+ mainp->suspended = TRUE;
+ }
+ return;
+ }
+ /* We did finish the row. Undo our little suspension hack if a previous
+ * call suspended; then mark the main buffer empty.
+ */
+ if (mainp->suspended) {
+ (*in_row_ctr)++;
+ mainp->suspended = FALSE;
+ }
+ mainp->rowgroup_ctr = 0;
+ mainp->cur_iMCU_row++;
+ }
+}
+
+
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+
+/*
+ * Process some data.
+ * This routine handles all of the modes that use a full-size buffer.
+ */
+
+METHODDEF(void)
+process_data_buffer_main (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail)
+{
+ my_main_ptr mainp = (my_main_ptr) cinfo->mainp;
+ int ci;
+ jpeg_component_info *compptr;
+ boolean writing = (mainp->pass_mode != JBUF_CRANK_DEST);
+ int data_unit = cinfo->data_unit;
+
+ while (mainp->cur_iMCU_row < cinfo->total_iMCU_rows) {
+ /* Realign the virtual buffers if at the start of an iMCU row. */
+ if (mainp->rowgroup_ctr == 0) {
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ mainp->buffer[ci] = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, mainp->whole_image[ci],
+ mainp->cur_iMCU_row * (compptr->v_samp_factor * data_unit),
+ (JDIMENSION) (compptr->v_samp_factor * data_unit), writing);
+ }
+ /* In a read pass, pretend we just read some source data. */
+ if (! writing) {
+ *in_row_ctr += cinfo->max_v_samp_factor * data_unit;
+ mainp->rowgroup_ctr = data_unit;
+ }
+ }
+
+ /* If a write pass, read input data until the current iMCU row is full. */
+ /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
+ if (writing) {
+ (*cinfo->prep->pre_process_data) (cinfo,
+ input_buf, in_row_ctr, in_rows_avail,
+ mainp->buffer, &mainp->rowgroup_ctr,
+ (JDIMENSION) data_unit);
+ /* Return to application if we need more data to fill the iMCU row. */
+ if (mainp->rowgroup_ctr < data_unit)
+ return;
+ }
+
+ /* Emit data, unless this is a sink-only pass. */
+ if (mainp->pass_mode != JBUF_SAVE_SOURCE) {
+ if (! (*cinfo->codec->compress_data) (cinfo, mainp->buffer)) {
+ /* If compressor did not consume the whole row, then we must need to
+ * suspend processing and return to the application. In this situation
+ * we pretend we didn't yet consume the last input row; otherwise, if
+ * it happened to be the last row of the image, the application would
+ * think we were done.
+ */
+ if (! mainp->suspended) {
+ (*in_row_ctr)--;
+ mainp->suspended = TRUE;
+ }
+ return;
+ }
+ /* We did finish the row. Undo our little suspension hack if a previous
+ * call suspended; then mark the main buffer empty.
+ */
+ if (mainp->suspended) {
+ (*in_row_ctr)++;
+ mainp->suspended = FALSE;
+ }
+ }
+
+ /* If get here, we are done with this iMCU row. Mark buffer empty. */
+ mainp->rowgroup_ctr = 0;
+ mainp->cur_iMCU_row++;
+ }
+}
+
+#endif /* FULL_MAIN_BUFFER_SUPPORTED */
+
+
+/*
+ * Initialize main buffer controller.
+ */
+
+GLOBAL(void)
+jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
+{
+ my_main_ptr mainp;
+ int ci;
+ jpeg_component_info *compptr;
+ int data_unit = cinfo->data_unit;
+
+ mainp = (my_main_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_main_controller));
+ cinfo->mainp = (struct jpeg_c_main_controller *) mainp;
+ mainp->pub.start_pass = start_pass_main;
+
+ /* We don't need to create a buffer in raw-data mode. */
+ if (cinfo->raw_data_in)
+ return;
+
+ /* Create the buffer. It holds downsampled data, so each component
+ * may be of a different size.
+ */
+ if (need_full_buffer) {
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+ /* Allocate a full-image virtual array for each component */
+ /* Note we pad the bottom to a multiple of the iMCU height */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ mainp->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ compptr->width_in_data_units * data_unit * SIZEOF(JSAMPLE16),
+ (JDIMENSION) jround_up((long) compptr->height_in_data_units,
+ (long) compptr->v_samp_factor) * data_unit,
+ (JDIMENSION) (compptr->v_samp_factor * data_unit));
+ }
+#else
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+#endif
+ } else {
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+ mainp->whole_image[0] = NULL; /* flag for no virtual arrays */
+#endif
+ /* Allocate a strip buffer for each component */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ mainp->buffer[ci] = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ compptr->width_in_data_units * data_unit * SIZEOF(JSAMPLE16),
+ (JDIMENSION) (compptr->v_samp_factor * data_unit));
+ }
+ }
+}
diff --git a/jpeg-6c/jcmarker.c b/jpeg-6c/jcmarker.c
new file mode 100644
index 0000000..1541dc6
--- /dev/null
+++ b/jpeg-6c/jcmarker.c
@@ -0,0 +1,672 @@
+/*
+ * jcmarker.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to write JPEG datastream markers.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+typedef enum { /* JPEG marker codes */
+ M_SOF0 = 0xc0,
+ M_SOF1 = 0xc1,
+ M_SOF2 = 0xc2,
+ M_SOF3 = 0xc3,
+
+ M_SOF5 = 0xc5,
+ M_SOF6 = 0xc6,
+ M_SOF7 = 0xc7,
+
+ M_JPG = 0xc8,
+ M_SOF9 = 0xc9,
+ M_SOF10 = 0xca,
+ M_SOF11 = 0xcb,
+
+ M_SOF13 = 0xcd,
+ M_SOF14 = 0xce,
+ M_SOF15 = 0xcf,
+
+ M_DHT = 0xc4,
+
+ M_DAC = 0xcc,
+
+ M_RST0 = 0xd0,
+ M_RST1 = 0xd1,
+ M_RST2 = 0xd2,
+ M_RST3 = 0xd3,
+ M_RST4 = 0xd4,
+ M_RST5 = 0xd5,
+ M_RST6 = 0xd6,
+ M_RST7 = 0xd7,
+
+ M_SOI = 0xd8,
+ M_EOI = 0xd9,
+ M_SOS = 0xda,
+ M_DQT = 0xdb,
+ M_DNL = 0xdc,
+ M_DRI = 0xdd,
+ M_DHP = 0xde,
+ M_EXP = 0xdf,
+
+ M_APP0 = 0xe0,
+ M_APP1 = 0xe1,
+ M_APP2 = 0xe2,
+ M_APP3 = 0xe3,
+ M_APP4 = 0xe4,
+ M_APP5 = 0xe5,
+ M_APP6 = 0xe6,
+ M_APP7 = 0xe7,
+ M_APP8 = 0xe8,
+ M_APP9 = 0xe9,
+ M_APP10 = 0xea,
+ M_APP11 = 0xeb,
+ M_APP12 = 0xec,
+ M_APP13 = 0xed,
+ M_APP14 = 0xee,
+ M_APP15 = 0xef,
+
+ M_JPG0 = 0xf0,
+ M_JPG13 = 0xfd,
+ M_COM = 0xfe,
+
+ M_TEM = 0x01,
+
+ M_ERROR = 0x100
+} JPEG_MARKER;
+
+
+/* Private state */
+
+typedef struct {
+ struct jpeg_marker_writer pub; /* public fields */
+
+ unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
+} my_marker_writer;
+
+typedef my_marker_writer * my_marker_ptr;
+
+
+/*
+ * Basic output routines.
+ *
+ * Note that we do not support suspension while writing a marker.
+ * Therefore, an application using suspension must ensure that there is
+ * enough buffer space for the initial markers (typ. 600-700 bytes) before
+ * calling jpeg_start_compress, and enough space to write the trailing EOI
+ * (a few bytes) before calling jpeg_finish_compress. Multipass compression
+ * modes are not supported at all with suspension, so those two are the only
+ * points where markers will be written.
+ */
+
+LOCAL(void)
+emit_byte (j_compress_ptr cinfo, int val)
+/* Emit a byte */
+{
+ struct jpeg_destination_mgr * dest = cinfo->dest;
+
+ *(dest->next_output_byte)++ = (JOCTET) val;
+ if (--dest->free_in_buffer == 0) {
+ if (! (*dest->empty_output_buffer) (cinfo))
+ ERREXIT(cinfo, JERR_CANT_SUSPEND);
+ }
+}
+
+
+LOCAL(void)
+emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
+/* Emit a marker code */
+{
+ emit_byte(cinfo, 0xFF);
+ emit_byte(cinfo, (int) mark);
+}
+
+
+LOCAL(void)
+emit_2bytes (j_compress_ptr cinfo, int value)
+/* Emit a 2-byte integer; these are always MSB first in JPEG files */
+{
+ emit_byte(cinfo, (value >> 8) & 0xFF);
+ emit_byte(cinfo, value & 0xFF);
+}
+
+
+/*
+ * Routines to write specific marker types.
+ */
+
+LOCAL(int)
+emit_dqt (j_compress_ptr cinfo, int index)
+/* Emit a DQT marker */
+/* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
+{
+ JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
+ int prec;
+ int i;
+
+ if (qtbl == NULL)
+ ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
+
+ prec = 0;
+ for (i = 0; i < DCTSIZE2; i++) {
+ if (qtbl->quantval[i] > 255)
+ prec = 1;
+ }
+
+ if (! qtbl->sent_table) {
+ emit_marker(cinfo, M_DQT);
+
+ emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
+
+ emit_byte(cinfo, index + (prec<<4));
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ /* The table entries must be emitted in zigzag order. */
+ unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
+ if (prec)
+ emit_byte(cinfo, (int) (qval >> 8));
+ emit_byte(cinfo, (int) (qval & 0xFF));
+ }
+
+ qtbl->sent_table = TRUE;
+ }
+
+ return prec;
+}
+
+
+LOCAL(void)
+emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
+/* Emit a DHT marker */
+{
+ JHUFF_TBL * htbl;
+ int length, i;
+
+ if (is_ac) {
+ htbl = cinfo->ac_huff_tbl_ptrs[index];
+ index += 0x10; /* output index has AC bit set */
+ } else {
+ htbl = cinfo->dc_huff_tbl_ptrs[index];
+ }
+
+ if (htbl == NULL)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
+
+ if (! htbl->sent_table) {
+ emit_marker(cinfo, M_DHT);
+
+ length = 0;
+ for (i = 1; i <= 16; i++)
+ length += htbl->bits[i];
+
+ emit_2bytes(cinfo, length + 2 + 1 + 16);
+ emit_byte(cinfo, index);
+
+ for (i = 1; i <= 16; i++)
+ emit_byte(cinfo, htbl->bits[i]);
+
+ for (i = 0; i < length; i++)
+ emit_byte(cinfo, htbl->huffval[i]);
+
+ htbl->sent_table = TRUE;
+ }
+}
+
+
+LOCAL(void)
+emit_dac (j_compress_ptr cinfo)
+/* Emit a DAC marker */
+/* Since the useful info is so small, we want to emit all the tables in */
+/* one DAC marker. Therefore this routine does its own scan of the table. */
+{
+#ifdef C_ARITH_CODING_SUPPORTED
+ char dc_in_use[NUM_ARITH_TBLS];
+ char ac_in_use[NUM_ARITH_TBLS];
+ int length, i;
+ jpeg_component_info *compptr;
+
+ for (i = 0; i < NUM_ARITH_TBLS; i++)
+ dc_in_use[i] = ac_in_use[i] = 0;
+
+ for (i = 0; i < cinfo->comps_in_scan; i++) {
+ compptr = cinfo->cur_comp_info[i];
+ dc_in_use[compptr->dc_tbl_no] = 1;
+ ac_in_use[compptr->ac_tbl_no] = 1;
+ }
+
+ length = 0;
+ for (i = 0; i < NUM_ARITH_TBLS; i++)
+ length += dc_in_use[i] + ac_in_use[i];
+
+ emit_marker(cinfo, M_DAC);
+
+ emit_2bytes(cinfo, length*2 + 2);
+
+ for (i = 0; i < NUM_ARITH_TBLS; i++) {
+ if (dc_in_use[i]) {
+ emit_byte(cinfo, i);
+ emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
+ }
+ if (ac_in_use[i]) {
+ emit_byte(cinfo, i + 0x10);
+ emit_byte(cinfo, cinfo->arith_ac_K[i]);
+ }
+ }
+#endif /* C_ARITH_CODING_SUPPORTED */
+}
+
+
+LOCAL(void)
+emit_dri (j_compress_ptr cinfo)
+/* Emit a DRI marker */
+{
+ emit_marker(cinfo, M_DRI);
+
+ emit_2bytes(cinfo, 4); /* fixed length */
+
+ emit_2bytes(cinfo, (int) cinfo->restart_interval);
+}
+
+
+LOCAL(void)
+emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
+/* Emit a SOF marker */
+{
+ int ci;
+ jpeg_component_info *compptr;
+
+ emit_marker(cinfo, code);
+
+ emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
+
+ /* Make sure image isn't bigger than SOF field can handle */
+ if ((long) cinfo->image_height > 65535L ||
+ (long) cinfo->image_width > 65535L)
+ ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
+
+ emit_byte(cinfo, cinfo->data_precision);
+ emit_2bytes(cinfo, (int) cinfo->image_height);
+ emit_2bytes(cinfo, (int) cinfo->image_width);
+
+ emit_byte(cinfo, cinfo->num_components);
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ emit_byte(cinfo, compptr->component_id);
+ emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
+ emit_byte(cinfo, compptr->quant_tbl_no);
+ }
+}
+
+
+LOCAL(void)
+emit_sos (j_compress_ptr cinfo)
+/* Emit a SOS marker */
+{
+ int i, td, ta;
+ jpeg_component_info *compptr;
+
+ emit_marker(cinfo, M_SOS);
+
+ emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
+
+ emit_byte(cinfo, cinfo->comps_in_scan);
+
+ for (i = 0; i < cinfo->comps_in_scan; i++) {
+ compptr = cinfo->cur_comp_info[i];
+ emit_byte(cinfo, compptr->component_id);
+ td = compptr->dc_tbl_no;
+ ta = compptr->ac_tbl_no;
+ if (cinfo->process == JPROC_PROGRESSIVE) {
+ /* Progressive mode: only DC or only AC tables are used in one scan;
+ * furthermore, Huffman coding of DC refinement uses no table at all.
+ * We emit 0 for unused field(s); this is recommended by the P&M text
+ * but does not seem to be specified in the standard.
+ */
+ if (cinfo->Ss == 0) {
+ ta = 0; /* DC scan */
+ if (cinfo->Ah != 0 && !cinfo->arith_code)
+ td = 0; /* no DC table either */
+ } else {
+ td = 0; /* AC scan */
+ }
+ }
+ emit_byte(cinfo, (td << 4) + ta);
+ }
+
+ emit_byte(cinfo, cinfo->Ss);
+ emit_byte(cinfo, cinfo->Se);
+ emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
+}
+
+
+LOCAL(void)
+emit_jfif_app0 (j_compress_ptr cinfo)
+/* Emit a JFIF-compliant APP0 marker */
+{
+ /*
+ * Length of APP0 block (2 bytes)
+ * Block ID (4 bytes - ASCII "JFIF")
+ * Zero byte (1 byte to terminate the ID string)
+ * Version Major, Minor (2 bytes - major first)
+ * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
+ * Xdpu (2 bytes - dots per unit horizontal)
+ * Ydpu (2 bytes - dots per unit vertical)
+ * Thumbnail X size (1 byte)
+ * Thumbnail Y size (1 byte)
+ */
+
+ emit_marker(cinfo, M_APP0);
+
+ emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
+
+ emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
+ emit_byte(cinfo, 0x46);
+ emit_byte(cinfo, 0x49);
+ emit_byte(cinfo, 0x46);
+ emit_byte(cinfo, 0);
+ emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
+ emit_byte(cinfo, cinfo->JFIF_minor_version);
+ emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
+ emit_2bytes(cinfo, (int) cinfo->X_density);
+ emit_2bytes(cinfo, (int) cinfo->Y_density);
+ emit_byte(cinfo, 0); /* No thumbnail image */
+ emit_byte(cinfo, 0);
+}
+
+
+LOCAL(void)
+emit_adobe_app14 (j_compress_ptr cinfo)
+/* Emit an Adobe APP14 marker */
+{
+ /*
+ * Length of APP14 block (2 bytes)
+ * Block ID (5 bytes - ASCII "Adobe")
+ * Version Number (2 bytes - currently 100)
+ * Flags0 (2 bytes - currently 0)
+ * Flags1 (2 bytes - currently 0)
+ * Color transform (1 byte)
+ *
+ * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
+ * now in circulation seem to use Version = 100, so that's what we write.
+ *
+ * We write the color transform byte as 1 if the JPEG color space is
+ * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
+ * whether the encoder performed a transformation, which is pretty useless.
+ */
+
+ emit_marker(cinfo, M_APP14);
+
+ emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
+
+ emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
+ emit_byte(cinfo, 0x64);
+ emit_byte(cinfo, 0x6F);
+ emit_byte(cinfo, 0x62);
+ emit_byte(cinfo, 0x65);
+ emit_2bytes(cinfo, 100); /* Version */
+ emit_2bytes(cinfo, 0); /* Flags0 */
+ emit_2bytes(cinfo, 0); /* Flags1 */
+ switch (cinfo->jpeg_color_space) {
+ case JCS_YCbCr:
+ emit_byte(cinfo, 1); /* Color transform = 1 */
+ break;
+ case JCS_YCCK:
+ emit_byte(cinfo, 2); /* Color transform = 2 */
+ break;
+ default:
+ emit_byte(cinfo, 0); /* Color transform = 0 */
+ break;
+ }
+}
+
+
+/*
+ * These routines allow writing an arbitrary marker with parameters.
+ * The only intended use is to emit COM or APPn markers after calling
+ * write_file_header and before calling write_frame_header.
+ * Other uses are not guaranteed to produce desirable results.
+ * Counting the parameter bytes properly is the caller's responsibility.
+ */
+
+METHODDEF(void)
+write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
+/* Emit an arbitrary marker header */
+{
+ if (datalen > (unsigned int) 65533) /* safety check */
+ ERREXIT(cinfo, JERR_BAD_LENGTH);
+
+ emit_marker(cinfo, (JPEG_MARKER) marker);
+
+ emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
+}
+
+METHODDEF(void)
+write_marker_byte (j_compress_ptr cinfo, int val)
+/* Emit one byte of marker parameters following write_marker_header */
+{
+ emit_byte(cinfo, val);
+}
+
+
+/*
+ * Write datastream header.
+ * This consists of an SOI and optional APPn markers.
+ * We recommend use of the JFIF marker, but not the Adobe marker,
+ * when using YCbCr or grayscale data. The JFIF marker should NOT
+ * be used for any other JPEG colorspace. The Adobe marker is helpful
+ * to distinguish RGB, CMYK, and YCCK colorspaces.
+ * Note that an application can write additional header markers after
+ * jpeg_start_compress returns.
+ */
+
+METHODDEF(void)
+write_file_header (j_compress_ptr cinfo)
+{
+ my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
+
+ emit_marker(cinfo, M_SOI); /* first the SOI */
+
+ /* SOI is defined to reset restart interval to 0 */
+ marker->last_restart_interval = 0;
+
+ if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
+ emit_jfif_app0(cinfo);
+ if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
+ emit_adobe_app14(cinfo);
+}
+
+
+/*
+ * Write frame header.
+ * This consists of DQT and SOFn markers.
+ * Note that we do not emit the SOF until we have emitted the DQT(s).
+ * This avoids compatibility problems with incorrect implementations that
+ * try to error-check the quant table numbers as soon as they see the SOF.
+ */
+
+METHODDEF(void)
+write_frame_header (j_compress_ptr cinfo)
+{
+ int ci, prec = 0;
+ boolean is_baseline;
+ jpeg_component_info *compptr;
+
+ if (cinfo->process != JPROC_LOSSLESS) {
+ /* Emit DQT for each quantization table.
+ * Note that emit_dqt() suppresses any duplicate tables.
+ */
+ prec = 0;
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ prec += emit_dqt(cinfo, compptr->quant_tbl_no);
+ }
+ /* now prec is nonzero if there are any 16-bit quant tables. */
+ }
+
+ /* Check for a non-baseline specification.
+ * Note we assume that Huffman table numbers won't be changed later.
+ */
+ if (cinfo->arith_code || cinfo->process != JPROC_SEQUENTIAL ||
+ cinfo->data_precision != 8) {
+ is_baseline = FALSE;
+ } else {
+ is_baseline = TRUE;
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
+ is_baseline = FALSE;
+ }
+ if (prec && is_baseline) {
+ is_baseline = FALSE;
+ /* If it's baseline except for quantizer size, warn the user */
+ TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
+ }
+ }
+
+ /* Emit the proper SOF marker */
+ if (cinfo->arith_code) {
+ emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
+ } else {
+ if (cinfo->process == JPROC_PROGRESSIVE)
+ emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
+ else if (cinfo->process == JPROC_LOSSLESS)
+ emit_sof(cinfo, M_SOF3); /* SOF code for lossless Huffman */
+ else if (is_baseline)
+ emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
+ else
+ emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
+ }
+}
+
+
+/*
+ * Write scan header.
+ * This consists of DHT or DAC markers, optional DRI, and SOS.
+ * Compressed data will be written following the SOS.
+ */
+
+METHODDEF(void)
+write_scan_header (j_compress_ptr cinfo)
+{
+ my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
+ int i;
+ jpeg_component_info *compptr;
+
+ if (cinfo->arith_code) {
+ /* Emit arith conditioning info. We may have some duplication
+ * if the file has multiple scans, but it's so small it's hardly
+ * worth worrying about.
+ */
+ emit_dac(cinfo);
+ } else {
+ /* Emit Huffman tables.
+ * Note that emit_dht() suppresses any duplicate tables.
+ */
+ for (i = 0; i < cinfo->comps_in_scan; i++) {
+ compptr = cinfo->cur_comp_info[i];
+ if (cinfo->process == JPROC_PROGRESSIVE) {
+ /* Progressive mode: only DC or only AC tables are used in one scan */
+ if (cinfo->Ss == 0) {
+ if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
+ emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
+ } else {
+ emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
+ }
+ } else if (cinfo->process == JPROC_LOSSLESS) {
+ /* Lossless mode: only DC tables are used */
+ emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
+ } else {
+ /* Sequential mode: need both DC and AC tables */
+ emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
+ emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
+ }
+ }
+ }
+
+ /* Emit DRI if required --- note that DRI value could change for each scan.
+ * We avoid wasting space with unnecessary DRIs, however.
+ */
+ if (cinfo->restart_interval != marker->last_restart_interval) {
+ emit_dri(cinfo);
+ marker->last_restart_interval = cinfo->restart_interval;
+ }
+
+ emit_sos(cinfo);
+}
+
+
+/*
+ * Write datastream trailer.
+ */
+
+METHODDEF(void)
+write_file_trailer (j_compress_ptr cinfo)
+{
+ emit_marker(cinfo, M_EOI);
+}
+
+
+/*
+ * Write an abbreviated table-specification datastream.
+ * This consists of SOI, DQT and DHT tables, and EOI.
+ * Any table that is defined and not marked sent_table = TRUE will be
+ * emitted. Note that all tables will be marked sent_table = TRUE at exit.
+ */
+
+METHODDEF(void)
+write_tables_only (j_compress_ptr cinfo)
+{
+ int i;
+
+ emit_marker(cinfo, M_SOI);
+
+ for (i = 0; i < NUM_QUANT_TBLS; i++) {
+ if (cinfo->quant_tbl_ptrs[i] != NULL)
+ (void) emit_dqt(cinfo, i);
+ }
+
+ if (! cinfo->arith_code) {
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
+ emit_dht(cinfo, i, FALSE);
+ if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
+ emit_dht(cinfo, i, TRUE);
+ }
+ }
+
+ emit_marker(cinfo, M_EOI);
+}
+
+
+/*
+ * Initialize the marker writer module.
+ */
+
+GLOBAL(void)
+jinit_marker_writer (j_compress_ptr cinfo)
+{
+ my_marker_ptr marker;
+
+ /* Create the subobject */
+ marker = (my_marker_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_marker_writer));
+ cinfo->marker = (struct jpeg_marker_writer *) marker;
+ /* Initialize method pointers */
+ marker->pub.write_file_header = write_file_header;
+ marker->pub.write_frame_header = write_frame_header;
+ marker->pub.write_scan_header = write_scan_header;
+ marker->pub.write_file_trailer = write_file_trailer;
+ marker->pub.write_tables_only = write_tables_only;
+ marker->pub.write_marker_header = write_marker_header;
+ marker->pub.write_marker_byte = write_marker_byte;
+ /* Initialize private state */
+ marker->last_restart_interval = 0;
+}
diff --git a/jpeg-6c/jcmaster.c b/jpeg-6c/jcmaster.c
new file mode 100644
index 0000000..1e8cd8d
--- /dev/null
+++ b/jpeg-6c/jcmaster.c
@@ -0,0 +1,654 @@
+/*
+ * jcmaster.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains master control logic for the JPEG compressor.
+ * These routines are concerned with parameter validation, initial setup,
+ * and inter-pass control (determining the number of passes and the work
+ * to be done in each pass).
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h" /* Private declarations for lossy codec */
+
+
+/* Private state */
+
+typedef enum {
+ main_pass, /* input data, also do first output step */
+ huff_opt_pass, /* Huffman code optimization pass */
+ output_pass /* data output pass */
+} c_pass_type;
+
+typedef struct {
+ struct jpeg_comp_master pub; /* public fields */
+
+ c_pass_type pass_type; /* the type of the current pass */
+
+ int pass_number; /* # of passes completed */
+ int total_passes; /* total # of passes needed */
+
+ int scan_number; /* current index in scan_info[] */
+} my_comp_master;
+
+typedef my_comp_master * my_master_ptr;
+
+
+/*
+ * Support routines that do various essential calculations.
+ */
+
+LOCAL(void)
+initial_setup (j_compress_ptr cinfo)
+/* Do computations that are needed before master selection phase */
+{
+ int ci;
+ jpeg_component_info *compptr;
+ long samplesperrow;
+ JDIMENSION jd_samplesperrow;
+ int data_unit = cinfo->data_unit;
+
+ /* Sanity check on image dimensions */
+ if (cinfo->image_height <= 0 || cinfo->image_width <= 0
+ || cinfo->num_components <= 0 || cinfo->input_components <= 0)
+ ERREXIT(cinfo, JERR_EMPTY_IMAGE);
+
+ /* Make sure image isn't bigger than I can handle */
+ if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
+ (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
+ ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
+
+ /* Width of an input scanline must be representable as JDIMENSION. */
+ samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
+ jd_samplesperrow = (JDIMENSION) samplesperrow;
+ if ((long) jd_samplesperrow != samplesperrow)
+ ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
+
+ /* For now, precision must match compiled-in value... */
+/* if (cinfo->data_precision != BITS_IN_JSAMPLE)
+ ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);*/
+
+ /* Check that number of components won't exceed internal array sizes */
+ if (cinfo->num_components > MAX_COMPONENTS)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
+ MAX_COMPONENTS);
+
+ /* Compute maximum sampling factors; check factor validity */
+ cinfo->max_h_samp_factor = 1;
+ cinfo->max_v_samp_factor = 1;
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
+ compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
+ ERREXIT(cinfo, JERR_BAD_SAMPLING);
+ cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
+ compptr->h_samp_factor);
+ cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
+ compptr->v_samp_factor);
+ }
+
+ /* Compute dimensions of components */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Fill in the correct component_index value; don't rely on application */
+ compptr->component_index = ci;
+ /* For compression, we never do any codec-based processing. */
+ compptr->codec_data_unit = data_unit;
+ /* Size in data units */
+ compptr->width_in_data_units = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+ (long) (cinfo->max_h_samp_factor * data_unit));
+ compptr->height_in_data_units = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+ (long) (cinfo->max_v_samp_factor * data_unit));
+ /* Size in samples */
+ compptr->downsampled_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+ (long) cinfo->max_h_samp_factor);
+ compptr->downsampled_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+ (long) cinfo->max_v_samp_factor);
+ /* Mark component needed (this flag isn't actually used for compression) */
+ compptr->component_needed = TRUE;
+ }
+
+ /* Compute number of fully interleaved MCU rows (number of times that
+ * main controller will call coefficient controller).
+ */
+ cinfo->total_iMCU_rows = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+ (long) (cinfo->max_v_samp_factor*data_unit));
+}
+
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+#define NEED_SCAN_SCRIPT
+#else
+#ifdef C_LOSSLESS_SUPPORTED
+#define NEED_SCAN_SCRIPT
+#endif
+#endif
+
+#ifdef NEED_SCAN_SCRIPT
+
+LOCAL(void)
+validate_script (j_compress_ptr cinfo)
+/* Verify that the scan script in cinfo->scan_info[] is valid; also
+ * determine whether it uses progressive JPEG, and set cinfo->process.
+ */
+{
+ const jpeg_scan_info * scanptr;
+ int scanno, ncomps, ci, coefi, thisi;
+ int Ss, Se, Ah, Al;
+ boolean component_sent[MAX_COMPONENTS];
+#ifdef C_PROGRESSIVE_SUPPORTED
+ int * last_bitpos_ptr;
+ int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
+ /* -1 until that coefficient has been seen; then last Al for it */
+#endif
+
+ if (cinfo->num_scans <= 0)
+ ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
+
+#ifndef C_MULTISCAN_FILES_SUPPORTED
+ if (cinfo->num_scans > 1)
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+
+ scanptr = cinfo->scan_info;
+ if (cinfo->lossless) {
+#ifdef C_LOSSLESS_SUPPORTED
+ cinfo->process = JPROC_LOSSLESS;
+ for (ci = 0; ci < cinfo->num_components; ci++)
+ component_sent[ci] = FALSE;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ }
+ /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
+ * for progressive JPEG, no scan can have this.
+ */
+ else if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
+#ifdef C_PROGRESSIVE_SUPPORTED
+ cinfo->process = JPROC_PROGRESSIVE;
+ last_bitpos_ptr = & last_bitpos[0][0];
+ for (ci = 0; ci < cinfo->num_components; ci++)
+ for (coefi = 0; coefi < DCTSIZE2; coefi++)
+ *last_bitpos_ptr++ = -1;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ cinfo->process = JPROC_SEQUENTIAL;
+ for (ci = 0; ci < cinfo->num_components; ci++)
+ component_sent[ci] = FALSE;
+ }
+
+ for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
+ /* Validate component indexes */
+ ncomps = scanptr->comps_in_scan;
+ if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
+ for (ci = 0; ci < ncomps; ci++) {
+ thisi = scanptr->component_index[ci];
+ if (thisi < 0 || thisi >= cinfo->num_components)
+ ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
+ /* Components must appear in SOF order within each scan */
+ if (ci > 0 && thisi <= scanptr->component_index[ci-1])
+ ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
+ }
+ /* Validate progression parameters */
+ Ss = scanptr->Ss;
+ Se = scanptr->Se;
+ Ah = scanptr->Ah;
+ Al = scanptr->Al;
+ if (cinfo->process == JPROC_LOSSLESS) {
+#ifdef C_LOSSLESS_SUPPORTED
+ /* The JPEG spec simply gives the range 0..15 for Al (Pt), but that
+ * seems wrong: the upper bound ought to depend on data precision.
+ * Perhaps they really meant 0..N-1 for N-bit precision, which is what
+ * we allow here.
+ */
+ if (Ss < 1 || Ss > 7 || /* predictor selector */
+ Se != 0 || Ah != 0 ||
+ Al < 0 || Al >= cinfo->data_precision || Al >= JSAMPLEMAX) /* point transform */
+ ERREXIT1(cinfo, JERR_BAD_LOSSLESS_SCRIPT, scanno);
+ /* Make sure components are not sent twice */
+ for (ci = 0; ci < ncomps; ci++) {
+ thisi = scanptr->component_index[ci];
+ if (component_sent[thisi])
+ ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
+ component_sent[thisi] = TRUE;
+ }
+#endif
+ } else if (cinfo->process == JPROC_PROGRESSIVE) {
+#ifdef C_PROGRESSIVE_SUPPORTED
+ /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
+ * seems wrong: the upper bound ought to depend on data precision.
+ * Perhaps they really meant 0..N+1 for N-bit precision.
+ * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
+ * out-of-range reconstructed DC values during the first DC scan,
+ * which might cause problems for some decoders.
+ */
+/*#if BITS_IN_JSAMPLE == 8
+#define MAX_AH_AL 10
+#else
+#define MAX_AH_AL 13
+#endif*/
+ if (cinfo->data_precision <= 8) {
+ if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
+ Ah < 0 || Ah > 10 || Al < 0 || Al > 10)
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ } else {
+ if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
+ Ah < 0 || Ah > 13 || Al < 0 || Al > 13)
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ }
+ if (Ss == 0) {
+ if (Se != 0) /* DC and AC together not OK */
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ } else {
+ if (ncomps != 1) /* AC scans must be for only one component */
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ }
+ for (ci = 0; ci < ncomps; ci++) {
+ last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
+ if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ for (coefi = Ss; coefi <= Se; coefi++) {
+ if (last_bitpos_ptr[coefi] < 0) {
+ /* first scan of this coefficient */
+ if (Ah != 0)
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ } else {
+ /* not first scan */
+ if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ }
+ last_bitpos_ptr[coefi] = Al;
+ }
+ }
+#endif
+ } else {
+ /* For sequential JPEG, all progression parameters must be these: */
+ if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
+ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
+ /* Make sure components are not sent twice */
+ for (ci = 0; ci < ncomps; ci++) {
+ thisi = scanptr->component_index[ci];
+ if (component_sent[thisi])
+ ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
+ component_sent[thisi] = TRUE;
+ }
+ }
+ }
+
+ /* Now verify that everything got sent. */
+ if (cinfo->process == JPROC_PROGRESSIVE) {
+#ifdef C_PROGRESSIVE_SUPPORTED
+ /* For progressive mode, we only check that at least some DC data
+ * got sent for each component; the spec does not require that all bits
+ * of all coefficients be transmitted. Would it be wiser to enforce
+ * transmission of all coefficient bits??
+ */
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ if (last_bitpos[ci][0] < 0)
+ ERREXIT(cinfo, JERR_MISSING_DATA);
+ }
+#endif
+ } else {
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ if (! component_sent[ci])
+ ERREXIT(cinfo, JERR_MISSING_DATA);
+ }
+ }
+}
+
+#endif /* NEED_SCAN_SCRIPT */
+
+
+LOCAL(void)
+select_scan_parameters (j_compress_ptr cinfo)
+/* Set up the scan parameters for the current scan */
+{
+ int ci;
+
+#ifdef NEED_SCAN_SCRIPT
+ if (cinfo->scan_info != NULL) {
+ /* Prepare for current scan --- the script is already validated */
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+ const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
+
+ cinfo->comps_in_scan = scanptr->comps_in_scan;
+ for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
+ cinfo->cur_comp_info[ci] =
+ &cinfo->comp_info[scanptr->component_index[ci]];
+ }
+ cinfo->Ss = scanptr->Ss;
+ cinfo->Se = scanptr->Se;
+ cinfo->Ah = scanptr->Ah;
+ cinfo->Al = scanptr->Al;
+ } else
+#endif
+ {
+ /* Prepare for single sequential-JPEG scan containing all components */
+ if (cinfo->num_components > MAX_COMPS_IN_SCAN)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
+ MAX_COMPS_IN_SCAN);
+ cinfo->comps_in_scan = cinfo->num_components;
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
+ }
+ if (cinfo->lossless) {
+#ifdef C_LOSSLESS_SUPPORTED
+ /* If we fall through to here, the user specified lossless, but did not
+ * provide a scan script.
+ */
+ ERREXIT(cinfo, JERR_NO_LOSSLESS_SCRIPT);
+#endif
+ } else {
+ cinfo->process = JPROC_SEQUENTIAL;
+ cinfo->Ss = 0;
+ cinfo->Se = DCTSIZE2-1;
+ cinfo->Ah = 0;
+ cinfo->Al = 0;
+ }
+ }
+}
+
+
+LOCAL(void)
+per_scan_setup (j_compress_ptr cinfo)
+/* Do computations that are needed before processing a JPEG scan */
+/* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
+{
+ int ci, mcublks, tmp;
+ jpeg_component_info *compptr;
+ int data_unit = cinfo->data_unit;
+
+ if (cinfo->comps_in_scan == 1) {
+
+ /* Noninterleaved (single-component) scan */
+ compptr = cinfo->cur_comp_info[0];
+
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = compptr->width_in_data_units;
+ cinfo->MCU_rows_in_scan = compptr->height_in_data_units;
+
+ /* For noninterleaved scan, always one block per MCU */
+ compptr->MCU_width = 1;
+ compptr->MCU_height = 1;
+ compptr->MCU_data_units = 1;
+ compptr->MCU_sample_width = data_unit;
+ compptr->last_col_width = 1;
+ /* For noninterleaved scans, it is convenient to define last_row_height
+ * as the number of block rows present in the last iMCU row.
+ */
+ tmp = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
+ if (tmp == 0) tmp = compptr->v_samp_factor;
+ compptr->last_row_height = tmp;
+
+ /* Prepare array describing MCU composition */
+ cinfo->data_units_in_MCU = 1;
+ cinfo->MCU_membership[0] = 0;
+
+ } else {
+
+ /* Interleaved (multi-component) scan */
+ if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
+ MAX_COMPS_IN_SCAN);
+
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width,
+ (long) (cinfo->max_h_samp_factor*data_unit));
+ cinfo->MCU_rows_in_scan = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+ (long) (cinfo->max_v_samp_factor*data_unit));
+
+ cinfo->data_units_in_MCU = 0;
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* Sampling factors give # of blocks of component in each MCU */
+ compptr->MCU_width = compptr->h_samp_factor;
+ compptr->MCU_height = compptr->v_samp_factor;
+ compptr->MCU_data_units = compptr->MCU_width * compptr->MCU_height;
+ compptr->MCU_sample_width = compptr->MCU_width * data_unit;
+ /* Figure number of non-dummy blocks in last MCU column & row */
+ tmp = (int) (compptr->width_in_data_units % compptr->MCU_width);
+ if (tmp == 0) tmp = compptr->MCU_width;
+ compptr->last_col_width = tmp;
+ tmp = (int) (compptr->height_in_data_units % compptr->MCU_height);
+ if (tmp == 0) tmp = compptr->MCU_height;
+ compptr->last_row_height = tmp;
+ /* Prepare array describing MCU composition */
+ mcublks = compptr->MCU_data_units;
+ if (cinfo->data_units_in_MCU + mcublks > C_MAX_DATA_UNITS_IN_MCU)
+ ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
+ while (mcublks-- > 0) {
+ cinfo->MCU_membership[cinfo->data_units_in_MCU++] = ci;
+ }
+ }
+
+ }
+
+ /* Convert restart specified in rows to actual MCU count. */
+ /* Note that count must fit in 16 bits, so we provide limiting. */
+ if (cinfo->restart_in_rows > 0) {
+ long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
+ cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
+ }
+}
+
+
+/*
+ * Per-pass setup.
+ * This is called at the beginning of each pass. We determine which modules
+ * will be active during this pass and give them appropriate start_pass calls.
+ * We also set is_last_pass to indicate whether any more passes will be
+ * required.
+ */
+
+METHODDEF(void)
+prepare_for_pass (j_compress_ptr cinfo)
+{
+/* j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;*/
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ switch (master->pass_type) {
+ case main_pass:
+ /* Initial pass: will collect input data, and do either Huffman
+ * optimization or data output for the first scan.
+ */
+ select_scan_parameters(cinfo);
+ per_scan_setup(cinfo);
+ if (! cinfo->raw_data_in) {
+ (*cinfo->cconvert->start_pass) (cinfo);
+ (*cinfo->downsample->start_pass) (cinfo);
+ (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
+ }
+ (*cinfo->codec->entropy_start_pass) (cinfo, cinfo->optimize_coding);
+ (*cinfo->codec->start_pass) (cinfo,
+ (master->total_passes > 1 ?
+ JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
+ (*cinfo->mainp->start_pass) (cinfo, JBUF_PASS_THRU);
+ if (cinfo->optimize_coding) {
+ /* No immediate data output; postpone writing frame/scan headers */
+ master->pub.call_pass_startup = FALSE;
+ } else {
+ /* Will write frame/scan headers at first jpeg_write_scanlines call */
+ master->pub.call_pass_startup = TRUE;
+ }
+ break;
+#ifdef ENTROPY_OPT_SUPPORTED
+ case huff_opt_pass:
+ /* Do Huffman optimization for a scan after the first one. */
+ select_scan_parameters(cinfo);
+ per_scan_setup(cinfo);
+ if ((*cinfo->codec->need_optimization_pass) (cinfo) || cinfo->arith_code) {
+ (*cinfo->codec->entropy_start_pass) (cinfo, TRUE);
+ (*cinfo->codec->start_pass) (cinfo, JBUF_CRANK_DEST);
+ master->pub.call_pass_startup = FALSE;
+ break;
+ }
+ /* Special case: Huffman DC refinement scans need no Huffman table
+ * and therefore we can skip the optimization pass for them.
+ */
+ master->pass_type = output_pass;
+ master->pass_number++;
+ /*FALLTHROUGH*/
+#endif
+ case output_pass:
+ /* Do a data-output pass. */
+ /* We need not repeat per-scan setup if prior optimization pass did it. */
+ if (! cinfo->optimize_coding) {
+ select_scan_parameters(cinfo);
+ per_scan_setup(cinfo);
+ }
+ (*cinfo->codec->entropy_start_pass) (cinfo, FALSE);
+ (*cinfo->codec->start_pass) (cinfo, JBUF_CRANK_DEST);
+ /* We emit frame/scan headers now */
+ if (master->scan_number == 0)
+ (*cinfo->marker->write_frame_header) (cinfo);
+ (*cinfo->marker->write_scan_header) (cinfo);
+ master->pub.call_pass_startup = FALSE;
+ break;
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ }
+
+ master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
+
+ /* Set up progress monitor's pass info if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->completed_passes = master->pass_number;
+ cinfo->progress->total_passes = master->total_passes;
+ }
+}
+
+
+/*
+ * Special start-of-pass hook.
+ * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
+ * In single-pass processing, we need this hook because we don't want to
+ * write frame/scan headers during jpeg_start_compress; we want to let the
+ * application write COM markers etc. between jpeg_start_compress and the
+ * jpeg_write_scanlines loop.
+ * In multi-pass processing, this routine is not used.
+ */
+
+METHODDEF(void)
+pass_startup (j_compress_ptr cinfo)
+{
+ cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
+
+ (*cinfo->marker->write_frame_header) (cinfo);
+ (*cinfo->marker->write_scan_header) (cinfo);
+}
+
+
+/*
+ * Finish up at end of pass.
+ */
+
+METHODDEF(void)
+finish_pass_master (j_compress_ptr cinfo)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ /* The entropy coder always needs an end-of-pass call,
+ * either to analyze statistics or to flush its output buffer.
+ */
+ (*lossyc->pub.entropy_finish_pass) (cinfo);
+
+ /* Update state for next pass */
+ switch (master->pass_type) {
+ case main_pass:
+ /* next pass is either output of scan 0 (after optimization)
+ * or output of scan 1 (if no optimization).
+ */
+ master->pass_type = output_pass;
+ if (! cinfo->optimize_coding)
+ master->scan_number++;
+ break;
+ case huff_opt_pass:
+ /* next pass is always output of current scan */
+ master->pass_type = output_pass;
+ break;
+ case output_pass:
+ /* next pass is either optimization or output of next scan */
+ if (cinfo->optimize_coding)
+ master->pass_type = huff_opt_pass;
+ master->scan_number++;
+ break;
+ }
+
+ master->pass_number++;
+}
+
+
+/*
+ * Initialize master compression control.
+ */
+
+GLOBAL(void)
+jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
+{
+ my_master_ptr master;
+
+ master = (my_master_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_comp_master));
+ cinfo->master = (struct jpeg_comp_master *) master;
+ master->pub.prepare_for_pass = prepare_for_pass;
+ master->pub.pass_startup = pass_startup;
+ master->pub.finish_pass = finish_pass_master;
+ master->pub.is_last_pass = FALSE;
+
+ cinfo->data_unit = cinfo->lossless ? 1 : DCTSIZE;
+
+ /* Validate parameters, determine derived values */
+ initial_setup(cinfo);
+
+ if (cinfo->scan_info != NULL) {
+#ifdef NEED_SCAN_SCRIPT
+ validate_script(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ cinfo->process = JPROC_SEQUENTIAL;
+ cinfo->num_scans = 1;
+ }
+
+ if (cinfo->process == JPROC_PROGRESSIVE || /* TEMPORARY HACK ??? */
+ cinfo->process == JPROC_LOSSLESS)
+ cinfo->optimize_coding = TRUE; /* assume default tables no good for
+ * progressive mode or lossless mode */
+
+ /* Initialize my private state */
+ if (transcode_only) {
+ /* no main pass in transcoding */
+ if (cinfo->optimize_coding)
+ master->pass_type = huff_opt_pass;
+ else
+ master->pass_type = output_pass;
+ } else {
+ /* for normal compression, first pass is always this type: */
+ master->pass_type = main_pass;
+ }
+ master->scan_number = 0;
+ master->pass_number = 0;
+ if (cinfo->optimize_coding)
+ master->total_passes = cinfo->num_scans * 2;
+ else
+ master->total_passes = cinfo->num_scans;
+}
diff --git a/jpeg-6c/jcodec.c b/jpeg-6c/jcodec.c
new file mode 100644
index 0000000..9529caa
--- /dev/null
+++ b/jpeg-6c/jcodec.c
@@ -0,0 +1,53 @@
+/*
+ * jcodec.c
+ *
+ * Copyright (C) 1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains utility functions for the JPEG codec(s).
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h"
+#include "jlossls.h"
+
+
+/*
+ * Initialize the compression codec.
+ * This is called only once, during master selection.
+ */
+
+GLOBAL(void)
+jinit_c_codec (j_compress_ptr cinfo)
+{
+ if (cinfo->process == JPROC_LOSSLESS) {
+#ifdef C_LOSSLESS_SUPPORTED
+ jinit_lossless_c_codec(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else
+ jinit_lossy_c_codec(cinfo);
+}
+
+
+/*
+ * Initialize the decompression codec.
+ * This is called only once, during master selection.
+ */
+
+GLOBAL(void)
+jinit_d_codec (j_decompress_ptr cinfo)
+{
+ if (cinfo->process == JPROC_LOSSLESS) {
+#ifdef D_LOSSLESS_SUPPORTED
+ jinit_lossless_d_codec(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else
+ jinit_lossy_d_codec(cinfo);
+}
diff --git a/jpeg-6c/jcomapi.c b/jpeg-6c/jcomapi.c
new file mode 100644
index 0000000..9b1fa75
--- /dev/null
+++ b/jpeg-6c/jcomapi.c
@@ -0,0 +1,106 @@
+/*
+ * jcomapi.c
+ *
+ * Copyright (C) 1994-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains application interface routines that are used for both
+ * compression and decompression.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Abort processing of a JPEG compression or decompression operation,
+ * but don't destroy the object itself.
+ *
+ * For this, we merely clean up all the nonpermanent memory pools.
+ * Note that temp files (virtual arrays) are not allowed to belong to
+ * the permanent pool, so we will be able to close all temp files here.
+ * Closing a data source or destination, if necessary, is the application's
+ * responsibility.
+ */
+
+GLOBAL(void)
+jpeg_abort (j_common_ptr cinfo)
+{
+ int pool;
+
+ /* Do nothing if called on a not-initialized or destroyed JPEG object. */
+ if (cinfo->mem == NULL)
+ return;
+
+ /* Releasing pools in reverse order might help avoid fragmentation
+ * with some (brain-damaged) malloc libraries.
+ */
+ for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
+ (*cinfo->mem->free_pool) (cinfo, pool);
+ }
+
+ /* Reset overall state for possible reuse of object */
+ if (cinfo->is_decompressor) {
+ cinfo->global_state = DSTATE_START;
+ /* Try to keep application from accessing now-deleted marker list.
+ * A bit kludgy to do it here, but this is the most central place.
+ */
+ ((j_decompress_ptr) cinfo)->marker_list = NULL;
+ } else {
+ cinfo->global_state = CSTATE_START;
+ }
+}
+
+
+/*
+ * Destruction of a JPEG object.
+ *
+ * Everything gets deallocated except the master jpeg_compress_struct itself
+ * and the error manager struct. Both of these are supplied by the application
+ * and must be freed, if necessary, by the application. (Often they are on
+ * the stack and so don't need to be freed anyway.)
+ * Closing a data source or destination, if necessary, is the application's
+ * responsibility.
+ */
+
+GLOBAL(void)
+jpeg_destroy (j_common_ptr cinfo)
+{
+ /* We need only tell the memory manager to release everything. */
+ /* NB: mem pointer is NULL if memory mgr failed to initialize. */
+ if (cinfo->mem != NULL)
+ (*cinfo->mem->self_destruct) (cinfo);
+ cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
+ cinfo->global_state = 0; /* mark it destroyed */
+}
+
+
+/*
+ * Convenience routines for allocating quantization and Huffman tables.
+ * (Would jutils.c be a more reasonable place to put these?)
+ */
+
+GLOBAL(JQUANT_TBL *)
+jpeg_alloc_quant_table (j_common_ptr cinfo)
+{
+ JQUANT_TBL *tbl;
+
+ tbl = (JQUANT_TBL *)
+ (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
+ tbl->sent_table = FALSE; /* make sure this is false in any new table */
+ return tbl;
+}
+
+
+GLOBAL(JHUFF_TBL *)
+jpeg_alloc_huff_table (j_common_ptr cinfo)
+{
+ JHUFF_TBL *tbl;
+
+ tbl = (JHUFF_TBL *)
+ (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
+ tbl->sent_table = FALSE; /* make sure this is false in any new table */
+ return tbl;
+}
diff --git a/jpeg-6c/jconfig.bcc b/jpeg-6c/jconfig.bcc
new file mode 100644
index 0000000..c6c53ff
--- /dev/null
+++ b/jpeg-6c/jconfig.bcc
@@ -0,0 +1,48 @@
+/* jconfig.bcc --- jconfig.h for Borland C (Turbo C) on MS-DOS or OS/2. */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+/* #define void char */
+/* #define const */
+#undef CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H
+#define HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#ifdef __MSDOS__
+#define NEED_FAR_POINTERS /* for small or medium memory model */
+#endif
+#undef NEED_SHORT_EXTERNAL_NAMES
+#undef INCOMPLETE_TYPES_BROKEN /* this assumes you have -w-stu in CFLAGS */
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+
+#ifdef __MSDOS__
+#define USE_MSDOS_MEMMGR /* Define this if you use jmemdos.c */
+#define MAX_ALLOC_CHUNK 65520L /* Maximum request to malloc() */
+#define USE_FMEM /* Borland has _fmemcpy() and _fmemset() */
+#endif
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#define TWO_FILE_COMMANDLINE
+#define USE_SETMODE /* Borland has setmode() */
+#ifdef __MSDOS__
+#define NEED_SIGNAL_CATCHER /* Define this if you use jmemdos.c */
+#endif
+#undef DONT_USE_B_MODE
+#undef PROGRESS_REPORT /* optional */
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/jpeg-6c/jconfig.cfg b/jpeg-6c/jconfig.cfg
new file mode 100644
index 0000000..36a04fa
--- /dev/null
+++ b/jpeg-6c/jconfig.cfg
@@ -0,0 +1,44 @@
+/* jconfig.cfg --- source file edited by configure script */
+/* see jconfig.doc for explanations */
+
+#undef HAVE_PROTOTYPES
+#undef HAVE_UNSIGNED_CHAR
+#undef HAVE_UNSIGNED_SHORT
+#undef void
+#undef const
+#undef CHAR_IS_UNSIGNED
+#undef HAVE_STDDEF_H
+#undef HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#undef NEED_FAR_POINTERS
+#undef NEED_SHORT_EXTERNAL_NAMES
+/* Define this if you get warnings about undefined structures. */
+#undef INCOMPLETE_TYPES_BROKEN
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+#undef INLINE
+/* These are for configuring the JPEG memory manager. */
+#undef DEFAULT_MAX_MEM
+#undef NO_MKTEMP
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#undef TWO_FILE_COMMANDLINE
+#undef NEED_SIGNAL_CATCHER
+#undef DONT_USE_B_MODE
+
+/* Define this if you want percent-done progress reports from cjpeg/djpeg. */
+#undef PROGRESS_REPORT
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/jpeg-6c/jconfig.dj b/jpeg-6c/jconfig.dj
new file mode 100644
index 0000000..f759a9d
--- /dev/null
+++ b/jpeg-6c/jconfig.dj
@@ -0,0 +1,38 @@
+/* jconfig.dj --- jconfig.h for DJGPP (Delorie's GNU C port) on MS-DOS. */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+/* #define void char */
+/* #define const */
+#undef CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H
+#define HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#undef NEED_FAR_POINTERS /* DJGPP uses flat 32-bit addressing */
+#undef NEED_SHORT_EXTERNAL_NAMES
+#undef INCOMPLETE_TYPES_BROKEN
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#undef TWO_FILE_COMMANDLINE /* optional */
+#define USE_SETMODE /* Needed to make one-file style work in DJGPP */
+#undef NEED_SIGNAL_CATCHER /* Define this if you use jmemname.c */
+#undef DONT_USE_B_MODE
+#undef PROGRESS_REPORT /* optional */
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/jpeg-6c/jconfig.doc b/jpeg-6c/jconfig.doc
new file mode 100644
index 0000000..c18d1c0
--- /dev/null
+++ b/jpeg-6c/jconfig.doc
@@ -0,0 +1,155 @@
+/*
+ * jconfig.doc
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file documents the configuration options that are required to
+ * customize the JPEG software for a particular system.
+ *
+ * The actual configuration options for a particular installation are stored
+ * in jconfig.h. On many machines, jconfig.h can be generated automatically
+ * or copied from one of the "canned" jconfig files that we supply. But if
+ * you need to generate a jconfig.h file by hand, this file tells you how.
+ *
+ * DO NOT EDIT THIS FILE --- IT WON'T ACCOMPLISH ANYTHING.
+ * EDIT A COPY NAMED JCONFIG.H.
+ */
+
+
+/*
+ * These symbols indicate the properties of your machine or compiler.
+ * #define the symbol if yes, #undef it if no.
+ */
+
+/* Does your compiler support function prototypes?
+ * (If not, you also need to use ansi2knr, see install.doc)
+ */
+#define HAVE_PROTOTYPES
+
+/* Does your compiler support the declaration "unsigned char" ?
+ * How about "unsigned short" ?
+ */
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+
+/* Define "void" as "char" if your compiler doesn't know about type void.
+ * NOTE: be sure to define void such that "void *" represents the most general
+ * pointer type, e.g., that returned by malloc().
+ */
+/* #define void char */
+
+/* Define "const" as empty if your compiler doesn't know the "const" keyword.
+ */
+/* #define const */
+
+/* Define this if an ordinary "char" type is unsigned.
+ * If you're not sure, leaving it undefined will work at some cost in speed.
+ * If you defined HAVE_UNSIGNED_CHAR then the speed difference is minimal.
+ */
+#undef CHAR_IS_UNSIGNED
+
+/* Define this if your system has an ANSI-conforming <stddef.h> file.
+ */
+#define HAVE_STDDEF_H
+
+/* Define this if your system has an ANSI-conforming <stdlib.h> file.
+ */
+#define HAVE_STDLIB_H
+
+/* Define this if your system does not have an ANSI/SysV <string.h>,
+ * but does have a BSD-style <strings.h>.
+ */
+#undef NEED_BSD_STRINGS
+
+/* Define this if your system does not provide typedef size_t in any of the
+ * ANSI-standard places (stddef.h, stdlib.h, or stdio.h), but places it in
+ * <sys/types.h> instead.
+ */
+#undef NEED_SYS_TYPES_H
+
+/* For 80x86 machines, you need to define NEED_FAR_POINTERS,
+ * unless you are using a large-data memory model or 80386 flat-memory mode.
+ * On less brain-damaged CPUs this symbol must not be defined.
+ * (Defining this symbol causes large data structures to be referenced through
+ * "far" pointers and to be allocated with a special version of malloc.)
+ */
+#undef NEED_FAR_POINTERS
+
+/* Define this if your linker needs global names to be unique in less
+ * than the first 15 characters.
+ */
+#undef NEED_SHORT_EXTERNAL_NAMES
+
+/* Although a real ANSI C compiler can deal perfectly well with pointers to
+ * unspecified structures (see "incomplete types" in the spec), a few pre-ANSI
+ * and pseudo-ANSI compilers get confused. To keep one of these bozos happy,
+ * define INCOMPLETE_TYPES_BROKEN. This is not recommended unless you
+ * actually get "missing structure definition" warnings or errors while
+ * compiling the JPEG code.
+ */
+#undef INCOMPLETE_TYPES_BROKEN
+
+
+/*
+ * The following options affect code selection within the JPEG library,
+ * but they don't need to be visible to applications using the library.
+ * To minimize application namespace pollution, the symbols won't be
+ * defined unless JPEG_INTERNALS has been defined.
+ */
+
+#ifdef JPEG_INTERNALS
+
+/* Define this if your compiler implements ">>" on signed values as a logical
+ * (unsigned) shift; leave it undefined if ">>" is a signed (arithmetic) shift,
+ * which is the normal and rational definition.
+ */
+#undef RIGHT_SHIFT_IS_UNSIGNED
+
+
+#endif /* JPEG_INTERNALS */
+
+
+/*
+ * The remaining options do not affect the JPEG library proper,
+ * but only the sample applications cjpeg/djpeg (see cjpeg.c, djpeg.c).
+ * Other applications can ignore these.
+ */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+/* These defines indicate which image (non-JPEG) file formats are allowed. */
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+/* Define this if you want to name both input and output files on the command
+ * line, rather than using stdout and optionally stdin. You MUST do this if
+ * your system can't cope with binary I/O to stdin/stdout. See comments at
+ * head of cjpeg.c or djpeg.c.
+ */
+#undef TWO_FILE_COMMANDLINE
+
+/* Define this if your system needs explicit cleanup of temporary files.
+ * This is crucial under MS-DOS, where the temporary "files" may be areas
+ * of extended memory; on most other systems it's not as important.
+ */
+#undef NEED_SIGNAL_CATCHER
+
+/* By default, we open image files with fopen(...,"rb") or fopen(...,"wb").
+ * This is necessary on systems that distinguish text files from binary files,
+ * and is harmless on most systems that don't. If you have one of the rare
+ * systems that complains about the "b" spec, define this symbol.
+ */
+#undef DONT_USE_B_MODE
+
+/* Define this if you want percent-done progress reports from cjpeg/djpeg.
+ */
+#undef PROGRESS_REPORT
+
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/jpeg-6c/jconfig.mac b/jpeg-6c/jconfig.mac
new file mode 100644
index 0000000..0de3efe
--- /dev/null
+++ b/jpeg-6c/jconfig.mac
@@ -0,0 +1,43 @@
+/* jconfig.mac --- jconfig.h for CodeWarrior on Apple Macintosh */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+/* #define void char */
+/* #define const */
+#undef CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H
+#define HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#undef NEED_FAR_POINTERS
+#undef NEED_SHORT_EXTERNAL_NAMES
+#undef INCOMPLETE_TYPES_BROKEN
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+
+#define USE_MAC_MEMMGR /* Define this if you use jmemmac.c */
+
+#define ALIGN_TYPE long /* Needed for 680x0 Macs */
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#define USE_CCOMMAND /* Command line reader for Macintosh */
+#define TWO_FILE_COMMANDLINE /* Binary I/O thru stdin/stdout doesn't work */
+
+#undef NEED_SIGNAL_CATCHER
+#undef DONT_USE_B_MODE
+#undef PROGRESS_REPORT /* optional */
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/jpeg-6c/jconfig.manx b/jpeg-6c/jconfig.manx
new file mode 100644
index 0000000..6dd0d00
--- /dev/null
+++ b/jpeg-6c/jconfig.manx
@@ -0,0 +1,43 @@
+/* jconfig.manx --- jconfig.h for Amiga systems using Manx Aztec C ver 5.x. */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+/* #define void char */
+/* #define const */
+#undef CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H
+#define HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#undef NEED_FAR_POINTERS
+#undef NEED_SHORT_EXTERNAL_NAMES
+#undef INCOMPLETE_TYPES_BROKEN
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+
+#define TEMP_DIRECTORY "JPEGTMP:" /* recommended setting for Amiga */
+
+#define SHORTxSHORT_32 /* produces better DCT code with Aztec C */
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#define TWO_FILE_COMMANDLINE
+#define NEED_SIGNAL_CATCHER
+#undef DONT_USE_B_MODE
+#undef PROGRESS_REPORT /* optional */
+
+#define signal_catcher _abort /* hack for Aztec C naming requirements */
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/jpeg-6c/jconfig.mc6 b/jpeg-6c/jconfig.mc6
new file mode 100644
index 0000000..c55082d
--- /dev/null
+++ b/jpeg-6c/jconfig.mc6
@@ -0,0 +1,52 @@
+/* jconfig.mc6 --- jconfig.h for Microsoft C on MS-DOS, version 6.00A & up. */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+/* #define void char */
+/* #define const */
+#undef CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H
+#define HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#define NEED_FAR_POINTERS /* for small or medium memory model */
+#undef NEED_SHORT_EXTERNAL_NAMES
+#undef INCOMPLETE_TYPES_BROKEN
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+
+#define USE_MSDOS_MEMMGR /* Define this if you use jmemdos.c */
+
+#define MAX_ALLOC_CHUNK 65520L /* Maximum request to malloc() */
+
+#define USE_FMEM /* Microsoft has _fmemcpy() and _fmemset() */
+
+#define NEED_FHEAPMIN /* far heap management routines are broken */
+
+#define SHORTxLCONST_32 /* enable compiler-specific DCT optimization */
+/* Note: the above define is known to improve the code with Microsoft C 6.00A.
+ * I do not know whether it is good for later compiler versions.
+ * Please report any info on this point to jpeg-info at uunet.uu.net.
+ */
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#define TWO_FILE_COMMANDLINE
+#define USE_SETMODE /* Microsoft has setmode() */
+#define NEED_SIGNAL_CATCHER /* Define this if you use jmemdos.c */
+#undef DONT_USE_B_MODE
+#undef PROGRESS_REPORT /* optional */
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/jpeg-6c/jconfig.osx.h b/jpeg-6c/jconfig.osx.h
new file mode 100644
index 0000000..9594ec5
--- /dev/null
+++ b/jpeg-6c/jconfig.osx.h
@@ -0,0 +1,45 @@
+/* jconfig.h. Generated automatically by configure. */
+/* jconfig.cfg --- source file edited by configure script */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+#undef void
+#undef const
+#undef CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H
+#define HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#undef NEED_FAR_POINTERS
+#undef NEED_SHORT_EXTERNAL_NAMES
+/* Define this if you get warnings about undefined structures. */
+#undef INCOMPLETE_TYPES_BROKEN
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+#define INLINE __inline__
+/* These are for configuring the JPEG memory manager. */
+#undef DEFAULT_MAX_MEM
+#undef NO_MKTEMP
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#undef TWO_FILE_COMMANDLINE
+#undef NEED_SIGNAL_CATCHER
+#undef DONT_USE_B_MODE
+
+/* Define this if you want percent-done progress reports from cjpeg/djpeg. */
+#undef PROGRESS_REPORT
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/jpeg-6c/jconfig.sas b/jpeg-6c/jconfig.sas
new file mode 100644
index 0000000..efdac22
--- /dev/null
+++ b/jpeg-6c/jconfig.sas
@@ -0,0 +1,43 @@
+/* jconfig.sas --- jconfig.h for Amiga systems using SAS C 6.0 and up. */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+/* #define void char */
+/* #define const */
+#undef CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H
+#define HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#undef NEED_FAR_POINTERS
+#undef NEED_SHORT_EXTERNAL_NAMES
+#undef INCOMPLETE_TYPES_BROKEN
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+
+#define TEMP_DIRECTORY "JPEGTMP:" /* recommended setting for Amiga */
+
+#define NO_MKTEMP /* SAS C doesn't have mktemp() */
+
+#define SHORTxSHORT_32 /* produces better DCT code with SAS C */
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#define TWO_FILE_COMMANDLINE
+#define NEED_SIGNAL_CATCHER
+#undef DONT_USE_B_MODE
+#undef PROGRESS_REPORT /* optional */
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/jpeg-6c/jconfig.st b/jpeg-6c/jconfig.st
new file mode 100644
index 0000000..4421b7a
--- /dev/null
+++ b/jpeg-6c/jconfig.st
@@ -0,0 +1,42 @@
+/* jconfig.st --- jconfig.h for Atari ST/STE/TT using Pure C or Turbo C. */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+/* #define void char */
+/* #define const */
+#undef CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H
+#define HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#undef NEED_FAR_POINTERS
+#undef NEED_SHORT_EXTERNAL_NAMES
+#define INCOMPLETE_TYPES_BROKEN /* suppress undefined-structure warnings */
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+
+#define ALIGN_TYPE long /* apparently double is a weird size? */
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#define TWO_FILE_COMMANDLINE /* optional -- undef if you like Unix style */
+/* Note: if you undef TWO_FILE_COMMANDLINE, you may need to define
+ * USE_SETMODE. Some Atari compilers require it, some do not.
+ */
+#define NEED_SIGNAL_CATCHER /* needed if you use jmemname.c */
+#undef DONT_USE_B_MODE
+#undef PROGRESS_REPORT /* optional */
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/jpeg-6c/jconfig.vc b/jpeg-6c/jconfig.vc
new file mode 100644
index 0000000..7e291c7
--- /dev/null
+++ b/jpeg-6c/jconfig.vc
@@ -0,0 +1,45 @@
+/* jconfig.vc --- jconfig.h for Microsoft Visual C++ on Windows 95 or NT. */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+/* #define void char */
+/* #define const */
+#undef CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H
+#define HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
+#undef NEED_SHORT_EXTERNAL_NAMES
+#undef INCOMPLETE_TYPES_BROKEN
+
+/* Define "boolean" as unsigned char, not int, per Windows custom */
+#ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
+typedef unsigned char boolean;
+#endif
+#define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
+
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#define TWO_FILE_COMMANDLINE /* optional */
+#define USE_SETMODE /* Microsoft has setmode() */
+#undef NEED_SIGNAL_CATCHER
+#undef DONT_USE_B_MODE
+#undef PROGRESS_REPORT /* optional */
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/jpeg-6c/jconfig.vms b/jpeg-6c/jconfig.vms
new file mode 100644
index 0000000..55a6ffb
--- /dev/null
+++ b/jpeg-6c/jconfig.vms
@@ -0,0 +1,37 @@
+/* jconfig.vms --- jconfig.h for use on Digital VMS. */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+/* #define void char */
+/* #define const */
+#undef CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H
+#define HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#undef NEED_FAR_POINTERS
+#undef NEED_SHORT_EXTERNAL_NAMES
+#undef INCOMPLETE_TYPES_BROKEN
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#define TWO_FILE_COMMANDLINE /* Needed on VMS */
+#undef NEED_SIGNAL_CATCHER
+#undef DONT_USE_B_MODE
+#undef PROGRESS_REPORT /* optional */
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/jpeg-6c/jconfig.wat b/jpeg-6c/jconfig.wat
new file mode 100644
index 0000000..6cc545b
--- /dev/null
+++ b/jpeg-6c/jconfig.wat
@@ -0,0 +1,38 @@
+/* jconfig.wat --- jconfig.h for Watcom C/C++ on MS-DOS or OS/2. */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES
+#define HAVE_UNSIGNED_CHAR
+#define HAVE_UNSIGNED_SHORT
+/* #define void char */
+/* #define const */
+#define CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H
+#define HAVE_STDLIB_H
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#undef NEED_FAR_POINTERS /* Watcom uses flat 32-bit addressing */
+#undef NEED_SHORT_EXTERNAL_NAMES
+#undef INCOMPLETE_TYPES_BROKEN
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED /* BMP image file format */
+#define GIF_SUPPORTED /* GIF image file format */
+#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED /* Utah RLE image file format */
+#define TARGA_SUPPORTED /* Targa image file format */
+
+#undef TWO_FILE_COMMANDLINE /* optional */
+#define USE_SETMODE /* Needed to make one-file style work in Watcom */
+#undef NEED_SIGNAL_CATCHER /* Define this if you use jmemname.c */
+#undef DONT_USE_B_MODE
+#undef PROGRESS_REPORT /* optional */
+
+#endif /* JPEG_CJPEG_DJPEG */
diff --git a/jpeg-6c/jcparam.c b/jpeg-6c/jcparam.c
new file mode 100644
index 0000000..427f44a
--- /dev/null
+++ b/jpeg-6c/jcparam.c
@@ -0,0 +1,716 @@
+/*
+ * jcparam.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains optional default-setting code for the JPEG compressor.
+ * Applications do not have to use this file, but those that don't use it
+ * must know a lot more about the innards of the JPEG code.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Quantization table setup routines
+ */
+
+GLOBAL(void)
+jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
+ const unsigned int *basic_table,
+ int scale_factor, boolean force_baseline)
+/* Define a quantization table equal to the basic_table times
+ * a scale factor (given as a percentage).
+ * If force_baseline is TRUE, the computed quantization table entries
+ * are limited to 1..255 for JPEG baseline compatibility.
+ */
+{
+ JQUANT_TBL ** qtblptr;
+ int i;
+ long temp;
+
+ /* Safety check to ensure start_compress not called yet. */
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
+ ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
+
+ qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
+
+ if (*qtblptr == NULL)
+ *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
+ /* limit the values to the valid range */
+ if (temp <= 0L) temp = 1L;
+ if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
+ if (force_baseline && temp > 255L)
+ temp = 255L; /* limit to baseline range if requested */
+ (*qtblptr)->quantval[i] = (UINT16) temp;
+ }
+
+ /* Initialize sent_table FALSE so table will be written to JPEG file. */
+ (*qtblptr)->sent_table = FALSE;
+}
+
+
+GLOBAL(void)
+jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
+ boolean force_baseline)
+/* Set or change the 'quality' (quantization) setting, using default tables
+ * and a straight percentage-scaling quality scale. In most cases it's better
+ * to use jpeg_set_quality (below); this entry point is provided for
+ * applications that insist on a linear percentage scaling.
+ */
+{
+ /* These are the sample quantization tables given in JPEG spec section K.1.
+ * The spec says that the values given produce "good" quality, and
+ * when divided by 2, "very good" quality.
+ */
+ static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
+ 16, 11, 10, 16, 24, 40, 51, 61,
+ 12, 12, 14, 19, 26, 58, 60, 55,
+ 14, 13, 16, 24, 40, 57, 69, 56,
+ 14, 17, 22, 29, 51, 87, 80, 62,
+ 18, 22, 37, 56, 68, 109, 103, 77,
+ 24, 35, 55, 64, 81, 104, 113, 92,
+ 49, 64, 78, 87, 103, 121, 120, 101,
+ 72, 92, 95, 98, 112, 100, 103, 99
+ };
+ static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
+ 17, 18, 24, 47, 99, 99, 99, 99,
+ 18, 21, 26, 66, 99, 99, 99, 99,
+ 24, 26, 56, 99, 99, 99, 99, 99,
+ 47, 66, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99
+ };
+
+ /* Set up two quantization tables using the specified scaling */
+ jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
+ scale_factor, force_baseline);
+ jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
+ scale_factor, force_baseline);
+}
+
+
+GLOBAL(int)
+jpeg_quality_scaling (int quality)
+/* Convert a user-specified quality rating to a percentage scaling factor
+ * for an underlying quantization table, using our recommended scaling curve.
+ * The input 'quality' factor should be 0 (terrible) to 100 (very good).
+ */
+{
+ /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
+ if (quality <= 0) quality = 1;
+ if (quality > 100) quality = 100;
+
+ /* The basic table is used as-is (scaling 100) for a quality of 50.
+ * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
+ * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
+ * to make all the table entries 1 (hence, minimum quantization loss).
+ * Qualities 1..50 are converted to scaling percentage 5000/Q.
+ */
+ if (quality < 50)
+ quality = 5000 / quality;
+ else
+ quality = 200 - quality*2;
+
+ return quality;
+}
+
+
+GLOBAL(void)
+jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
+/* Set or change the 'quality' (quantization) setting, using default tables.
+ * This is the standard quality-adjusting entry point for typical user
+ * interfaces; only those who want detailed control over quantization tables
+ * would use the preceding three routines directly.
+ */
+{
+ /* Convert user 0-100 rating to percentage scaling */
+ quality = jpeg_quality_scaling(quality);
+
+ /* Set up standard quality tables */
+ jpeg_set_linear_quality(cinfo, quality, force_baseline);
+}
+
+
+/*
+ * Huffman table setup routines
+ */
+
+LOCAL(void)
+add_huff_table (j_compress_ptr cinfo,
+ JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
+/* Define a Huffman table */
+{
+ int nsymbols, len;
+
+ if (*htblptr == NULL)
+ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+
+ /* Copy the number-of-symbols-of-each-code-length counts */
+ MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
+
+ /* Validate the counts. We do this here mainly so we can copy the right
+ * number of symbols from the val[] array, without risking marching off
+ * the end of memory. jchuff.c will do a more thorough test later.
+ */
+ nsymbols = 0;
+ for (len = 1; len <= 16; len++)
+ nsymbols += bits[len];
+ if (nsymbols < 1 || nsymbols > 256)
+ ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
+
+ MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
+
+ /* Initialize sent_table FALSE so table will be written to JPEG file. */
+ (*htblptr)->sent_table = FALSE;
+}
+
+
+LOCAL(void)
+std_huff_tables (j_compress_ptr cinfo)
+/* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
+/* IMPORTANT: these are only valid for 8-bit data precision! */
+{
+ static const UINT8 bits_dc_luminance[17] =
+ { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
+ static const UINT8 val_dc_luminance[] =
+ { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
+
+ static const UINT8 bits_dc_chrominance[17] =
+ { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
+ static const UINT8 val_dc_chrominance[] =
+ { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
+
+ static const UINT8 bits_ac_luminance[17] =
+ { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
+ static const UINT8 val_ac_luminance[] =
+ { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
+ 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
+ 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
+ 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
+ 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
+ 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
+ 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
+ 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
+ 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
+ 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
+ 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
+ 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
+ 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
+ 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
+ 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
+ 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
+ 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
+ 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
+ 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
+ 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
+ 0xf9, 0xfa };
+
+ static const UINT8 bits_ac_chrominance[17] =
+ { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
+ static const UINT8 val_ac_chrominance[] =
+ { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
+ 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
+ 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
+ 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
+ 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
+ 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
+ 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
+ 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
+ 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
+ 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
+ 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
+ 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
+ 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
+ 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
+ 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
+ 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
+ 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
+ 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
+ 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
+ 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
+ 0xf9, 0xfa };
+
+ add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
+ bits_dc_luminance, val_dc_luminance);
+ add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
+ bits_ac_luminance, val_ac_luminance);
+ add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
+ bits_dc_chrominance, val_dc_chrominance);
+ add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
+ bits_ac_chrominance, val_ac_chrominance);
+}
+
+
+/*
+ * Default parameter setup for compression.
+ *
+ * Applications that don't choose to use this routine must do their
+ * own setup of all these parameters. Alternately, you can call this
+ * to establish defaults and then alter parameters selectively. This
+ * is the recommended approach since, if we add any new parameters,
+ * your code will still work (they'll be set to reasonable defaults).
+ */
+
+GLOBAL(void)
+jpeg_set_defaults (j_compress_ptr cinfo)
+{
+ int i;
+
+ /* Safety check to ensure start_compress not called yet. */
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ /* Allocate comp_info array large enough for maximum component count.
+ * Array is made permanent in case application wants to compress
+ * multiple images at same param settings.
+ */
+ if (cinfo->comp_info == NULL)
+ cinfo->comp_info = (jpeg_component_info *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ MAX_COMPONENTS * SIZEOF(jpeg_component_info));
+
+ /* Initialize everything not dependent on the color space */
+
+ cinfo->lossless = FALSE;
+ cinfo->lossless_scaling = TRUE;
+ cinfo->data_precision = 8;
+ cinfo->maxjsample = 255;
+ cinfo->centerjsample = 128;
+#ifdef HAVE_GETJSAMPLE_MASK
+ cinfo->maskjsample = 0xFF;
+#endif
+ /* Set up two quantization tables using default quality of 75 */
+ jpeg_set_quality(cinfo, 75, TRUE);
+ /* Set up two Huffman tables */
+ std_huff_tables(cinfo);
+
+ /* Initialize default arithmetic coding conditioning */
+ for (i = 0; i < NUM_ARITH_TBLS; i++) {
+ cinfo->arith_dc_L[i] = 0;
+ cinfo->arith_dc_U[i] = 1;
+ cinfo->arith_ac_K[i] = 5;
+ }
+
+ /* Default is no multiple-scan output */
+ cinfo->scan_info = NULL;
+ cinfo->num_scans = 0;
+
+ /* Expect normal source image, not raw downsampled data */
+ cinfo->raw_data_in = FALSE;
+ cinfo->raw_data_buffer = NULL;
+
+ /* Use Huffman coding, not arithmetic coding, by default */
+ cinfo->arith_code = FALSE;
+
+ /* By default, don't do extra passes to optimize entropy coding */
+ cinfo->optimize_coding = FALSE;
+
+ /* By default, use the simpler non-cosited sampling alignment */
+ cinfo->CCIR601_sampling = FALSE;
+
+ /* No input smoothing */
+ cinfo->smoothing_factor = 0;
+
+ /* DCT algorithm preference */
+ cinfo->dct_method = JDCT_DEFAULT;
+
+ /* No restart markers */
+ cinfo->restart_interval = 0;
+ cinfo->restart_in_rows = 0;
+
+ /* Fill in default JFIF marker parameters. Note that whether the marker
+ * will actually be written is determined by jpeg_set_colorspace.
+ *
+ * By default, the library emits JFIF version code 1.01.
+ * An application that wants to emit JFIF 1.02 extension markers should set
+ * JFIF_minor_version to 2. We could probably get away with just defaulting
+ * to 1.02, but there may still be some decoders in use that will complain
+ * about that; saying 1.01 should minimize compatibility problems.
+ */
+ cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
+ cinfo->JFIF_minor_version = 1;
+ cinfo->density_unit = 0; /* Pixel size is unknown by default */
+ cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
+ cinfo->Y_density = 1;
+
+ /* Choose JPEG colorspace based on input space, set defaults accordingly */
+
+ jpeg_default_colorspace(cinfo);
+}
+
+
+/*
+ * Select an appropriate JPEG colorspace for in_color_space.
+ */
+
+GLOBAL(void)
+jpeg_default_colorspace (j_compress_ptr cinfo)
+{
+ if (cinfo->lossless)
+ jpeg_set_colorspace(cinfo, cinfo->in_color_space);
+ else { /* lossy */
+ switch (cinfo->in_color_space) {
+ case JCS_GRAYSCALE:
+ jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
+ break;
+ case JCS_RGB:
+ jpeg_set_colorspace(cinfo, JCS_YCbCr);
+ break;
+ case JCS_YCbCr:
+ jpeg_set_colorspace(cinfo, JCS_YCbCr);
+ break;
+ case JCS_CMYK:
+ jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
+ break;
+ case JCS_YCCK:
+ jpeg_set_colorspace(cinfo, JCS_YCCK);
+ break;
+ case JCS_UNKNOWN:
+ jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
+ break;
+ default:
+ ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+ }
+ }
+}
+
+
+/*
+ * Set the JPEG colorspace, and choose colorspace-dependent default values.
+ */
+
+GLOBAL(void)
+jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
+{
+ jpeg_component_info * compptr;
+ int ci;
+
+#define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
+ (compptr = &cinfo->comp_info[index], \
+ compptr->component_id = (id), \
+ compptr->h_samp_factor = (hsamp), \
+ compptr->v_samp_factor = (vsamp), \
+ compptr->quant_tbl_no = (quant), \
+ compptr->dc_tbl_no = (dctbl), \
+ compptr->ac_tbl_no = (actbl) )
+
+ /* Safety check to ensure start_compress not called yet. */
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
+ * tables 1 for chrominance components.
+ */
+
+ cinfo->jpeg_color_space = colorspace;
+
+ cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
+ cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
+
+ /* Fix the bit width stuff here, by now cinfo->data_precision should be set */
+ if (2 > cinfo->data_precision || cinfo->data_precision > 16)
+ ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
+ if (!cinfo->lossless) {
+ if (cinfo->data_precision <=8) {
+ if (cinfo->data_precision !=8) {
+ WARNMS2(cinfo, JWRN_JPEG_PRECISION_CHANGED, cinfo->data_precision, 8);
+ cinfo->data_precision = 8;
+ }
+ } else if (cinfo->data_precision != 12) {
+ WARNMS2(cinfo, JWRN_JPEG_PRECISION_CHANGED, cinfo->data_precision, 12);
+ cinfo->data_precision = 12;
+ }
+ }
+ cinfo->maxjsample = (1 << cinfo->data_precision) - 1;
+ cinfo->centerjsample = (cinfo->maxjsample + 1)/2;
+#ifdef HAVE_GETJSAMPLE_MASK
+ cinfo->maskjsample = cinfo->maxjsample;
+#endif
+
+ /* The standard Huffman tables are only valid for 8-bit data precision.
+ * If the precision is higher, force optimization on so that usable
+ * tables will be computed. This test can be removed if default tables
+ * are supplied that are valid for the desired precision.
+ */
+ if (cinfo->data_precision != 8)
+ cinfo->optimize_coding = TRUE;
+
+ switch (colorspace) {
+ case JCS_GRAYSCALE:
+ cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
+ cinfo->num_components = 1;
+ /* JFIF specifies component ID 1 */
+ SET_COMP(0, 1, 1,1, 0, 0,0);
+ break;
+ case JCS_RGB:
+ cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
+ cinfo->num_components = 3;
+ SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
+ SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
+ SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
+ break;
+ case JCS_YCbCr:
+ cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
+ cinfo->num_components = 3;
+ /* JFIF specifies component IDs 1,2,3 */
+ if (cinfo->lossless) {
+ SET_COMP(0, 1, 1,1, 0, 0,0);
+ SET_COMP(1, 2, 1,1, 1, 1,1);
+ SET_COMP(2, 3, 1,1, 1, 1,1);
+ } else { /* lossy */
+ /* We default to 2x2 subsamples of chrominance */
+ SET_COMP(0, 1, 2,2, 0, 0,0);
+ SET_COMP(1, 2, 1,1, 1, 1,1);
+ SET_COMP(2, 3, 1,1, 1, 1,1);
+ }
+ break;
+ case JCS_CMYK:
+ cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
+ cinfo->num_components = 4;
+ SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
+ SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
+ SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
+ SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
+ break;
+ case JCS_YCCK:
+ cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
+ cinfo->num_components = 4;
+ if (cinfo->lossless) {
+ SET_COMP(0, 1, 1,1, 0, 0,0);
+ SET_COMP(1, 2, 1,1, 1, 1,1);
+ SET_COMP(2, 3, 1,1, 1, 1,1);
+ SET_COMP(3, 4, 1,1, 0, 0,0);
+ } else { /* lossy */
+ SET_COMP(0, 1, 2,2, 0, 0,0);
+ SET_COMP(1, 2, 1,1, 1, 1,1);
+ SET_COMP(2, 3, 1,1, 1, 1,1);
+ SET_COMP(3, 4, 2,2, 0, 0,0);
+ }
+ break;
+ case JCS_UNKNOWN:
+ cinfo->num_components = cinfo->input_components;
+ if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
+ MAX_COMPONENTS);
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ SET_COMP(ci, ci, 1,1, 0, 0,0);
+ }
+ break;
+ default:
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ }
+}
+
+
+#ifdef C_PROGRESSIVE_SUPPORTED
+
+LOCAL(jpeg_scan_info *)
+fill_scans (jpeg_scan_info * scanptr, int ncomps,
+ int Ss, int Se, int Ah, int Al)
+/* Support routine: generate one scan for each component */
+{
+ int ci;
+
+ for (ci = 0; ci < ncomps; ci++) {
+ scanptr->comps_in_scan = 1;
+ scanptr->component_index[0] = ci;
+ scanptr->Ss = Ss;
+ scanptr->Se = Se;
+ scanptr->Ah = Ah;
+ scanptr->Al = Al;
+ scanptr++;
+ }
+ return scanptr;
+}
+
+
+LOCAL(jpeg_scan_info *)
+fill_a_scan (jpeg_scan_info * scanptr, int ci,
+ int Ss, int Se, int Ah, int Al)
+/* Support routine: generate one scan for specified component */
+{
+ scanptr->comps_in_scan = 1;
+ scanptr->component_index[0] = ci;
+ scanptr->Ss = Ss;
+ scanptr->Se = Se;
+ scanptr->Ah = Ah;
+ scanptr->Al = Al;
+ scanptr++;
+ return scanptr;
+}
+
+LOCAL(jpeg_scan_info *)
+fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
+/* Support routine: generate interleaved DC scan if possible, else N scans */
+{
+ int ci;
+
+ if (ncomps <= MAX_COMPS_IN_SCAN) {
+ /* Single interleaved DC scan */
+ scanptr->comps_in_scan = ncomps;
+ for (ci = 0; ci < ncomps; ci++)
+ scanptr->component_index[ci] = ci;
+ scanptr->Ss = scanptr->Se = 0;
+ scanptr->Ah = Ah;
+ scanptr->Al = Al;
+ scanptr++;
+ } else {
+ /* Noninterleaved DC scan for each component */
+ scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
+ }
+ return scanptr;
+}
+
+
+/*
+ * Create a recommended progressive-JPEG script.
+ * cinfo->num_components and cinfo->jpeg_color_space must be correct.
+ */
+
+GLOBAL(void)
+jpeg_simple_progression (j_compress_ptr cinfo)
+{
+ int ncomps = cinfo->num_components;
+ int nscans;
+ jpeg_scan_info * scanptr;
+
+ /* Safety check to ensure start_compress not called yet. */
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ /* Figure space needed for script. Calculation must match code below! */
+ if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
+ /* Custom script for YCbCr color images. */
+ nscans = 10;
+ } else {
+ /* All-purpose script for other color spaces. */
+ if (ncomps > MAX_COMPS_IN_SCAN)
+ nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
+ else
+ nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
+ }
+
+ /* Allocate space for script.
+ * We need to put it in the permanent pool in case the application performs
+ * multiple compressions without changing the settings. To avoid a memory
+ * leak if jpeg_simple_progression is called repeatedly for the same JPEG
+ * object, we try to re-use previously allocated space, and we allocate
+ * enough space to handle YCbCr even if initially asked for grayscale.
+ */
+ if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
+ cinfo->script_space_size = MAX(nscans, 10);
+ cinfo->script_space = (jpeg_scan_info *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ cinfo->script_space_size * SIZEOF(jpeg_scan_info));
+ }
+ scanptr = cinfo->script_space;
+ cinfo->scan_info = scanptr;
+ cinfo->num_scans = nscans;
+
+ if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
+ /* Custom script for YCbCr color images. */
+ /* Initial DC scan */
+ scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
+ /* Initial AC scan: get some luma data out in a hurry */
+ scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
+ /* Chroma data is too small to be worth expending many scans on */
+ scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
+ scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
+ /* Complete spectral selection for luma AC */
+ scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
+ /* Refine next bit of luma AC */
+ scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
+ /* Finish DC successive approximation */
+ scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
+ /* Finish AC successive approximation */
+ scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
+ scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
+ /* Luma bottom bit comes last since it's usually largest scan */
+ scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
+ } else {
+ /* All-purpose script for other color spaces. */
+ /* Successive approximation first pass */
+ scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
+ scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
+ scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
+ /* Successive approximation second pass */
+ scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
+ /* Successive approximation final pass */
+ scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
+ scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
+ }
+}
+
+#endif /* C_PROGRESSIVE_SUPPORTED */
+
+
+#ifdef C_LOSSLESS_SUPPORTED
+
+/*
+ * Create a single-entry lossless-JPEG script containing all components.
+ * cinfo->num_components must be correct.
+ */
+
+GLOBAL(void)
+jpeg_simple_lossless (j_compress_ptr cinfo, int predictor, int point_transform)
+{
+ int ncomps = cinfo->num_components;
+ int nscans = 1;
+ int ci;
+ jpeg_scan_info * scanptr;
+
+ /* Safety check to ensure start_compress not called yet. */
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ cinfo->lossless = TRUE;
+
+ /* Set jpeg_color_space. */
+ jpeg_default_colorspace(cinfo);
+
+ /* Check to ensure that all components will fit in one scan. */
+ if (cinfo->num_components > MAX_COMPS_IN_SCAN)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
+ MAX_COMPS_IN_SCAN);
+
+ /* Allocate space for script.
+ * We need to put it in the permanent pool in case the application performs
+ * multiple compressions without changing the settings. To avoid a memory
+ * leak if jpeg_simple_lossless is called repeatedly for the same JPEG
+ * object, we try to re-use previously allocated space.
+ */
+ if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
+ cinfo->script_space_size = nscans;
+ cinfo->script_space = (jpeg_scan_info *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ cinfo->script_space_size * SIZEOF(jpeg_scan_info));
+ }
+ scanptr = cinfo->script_space;
+ cinfo->scan_info = scanptr;
+ cinfo->num_scans = nscans;
+
+ /* Fill the script. */
+ scanptr->comps_in_scan = ncomps;
+ for (ci = 0; ci < ncomps; ci++)
+ scanptr->component_index[ci] = ci;
+ scanptr->Ss = predictor;
+ scanptr->Se = 0;
+ scanptr->Ah = 0;
+ scanptr->Al = point_transform;
+}
+
+#endif /* C_LOSSLESS_SUPPORTED */
diff --git a/jpeg-6c/jcphuff.c b/jpeg-6c/jcphuff.c
new file mode 100644
index 0000000..c27d0b3
--- /dev/null
+++ b/jpeg-6c/jcphuff.c
@@ -0,0 +1,851 @@
+/*
+ * jcphuff.c
+ *
+ * Copyright (C) 1995-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains Huffman entropy encoding routines for progressive JPEG.
+ *
+ * We do not support output suspension in this module, since the library
+ * currently does not allow multiple-scan files to be written with output
+ * suspension.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h" /* Private declarations for lossy codec */
+#include "jchuff.h" /* Declarations shared with jc*huff.c */
+
+#ifdef C_PROGRESSIVE_SUPPORTED
+
+/* Expanded entropy encoder object for progressive Huffman encoding. */
+
+typedef struct {
+ /* Mode flag: TRUE for optimization, FALSE for actual data output */
+ boolean gather_statistics;
+
+ /* Bit-level coding status.
+ * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
+ */
+ JOCTET * next_output_byte; /* => next byte to write in buffer */
+ size_t free_in_buffer; /* # of byte spaces remaining in buffer */
+ INT32 put_buffer; /* current bit-accumulation buffer */
+ int put_bits; /* # of bits now in it */
+ j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
+
+ /* Coding status for DC components */
+ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
+
+ /* Coding status for AC components */
+ int ac_tbl_no; /* the table number of the single component */
+ unsigned int EOBRUN; /* run length of EOBs */
+ unsigned int BE; /* # of buffered correction bits before MCU */
+ char * bit_buffer; /* buffer for correction bits (1 per char) */
+ /* packing correction bits tightly would save some space but cost time... */
+
+ unsigned int restarts_to_go; /* MCUs left in this restart interval */
+ int next_restart_num; /* next restart number to write (0-7) */
+
+ /* Pointers to derived tables (these workspaces have image lifespan).
+ * Since any one scan codes only DC or only AC, we only need one set
+ * of tables, not one for DC and one for AC.
+ */
+ c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
+
+ /* Statistics tables for optimization; again, one set is enough */
+ long * count_ptrs[NUM_HUFF_TBLS];
+} phuff_entropy_encoder;
+
+typedef phuff_entropy_encoder * phuff_entropy_ptr;
+
+/* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
+ * buffer can hold. Larger sizes may slightly improve compression, but
+ * 1000 is already well into the realm of overkill.
+ * The minimum safe size is 64 bits.
+ */
+
+#define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
+
+/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
+ * We assume that int right shift is unsigned if INT32 right shift is,
+ * which should be safe.
+ */
+
+#ifdef RIGHT_SHIFT_IS_UNSIGNED
+#define ISHIFT_TEMPS int ishift_temp;
+#define IRIGHT_SHIFT(x,shft) \
+ ((ishift_temp = (x)) < 0 ? \
+ (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
+ (ishift_temp >> (shft)))
+#else
+#define ISHIFT_TEMPS
+#define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
+#endif
+
+/* Forward declarations */
+METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
+METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
+
+
+/*
+ * Initialize for a Huffman-compressed scan using progressive JPEG.
+ */
+
+METHODDEF(void)
+start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+ boolean is_DC_band;
+ int ci, tbl;
+ jpeg_component_info * compptr;
+
+ entropy->cinfo = cinfo;
+ entropy->gather_statistics = gather_statistics;
+
+ is_DC_band = (cinfo->Ss == 0);
+
+ /* We assume jcmaster.c already validated the scan parameters. */
+
+ /* Select execution routines */
+ if (cinfo->Ah == 0) {
+ if (is_DC_band)
+ lossyc->entropy_encode_mcu = encode_mcu_DC_first;
+ else
+ lossyc->entropy_encode_mcu = encode_mcu_AC_first;
+ } else {
+ if (is_DC_band)
+ lossyc->entropy_encode_mcu = encode_mcu_DC_refine;
+ else {
+ lossyc->entropy_encode_mcu = encode_mcu_AC_refine;
+ /* AC refinement needs a correction bit buffer */
+ if (entropy->bit_buffer == NULL)
+ entropy->bit_buffer = (char *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ MAX_CORR_BITS * SIZEOF(char));
+ }
+ }
+ if (gather_statistics)
+ lossyc->pub.entropy_finish_pass = finish_pass_gather_phuff;
+ else
+ lossyc->pub.entropy_finish_pass = finish_pass_phuff;
+
+ /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
+ * for AC coefficients.
+ */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* Initialize DC predictions to 0 */
+ entropy->last_dc_val[ci] = 0;
+ /* Get table index */
+ if (is_DC_band) {
+ if (cinfo->Ah != 0) /* DC refinement needs no table */
+ continue;
+ tbl = compptr->dc_tbl_no;
+ } else {
+ entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
+ }
+ if (gather_statistics) {
+ /* Check for invalid table index */
+ /* (make_c_derived_tbl does this in the other path) */
+ if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
+ /* Allocate and zero the statistics tables */
+ /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
+ if (entropy->count_ptrs[tbl] == NULL)
+ entropy->count_ptrs[tbl] = (long *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ 257 * SIZEOF(long));
+ MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
+ } else {
+ /* Compute derived values for Huffman table */
+ /* We may do this more than once for a table, but it's not expensive */
+ jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
+ & entropy->derived_tbls[tbl]);
+ }
+ }
+
+ /* Initialize AC stuff */
+ entropy->EOBRUN = 0;
+ entropy->BE = 0;
+
+ /* Initialize bit buffer to empty */
+ entropy->put_buffer = 0;
+ entropy->put_bits = 0;
+
+ /* Initialize restart stuff */
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num = 0;
+}
+
+
+/* Outputting bytes to the file.
+ * NB: these must be called only when actually outputting,
+ * that is, entropy->gather_statistics == FALSE.
+ */
+
+/* Emit a byte */
+#define emit_byte(entropy,val) \
+ { *(entropy)->next_output_byte++ = (JOCTET) (val); \
+ if (--(entropy)->free_in_buffer == 0) \
+ dump_buffer(entropy); }
+
+
+LOCAL(void)
+dump_buffer (phuff_entropy_ptr entropy)
+/* Empty the output buffer; we do not support suspension in this module. */
+{
+ struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
+
+ if (! (*dest->empty_output_buffer) (entropy->cinfo))
+ ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
+ /* After a successful buffer dump, must reset buffer pointers */
+ entropy->next_output_byte = dest->next_output_byte;
+ entropy->free_in_buffer = dest->free_in_buffer;
+}
+
+
+/* Outputting bits to the file */
+
+/* Only the right 24 bits of put_buffer are used; the valid bits are
+ * left-justified in this part. At most 16 bits can be passed to emit_bits
+ * in one call, and we never retain more than 7 bits in put_buffer
+ * between calls, so 24 bits are sufficient.
+ */
+
+INLINE
+LOCAL(void)
+emit_bits (phuff_entropy_ptr entropy, unsigned int code, int size)
+/* Emit some bits, unless we are in gather mode */
+{
+ /* This routine is heavily used, so it's worth coding tightly. */
+ register INT32 put_buffer = (INT32) code;
+ register int put_bits = entropy->put_bits;
+
+ /* if size is 0, caller used an invalid Huffman table entry */
+ if (size == 0)
+ ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
+
+ if (entropy->gather_statistics)
+ return; /* do nothing if we're only getting stats */
+
+ put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
+
+ put_bits += size; /* new number of bits in buffer */
+
+ put_buffer <<= 24 - put_bits; /* align incoming bits */
+
+ put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
+
+ while (put_bits >= 8) {
+ int c = (int) ((put_buffer >> 16) & 0xFF);
+
+ emit_byte(entropy, c);
+ if (c == 0xFF) { /* need to stuff a zero byte? */
+ emit_byte(entropy, 0);
+ }
+ put_buffer <<= 8;
+ put_bits -= 8;
+ }
+
+ entropy->put_buffer = put_buffer; /* update variables */
+ entropy->put_bits = put_bits;
+}
+
+
+LOCAL(void)
+flush_bits (phuff_entropy_ptr entropy)
+{
+ emit_bits(entropy, 0x7F, 7); /* fill any partial byte with ones */
+ entropy->put_buffer = 0; /* and reset bit-buffer to empty */
+ entropy->put_bits = 0;
+}
+
+
+/*
+ * Emit (or just count) a Huffman symbol.
+ */
+
+INLINE
+LOCAL(void)
+emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
+{
+ if (entropy->gather_statistics)
+ entropy->count_ptrs[tbl_no][symbol]++;
+ else {
+ c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
+ emit_bits(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
+ }
+}
+
+
+/*
+ * Emit bits from a correction bit buffer.
+ */
+
+LOCAL(void)
+emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
+ unsigned int nbits)
+{
+ if (entropy->gather_statistics)
+ return; /* no real work */
+
+ while (nbits > 0) {
+ emit_bits(entropy, (unsigned int) (*bufstart), 1);
+ bufstart++;
+ nbits--;
+ }
+}
+
+
+/*
+ * Emit any pending EOBRUN symbol.
+ */
+
+LOCAL(void)
+emit_eobrun (phuff_entropy_ptr entropy)
+{
+ register int temp, nbits;
+
+ if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
+ temp = entropy->EOBRUN;
+ nbits = 0;
+ while ((temp >>= 1))
+ nbits++;
+ /* safety check: shouldn't happen given limited correction-bit buffer */
+ if (nbits > 18)
+ ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
+
+ emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
+ if (nbits)
+ emit_bits(entropy, entropy->EOBRUN, nbits);
+
+ entropy->EOBRUN = 0;
+
+ /* Emit any buffered correction bits */
+ emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
+ entropy->BE = 0;
+ }
+}
+
+
+/*
+ * Emit a restart marker & resynchronize predictions.
+ */
+
+LOCAL(void)
+emit_restart (phuff_entropy_ptr entropy, int restart_num)
+{
+ int ci;
+
+ emit_eobrun(entropy);
+
+ if (! entropy->gather_statistics) {
+ flush_bits(entropy);
+ emit_byte(entropy, 0xFF);
+ emit_byte(entropy, JPEG_RST0 + restart_num);
+ }
+
+ if (entropy->cinfo->Ss == 0) {
+ /* Re-initialize DC predictions to 0 */
+ for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
+ entropy->last_dc_val[ci] = 0;
+ } else {
+ /* Re-initialize all AC-related fields to 0 */
+ entropy->EOBRUN = 0;
+ entropy->BE = 0;
+ }
+}
+
+
+/*
+ * MCU encoding for DC initial scan (either spectral selection,
+ * or first pass of successive approximation).
+ */
+
+METHODDEF(boolean)
+encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+ register int temp, temp2;
+ register int nbits;
+ int blkn, ci;
+ int Al = cinfo->Al;
+ JBLOCKROW block;
+ jpeg_component_info * compptr;
+ ISHIFT_TEMPS
+
+ entropy->next_output_byte = cinfo->dest->next_output_byte;
+ entropy->free_in_buffer = cinfo->dest->free_in_buffer;
+
+ /* Emit restart marker if needed */
+ if (cinfo->restart_interval)
+ if (entropy->restarts_to_go == 0)
+ emit_restart(entropy, entropy->next_restart_num);
+
+ /* Encode the MCU data blocks */
+ for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+
+ /* Compute the DC value after the required point transform by Al.
+ * This is simply an arithmetic right shift.
+ */
+ temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
+
+ /* DC differences are figured on the point-transformed values. */
+ temp = temp2 - entropy->last_dc_val[ci];
+ entropy->last_dc_val[ci] = temp2;
+
+ /* Encode the DC coefficient difference per section G.1.2.1 */
+ temp2 = temp;
+ if (temp < 0) {
+ temp = -temp; /* temp is abs value of input */
+ /* For a negative input, want temp2 = bitwise complement of abs(input) */
+ /* This code assumes we are on a two's complement machine */
+ temp2--;
+ }
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ nbits = 0;
+ while (temp) {
+ nbits++;
+ temp >>= 1;
+ }
+ /* Check for out-of-range coefficient values.
+ * Since we're encoding a difference, the range limit is twice as much.
+ * was MAX_COEF_BITS +1, 11 or 15, now data_precision + 3.
+ */
+ if (nbits > (cinfo->data_precision + 3))
+ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+
+ /* Count/emit the Huffman-coded symbol for the number of bits */
+ emit_symbol(entropy, compptr->dc_tbl_no, nbits);
+
+ /* Emit that number of bits of the value, if positive, */
+ /* or the complement of its magnitude, if negative. */
+ if (nbits) /* emit_bits rejects calls with size 0 */
+ emit_bits(entropy, (unsigned int) temp2, nbits);
+ }
+
+ cinfo->dest->next_output_byte = entropy->next_output_byte;
+ cinfo->dest->free_in_buffer = entropy->free_in_buffer;
+
+ /* Update restart-interval state too */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num++;
+ entropy->next_restart_num &= 7;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ return TRUE;
+}
+
+
+/*
+ * MCU encoding for AC initial scan (either spectral selection,
+ * or first pass of successive approximation).
+ */
+
+METHODDEF(boolean)
+encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+ register int temp, temp2;
+ register int nbits;
+ register int r, k;
+ int Se = cinfo->Se;
+ int Al = cinfo->Al;
+ JBLOCKROW block;
+
+ entropy->next_output_byte = cinfo->dest->next_output_byte;
+ entropy->free_in_buffer = cinfo->dest->free_in_buffer;
+
+ /* Emit restart marker if needed */
+ if (cinfo->restart_interval)
+ if (entropy->restarts_to_go == 0)
+ emit_restart(entropy, entropy->next_restart_num);
+
+ /* Encode the MCU data block */
+ block = MCU_data[0];
+
+ /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
+
+ r = 0; /* r = run length of zeros */
+
+ for (k = cinfo->Ss; k <= Se; k++) {
+ if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
+ r++;
+ continue;
+ }
+ /* We must apply the point transform by Al. For AC coefficients this
+ * is an integer division with rounding towards 0. To do this portably
+ * in C, we shift after obtaining the absolute value; so the code is
+ * interwoven with finding the abs value (temp) and output bits (temp2).
+ */
+ if (temp < 0) {
+ temp = -temp; /* temp is abs value of input */
+ temp >>= Al; /* apply the point transform */
+ /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
+ temp2 = ~temp;
+ } else {
+ temp >>= Al; /* apply the point transform */
+ temp2 = temp;
+ }
+ /* Watch out for case that nonzero coef is zero after point transform */
+ if (temp == 0) {
+ r++;
+ continue;
+ }
+
+ /* Emit any pending EOBRUN */
+ if (entropy->EOBRUN > 0)
+ emit_eobrun(entropy);
+ /* if run length > 15, must emit special run-length-16 codes (0xF0) */
+ while (r > 15) {
+ emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
+ r -= 16;
+ }
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ nbits = 1; /* there must be at least one 1 bit */
+ while ((temp >>= 1))
+ nbits++;
+ /* Check for out-of-range coefficient values */
+ /* was MAX_COEF_BITS, 10 or 14, now data_precision + 2. */
+ if (nbits > (cinfo->data_precision + 2))
+ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+
+ /* Count/emit Huffman symbol for run length / number of bits */
+ emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
+
+ /* Emit that number of bits of the value, if positive, */
+ /* or the complement of its magnitude, if negative. */
+ emit_bits(entropy, (unsigned int) temp2, nbits);
+
+ r = 0; /* reset zero run length */
+ }
+
+ if (r > 0) { /* If there are trailing zeroes, */
+ entropy->EOBRUN++; /* count an EOB */
+ if (entropy->EOBRUN == 0x7FFF)
+ emit_eobrun(entropy); /* force it out to avoid overflow */
+ }
+
+ cinfo->dest->next_output_byte = entropy->next_output_byte;
+ cinfo->dest->free_in_buffer = entropy->free_in_buffer;
+
+ /* Update restart-interval state too */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num++;
+ entropy->next_restart_num &= 7;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ return TRUE;
+}
+
+
+/*
+ * MCU encoding for DC successive approximation refinement scan.
+ * Note: we assume such scans can be multi-component, although the spec
+ * is not very clear on the point.
+ */
+
+METHODDEF(boolean)
+encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+ register int temp;
+ int blkn;
+ int Al = cinfo->Al;
+ JBLOCKROW block;
+
+ entropy->next_output_byte = cinfo->dest->next_output_byte;
+ entropy->free_in_buffer = cinfo->dest->free_in_buffer;
+
+ /* Emit restart marker if needed */
+ if (cinfo->restart_interval)
+ if (entropy->restarts_to_go == 0)
+ emit_restart(entropy, entropy->next_restart_num);
+
+ /* Encode the MCU data blocks */
+ for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+
+ /* We simply emit the Al'th bit of the DC coefficient value. */
+ temp = (*block)[0];
+ emit_bits(entropy, (unsigned int) (temp >> Al), 1);
+ }
+
+ cinfo->dest->next_output_byte = entropy->next_output_byte;
+ cinfo->dest->free_in_buffer = entropy->free_in_buffer;
+
+ /* Update restart-interval state too */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num++;
+ entropy->next_restart_num &= 7;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ return TRUE;
+}
+
+
+/*
+ * MCU encoding for AC successive approximation refinement scan.
+ */
+
+METHODDEF(boolean)
+encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+ register int temp;
+ register int r, k;
+ int EOB;
+ char *BR_buffer;
+ unsigned int BR;
+ int Se = cinfo->Se;
+ int Al = cinfo->Al;
+ JBLOCKROW block;
+ int absvalues[DCTSIZE2];
+
+ entropy->next_output_byte = cinfo->dest->next_output_byte;
+ entropy->free_in_buffer = cinfo->dest->free_in_buffer;
+
+ /* Emit restart marker if needed */
+ if (cinfo->restart_interval)
+ if (entropy->restarts_to_go == 0)
+ emit_restart(entropy, entropy->next_restart_num);
+
+ /* Encode the MCU data block */
+ block = MCU_data[0];
+
+ /* It is convenient to make a pre-pass to determine the transformed
+ * coefficients' absolute values and the EOB position.
+ */
+ EOB = 0;
+ for (k = cinfo->Ss; k <= Se; k++) {
+ temp = (*block)[jpeg_natural_order[k]];
+ /* We must apply the point transform by Al. For AC coefficients this
+ * is an integer division with rounding towards 0. To do this portably
+ * in C, we shift after obtaining the absolute value.
+ */
+ if (temp < 0)
+ temp = -temp; /* temp is abs value of input */
+ temp >>= Al; /* apply the point transform */
+ absvalues[k] = temp; /* save abs value for main pass */
+ if (temp == 1)
+ EOB = k; /* EOB = index of last newly-nonzero coef */
+ }
+
+ /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
+
+ r = 0; /* r = run length of zeros */
+ BR = 0; /* BR = count of buffered bits added now */
+ BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
+
+ for (k = cinfo->Ss; k <= Se; k++) {
+ if ((temp = absvalues[k]) == 0) {
+ r++;
+ continue;
+ }
+
+ /* Emit any required ZRLs, but not if they can be folded into EOB */
+ while (r > 15 && k <= EOB) {
+ /* emit any pending EOBRUN and the BE correction bits */
+ emit_eobrun(entropy);
+ /* Emit ZRL */
+ emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
+ r -= 16;
+ /* Emit buffered correction bits that must be associated with ZRL */
+ emit_buffered_bits(entropy, BR_buffer, BR);
+ BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
+ BR = 0;
+ }
+
+ /* If the coef was previously nonzero, it only needs a correction bit.
+ * NOTE: a straight translation of the spec's figure G.7 would suggest
+ * that we also need to test r > 15. But if r > 15, we can only get here
+ * if k > EOB, which implies that this coefficient is not 1.
+ */
+ if (temp > 1) {
+ /* The correction bit is the next bit of the absolute value. */
+ BR_buffer[BR++] = (char) (temp & 1);
+ continue;
+ }
+
+ /* Emit any pending EOBRUN and the BE correction bits */
+ emit_eobrun(entropy);
+
+ /* Count/emit Huffman symbol for run length / number of bits */
+ emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
+
+ /* Emit output bit for newly-nonzero coef */
+ temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
+ emit_bits(entropy, (unsigned int) temp, 1);
+
+ /* Emit buffered correction bits that must be associated with this code */
+ emit_buffered_bits(entropy, BR_buffer, BR);
+ BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
+ BR = 0;
+ r = 0; /* reset zero run length */
+ }
+
+ if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
+ entropy->EOBRUN++; /* count an EOB */
+ entropy->BE += BR; /* concat my correction bits to older ones */
+ /* We force out the EOB if we risk either:
+ * 1. overflow of the EOB counter;
+ * 2. overflow of the correction bit buffer during the next MCU.
+ */
+ if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
+ emit_eobrun(entropy);
+ }
+
+ cinfo->dest->next_output_byte = entropy->next_output_byte;
+ cinfo->dest->free_in_buffer = entropy->free_in_buffer;
+
+ /* Update restart-interval state too */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num++;
+ entropy->next_restart_num &= 7;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ return TRUE;
+}
+
+
+/*
+ * Finish up at the end of a Huffman-compressed progressive scan.
+ */
+
+METHODDEF(void)
+finish_pass_phuff (j_compress_ptr cinfo)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+
+ entropy->next_output_byte = cinfo->dest->next_output_byte;
+ entropy->free_in_buffer = cinfo->dest->free_in_buffer;
+
+ /* Flush out any buffered data */
+ emit_eobrun(entropy);
+ flush_bits(entropy);
+
+ cinfo->dest->next_output_byte = entropy->next_output_byte;
+ cinfo->dest->free_in_buffer = entropy->free_in_buffer;
+}
+
+
+/*
+ * Finish up a statistics-gathering pass and create the new Huffman tables.
+ */
+
+METHODDEF(void)
+finish_pass_gather_phuff (j_compress_ptr cinfo)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+ boolean is_DC_band;
+ int ci, tbl;
+ jpeg_component_info * compptr;
+ JHUFF_TBL **htblptr;
+ boolean did[NUM_HUFF_TBLS];
+
+ /* Flush out buffered data (all we care about is counting the EOB symbol) */
+ emit_eobrun(entropy);
+
+ is_DC_band = (cinfo->Ss == 0);
+
+ /* It's important not to apply jpeg_gen_optimal_table more than once
+ * per table, because it clobbers the input frequency counts!
+ */
+ MEMZERO(did, SIZEOF(did));
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ if (is_DC_band) {
+ if (cinfo->Ah != 0) /* DC refinement needs no table */
+ continue;
+ tbl = compptr->dc_tbl_no;
+ } else {
+ tbl = compptr->ac_tbl_no;
+ }
+ if (! did[tbl]) {
+ if (is_DC_band)
+ htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
+ else
+ htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
+ if (*htblptr == NULL)
+ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+ jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
+ did[tbl] = TRUE;
+ }
+ }
+}
+
+
+METHODDEF(boolean)
+need_optimization_pass (j_compress_ptr cinfo)
+{
+ return (cinfo->Ss != 0 || cinfo->Ah == 0);
+}
+
+
+/*
+ * Module initialization routine for progressive Huffman entropy encoding.
+ */
+
+GLOBAL(void)
+jinit_phuff_encoder (j_compress_ptr cinfo)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy;
+ int i;
+
+ entropy = (phuff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(phuff_entropy_encoder));
+ lossyc->entropy_private = (struct jpeg_entropy_encoder *) entropy;
+ lossyc->pub.entropy_start_pass = start_pass_phuff;
+ lossyc->pub.need_optimization_pass = need_optimization_pass;
+
+ /* Mark tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ entropy->derived_tbls[i] = NULL;
+ entropy->count_ptrs[i] = NULL;
+ }
+ entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
+}
+
+#endif /* C_PROGRESSIVE_SUPPORTED */
diff --git a/jpeg-6c/jcpred.c b/jpeg-6c/jcpred.c
new file mode 100644
index 0000000..aaa93c2
--- /dev/null
+++ b/jpeg-6c/jcpred.c
@@ -0,0 +1,298 @@
+/*
+ * jcpred.c
+ *
+ * Copyright (C) 1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains sample differencing for lossless JPEG.
+ *
+ * In order to avoid paying the performance penalty of having to check the
+ * predictor being used and the row being processed for each call of the
+ * undifferencer, and to promote optimization, we have separate differencing
+ * functions for each case.
+ *
+ * We are able to avoid duplicating source code by implementing the predictors
+ * and differencers as macros. Each of the differencing functions are
+ * simply wrappers around a DIFFERENCE macro with the appropriate PREDICTOR
+ * macro passed as an argument.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossls.h" /* Private declarations for lossless codec */
+
+
+#ifdef C_LOSSLESS_SUPPORTED
+
+/* Private predictor object */
+
+typedef struct {
+ /* MCU-rows left in the restart interval for each component */
+ unsigned int restart_rows_to_go[MAX_COMPONENTS];
+} c_predictor;
+
+typedef c_predictor * c_pred_ptr;
+
+/* Forward declarations */
+LOCAL(void) reset_predictor
+ JPP((j_compress_ptr cinfo, int ci));
+METHODDEF(void) start_pass
+ JPP((j_compress_ptr cinfo));
+
+
+/* Predictor for the first column of the first row: 2^(P-Pt-1) */
+#define INITIAL_PREDICTORx (1 << (cinfo->data_precision - cinfo->Al - 1))
+
+/* Predictor for the first column of the remaining rows: Rb */
+#define INITIAL_PREDICTOR2 GETJSAMPLE(prev_row[0])
+
+
+/*
+ * 1-Dimensional differencer routine.
+ *
+ * This macro implements the 1-D horizontal predictor (1). INITIAL_PREDICTOR
+ * is used as the special case predictor for the first column, which must be
+ * either INITIAL_PREDICTOR2 or INITIAL_PREDICTORx. The remaining samples
+ * use PREDICTOR1.
+ */
+
+#define DIFFERENCE_1D(INITIAL_PREDICTOR) \
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec; \
+ c_pred_ptr pred = (c_pred_ptr) losslsc->pred_private; \
+ boolean restart = FALSE; \
+ int xindex; \
+ int samp, Ra; \
+ \
+ samp = GETJSAMPLE(input_buf[0]); \
+ diff_buf[0] = samp - INITIAL_PREDICTOR; \
+ \
+ for (xindex = 1; xindex < width; xindex++) { \
+ Ra = samp; \
+ samp = GETJSAMPLE(input_buf[xindex]); \
+ diff_buf[xindex] = samp - PREDICTOR1; \
+ } \
+ \
+ /* Account for restart interval (no-op if not using restarts) */ \
+ if (cinfo->restart_interval) { \
+ if (--(pred->restart_rows_to_go[ci]) == 0) { \
+ reset_predictor(cinfo, ci); \
+ restart = TRUE; \
+ } \
+ }
+
+
+/*
+ * 2-Dimensional differencer routine.
+ *
+ * This macro implements the 2-D horizontal predictors (#2-7). PREDICTOR2 is
+ * used as the special case predictor for the first column. The remaining
+ * samples use PREDICTOR, which is a function of Ra, Rb, Rc.
+ *
+ * Because prev_row and output_buf may point to the same storage area (in an
+ * interleaved image with Vi=1, for example), we must take care to buffer Rb/Rc
+ * before writing the current reconstructed sample value into output_buf.
+ */
+
+#define DIFFERENCE_2D(PREDICTOR) \
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec; \
+ c_pred_ptr pred = (c_pred_ptr) losslsc->pred_private; \
+ int xindex; \
+ int samp, Ra, Rb, Rc; \
+ \
+ Rb = GETJSAMPLE(prev_row[0]); \
+ samp = GETJSAMPLE(input_buf[0]); \
+ diff_buf[0] = samp - PREDICTOR2; \
+ \
+ for (xindex = 1; xindex < width; xindex++) { \
+ Rc = Rb; \
+ Rb = GETJSAMPLE(prev_row[xindex]); \
+ Ra = samp; \
+ samp = GETJSAMPLE(input_buf[xindex]); \
+ diff_buf[xindex] = samp - PREDICTOR; \
+ } \
+ \
+ /* Account for restart interval (no-op if not using restarts) */ \
+ if (cinfo->restart_interval) { \
+ if (--pred->restart_rows_to_go[ci] == 0) \
+ reset_predictor(cinfo, ci); \
+ }
+
+
+/*
+ * Differencers for the all rows but the first in a scan or restart interval.
+ * The first sample in the row is differenced using the vertical
+ * predictor (2). The rest of the samples are differenced using the
+ * predictor specified in the scan header.
+ */
+
+METHODDEF(void)
+jpeg_difference1(j_compress_ptr cinfo, int ci,
+ JSAMPROW16 input_buf, JSAMPROW16 prev_row,
+ JDIFFROW diff_buf, JDIMENSION width)
+{
+ DIFFERENCE_1D(INITIAL_PREDICTOR2);
+}
+
+METHODDEF(void)
+jpeg_difference2(j_compress_ptr cinfo, int ci,
+ JSAMPROW16 input_buf, JSAMPROW16 prev_row,
+ JDIFFROW diff_buf, JDIMENSION width)
+{
+ DIFFERENCE_2D(PREDICTOR2);
+}
+
+METHODDEF(void)
+jpeg_difference3(j_compress_ptr cinfo, int ci,
+ JSAMPROW16 input_buf, JSAMPROW16 prev_row,
+ JDIFFROW diff_buf, JDIMENSION width)
+{
+ DIFFERENCE_2D(PREDICTOR3);
+}
+
+METHODDEF(void)
+jpeg_difference4(j_compress_ptr cinfo, int ci,
+ JSAMPROW16 input_buf, JSAMPROW16 prev_row,
+ JDIFFROW diff_buf, JDIMENSION width)
+{
+ DIFFERENCE_2D(PREDICTOR4);
+}
+
+METHODDEF(void)
+jpeg_difference5(j_compress_ptr cinfo, int ci,
+ JSAMPROW16 input_buf, JSAMPROW16 prev_row,
+ JDIFFROW diff_buf, JDIMENSION width)
+{
+ DIFFERENCE_2D(PREDICTOR5);
+}
+
+METHODDEF(void)
+jpeg_difference6(j_compress_ptr cinfo, int ci,
+ JSAMPROW16 input_buf, JSAMPROW16 prev_row,
+ JDIFFROW diff_buf, JDIMENSION width)
+{
+ DIFFERENCE_2D(PREDICTOR6);
+}
+
+METHODDEF(void)
+jpeg_difference7(j_compress_ptr cinfo, int ci,
+ JSAMPROW16 input_buf, JSAMPROW16 prev_row,
+ JDIFFROW diff_buf, JDIMENSION width)
+{
+ DIFFERENCE_2D(PREDICTOR7);
+}
+
+
+/*
+ * Differencer for the first row in a scan or restart interval. The first
+ * sample in the row is differenced using the special predictor constant
+ * x=2^(P-Pt-1). The rest of the samples are differenced using the
+ * 1-D horizontal predictor (1).
+ */
+
+METHODDEF(void)
+jpeg_difference_first_row(j_compress_ptr cinfo, int ci,
+ JSAMPROW16 input_buf, JSAMPROW16 prev_row,
+ JDIFFROW diff_buf, JDIMENSION width)
+{
+ DIFFERENCE_1D(INITIAL_PREDICTORx);
+
+ /*
+ * Now that we have differenced the first row, we want to use the
+ * differencer which corresponds to the predictor specified in the
+ * scan header.
+ *
+ * Note that we don't to do this if we have just reset the predictor
+ * for a new restart interval.
+ */
+ if (!restart) {
+ switch (cinfo->Ss) {
+ case 1:
+ losslsc->predict_difference[ci] = jpeg_difference1;
+ break;
+ case 2:
+ losslsc->predict_difference[ci] = jpeg_difference2;
+ break;
+ case 3:
+ losslsc->predict_difference[ci] = jpeg_difference3;
+ break;
+ case 4:
+ losslsc->predict_difference[ci] = jpeg_difference4;
+ break;
+ case 5:
+ losslsc->predict_difference[ci] = jpeg_difference5;
+ break;
+ case 6:
+ losslsc->predict_difference[ci] = jpeg_difference6;
+ break;
+ case 7:
+ losslsc->predict_difference[ci] = jpeg_difference7;
+ break;
+ }
+ }
+}
+
+/*
+ * Reset predictor at the start of a pass or restart interval.
+ */
+
+LOCAL(void)
+reset_predictor (j_compress_ptr cinfo, int ci)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ c_pred_ptr pred = (c_pred_ptr) losslsc->pred_private;
+
+ /* Initialize restart counter */
+ pred->restart_rows_to_go[ci] =
+ cinfo->restart_interval / cinfo->MCUs_per_row;
+
+ /* Set difference function to first row function */
+ losslsc->predict_difference[ci] = jpeg_difference_first_row;
+}
+
+
+/*
+ * Initialize for an input processing pass.
+ */
+
+METHODDEF(void)
+start_pass (j_compress_ptr cinfo)
+{
+/* j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ c_pred_ptr pred = (c_pred_ptr) losslsc->pred_private;*/
+ int ci;
+
+ /* Check that the restart interval is an integer multiple of the number
+ * of MCU in an MCU-row.
+ */
+ if (cinfo->restart_interval % cinfo->MCUs_per_row != 0)
+ ERREXIT2(cinfo, JERR_BAD_RESTART,
+ cinfo->restart_interval, cinfo->MCUs_per_row);
+
+ /* Set predictors for start of pass */
+ for (ci = 0; ci < cinfo->num_components; ci++)
+ reset_predictor(cinfo, ci);
+}
+
+
+/*
+ * Module initialization routine for the differencer.
+ */
+
+GLOBAL(void)
+jinit_differencer (j_compress_ptr cinfo)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+ c_pred_ptr pred;
+
+ pred = (c_pred_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(c_predictor));
+ losslsc->pred_private = (void *) pred;
+ losslsc->predict_start_pass = start_pass;
+}
+
+#endif /* C_LOSSLESS_SUPPORTED */
+
diff --git a/jpeg-6c/jcprepct.c b/jpeg-6c/jcprepct.c
new file mode 100644
index 0000000..7ee7b5d
--- /dev/null
+++ b/jpeg-6c/jcprepct.c
@@ -0,0 +1,355 @@
+/*
+ * jcprepct.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the compression preprocessing controller.
+ * This controller manages the color conversion, downsampling,
+ * and edge expansion steps.
+ *
+ * Most of the complexity here is associated with buffering input rows
+ * as required by the downsampler. See the comments at the head of
+ * jcsample.c for the downsampler's needs.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* At present, jcsample.c can request context rows only for smoothing.
+ * In the future, we might also need context rows for CCIR601 sampling
+ * or other more-complex downsampling procedures. The code to support
+ * context rows should be compiled only if needed.
+ */
+#ifdef INPUT_SMOOTHING_SUPPORTED
+#define CONTEXT_ROWS_SUPPORTED
+#endif
+
+
+/*
+ * For the simple (no-context-row) case, we just need to buffer one
+ * row group's worth of pixels for the downsampling step. At the bottom of
+ * the image, we pad to a full row group by replicating the last pixel row.
+ * The downsampler's last output row is then replicated if needed to pad
+ * out to a full iMCU row.
+ *
+ * When providing context rows, we must buffer three row groups' worth of
+ * pixels. Three row groups are physically allocated, but the row pointer
+ * arrays are made five row groups high, with the extra pointers above and
+ * below "wrapping around" to point to the last and first real row groups.
+ * This allows the downsampler to access the proper context rows.
+ * At the top and bottom of the image, we create dummy context rows by
+ * copying the first or last real pixel row. This copying could be avoided
+ * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
+ * trouble on the compression side.
+ */
+
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_c_prep_controller pub; /* public fields */
+
+ /* Downsampling input buffer. This buffer holds color-converted data
+ * until we have enough to do a downsample step.
+ */
+ JSAMPARRAY16 color_buf[MAX_COMPONENTS];
+
+ JDIMENSION rows_to_go; /* counts rows remaining in source image */
+ int next_buf_row; /* index of next row to store in color_buf */
+
+#ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
+ int this_row_group; /* starting row index of group to process */
+ int next_buf_stop; /* downsample when we reach this index */
+#endif
+} my_prep_controller;
+
+typedef my_prep_controller * my_prep_ptr;
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF(void)
+start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
+
+ if (pass_mode != JBUF_PASS_THRU)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+
+ /* Initialize total-height counter for detecting bottom of image */
+ prep->rows_to_go = cinfo->image_height;
+ /* Mark the conversion buffer empty */
+ prep->next_buf_row = 0;
+#ifdef CONTEXT_ROWS_SUPPORTED
+ /* Preset additional state variables for context mode.
+ * These aren't used in non-context mode, so we needn't test which mode.
+ */
+ prep->this_row_group = 0;
+ /* Set next_buf_stop to stop after two row groups have been read in. */
+ prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
+#endif
+}
+
+
+/*
+ * Expand an image vertically from height input_rows to height output_rows,
+ * by duplicating the bottom row.
+ */
+
+LOCAL(void)
+expand_bottom_edge (JSAMPARRAY16 image_data, JDIMENSION num_cols,
+ int input_rows, int output_rows)
+{
+ register int row;
+
+ for (row = input_rows; row < output_rows; row++) {
+ jcopy_sample_rows(image_data, input_rows-1, image_data, row,
+ 1, num_cols);
+ }
+}
+
+
+/*
+ * Process some data in the simple no-context case.
+ *
+ * Preprocessor output data is counted in "row groups". A row group
+ * is defined to be v_samp_factor sample rows of each component.
+ * Downsampling will produce this much data from each max_v_samp_factor
+ * input rows.
+ */
+
+METHODDEF(void)
+pre_process_data (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail,
+ JSAMPIMAGE16 output_buf, JDIMENSION *out_row_group_ctr,
+ JDIMENSION out_row_groups_avail)
+{
+ my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
+ int numrows, ci;
+ JDIMENSION inrows;
+ jpeg_component_info * compptr;
+
+ while (*in_row_ctr < in_rows_avail &&
+ *out_row_group_ctr < out_row_groups_avail) {
+ /* Do color conversion to fill the conversion buffer. */
+ inrows = in_rows_avail - *in_row_ctr;
+ numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
+ numrows = (int) MIN((JDIMENSION) numrows, inrows);
+ (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
+ prep->color_buf,
+ (JDIMENSION) prep->next_buf_row,
+ numrows);
+ *in_row_ctr += numrows;
+ prep->next_buf_row += numrows;
+ prep->rows_to_go -= numrows;
+ /* If at bottom of image, pad to fill the conversion buffer. */
+ if (prep->rows_to_go == 0 &&
+ prep->next_buf_row < cinfo->max_v_samp_factor) {
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
+ prep->next_buf_row, cinfo->max_v_samp_factor);
+ }
+ prep->next_buf_row = cinfo->max_v_samp_factor;
+ }
+ /* If we've filled the conversion buffer, empty it. */
+ if (prep->next_buf_row == cinfo->max_v_samp_factor) {
+ (*cinfo->downsample->downsample) (cinfo,
+ prep->color_buf, (JDIMENSION) 0,
+ output_buf, *out_row_group_ctr);
+ prep->next_buf_row = 0;
+ (*out_row_group_ctr)++;
+ }
+ /* If at bottom of image, pad the output to a full iMCU height.
+ * Note we assume the caller is providing a one-iMCU-height output buffer!
+ */
+ if (prep->rows_to_go == 0 &&
+ *out_row_group_ctr < out_row_groups_avail) {
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ expand_bottom_edge(output_buf[ci],
+ compptr->width_in_data_units * cinfo->data_unit,
+ (int) (*out_row_group_ctr * compptr->v_samp_factor),
+ (int) (out_row_groups_avail * compptr->v_samp_factor));
+ }
+ *out_row_group_ctr = out_row_groups_avail;
+ break; /* can exit outer loop without test */
+ }
+ }
+}
+
+
+#ifdef CONTEXT_ROWS_SUPPORTED
+
+/*
+ * Process some data in the context case.
+ */
+
+METHODDEF(void)
+pre_process_context (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail,
+ JSAMPIMAGE16 output_buf, JDIMENSION *out_row_group_ctr,
+ JDIMENSION out_row_groups_avail)
+{
+ my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
+ int numrows, ci;
+ int buf_height = cinfo->max_v_samp_factor * 3;
+ JDIMENSION inrows;
+
+ while (*out_row_group_ctr < out_row_groups_avail) {
+ if (*in_row_ctr < in_rows_avail) {
+ /* Do color conversion to fill the conversion buffer. */
+ inrows = in_rows_avail - *in_row_ctr;
+ numrows = prep->next_buf_stop - prep->next_buf_row;
+ numrows = (int) MIN((JDIMENSION) numrows, inrows);
+ (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
+ prep->color_buf,
+ (JDIMENSION) prep->next_buf_row,
+ numrows);
+ /* Pad at top of image, if first time through */
+ if (prep->rows_to_go == cinfo->image_height) {
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ int row;
+ for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
+ jcopy_sample_rows(prep->color_buf[ci], 0,
+ prep->color_buf[ci], -row,
+ 1, cinfo->image_width);
+ }
+ }
+ }
+ *in_row_ctr += numrows;
+ prep->next_buf_row += numrows;
+ prep->rows_to_go -= numrows;
+ } else {
+ /* Return for more data, unless we are at the bottom of the image. */
+ if (prep->rows_to_go != 0)
+ break;
+ /* When at bottom of image, pad to fill the conversion buffer. */
+ if (prep->next_buf_row < prep->next_buf_stop) {
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
+ prep->next_buf_row, prep->next_buf_stop);
+ }
+ prep->next_buf_row = prep->next_buf_stop;
+ }
+ }
+ /* If we've gotten enough data, downsample a row group. */
+ if (prep->next_buf_row == prep->next_buf_stop) {
+ (*cinfo->downsample->downsample) (cinfo,
+ prep->color_buf,
+ (JDIMENSION) prep->this_row_group,
+ output_buf, *out_row_group_ctr);
+ (*out_row_group_ctr)++;
+ /* Advance pointers with wraparound as necessary. */
+ prep->this_row_group += cinfo->max_v_samp_factor;
+ if (prep->this_row_group >= buf_height)
+ prep->this_row_group = 0;
+ if (prep->next_buf_row >= buf_height)
+ prep->next_buf_row = 0;
+ prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
+ }
+ }
+}
+
+
+/*
+ * Create the wrapped-around downsampling input buffer needed for context mode.
+ */
+
+LOCAL(void)
+create_context_buffer (j_compress_ptr cinfo)
+{
+ my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
+ int rgroup_height = cinfo->max_v_samp_factor;
+ int ci, i;
+ jpeg_component_info * compptr;
+ JSAMPARRAY16 true_buffer, fake_buffer;
+
+ /* Grab enough space for fake row pointers for all the components;
+ * we need five row groups' worth of pointers for each component.
+ */
+ fake_buffer = (JSAMPARRAY16)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->num_components * 5 * rgroup_height) *
+ SIZEOF(JSAMPROW16));
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Allocate the actual buffer space (3 row groups) for this component.
+ * We make the buffer wide enough to allow the downsampler to edge-expand
+ * horizontally within the buffer, if it so chooses.
+ */
+ true_buffer = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) (((long) compptr->width_in_data_units * cinfo->data_unit *
+ cinfo->max_h_samp_factor * SIZEOF(JSAMPLE16)) / compptr->h_samp_factor),
+ (JDIMENSION) (3 * rgroup_height));
+ /* Copy true buffer row pointers into the middle of the fake row array */
+ MEMCOPY(fake_buffer + rgroup_height, true_buffer,
+ 3 * rgroup_height * SIZEOF(JSAMPROW16));
+ /* Fill in the above and below wraparound pointers */
+ for (i = 0; i < rgroup_height; i++) {
+ fake_buffer[i] = true_buffer[2 * rgroup_height + i];
+ fake_buffer[4 * rgroup_height + i] = true_buffer[i];
+ }
+ prep->color_buf[ci] = fake_buffer + rgroup_height;
+ fake_buffer += 5 * rgroup_height; /* point to space for next component */
+ }
+}
+
+#endif /* CONTEXT_ROWS_SUPPORTED */
+
+
+/*
+ * Initialize preprocessing controller.
+ */
+
+GLOBAL(void)
+jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
+{
+ my_prep_ptr prep;
+ int ci;
+ jpeg_component_info * compptr;
+
+ if (need_full_buffer) /* safety check */
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+
+ prep = (my_prep_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_prep_controller));
+ cinfo->prep = (struct jpeg_c_prep_controller *) prep;
+ prep->pub.start_pass = start_pass_prep;
+
+ /* Allocate the color conversion buffer.
+ * We make the buffer wide enough to allow the downsampler to edge-expand
+ * horizontally within the buffer, if it so chooses.
+ */
+ if (cinfo->downsample->need_context_rows) {
+ /* Set up to provide context rows */
+#ifdef CONTEXT_ROWS_SUPPORTED
+ prep->pub.pre_process_data = pre_process_context;
+ create_context_buffer(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ /* No context, just make it tall enough for one row group */
+ prep->pub.pre_process_data = pre_process_data;
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ prep->color_buf[ci] = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) (((long) compptr->width_in_data_units * cinfo->data_unit *
+ cinfo->max_h_samp_factor * SIZEOF(JSAMPLE16)) / compptr->h_samp_factor),
+ (JDIMENSION) cinfo->max_v_samp_factor);
+ }
+ }
+}
diff --git a/jpeg-6c/jcsample.c b/jpeg-6c/jcsample.c
new file mode 100644
index 0000000..3b814d4
--- /dev/null
+++ b/jpeg-6c/jcsample.c
@@ -0,0 +1,520 @@
+/*
+ * jcsample.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains downsampling routines.
+ *
+ * Downsampling input data is counted in "row groups". A row group
+ * is defined to be max_v_samp_factor pixel rows of each component,
+ * from which the downsampler produces v_samp_factor sample rows.
+ * A single row group is processed in each call to the downsampler module.
+ *
+ * The downsampler is responsible for edge-expansion of its output data
+ * to fill an integral number of DCT blocks horizontally. The source buffer
+ * may be modified if it is helpful for this purpose (the source buffer is
+ * allocated wide enough to correspond to the desired output width).
+ * The caller (the prep controller) is responsible for vertical padding.
+ *
+ * The downsampler may request "context rows" by setting need_context_rows
+ * during startup. In this case, the input arrays will contain at least
+ * one row group's worth of pixels above and below the passed-in data;
+ * the caller will create dummy rows at image top and bottom by replicating
+ * the first or last real pixel row.
+ *
+ * An excellent reference for image resampling is
+ * Digital Image Warping, George Wolberg, 1990.
+ * Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7.
+ *
+ * The downsampling algorithm used here is a simple average of the source
+ * pixels covered by the output pixel. The hi-falutin sampling literature
+ * refers to this as a "box filter". In general the characteristics of a box
+ * filter are not very good, but for the specific cases we normally use (1:1
+ * and 2:1 ratios) the box is equivalent to a "triangle filter" which is not
+ * nearly so bad. If you intend to use other sampling ratios, you'd be well
+ * advised to improve this code.
+ *
+ * A simple input-smoothing capability is provided. This is mainly intended
+ * for cleaning up color-dithered GIF input files (if you find it inadequate,
+ * we suggest using an external filtering program such as pnmconvol). When
+ * enabled, each input pixel P is replaced by a weighted sum of itself and its
+ * eight neighbors. P's weight is 1-8*SF and each neighbor's weight is SF,
+ * where SF = (smoothing_factor / 1024).
+ * Currently, smoothing is only supported for 2h2v sampling factors.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Pointer to routine to downsample a single component */
+typedef JMETHOD(void, downsample1_ptr,
+ (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 output_data));
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_downsampler pub; /* public fields */
+
+ /* Downsampling method pointers, one per component */
+ downsample1_ptr methods[MAX_COMPONENTS];
+} my_downsampler;
+
+typedef my_downsampler * my_downsample_ptr;
+
+
+/*
+ * Initialize for a downsampling pass.
+ */
+
+METHODDEF(void)
+start_pass_downsample (j_compress_ptr cinfo)
+{
+ /* no work for now */
+}
+
+
+/*
+ * Expand a component horizontally from width input_cols to width output_cols,
+ * by duplicating the rightmost samples.
+ */
+
+LOCAL(void)
+expand_right_edge (JSAMPARRAY16 image_data, int num_rows,
+ JDIMENSION input_cols, JDIMENSION output_cols)
+{
+ register JSAMPROW16 ptr;
+ register JSAMPLE16 pixval;
+ register int count;
+ int row;
+ int numcols = (int) (output_cols - input_cols);
+
+ if (numcols > 0) {
+ for (row = 0; row < num_rows; row++) {
+ ptr = image_data[row] + input_cols;
+ pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
+ for (count = numcols; count > 0; count--)
+ *ptr++ = pixval;
+ }
+ }
+}
+
+
+/*
+ * Do downsampling for a whole row group (all components).
+ *
+ * In this version we simply downsample each component independently.
+ */
+
+METHODDEF(void)
+sep_downsample (j_compress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION in_row_index,
+ JSAMPIMAGE16 output_buf, JDIMENSION out_row_group_index)
+{
+ my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
+ int ci;
+ jpeg_component_info * compptr;
+ JSAMPARRAY16 in_ptr, out_ptr;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ in_ptr = input_buf[ci] + in_row_index;
+ out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
+ (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
+ }
+}
+
+
+/*
+ * Downsample pixel values of a single component.
+ * One row group is processed per call.
+ * This version handles arbitrary integral sampling ratios, without smoothing.
+ * Note that this version is not actually used for customary sampling ratios.
+ */
+
+METHODDEF(void)
+int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 output_data)
+{
+ int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
+ JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
+ JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit;
+ JSAMPROW16 inptr, outptr;
+ INT32 outvalue;
+
+ h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
+ v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
+ numpix = h_expand * v_expand;
+ numpix2 = numpix/2;
+
+ /* Expand input data enough to let all the output samples be generated
+ * by the standard loop. Special-casing padded output would be more
+ * efficient.
+ */
+ expand_right_edge(input_data, cinfo->max_v_samp_factor,
+ cinfo->image_width, output_cols * h_expand);
+
+ inrow = 0;
+ for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
+ outptr = output_data[outrow];
+ for (outcol = 0, outcol_h = 0; outcol < output_cols;
+ outcol++, outcol_h += h_expand) {
+ outvalue = 0;
+ for (v = 0; v < v_expand; v++) {
+ inptr = input_data[inrow+v] + outcol_h;
+ for (h = 0; h < h_expand; h++) {
+ outvalue += (INT32) GETJSAMPLE(*inptr++);
+ }
+ }
+ *outptr++ = (JSAMPLE16) ((outvalue + numpix2) / numpix);
+ }
+ inrow += v_expand;
+ }
+}
+
+
+/*
+ * Downsample pixel values of a single component.
+ * This version handles the special case of a full-size component,
+ * without smoothing.
+ */
+
+METHODDEF(void)
+fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 output_data)
+{
+ /* Copy the data */
+ jcopy_sample_rows(input_data, 0, output_data, 0,
+ cinfo->max_v_samp_factor, cinfo->image_width);
+ /* Edge-expand */
+ expand_right_edge(output_data, cinfo->max_v_samp_factor,
+ cinfo->image_width, compptr->width_in_data_units * cinfo->data_unit);
+}
+
+
+/*
+ * Downsample pixel values of a single component.
+ * This version handles the common case of 2:1 horizontal and 1:1 vertical,
+ * without smoothing.
+ *
+ * A note about the "bias" calculations: when rounding fractional values to
+ * integer, we do not want to always round 0.5 up to the next integer.
+ * If we did that, we'd introduce a noticeable bias towards larger values.
+ * Instead, this code is arranged so that 0.5 will be rounded up or down at
+ * alternate pixel locations (a simple ordered dither pattern).
+ */
+
+METHODDEF(void)
+h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 output_data)
+{
+ int outrow;
+ JDIMENSION outcol;
+ JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit;
+ register JSAMPROW16 inptr, outptr;
+ register int bias;
+
+ /* Expand input data enough to let all the output samples be generated
+ * by the standard loop. Special-casing padded output would be more
+ * efficient.
+ */
+ expand_right_edge(input_data, cinfo->max_v_samp_factor,
+ cinfo->image_width, output_cols * 2);
+
+ for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
+ outptr = output_data[outrow];
+ inptr = input_data[outrow];
+ bias = 0; /* bias = 0,1,0,1,... for successive samples */
+ for (outcol = 0; outcol < output_cols; outcol++) {
+ *outptr++ = (JSAMPLE16) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
+ + bias) >> 1);
+ bias ^= 1; /* 0=>1, 1=>0 */
+ inptr += 2;
+ }
+ }
+}
+
+
+/*
+ * Downsample pixel values of a single component.
+ * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
+ * without smoothing.
+ */
+
+METHODDEF(void)
+h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 output_data)
+{
+ int inrow, outrow;
+ JDIMENSION outcol;
+ JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit;
+ register JSAMPROW16 inptr0, inptr1, outptr;
+ register int bias;
+
+ /* Expand input data enough to let all the output samples be generated
+ * by the standard loop. Special-casing padded output would be more
+ * efficient.
+ */
+ expand_right_edge(input_data, cinfo->max_v_samp_factor,
+ cinfo->image_width, output_cols * 2);
+
+ inrow = 0;
+ for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
+ outptr = output_data[outrow];
+ inptr0 = input_data[inrow];
+ inptr1 = input_data[inrow+1];
+ bias = 1; /* bias = 1,2,1,2,... for successive samples */
+ for (outcol = 0; outcol < output_cols; outcol++) {
+ *outptr++ = (JSAMPLE16) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
+ GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
+ + bias) >> 2);
+ bias ^= 3; /* 1=>2, 2=>1 */
+ inptr0 += 2; inptr1 += 2;
+ }
+ inrow += 2;
+ }
+}
+
+
+#ifdef INPUT_SMOOTHING_SUPPORTED
+
+/*
+ * Downsample pixel values of a single component.
+ * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
+ * with smoothing. One row of context is required.
+ */
+
+METHODDEF(void)
+h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 output_data)
+{
+ int inrow, outrow;
+ JDIMENSION colctr;
+ JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit;
+ register JSAMPROW16 inptr0, inptr1, above_ptr, below_ptr, outptr;
+ INT32 membersum, neighsum, memberscale, neighscale;
+
+ /* Expand input data enough to let all the output samples be generated
+ * by the standard loop. Special-casing padded output would be more
+ * efficient.
+ */
+ expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
+ cinfo->image_width, output_cols * 2);
+
+ /* We don't bother to form the individual "smoothed" input pixel values;
+ * we can directly compute the output which is the average of the four
+ * smoothed values. Each of the four member pixels contributes a fraction
+ * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
+ * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
+ * output. The four corner-adjacent neighbor pixels contribute a fraction
+ * SF to just one smoothed pixel, or SF/4 to the final output; while the
+ * eight edge-adjacent neighbors contribute SF to each of two smoothed
+ * pixels, or SF/2 overall. In order to use integer arithmetic, these
+ * factors are scaled by 2^16 = 65536.
+ * Also recall that SF = smoothing_factor / 1024.
+ */
+
+ memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
+ neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
+
+ inrow = 0;
+ for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
+ outptr = output_data[outrow];
+ inptr0 = input_data[inrow];
+ inptr1 = input_data[inrow+1];
+ above_ptr = input_data[inrow-1];
+ below_ptr = input_data[inrow+2];
+
+ /* Special case for first column: pretend column -1 is same as column 0 */
+ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
+ GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
+ neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
+ GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
+ GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
+ GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
+ neighsum += neighsum;
+ neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
+ GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
+ membersum = membersum * memberscale + neighsum * neighscale;
+ *outptr++ = (JSAMPLE16) ((membersum + 32768) >> 16);
+ inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
+
+ for (colctr = output_cols - 2; colctr > 0; colctr--) {
+ /* sum of pixels directly mapped to this output element */
+ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
+ GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
+ /* sum of edge-neighbor pixels */
+ neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
+ GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
+ GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
+ GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
+ /* The edge-neighbors count twice as much as corner-neighbors */
+ neighsum += neighsum;
+ /* Add in the corner-neighbors */
+ neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
+ GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
+ /* form final output scaled up by 2^16 */
+ membersum = membersum * memberscale + neighsum * neighscale;
+ /* round, descale and output it */
+ *outptr++ = (JSAMPLE16) ((membersum + 32768) >> 16);
+ inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
+ }
+
+ /* Special case for last column */
+ membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
+ GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
+ neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
+ GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
+ GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
+ GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
+ neighsum += neighsum;
+ neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
+ GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
+ membersum = membersum * memberscale + neighsum * neighscale;
+ *outptr = (JSAMPLE16) ((membersum + 32768) >> 16);
+
+ inrow += 2;
+ }
+}
+
+
+/*
+ * Downsample pixel values of a single component.
+ * This version handles the special case of a full-size component,
+ * with smoothing. One row of context is required.
+ */
+
+METHODDEF(void)
+fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 output_data)
+{
+ int outrow;
+ JDIMENSION colctr;
+ JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit;
+ register JSAMPROW16 inptr, above_ptr, below_ptr, outptr;
+ INT32 membersum, neighsum, memberscale, neighscale;
+ int colsum, lastcolsum, nextcolsum;
+
+ /* Expand input data enough to let all the output samples be generated
+ * by the standard loop. Special-casing padded output would be more
+ * efficient.
+ */
+ expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
+ cinfo->image_width, output_cols);
+
+ /* Each of the eight neighbor pixels contributes a fraction SF to the
+ * smoothed pixel, while the main pixel contributes (1-8*SF). In order
+ * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
+ * Also recall that SF = smoothing_factor / 1024.
+ */
+
+ memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
+ neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
+
+ for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
+ outptr = output_data[outrow];
+ inptr = input_data[outrow];
+ above_ptr = input_data[outrow-1];
+ below_ptr = input_data[outrow+1];
+
+ /* Special case for first column */
+ colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
+ GETJSAMPLE(*inptr);
+ membersum = GETJSAMPLE(*inptr++);
+ nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
+ GETJSAMPLE(*inptr);
+ neighsum = colsum + (colsum - membersum) + nextcolsum;
+ membersum = membersum * memberscale + neighsum * neighscale;
+ *outptr++ = (JSAMPLE16) ((membersum + 32768) >> 16);
+ lastcolsum = colsum; colsum = nextcolsum;
+
+ for (colctr = output_cols - 2; colctr > 0; colctr--) {
+ membersum = GETJSAMPLE(*inptr++);
+ above_ptr++; below_ptr++;
+ nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
+ GETJSAMPLE(*inptr);
+ neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
+ membersum = membersum * memberscale + neighsum * neighscale;
+ *outptr++ = (JSAMPLE16) ((membersum + 32768) >> 16);
+ lastcolsum = colsum; colsum = nextcolsum;
+ }
+
+ /* Special case for last column */
+ membersum = GETJSAMPLE(*inptr);
+ neighsum = lastcolsum + (colsum - membersum) + colsum;
+ membersum = membersum * memberscale + neighsum * neighscale;
+ *outptr = (JSAMPLE16) ((membersum + 32768) >> 16);
+
+ }
+}
+
+#endif /* INPUT_SMOOTHING_SUPPORTED */
+
+
+/*
+ * Module initialization routine for downsampling.
+ * Note that we must select a routine for each component.
+ */
+
+GLOBAL(void)
+jinit_downsampler (j_compress_ptr cinfo)
+{
+ my_downsample_ptr downsample;
+ int ci;
+ jpeg_component_info * compptr;
+ boolean smoothok = TRUE;
+
+ downsample = (my_downsample_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_downsampler));
+ cinfo->downsample = (struct jpeg_downsampler *) downsample;
+ downsample->pub.start_pass = start_pass_downsample;
+ downsample->pub.downsample = sep_downsample;
+ downsample->pub.need_context_rows = FALSE;
+
+ if (cinfo->CCIR601_sampling)
+ ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
+
+ /* Verify we can handle the sampling factors, and set up method pointers */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
+ compptr->v_samp_factor == cinfo->max_v_samp_factor) {
+#ifdef INPUT_SMOOTHING_SUPPORTED
+ if (cinfo->smoothing_factor) {
+ downsample->methods[ci] = fullsize_smooth_downsample;
+ downsample->pub.need_context_rows = TRUE;
+ } else
+#endif
+ downsample->methods[ci] = fullsize_downsample;
+ } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
+ compptr->v_samp_factor == cinfo->max_v_samp_factor) {
+ smoothok = FALSE;
+ downsample->methods[ci] = h2v1_downsample;
+ } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
+ compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
+#ifdef INPUT_SMOOTHING_SUPPORTED
+ if (cinfo->smoothing_factor) {
+ downsample->methods[ci] = h2v2_smooth_downsample;
+ downsample->pub.need_context_rows = TRUE;
+ } else
+#endif
+ downsample->methods[ci] = h2v2_downsample;
+ } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
+ (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
+ smoothok = FALSE;
+ downsample->methods[ci] = int_downsample;
+ } else
+ ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
+ }
+
+#ifdef INPUT_SMOOTHING_SUPPORTED
+ if (cinfo->smoothing_factor && !smoothok)
+ TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
+#endif
+}
diff --git a/jpeg-6c/jcscale.c b/jpeg-6c/jcscale.c
new file mode 100644
index 0000000..9a68e35
--- /dev/null
+++ b/jpeg-6c/jcscale.c
@@ -0,0 +1,63 @@
+/*
+ * jcscale.c
+ *
+ * Copyright (C) 1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains sample downscaling by 2^Pt for lossless JPEG.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossls.h" /* Private declarations for lossless codec */
+
+
+#ifdef C_LOSSLESS_SUPPORTED
+
+METHODDEF(void)
+simple_downscale(j_compress_ptr cinfo,
+ JSAMPROW16 input_buf, JSAMPROW16 output_buf, JDIMENSION width)
+{
+/* j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;*/
+ int xindex;
+
+ for (xindex = 0; xindex < width; xindex++)
+ output_buf[xindex] = (JSAMPLE16) RIGHT_SHIFT(GETJSAMPLE(input_buf[xindex]),
+ cinfo->Al);
+}
+
+
+METHODDEF(void)
+noscale(j_compress_ptr cinfo,
+ JSAMPROW16 input_buf, JSAMPROW16 output_buf, JDIMENSION width)
+{
+ MEMCOPY(output_buf, input_buf, width * SIZEOF(JSAMPLE16));
+ return;
+}
+
+
+METHODDEF(void)
+scaler_start_pass (j_compress_ptr cinfo)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+
+ /* Set scaler function based on Pt */
+ if ((cinfo->Al) && cinfo->lossless_scaling)
+ losslsc->scaler_scale = simple_downscale;
+ else
+ losslsc->scaler_scale = noscale;
+}
+
+
+GLOBAL(void)
+jinit_c_scaler (j_compress_ptr cinfo)
+{
+ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
+
+ losslsc->scaler_start_pass = scaler_start_pass;
+}
+
+#endif /* C_LOSSLESS_SUPPORTED */
diff --git a/jpeg-6c/jcshuff.c b/jpeg-6c/jcshuff.c
new file mode 100644
index 0000000..6e1e5b4
--- /dev/null
+++ b/jpeg-6c/jcshuff.c
@@ -0,0 +1,666 @@
+/*
+ * jcshuff.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains Huffman entropy encoding routines for sequential JPEG.
+ *
+ * Much of the complexity here has to do with supporting output suspension.
+ * If the data destination module demands suspension, we want to be able to
+ * back up to the start of the current MCU. To do this, we copy state
+ * variables into local working storage, and update them back to the
+ * permanent JPEG objects only upon successful completion of an MCU.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h" /* Private declarations for lossy codec */
+#include "jchuff.h" /* Declarations shared with jc*huff.c */
+
+
+/* Expanded entropy encoder object for Huffman encoding.
+ *
+ * The savable_state subrecord contains fields that change within an MCU,
+ * but must not be updated permanently until we complete the MCU.
+ */
+
+typedef struct {
+ INT32 put_buffer; /* current bit-accumulation buffer */
+ int put_bits; /* # of bits now in it */
+ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
+} savable_state;
+
+/* This macro is to work around compilers with missing or broken
+ * structure assignment. You'll need to fix this code if you have
+ * such a compiler and you change MAX_COMPS_IN_SCAN.
+ */
+
+#ifndef NO_STRUCT_ASSIGN
+#define ASSIGN_STATE(dest,src) ((dest) = (src))
+#else
+#if MAX_COMPS_IN_SCAN == 4
+#define ASSIGN_STATE(dest,src) \
+ ((dest).put_buffer = (src).put_buffer, \
+ (dest).put_bits = (src).put_bits, \
+ (dest).last_dc_val[0] = (src).last_dc_val[0], \
+ (dest).last_dc_val[1] = (src).last_dc_val[1], \
+ (dest).last_dc_val[2] = (src).last_dc_val[2], \
+ (dest).last_dc_val[3] = (src).last_dc_val[3])
+#endif
+#endif
+
+
+typedef struct {
+ savable_state saved; /* Bit buffer & DC state at start of MCU */
+
+ /* These fields are NOT loaded into local working state. */
+ unsigned int restarts_to_go; /* MCUs left in this restart interval */
+ int next_restart_num; /* next restart number to write (0-7) */
+
+ /* Pointers to derived tables (these workspaces have image lifespan) */
+ c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
+ c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
+
+#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
+ long * dc_count_ptrs[NUM_HUFF_TBLS];
+ long * ac_count_ptrs[NUM_HUFF_TBLS];
+#endif
+} shuff_entropy_encoder;
+
+typedef shuff_entropy_encoder * shuff_entropy_ptr;
+
+/* Working state while writing an MCU.
+ * This struct contains all the fields that are needed by subroutines.
+ */
+
+typedef struct {
+ JOCTET * next_output_byte; /* => next byte to write in buffer */
+ size_t free_in_buffer; /* # of byte spaces remaining in buffer */
+ savable_state cur; /* Current bit buffer & DC state */
+ j_compress_ptr cinfo; /* dump_buffer needs access to this */
+} working_state;
+
+
+/* Forward declarations */
+METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
+#ifdef ENTROPY_OPT_SUPPORTED
+METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
+#endif
+
+
+/*
+ * Initialize for a Huffman-compressed scan.
+ * If gather_statistics is TRUE, we do not output anything during the scan,
+ * just count the Huffman symbols used and generate Huffman code tables.
+ */
+
+METHODDEF(void)
+start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
+ int ci, dctbl, actbl;
+ jpeg_component_info * compptr;
+
+ if (gather_statistics) {
+#ifdef ENTROPY_OPT_SUPPORTED
+ lossyc->entropy_encode_mcu = encode_mcu_gather;
+ lossyc->pub.entropy_finish_pass = finish_pass_gather;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ lossyc->entropy_encode_mcu = encode_mcu_huff;
+ lossyc->pub.entropy_finish_pass = finish_pass_huff;
+ }
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ dctbl = compptr->dc_tbl_no;
+ actbl = compptr->ac_tbl_no;
+ if (gather_statistics) {
+#ifdef ENTROPY_OPT_SUPPORTED
+ /* Check for invalid table indexes */
+ /* (make_c_derived_tbl does this in the other path) */
+ if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
+ if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
+ /* Allocate and zero the statistics tables */
+ /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
+ if (entropy->dc_count_ptrs[dctbl] == NULL)
+ entropy->dc_count_ptrs[dctbl] = (long *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ 257 * SIZEOF(long));
+ MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
+ if (entropy->ac_count_ptrs[actbl] == NULL)
+ entropy->ac_count_ptrs[actbl] = (long *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ 257 * SIZEOF(long));
+ MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
+#endif
+ } else {
+ /* Compute derived values for Huffman tables */
+ /* We may do this more than once for a table, but it's not expensive */
+ jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
+ & entropy->dc_derived_tbls[dctbl]);
+ jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
+ & entropy->ac_derived_tbls[actbl]);
+ }
+ /* Initialize DC predictions to 0 */
+ entropy->saved.last_dc_val[ci] = 0;
+ }
+
+ /* Initialize bit buffer to empty */
+ entropy->saved.put_buffer = 0;
+ entropy->saved.put_bits = 0;
+
+ /* Initialize restart stuff */
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num = 0;
+}
+
+
+/* Outputting bytes to the file */
+
+/* Emit a byte, taking 'action' if must suspend. */
+#define emit_byte(state,val,action) \
+ { *(state)->next_output_byte++ = (JOCTET) (val); \
+ if (--(state)->free_in_buffer == 0) \
+ if (! dump_buffer(state)) \
+ { action; } }
+
+
+LOCAL(boolean)
+dump_buffer (working_state * state)
+/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
+{
+ struct jpeg_destination_mgr * dest = state->cinfo->dest;
+
+ if (! (*dest->empty_output_buffer) (state->cinfo))
+ return FALSE;
+ /* After a successful buffer dump, must reset buffer pointers */
+ state->next_output_byte = dest->next_output_byte;
+ state->free_in_buffer = dest->free_in_buffer;
+ return TRUE;
+}
+
+
+/* Outputting bits to the file */
+
+/* Only the right 24 bits of put_buffer are used; the valid bits are
+ * left-justified in this part. At most 16 bits can be passed to emit_bits
+ * in one call, and we never retain more than 7 bits in put_buffer
+ * between calls, so 24 bits are sufficient.
+ */
+
+INLINE
+LOCAL(boolean)
+emit_bits (working_state * state, unsigned int code, int size)
+/* Emit some bits; return TRUE if successful, FALSE if must suspend */
+{
+ /* This routine is heavily used, so it's worth coding tightly. */
+ register INT32 put_buffer = (INT32) code;
+ register int put_bits = state->cur.put_bits;
+
+ /* if size is 0, caller used an invalid Huffman table entry */
+ if (size == 0)
+ ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
+
+ put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
+
+ put_bits += size; /* new number of bits in buffer */
+
+ put_buffer <<= 24 - put_bits; /* align incoming bits */
+
+ put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
+
+ while (put_bits >= 8) {
+ int c = (int) ((put_buffer >> 16) & 0xFF);
+
+ emit_byte(state, c, return FALSE);
+ if (c == 0xFF) { /* need to stuff a zero byte? */
+ emit_byte(state, 0, return FALSE);
+ }
+ put_buffer <<= 8;
+ put_bits -= 8;
+ }
+
+ state->cur.put_buffer = put_buffer; /* update state variables */
+ state->cur.put_bits = put_bits;
+
+ return TRUE;
+}
+
+
+LOCAL(boolean)
+flush_bits (working_state * state)
+{
+ if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
+ return FALSE;
+ state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
+ state->cur.put_bits = 0;
+ return TRUE;
+}
+
+
+/* Encode a single block's worth of coefficients */
+
+LOCAL(boolean)
+encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
+ c_derived_tbl *dctbl, c_derived_tbl *actbl)
+{
+ register int temp, temp2;
+ register int nbits;
+ register int k, r, i;
+
+ /* Encode the DC coefficient difference per section F.1.2.1 */
+
+ temp = temp2 = block[0] - last_dc_val;
+
+ if (temp < 0) {
+ temp = -temp; /* temp is abs value of input */
+ /* For a negative input, want temp2 = bitwise complement of abs(input) */
+ /* This code assumes we are on a two's complement machine */
+ temp2--;
+ }
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ nbits = 0;
+ while (temp) {
+ nbits++;
+ temp >>= 1;
+ }
+ /* Check for out-of-range coefficient values.
+ * Since we're encoding a difference, the range limit is twice as much.
+ * was MAX_COEF_BITS +1, 11 or 15, now data_precision + 3.
+ */
+ if (nbits > (state->cinfo->data_precision + 3))
+ ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
+
+ /* Emit the Huffman-coded symbol for the number of bits */
+ if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
+ return FALSE;
+
+ /* Emit that number of bits of the value, if positive, */
+ /* or the complement of its magnitude, if negative. */
+ if (nbits) /* emit_bits rejects calls with size 0 */
+ if (! emit_bits(state, (unsigned int) temp2, nbits))
+ return FALSE;
+
+ /* Encode the AC coefficients per section F.1.2.2 */
+
+ r = 0; /* r = run length of zeros */
+
+ for (k = 1; k < DCTSIZE2; k++) {
+ if ((temp = block[jpeg_natural_order[k]]) == 0) {
+ r++;
+ } else {
+ /* if run length > 15, must emit special run-length-16 codes (0xF0) */
+ while (r > 15) {
+ if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
+ return FALSE;
+ r -= 16;
+ }
+
+ temp2 = temp;
+ if (temp < 0) {
+ temp = -temp; /* temp is abs value of input */
+ /* This code assumes we are on a two's complement machine */
+ temp2--;
+ }
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ nbits = 1; /* there must be at least one 1 bit */
+ while ((temp >>= 1))
+ nbits++;
+ /* Check for out-of-range coefficient values */
+ /* was MAX_COEF_BITS, 10 or 14, now data_precision + 2. */
+ if (nbits > (state->cinfo->data_precision + 2))
+ ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
+
+ /* Emit Huffman symbol for run length / number of bits */
+ i = (r << 4) + nbits;
+ if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
+ return FALSE;
+
+ /* Emit that number of bits of the value, if positive, */
+ /* or the complement of its magnitude, if negative. */
+ if (! emit_bits(state, (unsigned int) temp2, nbits))
+ return FALSE;
+
+ r = 0;
+ }
+ }
+
+ /* If the last coef(s) were zero, emit an end-of-block code */
+ if (r > 0)
+ if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
+ return FALSE;
+
+ return TRUE;
+}
+
+
+/*
+ * Emit a restart marker & resynchronize predictions.
+ */
+
+LOCAL(boolean)
+emit_restart (working_state * state, int restart_num)
+{
+ int ci;
+
+ if (! flush_bits(state))
+ return FALSE;
+
+ emit_byte(state, 0xFF, return FALSE);
+ emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
+
+ /* Re-initialize DC predictions to 0 */
+ for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
+ state->cur.last_dc_val[ci] = 0;
+
+ /* The restart counter is not updated until we successfully write the MCU. */
+
+ return TRUE;
+}
+
+
+/*
+ * Encode and output one MCU's worth of Huffman-compressed coefficients.
+ */
+
+METHODDEF(boolean)
+encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
+ working_state state;
+ int blkn, ci;
+ jpeg_component_info * compptr;
+
+ /* Load up working state */
+ state.next_output_byte = cinfo->dest->next_output_byte;
+ state.free_in_buffer = cinfo->dest->free_in_buffer;
+ ASSIGN_STATE(state.cur, entropy->saved);
+ state.cinfo = cinfo;
+
+ /* Emit restart marker if needed */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! emit_restart(&state, entropy->next_restart_num))
+ return FALSE;
+ }
+
+ /* Encode the MCU data blocks */
+ for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+ if (! encode_one_block(&state,
+ MCU_data[blkn][0], state.cur.last_dc_val[ci],
+ entropy->dc_derived_tbls[compptr->dc_tbl_no],
+ entropy->ac_derived_tbls[compptr->ac_tbl_no]))
+ return FALSE;
+ /* Update last_dc_val */
+ state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
+ }
+
+ /* Completed MCU, so update state */
+ cinfo->dest->next_output_byte = state.next_output_byte;
+ cinfo->dest->free_in_buffer = state.free_in_buffer;
+ ASSIGN_STATE(entropy->saved, state.cur);
+
+ /* Update restart-interval state too */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ entropy->restarts_to_go = cinfo->restart_interval;
+ entropy->next_restart_num++;
+ entropy->next_restart_num &= 7;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ return TRUE;
+}
+
+
+/*
+ * Finish up at the end of a Huffman-compressed scan.
+ */
+
+METHODDEF(void)
+finish_pass_huff (j_compress_ptr cinfo)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
+ working_state state;
+
+ /* Load up working state ... flush_bits needs it */
+ state.next_output_byte = cinfo->dest->next_output_byte;
+ state.free_in_buffer = cinfo->dest->free_in_buffer;
+ ASSIGN_STATE(state.cur, entropy->saved);
+ state.cinfo = cinfo;
+
+ /* Flush out the last data */
+ if (! flush_bits(&state))
+ ERREXIT(cinfo, JERR_CANT_SUSPEND);
+
+ /* Update state */
+ cinfo->dest->next_output_byte = state.next_output_byte;
+ cinfo->dest->free_in_buffer = state.free_in_buffer;
+ ASSIGN_STATE(entropy->saved, state.cur);
+}
+
+
+/*
+ * Huffman coding optimization.
+ *
+ * We first scan the supplied data and count the number of uses of each symbol
+ * that is to be Huffman-coded. (This process MUST agree with the code above.)
+ * Then we build a Huffman coding tree for the observed counts.
+ * Symbols which are not needed at all for the particular image are not
+ * assigned any code, which saves space in the DHT marker as well as in
+ * the compressed data.
+ */
+
+#ifdef ENTROPY_OPT_SUPPORTED
+
+
+/* Process a single block's worth of coefficients */
+
+LOCAL(void)
+htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
+ long dc_counts[], long ac_counts[])
+{
+ register int temp;
+ register int nbits;
+ register int k, r;
+
+ /* Encode the DC coefficient difference per section F.1.2.1 */
+
+ temp = block[0] - last_dc_val;
+ if (temp < 0)
+ temp = -temp;
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ nbits = 0;
+ while (temp) {
+ nbits++;
+ temp >>= 1;
+ }
+ /* Check for out-of-range coefficient values.
+ * Since we're encoding a difference, the range limit is twice as much.
+ * was MAX_COEF_BITS +1, 11 or 15, now data_precision + 3.
+ */
+ if (nbits > (cinfo->data_precision + 3))
+ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+
+ /* Count the Huffman symbol for the number of bits */
+ dc_counts[nbits]++;
+
+ /* Encode the AC coefficients per section F.1.2.2 */
+
+ r = 0; /* r = run length of zeros */
+
+ for (k = 1; k < DCTSIZE2; k++) {
+ if ((temp = block[jpeg_natural_order[k]]) == 0) {
+ r++;
+ } else {
+ /* if run length > 15, must emit special run-length-16 codes (0xF0) */
+ while (r > 15) {
+ ac_counts[0xF0]++;
+ r -= 16;
+ }
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ if (temp < 0)
+ temp = -temp;
+
+ /* Find the number of bits needed for the magnitude of the coefficient */
+ nbits = 1; /* there must be at least one 1 bit */
+ while ((temp >>= 1))
+ nbits++;
+ /* Check for out-of-range coefficient values */
+ /* was MAX_COEF_BITS, 10 or 14, now data_precision + 2. */
+ if (nbits > (cinfo->data_precision + 2))
+ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+
+ /* Count Huffman symbol for run length / number of bits */
+ ac_counts[(r << 4) + nbits]++;
+
+ r = 0;
+ }
+ }
+
+ /* If the last coef(s) were zero, emit an end-of-block code */
+ if (r > 0)
+ ac_counts[0]++;
+}
+
+
+/*
+ * Trial-encode one MCU's worth of Huffman-compressed coefficients.
+ * No data is actually output, so no suspension return is possible.
+ */
+
+METHODDEF(boolean)
+encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
+ int blkn, ci;
+ jpeg_component_info * compptr;
+
+ /* Take care of restart intervals if needed */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0) {
+ /* Re-initialize DC predictions to 0 */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++)
+ entropy->saved.last_dc_val[ci] = 0;
+ /* Update restart state */
+ entropy->restarts_to_go = cinfo->restart_interval;
+ }
+ entropy->restarts_to_go--;
+ }
+
+ for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+ htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
+ entropy->dc_count_ptrs[compptr->dc_tbl_no],
+ entropy->ac_count_ptrs[compptr->ac_tbl_no]);
+ entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
+ }
+
+ return TRUE;
+}
+
+
+/*
+ * Finish up a statistics-gathering pass and create the new Huffman tables.
+ */
+
+METHODDEF(void)
+finish_pass_gather (j_compress_ptr cinfo)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
+ int ci, dctbl, actbl;
+ jpeg_component_info * compptr;
+ JHUFF_TBL **htblptr;
+ boolean did_dc[NUM_HUFF_TBLS];
+ boolean did_ac[NUM_HUFF_TBLS];
+
+ /* It's important not to apply jpeg_gen_optimal_table more than once
+ * per table, because it clobbers the input frequency counts!
+ */
+ MEMZERO(did_dc, SIZEOF(did_dc));
+ MEMZERO(did_ac, SIZEOF(did_ac));
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ dctbl = compptr->dc_tbl_no;
+ actbl = compptr->ac_tbl_no;
+ if (! did_dc[dctbl]) {
+ htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
+ if (*htblptr == NULL)
+ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+ jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
+ did_dc[dctbl] = TRUE;
+ }
+ if (! did_ac[actbl]) {
+ htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
+ if (*htblptr == NULL)
+ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+ jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
+ did_ac[actbl] = TRUE;
+ }
+ }
+}
+
+
+#endif /* ENTROPY_OPT_SUPPORTED */
+
+
+METHODDEF(boolean)
+need_optimization_pass (j_compress_ptr cinfo)
+{
+ return TRUE;
+}
+
+
+/*
+ * Module initialization routine for Huffman entropy encoding.
+ */
+
+GLOBAL(void)
+jinit_shuff_encoder (j_compress_ptr cinfo)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ shuff_entropy_ptr entropy;
+ int i;
+
+ entropy = (shuff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(shuff_entropy_encoder));
+ lossyc->entropy_private = (struct jpeg_entropy_encoder *) entropy;
+ lossyc->pub.entropy_start_pass = start_pass_huff;
+ lossyc->pub.need_optimization_pass = need_optimization_pass;
+
+ /* Mark tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
+#ifdef ENTROPY_OPT_SUPPORTED
+ entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
+#endif
+ }
+}
diff --git a/jpeg-6c/jctrans.c b/jpeg-6c/jctrans.c
new file mode 100644
index 0000000..af03ead
--- /dev/null
+++ b/jpeg-6c/jctrans.c
@@ -0,0 +1,427 @@
+/*
+ * jctrans.c
+ *
+ * Copyright (C) 1995-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains library routines for transcoding compression,
+ * that is, writing raw DCT coefficient arrays to an output JPEG file.
+ * The routines in jcapimin.c will also be needed by a transcoder.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h" /* Private declarations for lossy codec */
+
+
+/* Forward declarations */
+LOCAL(void) transencode_master_selection
+ JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
+LOCAL(void) transencode_codec
+ JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
+LOCAL(void) transencode_coef_controller
+ JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
+
+
+/*
+ * Compression initialization for writing raw-coefficient data.
+ * Before calling this, all parameters and a data destination must be set up.
+ * Call jpeg_finish_compress() to actually write the data.
+ *
+ * The number of passed virtual arrays must match cinfo->num_components.
+ * Note that the virtual arrays need not be filled or even realized at
+ * the time write_coefficients is called; indeed, if the virtual arrays
+ * were requested from this compression object's memory manager, they
+ * typically will be realized during this routine and filled afterwards.
+ */
+
+GLOBAL(void)
+jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
+{
+ if (cinfo->global_state != CSTATE_START)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ /* Mark all tables to be written */
+ jpeg_suppress_tables(cinfo, FALSE);
+ /* (Re)initialize error mgr and destination modules */
+ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
+ (*cinfo->dest->init_destination) (cinfo);
+ /* Perform master selection of active modules */
+ transencode_master_selection(cinfo, coef_arrays);
+ /* Wait for jpeg_finish_compress() call */
+ cinfo->next_scanline = 0; /* so jpeg_write_marker works */
+ cinfo->global_state = CSTATE_WRCOEFS;
+}
+
+
+/*
+ * Initialize the compression object with default parameters,
+ * then copy from the source object all parameters needed for lossless
+ * transcoding. Parameters that can be varied without loss (such as
+ * scan script and Huffman optimization) are left in their default states.
+ */
+
+GLOBAL(void)
+jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
+ j_compress_ptr dstinfo)
+{
+ JQUANT_TBL ** qtblptr;
+ jpeg_component_info *incomp, *outcomp;
+ JQUANT_TBL *c_quant, *slot_quant;
+ int tblno, ci, coefi;
+
+ /* Safety check to ensure start_compress not called yet. */
+ if (dstinfo->global_state != CSTATE_START)
+ ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
+ /* Copy fundamental image dimensions */
+ dstinfo->image_width = srcinfo->image_width;
+ dstinfo->image_height = srcinfo->image_height;
+ dstinfo->input_components = srcinfo->num_components;
+ dstinfo->in_color_space = srcinfo->jpeg_color_space;
+ /* Initialize all parameters to default values */
+ jpeg_set_defaults(dstinfo);
+ /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
+ * Fix it to get the right header markers for the image colorspace.
+ */
+ jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
+ dstinfo->data_precision = srcinfo->data_precision;
+ dstinfo->data_precision_other = srcinfo->data_precision_other;
+ dstinfo->maxjsample = srcinfo->maxjsample;
+ dstinfo->centerjsample = srcinfo->centerjsample;
+#ifdef HAVE_GETJSAMPLE_MASK
+ dstinfo->maskjsample = srcinfo->maskjsample;
+#endif
+ dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
+ /* Copy the source's quantization tables. */
+ for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
+ if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
+ qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
+ if (*qtblptr == NULL)
+ *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
+ MEMCOPY((*qtblptr)->quantval,
+ srcinfo->quant_tbl_ptrs[tblno]->quantval,
+ SIZEOF((*qtblptr)->quantval));
+ (*qtblptr)->sent_table = FALSE;
+ }
+ }
+ /* Copy the source's per-component info.
+ * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
+ */
+ dstinfo->num_components = srcinfo->num_components;
+ if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
+ ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
+ MAX_COMPONENTS);
+ for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
+ ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
+ outcomp->component_id = incomp->component_id;
+ outcomp->h_samp_factor = incomp->h_samp_factor;
+ outcomp->v_samp_factor = incomp->v_samp_factor;
+ outcomp->quant_tbl_no = incomp->quant_tbl_no;
+ /* Make sure saved quantization table for component matches the qtable
+ * slot. If not, the input file re-used this qtable slot.
+ * IJG encoder currently cannot duplicate this.
+ */
+ tblno = outcomp->quant_tbl_no;
+ if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
+ srcinfo->quant_tbl_ptrs[tblno] == NULL)
+ ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
+ slot_quant = srcinfo->quant_tbl_ptrs[tblno];
+ c_quant = incomp->quant_table;
+ if (c_quant != NULL) {
+ for (coefi = 0; coefi < DCTSIZE2; coefi++) {
+ if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
+ ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
+ }
+ }
+ /* Note: we do not copy the source's Huffman table assignments;
+ * instead we rely on jpeg_set_colorspace to have made a suitable choice.
+ */
+ }
+ /* Also copy JFIF version and resolution information, if available.
+ * Strictly speaking this isn't "critical" info, but it's nearly
+ * always appropriate to copy it if available. In particular,
+ * if the application chooses to copy JFIF 1.02 extension markers from
+ * the source file, we need to copy the version to make sure we don't
+ * emit a file that has 1.02 extensions but a claimed version of 1.01.
+ * We will *not*, however, copy version info from mislabeled "2.01" files.
+ */
+ if (srcinfo->saw_JFIF_marker) {
+ if (srcinfo->JFIF_major_version == 1) {
+ dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
+ dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
+ }
+ dstinfo->density_unit = srcinfo->density_unit;
+ dstinfo->X_density = srcinfo->X_density;
+ dstinfo->Y_density = srcinfo->Y_density;
+ }
+}
+
+
+/*
+ * Master selection of compression modules for transcoding.
+ * This substitutes for jcinit.c's initialization of the full compressor.
+ */
+
+LOCAL(void)
+transencode_master_selection (j_compress_ptr cinfo,
+ jvirt_barray_ptr * coef_arrays)
+{
+ cinfo->data_unit = DCTSIZE;
+ /* Although we don't actually use input_components for transcoding,
+ * jcmaster.c's initial_setup will complain if input_components is 0.
+ */
+ cinfo->input_components = 1;
+ /* Initialize master control (includes parameter checking/processing) */
+ jinit_c_master_control(cinfo, TRUE /* transcode only */);
+
+ /* We need a special compression codec. */
+ transencode_codec(cinfo, coef_arrays);
+
+ jinit_marker_writer(cinfo);
+
+ /* We can now tell the memory manager to allocate virtual arrays. */
+ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
+
+ /* Write the datastream header (SOI, JFIF) immediately.
+ * Frame and scan headers are postponed till later.
+ * This lets application insert special markers after the SOI.
+ */
+ (*cinfo->marker->write_file_header) (cinfo);
+}
+
+
+/*
+ * The rest of this file is a special implementation of the coefficient
+ * buffer controller. This is similar to jccoefct.c, but it handles only
+ * output from presupplied virtual arrays. Furthermore, we generate any
+ * dummy padding blocks on-the-fly rather than expecting them to be present
+ * in the arrays.
+ */
+
+/* Private buffer controller object */
+
+typedef struct {
+ JDIMENSION iMCU_row_num; /* iMCU row # within image */
+ JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
+ int MCU_vert_offset; /* counts MCU rows within iMCU row */
+ int MCU_rows_per_iMCU_row; /* number of such rows needed */
+
+ /* Virtual block array for each component. */
+ jvirt_barray_ptr * whole_image;
+
+ /* Workspace for constructing dummy blocks at right/bottom edges. */
+ JBLOCKROW dummy_buffer[C_MAX_DATA_UNITS_IN_MCU];
+} c_coef_controller;
+
+typedef c_coef_controller * c_coef_ptr;
+
+
+LOCAL(void)
+start_iMCU_row (j_compress_ptr cinfo)
+/* Reset within-iMCU-row counters for a new row */
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+ * But at the bottom of the image, process only what's left.
+ */
+ if (cinfo->comps_in_scan > 1) {
+ coef->MCU_rows_per_iMCU_row = 1;
+ } else {
+ if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
+ else
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
+ }
+
+ coef->mcu_ctr = 0;
+ coef->MCU_vert_offset = 0;
+}
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF(void)
+start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+
+ if (pass_mode != JBUF_CRANK_DEST)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+
+ coef->iMCU_row_num = 0;
+ start_iMCU_row(cinfo);
+}
+
+
+/*
+ * Process some data.
+ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
+ * per call, ie, v_samp_factor block rows for each component in the scan.
+ * The data is obtained from the virtual arrays and fed to the entropy coder.
+ * Returns TRUE if the iMCU row is completed, FALSE if suspended.
+ *
+ * NB: input_buf is ignored; it is likely to be a NULL pointer.
+ */
+
+METHODDEF(boolean)
+compress_output (j_compress_ptr cinfo, JSAMPIMAGE16 input_buf)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ int blkn, ci, xindex, yindex, yoffset, blockcnt;
+ JDIMENSION start_col;
+ JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
+ JBLOCKROW MCU_buffer[C_MAX_DATA_UNITS_IN_MCU];
+ JBLOCKROW buffer_ptr;
+ jpeg_component_info *compptr;
+
+ /* Align the virtual buffers for the components used in this scan. */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ buffer[ci] = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
+ coef->iMCU_row_num * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ }
+
+ /* Loop to process one whole iMCU row */
+ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
+ yoffset++) {
+ for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
+ MCU_col_num++) {
+ /* Construct list of pointers to DCT blocks belonging to this MCU */
+ blkn = 0; /* index of current DCT block within MCU */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ start_col = MCU_col_num * compptr->MCU_width;
+ blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
+ : compptr->last_col_width;
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ if (coef->iMCU_row_num < last_iMCU_row ||
+ yindex+yoffset < compptr->last_row_height) {
+ /* Fill in pointers to real blocks in this row */
+ buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
+ for (xindex = 0; xindex < blockcnt; xindex++)
+ MCU_buffer[blkn++] = buffer_ptr++;
+ } else {
+ /* At bottom of image, need a whole row of dummy blocks */
+ xindex = 0;
+ }
+ /* Fill in any dummy blocks needed in this row.
+ * Dummy blocks are filled in the same way as in jccoefct.c:
+ * all zeroes in the AC entries, DC entries equal to previous
+ * block's DC value. The init routine has already zeroed the
+ * AC entries, so we need only set the DC entries correctly.
+ */
+ for (; xindex < compptr->MCU_width; xindex++) {
+ MCU_buffer[blkn] = coef->dummy_buffer[blkn];
+ MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
+ blkn++;
+ }
+ }
+ }
+ /* Try to write the MCU. */
+ if (! (*lossyc->entropy_encode_mcu) (cinfo, MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->mcu_ctr = MCU_col_num;
+ return FALSE;
+ }
+ }
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ coef->mcu_ctr = 0;
+ }
+ /* Completed the iMCU row, advance counters for next one */
+ coef->iMCU_row_num++;
+ start_iMCU_row(cinfo);
+ return TRUE;
+}
+
+
+/*
+ * Initialize coefficient buffer controller.
+ *
+ * Each passed coefficient array must be the right size for that
+ * coefficient: width_in_data_units wide and height_in_data_units high,
+ * with unitheight at least v_samp_factor.
+ */
+
+LOCAL(void)
+transencode_coef_controller (j_compress_ptr cinfo,
+ jvirt_barray_ptr * coef_arrays)
+{
+ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ c_coef_ptr coef;
+ JBLOCKROW buffer;
+ int i;
+
+ coef = (c_coef_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(c_coef_controller));
+ lossyc->coef_private = (struct jpeg_c_coef_controller *) coef;
+
+ /* Save pointer to virtual arrays */
+ coef->whole_image = coef_arrays;
+
+ /* Allocate and pre-zero space for dummy DCT blocks. */
+ buffer = (JBLOCKROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ C_MAX_DATA_UNITS_IN_MCU * SIZEOF(JBLOCK));
+ jzero_far((void FAR *) buffer, C_MAX_DATA_UNITS_IN_MCU * SIZEOF(JBLOCK));
+ for (i = 0; i < C_MAX_DATA_UNITS_IN_MCU; i++) {
+ coef->dummy_buffer[i] = buffer + i;
+ }
+}
+
+
+/*
+ * Initialize the transencoer codec.
+ * This is called only once, during master selection.
+ */
+
+LOCAL(void)
+transencode_codec (j_compress_ptr cinfo,
+ jvirt_barray_ptr * coef_arrays)
+{
+ j_lossy_c_ptr lossyc;
+
+ /* Create subobject in permanent pool */
+ lossyc = (j_lossy_c_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(jpeg_lossy_c_codec));
+ cinfo->codec = (struct jpeg_c_codec *) lossyc;
+
+ /* Initialize sub-modules */
+
+ /* Entropy encoding: either Huffman or arithmetic coding. */
+ if (cinfo->arith_code) {
+ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+ } else {
+ if (cinfo->process == JPROC_PROGRESSIVE) {
+#ifdef C_PROGRESSIVE_SUPPORTED
+ jinit_phuff_encoder(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else
+ jinit_shuff_encoder(cinfo);
+ }
+
+ /* We need a special coefficient buffer controller. */
+ transencode_coef_controller(cinfo, coef_arrays);
+
+ /* Initialize method pointers */
+ lossyc->pub.start_pass = start_pass_coef;
+ lossyc->pub.compress_data = compress_output;
+}
diff --git a/jpeg-6c/jdapimin.c b/jpeg-6c/jdapimin.c
new file mode 100644
index 0000000..e34add0
--- /dev/null
+++ b/jpeg-6c/jdapimin.c
@@ -0,0 +1,403 @@
+/*
+ * jdapimin.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains application interface code for the decompression half
+ * of the JPEG library. These are the "minimum" API routines that may be
+ * needed in either the normal full-decompression case or the
+ * transcoding-only case.
+ *
+ * Most of the routines intended to be called directly by an application
+ * are in this file or in jdapistd.c. But also see jcomapi.c for routines
+ * shared by compression and decompression, and jdtrans.c for the transcoding
+ * case.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Initialization of a JPEG decompression object.
+ * The error manager must already be set up (in case memory manager fails).
+ */
+
+GLOBAL(void)
+jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
+{
+ int i;
+
+ /* Guard against version mismatches between library and caller. */
+ cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
+ if (version != JPEG_LIB_VERSION)
+ ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
+ if (structsize != SIZEOF(struct jpeg_decompress_struct))
+ ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
+ (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
+
+ /* For debugging purposes, we zero the whole master structure.
+ * But the application has already set the err pointer, and may have set
+ * client_data, so we have to save and restore those fields.
+ * Note: if application hasn't set client_data, tools like Purify may
+ * complain here.
+ */
+ {
+ struct jpeg_error_mgr * err = cinfo->err;
+ void * client_data = cinfo->client_data; /* ignore Purify complaint here */
+ MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
+ cinfo->err = err;
+ cinfo->client_data = client_data;
+ }
+ cinfo->is_decompressor = TRUE;
+
+ /* Initialize a memory manager instance for this object */
+ jinit_memory_mgr((j_common_ptr) cinfo);
+
+ /* Zero out pointers to permanent structures. */
+ cinfo->progress = NULL;
+ cinfo->src = NULL;
+
+ for (i = 0; i < NUM_QUANT_TBLS; i++)
+ cinfo->quant_tbl_ptrs[i] = NULL;
+
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ cinfo->dc_huff_tbl_ptrs[i] = NULL;
+ cinfo->ac_huff_tbl_ptrs[i] = NULL;
+ }
+
+ /* Initialize marker processor so application can override methods
+ * for COM, APPn markers before calling jpeg_read_header.
+ */
+ cinfo->marker_list = NULL;
+ jinit_marker_reader(cinfo);
+
+ /* And initialize the overall input controller. */
+ jinit_input_controller(cinfo);
+
+ /* OK, I'm ready */
+ cinfo->global_state = DSTATE_START;
+}
+
+
+/*
+ * Destruction of a JPEG decompression object
+ */
+
+GLOBAL(void)
+jpeg_destroy_decompress (j_decompress_ptr cinfo)
+{
+ jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
+}
+
+
+/*
+ * Abort processing of a JPEG decompression operation,
+ * but don't destroy the object itself.
+ */
+
+GLOBAL(void)
+jpeg_abort_decompress (j_decompress_ptr cinfo)
+{
+ jpeg_abort((j_common_ptr) cinfo); /* use common routine */
+}
+
+
+/*
+ * Set default decompression parameters.
+ */
+
+LOCAL(void)
+default_decompress_parms (j_decompress_ptr cinfo)
+{
+ /* Guess the input colorspace, and set output colorspace accordingly. */
+ /* (Wish JPEG committee had provided a real way to specify this...) */
+ /* Note application may override our guesses. */
+ switch (cinfo->num_components) {
+ case 1:
+ cinfo->jpeg_color_space = JCS_GRAYSCALE;
+ cinfo->out_color_space = JCS_GRAYSCALE;
+ break;
+
+ case 3:
+ if (cinfo->saw_JFIF_marker) {
+ cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
+ } else if (cinfo->saw_Adobe_marker) {
+ switch (cinfo->Adobe_transform) {
+ case 0:
+ cinfo->jpeg_color_space = JCS_RGB;
+ break;
+ case 1:
+ cinfo->jpeg_color_space = JCS_YCbCr;
+ break;
+ default:
+ WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
+ cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
+ break;
+ }
+ } else {
+ /* Saw no special markers, try to guess from the component IDs */
+ int cid0 = cinfo->comp_info[0].component_id;
+ int cid1 = cinfo->comp_info[1].component_id;
+ int cid2 = cinfo->comp_info[2].component_id;
+
+ if (cid0 == 1 && cid1 == 2 && cid2 == 3)
+ cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
+ else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
+ cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
+ else {
+ if (cinfo->process == JPROC_LOSSLESS) {
+ TRACEMS3(cinfo, 1, JTRC_UNKNOWN_LOSSLESS_IDS, cid0, cid1, cid2);
+ cinfo->jpeg_color_space = JCS_RGB; /* assume it's RGB */
+ }
+ else { /* Lossy processes */
+ TRACEMS3(cinfo, 1, JTRC_UNKNOWN_LOSSY_IDS, cid0, cid1, cid2);
+ cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
+ }
+ }
+ }
+ /* Always guess RGB is proper output colorspace. */
+ cinfo->out_color_space = JCS_RGB;
+ break;
+
+ case 4:
+ if (cinfo->saw_Adobe_marker) {
+ switch (cinfo->Adobe_transform) {
+ case 0:
+ cinfo->jpeg_color_space = JCS_CMYK;
+ break;
+ case 2:
+ cinfo->jpeg_color_space = JCS_YCCK;
+ break;
+ default:
+ WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
+ cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
+ break;
+ }
+ } else {
+ /* No special markers, assume straight CMYK. */
+ cinfo->jpeg_color_space = JCS_CMYK;
+ }
+ cinfo->out_color_space = JCS_CMYK;
+ break;
+
+ default:
+ cinfo->jpeg_color_space = JCS_UNKNOWN;
+ cinfo->out_color_space = JCS_UNKNOWN;
+ break;
+ }
+
+ /* Set defaults for other decompression parameters. */
+ cinfo->scale_num = 1; /* 1:1 scaling */
+ cinfo->scale_denom = 1;
+ cinfo->output_gamma = 1.0;
+ cinfo->buffered_image = FALSE;
+ cinfo->raw_data_out = FALSE;
+ cinfo->dct_method = JDCT_DEFAULT;
+ cinfo->do_fancy_upsampling = TRUE;
+ cinfo->do_block_smoothing = TRUE;
+ cinfo->quantize_colors = FALSE;
+ /* We set these in case application only sets quantize_colors. */
+ cinfo->dither_mode = JDITHER_FS;
+#ifdef QUANT_2PASS_SUPPORTED
+ cinfo->two_pass_quantize = TRUE;
+#else
+ cinfo->two_pass_quantize = FALSE;
+#endif
+ cinfo->desired_number_of_colors = 256;
+ cinfo->colormap = NULL;
+ cinfo->colormap16 = NULL;
+ /* Initialize for no mode change in buffered-image mode. */
+ cinfo->enable_1pass_quant = FALSE;
+ cinfo->enable_external_quant = FALSE;
+ cinfo->enable_2pass_quant = FALSE;
+}
+
+
+/*
+ * Decompression startup: read start of JPEG datastream to see what's there.
+ * Need only initialize JPEG object and supply a data source before calling.
+ *
+ * This routine will read as far as the first SOS marker (ie, actual start of
+ * compressed data), and will save all tables and parameters in the JPEG
+ * object. It will also initialize the decompression parameters to default
+ * values, and finally return JPEG_HEADER_OK. On return, the application may
+ * adjust the decompression parameters and then call jpeg_start_decompress.
+ * (Or, if the application only wanted to determine the image parameters,
+ * the data need not be decompressed. In that case, call jpeg_abort or
+ * jpeg_destroy to release any temporary space.)
+ * If an abbreviated (tables only) datastream is presented, the routine will
+ * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
+ * re-use the JPEG object to read the abbreviated image datastream(s).
+ * It is unnecessary (but OK) to call jpeg_abort in this case.
+ * The JPEG_SUSPENDED return code only occurs if the data source module
+ * requests suspension of the decompressor. In this case the application
+ * should load more source data and then re-call jpeg_read_header to resume
+ * processing.
+ * If a non-suspending data source is used and require_image is TRUE, then the
+ * return code need not be inspected since only JPEG_HEADER_OK is possible.
+ *
+ * This routine is now just a front end to jpeg_consume_input, with some
+ * extra error checking.
+ */
+
+GLOBAL(int)
+jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
+{
+ int retcode;
+
+ if (cinfo->global_state != DSTATE_START &&
+ cinfo->global_state != DSTATE_INHEADER)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ retcode = jpeg_consume_input(cinfo);
+
+ switch (retcode) {
+ case JPEG_REACHED_SOS:
+ retcode = JPEG_HEADER_OK;
+ break;
+ case JPEG_REACHED_EOI:
+ if (require_image) /* Complain if application wanted an image */
+ ERREXIT(cinfo, JERR_NO_IMAGE);
+ /* Reset to start state; it would be safer to require the application to
+ * call jpeg_abort, but we can't change it now for compatibility reasons.
+ * A side effect is to free any temporary memory (there shouldn't be any).
+ */
+ jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
+ retcode = JPEG_HEADER_TABLES_ONLY;
+ break;
+ case JPEG_SUSPENDED:
+ /* no work */
+ break;
+ }
+
+ return retcode;
+}
+
+
+/*
+ * Consume data in advance of what the decompressor requires.
+ * This can be called at any time once the decompressor object has
+ * been created and a data source has been set up.
+ *
+ * This routine is essentially a state machine that handles a couple
+ * of critical state-transition actions, namely initial setup and
+ * transition from header scanning to ready-for-start_decompress.
+ * All the actual input is done via the input controller's consume_input
+ * method.
+ */
+
+GLOBAL(int)
+jpeg_consume_input (j_decompress_ptr cinfo)
+{
+ int retcode = JPEG_SUSPENDED;
+
+ /* NB: every possible DSTATE value should be listed in this switch */
+ switch (cinfo->global_state) {
+ case DSTATE_START:
+ /* Start-of-datastream actions: reset appropriate modules */
+ (*cinfo->inputctl->reset_input_controller) (cinfo);
+ /* Initialize application's data source module */
+ (*cinfo->src->init_source) (cinfo);
+ cinfo->global_state = DSTATE_INHEADER;
+ /*FALLTHROUGH*/
+ case DSTATE_INHEADER:
+ retcode = (*cinfo->inputctl->consume_input) (cinfo);
+ if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
+ /* Set up default parameters based on header data */
+ default_decompress_parms(cinfo);
+ /* Set global state: ready for start_decompress */
+ cinfo->global_state = DSTATE_READY;
+ }
+ break;
+ case DSTATE_READY:
+ /* Can't advance past first SOS until start_decompress is called */
+ retcode = JPEG_REACHED_SOS;
+ break;
+ case DSTATE_PRELOAD:
+ case DSTATE_PRESCAN:
+ case DSTATE_SCANNING:
+ case DSTATE_RAW_OK:
+ case DSTATE_BUFIMAGE:
+ case DSTATE_BUFPOST:
+ case DSTATE_STOPPING:
+ retcode = (*cinfo->inputctl->consume_input) (cinfo);
+ break;
+ default:
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ }
+ return retcode;
+}
+
+
+/*
+ * Have we finished reading the input file?
+ */
+
+GLOBAL(boolean)
+jpeg_input_complete (j_decompress_ptr cinfo)
+{
+ /* Check for valid jpeg object */
+ if (cinfo->global_state < DSTATE_START ||
+ cinfo->global_state > DSTATE_STOPPING)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ return cinfo->inputctl->eoi_reached;
+}
+
+
+/*
+ * Is there more than one scan?
+ */
+
+GLOBAL(boolean)
+jpeg_has_multiple_scans (j_decompress_ptr cinfo)
+{
+ /* Only valid after jpeg_read_header completes */
+ if (cinfo->global_state < DSTATE_READY ||
+ cinfo->global_state > DSTATE_STOPPING)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ return cinfo->inputctl->has_multiple_scans;
+}
+
+
+/*
+ * Finish JPEG decompression.
+ *
+ * This will normally just verify the file trailer and release temp storage.
+ *
+ * Returns FALSE if suspended. The return value need be inspected only if
+ * a suspending data source is used.
+ */
+
+GLOBAL(boolean)
+jpeg_finish_decompress (j_decompress_ptr cinfo)
+{
+ if ((cinfo->global_state == DSTATE_SCANNING ||
+ cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
+ /* Terminate final pass of non-buffered mode */
+ if (cinfo->output_scanline < cinfo->output_height)
+ ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
+ (*cinfo->master->finish_output_pass) (cinfo);
+ cinfo->global_state = DSTATE_STOPPING;
+ } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
+ /* Finishing after a buffered-image operation */
+ cinfo->global_state = DSTATE_STOPPING;
+ } else if (cinfo->global_state != DSTATE_STOPPING) {
+ /* STOPPING = repeat call after a suspension, anything else is error */
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ }
+ /* Read until EOI */
+ while (! cinfo->inputctl->eoi_reached) {
+ if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
+ return FALSE; /* Suspend, come back later */
+ }
+ /* Do final cleanup */
+ (*cinfo->src->term_source) (cinfo);
+ /* We can use jpeg_abort to release memory and reset global_state */
+ jpeg_abort((j_common_ptr) cinfo);
+ return TRUE;
+}
diff --git a/jpeg-6c/jdapistd.c b/jpeg-6c/jdapistd.c
new file mode 100644
index 0000000..149970e
--- /dev/null
+++ b/jpeg-6c/jdapistd.c
@@ -0,0 +1,386 @@
+/*
+ * jdapistd.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains application interface code for the decompression half
+ * of the JPEG library. These are the "standard" API routines that are
+ * used in the normal full-decompression case. They are not used by a
+ * transcoding-only application. Note that if an application links in
+ * jpeg_start_decompress, it will end up linking in the entire decompressor.
+ * We thus must separate this file from jdapimin.c to avoid linking the
+ * whole decompression library into a transcoder.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Forward declarations */
+LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
+
+
+/*
+ * Decompression initialization.
+ * jpeg_read_header must be completed before calling this.
+ *
+ * If a multipass operating mode was selected, this will do all but the
+ * last pass, and thus may take a great deal of time.
+ *
+ * Returns FALSE if suspended. The return value need be inspected only if
+ * a suspending data source is used.
+ */
+
+GLOBAL(boolean)
+jpeg_start_decompress (j_decompress_ptr cinfo)
+{
+ /* Fix scaling here */
+ if (cinfo->data_precision == cinfo->data_precision_other)
+ cinfo->shft = 0;
+ /* Warn now if scaled */
+ if (cinfo->shft != 0) WARNMS2(cinfo, JWRN_SCALED,
+ cinfo->data_precision, cinfo->data_precision_other);
+
+ if (cinfo->global_state == DSTATE_READY) {
+ /* First call: initialize master control, select active modules */
+ jinit_master_decompress(cinfo);
+ if (cinfo->buffered_image) {
+ /* No more work here; expecting jpeg_start_output next */
+ cinfo->global_state = DSTATE_BUFIMAGE;
+ return TRUE;
+ }
+ cinfo->global_state = DSTATE_PRELOAD;
+ }
+ if (cinfo->global_state == DSTATE_PRELOAD) {
+ /* If file has multiple scans, absorb them all into the coef buffer */
+ if (cinfo->inputctl->has_multiple_scans) {
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ for (;;) {
+ int retcode;
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL)
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ /* Absorb some more input */
+ retcode = (*cinfo->inputctl->consume_input) (cinfo);
+ if (retcode == JPEG_SUSPENDED)
+ return FALSE;
+ if (retcode == JPEG_REACHED_EOI)
+ break;
+ /* Advance progress counter if appropriate */
+ if (cinfo->progress != NULL &&
+ (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
+ if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
+ /* jdmaster underestimated number of scans; ratchet up one scan */
+ cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
+ }
+ }
+ }
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
+ }
+ cinfo->output_scan_number = cinfo->input_scan_number;
+ } else if (cinfo->global_state != DSTATE_PRESCAN)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ /* Perform any dummy output passes, and set up for the final pass */
+ return output_pass_setup(cinfo);
+}
+
+
+/*
+ * Set up for an output pass, and perform any dummy pass(es) needed.
+ * Common subroutine for jpeg_start_decompress and jpeg_start_output.
+ * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
+ * Exit: If done, returns TRUE and sets global_state for proper output mode.
+ * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
+ */
+
+LOCAL(boolean)
+output_pass_setup (j_decompress_ptr cinfo)
+{
+ if (cinfo->global_state != DSTATE_PRESCAN) {
+ /* First call: do pass setup */
+ (*cinfo->master->prepare_for_output_pass) (cinfo);
+ cinfo->output_scanline = 0;
+ cinfo->global_state = DSTATE_PRESCAN;
+ }
+ /* Loop over any required dummy passes */
+ while (cinfo->master->is_dummy_pass) {
+#ifdef QUANT_2PASS_SUPPORTED
+ /* Crank through the dummy pass */
+ while (cinfo->output_scanline < cinfo->output_height) {
+ JDIMENSION last_scanline;
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->output_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->output_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+ /* Process some data */
+ last_scanline = cinfo->output_scanline;
+ (*cinfo->mainp->process_data) (cinfo, (JSAMPARRAY16) NULL,
+ &cinfo->output_scanline, (JDIMENSION) 0);
+ if (cinfo->output_scanline == last_scanline)
+ return FALSE; /* No progress made, must suspend */
+ }
+ /* Finish up dummy pass, and set up for another one */
+ (*cinfo->master->finish_output_pass) (cinfo);
+ (*cinfo->master->prepare_for_output_pass) (cinfo);
+ cinfo->output_scanline = 0;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif /* QUANT_2PASS_SUPPORTED */
+ }
+ /* Ready for application to drive output pass through
+ * jpeg_read_scanlines or jpeg_read_raw_data.
+ */
+ cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
+ return TRUE;
+}
+
+
+/*
+ * Read some scanlines of data from the JPEG decompressor.
+ *
+ * The return value will be the number of lines actually read.
+ * This may be less than the number requested in several cases,
+ * including bottom of image, data source suspension, and operating
+ * modes that emit multiple scanlines at a time.
+ *
+ * Note: we warn about excess calls to jpeg_read_scanlines() since
+ * this likely signals an application programmer error. However,
+ * an oversize buffer (max_lines > scanlines remaining) is not an error.
+ */
+
+GLOBAL(JDIMENSION)
+jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
+ JDIMENSION max_lines)
+{
+ JDIMENSION row_ctr;
+ JSAMPARRAY16 scanlines16;
+ JDIMENSION max_lines_buffer;
+ register JDIMENSION col, width = 0;
+ register JSAMPLE16 *temp_buf_ptr;
+ register JSAMPLE16 *out_buf16_row_ptr;
+ register JSAMPLE *out_buf_row_ptr;
+ register int rshft;
+ int line;
+
+ if (cinfo->global_state != DSTATE_SCANNING)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ if (cinfo->output_scanline >= cinfo->output_height) {
+ WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+ return 0;
+ }
+
+ /* Deal with 8 bit outputs and scaling. */
+ max_lines_buffer = max_lines;
+ if ((cinfo->shft != 0) || (cinfo->buffer_size_char)) {
+ /* Create a data buffer <= DCTSIZE */
+ if (max_lines_buffer > DCTSIZE) max_lines_buffer = DCTSIZE;
+ width = cinfo->output_width * cinfo->output_components;
+ scanlines16 = (JSAMPARRAY16)(cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE_BUF, (JDIMENSION) width *
+ SIZEOF(JSAMPLE16), max_lines_buffer);
+
+ } else { /* Short buffer, no scalling, just cast. */
+ scanlines16 = (JSAMPARRAY16)scanlines;
+ }
+
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->output_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->output_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+
+ /* Process some data */
+ row_ctr = 0;
+ (*cinfo->mainp->process_data) (cinfo, scanlines16, &row_ctr, max_lines_buffer);
+ cinfo->output_scanline += row_ctr;
+
+ /* Copy the buffer if needed. */
+ rshft = cinfo->shft;
+ if (cinfo->buffer_size_char) {
+ for (line = 0; line < row_ctr; line++) {
+ temp_buf_ptr = scanlines16[line];
+ out_buf_row_ptr = scanlines[line];
+ if (rshft == 0 ) { /* Faster */
+ for (col = 0; col < width; col++) {
+ *out_buf_row_ptr++ = *temp_buf_ptr++;
+ }
+ } else if (rshft > 0) { /* Shift data. */
+ for (col = 0; col < width; col++) {
+ *out_buf_row_ptr++ = (*temp_buf_ptr++ >> rshft);
+ }
+ } else { /* Shift data the other way. */
+ rshft = -rshft;
+ for (col = 0; col < width; col++) {
+ *out_buf_row_ptr++ = (*temp_buf_ptr++ << rshft);
+ }
+ }
+ }
+ } else if ( rshft != 0) { /* 16 bit shifted. */
+ for (line = 0; line < row_ctr; line++) {
+ temp_buf_ptr = scanlines16[line];
+ out_buf16_row_ptr = (JSAMPLE16 *)scanlines[line];
+ if (rshft > 0) { /* Shift data. */
+ for (col = 0; col < width; col++) {
+ *temp_buf_ptr++ = (*out_buf16_row_ptr++ >> rshft);
+ }
+ } else { /* Shift data the other way. */
+ rshft = -rshft;
+ for (col = 0; col < width; col++) {
+ *temp_buf_ptr++ = (*out_buf16_row_ptr++ << rshft);
+ }
+ }
+ }
+ }
+
+ /* Free the buffer if used. */
+ if ( scanlines16 != (JSAMPARRAY16)scanlines ) {
+ cinfo->mem->free_pool ((j_common_ptr)cinfo, JPOOL_IMAGE_BUF);
+ scanlines16 = NULL;
+ }
+
+ return row_ctr;
+}
+
+
+/*
+ * Alternate entry point to read raw data.
+ * Processes exactly one iMCU row per call, unless suspended.
+ */
+
+GLOBAL(JDIMENSION)
+jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
+ JDIMENSION max_lines)
+{
+ JDIMENSION lines_per_iMCU_row;
+ JSAMPIMAGE16 data16;
+ register JDIMENSION col, row;
+ register int component;
+ register JSAMPLE *out_buf_row_ptr;
+ register JSAMPLE16 *in_buf_row_ptr;
+
+ if (cinfo->global_state != DSTATE_RAW_OK)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ if (cinfo->output_scanline >= cinfo->output_height) {
+ WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+ return 0;
+ }
+
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->pass_counter = (long) cinfo->output_scanline;
+ cinfo->progress->pass_limit = (long) cinfo->output_height;
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ }
+
+ /* Verify that at least one iMCU row can be returned. */
+ lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_codec_data_unit;
+ if (max_lines < lines_per_iMCU_row)
+ ERREXIT(cinfo, JERR_BUFFER_SIZE);
+
+ /* Check user's buffer size. */
+ if (cinfo->buffer_size_char && (cinfo->data_precision_other <= 8)) { /* Defaults are true */
+ /* Make a 16 bit image buffer */
+ data16 = (JSAMPIMAGE16)(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE_BUF,
+ cinfo->output_components * SIZEOF(JSAMPARRAY16));
+ for (component = 0; component < cinfo->output_components; component++) {
+ data16[component] = (JSAMPARRAY16)(cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE_BUF, (JDIMENSION) cinfo->output_width *
+ SIZEOF(JSAMPLE16), max_lines);
+ }
+ } else data16 = (JSAMPIMAGE16)data; /* Is a 16 bit buffer */
+
+ /* Decompress directly into user's buffer. */
+ if (! (*cinfo->codec->decompress_data) (cinfo, (JSAMPIMAGE16)data16)) {
+ if (data16 != (JSAMPIMAGE16)data) {
+ cinfo->mem->free_pool ((j_common_ptr)cinfo, JPOOL_IMAGE_BUF);
+ data16 = NULL;
+ }
+ return 0; /* suspension forced, can do nothing more */
+ }
+
+ /* OK, we processed one iMCU row. */
+ /* If needed, copy the data. */
+ if (data16 != (JSAMPIMAGE16)data) {
+ for (component = 0; component < cinfo->output_components; component++) {
+ for (row = 0; row < lines_per_iMCU_row; row++) {
+ out_buf_row_ptr = data[component][row];
+ in_buf_row_ptr = data16[component][row];
+ for (col = 0; col < cinfo->output_width; col++) {
+ *out_buf_row_ptr++ = (JSAMPLE)(*in_buf_row_ptr++ & 0xFF);
+ }
+ }
+ }
+ cinfo->mem->free_pool ((j_common_ptr)cinfo, JPOOL_IMAGE_BUF);
+ data16 = NULL;
+ }
+ cinfo->output_scanline += lines_per_iMCU_row;
+ return lines_per_iMCU_row;
+}
+
+
+/* Additional entry points for buffered-image mode. */
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+
+/*
+ * Initialize for an output pass in buffered-image mode.
+ */
+
+GLOBAL(boolean)
+jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
+{
+ if (cinfo->global_state != DSTATE_BUFIMAGE &&
+ cinfo->global_state != DSTATE_PRESCAN)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ /* Limit scan number to valid range */
+ if (scan_number <= 0)
+ scan_number = 1;
+ if (cinfo->inputctl->eoi_reached &&
+ scan_number > cinfo->input_scan_number)
+ scan_number = cinfo->input_scan_number;
+ cinfo->output_scan_number = scan_number;
+ /* Perform any dummy output passes, and set up for the real pass */
+ return output_pass_setup(cinfo);
+}
+
+
+/*
+ * Finish up after an output pass in buffered-image mode.
+ *
+ * Returns FALSE if suspended. The return value need be inspected only if
+ * a suspending data source is used.
+ */
+
+GLOBAL(boolean)
+jpeg_finish_output (j_decompress_ptr cinfo)
+{
+ if ((cinfo->global_state == DSTATE_SCANNING ||
+ cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
+ /* Terminate this pass. */
+ /* We do not require the whole pass to have been completed. */
+ (*cinfo->master->finish_output_pass) (cinfo);
+ cinfo->global_state = DSTATE_BUFPOST;
+ } else if (cinfo->global_state != DSTATE_BUFPOST) {
+ /* BUFPOST = repeat call after a suspension, anything else is error */
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ }
+ /* Read markers looking for SOS or EOI */
+ while (cinfo->input_scan_number <= cinfo->output_scan_number &&
+ ! cinfo->inputctl->eoi_reached) {
+ if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
+ return FALSE; /* Suspend, come back later */
+ }
+ cinfo->global_state = DSTATE_BUFIMAGE;
+ return TRUE;
+}
+
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
diff --git a/jpeg-6c/jdatadst.c b/jpeg-6c/jdatadst.c
new file mode 100644
index 0000000..a8f6fb0
--- /dev/null
+++ b/jpeg-6c/jdatadst.c
@@ -0,0 +1,151 @@
+/*
+ * jdatadst.c
+ *
+ * Copyright (C) 1994-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains compression data destination routines for the case of
+ * emitting JPEG data to a file (or any stdio stream). While these routines
+ * are sufficient for most applications, some will want to use a different
+ * destination manager.
+ * IMPORTANT: we assume that fwrite() will correctly transcribe an array of
+ * JOCTETs into 8-bit-wide elements on external storage. If char is wider
+ * than 8 bits on your machine, you may need to do some tweaking.
+ */
+
+/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jerror.h"
+
+
+/* Expanded data destination object for stdio output */
+
+typedef struct {
+ struct jpeg_destination_mgr pub; /* public fields */
+
+ FILE * outfile; /* target stream */
+ JOCTET * buffer; /* start of buffer */
+} my_destination_mgr;
+
+typedef my_destination_mgr * my_dest_ptr;
+
+#define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */
+
+
+/*
+ * Initialize destination --- called by jpeg_start_compress
+ * before any data is actually written.
+ */
+
+METHODDEF(void)
+init_destination (j_compress_ptr cinfo)
+{
+ my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
+
+ /* Allocate the output buffer --- it will be released when done with image */
+ dest->buffer = (JOCTET *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ OUTPUT_BUF_SIZE * SIZEOF(JOCTET));
+
+ dest->pub.next_output_byte = dest->buffer;
+ dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
+}
+
+
+/*
+ * Empty the output buffer --- called whenever buffer fills up.
+ *
+ * In typical applications, this should write the entire output buffer
+ * (ignoring the current state of next_output_byte & free_in_buffer),
+ * reset the pointer & count to the start of the buffer, and return TRUE
+ * indicating that the buffer has been dumped.
+ *
+ * In applications that need to be able to suspend compression due to output
+ * overrun, a FALSE return indicates that the buffer cannot be emptied now.
+ * In this situation, the compressor will return to its caller (possibly with
+ * an indication that it has not accepted all the supplied scanlines). The
+ * application should resume compression after it has made more room in the
+ * output buffer. Note that there are substantial restrictions on the use of
+ * suspension --- see the documentation.
+ *
+ * When suspending, the compressor will back up to a convenient restart point
+ * (typically the start of the current MCU). next_output_byte & free_in_buffer
+ * indicate where the restart point will be if the current call returns FALSE.
+ * Data beyond this point will be regenerated after resumption, so do not
+ * write it out when emptying the buffer externally.
+ */
+
+METHODDEF(boolean)
+empty_output_buffer (j_compress_ptr cinfo)
+{
+ my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
+
+ if (JFWRITE(dest->outfile, dest->buffer, OUTPUT_BUF_SIZE) !=
+ (size_t) OUTPUT_BUF_SIZE)
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+
+ dest->pub.next_output_byte = dest->buffer;
+ dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
+
+ return TRUE;
+}
+
+
+/*
+ * Terminate destination --- called by jpeg_finish_compress
+ * after all data has been written. Usually needs to flush buffer.
+ *
+ * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
+ * application must deal with any cleanup that should happen even
+ * for error exit.
+ */
+
+METHODDEF(void)
+term_destination (j_compress_ptr cinfo)
+{
+ my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
+ size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
+
+ /* Write any data remaining in the buffer */
+ if (datacount > 0) {
+ if (JFWRITE(dest->outfile, dest->buffer, datacount) != datacount)
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+ }
+ fflush(dest->outfile);
+ /* Make sure we wrote the output file OK */
+ if (ferror(dest->outfile))
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+}
+
+
+/*
+ * Prepare for output to a stdio stream.
+ * The caller must have already opened the stream, and is responsible
+ * for closing it after finishing compression.
+ */
+
+GLOBAL(void)
+jpeg_stdio_dest (j_compress_ptr cinfo, FILE * outfile)
+{
+ my_dest_ptr dest;
+
+ /* The destination object is made permanent so that multiple JPEG images
+ * can be written to the same file without re-executing jpeg_stdio_dest.
+ * This makes it dangerous to use this manager and a different destination
+ * manager serially with the same JPEG object, because their private object
+ * sizes may be different. Caveat programmer.
+ */
+ if (cinfo->dest == NULL) { /* first time for this JPEG object? */
+ cinfo->dest = (struct jpeg_destination_mgr *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(my_destination_mgr));
+ }
+
+ dest = (my_dest_ptr) cinfo->dest;
+ dest->pub.init_destination = init_destination;
+ dest->pub.empty_output_buffer = empty_output_buffer;
+ dest->pub.term_destination = term_destination;
+ dest->outfile = outfile;
+}
diff --git a/jpeg-6c/jdatasrc.c b/jpeg-6c/jdatasrc.c
new file mode 100644
index 0000000..edc752b
--- /dev/null
+++ b/jpeg-6c/jdatasrc.c
@@ -0,0 +1,212 @@
+/*
+ * jdatasrc.c
+ *
+ * Copyright (C) 1994-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains decompression data source routines for the case of
+ * reading JPEG data from a file (or any stdio stream). While these routines
+ * are sufficient for most applications, some will want to use a different
+ * source manager.
+ * IMPORTANT: we assume that fread() will correctly transcribe an array of
+ * JOCTETs from 8-bit-wide elements on external storage. If char is wider
+ * than 8 bits on your machine, you may need to do some tweaking.
+ */
+
+/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jerror.h"
+
+
+/* Expanded data source object for stdio input */
+
+typedef struct {
+ struct jpeg_source_mgr pub; /* public fields */
+
+ FILE * infile; /* source stream */
+ JOCTET * buffer; /* start of buffer */
+ boolean start_of_file; /* have we gotten any data yet? */
+} my_source_mgr;
+
+typedef my_source_mgr * my_src_ptr;
+
+#define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
+
+
+/*
+ * Initialize source --- called by jpeg_read_header
+ * before any data is actually read.
+ */
+
+METHODDEF(void)
+init_source (j_decompress_ptr cinfo)
+{
+ my_src_ptr src = (my_src_ptr) cinfo->src;
+
+ /* We reset the empty-input-file flag for each image,
+ * but we don't clear the input buffer.
+ * This is correct behavior for reading a series of images from one source.
+ */
+ src->start_of_file = TRUE;
+}
+
+
+/*
+ * Fill the input buffer --- called whenever buffer is emptied.
+ *
+ * In typical applications, this should read fresh data into the buffer
+ * (ignoring the current state of next_input_byte & bytes_in_buffer),
+ * reset the pointer & count to the start of the buffer, and return TRUE
+ * indicating that the buffer has been reloaded. It is not necessary to
+ * fill the buffer entirely, only to obtain at least one more byte.
+ *
+ * There is no such thing as an EOF return. If the end of the file has been
+ * reached, the routine has a choice of ERREXIT() or inserting fake data into
+ * the buffer. In most cases, generating a warning message and inserting a
+ * fake EOI marker is the best course of action --- this will allow the
+ * decompressor to output however much of the image is there. However,
+ * the resulting error message is misleading if the real problem is an empty
+ * input file, so we handle that case specially.
+ *
+ * In applications that need to be able to suspend compression due to input
+ * not being available yet, a FALSE return indicates that no more data can be
+ * obtained right now, but more may be forthcoming later. In this situation,
+ * the decompressor will return to its caller (with an indication of the
+ * number of scanlines it has read, if any). The application should resume
+ * decompression after it has loaded more data into the input buffer. Note
+ * that there are substantial restrictions on the use of suspension --- see
+ * the documentation.
+ *
+ * When suspending, the decompressor will back up to a convenient restart point
+ * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
+ * indicate where the restart point will be if the current call returns FALSE.
+ * Data beyond this point must be rescanned after resumption, so move it to
+ * the front of the buffer rather than discarding it.
+ */
+
+METHODDEF(boolean)
+fill_input_buffer (j_decompress_ptr cinfo)
+{
+ my_src_ptr src = (my_src_ptr) cinfo->src;
+ size_t nbytes;
+
+ nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
+
+ if (nbytes <= 0) {
+ if (src->start_of_file) /* Treat empty input file as fatal error */
+ ERREXIT(cinfo, JERR_INPUT_EMPTY);
+ WARNMS(cinfo, JWRN_JPEG_EOF);
+ /* Insert a fake EOI marker */
+ src->buffer[0] = (JOCTET) 0xFF;
+ src->buffer[1] = (JOCTET) JPEG_EOI;
+ nbytes = 2;
+ }
+
+ src->pub.next_input_byte = src->buffer;
+ src->pub.bytes_in_buffer = nbytes;
+ src->start_of_file = FALSE;
+
+ return TRUE;
+}
+
+
+/*
+ * Skip data --- used to skip over a potentially large amount of
+ * uninteresting data (such as an APPn marker).
+ *
+ * Writers of suspendable-input applications must note that skip_input_data
+ * is not granted the right to give a suspension return. If the skip extends
+ * beyond the data currently in the buffer, the buffer can be marked empty so
+ * that the next read will cause a fill_input_buffer call that can suspend.
+ * Arranging for additional bytes to be discarded before reloading the input
+ * buffer is the application writer's problem.
+ */
+
+METHODDEF(void)
+skip_input_data (j_decompress_ptr cinfo, long num_bytes)
+{
+ my_src_ptr src = (my_src_ptr) cinfo->src;
+
+ /* Just a dumb implementation for now. Could use fseek() except
+ * it doesn't work on pipes. Not clear that being smart is worth
+ * any trouble anyway --- large skips are infrequent.
+ */
+ if (num_bytes > 0) {
+ while (num_bytes > (long) src->pub.bytes_in_buffer) {
+ num_bytes -= (long) src->pub.bytes_in_buffer;
+ (void) fill_input_buffer(cinfo);
+ /* note we assume that fill_input_buffer will never return FALSE,
+ * so suspension need not be handled.
+ */
+ }
+ src->pub.next_input_byte += (size_t) num_bytes;
+ src->pub.bytes_in_buffer -= (size_t) num_bytes;
+ }
+}
+
+
+/*
+ * An additional method that can be provided by data source modules is the
+ * resync_to_restart method for error recovery in the presence of RST markers.
+ * For the moment, this source module just uses the default resync method
+ * provided by the JPEG library. That method assumes that no backtracking
+ * is possible.
+ */
+
+
+/*
+ * Terminate source --- called by jpeg_finish_decompress
+ * after all data has been read. Often a no-op.
+ *
+ * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
+ * application must deal with any cleanup that should happen even
+ * for error exit.
+ */
+
+METHODDEF(void)
+term_source (j_decompress_ptr cinfo)
+{
+ /* no work necessary here */
+}
+
+
+/*
+ * Prepare for input from a stdio stream.
+ * The caller must have already opened the stream, and is responsible
+ * for closing it after finishing decompression.
+ */
+
+GLOBAL(void)
+jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
+{
+ my_src_ptr src;
+
+ /* The source object and input buffer are made permanent so that a series
+ * of JPEG images can be read from the same file by calling jpeg_stdio_src
+ * only before the first one. (If we discarded the buffer at the end of
+ * one image, we'd likely lose the start of the next one.)
+ * This makes it unsafe to use this manager and a different source
+ * manager serially with the same JPEG object. Caveat programmer.
+ */
+ if (cinfo->src == NULL) { /* first time for this JPEG object? */
+ cinfo->src = (struct jpeg_source_mgr *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(my_source_mgr));
+ src = (my_src_ptr) cinfo->src;
+ src->buffer = (JOCTET *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ INPUT_BUF_SIZE * SIZEOF(JOCTET));
+ }
+
+ src = (my_src_ptr) cinfo->src;
+ src->pub.init_source = init_source;
+ src->pub.fill_input_buffer = fill_input_buffer;
+ src->pub.skip_input_data = skip_input_data;
+ src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
+ src->pub.term_source = term_source;
+ src->infile = infile;
+ src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
+ src->pub.next_input_byte = NULL; /* until buffer loaded */
+}
diff --git a/jpeg-6c/jdcoefct.c b/jpeg-6c/jdcoefct.c
new file mode 100644
index 0000000..d5c4497
--- /dev/null
+++ b/jpeg-6c/jdcoefct.c
@@ -0,0 +1,744 @@
+/*
+ * jdcoefct.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the coefficient buffer controller for decompression.
+ * This controller is the top level of the lossy JPEG decompressor proper.
+ * The coefficient buffer lies between entropy decoding and inverse-DCT steps.
+ *
+ * In buffered-image mode, this controller is the interface between
+ * input-oriented processing and output-oriented processing.
+ * Also, the input side (only) is used when reading a file for transcoding.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h"
+
+/* Block smoothing is only applicable for progressive JPEG, so: */
+#ifndef D_PROGRESSIVE_SUPPORTED
+#undef BLOCK_SMOOTHING_SUPPORTED
+#endif
+
+/* Private buffer controller object */
+
+typedef struct {
+ /* These variables keep track of the current location of the input side. */
+ /* cinfo->input_iMCU_row is also used for this. */
+ JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
+ int MCU_vert_offset; /* counts MCU rows within iMCU row */
+ int MCU_rows_per_iMCU_row; /* number of such rows needed */
+
+ /* The output side's location is represented by cinfo->output_iMCU_row. */
+
+ /* In single-pass modes, it's sufficient to buffer just one MCU.
+ * We allocate a workspace of D_MAX_DATA_UNITS_IN_MCU coefficient blocks,
+ * and let the entropy decoder write into that workspace each time.
+ * (On 80x86, the workspace is FAR even though it's not really very big;
+ * this is to keep the module interfaces unchanged when a large coefficient
+ * buffer is necessary.)
+ * In multi-pass modes, this array points to the current MCU's blocks
+ * within the virtual arrays; it is used only by the input side.
+ */
+ JBLOCKROW MCU_buffer[D_MAX_DATA_UNITS_IN_MCU];
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ /* In multi-pass modes, we need a virtual block array for each component. */
+ jvirt_barray_ptr whole_image[MAX_COMPONENTS];
+#endif
+
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+ /* When doing block smoothing, we latch coefficient Al values here */
+ int * coef_bits_latch;
+#define SAVED_COEFS 6 /* we save coef_bits[0..5] */
+#endif
+} d_coef_controller;
+
+typedef d_coef_controller * d_coef_ptr;
+
+/* Forward declarations */
+METHODDEF(int) decompress_onepass
+ JPP((j_decompress_ptr cinfo, JSAMPIMAGE16 output_buf));
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+METHODDEF(int) decompress_data
+ JPP((j_decompress_ptr cinfo, JSAMPIMAGE16 output_buf));
+#endif
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
+METHODDEF(int) decompress_smooth_data
+ JPP((j_decompress_ptr cinfo, JSAMPIMAGE16 output_buf));
+#endif
+
+
+LOCAL(void)
+start_iMCU_row (j_decompress_ptr cinfo)
+/* Reset within-iMCU-row counters for a new row (input side) */
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+ * But at the bottom of the image, process only what's left.
+ */
+ if (cinfo->comps_in_scan > 1) {
+ coef->MCU_rows_per_iMCU_row = 1;
+ } else {
+ if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
+ else
+ coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
+ }
+
+ coef->MCU_ctr = 0;
+ coef->MCU_vert_offset = 0;
+}
+
+
+/*
+ * Initialize for an input processing pass.
+ */
+
+METHODDEF(void)
+start_input_pass (j_decompress_ptr cinfo)
+{
+ cinfo->input_iMCU_row = 0;
+ start_iMCU_row(cinfo);
+}
+
+
+/*
+ * Initialize for an output processing pass.
+ */
+
+METHODDEF(void)
+start_output_pass (j_decompress_ptr cinfo)
+{
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+/* d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;*/
+
+ /* If multipass, check to see whether to use block smoothing on this pass */
+ if (lossyd->coef_arrays != NULL) {
+ if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
+ lossyd->pub.decompress_data = decompress_smooth_data;
+ else
+ lossyd->pub.decompress_data = decompress_data;
+ }
+#endif
+ cinfo->output_iMCU_row = 0;
+}
+
+
+/*
+ * Decompress and return some data in the single-pass case.
+ * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
+ * Input and output must run in lockstep since we have only a one-MCU buffer.
+ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
+ *
+ * NB: output_buf contains a plane for each component in image,
+ * which we index according to the component's SOF position.
+ */
+
+METHODDEF(int)
+decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE16 output_buf)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ int blkn, ci, xindex, yindex, yoffset, useful_width;
+ JSAMPARRAY16 output_ptr;
+ JDIMENSION start_col, output_col;
+ jpeg_component_info *compptr;
+ inverse_DCT_method_ptr inverse_DCT;
+
+ /* Loop to process as much as one whole iMCU row */
+ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
+ yoffset++) {
+ for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
+ MCU_col_num++) {
+ /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
+ jzero_far((void FAR *) coef->MCU_buffer[0],
+ (size_t) (cinfo->data_units_in_MCU * SIZEOF(JBLOCK)));
+ if (! (*lossyd->entropy_decode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->MCU_ctr = MCU_col_num;
+ return JPEG_SUSPENDED;
+ }
+ /* Determine where data should go in output_buf and do the IDCT thing.
+ * We skip dummy blocks at the right and bottom edges (but blkn gets
+ * incremented past them!). Note the inner loop relies on having
+ * allocated the MCU_buffer[] blocks sequentially.
+ */
+ blkn = 0; /* index of current DCT block within MCU */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* Don't bother to IDCT an uninteresting component. */
+ if (! compptr->component_needed) {
+ blkn += compptr->MCU_data_units;
+ continue;
+ }
+ inverse_DCT = lossyd->inverse_DCT[compptr->component_index];
+ useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
+ : compptr->last_col_width;
+ output_ptr = output_buf[compptr->component_index] +
+ yoffset * compptr->codec_data_unit;
+ start_col = MCU_col_num * compptr->MCU_sample_width;
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ if (cinfo->input_iMCU_row < last_iMCU_row ||
+ yoffset+yindex < compptr->last_row_height) {
+ output_col = start_col;
+ for (xindex = 0; xindex < useful_width; xindex++) {
+ (*inverse_DCT) (cinfo, compptr,
+ (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
+ output_ptr, output_col);
+ output_col += compptr->codec_data_unit;
+ }
+ }
+ blkn += compptr->MCU_width;
+ output_ptr += compptr->codec_data_unit;
+ }
+ }
+ }
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ coef->MCU_ctr = 0;
+ }
+ /* Completed the iMCU row, advance counters for next one */
+ cinfo->output_iMCU_row++;
+ if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
+ start_iMCU_row(cinfo);
+ return JPEG_ROW_COMPLETED;
+ }
+ /* Completed the scan */
+ (*cinfo->inputctl->finish_input_pass) (cinfo);
+ return JPEG_SCAN_COMPLETED;
+}
+
+
+/*
+ * Dummy consume-input routine for single-pass operation.
+ */
+
+METHODDEF(int)
+dummy_consume_data (j_decompress_ptr cinfo)
+{
+ return JPEG_SUSPENDED; /* Always indicate nothing was done */
+}
+
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+
+/*
+ * Consume input data and store it in the full-image coefficient buffer.
+ * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
+ * ie, v_samp_factor block rows for each component in the scan.
+ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
+ */
+
+METHODDEF(int)
+consume_data (j_decompress_ptr cinfo)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ int blkn, ci, xindex, yindex, yoffset;
+ JDIMENSION start_col;
+ JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
+ JBLOCKROW buffer_ptr;
+ jpeg_component_info *compptr;
+
+ /* Align the virtual buffers for the components used in this scan. */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ buffer[ci] = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
+ cinfo->input_iMCU_row * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ /* Note: entropy decoder expects buffer to be zeroed,
+ * but this is handled automatically by the memory manager
+ * because we requested a pre-zeroed array.
+ */
+ }
+
+ /* Loop to process one whole iMCU row */
+ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
+ yoffset++) {
+ for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
+ MCU_col_num++) {
+ /* Construct list of pointers to DCT blocks belonging to this MCU */
+ blkn = 0; /* index of current DCT block within MCU */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ start_col = MCU_col_num * compptr->MCU_width;
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
+ for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
+ coef->MCU_buffer[blkn++] = buffer_ptr++;
+ }
+ }
+ }
+ /* Try to fetch the MCU. */
+ if (! (*lossyd->entropy_decode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->MCU_ctr = MCU_col_num;
+ return JPEG_SUSPENDED;
+ }
+ }
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ coef->MCU_ctr = 0;
+ }
+ /* Completed the iMCU row, advance counters for next one */
+ if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
+ start_iMCU_row(cinfo);
+ return JPEG_ROW_COMPLETED;
+ }
+ /* Completed the scan */
+ (*cinfo->inputctl->finish_input_pass) (cinfo);
+ return JPEG_SCAN_COMPLETED;
+}
+
+
+/*
+ * Decompress and return some data in the multi-pass case.
+ * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
+ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
+ *
+ * NB: output_buf contains a plane for each component in image.
+ */
+
+METHODDEF(int)
+decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE16 output_buf)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION block_num;
+ int ci, block_row, block_rows;
+ JBLOCKARRAY buffer;
+ JBLOCKROW buffer_ptr;
+ JSAMPARRAY16 output_ptr;
+ JDIMENSION output_col;
+ jpeg_component_info *compptr;
+ inverse_DCT_method_ptr inverse_DCT;
+
+ /* Force some input to be done if we are getting ahead of the input. */
+ while (cinfo->input_scan_number < cinfo->output_scan_number ||
+ (cinfo->input_scan_number == cinfo->output_scan_number &&
+ cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
+ if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
+ return JPEG_SUSPENDED;
+ }
+
+ /* OK, output from the virtual arrays. */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Don't bother to IDCT an uninteresting component. */
+ if (! compptr->component_needed)
+ continue;
+ /* Align the virtual buffer for this component. */
+ buffer = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[ci],
+ cinfo->output_iMCU_row * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ /* Count non-dummy DCT block rows in this iMCU row. */
+ if (cinfo->output_iMCU_row < last_iMCU_row)
+ block_rows = compptr->v_samp_factor;
+ else {
+ /* NB: can't use last_row_height here; it is input-side-dependent! */
+ block_rows = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ }
+ inverse_DCT = lossyd->inverse_DCT[ci];
+ output_ptr = output_buf[ci];
+ /* Loop over all DCT blocks to be processed. */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+ buffer_ptr = buffer[block_row];
+ output_col = 0;
+ for (block_num = 0; block_num < compptr->width_in_data_units; block_num++) {
+ (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
+ output_ptr, output_col);
+ buffer_ptr++;
+ output_col += compptr->codec_data_unit;
+ }
+ output_ptr += compptr->codec_data_unit;
+ }
+ }
+
+ if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
+ return JPEG_ROW_COMPLETED;
+ return JPEG_SCAN_COMPLETED;
+}
+
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
+
+
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+
+/*
+ * This code applies interblock smoothing as described by section K.8
+ * of the JPEG standard: the first 5 AC coefficients are estimated from
+ * the DC values of a DCT block and its 8 neighboring blocks.
+ * We apply smoothing only for progressive JPEG decoding, and only if
+ * the coefficients it can estimate are not yet known to full precision.
+ */
+
+/* Natural-order array positions of the first 5 zigzag-order coefficients */
+#define Q01_POS 1
+#define Q10_POS 8
+#define Q20_POS 16
+#define Q11_POS 9
+#define Q02_POS 2
+
+/*
+ * Determine whether block smoothing is applicable and safe.
+ * We also latch the current states of the coef_bits[] entries for the
+ * AC coefficients; otherwise, if the input side of the decompressor
+ * advances into a new scan, we might think the coefficients are known
+ * more accurately than they really are.
+ */
+
+LOCAL(boolean)
+smoothing_ok (j_decompress_ptr cinfo)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+ boolean smoothing_useful = FALSE;
+ int ci, coefi;
+ jpeg_component_info *compptr;
+ JQUANT_TBL * qtable;
+ int * coef_bits;
+ int * coef_bits_latch;
+
+ if (! cinfo->process == JPROC_PROGRESSIVE || cinfo->coef_bits == NULL)
+ return FALSE;
+
+ /* Allocate latch area if not already done */
+ if (coef->coef_bits_latch == NULL)
+ coef->coef_bits_latch = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->num_components *
+ (SAVED_COEFS * SIZEOF(int)));
+ coef_bits_latch = coef->coef_bits_latch;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* All components' quantization values must already be latched. */
+ if ((qtable = compptr->quant_table) == NULL)
+ return FALSE;
+ /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
+ if (qtable->quantval[0] == 0 ||
+ qtable->quantval[Q01_POS] == 0 ||
+ qtable->quantval[Q10_POS] == 0 ||
+ qtable->quantval[Q20_POS] == 0 ||
+ qtable->quantval[Q11_POS] == 0 ||
+ qtable->quantval[Q02_POS] == 0)
+ return FALSE;
+ /* DC values must be at least partly known for all components. */
+ coef_bits = cinfo->coef_bits[ci];
+ if (coef_bits[0] < 0)
+ return FALSE;
+ /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
+ for (coefi = 1; coefi <= 5; coefi++) {
+ coef_bits_latch[coefi] = coef_bits[coefi];
+ if (coef_bits[coefi] != 0)
+ smoothing_useful = TRUE;
+ }
+ coef_bits_latch += SAVED_COEFS;
+ }
+
+ return smoothing_useful;
+}
+
+
+/*
+ * Variant of decompress_data for use when doing block smoothing.
+ */
+
+METHODDEF(int)
+decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE16 output_buf)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION block_num, last_block_column;
+ int ci, block_row, block_rows, access_rows;
+ JBLOCKARRAY buffer;
+ JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
+ JSAMPARRAY16 output_ptr;
+ JDIMENSION output_col;
+ jpeg_component_info *compptr;
+ inverse_DCT_method_ptr inverse_DCT;
+ boolean first_row, last_row;
+ JBLOCK workspace;
+ int *coef_bits;
+ JQUANT_TBL *quanttbl;
+ INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
+ int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
+ int Al, pred;
+
+ /* Force some input to be done if we are getting ahead of the input. */
+ while (cinfo->input_scan_number <= cinfo->output_scan_number &&
+ ! cinfo->inputctl->eoi_reached) {
+ if (cinfo->input_scan_number == cinfo->output_scan_number) {
+ /* If input is working on current scan, we ordinarily want it to
+ * have completed the current row. But if input scan is DC,
+ * we want it to keep one row ahead so that next block row's DC
+ * values are up to date.
+ */
+ JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
+ if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
+ break;
+ }
+ if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
+ return JPEG_SUSPENDED;
+ }
+
+ /* OK, output from the virtual arrays. */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Don't bother to IDCT an uninteresting component. */
+ if (! compptr->component_needed)
+ continue;
+ /* Count non-dummy DCT block rows in this iMCU row. */
+ if (cinfo->output_iMCU_row < last_iMCU_row) {
+ block_rows = compptr->v_samp_factor;
+ access_rows = block_rows * 2; /* this and next iMCU row */
+ last_row = FALSE;
+ } else {
+ /* NB: can't use last_row_height here; it is input-side-dependent! */
+ block_rows = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ access_rows = block_rows; /* this iMCU row only */
+ last_row = TRUE;
+ }
+ /* Align the virtual buffer for this component. */
+ if (cinfo->output_iMCU_row > 0) {
+ access_rows += compptr->v_samp_factor; /* prior iMCU row too */
+ buffer = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[ci],
+ (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
+ (JDIMENSION) access_rows, FALSE);
+ buffer += compptr->v_samp_factor; /* point to current iMCU row */
+ first_row = FALSE;
+ } else {
+ buffer = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef->whole_image[ci],
+ (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
+ first_row = TRUE;
+ }
+ /* Fetch component-dependent info */
+ coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
+ quanttbl = compptr->quant_table;
+ Q00 = quanttbl->quantval[0];
+ Q01 = quanttbl->quantval[Q01_POS];
+ Q10 = quanttbl->quantval[Q10_POS];
+ Q20 = quanttbl->quantval[Q20_POS];
+ Q11 = quanttbl->quantval[Q11_POS];
+ Q02 = quanttbl->quantval[Q02_POS];
+ inverse_DCT = lossyd->inverse_DCT[ci];
+ output_ptr = output_buf[ci];
+ /* Loop over all DCT blocks to be processed. */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+ buffer_ptr = buffer[block_row];
+ if (first_row && block_row == 0)
+ prev_block_row = buffer_ptr;
+ else
+ prev_block_row = buffer[block_row-1];
+ if (last_row && block_row == block_rows-1)
+ next_block_row = buffer_ptr;
+ else
+ next_block_row = buffer[block_row+1];
+ /* We fetch the surrounding DC values using a sliding-register approach.
+ * Initialize all nine here so as to do the right thing on narrow pics.
+ */
+ DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
+ DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
+ DC7 = DC8 = DC9 = (int) next_block_row[0][0];
+ output_col = 0;
+ last_block_column = compptr->width_in_data_units - 1;
+ for (block_num = 0; block_num <= last_block_column; block_num++) {
+ /* Fetch current DCT block into workspace so we can modify it. */
+ jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
+ /* Update DC values */
+ if (block_num < last_block_column) {
+ DC3 = (int) prev_block_row[1][0];
+ DC6 = (int) buffer_ptr[1][0];
+ DC9 = (int) next_block_row[1][0];
+ }
+ /* Compute coefficient estimates per K.8.
+ * An estimate is applied only if coefficient is still zero,
+ * and is not known to be fully accurate.
+ */
+ /* AC01 */
+ if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
+ num = 36 * Q00 * (DC4 - DC6);
+ if (num >= 0) {
+ pred = (int) (((Q01<<7) + num) / (Q01<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q01<<7) - num) / (Q01<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[1] = (JCOEF) pred;
+ }
+ /* AC10 */
+ if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
+ num = 36 * Q00 * (DC2 - DC8);
+ if (num >= 0) {
+ pred = (int) (((Q10<<7) + num) / (Q10<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q10<<7) - num) / (Q10<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[8] = (JCOEF) pred;
+ }
+ /* AC20 */
+ if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
+ num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
+ if (num >= 0) {
+ pred = (int) (((Q20<<7) + num) / (Q20<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q20<<7) - num) / (Q20<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[16] = (JCOEF) pred;
+ }
+ /* AC11 */
+ if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
+ num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
+ if (num >= 0) {
+ pred = (int) (((Q11<<7) + num) / (Q11<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q11<<7) - num) / (Q11<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[9] = (JCOEF) pred;
+ }
+ /* AC02 */
+ if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
+ num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
+ if (num >= 0) {
+ pred = (int) (((Q02<<7) + num) / (Q02<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ } else {
+ pred = (int) (((Q02<<7) - num) / (Q02<<8));
+ if (Al > 0 && pred >= (1<<Al))
+ pred = (1<<Al)-1;
+ pred = -pred;
+ }
+ workspace[2] = (JCOEF) pred;
+ }
+ /* OK, do the IDCT */
+ (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
+ output_ptr, output_col);
+ /* Advance for next column */
+ DC1 = DC2; DC2 = DC3;
+ DC4 = DC5; DC5 = DC6;
+ DC7 = DC8; DC8 = DC9;
+ buffer_ptr++, prev_block_row++, next_block_row++;
+ output_col += compptr->codec_data_unit;
+ }
+ output_ptr += compptr->codec_data_unit;
+ }
+ }
+
+ if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
+ return JPEG_ROW_COMPLETED;
+ return JPEG_SCAN_COMPLETED;
+}
+
+#endif /* BLOCK_SMOOTHING_SUPPORTED */
+
+
+/*
+ * Initialize coefficient buffer controller.
+ */
+
+GLOBAL(void)
+jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ d_coef_ptr coef;
+
+ coef = (d_coef_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(d_coef_controller));
+ lossyd->coef_private = (void *) coef;
+ lossyd->coef_start_input_pass = start_input_pass;
+ lossyd->coef_start_output_pass = start_output_pass;
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+ coef->coef_bits_latch = NULL;
+#endif
+
+ /* Create the coefficient buffer. */
+ if (need_full_buffer) {
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ /* Allocate a full-image virtual array for each component, */
+ /* padded to a multiple of samp_factor DCT blocks in each direction. */
+ /* Note we ask for a pre-zeroed array. */
+ int ci, access_rows;
+ jpeg_component_info *compptr;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ access_rows = compptr->v_samp_factor;
+#ifdef BLOCK_SMOOTHING_SUPPORTED
+ /* If block smoothing could be used, need a bigger window */
+ if (cinfo->process == JPROC_PROGRESSIVE)
+ access_rows *= 3;
+#endif
+ coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JSAMPLE16),
+ (JDIMENSION) jround_up((long) compptr->height_in_data_units,
+ (long) compptr->v_samp_factor),
+ (JDIMENSION) access_rows);
+ }
+ lossyd->pub.consume_data = consume_data;
+ lossyd->pub.decompress_data = decompress_data;
+ lossyd->coef_arrays = coef->whole_image; /* link to virtual arrays */
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ /* We only need a single-MCU buffer. */
+ JBLOCKROW buffer;
+ int i;
+
+ buffer = (JBLOCKROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ D_MAX_DATA_UNITS_IN_MCU * SIZEOF(JBLOCK));
+ for (i = 0; i < D_MAX_DATA_UNITS_IN_MCU; i++) {
+ coef->MCU_buffer[i] = buffer + i;
+ }
+ lossyd->pub.consume_data = dummy_consume_data;
+ lossyd->pub.decompress_data = decompress_onepass;
+ lossyd->coef_arrays = NULL; /* flag for no virtual arrays */
+ }
+}
diff --git a/jpeg-6c/jdcolor.c b/jpeg-6c/jdcolor.c
new file mode 100644
index 0000000..6d8215c
--- /dev/null
+++ b/jpeg-6c/jdcolor.c
@@ -0,0 +1,397 @@
+/*
+ * jdcolor.c
+ *
+ * Copyright (C) 1991-1997, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains output colorspace conversion routines.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_color_deconverter pub; /* public fields */
+
+ /* Private state for YCC->RGB conversion */
+ int * Cr_r_tab; /* => table for Cr to R conversion */
+ int * Cb_b_tab; /* => table for Cb to B conversion */
+ INT32 * Cr_g_tab; /* => table for Cr to G conversion */
+ INT32 * Cb_g_tab; /* => table for Cb to G conversion */
+} my_color_deconverter;
+
+typedef my_color_deconverter * my_cconvert_ptr;
+
+
+/**************** YCbCr -> RGB conversion: most common case **************/
+
+/*
+ * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
+ * normalized to the range 0..cinfo->maxjsample rather than -0.5 .. 0.5.
+ * The conversion equations to be implemented are therefore
+ * R = Y + 1.40200 * Cr
+ * G = Y - 0.34414 * Cb - 0.71414 * Cr
+ * B = Y + 1.77200 * Cb
+ * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
+ * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
+ *
+ * To avoid floating-point arithmetic, we represent the fractional constants
+ * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
+ * the products by 2^16, with appropriate rounding, to get the correct answer.
+ * Notice that Y, being an integral input, does not contribute any fraction
+ * so it need not participate in the rounding.
+ *
+ * For even more speed, we avoid doing any multiplications in the inner loop
+ * by precalculating the constants times Cb and Cr for all possible values.
+ * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
+ * for 12-bit samples it is still acceptable. It's not very reasonable for
+ * 16-bit samples, but if you want lossless storage you shouldn't be changing
+ * colorspace anyway.
+ * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
+ * values for the G calculation are left scaled up, since we must add them
+ * together before rounding.
+ */
+
+#define SCALEBITS 16 /* speediest right-shift on some machines */
+#define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
+#define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
+
+
+/*
+ * Initialize tables for YCC->RGB colorspace conversion.
+ */
+
+LOCAL(void)
+build_ycc_rgb_table (j_decompress_ptr cinfo)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ int i;
+ INT32 x;
+ SHIFT_TEMPS
+
+ cconvert->Cr_r_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(int));
+ cconvert->Cb_b_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(int));
+ cconvert->Cr_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(INT32));
+ cconvert->Cb_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(INT32));
+
+ for (i = 0, x = -cinfo->centerjsample; i <= cinfo->maxjsample; i++, x++) {
+ /* i is the actual input pixel value, in the range 0..cinfo->maxjsample */
+ /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
+ /* Cr=>R value is nearest int to 1.40200 * x */
+ cconvert->Cr_r_tab[i] = (int)
+ RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
+ /* Cb=>B value is nearest int to 1.77200 * x */
+ cconvert->Cb_b_tab[i] = (int)
+ RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
+ /* Cr=>G value is scaled-up -0.71414 * x */
+ cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
+ /* Cb=>G value is scaled-up -0.34414 * x */
+ /* We also add in ONE_HALF so that need not do it in inner loop */
+ cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
+ }
+}
+
+
+/*
+ * Convert some rows of samples to the output colorspace.
+ *
+ * Note that we change from noninterleaved, one-plane-per-component format
+ * to interleaved-pixel format. The output buffer is therefore three times
+ * as wide as the input buffer.
+ * A starting row offset is provided only for the input buffer. The caller
+ * can easily adjust the passed output_buf value to accommodate any row
+ * offset required on that side.
+ */
+
+METHODDEF(void)
+ycc_rgb_convert (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION input_row,
+ JSAMPARRAY16 output_buf, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int y, cb, cr;
+ register JSAMPROW16 outptr;
+ register JSAMPROW16 inptr0, inptr1, inptr2;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->output_width;
+ /* copy these pointers into registers if possible */
+ register JSAMPLE16 * range_limit = cinfo->sample_range_limit;
+ register int * Crrtab = cconvert->Cr_r_tab;
+ register int * Cbbtab = cconvert->Cb_b_tab;
+ register INT32 * Crgtab = cconvert->Cr_g_tab;
+ register INT32 * Cbgtab = cconvert->Cb_g_tab;
+ SHIFT_TEMPS
+
+ while (--num_rows >= 0) {
+ inptr0 = input_buf[0][input_row];
+ inptr1 = input_buf[1][input_row];
+ inptr2 = input_buf[2][input_row];
+ input_row++;
+ outptr = *output_buf++;
+ for (col = 0; col < num_cols; col++) {
+ y = GETJSAMPLE(inptr0[col]);
+ cb = GETJSAMPLE(inptr1[col]);
+ cr = GETJSAMPLE(inptr2[col]);
+ /* Range-limiting is essential due to noise introduced by DCT losses. */
+ outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
+ outptr[RGB_GREEN] = range_limit[y +
+ ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
+ SCALEBITS))];
+ outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
+ outptr += RGB_PIXELSIZE;
+ }
+ }
+}
+
+
+/**************** Cases other than YCbCr -> RGB **************/
+
+
+/*
+ * Color conversion for no colorspace change: just copy the data,
+ * converting from separate-planes to interleaved representation.
+ */
+
+METHODDEF(void)
+null_convert (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION input_row,
+ JSAMPARRAY16 output_buf, int num_rows)
+{
+ register JSAMPROW16 inptr, outptr;
+ register JDIMENSION count;
+ register int num_components = cinfo->num_components;
+ JDIMENSION num_cols = cinfo->output_width;
+ int ci;
+
+ while (--num_rows >= 0) {
+ for (ci = 0; ci < num_components; ci++) {
+ inptr = input_buf[ci][input_row];
+ outptr = output_buf[0] + ci;
+ for (count = num_cols; count > 0; count--) {
+ *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
+ outptr += num_components;
+ }
+ }
+ input_row++;
+ output_buf++;
+ }
+}
+
+
+/*
+ * Color conversion for grayscale: just copy the data.
+ * This also works for YCbCr -> grayscale conversion, in which
+ * we just copy the Y (luminance) component and ignore chrominance.
+ */
+
+METHODDEF(void)
+grayscale_convert (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION input_row,
+ JSAMPARRAY16 output_buf, int num_rows)
+{
+ jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
+ num_rows, cinfo->output_width);
+}
+
+
+/*
+ * Convert grayscale to RGB: just duplicate the graylevel three times.
+ * This is provided to support applications that don't want to cope
+ * with grayscale as a separate case.
+ */
+
+METHODDEF(void)
+gray_rgb_convert (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION input_row,
+ JSAMPARRAY16 output_buf, int num_rows)
+{
+ register JSAMPROW16 inptr, outptr;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->output_width;
+
+ while (--num_rows >= 0) {
+ inptr = input_buf[0][input_row++];
+ outptr = *output_buf++;
+ for (col = 0; col < num_cols; col++) {
+ /* We can dispense with GETJSAMPLE() here */
+ outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
+ outptr += RGB_PIXELSIZE;
+ }
+ }
+}
+
+
+/*
+ * Adobe-style YCCK->CMYK conversion.
+ * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
+ * conversion as above, while passing K (black) unchanged.
+ * We assume build_ycc_rgb_table has been called.
+ */
+
+METHODDEF(void)
+ycck_cmyk_convert (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION input_row,
+ JSAMPARRAY16 output_buf, int num_rows)
+{
+ my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+ register int y, cb, cr;
+ register JSAMPROW16 outptr;
+ register JSAMPROW16 inptr0, inptr1, inptr2, inptr3;
+ register JDIMENSION col;
+ JDIMENSION num_cols = cinfo->output_width;
+ /* copy these pointers into registers if possible */
+ register JSAMPLE16 * range_limit = cinfo->sample_range_limit;
+ register int * Crrtab = cconvert->Cr_r_tab;
+ register int * Cbbtab = cconvert->Cb_b_tab;
+ register INT32 * Crgtab = cconvert->Cr_g_tab;
+ register INT32 * Cbgtab = cconvert->Cb_g_tab;
+ SHIFT_TEMPS
+
+ while (--num_rows >= 0) {
+ inptr0 = input_buf[0][input_row];
+ inptr1 = input_buf[1][input_row];
+ inptr2 = input_buf[2][input_row];
+ inptr3 = input_buf[3][input_row];
+ input_row++;
+ outptr = *output_buf++;
+ for (col = 0; col < num_cols; col++) {
+ y = GETJSAMPLE(inptr0[col]);
+ cb = GETJSAMPLE(inptr1[col]);
+ cr = GETJSAMPLE(inptr2[col]);
+ /* Range-limiting is essential due to noise introduced by DCT losses. */
+ outptr[0] = range_limit[cinfo->maxjsample - (y + Crrtab[cr])]; /* red */
+ outptr[1] = range_limit[cinfo->maxjsample - (y + /* green */
+ ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
+ SCALEBITS)))];
+ outptr[2] = range_limit[cinfo->maxjsample - (y + Cbbtab[cb])]; /* blue */
+ /* K passes through unchanged */
+ outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
+ outptr += 4;
+ }
+ }
+}
+
+
+/*
+ * Empty method for start_pass.
+ */
+
+METHODDEF(void)
+start_pass_dcolor (j_decompress_ptr cinfo)
+{
+ /* no work needed */
+}
+
+
+/*
+ * Module initialization routine for output colorspace conversion.
+ */
+
+GLOBAL(void)
+jinit_color_deconverter (j_decompress_ptr cinfo)
+{
+ my_cconvert_ptr cconvert;
+ int ci;
+
+ cconvert = (my_cconvert_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_color_deconverter));
+ cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
+ cconvert->pub.start_pass = start_pass_dcolor;
+
+ /* Make sure num_components agrees with jpeg_color_space */
+ switch (cinfo->jpeg_color_space) {
+ case JCS_GRAYSCALE:
+ if (cinfo->num_components != 1)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ break;
+
+ case JCS_RGB:
+ case JCS_YCbCr:
+ if (cinfo->num_components != 3)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ break;
+
+ case JCS_CMYK:
+ case JCS_YCCK:
+ if (cinfo->num_components != 4)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ break;
+
+ default: /* JCS_UNKNOWN can be anything */
+ if (cinfo->num_components < 1)
+ ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+ break;
+ }
+
+ /* Set out_color_components and conversion method based on requested space.
+ * Also clear the component_needed flags for any unused components,
+ * so that earlier pipeline stages can avoid useless computation.
+ */
+
+ switch (cinfo->out_color_space) {
+ case JCS_GRAYSCALE:
+ cinfo->out_color_components = 1;
+ if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
+ cinfo->jpeg_color_space == JCS_YCbCr) {
+ cconvert->pub.color_convert = grayscale_convert;
+ /* For color->grayscale conversion, only the Y (0) component is needed */
+ for (ci = 1; ci < cinfo->num_components; ci++)
+ cinfo->comp_info[ci].component_needed = FALSE;
+ } else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_RGB:
+ cinfo->out_color_components = RGB_PIXELSIZE;
+ if (cinfo->jpeg_color_space == JCS_YCbCr) {
+ cconvert->pub.color_convert = ycc_rgb_convert;
+ build_ycc_rgb_table(cinfo);
+ } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
+ cconvert->pub.color_convert = gray_rgb_convert;
+ } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
+ cconvert->pub.color_convert = null_convert;
+ } else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ case JCS_CMYK:
+ cinfo->out_color_components = 4;
+ if (cinfo->jpeg_color_space == JCS_YCCK) {
+ cconvert->pub.color_convert = ycck_cmyk_convert;
+ build_ycc_rgb_table(cinfo);
+ } else if (cinfo->jpeg_color_space == JCS_CMYK) {
+ cconvert->pub.color_convert = null_convert;
+ } else
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+
+ default:
+ /* Permit null conversion to same output space */
+ if (cinfo->out_color_space == cinfo->jpeg_color_space) {
+ cinfo->out_color_components = cinfo->num_components;
+ cconvert->pub.color_convert = null_convert;
+ } else /* unsupported non-null conversion */
+ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+ break;
+ }
+
+ if (cinfo->quantize_colors)
+ cinfo->output_components = 1; /* single colormapped output component */
+ else
+ cinfo->output_components = cinfo->out_color_components;
+}
diff --git a/jpeg-6c/jdct.h b/jpeg-6c/jdct.h
new file mode 100644
index 0000000..0a80634
--- /dev/null
+++ b/jpeg-6c/jdct.h
@@ -0,0 +1,177 @@
+/*
+ * jdct.h
+ *
+ * Copyright (C) 1994-1996, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This include file contains common declarations for the forward and
+ * inverse DCT modules. These declarations are private to the DCT managers
+ * (jcdctmgr.c, jddctmgr.c) and the individual DCT algorithms.
+ * The individual DCT algorithms are kept in separate files to ease
+ * machine-dependent tuning (e.g., assembly coding).
+ */
+
+
+/*
+ * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
+ * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
+ * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
+ * implementations use an array of type FAST_FLOAT, instead.)
+ * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
+ * The DCT outputs are returned scaled up by a factor of 8; they therefore
+ * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
+ * convention improves accuracy in integer implementations and saves some
+ * work in floating-point ones.
+ * Quantization of the output coefficients is done by jcdctmgr.c.
+ */
+
+/*#if BITS_IN_JSAMPLE == 8
+typedef int DCTELEM;*/ /* 16 or 32 bits is fine */
+/*#else*/
+typedef INT32 DCTELEM; /* must have 32 bits */
+/*#endif*/
+
+typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data, boolean jpeg8));
+typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
+
+
+/*
+ * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
+ * to an output sample array. The routine must dequantize the input data as
+ * well as perform the IDCT; for dequantization, it uses the multiplier table
+ * pointed to by compptr->dct_table. The output data is to be placed into the
+ * sample array starting at a specified column. (Any row offset needed will
+ * be applied to the array pointer before it is passed to the IDCT code.)
+ * Note that the number of samples emitted by the IDCT routine is
+ * DCT_scaled_size * DCT_scaled_size.
+ */
+
+/* typedef inverse_DCT_method_ptr is declared in jpegint.h */
+
+/*
+ * Each IDCT routine has its own ideas about the best dct_table element type.
+ */
+
+typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
+/*#if BITS_IN_JSAMPLE == 8
+typedef MULTIPLIER IFAST_MULT_TYPE;*/ /* 16 bits is OK, use short if faster */
+/*#define IFAST_SCALE_BITS 2*/ /* fractional bits in scale factors */
+/*#else*/
+typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
+/*#define IFAST_SCALE_BITS 13*/ /* fractional bits in scale factors */
+/*#endif*/
+typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
+
+
+/*
+ * Each IDCT routine is responsible for range-limiting its results and
+ * converting them to unsigned form (0..cinfo->maxjsample). The raw outputs could
+ * be quite far out of range if the input data is corrupt, so a bulletproof
+ * range-limiting step is required. We use a mask-and-table-lookup method
+ * to do the combined operations quickly. See the comments with
+ * prepare_range_limit_table (in jdmaster.c) for more info.
+ */
+
+#define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + cinfo->centerjsample)
+
+#define RANGE_MASK (cinfo->maxjsample * 4 + 3) /* 2 bits wider than legal samples */
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_fdct_islow jFDislow
+#define jpeg_fdct_ifast jFDifast
+#define jpeg_fdct_float jFDfloat
+#define jpeg_idct_islow jRDislow
+#define jpeg_idct_ifast jRDifast
+#define jpeg_idct_float jRDfloat
+#define jpeg_idct_4x4 jRD4x4
+#define jpeg_idct_2x2 jRD2x2
+#define jpeg_idct_1x1 jRD1x1
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+/* Extern declarations for the forward and inverse DCT routines. */
+
+EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data, boolean jpeg8));
+EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data, boolean jpeg8));
+EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
+
+EXTERN(void) jpeg_idct_islow
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY16 output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_ifast
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY16 output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_float
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY16 output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_4x4
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY16 output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_2x2
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY16 output_buf, JDIMENSION output_col));
+EXTERN(void) jpeg_idct_1x1
+ JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block, JSAMPARRAY16 output_buf, JDIMENSION output_col));
+
+
+/*
+ * Macros for handling fixed-point arithmetic; these are used by many
+ * but not all of the DCT/IDCT modules.
+ *
+ * All values are expected to be of type INT32.
+ * Fractional constants are scaled left by CONST_BITS bits.
+ * CONST_BITS is defined within each module using these macros,
+ * and may differ from one module to the next.
+ */
+
+#define ONE ((INT32) 1)
+#define CONST_SCALE (ONE << CONST_BITS)
+
+/* Convert a positive real constant to an integer scaled by CONST_SCALE.
+ * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
+ * thus causing a lot of useless floating-point operations at run time.
+ */
+
+#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
+ * the fudge factor is correct for either sign of X.
+ */
+
+#define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
+
+/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
+ * This macro is used only when the two inputs will actually be no more than
+ * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
+ * full 32x32 multiply. This provides a useful speedup on many machines.
+ * Unfortunately there is no way to specify a 16x16->32 multiply portably
+ * in C, but some C compilers will do the right thing if you provide the
+ * correct combination of casts.
+ */
+
+#ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
+#define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
+#endif
+#ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
+#define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
+#endif
+
+#ifndef MULTIPLY16C16 /* default definition */
+#define MULTIPLY16C16(var,const) ((var) * (const))
+#endif
+
+/* Same except both inputs are variables. */
+
+#ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
+#define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
+#endif
+
+#ifndef MULTIPLY16V16 /* default definition */
+#define MULTIPLY16V16(var1,var2) ((var1) * (var2))
+#endif
diff --git a/jpeg-6c/jddctmgr.c b/jpeg-6c/jddctmgr.c
new file mode 100644
index 0000000..1aa1500
--- /dev/null
+++ b/jpeg-6c/jddctmgr.c
@@ -0,0 +1,273 @@
+/*
+ * jddctmgr.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the inverse-DCT management logic.
+ * This code selects a particular IDCT implementation to be used,
+ * and it performs related housekeeping chores. No code in this file
+ * is executed per IDCT step, only during output pass setup.
+ *
+ * Note that the IDCT routines are responsible for performing coefficient
+ * dequantization as well as the IDCT proper. This module sets up the
+ * dequantization multiplier table needed by the IDCT routine.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h" /* Private declarations for lossy subsystem */
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+
+/*
+ * The decompressor input side (jdinput.c) saves away the appropriate
+ * quantization table for each component at the start of the first scan
+ * involving that component. (This is necessary in order to correctly
+ * decode files that reuse Q-table slots.)
+ * When we are ready to make an output pass, the saved Q-table is converted
+ * to a multiplier table that will actually be used by the IDCT routine.
+ * The multiplier table contents are IDCT-method-dependent. To support
+ * application changes in IDCT method between scans, we can remake the
+ * multiplier tables if necessary.
+ * In buffered-image mode, the first output pass may occur before any data
+ * has been seen for some components, and thus before their Q-tables have
+ * been saved away. To handle this case, multiplier tables are preset
+ * to zeroes; the result of the IDCT will be a neutral gray level.
+ */
+
+
+/* Private subobject for this module */
+
+typedef struct {
+ /* This array contains the IDCT method code that each multiplier table
+ * is currently set up for, or -1 if it's not yet set up.
+ * The actual multiplier tables are pointed to by dct_table in the
+ * per-component comp_info structures.
+ */
+ int cur_method[MAX_COMPONENTS];
+} idct_controller;
+
+typedef idct_controller * idct_ptr;
+
+
+/* Allocated multiplier tables: big enough for any supported variant */
+
+typedef union {
+ ISLOW_MULT_TYPE islow_array[DCTSIZE2];
+#ifdef DCT_IFAST_SUPPORTED
+ IFAST_MULT_TYPE ifast_array[DCTSIZE2];
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ FLOAT_MULT_TYPE float_array[DCTSIZE2];
+#endif
+} multiplier_table;
+
+
+/* The current scaled-IDCT routines require ISLOW-style multiplier tables,
+ * so be sure to compile that code if either ISLOW or SCALING is requested.
+ */
+#ifdef DCT_ISLOW_SUPPORTED
+#define PROVIDE_ISLOW_TABLES
+#else
+#ifdef IDCT_SCALING_SUPPORTED
+#define PROVIDE_ISLOW_TABLES
+#endif
+#endif
+
+
+/*
+ * Prepare for an output pass.
+ * Here we select the proper IDCT routine for each component and build
+ * a matching multiplier table.
+ */
+
+METHODDEF(void)
+start_pass (j_decompress_ptr cinfo)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ idct_ptr idct = (idct_ptr) lossyd->idct_private;
+ int ci, i, ifast_sb;
+ jpeg_component_info *compptr;
+ int method = 0;
+ inverse_DCT_method_ptr method_ptr = NULL;
+ JQUANT_TBL * qtbl;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Select the proper IDCT routine for this component's scaling */
+ switch (compptr->codec_data_unit) {
+#ifdef IDCT_SCALING_SUPPORTED
+ case 1:
+ method_ptr = jpeg_idct_1x1;
+ method = JDCT_ISLOW; /* jidctred uses islow-style table */
+ break;
+ case 2:
+ method_ptr = jpeg_idct_2x2;
+ method = JDCT_ISLOW; /* jidctred uses islow-style table */
+ break;
+ case 4:
+ method_ptr = jpeg_idct_4x4;
+ method = JDCT_ISLOW; /* jidctred uses islow-style table */
+ break;
+#endif
+ case DCTSIZE:
+ switch (cinfo->dct_method) {
+#ifdef DCT_ISLOW_SUPPORTED
+ case JDCT_ISLOW:
+ method_ptr = jpeg_idct_islow;
+ method = JDCT_ISLOW;
+ break;
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+ case JDCT_IFAST:
+ method_ptr = jpeg_idct_ifast;
+ method = JDCT_IFAST;
+ break;
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ case JDCT_FLOAT:
+ method_ptr = jpeg_idct_float;
+ method = JDCT_FLOAT;
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ break;
+ }
+ break;
+ default:
+ ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->codec_data_unit);
+ break;
+ }
+ lossyd->inverse_DCT[ci] = method_ptr;
+ /* Create multiplier table from quant table.
+ * However, we can skip this if the component is uninteresting
+ * or if we already built the table. Also, if no quant table
+ * has yet been saved for the component, we leave the
+ * multiplier table all-zero; we'll be reading zeroes from the
+ * coefficient controller's buffer anyway.
+ */
+ if (! compptr->component_needed || idct->cur_method[ci] == method)
+ continue;
+ qtbl = compptr->quant_table;
+ if (qtbl == NULL) /* happens if no data yet for component */
+ continue;
+ idct->cur_method[ci] = method;
+ switch (method) {
+#ifdef PROVIDE_ISLOW_TABLES
+ case JDCT_ISLOW:
+ {
+ /* For LL&M IDCT method, multipliers are equal to raw quantization
+ * coefficients, but are stored as ints to ensure access efficiency.
+ */
+ ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
+ for (i = 0; i < DCTSIZE2; i++) {
+ ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
+ }
+ }
+ break;
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+ case JDCT_IFAST:
+ {
+ /* For AA&N IDCT method, multipliers are equal to quantization
+ * coefficients scaled by scalefactor[row]*scalefactor[col], where
+ * scalefactor[0] = 1
+ * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
+ * For integer operation, the multiplier table is to be scaled by
+ * IFAST_SCALE_BITS.
+ */
+ IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
+#define CONST_BITS 14
+ static const INT16 aanscales[DCTSIZE2] = {
+ /* precomputed values scaled up by 14 bits */
+ 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
+ 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
+ 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
+ 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
+ 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
+ 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
+ 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
+ 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
+ };
+ SHIFT_TEMPS
+ if(cinfo->data_precision <= 8 ) ifast_sb = 2;
+ else ifast_sb = 13;
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ ifmtbl[i] = (IFAST_MULT_TYPE)
+ DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
+ (INT32) aanscales[i]),
+ CONST_BITS-ifast_sb);
+ }
+ }
+ break;
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+ case JDCT_FLOAT:
+ {
+ /* For float AA&N IDCT method, multipliers are equal to quantization
+ * coefficients scaled by scalefactor[row]*scalefactor[col], where
+ * scalefactor[0] = 1
+ * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
+ */
+ FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
+ int row, col;
+ static const double aanscalefactor[DCTSIZE] = {
+ 1.0, 1.387039845, 1.306562965, 1.175875602,
+ 1.0, 0.785694958, 0.541196100, 0.275899379
+ };
+
+ i = 0;
+ for (row = 0; row < DCTSIZE; row++) {
+ for (col = 0; col < DCTSIZE; col++) {
+ fmtbl[i] = (FLOAT_MULT_TYPE)
+ ((double) qtbl->quantval[i] *
+ aanscalefactor[row] * aanscalefactor[col]);
+ i++;
+ }
+ }
+ }
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ break;
+ }
+ }
+}
+
+
+/*
+ * Initialize IDCT manager.
+ */
+
+GLOBAL(void)
+jinit_inverse_dct (j_decompress_ptr cinfo)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ idct_ptr idct;
+ int ci;
+ jpeg_component_info *compptr;
+
+ idct = (idct_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(idct_controller));
+ lossyd->idct_private = (void *) idct;
+ lossyd->idct_start_pass = start_pass;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Allocate and pre-zero a multiplier table for each component */
+ compptr->dct_table =
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(multiplier_table));
+ MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
+ /* Mark multiplier table not yet set up for any method */
+ idct->cur_method[ci] = -1;
+ }
+}
diff --git a/jpeg-6c/jddiffct.c b/jpeg-6c/jddiffct.c
new file mode 100644
index 0000000..3df8e30
--- /dev/null
+++ b/jpeg-6c/jddiffct.c
@@ -0,0 +1,399 @@
+/*
+ * jddiffct.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the [un]difference buffer controller for decompression.
+ * This controller is the top level of the lossless JPEG decompressor proper.
+ * The difference buffer lies between the entropy decoding and
+ * prediction/undifferencing steps. The undifference buffer lies between the
+ * prediction/undifferencing and scaling steps.
+ *
+ * In buffered-image mode, this controller is the interface between
+ * input-oriented processing and output-oriented processing.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossls.h"
+
+
+#ifdef D_LOSSLESS_SUPPORTED
+
+/* Private buffer controller object */
+
+typedef struct {
+ /* These variables keep track of the current location of the input side. */
+ /* cinfo->input_iMCU_row is also used for this. */
+ JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
+ unsigned int restart_rows_to_go; /* MCU-rows left in this restart interval */
+ unsigned int MCU_vert_offset; /* counts MCU rows within iMCU row */
+ unsigned int MCU_rows_per_iMCU_row; /* number of such rows needed */
+
+ /* The output side's location is represented by cinfo->output_iMCU_row. */
+
+ JDIFFARRAY diff_buf[MAX_COMPONENTS]; /* iMCU row of differences */
+ JDIFFARRAY undiff_buf[MAX_COMPONENTS]; /* iMCU row of undiff'd samples */
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ /* In multi-pass modes, we need a virtual sample array for each component. */
+ jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
+#endif
+} d_diff_controller;
+
+typedef d_diff_controller * d_diff_ptr;
+
+/* Forward declarations */
+METHODDEF(int) decompress_data
+ JPP((j_decompress_ptr cinfo, JSAMPIMAGE16 output_buf));
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+METHODDEF(int) output_data
+ JPP((j_decompress_ptr cinfo, JSAMPIMAGE16 output_buf));
+#endif
+
+
+LOCAL(void)
+start_iMCU_row (j_decompress_ptr cinfo)
+/* Reset within-iMCU-row counters for a new row (input side) */
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ d_diff_ptr diff = (d_diff_ptr) losslsd->diff_private;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+ * But at the bottom of the image, process only what's left.
+ */
+ if (cinfo->comps_in_scan > 1) {
+ diff->MCU_rows_per_iMCU_row = 1;
+ } else {
+ if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
+ diff->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
+ else
+ diff->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
+ }
+
+ diff->MCU_ctr = 0;
+ diff->MCU_vert_offset = 0;
+}
+
+
+/*
+ * Initialize for an input processing pass.
+ */
+
+METHODDEF(void)
+start_input_pass (j_decompress_ptr cinfo)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ d_diff_ptr diff = (d_diff_ptr) losslsd->diff_private;
+
+ /* Check that the restart interval is an integer multiple of the number
+ * of MCU in an MCU-row.
+ */
+ if (cinfo->restart_interval % cinfo->MCUs_per_row != 0)
+ ERREXIT2(cinfo, JERR_BAD_RESTART,
+ cinfo->restart_interval, cinfo->MCUs_per_row);
+
+ /* Initialize restart counter */
+ diff->restart_rows_to_go = cinfo->restart_interval / cinfo->MCUs_per_row;
+
+ cinfo->input_iMCU_row = 0;
+ start_iMCU_row(cinfo);
+}
+
+
+/*
+ * Check for a restart marker & resynchronize decoder, undifferencer.
+ * Returns FALSE if must suspend.
+ */
+
+METHODDEF(boolean)
+process_restart (j_decompress_ptr cinfo)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ d_diff_ptr diff = (d_diff_ptr) losslsd->diff_private;
+
+ if (! (*losslsd->entropy_process_restart) (cinfo))
+ return FALSE;
+
+ (*losslsd->predict_process_restart) (cinfo);
+
+ /* Reset restart counter */
+ diff->restart_rows_to_go = cinfo->restart_interval / cinfo->MCUs_per_row;
+
+ return TRUE;
+}
+
+
+/*
+ * Initialize for an output processing pass.
+ */
+
+METHODDEF(void)
+start_output_pass (j_decompress_ptr cinfo)
+{
+ cinfo->output_iMCU_row = 0;
+}
+
+
+/*
+ * Decompress and return some data in the supplied buffer.
+ * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
+ * Input and output must run in lockstep since we have only a one-MCU buffer.
+ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
+ *
+ * NB: output_buf contains a plane for each component in image,
+ * which we index according to the component's SOF position.
+ */
+
+METHODDEF(int)
+decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE16 output_buf)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ d_diff_ptr diff = (d_diff_ptr) losslsd->diff_private;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION MCU_count; /* number of MCUs decoded */
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ int comp, ci, yoffset, row, prev_row;
+ jpeg_component_info *compptr;
+
+ /* Loop to process as much as one whole iMCU row */
+ for (yoffset = diff->MCU_vert_offset; yoffset < diff->MCU_rows_per_iMCU_row;
+ yoffset++) {
+
+ /* Process restart marker if needed; may have to suspend */
+ if (cinfo->restart_interval) {
+ if (diff->restart_rows_to_go == 0)
+ if (! process_restart(cinfo))
+ return JPEG_SUSPENDED;
+ }
+
+ MCU_col_num = diff->MCU_ctr;
+ /* Try to fetch an MCU-row (or remaining portion of suspended MCU-row). */
+ MCU_count =
+ (*losslsd->entropy_decode_mcus) (cinfo,
+ diff->diff_buf, yoffset, MCU_col_num,
+ cinfo->MCUs_per_row - MCU_col_num);
+ if (MCU_count != cinfo->MCUs_per_row - MCU_col_num) {
+ /* Suspension forced; update state counters and exit */
+ diff->MCU_vert_offset = yoffset;
+ diff->MCU_ctr += MCU_count;
+ return JPEG_SUSPENDED;
+ }
+
+ /* Account for restart interval (no-op if not using restarts) */
+ diff->restart_rows_to_go--;
+
+ /* Completed an MCU row, but perhaps not an iMCU row */
+ diff->MCU_ctr = 0;
+ }
+
+ /*
+ * Undifference and scale each scanline of the disassembled MCU-row
+ * separately. We do not process dummy samples at the end of a scanline
+ * or dummy rows at the end of the image.
+ */
+ for (comp = 0; comp < cinfo->comps_in_scan; comp++) {
+ compptr = cinfo->cur_comp_info[comp];
+ ci = compptr->component_index;
+ for (row = 0, prev_row = compptr->v_samp_factor - 1;
+ row < (cinfo->input_iMCU_row == last_iMCU_row ?
+ compptr->last_row_height : compptr->v_samp_factor);
+ prev_row = row, row++) {
+ (*losslsd->predict_undifference[ci]) (cinfo, ci,
+ diff->diff_buf[ci][row],
+ diff->undiff_buf[ci][prev_row],
+ diff->undiff_buf[ci][row],
+ compptr->width_in_data_units);
+ (*losslsd->scaler_scale) (cinfo, diff->undiff_buf[ci][row],
+ output_buf[ci][row],
+ compptr->width_in_data_units);
+ }
+ }
+
+ /* Completed the iMCU row, advance counters for next one.
+ *
+ * NB: output_data will increment output_iMCU_row.
+ * This counter is not needed for the single-pass case
+ * or the input side of the multi-pass case.
+ */
+ if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
+ start_iMCU_row(cinfo);
+ return JPEG_ROW_COMPLETED;
+ }
+ /* Completed the scan */
+ (*cinfo->inputctl->finish_input_pass) (cinfo);
+ return JPEG_SCAN_COMPLETED;
+}
+
+
+/*
+ * Dummy consume-input routine for single-pass operation.
+ */
+
+METHODDEF(int)
+dummy_consume_data (j_decompress_ptr cinfo)
+{
+ return JPEG_SUSPENDED; /* Always indicate nothing was done */
+}
+
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+
+/*
+ * Consume input data and store it in the full-image sample buffer.
+ * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
+ * ie, v_samp_factor rows for each component in the scan.
+ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
+ */
+
+METHODDEF(int)
+consume_data (j_decompress_ptr cinfo)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ d_diff_ptr diff = (d_diff_ptr) losslsd->diff_private;
+/* JDIMENSION MCU_col_num; *//* index of current MCU within row */
+/* JDIMENSION MCU_count; */ /* number of MCUs decoded */
+/* JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;*/
+ int comp, ci;/*, yoffset, row, prev_row;*/
+ JSAMPARRAY16 buffer[MAX_COMPS_IN_SCAN];
+ jpeg_component_info *compptr;
+
+ /* Align the virtual buffers for the components used in this scan. */
+ for (comp = 0; comp < cinfo->comps_in_scan; comp++) {
+ compptr = cinfo->cur_comp_info[comp];
+ ci = compptr->component_index;
+ buffer[ci] = (JSAMPARRAY16)(*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, diff->whole_image[ci],
+ cinfo->input_iMCU_row * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ }
+
+ return decompress_data(cinfo, buffer);
+}
+
+
+/*
+ * Output some data from the full-image buffer sample in the multi-pass case.
+ * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
+ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
+ *
+ * NB: output_buf contains a plane for each component in image.
+ */
+
+METHODDEF(int)
+output_data (j_decompress_ptr cinfo, JSAMPIMAGE16 output_buf)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ d_diff_ptr diff = (d_diff_ptr) losslsd->diff_private;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ int ci, samp_rows, row;
+ JSAMPARRAY16 buffer;
+ jpeg_component_info *compptr;
+
+ /* Force some input to be done if we are getting ahead of the input. */
+ while (cinfo->input_scan_number < cinfo->output_scan_number ||
+ (cinfo->input_scan_number == cinfo->output_scan_number &&
+ cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
+ if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
+ return JPEG_SUSPENDED;
+ }
+
+ /* OK, output from the virtual arrays. */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Align the virtual buffer for this component. */
+ buffer = (JSAMPARRAY16)(*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, diff->whole_image[ci],
+ cinfo->output_iMCU_row * compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+
+ if (cinfo->output_iMCU_row < last_iMCU_row)
+ samp_rows = compptr->v_samp_factor;
+ else {
+ /* NB: can't use last_row_height here; it is input-side-dependent! */
+ samp_rows = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
+ if (samp_rows == 0) samp_rows = compptr->v_samp_factor;
+ }
+
+ for (row = 0; row < samp_rows; row++) {
+ MEMCOPY(output_buf[ci][row], buffer[row],
+ compptr->width_in_data_units * SIZEOF(JSAMPLE16));
+ }
+ }
+
+ if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
+ return JPEG_ROW_COMPLETED;
+ return JPEG_SCAN_COMPLETED;
+}
+
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
+
+
+/*
+ * Initialize difference buffer controller.
+ */
+
+GLOBAL(void)
+jinit_d_diff_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ d_diff_ptr diff;
+ int ci;
+ jpeg_component_info *compptr;
+
+ diff = (d_diff_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(d_diff_controller));
+ losslsd->diff_private = (void *) diff;
+ losslsd->diff_start_input_pass = start_input_pass;
+ losslsd->pub.start_output_pass = start_output_pass;
+
+ /* Create the [un]difference buffers. */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ diff->diff_buf[ci] = (*cinfo->mem->alloc_darray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JSAMPLE16),
+ (JDIMENSION) compptr->v_samp_factor);
+ diff->undiff_buf[ci] = (*cinfo->mem->alloc_darray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JSAMPLE16),
+ (JDIMENSION) compptr->v_samp_factor);
+ }
+
+ if (need_full_buffer) {
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ /* Allocate a full-image virtual array for each component. */
+ int access_rows;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ access_rows = compptr->v_samp_factor;
+ diff->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor) * SIZEOF(JSAMPLE16),
+ (JDIMENSION) jround_up((long) compptr->height_in_data_units,
+ (long) compptr->v_samp_factor),
+ (JDIMENSION) access_rows);
+ }
+ losslsd->pub.consume_data = consume_data;
+ losslsd->pub.decompress_data = output_data;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ losslsd->pub.consume_data = dummy_consume_data;
+ losslsd->pub.decompress_data = decompress_data;
+ diff->whole_image[0] = NULL; /* flag for no virtual arrays */
+ }
+}
+
+#endif /* D_LOSSLESS_SUPPORTED */
diff --git a/jpeg-6c/jdhuff.c b/jpeg-6c/jdhuff.c
new file mode 100644
index 0000000..6656ad8
--- /dev/null
+++ b/jpeg-6c/jdhuff.c
@@ -0,0 +1,315 @@
+/*
+ * jdhuff.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains Huffman entropy decoding routines which are shared
+ * by the sequential, progressive and lossless decoders.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h" /* Private declarations for lossy codec */
+#include "jlossls.h" /* Private declarations for lossless codec */
+#include "jdhuff.h" /* Declarations shared with jd*huff.c */
+
+
+/*
+ * Compute the derived values for a Huffman table.
+ * This routine also performs some validation checks on the table.
+ */
+
+GLOBAL(void)
+jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
+ d_derived_tbl ** pdtbl)
+{
+ JHUFF_TBL *htbl;
+ d_derived_tbl *dtbl;
+ int p, i, l, si, numsymbols;
+ int lookbits, ctr;
+ char huffsize[257];
+ unsigned int huffcode[257];
+ unsigned int code;
+
+ /* Note that huffsize[] and huffcode[] are filled in code-length order,
+ * paralleling the order of the symbols themselves in htbl->huffval[].
+ */
+
+ /* Find the input Huffman table */
+ if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
+ htbl =
+ isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
+ if (htbl == NULL)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
+
+ /* Allocate a workspace if we haven't already done so. */
+ if (*pdtbl == NULL)
+ *pdtbl = (d_derived_tbl *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(d_derived_tbl));
+ dtbl = *pdtbl;
+ dtbl->pub = htbl; /* fill in back link */
+
+ /* Figure C.1: make table of Huffman code length for each symbol */
+
+ p = 0;
+ for (l = 1; l <= 16; l++) {
+ i = (int) htbl->bits[l];
+ if (i < 0 || p + i > 256) /* protect against table overrun */
+ ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
+ while (i--)
+ huffsize[p++] = (char) l;
+ }
+ huffsize[p] = 0;
+ numsymbols = p;
+
+ /* Figure C.2: generate the codes themselves */
+ /* We also validate that the counts represent a legal Huffman code tree. */
+
+ code = 0;
+ si = huffsize[0];
+ p = 0;
+ while (huffsize[p]) {
+ while (((int) huffsize[p]) == si) {
+ huffcode[p++] = code;
+ code++;
+ }
+ /* code is now 1 more than the last code used for codelength si; but
+ * it must still fit in si bits, since no code is allowed to be all ones.
+ */
+ if (((INT32) code) >= (((INT32) 1) << si))
+ ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
+ code <<= 1;
+ si++;
+ }
+
+ /* Figure F.15: generate decoding tables for bit-sequential decoding */
+
+ p = 0;
+ for (l = 1; l <= 16; l++) {
+ if (htbl->bits[l]) {
+ /* valoffset[l] = huffval[] index of 1st symbol of code length l,
+ * minus the minimum code of length l
+ */
+ dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
+ p += htbl->bits[l];
+ dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
+ } else {
+ dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
+ }
+ }
+ dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
+
+ /* Compute lookahead tables to speed up decoding.
+ * First we set all the table entries to 0, indicating "too long";
+ * then we iterate through the Huffman codes that are short enough and
+ * fill in all the entries that correspond to bit sequences starting
+ * with that code.
+ */
+
+ MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
+
+ p = 0;
+ for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
+ for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
+ /* l = current code's length, p = its index in huffcode[] & huffval[]. */
+ /* Generate left-justified code followed by all possible bit sequences */
+ lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
+ for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
+ dtbl->look_nbits[lookbits] = l;
+ dtbl->look_sym[lookbits] = htbl->huffval[p];
+ lookbits++;
+ }
+ }
+ }
+
+ /* Validate symbols as being reasonable.
+ * For AC tables, we make no check, but accept all byte values 0..255.
+ * For DC tables, we require the symbols to be in range 0..16.
+ * (Tighter bounds could be applied depending on the data depth and mode,
+ * but this is sufficient to ensure safe decoding.)
+ */
+ if (isDC) {
+ for (i = 0; i < numsymbols; i++) {
+ int sym = htbl->huffval[i];
+ if (sym < 0 || sym > 16)
+ ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
+ }
+ }
+}
+
+
+/*
+ * Out-of-line code for bit fetching.
+ * See jdhuff.h for info about usage.
+ * Note: current values of get_buffer and bits_left are passed as parameters,
+ * but are returned in the corresponding fields of the state struct.
+ *
+ * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
+ * of get_buffer to be used. (On machines with wider words, an even larger
+ * buffer could be used.) However, on some machines 32-bit shifts are
+ * quite slow and take time proportional to the number of places shifted.
+ * (This is true with most PC compilers, for instance.) In this case it may
+ * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
+ * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
+ */
+
+#ifdef SLOW_SHIFT_32
+#define MIN_GET_BITS 15 /* minimum allowable value */
+#else
+#define MIN_GET_BITS (BIT_BUF_SIZE-7)
+#endif
+
+
+GLOBAL(boolean)
+jpeg_fill_bit_buffer (bitread_working_state * state,
+ register bit_buf_type get_buffer, register int bits_left,
+ int nbits)
+/* Load up the bit buffer to a depth of at least nbits */
+{
+ /* Copy heavily used state fields into locals (hopefully registers) */
+ register const JOCTET * next_input_byte = state->next_input_byte;
+ register size_t bytes_in_buffer = state->bytes_in_buffer;
+ j_decompress_ptr cinfo = state->cinfo;
+
+ /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
+ /* (It is assumed that no request will be for more than that many bits.) */
+ /* We fail to do so only if we hit a marker or are forced to suspend. */
+
+ if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
+ while (bits_left < MIN_GET_BITS) {
+ register int c;
+
+ /* Attempt to read a byte */
+ if (bytes_in_buffer == 0) {
+ if (! (*cinfo->src->fill_input_buffer) (cinfo))
+ return FALSE;
+ next_input_byte = cinfo->src->next_input_byte;
+ bytes_in_buffer = cinfo->src->bytes_in_buffer;
+ }
+ bytes_in_buffer--;
+ c = GETJOCTET(*next_input_byte++);
+
+ /* If it's 0xFF, check and discard stuffed zero byte */
+ if (c == 0xFF) {
+ /* Loop here to discard any padding FF's on terminating marker,
+ * so that we can save a valid unread_marker value. NOTE: we will
+ * accept multiple FF's followed by a 0 as meaning a single FF data
+ * byte. This data pattern is not valid according to the standard.
+ */
+ do {
+ if (bytes_in_buffer == 0) {
+ if (! (*cinfo->src->fill_input_buffer) (cinfo))
+ return FALSE;
+ next_input_byte = cinfo->src->next_input_byte;
+ bytes_in_buffer = cinfo->src->bytes_in_buffer;
+ }
+ bytes_in_buffer--;
+ c = GETJOCTET(*next_input_byte++);
+ } while (c == 0xFF);
+
+ if (c == 0) {
+ /* Found FF/00, which represents an FF data byte */
+ c = 0xFF;
+ } else {
+ /* Oops, it's actually a marker indicating end of compressed data.
+ * Save the marker code for later use.
+ * Fine point: it might appear that we should save the marker into
+ * bitread working state, not straight into permanent state. But
+ * once we have hit a marker, we cannot need to suspend within the
+ * current MCU, because we will read no more bytes from the data
+ * source. So it is OK to update permanent state right away.
+ */
+ cinfo->unread_marker = c;
+ /* See if we need to insert some fake zero bits. */
+ goto no_more_bytes;
+ }
+ }
+
+ /* OK, load c into get_buffer */
+ get_buffer = (get_buffer << 8) | c;
+ bits_left += 8;
+ } /* end while */
+ } else {
+ no_more_bytes:
+ /* We get here if we've read the marker that terminates the compressed
+ * data segment. There should be enough bits in the buffer register
+ * to satisfy the request; if so, no problem.
+ */
+ if (nbits > bits_left) {
+ /* Uh-oh. Report corrupted data to user and stuff zeroes into
+ * the data stream, so that we can produce some kind of image.
+ * We use a nonvolatile flag to ensure that only one warning message
+ * appears per data segment.
+ */
+ huffd_common_ptr huffd;
+ if (cinfo->process == JPROC_LOSSLESS)
+ huffd = (huffd_common_ptr) ((j_lossless_d_ptr) cinfo->codec)->entropy_private;
+ else
+ huffd = (huffd_common_ptr) ((j_lossy_d_ptr) cinfo->codec)->entropy_private;
+ if (! huffd->insufficient_data) {
+ WARNMS(cinfo, JWRN_HIT_MARKER);
+ huffd->insufficient_data = TRUE;
+ }
+ /* Fill the buffer with zero bits */
+ get_buffer <<= MIN_GET_BITS - bits_left;
+ bits_left = MIN_GET_BITS;
+ }
+ }
+
+ /* Unload the local registers */
+ state->next_input_byte = next_input_byte;
+ state->bytes_in_buffer = bytes_in_buffer;
+ state->get_buffer = get_buffer;
+ state->bits_left = bits_left;
+
+ return TRUE;
+}
+
+
+/*
+ * Out-of-line code for Huffman code decoding.
+ * See jdhuff.h for info about usage.
+ */
+
+GLOBAL(int)
+jpeg_huff_decode (bitread_working_state * state,
+ register bit_buf_type get_buffer, register int bits_left,
+ d_derived_tbl * htbl, int min_bits)
+{
+ register int l = min_bits;
+ register INT32 code;
+
+ /* HUFF_DECODE has determined that the code is at least min_bits */
+ /* bits long, so fetch that many bits in one swoop. */
+
+ CHECK_BIT_BUFFER(*state, l, return -1);
+ code = GET_BITS(l);
+
+ /* Collect the rest of the Huffman code one bit at a time. */
+ /* This is per Figure F.16 in the JPEG spec. */
+
+ while (code > htbl->maxcode[l]) {
+ code <<= 1;
+ CHECK_BIT_BUFFER(*state, 1, return -1);
+ code |= GET_BITS(1);
+ l++;
+ }
+
+ /* Unload the local registers */
+ state->get_buffer = get_buffer;
+ state->bits_left = bits_left;
+
+ /* With garbage input we may reach the sentinel value l = 17. */
+
+ if (l > 16) {
+ WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
+ return 0; /* fake a zero as the safest result */
+ }
+
+ return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
+}
diff --git a/jpeg-6c/jdhuff.h b/jpeg-6c/jdhuff.h
new file mode 100644
index 0000000..f9bfc5c
--- /dev/null
+++ b/jpeg-6c/jdhuff.h
@@ -0,0 +1,229 @@
+/*
+ * jdhuff.h
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains declarations for Huffman entropy decoding routines
+ * that are shared between the sequential decoder (jdhuff.c), the
+ * progressive decoder (jdphuff.c) and the lossless decoder (jdlhuff.c).
+ * No other modules need to see these.
+ */
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_make_d_derived_tbl jMkDDerived
+#define jpeg_fill_bit_buffer jFilBitBuf
+#define jpeg_huff_decode jHufDecode
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/* Derived data constructed for each Huffman table */
+
+#define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
+
+typedef struct {
+ /* Basic tables: (element [0] of each array is unused) */
+ INT32 maxcode[18]; /* largest code of length k (-1 if none) */
+ /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
+ INT32 valoffset[17]; /* huffval[] offset for codes of length k */
+ /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
+ * the smallest code of length k; so given a code of length k, the
+ * corresponding symbol is huffval[code + valoffset[k]]
+ */
+
+ /* Link to public Huffman table (needed only in jpeg_huff_decode) */
+ JHUFF_TBL *pub;
+
+ /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
+ * the input data stream. If the next Huffman code is no more
+ * than HUFF_LOOKAHEAD bits long, we can obtain its length and
+ * the corresponding symbol directly from these tables.
+ */
+ int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
+ UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
+} d_derived_tbl;
+
+/* Expand a Huffman table definition into the derived format */
+EXTERN(void) jpeg_make_d_derived_tbl
+ JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
+ d_derived_tbl ** pdtbl));
+
+
+/*
+ * Fetching the next N bits from the input stream is a time-critical operation
+ * for the Huffman decoders. We implement it with a combination of inline
+ * macros and out-of-line subroutines. Note that N (the number of bits
+ * demanded at one time) never exceeds 15 for JPEG use.
+ *
+ * We read source bytes into get_buffer and dole out bits as needed.
+ * If get_buffer already contains enough bits, they are fetched in-line
+ * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
+ * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
+ * as full as possible (not just to the number of bits needed; this
+ * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
+ * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
+ * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
+ * at least the requested number of bits --- dummy zeroes are inserted if
+ * necessary.
+ */
+
+typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
+#define BIT_BUF_SIZE 32 /* size of buffer in bits */
+
+/* If long is > 32 bits on your machine, and shifting/masking longs is
+ * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
+ * appropriately should be a win. Unfortunately we can't define the size
+ * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
+ * because not all machines measure sizeof in 8-bit bytes.
+ */
+
+typedef struct { /* Bitreading state saved across MCUs */
+ bit_buf_type get_buffer; /* current bit-extraction buffer */
+ int bits_left; /* # of unused bits in it */
+} bitread_perm_state;
+
+typedef struct { /* Bitreading working state within an MCU */
+ /* Current data source location */
+ /* We need a copy, rather than munging the original, in case of suspension */
+ const JOCTET * next_input_byte; /* => next byte to read from source */
+ size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
+ /* Bit input buffer --- note these values are kept in register variables,
+ * not in this struct, inside the inner loops.
+ */
+ bit_buf_type get_buffer; /* current bit-extraction buffer */
+ int bits_left; /* # of unused bits in it */
+ /* Pointer needed by jpeg_fill_bit_buffer. */
+ j_decompress_ptr cinfo; /* back link to decompress master record */
+} bitread_working_state;
+
+/* Macros to declare and load/save bitread local variables. */
+#define BITREAD_STATE_VARS \
+ register bit_buf_type get_buffer; \
+ register int bits_left; \
+ bitread_working_state br_state
+
+#define BITREAD_LOAD_STATE(cinfop,permstate) \
+ br_state.cinfo = cinfop; \
+ br_state.next_input_byte = cinfop->src->next_input_byte; \
+ br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
+ get_buffer = permstate.get_buffer; \
+ bits_left = permstate.bits_left;
+
+#define BITREAD_SAVE_STATE(cinfop,permstate) \
+ cinfop->src->next_input_byte = br_state.next_input_byte; \
+ cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
+ permstate.get_buffer = get_buffer; \
+ permstate.bits_left = bits_left
+
+/*
+ * These macros provide the in-line portion of bit fetching.
+ * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
+ * before using GET_BITS, PEEK_BITS, or DROP_BITS.
+ * The variables get_buffer and bits_left are assumed to be locals,
+ * but the state struct might not be (jpeg_huff_decode needs this).
+ * CHECK_BIT_BUFFER(state,n,action);
+ * Ensure there are N bits in get_buffer; if suspend, take action.
+ * val = GET_BITS(n);
+ * Fetch next N bits.
+ * val = PEEK_BITS(n);
+ * Fetch next N bits without removing them from the buffer.
+ * DROP_BITS(n);
+ * Discard next N bits.
+ * The value N should be a simple variable, not an expression, because it
+ * is evaluated multiple times.
+ */
+
+#define CHECK_BIT_BUFFER(state,nbits,action) \
+ { if (bits_left < (nbits)) { \
+ if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
+ { action; } \
+ get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
+
+#define GET_BITS(nbits) \
+ (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
+
+#define PEEK_BITS(nbits) \
+ (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
+
+#define DROP_BITS(nbits) \
+ (bits_left -= (nbits))
+
+/* Load up the bit buffer to a depth of at least nbits */
+EXTERN(boolean) jpeg_fill_bit_buffer
+ JPP((bitread_working_state * state, register bit_buf_type get_buffer,
+ register int bits_left, int nbits));
+
+
+/*
+ * Code for extracting next Huffman-coded symbol from input bit stream.
+ * Again, this is time-critical and we make the main paths be macros.
+ *
+ * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
+ * without looping. Usually, more than 95% of the Huffman codes will be 8
+ * or fewer bits long. The few overlength codes are handled with a loop,
+ * which need not be inline code.
+ *
+ * Notes about the HUFF_DECODE macro:
+ * 1. Near the end of the data segment, we may fail to get enough bits
+ * for a lookahead. In that case, we do it the hard way.
+ * 2. If the lookahead table contains no entry, the next code must be
+ * more than HUFF_LOOKAHEAD bits long.
+ * 3. jpeg_huff_decode returns -1 if forced to suspend.
+ */
+
+#define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
+{ register int nb, look; \
+ if (bits_left < HUFF_LOOKAHEAD) { \
+ if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
+ get_buffer = state.get_buffer; bits_left = state.bits_left; \
+ if (bits_left < HUFF_LOOKAHEAD) { \
+ nb = 1; goto slowlabel; \
+ } \
+ } \
+ look = PEEK_BITS(HUFF_LOOKAHEAD); \
+ if ((nb = htbl->look_nbits[look]) != 0) { \
+ DROP_BITS(nb); \
+ result = htbl->look_sym[look]; \
+ } else { \
+ nb = HUFF_LOOKAHEAD+1; \
+slowlabel: \
+ if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
+ { failaction; } \
+ get_buffer = state.get_buffer; bits_left = state.bits_left; \
+ } \
+}
+
+/* Out-of-line case for Huffman code fetching */
+EXTERN(int) jpeg_huff_decode
+ JPP((bitread_working_state * state, register bit_buf_type get_buffer,
+ register int bits_left, d_derived_tbl * htbl, int min_bits));
+
+
+/* Common fields between sequential, progressive and lossless Huffman entropy
+ * decoder master structs.
+ */
+
+#define huffd_common_fields \
+ boolean insufficient_data; /* set TRUE after emmitting warning */ \
+ /* These fields are loaded into local variables at start of each MCU. \
+ * In case of suspension, we exit WITHOUT updating them. \
+ */ \
+ bitread_perm_state bitstate /* Bit buffer at start of MCU */
+
+/* Routines that are to be used by any or all of the entropy decoders are
+ * declared to receive a pointer to this structure. There are no actual
+ * instances of huffd_common_struct, only of shuff_entropy_decoder,
+ * phuff_entropy_decoder and lhuff_entropy_decoder.
+ */
+struct huffd_common_struct {
+ huffd_common_fields; /* Fields common to all decoder struct types */
+ /* Additional fields follow in an actual shuff_entropy_decoder,
+ * phuff_entropy_decoder or lhuff_entropy_decoder struct. All four structs
+ * must agree on these initial fields! (This would be a lot cleaner in C++.)
+ */
+};
+
+typedef struct huffd_common_struct * huffd_common_ptr;
diff --git a/jpeg-6c/jdinput.c b/jpeg-6c/jdinput.c
new file mode 100644
index 0000000..6349bee
--- /dev/null
+++ b/jpeg-6c/jdinput.c
@@ -0,0 +1,348 @@
+/*
+ * jdinput.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains input control logic for the JPEG decompressor.
+ * These routines are concerned with controlling the decompressor's input
+ * processing (marker reading and coefficient/difference decoding).
+ * The actual input reading is done in jdmarker.c, jdhuff.c, jdphuff.c,
+ * and jdlhuff.c.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private state */
+
+typedef struct {
+ struct jpeg_input_controller pub; /* public fields */
+
+ boolean inheaders; /* TRUE until first SOS is reached */
+} my_input_controller;
+
+typedef my_input_controller * my_inputctl_ptr;
+
+
+/* Forward declarations */
+METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
+
+
+/*
+ * Routines to calculate various quantities related to the size of the image.
+ */
+
+LOCAL(void)
+initial_setup (j_decompress_ptr cinfo)
+/* Called once, when first SOS marker is reached */
+{
+ int ci;
+ jpeg_component_info *compptr;
+
+ /* Make sure image isn't bigger than I can handle */
+ if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
+ (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
+ ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
+
+/* if (cinfo->process == JPROC_LOSSLESS) {*/
+ /* If precision > compiled-in value, we must downscale */
+/* if (cinfo->data_precision > BITS_IN_JSAMPLE)
+ WARNMS2(cinfo, JWRN_MUST_DOWNSCALE,
+ cinfo->data_precision, BITS_IN_JSAMPLE);
+ }
+ else {*/ /* Lossy processes */
+ /* For now, precision must match compiled-in value... */
+/* if (cinfo->data_precision != BITS_IN_JSAMPLE)
+ ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
+ }*/
+
+ /* Check that number of components won't exceed internal array sizes */
+ if (cinfo->num_components > MAX_COMPONENTS)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
+ MAX_COMPONENTS);
+
+ /* Compute maximum sampling factors; check factor validity */
+ cinfo->max_h_samp_factor = 1;
+ cinfo->max_v_samp_factor = 1;
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
+ compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
+ ERREXIT(cinfo, JERR_BAD_SAMPLING);
+ cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
+ compptr->h_samp_factor);
+ cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
+ compptr->v_samp_factor);
+ }
+
+ /* We initialize codec_data_unit and min_codec_data_unit to data_unit.
+ * In the full decompressor, this will be overridden by jdmaster.c;
+ * but in the transcoder, jdmaster.c is not used, so we must do it here.
+ */
+ cinfo->min_codec_data_unit = cinfo->data_unit;
+
+ /* Compute dimensions of components */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ compptr->codec_data_unit = cinfo->data_unit;
+ /* Size in data units */
+ compptr->width_in_data_units = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+ (long) (cinfo->max_h_samp_factor * cinfo->data_unit));
+ compptr->height_in_data_units = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+ (long) (cinfo->max_v_samp_factor * cinfo->data_unit));
+ /* downsampled_width and downsampled_height will also be overridden by
+ * jdmaster.c if we are doing full decompression. The transcoder library
+ * doesn't use these values, but the calling application might.
+ */
+ /* Size in samples */
+ compptr->downsampled_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+ (long) cinfo->max_h_samp_factor);
+ compptr->downsampled_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+ (long) cinfo->max_v_samp_factor);
+ /* Mark component needed, until color conversion says otherwise */
+ compptr->component_needed = TRUE;
+ /* Mark no quantization table yet saved for component */
+ compptr->quant_table = NULL;
+ }
+
+ /* Compute number of fully interleaved MCU rows. */
+ cinfo->total_iMCU_rows = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+ (long) (cinfo->max_v_samp_factor*cinfo->data_unit));
+
+ /* Decide whether file contains multiple scans */
+ if (cinfo->comps_in_scan < cinfo->num_components ||
+ cinfo->process == JPROC_PROGRESSIVE)
+ cinfo->inputctl->has_multiple_scans = TRUE;
+ else
+ cinfo->inputctl->has_multiple_scans = FALSE;
+}
+
+
+LOCAL(void)
+per_scan_setup (j_decompress_ptr cinfo)
+/* Do computations that are needed before processing a JPEG scan */
+/* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
+{
+ int ci, mcublks, tmp;
+ jpeg_component_info *compptr;
+
+ if (cinfo->comps_in_scan == 1) {
+
+ /* Noninterleaved (single-component) scan */
+ compptr = cinfo->cur_comp_info[0];
+
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = compptr->width_in_data_units;
+ cinfo->MCU_rows_in_scan = compptr->height_in_data_units;
+
+ /* For noninterleaved scan, always one data unit per MCU */
+ compptr->MCU_width = 1;
+ compptr->MCU_height = 1;
+ compptr->MCU_data_units = 1;
+ compptr->MCU_sample_width = compptr->codec_data_unit;
+ compptr->last_col_width = 1;
+ /* For noninterleaved scans, it is convenient to define last_row_height
+ * as the number of data unit rows present in the last iMCU row.
+ */
+ tmp = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
+ if (tmp == 0) tmp = compptr->v_samp_factor;
+ compptr->last_row_height = tmp;
+
+ /* Prepare array describing MCU composition */
+ cinfo->data_units_in_MCU = 1;
+ cinfo->MCU_membership[0] = 0;
+
+ } else {
+
+ /* Interleaved (multi-component) scan */
+ if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
+ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
+ MAX_COMPS_IN_SCAN);
+
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width,
+ (long) (cinfo->max_h_samp_factor*cinfo->data_unit));
+ cinfo->MCU_rows_in_scan = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+ (long) (cinfo->max_v_samp_factor*cinfo->data_unit));
+
+ cinfo->data_units_in_MCU = 0;
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* Sampling factors give # of data units of component in each MCU */
+ compptr->MCU_width = compptr->h_samp_factor;
+ compptr->MCU_height = compptr->v_samp_factor;
+ compptr->MCU_data_units = compptr->MCU_width * compptr->MCU_height;
+ compptr->MCU_sample_width = compptr->MCU_width * compptr->codec_data_unit;
+ /* Figure number of non-dummy data units in last MCU column & row */
+ tmp = (int) (compptr->width_in_data_units % compptr->MCU_width);
+ if (tmp == 0) tmp = compptr->MCU_width;
+ compptr->last_col_width = tmp;
+ tmp = (int) (compptr->height_in_data_units % compptr->MCU_height);
+ if (tmp == 0) tmp = compptr->MCU_height;
+ compptr->last_row_height = tmp;
+ /* Prepare array describing MCU composition */
+ mcublks = compptr->MCU_data_units;
+ if (cinfo->data_units_in_MCU + mcublks > D_MAX_DATA_UNITS_IN_MCU)
+ ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
+ while (mcublks-- > 0) {
+ cinfo->MCU_membership[cinfo->data_units_in_MCU++] = ci;
+ }
+ }
+
+ }
+}
+
+
+/*
+ * Initialize the input modules to read a scan of compressed data.
+ * The first call to this is done by jdmaster.c after initializing
+ * the entire decompressor (during jpeg_start_decompress).
+ * Subsequent calls come from consume_markers, below.
+ */
+
+METHODDEF(void)
+start_input_pass (j_decompress_ptr cinfo)
+{
+ per_scan_setup(cinfo);
+ (*cinfo->codec->start_input_pass) (cinfo);
+ cinfo->inputctl->consume_input = cinfo->codec->consume_data;
+}
+
+
+/*
+ * Finish up after inputting a compressed-data scan.
+ * This is called by the coefficient controller after it's read all
+ * the expected data of the scan.
+ */
+
+METHODDEF(void)
+finish_input_pass (j_decompress_ptr cinfo)
+{
+ cinfo->inputctl->consume_input = consume_markers;
+}
+
+
+/*
+ * Read JPEG markers before, between, or after compressed-data scans.
+ * Change state as necessary when a new scan is reached.
+ * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
+ *
+ * The consume_input method pointer points either here or to the
+ * coefficient controller's consume_data routine, depending on whether
+ * we are reading a compressed data segment or inter-segment markers.
+ */
+
+METHODDEF(int)
+consume_markers (j_decompress_ptr cinfo)
+{
+ my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
+ int val;
+
+ if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
+ return JPEG_REACHED_EOI;
+
+ val = (*cinfo->marker->read_markers) (cinfo);
+
+ switch (val) {
+ case JPEG_REACHED_SOS: /* Found SOS */
+ if (inputctl->inheaders) { /* 1st SOS */
+ initial_setup(cinfo);
+ /*
+ * Initialize the decompression codec. We need to do this here so that
+ * any codec-specific fields and function pointers are available to
+ * the rest of the library.
+ */
+ jinit_d_codec(cinfo);
+ inputctl->inheaders = FALSE;
+ /* Note: start_input_pass must be called by jdmaster.c
+ * before any more input can be consumed. jdapimin.c is
+ * responsible for enforcing this sequencing.
+ */
+ } else { /* 2nd or later SOS marker */
+ if (! inputctl->pub.has_multiple_scans)
+ ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
+ start_input_pass(cinfo);
+ }
+ break;
+ case JPEG_REACHED_EOI: /* Found EOI */
+ inputctl->pub.eoi_reached = TRUE;
+ if (inputctl->inheaders) { /* Tables-only datastream, apparently */
+ if (cinfo->marker->saw_SOF)
+ ERREXIT(cinfo, JERR_SOF_NO_SOS);
+ } else {
+ /* Prevent infinite loop in coef ctlr's decompress_data routine
+ * if user set output_scan_number larger than number of scans.
+ */
+ if (cinfo->output_scan_number > cinfo->input_scan_number)
+ cinfo->output_scan_number = cinfo->input_scan_number;
+ }
+ break;
+ case JPEG_SUSPENDED:
+ break;
+ }
+
+ return val;
+}
+
+
+/*
+ * Reset state to begin a fresh datastream.
+ */
+
+METHODDEF(void)
+reset_input_controller (j_decompress_ptr cinfo)
+{
+ my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
+
+ inputctl->pub.consume_input = consume_markers;
+ inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
+ inputctl->pub.eoi_reached = FALSE;
+ inputctl->inheaders = TRUE;
+ /* Reset other modules */
+ (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
+ (*cinfo->marker->reset_marker_reader) (cinfo);
+ /* Reset progression state -- would be cleaner if entropy decoder did this */
+ cinfo->coef_bits = NULL;
+}
+
+
+/*
+ * Initialize the input controller module.
+ * This is called only once, when the decompression object is created.
+ */
+
+GLOBAL(void)
+jinit_input_controller (j_decompress_ptr cinfo)
+{
+ my_inputctl_ptr inputctl;
+
+ /* Create subobject in permanent pool */
+ inputctl = (my_inputctl_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(my_input_controller));
+ cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
+ /* Initialize method pointers */
+ inputctl->pub.consume_input = consume_markers;
+ inputctl->pub.reset_input_controller = reset_input_controller;
+ inputctl->pub.start_input_pass = start_input_pass;
+ inputctl->pub.finish_input_pass = finish_input_pass;
+ /* Initialize state: can't use reset_input_controller since we don't
+ * want to try to reset other modules yet.
+ */
+ inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
+ inputctl->pub.eoi_reached = FALSE;
+ inputctl->inheaders = TRUE;
+}
diff --git a/jpeg-6c/jdlhuff.c b/jpeg-6c/jdlhuff.c
new file mode 100644
index 0000000..d214690
--- /dev/null
+++ b/jpeg-6c/jdlhuff.c
@@ -0,0 +1,291 @@
+/*
+ * jdlhuff.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains Huffman entropy decoding routines for lossless JPEG.
+ *
+ * Much of the complexity here has to do with supporting input suspension.
+ * If the data source module demands suspension, we want to be able to back
+ * up to the start of the current MCU. To do this, we copy state variables
+ * into local working storage, and update them back to the permanent
+ * storage only upon successful completion of an MCU.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossls.h" /* Private declarations for lossless codec */
+#include "jdhuff.h" /* Declarations shared with jd*huff.c */
+
+
+#ifdef D_LOSSLESS_SUPPORTED
+
+typedef struct {
+ int ci, yoffset, MCU_width;
+} lhd_output_ptr_info;
+
+/*
+ * Private entropy decoder object for lossless Huffman decoding.
+ */
+
+typedef struct {
+ huffd_common_fields; /* Fields shared with other entropy decoders */
+
+ /* Pointers to derived tables (these workspaces have image lifespan) */
+ d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
+
+ /* Precalculated info set up by start_pass for use in decode_mcus: */
+
+ /* Pointers to derived tables to be used for each data unit within an MCU */
+ d_derived_tbl * cur_tbls[D_MAX_DATA_UNITS_IN_MCU];
+
+ /* Pointers to the proper output difference row for each group of data units
+ * within an MCU. For each component, there are Vi groups of Hi data units.
+ */
+ JDIFFROW output_ptr[D_MAX_DATA_UNITS_IN_MCU];
+
+ /* Number of output pointers in use for the current MCU. This is the sum
+ * of all Vi in the MCU.
+ */
+ int num_output_ptrs;
+
+ /* Information used for positioning the output pointers within the output
+ * difference rows.
+ */
+ lhd_output_ptr_info output_ptr_info[D_MAX_DATA_UNITS_IN_MCU];
+
+ /* Index of the proper output pointer for each data unit within an MCU */
+ int output_ptr_index[D_MAX_DATA_UNITS_IN_MCU];
+
+} lhuff_entropy_decoder;
+
+typedef lhuff_entropy_decoder * lhuff_entropy_ptr;
+
+
+/*
+ * Initialize for a Huffman-compressed scan.
+ */
+
+METHODDEF(void)
+start_pass_lhuff_decoder (j_decompress_ptr cinfo)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsd->entropy_private;
+ int ci, dctbl, sampn, ptrn, yoffset, xoffset;
+ jpeg_component_info * compptr;
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ dctbl = compptr->dc_tbl_no;
+ /* Make sure requested tables are present */
+ if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS ||
+ cinfo->dc_huff_tbl_ptrs[dctbl] == NULL)
+ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
+ /* Compute derived values for Huffman tables */
+ /* We may do this more than once for a table, but it's not expensive */
+ jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
+ & entropy->derived_tbls[dctbl]);
+ }
+
+ /* Precalculate decoding info for each sample in an MCU of this scan */
+ for (sampn = 0, ptrn = 0; sampn < cinfo->data_units_in_MCU;) {
+ compptr = cinfo->cur_comp_info[cinfo->MCU_membership[sampn]];
+ ci = compptr->component_index;
+ for (yoffset = 0; yoffset < compptr->MCU_height; yoffset++, ptrn++) {
+ /* Precalculate the setup info for each output pointer */
+ entropy->output_ptr_info[ptrn].ci = ci;
+ entropy->output_ptr_info[ptrn].yoffset = yoffset;
+ entropy->output_ptr_info[ptrn].MCU_width = compptr->MCU_width;
+ for (xoffset = 0; xoffset < compptr->MCU_width; xoffset++, sampn++) {
+ /* Precalculate the output pointer index for each sample */
+ entropy->output_ptr_index[sampn] = ptrn;
+ /* Precalculate which table to use for each sample */
+ entropy->cur_tbls[sampn] = entropy->derived_tbls[compptr->dc_tbl_no];
+ }
+ }
+ }
+ entropy->num_output_ptrs = ptrn;
+
+ /* Initialize bitread state variables */
+ entropy->bitstate.bits_left = 0;
+ entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
+ entropy->insufficient_data = FALSE;
+}
+
+
+/*
+ * Figure F.12: extend sign bit.
+ * On some machines, a shift and add will be faster than a table lookup.
+ */
+
+#ifdef AVOID_TABLES
+
+#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
+
+#else
+
+#define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
+
+static const int extend_test[16] = /* entry n is 2**(n-1) */
+ { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
+ 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
+
+static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
+ { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
+ ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
+ ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
+ ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
+
+#endif /* AVOID_TABLES */
+
+
+/*
+ * Check for a restart marker & resynchronize decoder.
+ * Returns FALSE if must suspend.
+ */
+
+METHODDEF(boolean)
+process_restart (j_decompress_ptr cinfo)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsd->entropy_private;
+/* int ci;*/
+
+ /* Throw away any unused bits remaining in bit buffer; */
+ /* include any full bytes in next_marker's count of discarded bytes */
+ cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
+ entropy->bitstate.bits_left = 0;
+
+ /* Advance past the RSTn marker */
+ if (! (*cinfo->marker->read_restart_marker) (cinfo))
+ return FALSE;
+
+ /* Reset out-of-data flag, unless read_restart_marker left us smack up
+ * against a marker. In that case we will end up treating the next data
+ * segment as empty, and we can avoid producing bogus output pixels by
+ * leaving the flag set.
+ */
+ if (cinfo->unread_marker == 0)
+ entropy->insufficient_data = FALSE;
+
+ return TRUE;
+}
+
+
+/*
+ * Decode and return nMCU's worth of Huffman-compressed differences.
+ * Each MCU is also disassembled and placed accordingly in diff_buf.
+ *
+ * MCU_col_num specifies the column of the first MCU being requested within
+ * the MCU-row. This tells us where to position the output row pointers in
+ * diff_buf.
+ *
+ * Returns the number of MCUs decoded. This may be less than nMCU if data
+ * source requested suspension. In that case no changes have been made to
+ * permanent state. (Exception: some output differences may already have
+ * been assigned. This is harmless for this module, since we'll just
+ * re-assign them on the next call.)
+ */
+
+METHODDEF(JDIMENSION)
+decode_mcus (j_decompress_ptr cinfo, JDIFFIMAGE diff_buf,
+ JDIMENSION MCU_row_num, JDIMENSION MCU_col_num, JDIMENSION nMCU)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsd->entropy_private;
+ int mcu_num, sampn, ci, yoffset, MCU_width, ptrn;
+ BITREAD_STATE_VARS;
+
+ /* Set output pointer locations based on MCU_col_num */
+ for (ptrn = 0; ptrn < entropy->num_output_ptrs; ptrn++) {
+ ci = entropy->output_ptr_info[ptrn].ci;
+ yoffset = entropy->output_ptr_info[ptrn].yoffset;
+ MCU_width = entropy->output_ptr_info[ptrn].MCU_width;
+ entropy->output_ptr[ptrn] =
+ diff_buf[ci][MCU_row_num + yoffset] + (MCU_col_num * MCU_width);
+ }
+
+ /*
+ * If we've run out of data, zero out the buffers and return.
+ * By resetting the undifferencer, the output samples will be CENTERJSAMPLE.
+ *
+ * NB: We should find a way to do this without interacting with the
+ * undifferencer module directly.
+ */
+ if (entropy->insufficient_data) {
+ for (ptrn = 0; ptrn < entropy->num_output_ptrs; ptrn++)
+ jzero_far((void FAR *) entropy->output_ptr[ptrn],
+ nMCU * entropy->output_ptr_info[ptrn].MCU_width * SIZEOF(JDIFF));
+
+ (*losslsd->predict_process_restart) (cinfo);
+ }
+
+ else {
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+
+ /* Outer loop handles the number of MCU requested */
+
+ for (mcu_num = 0; mcu_num < nMCU; mcu_num++) {
+
+ /* Inner loop handles the samples in the MCU */
+ for (sampn = 0; sampn < cinfo->data_units_in_MCU; sampn++) {
+ d_derived_tbl * dctbl = entropy->cur_tbls[sampn];
+ register int s, r;
+
+ /* Section H.2.2: decode the sample difference */
+ HUFF_DECODE(s, br_state, dctbl, return mcu_num, label1);
+ if (s) {
+ if (s == 16) /* special case: always output 32768 */
+ s = 32768;
+ else { /* normal case: fetch subsequent bits */
+ CHECK_BIT_BUFFER(br_state, s, return mcu_num);
+ r = GET_BITS(s);
+ s = HUFF_EXTEND(r, s);
+ }
+ }
+
+ /* Output the sample difference */
+ *entropy->output_ptr[entropy->output_ptr_index[sampn]]++ = (JDIFF) s;
+ }
+
+ /* Completed MCU, so update state */
+ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
+ }
+ }
+
+ return nMCU;
+}
+
+
+/*
+ * Module initialization routine for lossless Huffman entropy decoding.
+ */
+
+GLOBAL(void)
+jinit_lhuff_decoder (j_decompress_ptr cinfo)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ lhuff_entropy_ptr entropy;
+ int i;
+
+ entropy = (lhuff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(lhuff_entropy_decoder));
+ losslsd->entropy_private = (void *) entropy;
+ losslsd->entropy_start_pass = start_pass_lhuff_decoder;
+ losslsd->entropy_process_restart = process_restart;
+ losslsd->entropy_decode_mcus = decode_mcus;
+
+ /* Mark tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ entropy->derived_tbls[i] = NULL;
+ }
+}
+
+#endif /* D_LOSSLESS_SUPPORTED */
diff --git a/jpeg-6c/jdlossls.c b/jpeg-6c/jdlossls.c
new file mode 100644
index 0000000..83f95a2
--- /dev/null
+++ b/jpeg-6c/jdlossls.c
@@ -0,0 +1,94 @@
+/*
+ * jdlossls.c
+ *
+ * Copyright (C) 1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the control logic for the lossless JPEG decompressor.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossls.h"
+
+
+#ifdef D_LOSSLESS_SUPPORTED
+
+/*
+ * Compute output image dimensions and related values.
+ */
+
+METHODDEF(void)
+calc_output_dimensions (j_decompress_ptr cinfo)
+{
+ /* Hardwire it to "no scaling" */
+ cinfo->output_width = cinfo->image_width;
+ cinfo->output_height = cinfo->image_height;
+ /* jdinput.c has already initialized codec_data_unit to 1,
+ * and has computed unscaled downsampled_width and downsampled_height.
+ */
+}
+
+
+/*
+ * Initialize for an input processing pass.
+ */
+
+METHODDEF(void)
+start_input_pass (j_decompress_ptr cinfo)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+
+ (*losslsd->entropy_start_pass) (cinfo);
+ (*losslsd->predict_start_pass) (cinfo);
+ (*losslsd->scaler_start_pass) (cinfo);
+ (*losslsd->diff_start_input_pass) (cinfo);
+}
+
+
+/*
+ * Initialize the lossless decompression codec.
+ * This is called only once, during master selection.
+ */
+
+GLOBAL(void)
+jinit_lossless_d_codec(j_decompress_ptr cinfo)
+{
+ j_lossless_d_ptr losslsd;
+ boolean use_c_buffer;
+
+ /* Create subobject in permanent pool */
+ losslsd = (j_lossless_d_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(jpeg_lossless_d_codec));
+ cinfo->codec = (struct jpeg_d_codec *) losslsd;
+
+ /* Initialize sub-modules */
+ /* Entropy decoding: either Huffman or arithmetic coding. */
+ if (cinfo->arith_code) {
+ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+ } else {
+ jinit_lhuff_decoder(cinfo);
+ }
+
+ /* Undifferencer */
+ jinit_undifferencer(cinfo);
+
+ /* Scaler */
+ jinit_d_scaler(cinfo);
+
+ use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
+ jinit_d_diff_controller(cinfo, use_c_buffer);
+
+ /* Initialize method pointers.
+ *
+ * Note: consume_data, start_output_pass and decompress_data are
+ * assigned in jddiffct.c.
+ */
+ losslsd->pub.calc_output_dimensions = calc_output_dimensions;
+ losslsd->pub.start_input_pass = start_input_pass;
+}
+
+#endif /* D_LOSSLESS_SUPPORTED */
diff --git a/jpeg-6c/jdlossy.c b/jpeg-6c/jdlossy.c
new file mode 100644
index 0000000..a233ae4
--- /dev/null
+++ b/jpeg-6c/jdlossy.c
@@ -0,0 +1,228 @@
+/*
+ * jdlossy.c
+ *
+ * Copyright (C) 1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the control logic for the lossy JPEG decompressor.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h"
+
+
+/*
+ * Compute output image dimensions and related values.
+ */
+
+METHODDEF(void)
+calc_output_dimensions (j_decompress_ptr cinfo)
+{
+#ifdef IDCT_SCALING_SUPPORTED
+ int ci;
+ jpeg_component_info *compptr;
+
+ /* Compute actual output image dimensions and DCT scaling choices. */
+ if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
+ /* Provide 1/8 scaling */
+ cinfo->output_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width, 8L);
+ cinfo->output_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height, 8L);
+ cinfo->min_codec_data_unit = 1;
+ } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
+ /* Provide 1/4 scaling */
+ cinfo->output_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width, 4L);
+ cinfo->output_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height, 4L);
+ cinfo->min_codec_data_unit = 2;
+ } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
+ /* Provide 1/2 scaling */
+ cinfo->output_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width, 2L);
+ cinfo->output_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height, 2L);
+ cinfo->min_codec_data_unit = 4;
+ } else {
+ /* Provide 1/1 scaling */
+ cinfo->output_width = cinfo->image_width;
+ cinfo->output_height = cinfo->image_height;
+ cinfo->min_codec_data_unit = DCTSIZE;
+ }
+ /* In selecting the actual DCT scaling for each component, we try to
+ * scale up the chroma components via IDCT scaling rather than upsampling.
+ * This saves time if the upsampler gets to use 1:1 scaling.
+ * Note this code assumes that the supported DCT scalings are powers of 2.
+ */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ int ssize = cinfo->min_codec_data_unit;
+ while (ssize < DCTSIZE &&
+ (compptr->h_samp_factor * ssize * 2 <=
+ cinfo->max_h_samp_factor * cinfo->min_codec_data_unit) &&
+ (compptr->v_samp_factor * ssize * 2 <=
+ cinfo->max_v_samp_factor * cinfo->min_codec_data_unit)) {
+ ssize = ssize * 2;
+ }
+ compptr->codec_data_unit = ssize;
+ }
+
+ /* Recompute downsampled dimensions of components;
+ * application needs to know these if using raw downsampled data.
+ */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Size in samples, after IDCT scaling */
+ compptr->downsampled_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width *
+ (long) (compptr->h_samp_factor * compptr->codec_data_unit),
+ (long) (cinfo->max_h_samp_factor * DCTSIZE));
+ compptr->downsampled_height = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height *
+ (long) (compptr->v_samp_factor * compptr->codec_data_unit),
+ (long) (cinfo->max_v_samp_factor * DCTSIZE));
+ }
+
+#else /* !IDCT_SCALING_SUPPORTED */
+
+ /* Hardwire it to "no scaling" */
+ cinfo->output_width = cinfo->image_width;
+ cinfo->output_height = cinfo->image_height;
+ /* jdinput.c has already initialized codec_data_unit to DCTSIZE,
+ * and has computed unscaled downsampled_width and downsampled_height.
+ */
+
+#endif /* IDCT_SCALING_SUPPORTED */
+}
+
+
+/*
+ * Save away a copy of the Q-table referenced by each component present
+ * in the current scan, unless already saved during a prior scan.
+ *
+ * In a multiple-scan JPEG file, the encoder could assign different components
+ * the same Q-table slot number, but change table definitions between scans
+ * so that each component uses a different Q-table. (The IJG encoder is not
+ * currently capable of doing this, but other encoders might.) Since we want
+ * to be able to dequantize all the components at the end of the file, this
+ * means that we have to save away the table actually used for each component.
+ * We do this by copying the table at the start of the first scan containing
+ * the component.
+ * The JPEG spec prohibits the encoder from changing the contents of a Q-table
+ * slot between scans of a component using that slot. If the encoder does so
+ * anyway, this decoder will simply use the Q-table values that were current
+ * at the start of the first scan for the component.
+ *
+ * The decompressor output side looks only at the saved quant tables,
+ * not at the current Q-table slots.
+ */
+
+LOCAL(void)
+latch_quant_tables (j_decompress_ptr cinfo)
+{
+ int ci, qtblno;
+ jpeg_component_info *compptr;
+ JQUANT_TBL * qtbl;
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* No work if we already saved Q-table for this component */
+ if (compptr->quant_table != NULL)
+ continue;
+ /* Make sure specified quantization table is present */
+ qtblno = compptr->quant_tbl_no;
+ if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
+ cinfo->quant_tbl_ptrs[qtblno] == NULL)
+ ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
+ /* OK, save away the quantization table */
+ qtbl = (JQUANT_TBL *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(JQUANT_TBL));
+ MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
+ compptr->quant_table = qtbl;
+ }
+}
+
+
+/*
+ * Initialize for an input processing pass.
+ */
+
+METHODDEF(void)
+start_input_pass (j_decompress_ptr cinfo)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+
+ latch_quant_tables(cinfo);
+ (*lossyd->entropy_start_pass) (cinfo);
+ (*lossyd->coef_start_input_pass) (cinfo);
+}
+
+
+/*
+ * Initialize for an output processing pass.
+ */
+
+METHODDEF(void)
+start_output_pass (j_decompress_ptr cinfo)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+
+ (*lossyd->idct_start_pass) (cinfo);
+ (*lossyd->coef_start_output_pass) (cinfo);
+}
+
+/*
+ * Initialize the lossy decompression codec.
+ * This is called only once, during master selection.
+ */
+
+GLOBAL(void)
+jinit_lossy_d_codec (j_decompress_ptr cinfo)
+{
+ j_lossy_d_ptr lossyd;
+ boolean use_c_buffer;
+
+ /* Create subobject in permanent pool */
+ lossyd = (j_lossy_d_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(jpeg_lossy_d_codec));
+ cinfo->codec = (struct jpeg_d_codec *) lossyd;
+
+ /* Initialize sub-modules */
+
+ /* Inverse DCT */
+ jinit_inverse_dct(cinfo);
+ /* Entropy decoding: either Huffman or arithmetic coding. */
+ if (cinfo->arith_code) {
+ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+ } else {
+ if (cinfo->process == JPROC_PROGRESSIVE) {
+#ifdef D_PROGRESSIVE_SUPPORTED
+ jinit_phuff_decoder(cinfo);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else
+ jinit_shuff_decoder(cinfo);
+ }
+
+ use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
+ jinit_d_coef_controller(cinfo, use_c_buffer);
+
+ /* Initialize method pointers.
+ *
+ * Note: consume_data and decompress_data are assigned in jdcoefct.c.
+ */
+ lossyd->pub.calc_output_dimensions = calc_output_dimensions;
+ lossyd->pub.start_input_pass = start_input_pass;
+ lossyd->pub.start_output_pass = start_output_pass;
+}
+
+
+
+
diff --git a/jpeg-6c/jdmainct.c b/jpeg-6c/jdmainct.c
new file mode 100644
index 0000000..7503b32
--- /dev/null
+++ b/jpeg-6c/jdmainct.c
@@ -0,0 +1,513 @@
+/*
+ * jdmainct.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the main buffer controller for decompression.
+ * The main buffer lies between the JPEG decompressor proper and the
+ * post-processor; it holds downsampled data in the JPEG colorspace.
+ *
+ * Note that this code is bypassed in raw-data mode, since the application
+ * supplies the equivalent of the main buffer in that case.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * In the current system design, the main buffer need never be a full-image
+ * buffer; any full-height buffers will be found inside the coefficient or
+ * postprocessing controllers. Nonetheless, the main controller is not
+ * trivial. Its responsibility is to provide context rows for upsampling/
+ * rescaling, and doing this in an efficient fashion is a bit tricky.
+ *
+ * Postprocessor input data is counted in "row groups". A row group
+ * is defined to be (v_samp_factor * codec_data_unit / min_codec_data_unit)
+ * sample rows of each component. (We require codec_data_unit values to be
+ * chosen such that these numbers are integers. In practice codec_data_unit
+ * values will likely be powers of two, so we actually have the stronger
+ * condition that codec_data_unit / min_codec_data_unit is an integer.)
+ * Upsampling will typically produce max_v_samp_factor pixel rows from each
+ * row group (times any additional scale factor that the upsampler is
+ * applying).
+ *
+ * The decompression codec will deliver data to us one iMCU row at a time;
+ * each iMCU row contains v_samp_factor * codec_data_unit sample rows, or
+ * exactly min_codec_data_unit row groups. (This amount of data corresponds
+ * to one row of MCUs when the image is fully interleaved.) Note that the
+ * number of sample rows varies across components, but the number of row
+ * groups does not. Some garbage sample rows may be included in the last iMCU
+ * row at the bottom of the image.
+ *
+ * Depending on the vertical scaling algorithm used, the upsampler may need
+ * access to the sample row(s) above and below its current input row group.
+ * The upsampler is required to set need_context_rows TRUE at global selection
+ * time if so. When need_context_rows is FALSE, this controller can simply
+ * obtain one iMCU row at a time from the coefficient controller and dole it
+ * out as row groups to the postprocessor.
+ *
+ * When need_context_rows is TRUE, this controller guarantees that the buffer
+ * passed to postprocessing contains at least one row group's worth of samples
+ * above and below the row group(s) being processed. Note that the context
+ * rows "above" the first passed row group appear at negative row offsets in
+ * the passed buffer. At the top and bottom of the image, the required
+ * context rows are manufactured by duplicating the first or last real sample
+ * row; this avoids having special cases in the upsampling inner loops.
+ *
+ * The amount of context is fixed at one row group just because that's a
+ * convenient number for this controller to work with. The existing
+ * upsamplers really only need one sample row of context. An upsampler
+ * supporting arbitrary output rescaling might wish for more than one row
+ * group of context when shrinking the image; tough, we don't handle that.
+ * (This is justified by the assumption that downsizing will be handled mostly
+ * by adjusting the codec_data_unit values, so that the actual scale factor at
+ * the upsample step needn't be much less than one.)
+ *
+ * To provide the desired context, we have to retain the last two row groups
+ * of one iMCU row while reading in the next iMCU row. (The last row group
+ * can't be processed until we have another row group for its below-context,
+ * and so we have to save the next-to-last group too for its above-context.)
+ * We could do this most simply by copying data around in our buffer, but
+ * that'd be very slow. We can avoid copying any data by creating a rather
+ * strange pointer structure. Here's how it works. We allocate a workspace
+ * consisting of M+2 row groups (where M = min_codec_data_unit is the number
+ * of row groups per iMCU row). We create two sets of redundant pointers to
+ * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
+ * pointer lists look like this:
+ * M+1 M-1
+ * master pointer --> 0 master pointer --> 0
+ * 1 1
+ * ... ...
+ * M-3 M-3
+ * M-2 M
+ * M-1 M+1
+ * M M-2
+ * M+1 M-1
+ * 0 0
+ * We read alternate iMCU rows using each master pointer; thus the last two
+ * row groups of the previous iMCU row remain un-overwritten in the workspace.
+ * The pointer lists are set up so that the required context rows appear to
+ * be adjacent to the proper places when we pass the pointer lists to the
+ * upsampler.
+ *
+ * The above pictures describe the normal state of the pointer lists.
+ * At top and bottom of the image, we diddle the pointer lists to duplicate
+ * the first or last sample row as necessary (this is cheaper than copying
+ * sample rows around).
+ *
+ * This scheme breaks down if M < 2, ie, min_codec_data_unit is 1. In that
+ * situation each iMCU row provides only one row group so the buffering logic
+ * must be different (eg, we must read two iMCU rows before we can emit the
+ * first row group). For now, we simply do not support providing context
+ * rows when min_codec_data_unit is 1. That combination seems unlikely to
+ * be worth providing --- if someone wants a 1/8th-size preview, they probably
+ * want it quick and dirty, so a context-free upsampler is sufficient.
+ */
+
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_d_main_controller pub; /* public fields */
+
+ /* Pointer to allocated workspace (M or M+2 row groups). */
+ JSAMPARRAY16 buffer[MAX_COMPONENTS];
+
+ boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
+ JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
+
+ /* Remaining fields are only used in the context case. */
+
+ /* These are the master pointers to the funny-order pointer lists. */
+ JSAMPIMAGE16 xbuffer[2]; /* pointers to weird pointer lists */
+
+ int whichptr; /* indicates which pointer set is now in use */
+ int context_state; /* process_data state machine status */
+ JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
+ JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
+} my_main_controller;
+
+typedef my_main_controller * my_main_ptr;
+
+/* context_state values: */
+#define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
+#define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
+#define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
+
+
+/* Forward declarations */
+METHODDEF(void) process_data_simple_main
+ JPP((j_decompress_ptr cinfo, JSAMPARRAY16 output_buf,
+ JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
+METHODDEF(void) process_data_context_main
+ JPP((j_decompress_ptr cinfo, JSAMPARRAY16 output_buf,
+ JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
+#ifdef QUANT_2PASS_SUPPORTED
+METHODDEF(void) process_data_crank_post
+ JPP((j_decompress_ptr cinfo, JSAMPARRAY16 output_buf,
+ JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
+#endif
+
+
+LOCAL(void)
+alloc_funny_pointers (j_decompress_ptr cinfo)
+/* Allocate space for the funny pointer lists.
+ * This is done only once, not once per pass.
+ */
+{
+ my_main_ptr mainp = (my_main_ptr) cinfo->mainp;
+ int ci, rgroup;
+ int M = cinfo->min_codec_data_unit;
+ jpeg_component_info *compptr;
+ JSAMPARRAY16 xbuf;
+
+ /* Get top-level space for component array pointers.
+ * We alloc both arrays with one call to save a few cycles.
+ */
+ mainp->xbuffer[0] = (JSAMPIMAGE16)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->num_components * 2 * SIZEOF(JSAMPARRAY16));
+ mainp->xbuffer[1] = mainp->xbuffer[0] + cinfo->num_components;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ rgroup = (compptr->v_samp_factor * compptr->codec_data_unit) /
+ cinfo->min_codec_data_unit; /* height of a row group of component */
+ /* Get space for pointer lists --- M+4 row groups in each list.
+ * We alloc both pointer lists with one call to save a few cycles.
+ */
+ xbuf = (JSAMPARRAY16)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW16));
+ xbuf += rgroup; /* want one row group at negative offsets */
+ mainp->xbuffer[0][ci] = xbuf;
+ xbuf += rgroup * (M + 4);
+ mainp->xbuffer[1][ci] = xbuf;
+ }
+}
+
+
+LOCAL(void)
+make_funny_pointers (j_decompress_ptr cinfo)
+/* Create the funny pointer lists discussed in the comments above.
+ * The actual workspace is already allocated (in mainp->buffer),
+ * and the space for the pointer lists is allocated too.
+ * This routine just fills in the curiously ordered lists.
+ * This will be repeated at the beginning of each pass.
+ */
+{
+ my_main_ptr mainp = (my_main_ptr) cinfo->mainp;
+ int ci, i, rgroup;
+ int M = cinfo->min_codec_data_unit;
+ jpeg_component_info *compptr;
+ JSAMPARRAY16 buf, xbuf0, xbuf1;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ rgroup = (compptr->v_samp_factor * compptr->codec_data_unit) /
+ cinfo->min_codec_data_unit; /* height of a row group of component */
+ xbuf0 = mainp->xbuffer[0][ci];
+ xbuf1 = mainp->xbuffer[1][ci];
+ /* First copy the workspace pointers as-is */
+ buf = mainp->buffer[ci];
+ for (i = 0; i < rgroup * (M + 2); i++) {
+ xbuf0[i] = xbuf1[i] = buf[i];
+ }
+ /* In the second list, put the last four row groups in swapped order */
+ for (i = 0; i < rgroup * 2; i++) {
+ xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
+ xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
+ }
+ /* The wraparound pointers at top and bottom will be filled later
+ * (see set_wraparound_pointers, below). Initially we want the "above"
+ * pointers to duplicate the first actual data line. This only needs
+ * to happen in xbuffer[0].
+ */
+ for (i = 0; i < rgroup; i++) {
+ xbuf0[i - rgroup] = xbuf0[0];
+ }
+ }
+}
+
+
+LOCAL(void)
+set_wraparound_pointers (j_decompress_ptr cinfo)
+/* Set up the "wraparound" pointers at top and bottom of the pointer lists.
+ * This changes the pointer list state from top-of-image to the normal state.
+ */
+{
+ my_main_ptr mainp = (my_main_ptr) cinfo->mainp;
+ int ci, i, rgroup;
+ int M = cinfo->min_codec_data_unit;
+ jpeg_component_info *compptr;
+ JSAMPARRAY16 xbuf0, xbuf1;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ rgroup = (compptr->v_samp_factor * compptr->codec_data_unit) /
+ cinfo->min_codec_data_unit; /* height of a row group of component */
+ xbuf0 = mainp->xbuffer[0][ci];
+ xbuf1 = mainp->xbuffer[1][ci];
+ for (i = 0; i < rgroup; i++) {
+ xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
+ xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
+ xbuf0[rgroup*(M+2) + i] = xbuf0[i];
+ xbuf1[rgroup*(M+2) + i] = xbuf1[i];
+ }
+ }
+}
+
+
+LOCAL(void)
+set_bottom_pointers (j_decompress_ptr cinfo)
+/* Change the pointer lists to duplicate the last sample row at the bottom
+ * of the image. whichptr indicates which xbuffer holds the final iMCU row.
+ * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
+ */
+{
+ my_main_ptr mainp = (my_main_ptr) cinfo->mainp;
+ int ci, i, rgroup, iMCUheight, rows_left;
+ jpeg_component_info *compptr;
+ JSAMPARRAY16 xbuf;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Count sample rows in one iMCU row and in one row group */
+ iMCUheight = compptr->v_samp_factor * compptr->codec_data_unit;
+ rgroup = iMCUheight / cinfo->min_codec_data_unit;
+ /* Count nondummy sample rows remaining for this component */
+ rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
+ if (rows_left == 0) rows_left = iMCUheight;
+ /* Count nondummy row groups. Should get same answer for each component,
+ * so we need only do it once.
+ */
+ if (ci == 0) {
+ mainp->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
+ }
+ /* Duplicate the last real sample row rgroup*2 times; this pads out the
+ * last partial rowgroup and ensures at least one full rowgroup of context.
+ */
+ xbuf = mainp->xbuffer[mainp->whichptr][ci];
+ for (i = 0; i < rgroup * 2; i++) {
+ xbuf[rows_left + i] = xbuf[rows_left-1];
+ }
+ }
+}
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF(void)
+start_pass_main (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ my_main_ptr mainp = (my_main_ptr) cinfo->mainp;
+
+ switch (pass_mode) {
+ case JBUF_PASS_THRU:
+ if (cinfo->upsample->need_context_rows) {
+ mainp->pub.process_data = process_data_context_main;
+ make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
+ mainp->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
+ mainp->context_state = CTX_PREPARE_FOR_IMCU;
+ mainp->iMCU_row_ctr = 0;
+ } else {
+ /* Simple case with no context needed */
+ mainp->pub.process_data = process_data_simple_main;
+ }
+ mainp->buffer_full = FALSE; /* Mark buffer empty */
+ mainp->rowgroup_ctr = 0;
+ break;
+#ifdef QUANT_2PASS_SUPPORTED
+ case JBUF_CRANK_DEST:
+ /* For last pass of 2-pass quantization, just crank the postprocessor */
+ mainp->pub.process_data = process_data_crank_post;
+ break;
+#endif
+ default:
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ break;
+ }
+}
+
+
+/*
+ * Process some data.
+ * This handles the simple case where no context is required.
+ */
+
+METHODDEF(void)
+process_data_simple_main (j_decompress_ptr cinfo,
+ JSAMPARRAY16 output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_main_ptr mainp = (my_main_ptr) cinfo->mainp;
+ JDIMENSION rowgroups_avail;
+
+ /* Read input data if we haven't filled the main buffer yet */
+ if (! mainp->buffer_full) {
+ if (! (*cinfo->codec->decompress_data) (cinfo, mainp->buffer))
+ return; /* suspension forced, can do nothing more */
+ mainp->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
+ }
+
+ /* There are always min_codec_data_unit row groups in an iMCU row. */
+ rowgroups_avail = (JDIMENSION) cinfo->min_codec_data_unit;
+ /* Note: at the bottom of the image, we may pass extra garbage row groups
+ * to the postprocessor. The postprocessor has to check for bottom
+ * of image anyway (at row resolution), so no point in us doing it too.
+ */
+
+ /* Feed the postprocessor */
+ (*cinfo->post->post_process_data) (cinfo, mainp->buffer,
+ &mainp->rowgroup_ctr, rowgroups_avail,
+ output_buf, out_row_ctr, out_rows_avail);
+
+ /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
+ if (mainp->rowgroup_ctr >= rowgroups_avail) {
+ mainp->buffer_full = FALSE;
+ mainp->rowgroup_ctr = 0;
+ }
+}
+
+
+/*
+ * Process some data.
+ * This handles the case where context rows must be provided.
+ */
+
+METHODDEF(void)
+process_data_context_main (j_decompress_ptr cinfo,
+ JSAMPARRAY16 output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_main_ptr mainp = (my_main_ptr) cinfo->mainp;
+
+ /* Read input data if we haven't filled the main buffer yet */
+ if (! mainp->buffer_full) {
+ if (! (*cinfo->codec->decompress_data) (cinfo,
+ mainp->xbuffer[mainp->whichptr]))
+ return; /* suspension forced, can do nothing more */
+ mainp->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
+ mainp->iMCU_row_ctr++; /* count rows received */
+ }
+
+ /* Postprocessor typically will not swallow all the input data it is handed
+ * in one call (due to filling the output buffer first). Must be prepared
+ * to exit and restart. This switch lets us keep track of how far we got.
+ * Note that each case falls through to the next on successful completion.
+ */
+ switch (mainp->context_state) {
+ case CTX_POSTPONED_ROW:
+ /* Call postprocessor using previously set pointers for postponed row */
+ (*cinfo->post->post_process_data) (cinfo, mainp->xbuffer[mainp->whichptr],
+ &mainp->rowgroup_ctr, mainp->rowgroups_avail,
+ output_buf, out_row_ctr, out_rows_avail);
+ if (mainp->rowgroup_ctr < mainp->rowgroups_avail)
+ return; /* Need to suspend */
+ mainp->context_state = CTX_PREPARE_FOR_IMCU;
+ if (*out_row_ctr >= out_rows_avail)
+ return; /* Postprocessor exactly filled output buf */
+ /*FALLTHROUGH*/
+ case CTX_PREPARE_FOR_IMCU:
+ /* Prepare to process first M-1 row groups of this iMCU row */
+ mainp->rowgroup_ctr = 0;
+ mainp->rowgroups_avail = (JDIMENSION) (cinfo->min_codec_data_unit - 1);
+ /* Check for bottom of image: if so, tweak pointers to "duplicate"
+ * the last sample row, and adjust rowgroups_avail to ignore padding rows.
+ */
+ if (mainp->iMCU_row_ctr == cinfo->total_iMCU_rows)
+ set_bottom_pointers(cinfo);
+ mainp->context_state = CTX_PROCESS_IMCU;
+ /*FALLTHROUGH*/
+ case CTX_PROCESS_IMCU:
+ /* Call postprocessor using previously set pointers */
+ (*cinfo->post->post_process_data) (cinfo, mainp->xbuffer[mainp->whichptr],
+ &mainp->rowgroup_ctr, mainp->rowgroups_avail,
+ output_buf, out_row_ctr, out_rows_avail);
+ if (mainp->rowgroup_ctr < mainp->rowgroups_avail)
+ return; /* Need to suspend */
+ /* After the first iMCU, change wraparound pointers to normal state */
+ if (mainp->iMCU_row_ctr == 1)
+ set_wraparound_pointers(cinfo);
+ /* Prepare to load new iMCU row using other xbuffer list */
+ mainp->whichptr ^= 1; /* 0=>1 or 1=>0 */
+ mainp->buffer_full = FALSE;
+ /* Still need to process last row group of this iMCU row, */
+ /* which is saved at index M+1 of the other xbuffer */
+ mainp->rowgroup_ctr = (JDIMENSION) (cinfo->min_codec_data_unit + 1);
+ mainp->rowgroups_avail = (JDIMENSION) (cinfo->min_codec_data_unit + 2);
+ mainp->context_state = CTX_POSTPONED_ROW;
+ }
+}
+
+
+/*
+ * Process some data.
+ * Final pass of two-pass quantization: just call the postprocessor.
+ * Source data will be the postprocessor controller's internal buffer.
+ */
+
+#ifdef QUANT_2PASS_SUPPORTED
+
+METHODDEF(void)
+process_data_crank_post (j_decompress_ptr cinfo,
+ JSAMPARRAY16 output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE16) NULL,
+ (JDIMENSION *) NULL, (JDIMENSION) 0,
+ output_buf, out_row_ctr, out_rows_avail);
+}
+
+#endif /* QUANT_2PASS_SUPPORTED */
+
+
+/*
+ * Initialize main buffer controller.
+ */
+
+GLOBAL(void)
+jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
+{
+ my_main_ptr mainp;
+ int ci, rgroup, ngroups;
+ jpeg_component_info *compptr;
+
+ mainp = (my_main_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_main_controller));
+ cinfo->mainp = (struct jpeg_d_main_controller *) mainp;
+ mainp->pub.start_pass = start_pass_main;
+
+ if (need_full_buffer) /* shouldn't happen */
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+
+ /* Allocate the workspace.
+ * ngroups is the number of row groups we need.
+ */
+ if (cinfo->upsample->need_context_rows) {
+ if (cinfo->min_codec_data_unit < 2) /* unsupported, see comments above */
+ ERREXIT(cinfo, JERR_NOTIMPL);
+ alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
+ ngroups = cinfo->min_codec_data_unit + 2;
+ } else {
+ ngroups = cinfo->min_codec_data_unit;
+ }
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ rgroup = (compptr->v_samp_factor * compptr->codec_data_unit) /
+ cinfo->min_codec_data_unit; /* height of a row group of component */
+ mainp->buffer[ci] = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ compptr->width_in_data_units * compptr->codec_data_unit *
+ SIZEOF(JSAMPLE16), (JDIMENSION) (rgroup * ngroups));
+ }
+}
diff --git a/jpeg-6c/jdmarker.c b/jpeg-6c/jdmarker.c
new file mode 100644
index 0000000..0ab5822
--- /dev/null
+++ b/jpeg-6c/jdmarker.c
@@ -0,0 +1,1376 @@
+/*
+ * jdmarker.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to decode JPEG datastream markers.
+ * Most of the complexity arises from our desire to support input
+ * suspension: if not all of the data for a marker is available,
+ * we must exit back to the application. On resumption, we reprocess
+ * the marker.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+typedef enum { /* JPEG marker codes */
+ M_SOF0 = 0xc0,
+ M_SOF1 = 0xc1,
+ M_SOF2 = 0xc2,
+ M_SOF3 = 0xc3,
+
+ M_SOF5 = 0xc5,
+ M_SOF6 = 0xc6,
+ M_SOF7 = 0xc7,
+
+ M_JPG = 0xc8,
+ M_SOF9 = 0xc9,
+ M_SOF10 = 0xca,
+ M_SOF11 = 0xcb,
+
+ M_SOF13 = 0xcd,
+ M_SOF14 = 0xce,
+ M_SOF15 = 0xcf,
+
+ M_DHT = 0xc4,
+
+ M_DAC = 0xcc,
+
+ M_RST0 = 0xd0,
+ M_RST1 = 0xd1,
+ M_RST2 = 0xd2,
+ M_RST3 = 0xd3,
+ M_RST4 = 0xd4,
+ M_RST5 = 0xd5,
+ M_RST6 = 0xd6,
+ M_RST7 = 0xd7,
+
+ M_SOI = 0xd8,
+ M_EOI = 0xd9,
+ M_SOS = 0xda,
+ M_DQT = 0xdb,
+ M_DNL = 0xdc,
+ M_DRI = 0xdd,
+ M_DHP = 0xde,
+ M_EXP = 0xdf,
+
+ M_APP0 = 0xe0,
+ M_APP1 = 0xe1,
+ M_APP2 = 0xe2,
+ M_APP3 = 0xe3,
+ M_APP4 = 0xe4,
+ M_APP5 = 0xe5,
+ M_APP6 = 0xe6,
+ M_APP7 = 0xe7,
+ M_APP8 = 0xe8,
+ M_APP9 = 0xe9,
+ M_APP10 = 0xea,
+ M_APP11 = 0xeb,
+ M_APP12 = 0xec,
+ M_APP13 = 0xed,
+ M_APP14 = 0xee,
+ M_APP15 = 0xef,
+
+ M_JPG0 = 0xf0,
+ M_JPG13 = 0xfd,
+ M_COM = 0xfe,
+
+ M_TEM = 0x01,
+
+ M_ERROR = 0x100
+} JPEG_MARKER;
+
+
+/* Private state */
+
+typedef struct {
+ struct jpeg_marker_reader pub; /* public fields */
+
+ /* Application-overridable marker processing methods */
+ jpeg_marker_parser_method process_COM;
+ jpeg_marker_parser_method process_APPn[16];
+
+ /* Limit on marker data length to save for each marker type */
+ unsigned int length_limit_COM;
+ unsigned int length_limit_APPn[16];
+
+ /* Status of COM/APPn marker saving */
+ jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
+ unsigned int bytes_read; /* data bytes read so far in marker */
+ /* Note: cur_marker is not linked into marker_list until it's all read. */
+} my_marker_reader;
+
+typedef my_marker_reader * my_marker_ptr;
+
+
+/*
+ * Macros for fetching data from the data source module.
+ *
+ * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
+ * the current restart point; we update them only when we have reached a
+ * suitable place to restart if a suspension occurs.
+ */
+
+/* Declare and initialize local copies of input pointer/count */
+#define INPUT_VARS(cinfo) \
+ struct jpeg_source_mgr * datasrc = (cinfo)->src; \
+ const JOCTET * next_input_byte = datasrc->next_input_byte; \
+ size_t bytes_in_buffer = datasrc->bytes_in_buffer
+
+/* Unload the local copies --- do this only at a restart boundary */
+#define INPUT_SYNC(cinfo) \
+ ( datasrc->next_input_byte = next_input_byte, \
+ datasrc->bytes_in_buffer = bytes_in_buffer )
+
+/* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
+#define INPUT_RELOAD(cinfo) \
+ ( next_input_byte = datasrc->next_input_byte, \
+ bytes_in_buffer = datasrc->bytes_in_buffer )
+
+/* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
+ * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
+ * but we must reload the local copies after a successful fill.
+ */
+#define MAKE_BYTE_AVAIL(cinfo,action) \
+ if (bytes_in_buffer == 0) { \
+ if (! (*datasrc->fill_input_buffer) (cinfo)) \
+ { action; } \
+ INPUT_RELOAD(cinfo); \
+ }
+
+/* Read a byte into variable V.
+ * If must suspend, take the specified action (typically "return FALSE").
+ */
+#define INPUT_BYTE(cinfo,V,action) \
+ MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
+ bytes_in_buffer--; \
+ V = GETJOCTET(*next_input_byte++); )
+
+/* As above, but read two bytes interpreted as an unsigned 16-bit integer.
+ * V should be declared unsigned int or perhaps INT32.
+ */
+#define INPUT_2BYTES(cinfo,V,action) \
+ MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
+ bytes_in_buffer--; \
+ V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
+ MAKE_BYTE_AVAIL(cinfo,action); \
+ bytes_in_buffer--; \
+ V += GETJOCTET(*next_input_byte++); )
+
+
+/*
+ * Routines to process JPEG markers.
+ *
+ * Entry condition: JPEG marker itself has been read and its code saved
+ * in cinfo->unread_marker; input restart point is just after the marker.
+ *
+ * Exit: if return TRUE, have read and processed any parameters, and have
+ * updated the restart point to point after the parameters.
+ * If return FALSE, was forced to suspend before reaching end of
+ * marker parameters; restart point has not been moved. Same routine
+ * will be called again after application supplies more input data.
+ *
+ * This approach to suspension assumes that all of a marker's parameters
+ * can fit into a single input bufferload. This should hold for "normal"
+ * markers. Some COM/APPn markers might have large parameter segments
+ * that might not fit. If we are simply dropping such a marker, we use
+ * skip_input_data to get past it, and thereby put the problem on the
+ * source manager's shoulders. If we are saving the marker's contents
+ * into memory, we use a slightly different convention: when forced to
+ * suspend, the marker processor updates the restart point to the end of
+ * what it's consumed (ie, the end of the buffer) before returning FALSE.
+ * On resumption, cinfo->unread_marker still contains the marker code,
+ * but the data source will point to the next chunk of marker data.
+ * The marker processor must retain internal state to deal with this.
+ *
+ * Note that we don't bother to avoid duplicate trace messages if a
+ * suspension occurs within marker parameters. Other side effects
+ * require more care.
+ */
+
+
+LOCAL(boolean)
+get_soi (j_decompress_ptr cinfo)
+/* Process an SOI marker */
+{
+ int i;
+
+ TRACEMS(cinfo, 1, JTRC_SOI);
+
+ if (cinfo->marker->saw_SOI)
+ ERREXIT(cinfo, JERR_SOI_DUPLICATE);
+
+ /* Reset all parameters that are defined to be reset by SOI */
+
+ for (i = 0; i < NUM_ARITH_TBLS; i++) {
+ cinfo->arith_dc_L[i] = 0;
+ cinfo->arith_dc_U[i] = 1;
+ cinfo->arith_ac_K[i] = 5;
+ }
+ cinfo->restart_interval = 0;
+
+ /* Set initial assumptions for colorspace etc */
+
+ cinfo->jpeg_color_space = JCS_UNKNOWN;
+ cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
+
+ cinfo->saw_JFIF_marker = FALSE;
+ cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
+ cinfo->JFIF_minor_version = 1;
+ cinfo->density_unit = 0;
+ cinfo->X_density = 1;
+ cinfo->Y_density = 1;
+ cinfo->saw_Adobe_marker = FALSE;
+ cinfo->Adobe_transform = 0;
+
+ cinfo->marker->saw_SOI = TRUE;
+
+ return TRUE;
+}
+
+
+LOCAL(boolean)
+get_sof (j_decompress_ptr cinfo, J_CODEC_PROCESS process, boolean is_arith,
+ int data_unit)
+/* Process a SOFn marker */
+{
+ INT32 length;
+ int c, ci;
+ jpeg_component_info * compptr;
+ INPUT_VARS(cinfo);
+
+ cinfo->data_unit = data_unit;
+ cinfo->process = process;
+ cinfo->arith_code = is_arith;
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+
+ INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
+ cinfo->maxjsample = ((1<<cinfo->data_precision)-1);
+ cinfo->centerjsample = ((1<<cinfo->data_precision)/2);
+ cinfo->data_precision_other = 8; /* Default for compatabilty. */
+ cinfo->buffer_size_char = TRUE; /* Default for compatabilty. */
+ cinfo->shft = cinfo->data_precision - 8;
+ INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
+ INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
+ INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
+
+ length -= 8;
+
+ TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
+ (int) cinfo->image_width, (int) cinfo->image_height,
+ cinfo->num_components);
+
+ if (cinfo->marker->saw_SOF)
+ ERREXIT(cinfo, JERR_SOF_DUPLICATE);
+
+ /* We don't support files in which the image height is initially specified */
+ /* as 0 and is later redefined by DNL. As long as we have to check that, */
+ /* might as well have a general sanity check. */
+ if (cinfo->image_height <= 0 || cinfo->image_width <= 0
+ || cinfo->num_components <= 0)
+ ERREXIT(cinfo, JERR_EMPTY_IMAGE);
+
+ if (length != (cinfo->num_components * 3))
+ ERREXIT(cinfo, JERR_BAD_LENGTH);
+
+ if (cinfo->comp_info == NULL) /* do only once, even if suspend */
+ cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->num_components * SIZEOF(jpeg_component_info));
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ compptr->component_index = ci;
+ INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
+ INPUT_BYTE(cinfo, c, return FALSE);
+ compptr->h_samp_factor = (c >> 4) & 15;
+ compptr->v_samp_factor = (c ) & 15;
+ INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
+
+ TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
+ compptr->component_id, compptr->h_samp_factor,
+ compptr->v_samp_factor, compptr->quant_tbl_no);
+ }
+
+ cinfo->marker->saw_SOF = TRUE;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL(boolean)
+get_sos (j_decompress_ptr cinfo)
+/* Process a SOS marker */
+{
+ INT32 length;
+ int i, ci, n, c, cc;
+ jpeg_component_info * compptr;
+ INPUT_VARS(cinfo);
+
+ if (! cinfo->marker->saw_SOF)
+ ERREXIT(cinfo, JERR_SOS_NO_SOF);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+
+ INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
+
+ TRACEMS1(cinfo, 1, JTRC_SOS, n);
+
+ if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
+ ERREXIT(cinfo, JERR_BAD_LENGTH);
+
+ cinfo->comps_in_scan = n;
+
+ /* Collect the component-spec parameters */
+
+ for (i = 0; i < n; i++) {
+ INPUT_BYTE(cinfo, cc, return FALSE);
+ INPUT_BYTE(cinfo, c, return FALSE);
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ if (cc == compptr->component_id)
+ goto id_found;
+ }
+
+ ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
+
+ id_found:
+
+ cinfo->cur_comp_info[i] = compptr;
+ compptr->dc_tbl_no = (c >> 4) & 15;
+ compptr->ac_tbl_no = (c ) & 15;
+
+ TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
+ compptr->dc_tbl_no, compptr->ac_tbl_no);
+ }
+
+ /* Collect the additional scan parameters Ss, Se, Ah/Al. */
+ INPUT_BYTE(cinfo, c, return FALSE);
+ cinfo->Ss = c;
+ INPUT_BYTE(cinfo, c, return FALSE);
+ cinfo->Se = c;
+ INPUT_BYTE(cinfo, c, return FALSE);
+ cinfo->Ah = (c >> 4) & 15;
+ cinfo->Al = (c ) & 15;
+
+ TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
+ cinfo->Ah, cinfo->Al);
+
+ /* Prepare to scan data & restart markers */
+ cinfo->marker->next_restart_num = 0;
+
+ /* Count another SOS marker */
+ cinfo->input_scan_number++;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+#ifdef D_ARITH_CODING_SUPPORTED
+
+LOCAL(boolean)
+get_dac (j_decompress_ptr cinfo)
+/* Process a DAC marker */
+{
+ INT32 length;
+ int index, val;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ while (length > 0) {
+ INPUT_BYTE(cinfo, index, return FALSE);
+ INPUT_BYTE(cinfo, val, return FALSE);
+
+ length -= 2;
+
+ TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
+
+ if (index < 0 || index >= (2*NUM_ARITH_TBLS))
+ ERREXIT1(cinfo, JERR_DAC_INDEX, index);
+
+ if (index >= NUM_ARITH_TBLS) { /* define AC table */
+ cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
+ } else { /* define DC table */
+ cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
+ cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
+ if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
+ ERREXIT1(cinfo, JERR_DAC_VALUE, val);
+ }
+ }
+
+ if (length != 0)
+ ERREXIT(cinfo, JERR_BAD_LENGTH);
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+#else /* ! D_ARITH_CODING_SUPPORTED */
+
+#define get_dac(cinfo) skip_variable(cinfo)
+
+#endif /* D_ARITH_CODING_SUPPORTED */
+
+
+LOCAL(boolean)
+get_dht (j_decompress_ptr cinfo)
+/* Process a DHT marker */
+{
+ INT32 length;
+ UINT8 bits[17];
+ UINT8 huffval[256];
+ int i, index, count;
+ JHUFF_TBL **htblptr;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ while (length > 16) {
+ INPUT_BYTE(cinfo, index, return FALSE);
+
+ TRACEMS1(cinfo, 1, JTRC_DHT, index);
+
+ bits[0] = 0;
+ count = 0;
+ for (i = 1; i <= 16; i++) {
+ INPUT_BYTE(cinfo, bits[i], return FALSE);
+ count += bits[i];
+ }
+
+ length -= 1 + 16;
+
+ TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
+ bits[1], bits[2], bits[3], bits[4],
+ bits[5], bits[6], bits[7], bits[8]);
+ TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
+ bits[9], bits[10], bits[11], bits[12],
+ bits[13], bits[14], bits[15], bits[16]);
+
+ /* Here we just do minimal validation of the counts to avoid walking
+ * off the end of our table space. jdhuff.c will check more carefully.
+ */
+ if (count > 256 || ((INT32) count) > length)
+ ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
+
+ for (i = 0; i < count; i++)
+ INPUT_BYTE(cinfo, huffval[i], return FALSE);
+
+ length -= count;
+
+ if (index & 0x10) { /* AC table definition */
+ index -= 0x10;
+ htblptr = &cinfo->ac_huff_tbl_ptrs[index];
+ } else { /* DC table definition */
+ htblptr = &cinfo->dc_huff_tbl_ptrs[index];
+ }
+
+ if (index < 0 || index >= NUM_HUFF_TBLS)
+ ERREXIT1(cinfo, JERR_DHT_INDEX, index);
+
+ if (*htblptr == NULL)
+ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+
+ MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
+ MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
+ }
+
+ if (length != 0)
+ ERREXIT(cinfo, JERR_BAD_LENGTH);
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL(boolean)
+get_dqt (j_decompress_ptr cinfo)
+/* Process a DQT marker */
+{
+ INT32 length;
+ int n, i, prec = 0;
+ unsigned int tmp;
+ JQUANT_TBL *quant_ptr;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ while (length > 0) {
+ INPUT_BYTE(cinfo, n, return FALSE);
+ prec = n >> 4;
+ n &= 0x0F;
+
+ TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
+
+ if (n >= NUM_QUANT_TBLS)
+ ERREXIT1(cinfo, JERR_DQT_INDEX, n);
+
+ if (cinfo->quant_tbl_ptrs[n] == NULL)
+ cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
+ quant_ptr = cinfo->quant_tbl_ptrs[n];
+
+ for (i = 0; i < DCTSIZE2; i++) {
+ if (prec)
+ INPUT_2BYTES(cinfo, tmp, return FALSE);
+ else
+ INPUT_BYTE(cinfo, tmp, return FALSE);
+ /* We convert the zigzag-order table to natural array order. */
+ quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
+ }
+
+ if (cinfo->err->trace_level >= 2) {
+ for (i = 0; i < DCTSIZE2; i += 8) {
+ TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
+ quant_ptr->quantval[i], quant_ptr->quantval[i+1],
+ quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
+ quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
+ quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
+ }
+ }
+
+ length -= DCTSIZE2+1;
+ if (prec) length -= DCTSIZE2;
+ }
+
+ if (length != 0)
+ ERREXIT(cinfo, JERR_BAD_LENGTH);
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL(boolean)
+get_dri (j_decompress_ptr cinfo)
+/* Process a DRI marker */
+{
+ INT32 length;
+ unsigned int tmp;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+
+ if (length != 4)
+ ERREXIT(cinfo, JERR_BAD_LENGTH);
+
+ INPUT_2BYTES(cinfo, tmp, return FALSE);
+
+ TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
+
+ cinfo->restart_interval = tmp;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+/*
+ * Routines for processing APPn and COM markers.
+ * These are either saved in memory or discarded, per application request.
+ * APP0 and APP14 are specially checked to see if they are
+ * JFIF and Adobe markers, respectively.
+ */
+
+#define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
+#define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
+#define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
+
+
+LOCAL(void)
+examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
+ unsigned int datalen, INT32 remaining)
+/* Examine first few bytes from an APP0.
+ * Take appropriate action if it is a JFIF marker.
+ * datalen is # of bytes at data[], remaining is length of rest of marker data.
+ */
+{
+ INT32 totallen = (INT32) datalen + remaining;
+
+ if (datalen >= APP0_DATA_LEN &&
+ GETJOCTET(data[0]) == 0x4A &&
+ GETJOCTET(data[1]) == 0x46 &&
+ GETJOCTET(data[2]) == 0x49 &&
+ GETJOCTET(data[3]) == 0x46 &&
+ GETJOCTET(data[4]) == 0) {
+ /* Found JFIF APP0 marker: save info */
+ cinfo->saw_JFIF_marker = TRUE;
+ cinfo->JFIF_major_version = GETJOCTET(data[5]);
+ cinfo->JFIF_minor_version = GETJOCTET(data[6]);
+ cinfo->density_unit = GETJOCTET(data[7]);
+ cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
+ cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
+ /* Check version.
+ * Major version must be 1, anything else signals an incompatible change.
+ * (We used to treat this as an error, but now it's a nonfatal warning,
+ * because some bozo at Hijaak couldn't read the spec.)
+ * Minor version should be 0..2, but process anyway if newer.
+ */
+ if (cinfo->JFIF_major_version != 1)
+ WARNMS2(cinfo, JWRN_JFIF_MAJOR,
+ cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
+ /* Generate trace messages */
+ TRACEMS5(cinfo, 1, JTRC_JFIF,
+ cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
+ cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
+ /* Validate thumbnail dimensions and issue appropriate messages */
+ if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
+ TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
+ GETJOCTET(data[12]), GETJOCTET(data[13]));
+ totallen -= APP0_DATA_LEN;
+ if (totallen !=
+ ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
+ TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
+ } else if (datalen >= 6 &&
+ GETJOCTET(data[0]) == 0x4A &&
+ GETJOCTET(data[1]) == 0x46 &&
+ GETJOCTET(data[2]) == 0x58 &&
+ GETJOCTET(data[3]) == 0x58 &&
+ GETJOCTET(data[4]) == 0) {
+ /* Found JFIF "JFXX" extension APP0 marker */
+ /* The library doesn't actually do anything with these,
+ * but we try to produce a helpful trace message.
+ */
+ switch (GETJOCTET(data[5])) {
+ case 0x10:
+ TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
+ break;
+ case 0x11:
+ TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
+ break;
+ case 0x13:
+ TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
+ break;
+ default:
+ TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
+ GETJOCTET(data[5]), (int) totallen);
+ break;
+ }
+ } else {
+ /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
+ TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
+ }
+}
+
+
+LOCAL(void)
+examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
+ unsigned int datalen, INT32 remaining)
+/* Examine first few bytes from an APP14.
+ * Take appropriate action if it is an Adobe marker.
+ * datalen is # of bytes at data[], remaining is length of rest of marker data.
+ */
+{
+ unsigned int version, flags0, flags1, transform;
+
+ if (datalen >= APP14_DATA_LEN &&
+ GETJOCTET(data[0]) == 0x41 &&
+ GETJOCTET(data[1]) == 0x64 &&
+ GETJOCTET(data[2]) == 0x6F &&
+ GETJOCTET(data[3]) == 0x62 &&
+ GETJOCTET(data[4]) == 0x65) {
+ /* Found Adobe APP14 marker */
+ version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
+ flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
+ flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
+ transform = GETJOCTET(data[11]);
+ TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
+ cinfo->saw_Adobe_marker = TRUE;
+ cinfo->Adobe_transform = (UINT8) transform;
+ } else {
+ /* Start of APP14 does not match "Adobe", or too short */
+ TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
+ }
+}
+
+
+METHODDEF(boolean)
+get_interesting_appn (j_decompress_ptr cinfo)
+/* Process an APP0 or APP14 marker without saving it */
+{
+ INT32 length;
+ JOCTET b[APPN_DATA_LEN];
+ unsigned int i, numtoread;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ /* get the interesting part of the marker data */
+ if (length >= APPN_DATA_LEN)
+ numtoread = APPN_DATA_LEN;
+ else if (length > 0)
+ numtoread = (unsigned int) length;
+ else
+ numtoread = 0;
+ for (i = 0; i < numtoread; i++)
+ INPUT_BYTE(cinfo, b[i], return FALSE);
+ length -= numtoread;
+
+ /* process it */
+ switch (cinfo->unread_marker) {
+ case M_APP0:
+ examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
+ break;
+ case M_APP14:
+ examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
+ break;
+ default:
+ /* can't get here unless jpeg_save_markers chooses wrong processor */
+ ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
+ break;
+ }
+
+ /* skip any remaining data -- could be lots */
+ INPUT_SYNC(cinfo);
+ if (length > 0)
+ (*cinfo->src->skip_input_data) (cinfo, (long) length);
+
+ return TRUE;
+}
+
+
+#ifdef SAVE_MARKERS_SUPPORTED
+
+METHODDEF(boolean)
+save_marker (j_decompress_ptr cinfo)
+/* Save an APPn or COM marker into the marker list */
+{
+ my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
+ jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
+ unsigned int bytes_read, data_length;
+ JOCTET FAR * data;
+ INT32 length = 0;
+ INPUT_VARS(cinfo);
+
+ if (cur_marker == NULL) {
+ /* begin reading a marker */
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+ if (length >= 0) { /* watch out for bogus length word */
+ /* figure out how much we want to save */
+ unsigned int limit;
+ if (cinfo->unread_marker == (int) M_COM)
+ limit = marker->length_limit_COM;
+ else
+ limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
+ if ((unsigned int) length < limit)
+ limit = (unsigned int) length;
+ /* allocate and initialize the marker item */
+ cur_marker = (jpeg_saved_marker_ptr)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(struct jpeg_marker_struct) + limit);
+ cur_marker->next = NULL;
+ cur_marker->marker = (UINT8) cinfo->unread_marker;
+ cur_marker->original_length = (unsigned int) length;
+ cur_marker->data_length = limit;
+ /* data area is just beyond the jpeg_marker_struct */
+ data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
+ marker->cur_marker = cur_marker;
+ marker->bytes_read = 0;
+ bytes_read = 0;
+ data_length = limit;
+ } else {
+ /* deal with bogus length word */
+ bytes_read = data_length = 0;
+ data = NULL;
+ }
+ } else {
+ /* resume reading a marker */
+ bytes_read = marker->bytes_read;
+ data_length = cur_marker->data_length;
+ data = cur_marker->data + bytes_read;
+ }
+
+ while (bytes_read < data_length) {
+ INPUT_SYNC(cinfo); /* move the restart point to here */
+ marker->bytes_read = bytes_read;
+ /* If there's not at least one byte in buffer, suspend */
+ MAKE_BYTE_AVAIL(cinfo, return FALSE);
+ /* Copy bytes with reasonable rapidity */
+ while (bytes_read < data_length && bytes_in_buffer > 0) {
+ *data++ = *next_input_byte++;
+ bytes_in_buffer--;
+ bytes_read++;
+ }
+ }
+
+ /* Done reading what we want to read */
+ if (cur_marker != NULL) { /* will be NULL if bogus length word */
+ /* Add new marker to end of list */
+ if (cinfo->marker_list == NULL) {
+ cinfo->marker_list = cur_marker;
+ } else {
+ jpeg_saved_marker_ptr prev = cinfo->marker_list;
+ while (prev->next != NULL)
+ prev = prev->next;
+ prev->next = cur_marker;
+ }
+ /* Reset pointer & calc remaining data length */
+ data = cur_marker->data;
+ length = cur_marker->original_length - data_length;
+ }
+ /* Reset to initial state for next marker */
+ marker->cur_marker = NULL;
+
+ /* Process the marker if interesting; else just make a generic trace msg */
+ switch (cinfo->unread_marker) {
+ case M_APP0:
+ examine_app0(cinfo, data, data_length, length);
+ break;
+ case M_APP14:
+ examine_app14(cinfo, data, data_length, length);
+ break;
+ default:
+ TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
+ (int) (data_length + length));
+ break;
+ }
+
+ /* skip any remaining data -- could be lots */
+ INPUT_SYNC(cinfo); /* do before skip_input_data */
+ if (length > 0)
+ (*cinfo->src->skip_input_data) (cinfo, (long) length);
+
+ return TRUE;
+}
+
+#endif /* SAVE_MARKERS_SUPPORTED */
+
+
+METHODDEF(boolean)
+skip_variable (j_decompress_ptr cinfo)
+/* Skip over an unknown or uninteresting variable-length marker */
+{
+ INT32 length;
+ INPUT_VARS(cinfo);
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+ length -= 2;
+
+ TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
+
+ INPUT_SYNC(cinfo); /* do before skip_input_data */
+ if (length > 0)
+ (*cinfo->src->skip_input_data) (cinfo, (long) length);
+
+ return TRUE;
+}
+
+
+/*
+ * Find the next JPEG marker, save it in cinfo->unread_marker.
+ * Returns FALSE if had to suspend before reaching a marker;
+ * in that case cinfo->unread_marker is unchanged.
+ *
+ * Note that the result might not be a valid marker code,
+ * but it will never be 0 or FF.
+ */
+
+LOCAL(boolean)
+next_marker (j_decompress_ptr cinfo)
+{
+ int c;
+ INPUT_VARS(cinfo);
+
+ for (;;) {
+ INPUT_BYTE(cinfo, c, return FALSE);
+ /* Skip any non-FF bytes.
+ * This may look a bit inefficient, but it will not occur in a valid file.
+ * We sync after each discarded byte so that a suspending data source
+ * can discard the byte from its buffer.
+ */
+ while (c != 0xFF) {
+ cinfo->marker->discarded_bytes++;
+ INPUT_SYNC(cinfo);
+ INPUT_BYTE(cinfo, c, return FALSE);
+ }
+ /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
+ * pad bytes, so don't count them in discarded_bytes. We assume there
+ * will not be so many consecutive FF bytes as to overflow a suspending
+ * data source's input buffer.
+ */
+ do {
+ INPUT_BYTE(cinfo, c, return FALSE);
+ } while (c == 0xFF);
+ if (c != 0)
+ break; /* found a valid marker, exit loop */
+ /* Reach here if we found a stuffed-zero data sequence (FF/00).
+ * Discard it and loop back to try again.
+ */
+ cinfo->marker->discarded_bytes += 2;
+ INPUT_SYNC(cinfo);
+ }
+
+ if (cinfo->marker->discarded_bytes != 0) {
+ WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
+ cinfo->marker->discarded_bytes = 0;
+ }
+
+ cinfo->unread_marker = c;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+LOCAL(boolean)
+first_marker (j_decompress_ptr cinfo)
+/* Like next_marker, but used to obtain the initial SOI marker. */
+/* For this marker, we do not allow preceding garbage or fill; otherwise,
+ * we might well scan an entire input file before realizing it ain't JPEG.
+ * If an application wants to process non-JFIF files, it must seek to the
+ * SOI before calling the JPEG library.
+ */
+{
+ int c, c2;
+ INPUT_VARS(cinfo);
+
+ INPUT_BYTE(cinfo, c, return FALSE);
+ INPUT_BYTE(cinfo, c2, return FALSE);
+ if (c != 0xFF || c2 != (int) M_SOI)
+ ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
+
+ cinfo->unread_marker = c2;
+
+ INPUT_SYNC(cinfo);
+ return TRUE;
+}
+
+
+/*
+ * Read markers until SOS or EOI.
+ *
+ * Returns same codes as are defined for jpeg_consume_input:
+ * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
+ */
+
+METHODDEF(int)
+read_markers (j_decompress_ptr cinfo)
+{
+ /* Outer loop repeats once for each marker. */
+ for (;;) {
+ /* Collect the marker proper, unless we already did. */
+ /* NB: first_marker() enforces the requirement that SOI appear first. */
+ if (cinfo->unread_marker == 0) {
+ if (! cinfo->marker->saw_SOI) {
+ if (! first_marker(cinfo))
+ return JPEG_SUSPENDED;
+ } else {
+ if (! next_marker(cinfo))
+ return JPEG_SUSPENDED;
+ }
+ }
+ /* At this point cinfo->unread_marker contains the marker code and the
+ * input point is just past the marker proper, but before any parameters.
+ * A suspension will cause us to return with this state still true.
+ */
+ switch (cinfo->unread_marker) {
+ case M_SOI:
+ if (! get_soi(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF0: /* Baseline */
+ case M_SOF1: /* Extended sequential, Huffman */
+ if (! get_sof(cinfo, JPROC_SEQUENTIAL, FALSE, DCTSIZE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF2: /* Progressive, Huffman */
+ if (! get_sof(cinfo, JPROC_PROGRESSIVE, FALSE, DCTSIZE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF3: /* Lossless, Huffman */
+ if (! get_sof(cinfo, JPROC_LOSSLESS, FALSE, 1))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF9: /* Extended sequential, arithmetic */
+ if (! get_sof(cinfo, JPROC_SEQUENTIAL, TRUE, DCTSIZE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF10: /* Progressive, arithmetic */
+ if (! get_sof(cinfo, JPROC_PROGRESSIVE, TRUE, DCTSIZE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF11: /* Lossless, arithmetic */
+ if (! get_sof(cinfo, JPROC_LOSSLESS, TRUE, 1))
+ return JPEG_SUSPENDED;
+ break;
+
+ /* Currently unsupported SOFn types */
+ case M_SOF5: /* Differential sequential, Huffman */
+ case M_SOF6: /* Differential progressive, Huffman */
+ case M_SOF7: /* Differential lossless, Huffman */
+ case M_JPG: /* Reserved for JPEG extensions */
+ case M_SOF13: /* Differential sequential, arithmetic */
+ case M_SOF14: /* Differential progressive, arithmetic */
+ case M_SOF15: /* Differential lossless, arithmetic */
+ ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
+ break;
+
+ case M_SOS:
+ if (! get_sos(cinfo))
+ return JPEG_SUSPENDED;
+ cinfo->unread_marker = 0; /* processed the marker */
+ return JPEG_REACHED_SOS;
+
+ case M_EOI:
+ TRACEMS(cinfo, 1, JTRC_EOI);
+ cinfo->unread_marker = 0; /* processed the marker */
+ return JPEG_REACHED_EOI;
+
+ case M_DAC:
+ if (! get_dac(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_DHT:
+ if (! get_dht(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_DQT:
+ if (! get_dqt(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_DRI:
+ if (! get_dri(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_APP0:
+ case M_APP1:
+ case M_APP2:
+ case M_APP3:
+ case M_APP4:
+ case M_APP5:
+ case M_APP6:
+ case M_APP7:
+ case M_APP8:
+ case M_APP9:
+ case M_APP10:
+ case M_APP11:
+ case M_APP12:
+ case M_APP13:
+ case M_APP14:
+ case M_APP15:
+ if (! (*((my_marker_ptr) cinfo->marker)->process_APPn[
+ cinfo->unread_marker - (int) M_APP0]) (cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_COM:
+ if (! (*((my_marker_ptr) cinfo->marker)->process_COM) (cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_RST0: /* these are all parameterless */
+ case M_RST1:
+ case M_RST2:
+ case M_RST3:
+ case M_RST4:
+ case M_RST5:
+ case M_RST6:
+ case M_RST7:
+ case M_TEM:
+ TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
+ break;
+
+ case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
+ if (! skip_variable(cinfo))
+ return JPEG_SUSPENDED;
+ break;
+
+ default: /* must be DHP, EXP, JPGn, or RESn */
+ /* For now, we treat the reserved markers as fatal errors since they are
+ * likely to be used to signal incompatible JPEG Part 3 extensions.
+ * Once the JPEG 3 version-number marker is well defined, this code
+ * ought to change!
+ */
+ ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
+ break;
+ }
+ /* Successfully processed marker, so reset state variable */
+ cinfo->unread_marker = 0;
+ } /* end loop */
+}
+
+
+/*
+ * Read a restart marker, which is expected to appear next in the datastream;
+ * if the marker is not there, take appropriate recovery action.
+ * Returns FALSE if suspension is required.
+ *
+ * This is called by the entropy decoder after it has read an appropriate
+ * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
+ * has already read a marker from the data source. Under normal conditions
+ * cinfo->unread_marker will be reset to 0 before returning; if not reset,
+ * it holds a marker which the decoder will be unable to read past.
+ */
+
+METHODDEF(boolean)
+read_restart_marker (j_decompress_ptr cinfo)
+{
+ /* Obtain a marker unless we already did. */
+ /* Note that next_marker will complain if it skips any data. */
+ if (cinfo->unread_marker == 0) {
+ if (! next_marker(cinfo))
+ return FALSE;
+ }
+
+ if (cinfo->unread_marker ==
+ ((int) M_RST0 + cinfo->marker->next_restart_num)) {
+ /* Normal case --- swallow the marker and let entropy decoder continue */
+ TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
+ cinfo->unread_marker = 0;
+ } else {
+ /* Uh-oh, the restart markers have been messed up. */
+ /* Let the data source manager determine how to resync. */
+ if (! (*cinfo->src->resync_to_restart) (cinfo,
+ cinfo->marker->next_restart_num))
+ return FALSE;
+ }
+
+ /* Update next-restart state */
+ cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
+
+ return TRUE;
+}
+
+
+/*
+ * This is the default resync_to_restart method for data source managers
+ * to use if they don't have any better approach. Some data source managers
+ * may be able to back up, or may have additional knowledge about the data
+ * which permits a more intelligent recovery strategy; such managers would
+ * presumably supply their own resync method.
+ *
+ * read_restart_marker calls resync_to_restart if it finds a marker other than
+ * the restart marker it was expecting. (This code is *not* used unless
+ * a nonzero restart interval has been declared.) cinfo->unread_marker is
+ * the marker code actually found (might be anything, except 0 or FF).
+ * The desired restart marker number (0..7) is passed as a parameter.
+ * This routine is supposed to apply whatever error recovery strategy seems
+ * appropriate in order to position the input stream to the next data segment.
+ * Note that cinfo->unread_marker is treated as a marker appearing before
+ * the current data-source input point; usually it should be reset to zero
+ * before returning.
+ * Returns FALSE if suspension is required.
+ *
+ * This implementation is substantially constrained by wanting to treat the
+ * input as a data stream; this means we can't back up. Therefore, we have
+ * only the following actions to work with:
+ * 1. Simply discard the marker and let the entropy decoder resume at next
+ * byte of file.
+ * 2. Read forward until we find another marker, discarding intervening
+ * data. (In theory we could look ahead within the current bufferload,
+ * without having to discard data if we don't find the desired marker.
+ * This idea is not implemented here, in part because it makes behavior
+ * dependent on buffer size and chance buffer-boundary positions.)
+ * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
+ * This will cause the entropy decoder to process an empty data segment,
+ * inserting dummy zeroes, and then we will reprocess the marker.
+ *
+ * #2 is appropriate if we think the desired marker lies ahead, while #3 is
+ * appropriate if the found marker is a future restart marker (indicating
+ * that we have missed the desired restart marker, probably because it got
+ * corrupted).
+ * We apply #2 or #3 if the found marker is a restart marker no more than
+ * two counts behind or ahead of the expected one. We also apply #2 if the
+ * found marker is not a legal JPEG marker code (it's certainly bogus data).
+ * If the found marker is a restart marker more than 2 counts away, we do #1
+ * (too much risk that the marker is erroneous; with luck we will be able to
+ * resync at some future point).
+ * For any valid non-restart JPEG marker, we apply #3. This keeps us from
+ * overrunning the end of a scan. An implementation limited to single-scan
+ * files might find it better to apply #2 for markers other than EOI, since
+ * any other marker would have to be bogus data in that case.
+ */
+
+GLOBAL(boolean)
+jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
+{
+ int marker = cinfo->unread_marker;
+ int action = 1;
+
+ /* Always put up a warning. */
+ WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
+
+ /* Outer loop handles repeated decision after scanning forward. */
+ for (;;) {
+ if (marker < (int) M_SOF0)
+ action = 2; /* invalid marker */
+ else if (marker < (int) M_RST0 || marker > (int) M_RST7)
+ action = 3; /* valid non-restart marker */
+ else {
+ if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
+ marker == ((int) M_RST0 + ((desired+2) & 7)))
+ action = 3; /* one of the next two expected restarts */
+ else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
+ marker == ((int) M_RST0 + ((desired-2) & 7)))
+ action = 2; /* a prior restart, so advance */
+ else
+ action = 1; /* desired restart or too far away */
+ }
+ TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
+ switch (action) {
+ case 1:
+ /* Discard marker and let entropy decoder resume processing. */
+ cinfo->unread_marker = 0;
+ return TRUE;
+ case 2:
+ /* Scan to the next marker, and repeat the decision loop. */
+ if (! next_marker(cinfo))
+ return FALSE;
+ marker = cinfo->unread_marker;
+ break;
+ case 3:
+ /* Return without advancing past this marker. */
+ /* Entropy decoder will be forced to process an empty segment. */
+ return TRUE;
+ }
+ } /* end loop */
+}
+
+
+/*
+ * Reset marker processing state to begin a fresh datastream.
+ */
+
+METHODDEF(void)
+reset_marker_reader (j_decompress_ptr cinfo)
+{
+ my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
+
+ cinfo->comp_info = NULL; /* until allocated by get_sof */
+ cinfo->input_scan_number = 0; /* no SOS seen yet */
+ cinfo->unread_marker = 0; /* no pending marker */
+ marker->pub.saw_SOI = FALSE; /* set internal state too */
+ marker->pub.saw_SOF = FALSE;
+ marker->pub.discarded_bytes = 0;
+ marker->cur_marker = NULL;
+}
+
+
+/*
+ * Initialize the marker reader module.
+ * This is called only once, when the decompression object is created.
+ */
+
+GLOBAL(void)
+jinit_marker_reader (j_decompress_ptr cinfo)
+{
+ my_marker_ptr marker;
+ int i;
+
+ /* Create subobject in permanent pool */
+ marker = (my_marker_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
+ SIZEOF(my_marker_reader));
+ cinfo->marker = (struct jpeg_marker_reader *) marker;
+ /* Initialize public method pointers */
+ marker->pub.reset_marker_reader = reset_marker_reader;
+ marker->pub.read_markers = read_markers;
+ marker->pub.read_restart_marker = read_restart_marker;
+ /* Initialize COM/APPn processing.
+ * By default, we examine and then discard APP0 and APP14,
+ * but simply discard COM and all other APPn.
+ */
+ marker->process_COM = skip_variable;
+ marker->length_limit_COM = 0;
+ for (i = 0; i < 16; i++) {
+ marker->process_APPn[i] = skip_variable;
+ marker->length_limit_APPn[i] = 0;
+ }
+ marker->process_APPn[0] = get_interesting_appn;
+ marker->process_APPn[14] = get_interesting_appn;
+ /* Reset marker processing state */
+ reset_marker_reader(cinfo);
+}
+
+
+/*
+ * Control saving of COM and APPn markers into marker_list.
+ */
+
+#ifdef SAVE_MARKERS_SUPPORTED
+
+GLOBAL(void)
+jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
+ unsigned int length_limit)
+{
+ my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
+ long maxlength;
+ jpeg_marker_parser_method processor;
+
+ /* Length limit mustn't be larger than what we can allocate
+ * (should only be a concern in a 16-bit environment).
+ */
+ maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
+ if (((long) length_limit) > maxlength)
+ length_limit = (unsigned int) maxlength;
+
+ /* Choose processor routine to use.
+ * APP0/APP14 have special requirements.
+ */
+ if (length_limit) {
+ processor = save_marker;
+ /* If saving APP0/APP14, save at least enough for our internal use. */
+ if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
+ length_limit = APP0_DATA_LEN;
+ else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
+ length_limit = APP14_DATA_LEN;
+ } else {
+ processor = skip_variable;
+ /* If discarding APP0/APP14, use our regular on-the-fly processor. */
+ if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
+ processor = get_interesting_appn;
+ }
+
+ if (marker_code == (int) M_COM) {
+ marker->process_COM = processor;
+ marker->length_limit_COM = length_limit;
+ } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
+ marker->process_APPn[marker_code - (int) M_APP0] = processor;
+ marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
+ } else
+ ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
+}
+
+#endif /* SAVE_MARKERS_SUPPORTED */
+
+
+/*
+ * Install a special processing method for COM or APPn markers.
+ */
+
+GLOBAL(void)
+jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
+ jpeg_marker_parser_method routine)
+{
+ my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
+
+ if (marker_code == (int) M_COM)
+ marker->process_COM = routine;
+ else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
+ marker->process_APPn[marker_code - (int) M_APP0] = routine;
+ else
+ ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
+}
diff --git a/jpeg-6c/jdmaster.c b/jpeg-6c/jdmaster.c
new file mode 100644
index 0000000..e933dff
--- /dev/null
+++ b/jpeg-6c/jdmaster.c
@@ -0,0 +1,480 @@
+/*
+ * jdmaster.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains master control logic for the JPEG decompressor.
+ * These routines are concerned with selecting the modules to be executed
+ * and with determining the number of passes and the work to be done in each
+ * pass.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private state */
+
+typedef struct {
+ struct jpeg_decomp_master pub; /* public fields */
+
+ int pass_number; /* # of passes completed */
+
+ boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
+
+ /* Saved references to initialized quantizer modules,
+ * in case we need to switch modes.
+ */
+ struct jpeg_color_quantizer * quantizer_1pass;
+ struct jpeg_color_quantizer * quantizer_2pass;
+} my_decomp_master;
+
+typedef my_decomp_master * my_master_ptr;
+
+
+/*
+ * Determine whether merged upsample/color conversion should be used.
+ * CRUCIAL: this must match the actual capabilities of jdmerge.c!
+ */
+
+LOCAL(boolean)
+use_merged_upsample (j_decompress_ptr cinfo)
+{
+#ifdef UPSAMPLE_MERGING_SUPPORTED
+ /* Merging is the equivalent of plain box-filter upsampling */
+ if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
+ return FALSE;
+ /* jdmerge.c only supports YCC=>RGB color conversion */
+ if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
+ cinfo->out_color_space != JCS_RGB ||
+ cinfo->out_color_components != RGB_PIXELSIZE)
+ return FALSE;
+ /* and it only handles 2h1v or 2h2v sampling ratios */
+ if (cinfo->comp_info[0].h_samp_factor != 2 ||
+ cinfo->comp_info[1].h_samp_factor != 1 ||
+ cinfo->comp_info[2].h_samp_factor != 1 ||
+ cinfo->comp_info[0].v_samp_factor > 2 ||
+ cinfo->comp_info[1].v_samp_factor != 1 ||
+ cinfo->comp_info[2].v_samp_factor != 1)
+ return FALSE;
+ /* furthermore, it doesn't work if each component has been
+ processed differently */
+ if (cinfo->comp_info[0].codec_data_unit != cinfo->min_codec_data_unit ||
+ cinfo->comp_info[1].codec_data_unit != cinfo->min_codec_data_unit ||
+ cinfo->comp_info[2].codec_data_unit != cinfo->min_codec_data_unit)
+ return FALSE;
+ /* ??? also need to test for upsample-time rescaling, when & if supported */
+ return TRUE; /* by golly, it'll work... */
+#else
+ return FALSE;
+#endif
+}
+
+
+/*
+ * Compute output image dimensions and related values.
+ * NOTE: this is exported for possible use by application.
+ * Hence it mustn't do anything that can't be done twice.
+ * Also note that it may be called before the master module is initialized!
+ */
+
+GLOBAL(void)
+jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
+/* Do computations that are needed before master selection phase */
+{
+ /* Prevent application from calling me at wrong times */
+ if (cinfo->global_state != DSTATE_READY)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ (*cinfo->codec->calc_output_dimensions) (cinfo);
+
+ /* Report number of components in selected colorspace. */
+ /* Probably this should be in the color conversion module... */
+ switch (cinfo->out_color_space) {
+ case JCS_GRAYSCALE:
+ cinfo->out_color_components = 1;
+ break;
+ case JCS_RGB:
+#if RGB_PIXELSIZE != 3
+ cinfo->out_color_components = RGB_PIXELSIZE;
+ break;
+#endif /* else share code with YCbCr */
+ case JCS_YCbCr:
+ cinfo->out_color_components = 3;
+ break;
+ case JCS_CMYK:
+ case JCS_YCCK:
+ cinfo->out_color_components = 4;
+ break;
+ default: /* else must be same colorspace as in file */
+ cinfo->out_color_components = cinfo->num_components;
+ break;
+ }
+ cinfo->output_components = (cinfo->quantize_colors ? 1 :
+ cinfo->out_color_components);
+
+ /* See if upsampler will want to emit more than one row at a time */
+ if (use_merged_upsample(cinfo))
+ cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
+ else
+ cinfo->rec_outbuf_height = 1;
+}
+
+
+/*
+ * Several decompression processes need to range-limit values to the range
+ * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
+ * due to noise introduced by quantization, roundoff error, etc. These
+ * processes are inner loops and need to be as fast as possible. On most
+ * machines, particularly CPUs with pipelines or instruction prefetch,
+ * a (subscript-check-less) C table lookup
+ * x = sample_range_limit[x];
+ * is faster than explicit tests
+ * if (x < 0) x = 0;
+ * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
+ * These processes all use a common table prepared by the routine below.
+ *
+ * For most steps we can mathematically guarantee that the initial value
+ * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
+ * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
+ * limiting step (just after the IDCT), a wildly out-of-range value is
+ * possible if the input data is corrupt. To avoid any chance of indexing
+ * off the end of memory and getting a bad-pointer trap, we perform the
+ * post-IDCT limiting thus:
+ * x = range_limit[x & MASK];
+ * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
+ * samples. Under normal circumstances this is more than enough range and
+ * a correct output will be generated; with bogus input data the mask will
+ * cause wraparound, and we will safely generate a bogus-but-in-range output.
+ * For the post-IDCT step, we want to convert the data from signed to unsigned
+ * representation by adding CENTERJSAMPLE at the same time that we limit it.
+ * So the post-IDCT limiting table ends up looking like this:
+ * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
+ * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
+ * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
+ * 0,1,...,CENTERJSAMPLE-1
+ * Negative inputs select values from the upper half of the table after
+ * masking.
+ *
+ * We can save some space by overlapping the start of the post-IDCT table
+ * with the simpler range limiting table. The post-IDCT table begins at
+ * sample_range_limit + CENTERJSAMPLE.
+ *
+ * Note that the table is allocated in near data space on PCs; it's small
+ * enough and used often enough to justify this.
+ */
+
+LOCAL(void)
+prepare_range_limit_table (j_decompress_ptr cinfo)
+/* Allocate and fill in the sample_range_limit table */
+{
+ JSAMPLE16 * table;
+ int i;
+
+ table = (JSAMPLE16 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (5 * (cinfo->maxjsample+1) + cinfo->centerjsample) * SIZEOF(JSAMPLE16));
+ table += (cinfo->maxjsample+1); /* allow negative subscripts of simple table */
+ cinfo->sample_range_limit = table;
+ /* First segment of "simple" table: limit[x] = 0 for x < 0 */
+ MEMZERO(table - (cinfo->maxjsample+1), (cinfo->maxjsample+1) * SIZEOF(JSAMPLE16));
+ /* Main part of "simple" table: limit[x] = x */
+ for (i = 0; i <= cinfo->maxjsample; i++)
+ table[i] = (JSAMPLE16) i;
+ table += cinfo->centerjsample; /* Point to where post-IDCT table starts */
+ /* End of simple table, rest of first half of post-IDCT table */
+ for (i = cinfo->centerjsample; i < 2*(cinfo->maxjsample+1); i++)
+ table[i] = cinfo->maxjsample;
+ /* Second half of post-IDCT table */
+ MEMZERO(table + (2 * (cinfo->maxjsample+1)),
+ (2 * (cinfo->maxjsample+1) - cinfo->centerjsample) * SIZEOF(JSAMPLE16));
+ MEMCOPY(table + (4 * (cinfo->maxjsample+1) - cinfo->centerjsample),
+ cinfo->sample_range_limit, cinfo->centerjsample * SIZEOF(JSAMPLE16));
+}
+
+
+/*
+ * Master selection of decompression modules.
+ * This is done once at jpeg_start_decompress time. We determine
+ * which modules will be used and give them appropriate initialization calls.
+ * We also initialize the decompressor input side to begin consuming data.
+ *
+ * Since jpeg_read_header has finished, we know what is in the SOF
+ * and (first) SOS markers. We also have all the application parameter
+ * settings.
+ */
+
+LOCAL(void)
+master_selection (j_decompress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+ long samplesperrow;
+ JDIMENSION jd_samplesperrow;
+ JSAMPROW colormap_in_ptr;
+ JSAMPROW16 colormap_out_ptr;
+ int sample, col;
+
+ /* Initialize dimensions and other stuff */
+ jpeg_calc_output_dimensions(cinfo);
+ prepare_range_limit_table(cinfo);
+
+ /* Width of an output scanline must be representable as JDIMENSION. */
+ samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
+ jd_samplesperrow = (JDIMENSION) samplesperrow;
+ if ((long) jd_samplesperrow != samplesperrow)
+ ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
+
+ /* Initialize my private state */
+ master->pass_number = 0;
+ master->using_merged_upsample = use_merged_upsample(cinfo);
+
+ /* Color quantizer selection */
+ master->quantizer_1pass = NULL;
+ master->quantizer_2pass = NULL;
+ /* No mode changes if not using buffered-image mode. */
+ if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
+ cinfo->enable_1pass_quant = FALSE;
+ cinfo->enable_external_quant = FALSE;
+ cinfo->enable_2pass_quant = FALSE;
+ }
+ if (cinfo->quantize_colors) {
+ if (cinfo->raw_data_out)
+ ERREXIT(cinfo, JERR_NOTIMPL);
+ /* 2-pass quantizer only works in 3-component color space. */
+ if (cinfo->out_color_components != 3) {
+ cinfo->enable_1pass_quant = TRUE;
+ cinfo->enable_external_quant = FALSE;
+ cinfo->enable_2pass_quant = FALSE;
+ cinfo->colormap = NULL;
+ cinfo->colormap16 = NULL;
+ } else if (cinfo->colormap != NULL) {
+ if (cinfo->colormap16 == NULL) {
+ /* Copy the color map to 16 bits */
+ cinfo->colormap16 =
+ (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) ((cinfo->maxjsample + 1) * SIZEOF(JSAMPLE16)),
+ (JDIMENSION) cinfo->out_color_components);
+ for (sample = 0; sample < cinfo->out_color_components; sample++) {
+ colormap_in_ptr = cinfo->colormap[sample];
+ colormap_out_ptr = cinfo->colormap16[sample];
+ for (col = 0; col < cinfo->actual_number_of_colors; col++)
+ *colormap_out_ptr++ = (JSAMPLE16)*colormap_in_ptr++;
+ }
+ }
+ } else if (cinfo->colormap16 != NULL) {
+ cinfo->enable_external_quant = TRUE;
+ } else if (cinfo->two_pass_quantize) {
+ cinfo->enable_2pass_quant = TRUE;
+ } else {
+ cinfo->enable_1pass_quant = TRUE;
+ }
+
+ if (cinfo->enable_1pass_quant) {
+#ifdef QUANT_1PASS_SUPPORTED
+ jinit_1pass_quantizer(cinfo);
+ master->quantizer_1pass = cinfo->cquantize;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ }
+
+ /* We use the 2-pass code to map to external colormaps. */
+ if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
+#ifdef QUANT_2PASS_SUPPORTED
+ jinit_2pass_quantizer(cinfo);
+ master->quantizer_2pass = cinfo->cquantize;
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ }
+ /* If both quantizers are initialized, the 2-pass one is left active;
+ * this is necessary for starting with quantization to an external map.
+ */
+ }
+
+ /* Post-processing: in particular, color conversion first */
+ if (! cinfo->raw_data_out) {
+ if (master->using_merged_upsample) {
+#ifdef UPSAMPLE_MERGING_SUPPORTED
+ jinit_merged_upsampler(cinfo); /* does color conversion too */
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+ } else {
+ jinit_color_deconverter(cinfo);
+ jinit_upsampler(cinfo);
+ }
+ jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
+ }
+
+ /* Initialize principal buffer controllers. */
+ if (! cinfo->raw_data_out)
+ jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
+
+ /* We can now tell the memory manager to allocate virtual arrays. */
+ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
+
+ /* Initialize input side of decompressor to consume first scan. */
+ (*cinfo->inputctl->start_input_pass) (cinfo);
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+ /* If jpeg_start_decompress will read the whole file, initialize
+ * progress monitoring appropriately. The input step is counted
+ * as one pass.
+ */
+ if (cinfo->progress != NULL && ! cinfo->buffered_image &&
+ cinfo->inputctl->has_multiple_scans) {
+ int nscans;
+ /* Estimate number of scans to set pass_limit. */
+ if (cinfo->process == JPROC_PROGRESSIVE) {
+ /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
+ nscans = 2 + 3 * cinfo->num_components;
+ } else {
+ /* For a nonprogressive multiscan file, estimate 1 scan per component. */
+ nscans = cinfo->num_components;
+ }
+ cinfo->progress->pass_counter = 0L;
+ cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
+ cinfo->progress->completed_passes = 0;
+ cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
+ /* Count the input pass as done */
+ master->pass_number++;
+ }
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
+}
+
+
+/*
+ * Per-pass setup.
+ * This is called at the beginning of each output pass. We determine which
+ * modules will be active during this pass and give them appropriate
+ * start_pass calls. We also set is_dummy_pass to indicate whether this
+ * is a "real" output pass or a dummy pass for color quantization.
+ * (In the latter case, jdapistd.c will crank the pass to completion.)
+ */
+
+METHODDEF(void)
+prepare_for_output_pass (j_decompress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ if (master->pub.is_dummy_pass) {
+#ifdef QUANT_2PASS_SUPPORTED
+ /* Final pass of 2-pass quantization */
+ master->pub.is_dummy_pass = FALSE;
+ (*cinfo->cquantize->start_pass) (cinfo, FALSE);
+ (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
+ (*cinfo->mainp->start_pass) (cinfo, JBUF_CRANK_DEST);
+#else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif /* QUANT_2PASS_SUPPORTED */
+ } else {
+ if (cinfo->quantize_colors && cinfo->colormap16 == NULL) {
+ /* Select new quantization method */
+ if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
+ cinfo->cquantize = master->quantizer_2pass;
+ master->pub.is_dummy_pass = TRUE;
+ } else if (cinfo->enable_1pass_quant) {
+ cinfo->cquantize = master->quantizer_1pass;
+ } else {
+ ERREXIT(cinfo, JERR_MODE_CHANGE);
+ }
+ }
+ (*cinfo->codec->start_output_pass) (cinfo);
+ if (! cinfo->raw_data_out) {
+ if (! master->using_merged_upsample)
+ (*cinfo->cconvert->start_pass) (cinfo);
+ (*cinfo->upsample->start_pass) (cinfo);
+ if (cinfo->quantize_colors)
+ (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
+ (*cinfo->post->start_pass) (cinfo,
+ (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
+ (*cinfo->mainp->start_pass) (cinfo, JBUF_PASS_THRU);
+ }
+ }
+
+ /* Set up progress monitor's pass info if present */
+ if (cinfo->progress != NULL) {
+ cinfo->progress->completed_passes = master->pass_number;
+ cinfo->progress->total_passes = master->pass_number +
+ (master->pub.is_dummy_pass ? 2 : 1);
+ /* In buffered-image mode, we assume one more output pass if EOI not
+ * yet reached, but no more passes if EOI has been reached.
+ */
+ if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
+ cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
+ }
+ }
+}
+
+
+/*
+ * Finish up at end of an output pass.
+ */
+
+METHODDEF(void)
+finish_output_pass (j_decompress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ if (cinfo->quantize_colors)
+ (*cinfo->cquantize->finish_pass) (cinfo);
+ master->pass_number++;
+}
+
+
+#ifdef D_MULTISCAN_FILES_SUPPORTED
+
+/*
+ * Switch to a new external colormap between output passes.
+ */
+
+GLOBAL(void)
+jpeg_new_colormap (j_decompress_ptr cinfo)
+{
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ /* Prevent application from calling me at wrong times */
+ if (cinfo->global_state != DSTATE_BUFIMAGE)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+ if (cinfo->quantize_colors && cinfo->enable_external_quant &&
+ cinfo->colormap16 != NULL) {
+ /* Select 2-pass quantizer for external colormap use */
+ cinfo->cquantize = master->quantizer_2pass;
+ /* Notify quantizer of colormap change */
+ (*cinfo->cquantize->new_color_map) (cinfo);
+ master->pub.is_dummy_pass = FALSE; /* just in case */
+ } else
+ ERREXIT(cinfo, JERR_MODE_CHANGE);
+}
+
+#endif /* D_MULTISCAN_FILES_SUPPORTED */
+
+
+/*
+ * Initialize master decompression control and select active modules.
+ * This is performed at the start of jpeg_start_decompress.
+ */
+
+GLOBAL(void)
+jinit_master_decompress (j_decompress_ptr cinfo)
+{
+ my_master_ptr master;
+
+ master = (my_master_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_decomp_master));
+ cinfo->master = (struct jpeg_decomp_master *) master;
+ master->pub.prepare_for_output_pass = prepare_for_output_pass;
+ master->pub.finish_output_pass = finish_output_pass;
+
+ master->pub.is_dummy_pass = FALSE;
+
+ master_selection(cinfo);
+}
diff --git a/jpeg-6c/jdmerge.c b/jpeg-6c/jdmerge.c
new file mode 100644
index 0000000..170764e
--- /dev/null
+++ b/jpeg-6c/jdmerge.c
@@ -0,0 +1,401 @@
+/*
+ * jdmerge.c
+ *
+ * Copyright (C) 1994-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains code for merged upsampling/color conversion.
+ *
+ * This file combines functions from jdsample.c and jdcolor.c;
+ * read those files first to understand what's going on.
+ *
+ * When the chroma components are to be upsampled by simple replication
+ * (ie, box filtering), we can save some work in color conversion by
+ * calculating all the output pixels corresponding to a pair of chroma
+ * samples at one time. In the conversion equations
+ * R = Y + K1 * Cr
+ * G = Y + K2 * Cb + K3 * Cr
+ * B = Y + K4 * Cb
+ * only the Y term varies among the group of pixels corresponding to a pair
+ * of chroma samples, so the rest of the terms can be calculated just once.
+ * At typical sampling ratios, this eliminates half or three-quarters of the
+ * multiplications needed for color conversion.
+ *
+ * This file currently provides implementations for the following cases:
+ * YCbCr => RGB color conversion only.
+ * Sampling ratios of 2h1v or 2h2v.
+ * No scaling needed at upsample time.
+ * Corner-aligned (non-CCIR601) sampling alignment.
+ * Other special cases could be added, but in most applications these are
+ * the only common cases. (For uncommon cases we fall back on the more
+ * general code in jdsample.c and jdcolor.c.)
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+#ifdef UPSAMPLE_MERGING_SUPPORTED
+
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_upsampler pub; /* public fields */
+
+ /* Pointer to routine to do actual upsampling/conversion of one row group */
+ JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION in_row_group_ctr,
+ JSAMPARRAY16 output_buf));
+
+ /* Private state for YCC->RGB conversion */
+ int * Cr_r_tab; /* => table for Cr to R conversion */
+ int * Cb_b_tab; /* => table for Cb to B conversion */
+ INT32 * Cr_g_tab; /* => table for Cr to G conversion */
+ INT32 * Cb_g_tab; /* => table for Cb to G conversion */
+
+ /* For 2:1 vertical sampling, we produce two output rows at a time.
+ * We need a "spare" row buffer to hold the second output row if the
+ * application provides just a one-row buffer; we also use the spare
+ * to discard the dummy last row if the image height is odd.
+ */
+ JSAMPROW16 spare_row;
+ boolean spare_full; /* T if spare buffer is occupied */
+
+ JDIMENSION out_row_width; /* samples per output row */
+ JDIMENSION rows_to_go; /* counts rows remaining in image */
+} my_upsampler;
+
+typedef my_upsampler * my_upsample_ptr;
+
+#define SCALEBITS 16 /* speediest right-shift on some machines */
+#define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
+#define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
+
+
+/*
+ * Initialize tables for YCC->RGB colorspace conversion.
+ * This is taken directly from jdcolor.c; see that file for more info.
+ */
+
+LOCAL(void)
+build_ycc_rgb_table (j_decompress_ptr cinfo)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ int i;
+ INT32 x;
+ SHIFT_TEMPS
+
+ upsample->Cr_r_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(int));
+ upsample->Cb_b_tab = (int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(int));
+ upsample->Cr_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(INT32));
+ upsample->Cb_g_tab = (INT32 *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (cinfo->maxjsample+1) * SIZEOF(INT32));
+
+ for (i = 0, x = -cinfo->centerjsample; i <= cinfo->maxjsample; i++, x++) {
+ /* i is the actual input pixel value, in the range 0..cinfo->maxjsample */
+ /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
+ /* Cr=>R value is nearest int to 1.40200 * x */
+ upsample->Cr_r_tab[i] = (int)
+ RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
+ /* Cb=>B value is nearest int to 1.77200 * x */
+ upsample->Cb_b_tab[i] = (int)
+ RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
+ /* Cr=>G value is scaled-up -0.71414 * x */
+ upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
+ /* Cb=>G value is scaled-up -0.34414 * x */
+ /* We also add in ONE_HALF so that need not do it in inner loop */
+ upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
+ }
+}
+
+
+/*
+ * Initialize for an upsampling pass.
+ */
+
+METHODDEF(void)
+start_pass_merged_upsample (j_decompress_ptr cinfo)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+
+ /* Mark the spare buffer empty */
+ upsample->spare_full = FALSE;
+ /* Initialize total-height counter for detecting bottom of image */
+ upsample->rows_to_go = cinfo->output_height;
+}
+
+
+/*
+ * Control routine to do upsampling (and color conversion).
+ *
+ * The control routine just handles the row buffering considerations.
+ */
+
+METHODDEF(void)
+merged_2v_upsample (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY16 output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+/* 2:1 vertical sampling case: may need a spare row. */
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ JSAMPROW16 work_ptrs[2];
+ JDIMENSION num_rows; /* number of rows returned to caller */
+
+ if (upsample->spare_full) {
+ /* If we have a spare row saved from a previous cycle, just return it. */
+ jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
+ 1, upsample->out_row_width);
+ num_rows = 1;
+ upsample->spare_full = FALSE;
+ } else {
+ /* Figure number of rows to return to caller. */
+ num_rows = 2;
+ /* Not more than the distance to the end of the image. */
+ if (num_rows > upsample->rows_to_go)
+ num_rows = upsample->rows_to_go;
+ /* And not more than what the client can accept: */
+ out_rows_avail -= *out_row_ctr;
+ if (num_rows > out_rows_avail)
+ num_rows = out_rows_avail;
+ /* Create output pointer array for upsampler. */
+ work_ptrs[0] = output_buf[*out_row_ctr];
+ if (num_rows > 1) {
+ work_ptrs[1] = output_buf[*out_row_ctr + 1];
+ } else {
+ work_ptrs[1] = upsample->spare_row;
+ upsample->spare_full = TRUE;
+ }
+ /* Now do the upsampling. */
+ (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
+ }
+
+ /* Adjust counts */
+ *out_row_ctr += num_rows;
+ upsample->rows_to_go -= num_rows;
+ /* When the buffer is emptied, declare this input row group consumed */
+ if (! upsample->spare_full)
+ (*in_row_group_ctr)++;
+}
+
+
+METHODDEF(void)
+merged_1v_upsample (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY16 output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+/* 1:1 vertical sampling case: much easier, never need a spare row. */
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+
+ /* Just do the upsampling. */
+ (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
+ output_buf + *out_row_ctr);
+ /* Adjust counts */
+ (*out_row_ctr)++;
+ (*in_row_group_ctr)++;
+}
+
+
+/*
+ * These are the routines invoked by the control routines to do
+ * the actual upsampling/conversion. One row group is processed per call.
+ *
+ * Note: since we may be writing directly into application-supplied buffers,
+ * we have to be honest about the output width; we can't assume the buffer
+ * has been rounded up to an even width.
+ */
+
+
+/*
+ * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
+ */
+
+METHODDEF(void)
+h2v1_merged_upsample (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION in_row_group_ctr,
+ JSAMPARRAY16 output_buf)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ register int y, cred, cgreen, cblue;
+ int cb, cr;
+ register JSAMPROW16 outptr;
+ JSAMPROW16 inptr0, inptr1, inptr2;
+ JDIMENSION col;
+ /* copy these pointers into registers if possible */
+ register JSAMPLE16 * range_limit = cinfo->sample_range_limit;
+ int * Crrtab = upsample->Cr_r_tab;
+ int * Cbbtab = upsample->Cb_b_tab;
+ INT32 * Crgtab = upsample->Cr_g_tab;
+ INT32 * Cbgtab = upsample->Cb_g_tab;
+ SHIFT_TEMPS
+
+ inptr0 = input_buf[0][in_row_group_ctr];
+ inptr1 = input_buf[1][in_row_group_ctr];
+ inptr2 = input_buf[2][in_row_group_ctr];
+ outptr = output_buf[0];
+ /* Loop for each pair of output pixels */
+ for (col = cinfo->output_width >> 1; col > 0; col--) {
+ /* Do the chroma part of the calculation */
+ cb = GETJSAMPLE(*inptr1++);
+ cr = GETJSAMPLE(*inptr2++);
+ cred = Crrtab[cr];
+ cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
+ cblue = Cbbtab[cb];
+ /* Fetch 2 Y values and emit 2 pixels */
+ y = GETJSAMPLE(*inptr0++);
+ outptr[RGB_RED] = range_limit[y + cred];
+ outptr[RGB_GREEN] = range_limit[y + cgreen];
+ outptr[RGB_BLUE] = range_limit[y + cblue];
+ outptr += RGB_PIXELSIZE;
+ y = GETJSAMPLE(*inptr0++);
+ outptr[RGB_RED] = range_limit[y + cred];
+ outptr[RGB_GREEN] = range_limit[y + cgreen];
+ outptr[RGB_BLUE] = range_limit[y + cblue];
+ outptr += RGB_PIXELSIZE;
+ }
+ /* If image width is odd, do the last output column separately */
+ if (cinfo->output_width & 1) {
+ cb = GETJSAMPLE(*inptr1);
+ cr = GETJSAMPLE(*inptr2);
+ cred = Crrtab[cr];
+ cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
+ cblue = Cbbtab[cb];
+ y = GETJSAMPLE(*inptr0);
+ outptr[RGB_RED] = range_limit[y + cred];
+ outptr[RGB_GREEN] = range_limit[y + cgreen];
+ outptr[RGB_BLUE] = range_limit[y + cblue];
+ }
+}
+
+
+/*
+ * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
+ */
+
+METHODDEF(void)
+h2v2_merged_upsample (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION in_row_group_ctr,
+ JSAMPARRAY16 output_buf)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ register int y, cred, cgreen, cblue;
+ int cb, cr;
+ register JSAMPROW16 outptr0, outptr1;
+ JSAMPROW16 inptr00, inptr01, inptr1, inptr2;
+ JDIMENSION col;
+ /* copy these pointers into registers if possible */
+ register JSAMPLE16 * range_limit = cinfo->sample_range_limit;
+ int * Crrtab = upsample->Cr_r_tab;
+ int * Cbbtab = upsample->Cb_b_tab;
+ INT32 * Crgtab = upsample->Cr_g_tab;
+ INT32 * Cbgtab = upsample->Cb_g_tab;
+ SHIFT_TEMPS
+
+ inptr00 = input_buf[0][in_row_group_ctr*2];
+ inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
+ inptr1 = input_buf[1][in_row_group_ctr];
+ inptr2 = input_buf[2][in_row_group_ctr];
+ outptr0 = output_buf[0];
+ outptr1 = output_buf[1];
+ /* Loop for each group of output pixels */
+ for (col = cinfo->output_width >> 1; col > 0; col--) {
+ /* Do the chroma part of the calculation */
+ cb = GETJSAMPLE(*inptr1++);
+ cr = GETJSAMPLE(*inptr2++);
+ cred = Crrtab[cr];
+ cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
+ cblue = Cbbtab[cb];
+ /* Fetch 4 Y values and emit 4 pixels */
+ y = GETJSAMPLE(*inptr00++);
+ outptr0[RGB_RED] = range_limit[y + cred];
+ outptr0[RGB_GREEN] = range_limit[y + cgreen];
+ outptr0[RGB_BLUE] = range_limit[y + cblue];
+ outptr0 += RGB_PIXELSIZE;
+ y = GETJSAMPLE(*inptr00++);
+ outptr0[RGB_RED] = range_limit[y + cred];
+ outptr0[RGB_GREEN] = range_limit[y + cgreen];
+ outptr0[RGB_BLUE] = range_limit[y + cblue];
+ outptr0 += RGB_PIXELSIZE;
+ y = GETJSAMPLE(*inptr01++);
+ outptr1[RGB_RED] = range_limit[y + cred];
+ outptr1[RGB_GREEN] = range_limit[y + cgreen];
+ outptr1[RGB_BLUE] = range_limit[y + cblue];
+ outptr1 += RGB_PIXELSIZE;
+ y = GETJSAMPLE(*inptr01++);
+ outptr1[RGB_RED] = range_limit[y + cred];
+ outptr1[RGB_GREEN] = range_limit[y + cgreen];
+ outptr1[RGB_BLUE] = range_limit[y + cblue];
+ outptr1 += RGB_PIXELSIZE;
+ }
+ /* If image width is odd, do the last output column separately */
+ if (cinfo->output_width & 1) {
+ cb = GETJSAMPLE(*inptr1);
+ cr = GETJSAMPLE(*inptr2);
+ cred = Crrtab[cr];
+ cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
+ cblue = Cbbtab[cb];
+ y = GETJSAMPLE(*inptr00);
+ outptr0[RGB_RED] = range_limit[y + cred];
+ outptr0[RGB_GREEN] = range_limit[y + cgreen];
+ outptr0[RGB_BLUE] = range_limit[y + cblue];
+ y = GETJSAMPLE(*inptr01);
+ outptr1[RGB_RED] = range_limit[y + cred];
+ outptr1[RGB_GREEN] = range_limit[y + cgreen];
+ outptr1[RGB_BLUE] = range_limit[y + cblue];
+ }
+}
+
+
+/*
+ * Module initialization routine for merged upsampling/color conversion.
+ *
+ * NB: this is called under the conditions determined by use_merged_upsample()
+ * in jdmaster.c. That routine MUST correspond to the actual capabilities
+ * of this module; no safety checks are made here.
+ */
+
+GLOBAL(void)
+jinit_merged_upsampler (j_decompress_ptr cinfo)
+{
+ my_upsample_ptr upsample;
+
+ upsample = (my_upsample_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_upsampler));
+ cinfo->upsample = (struct jpeg_upsampler *) upsample;
+ upsample->pub.start_pass = start_pass_merged_upsample;
+ upsample->pub.need_context_rows = FALSE;
+
+ upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
+
+ if (cinfo->max_v_samp_factor == 2) {
+ upsample->pub.upsample = merged_2v_upsample;
+ upsample->upmethod = h2v2_merged_upsample;
+ /* Allocate a spare row buffer */
+ upsample->spare_row = (JSAMPROW16)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE16)));
+ } else {
+ upsample->pub.upsample = merged_1v_upsample;
+ upsample->upmethod = h2v1_merged_upsample;
+ /* No spare row needed */
+ upsample->spare_row = NULL;
+ }
+
+ build_ycc_rgb_table(cinfo);
+}
+
+#endif /* UPSAMPLE_MERGING_SUPPORTED */
diff --git a/jpeg-6c/jdphuff.c b/jpeg-6c/jdphuff.c
new file mode 100644
index 0000000..54f565a
--- /dev/null
+++ b/jpeg-6c/jdphuff.c
@@ -0,0 +1,675 @@
+/*
+ * jdphuff.c
+ *
+ * Copyright (C) 1995-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains Huffman entropy decoding routines for progressive JPEG.
+ *
+ * Much of the complexity here has to do with supporting input suspension.
+ * If the data source module demands suspension, we want to be able to back
+ * up to the start of the current MCU. To do this, we copy state variables
+ * into local working storage, and update them back to the permanent
+ * storage only upon successful completion of an MCU.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h" /* Private declarations for lossy subsystem */
+#include "jdhuff.h" /* Declarations shared with jd*huff.c */
+
+
+#ifdef D_PROGRESSIVE_SUPPORTED
+
+/*
+ * Private entropy decoder object for progressive Huffman decoding.
+ *
+ * The savable_state subrecord contains fields that change within an MCU,
+ * but must not be updated permanently until we complete the MCU.
+ */
+
+typedef struct {
+ unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
+ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
+} savable_state;
+
+/* This macro is to work around compilers with missing or broken
+ * structure assignment. You'll need to fix this code if you have
+ * such a compiler and you change MAX_COMPS_IN_SCAN.
+ */
+
+#ifndef NO_STRUCT_ASSIGN
+#define ASSIGN_STATE(dest,src) ((dest) = (src))
+#else
+#if MAX_COMPS_IN_SCAN == 4
+#define ASSIGN_STATE(dest,src) \
+ ((dest).EOBRUN = (src).EOBRUN, \
+ (dest).last_dc_val[0] = (src).last_dc_val[0], \
+ (dest).last_dc_val[1] = (src).last_dc_val[1], \
+ (dest).last_dc_val[2] = (src).last_dc_val[2], \
+ (dest).last_dc_val[3] = (src).last_dc_val[3])
+#endif
+#endif
+
+
+typedef struct {
+ huffd_common_fields; /* Fields shared with other entropy decoders */
+
+ /* These fields are loaded into local variables at start of each MCU.
+ * In case of suspension, we exit WITHOUT updating them.
+ */
+ savable_state saved; /* Other state at start of MCU */
+
+ /* These fields are NOT loaded into local working state. */
+ unsigned int restarts_to_go; /* MCUs left in this restart interval */
+
+ /* Pointers to derived tables (these workspaces have image lifespan) */
+ d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
+
+ d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
+} phuff_entropy_decoder;
+
+typedef phuff_entropy_decoder * phuff_entropy_ptr;
+
+/* Forward declarations */
+METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+
+
+/*
+ * Initialize for a Huffman-compressed scan.
+ */
+
+METHODDEF(void)
+start_pass_phuff_decoder (j_decompress_ptr cinfo)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyd->entropy_private;
+ boolean is_DC_band, bad;
+ int ci, coefi, tbl;
+ int *coef_bit_ptr;
+ jpeg_component_info * compptr;
+
+ is_DC_band = (cinfo->Ss == 0);
+
+ /* Validate scan parameters */
+ bad = FALSE;
+ if (is_DC_band) {
+ if (cinfo->Se != 0)
+ bad = TRUE;
+ } else {
+ /* need not check Ss/Se < 0 since they came from unsigned bytes */
+ if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
+ bad = TRUE;
+ /* AC scans may have only one component */
+ if (cinfo->comps_in_scan != 1)
+ bad = TRUE;
+ }
+ if (cinfo->Ah != 0) {
+ /* Successive approximation refinement scan: must have Al = Ah-1. */
+ if (cinfo->Al != cinfo->Ah-1)
+ bad = TRUE;
+ }
+ if (cinfo->Al > 13) /* need not check for < 0 */
+ bad = TRUE;
+ /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
+ * but the spec doesn't say so, and we try to be liberal about what we
+ * accept. Note: large Al values could result in out-of-range DC
+ * coefficients during early scans, leading to bizarre displays due to
+ * overflows in the IDCT math. But we won't crash.
+ */
+ if (bad)
+ ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
+ cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
+ /* Update progression status, and verify that scan order is legal.
+ * Note that inter-scan inconsistencies are treated as warnings
+ * not fatal errors ... not clear if this is right way to behave.
+ */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ int cindex = cinfo->cur_comp_info[ci]->component_index;
+ coef_bit_ptr = & cinfo->coef_bits[cindex][0];
+ if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
+ WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
+ for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
+ int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
+ if (cinfo->Ah != expected)
+ WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
+ coef_bit_ptr[coefi] = cinfo->Al;
+ }
+ }
+
+ /* Select MCU decoding routine */
+ if (cinfo->Ah == 0) {
+ if (is_DC_band)
+ lossyd->entropy_decode_mcu = decode_mcu_DC_first;
+ else
+ lossyd->entropy_decode_mcu = decode_mcu_AC_first;
+ } else {
+ if (is_DC_band)
+ lossyd->entropy_decode_mcu = decode_mcu_DC_refine;
+ else
+ lossyd->entropy_decode_mcu = decode_mcu_AC_refine;
+ }
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ /* Make sure requested tables are present, and compute derived tables.
+ * We may build same derived table more than once, but it's not expensive.
+ */
+ if (is_DC_band) {
+ if (cinfo->Ah == 0) { /* DC refinement needs no table */
+ tbl = compptr->dc_tbl_no;
+ jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
+ & entropy->derived_tbls[tbl]);
+ }
+ } else {
+ tbl = compptr->ac_tbl_no;
+ jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
+ & entropy->derived_tbls[tbl]);
+ /* remember the single active table */
+ entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
+ }
+ /* Initialize DC predictions to 0 */
+ entropy->saved.last_dc_val[ci] = 0;
+ }
+
+ /* Initialize bitread state variables */
+ entropy->bitstate.bits_left = 0;
+ entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
+ entropy->insufficient_data = FALSE;
+
+ /* Initialize private state variables */
+ entropy->saved.EOBRUN = 0;
+
+ /* Initialize restart counter */
+ entropy->restarts_to_go = cinfo->restart_interval;
+}
+
+
+/*
+ * Figure F.12: extend sign bit.
+ * On some machines, a shift and add will be faster than a table lookup.
+ */
+
+#ifdef AVOID_TABLES
+
+#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
+
+#else
+
+#define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
+
+static const int extend_test[16] = /* entry n is 2**(n-1) */
+ { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
+ 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
+
+static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
+ { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
+ ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
+ ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
+ ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
+
+#endif /* AVOID_TABLES */
+
+
+/*
+ * Check for a restart marker & resynchronize decoder.
+ * Returns FALSE if must suspend.
+ */
+
+LOCAL(boolean)
+process_restart (j_decompress_ptr cinfo)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyd->entropy_private;
+ int ci;
+
+ /* Throw away any unused bits remaining in bit buffer; */
+ /* include any full bytes in next_marker's count of discarded bytes */
+ cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
+ entropy->bitstate.bits_left = 0;
+
+ /* Advance past the RSTn marker */
+ if (! (*cinfo->marker->read_restart_marker) (cinfo))
+ return FALSE;
+
+ /* Re-initialize DC predictions to 0 */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++)
+ entropy->saved.last_dc_val[ci] = 0;
+ /* Re-init EOB run count, too */
+ entropy->saved.EOBRUN = 0;
+
+ /* Reset restart counter */
+ entropy->restarts_to_go = cinfo->restart_interval;
+
+ /* Reset out-of-data flag, unless read_restart_marker left us smack up
+ * against a marker. In that case we will end up treating the next data
+ * segment as empty, and we can avoid producing bogus output pixels by
+ * leaving the flag set.
+ */
+ if (cinfo->unread_marker == 0)
+ entropy->insufficient_data = FALSE;
+
+ return TRUE;
+}
+
+
+/*
+ * Huffman MCU decoding.
+ * Each of these routines decodes and returns one MCU's worth of
+ * Huffman-compressed coefficients.
+ * The coefficients are reordered from zigzag order into natural array order,
+ * but are not dequantized.
+ *
+ * The i'th block of the MCU is stored into the block pointed to by
+ * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
+ *
+ * We return FALSE if data source requested suspension. In that case no
+ * changes have been made to permanent state. (Exception: some output
+ * coefficients may already have been assigned. This is harmless for
+ * spectral selection, since we'll just re-assign them on the next call.
+ * Successive approximation AC refinement has to be more careful, however.)
+ */
+
+/*
+ * MCU decoding for DC initial scan (either spectral selection,
+ * or first pass of successive approximation).
+ */
+
+METHODDEF(boolean)
+decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyd->entropy_private;
+ int Al = cinfo->Al;
+ register int s, r;
+ int blkn, ci;
+ JBLOCKROW block;
+ BITREAD_STATE_VARS;
+ savable_state state;
+ d_derived_tbl * tbl;
+ jpeg_component_info * compptr;
+
+ /* Process restart marker if needed; may have to suspend */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! process_restart(cinfo))
+ return FALSE;
+ }
+
+ /* If we've run out of data, just leave the MCU set to zeroes.
+ * This way, we return uniform gray for the remainder of the segment.
+ */
+ if (! entropy->insufficient_data) {
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+ ASSIGN_STATE(state, entropy->saved);
+
+ /* Outer loop handles each block in the MCU */
+
+ for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+ tbl = entropy->derived_tbls[compptr->dc_tbl_no];
+
+ /* Decode a single block's worth of coefficients */
+
+ /* Section F.2.2.1: decode the DC coefficient difference */
+ HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
+ if (s) {
+ CHECK_BIT_BUFFER(br_state, s, return FALSE);
+ r = GET_BITS(s);
+ s = HUFF_EXTEND(r, s);
+ }
+
+ /* Convert DC difference to actual value, update last_dc_val */
+ s += state.last_dc_val[ci];
+ state.last_dc_val[ci] = s;
+ /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
+ (*block)[0] = (JCOEF) (s << Al);
+ }
+
+ /* Completed MCU, so update state */
+ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
+ ASSIGN_STATE(entropy->saved, state);
+ }
+
+ /* Account for restart interval (no-op if not using restarts) */
+ entropy->restarts_to_go--;
+
+ return TRUE;
+}
+
+
+/*
+ * MCU decoding for AC initial scan (either spectral selection,
+ * or first pass of successive approximation).
+ */
+
+METHODDEF(boolean)
+decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyd->entropy_private;
+ int Se = cinfo->Se;
+ int Al = cinfo->Al;
+ register int s, k, r;
+ unsigned int EOBRUN;
+ JBLOCKROW block;
+ BITREAD_STATE_VARS;
+ d_derived_tbl * tbl;
+
+ /* Process restart marker if needed; may have to suspend */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! process_restart(cinfo))
+ return FALSE;
+ }
+
+ /* If we've run out of data, just leave the MCU set to zeroes.
+ * This way, we return uniform gray for the remainder of the segment.
+ */
+ if (! entropy->insufficient_data) {
+
+ /* Load up working state.
+ * We can avoid loading/saving bitread state if in an EOB run.
+ */
+ EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
+
+ /* There is always only one block per MCU */
+
+ if (EOBRUN > 0) /* if it's a band of zeroes... */
+ EOBRUN--; /* ...process it now (we do nothing) */
+ else {
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+ block = MCU_data[0];
+ tbl = entropy->ac_derived_tbl;
+
+ for (k = cinfo->Ss; k <= Se; k++) {
+ HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
+ r = s >> 4;
+ s &= 15;
+ if (s) {
+ k += r;
+ CHECK_BIT_BUFFER(br_state, s, return FALSE);
+ r = GET_BITS(s);
+ s = HUFF_EXTEND(r, s);
+ /* Scale and output coefficient in natural (dezigzagged) order */
+ (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
+ } else {
+ if (r == 15) { /* ZRL */
+ k += 15; /* skip 15 zeroes in band */
+ } else { /* EOBr, run length is 2^r + appended bits */
+ EOBRUN = 1 << r;
+ if (r) { /* EOBr, r > 0 */
+ CHECK_BIT_BUFFER(br_state, r, return FALSE);
+ r = GET_BITS(r);
+ EOBRUN += r;
+ }
+ EOBRUN--; /* this band is processed at this moment */
+ break; /* force end-of-band */
+ }
+ }
+ }
+
+ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
+ }
+
+ /* Completed MCU, so update state */
+ entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
+ }
+
+ /* Account for restart interval (no-op if not using restarts) */
+ entropy->restarts_to_go--;
+
+ return TRUE;
+}
+
+
+/*
+ * MCU decoding for DC successive approximation refinement scan.
+ * Note: we assume such scans can be multi-component, although the spec
+ * is not very clear on the point.
+ */
+
+METHODDEF(boolean)
+decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyd->entropy_private;
+ int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
+ int blkn;
+ JBLOCKROW block;
+ BITREAD_STATE_VARS;
+
+ /* Process restart marker if needed; may have to suspend */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! process_restart(cinfo))
+ return FALSE;
+ }
+
+ /* Not worth the cycles to check insufficient_data here,
+ * since we will not change the data anyway if we read zeroes.
+ */
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+
+ /* Outer loop handles each block in the MCU */
+
+ for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+
+ /* Encoded data is simply the next bit of the two's-complement DC value */
+ CHECK_BIT_BUFFER(br_state, 1, return FALSE);
+ if (GET_BITS(1))
+ (*block)[0] |= p1;
+ /* Note: since we use |=, repeating the assignment later is safe */
+ }
+
+ /* Completed MCU, so update state */
+ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
+
+ /* Account for restart interval (no-op if not using restarts) */
+ entropy->restarts_to_go--;
+
+ return TRUE;
+}
+
+
+/*
+ * MCU decoding for AC successive approximation refinement scan.
+ */
+
+METHODDEF(boolean)
+decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyd->entropy_private;
+ int Se = cinfo->Se;
+ int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
+ int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
+ register int s, k, r;
+ unsigned int EOBRUN;
+ JBLOCKROW block;
+ JCOEFPTR thiscoef;
+ BITREAD_STATE_VARS;
+ d_derived_tbl * tbl;
+ int num_newnz;
+ int newnz_pos[DCTSIZE2];
+
+ /* Process restart marker if needed; may have to suspend */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! process_restart(cinfo))
+ return FALSE;
+ }
+
+ /* If we've run out of data, don't modify the MCU.
+ */
+ if (! entropy->insufficient_data) {
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+ EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
+
+ /* There is always only one block per MCU */
+ block = MCU_data[0];
+ tbl = entropy->ac_derived_tbl;
+
+ /* If we are forced to suspend, we must undo the assignments to any newly
+ * nonzero coefficients in the block, because otherwise we'd get confused
+ * next time about which coefficients were already nonzero.
+ * But we need not undo addition of bits to already-nonzero coefficients;
+ * instead, we can test the current bit to see if we already did it.
+ */
+ num_newnz = 0;
+
+ /* initialize coefficient loop counter to start of band */
+ k = cinfo->Ss;
+
+ if (EOBRUN == 0) {
+ for (; k <= Se; k++) {
+ HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
+ r = s >> 4;
+ s &= 15;
+ if (s) {
+ if (s != 1) /* size of new coef should always be 1 */
+ WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
+ CHECK_BIT_BUFFER(br_state, 1, goto undoit);
+ if (GET_BITS(1))
+ s = p1; /* newly nonzero coef is positive */
+ else
+ s = m1; /* newly nonzero coef is negative */
+ } else {
+ if (r != 15) {
+ EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
+ if (r) {
+ CHECK_BIT_BUFFER(br_state, r, goto undoit);
+ r = GET_BITS(r);
+ EOBRUN += r;
+ }
+ break; /* rest of block is handled by EOB logic */
+ }
+ /* note s = 0 for processing ZRL */
+ }
+ /* Advance over already-nonzero coefs and r still-zero coefs,
+ * appending correction bits to the nonzeroes. A correction bit is 1
+ * if the absolute value of the coefficient must be increased.
+ */
+ do {
+ thiscoef = *block + jpeg_natural_order[k];
+ if (*thiscoef != 0) {
+ CHECK_BIT_BUFFER(br_state, 1, goto undoit);
+ if (GET_BITS(1)) {
+ if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
+ if (*thiscoef >= 0)
+ *thiscoef += p1;
+ else
+ *thiscoef += m1;
+ }
+ }
+ } else {
+ if (--r < 0)
+ break; /* reached target zero coefficient */
+ }
+ k++;
+ } while (k <= Se);
+ if (s) {
+ int pos = jpeg_natural_order[k];
+ /* Output newly nonzero coefficient */
+ (*block)[pos] = (JCOEF) s;
+ /* Remember its position in case we have to suspend */
+ newnz_pos[num_newnz++] = pos;
+ }
+ }
+ }
+
+ if (EOBRUN > 0) {
+ /* Scan any remaining coefficient positions after the end-of-band
+ * (the last newly nonzero coefficient, if any). Append a correction
+ * bit to each already-nonzero coefficient. A correction bit is 1
+ * if the absolute value of the coefficient must be increased.
+ */
+ for (; k <= Se; k++) {
+ thiscoef = *block + jpeg_natural_order[k];
+ if (*thiscoef != 0) {
+ CHECK_BIT_BUFFER(br_state, 1, goto undoit);
+ if (GET_BITS(1)) {
+ if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
+ if (*thiscoef >= 0)
+ *thiscoef += p1;
+ else
+ *thiscoef += m1;
+ }
+ }
+ }
+ }
+ /* Count one block completed in EOB run */
+ EOBRUN--;
+ }
+
+ /* Completed MCU, so update state */
+ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
+ entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
+ }
+
+ /* Account for restart interval (no-op if not using restarts) */
+ entropy->restarts_to_go--;
+
+ return TRUE;
+
+undoit:
+ /* Re-zero any output coefficients that we made newly nonzero */
+ while (num_newnz > 0)
+ (*block)[newnz_pos[--num_newnz]] = 0;
+
+ return FALSE;
+}
+
+
+/*
+ * Module initialization routine for progressive Huffman entropy decoding.
+ */
+
+GLOBAL(void)
+jinit_phuff_decoder (j_decompress_ptr cinfo)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy;
+ int *coef_bit_ptr;
+ int ci, i;
+
+ entropy = (phuff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(phuff_entropy_decoder));
+ lossyd->entropy_private = (void *) entropy;
+ lossyd->entropy_start_pass = start_pass_phuff_decoder;
+
+ /* Mark derived tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ entropy->derived_tbls[i] = NULL;
+ }
+
+ /* Create progression status table */
+ cinfo->coef_bits = (int (*)[DCTSIZE2])
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->num_components*DCTSIZE2*SIZEOF(int));
+ coef_bit_ptr = & cinfo->coef_bits[0][0];
+ for (ci = 0; ci < cinfo->num_components; ci++)
+ for (i = 0; i < DCTSIZE2; i++)
+ *coef_bit_ptr++ = -1;
+}
+
+#endif /* D_PROGRESSIVE_SUPPORTED */
diff --git a/jpeg-6c/jdpostct.c b/jpeg-6c/jdpostct.c
new file mode 100644
index 0000000..7c80ba6
--- /dev/null
+++ b/jpeg-6c/jdpostct.c
@@ -0,0 +1,291 @@
+/*
+ * jdpostct.c
+ *
+ * Copyright (C) 1994-1996, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the decompression postprocessing controller.
+ * This controller manages the upsampling, color conversion, and color
+ * quantization/reduction steps; specifically, it controls the buffering
+ * between upsample/color conversion and color quantization/reduction.
+ *
+ * If no color quantization/reduction is required, then this module has no
+ * work to do, and it just hands off to the upsample/color conversion code.
+ * An integrated upsample/convert/quantize process would replace this module
+ * entirely.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Private buffer controller object */
+
+typedef struct {
+ struct jpeg_d_post_controller pub; /* public fields */
+
+ /* Color quantization source buffer: this holds output data from
+ * the upsample/color conversion step to be passed to the quantizer.
+ * For two-pass color quantization, we need a full-image buffer;
+ * for one-pass operation, a strip buffer is sufficient.
+ */
+ jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
+ JSAMPARRAY16 buffer; /* strip buffer, or current strip of virtual */
+ JDIMENSION strip_height; /* buffer size in rows */
+ /* for two-pass mode only: */
+ JDIMENSION starting_row; /* row # of first row in current strip */
+ JDIMENSION next_row; /* index of next row to fill/empty in strip */
+} my_post_controller;
+
+typedef my_post_controller * my_post_ptr;
+
+
+/* Forward declarations */
+METHODDEF(void) post_process_1pass
+ JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY16 output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+#ifdef QUANT_2PASS_SUPPORTED
+METHODDEF(void) post_process_prepass
+ JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY16 output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+METHODDEF(void) post_process_2pass
+ JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY16 output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+#endif
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF(void)
+start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+ my_post_ptr post = (my_post_ptr) cinfo->post;
+
+ switch (pass_mode) {
+ case JBUF_PASS_THRU:
+ if (cinfo->quantize_colors) {
+ /* Single-pass processing with color quantization. */
+ post->pub.post_process_data = post_process_1pass;
+ /* We could be doing buffered-image output before starting a 2-pass
+ * color quantization; in that case, jinit_d_post_controller did not
+ * allocate a strip buffer. Use the virtual-array buffer as workspace.
+ */
+ if (post->buffer == NULL) {
+ post->buffer = (JSAMPARRAY16)(*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, post->whole_image,
+ (JDIMENSION) 0, post->strip_height, TRUE);
+ }
+ } else {
+ /* For single-pass processing without color quantization,
+ * I have no work to do; just call the upsampler directly.
+ */
+ post->pub.post_process_data = cinfo->upsample->upsample;
+ }
+ break;
+#ifdef QUANT_2PASS_SUPPORTED
+ case JBUF_SAVE_AND_PASS:
+ /* First pass of 2-pass quantization */
+ if (post->whole_image == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ post->pub.post_process_data = post_process_prepass;
+ break;
+ case JBUF_CRANK_DEST:
+ /* Second pass of 2-pass quantization */
+ if (post->whole_image == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ post->pub.post_process_data = post_process_2pass;
+ break;
+#endif /* QUANT_2PASS_SUPPORTED */
+ default:
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+ break;
+ }
+ post->starting_row = post->next_row = 0;
+}
+
+
+/*
+ * Process some data in the one-pass (strip buffer) case.
+ * This is used for color precision reduction as well as one-pass quantization.
+ */
+
+METHODDEF(void)
+post_process_1pass (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY16 output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_post_ptr post = (my_post_ptr) cinfo->post;
+ JDIMENSION num_rows, max_rows;
+
+ /* Fill the buffer, but not more than what we can dump out in one go. */
+ /* Note we rely on the upsampler to detect bottom of image. */
+ max_rows = out_rows_avail - *out_row_ctr;
+ if (max_rows > post->strip_height)
+ max_rows = post->strip_height;
+ num_rows = 0;
+ (*cinfo->upsample->upsample) (cinfo,
+ input_buf, in_row_group_ctr, in_row_groups_avail,
+ post->buffer, &num_rows, max_rows);
+ /* Quantize and emit data. */
+ (*cinfo->cquantize->color_quantize) (cinfo,
+ post->buffer, output_buf + *out_row_ctr, (int) num_rows);
+ *out_row_ctr += num_rows;
+}
+
+
+#ifdef QUANT_2PASS_SUPPORTED
+
+/*
+ * Process some data in the first pass of 2-pass quantization.
+ */
+
+METHODDEF(void)
+post_process_prepass (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY16 output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_post_ptr post = (my_post_ptr) cinfo->post;
+ JDIMENSION old_next_row, num_rows;
+
+ /* Reposition virtual buffer if at start of strip. */
+ if (post->next_row == 0) {
+ post->buffer = (JSAMPARRAY16)(*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, post->whole_image,
+ post->starting_row, post->strip_height, TRUE);
+ }
+
+ /* Upsample some data (up to a strip height's worth). */
+ old_next_row = post->next_row;
+ (*cinfo->upsample->upsample) (cinfo,
+ input_buf, in_row_group_ctr, in_row_groups_avail,
+ post->buffer, &post->next_row, post->strip_height);
+
+ /* Allow quantizer to scan new data. No data is emitted, */
+ /* but we advance out_row_ctr so outer loop can tell when we're done. */
+ if (post->next_row > old_next_row) {
+ num_rows = post->next_row - old_next_row;
+ (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
+ (JSAMPARRAY16) NULL, (int) num_rows);
+ *out_row_ctr += num_rows;
+ }
+
+ /* Advance if we filled the strip. */
+ if (post->next_row >= post->strip_height) {
+ post->starting_row += post->strip_height;
+ post->next_row = 0;
+ }
+}
+
+
+/*
+ * Process some data in the second pass of 2-pass quantization.
+ */
+
+METHODDEF(void)
+post_process_2pass (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY16 output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_post_ptr post = (my_post_ptr) cinfo->post;
+ JDIMENSION num_rows, max_rows;
+
+ /* Reposition virtual buffer if at start of strip. */
+ if (post->next_row == 0) {
+ post->buffer = (JSAMPARRAY16)(*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, post->whole_image,
+ post->starting_row, post->strip_height, FALSE);
+ }
+
+ /* Determine number of rows to emit. */
+ num_rows = post->strip_height - post->next_row; /* available in strip */
+ max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
+ if (num_rows > max_rows)
+ num_rows = max_rows;
+ /* We have to check bottom of image here, can't depend on upsampler. */
+ max_rows = cinfo->output_height - post->starting_row;
+ if (num_rows > max_rows)
+ num_rows = max_rows;
+
+ /* Quantize and emit data. */
+ (*cinfo->cquantize->color_quantize) (cinfo,
+ post->buffer + post->next_row, output_buf + *out_row_ctr,
+ (int) num_rows);
+ *out_row_ctr += num_rows;
+
+ /* Advance if we filled the strip. */
+ post->next_row += num_rows;
+ if (post->next_row >= post->strip_height) {
+ post->starting_row += post->strip_height;
+ post->next_row = 0;
+ }
+}
+
+#endif /* QUANT_2PASS_SUPPORTED */
+
+
+/*
+ * Initialize postprocessing controller.
+ */
+
+GLOBAL(void)
+jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
+{
+ my_post_ptr post;
+
+ post = (my_post_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_post_controller));
+ cinfo->post = (struct jpeg_d_post_controller *) post;
+ post->pub.start_pass = start_pass_dpost;
+ post->whole_image = NULL; /* flag for no virtual arrays */
+ post->buffer = NULL; /* flag for no strip buffer */
+
+ /* Create the quantization buffer, if needed */
+ if (cinfo->quantize_colors) {
+ /* The buffer strip height is max_v_samp_factor, which is typically
+ * an efficient number of rows for upsampling to return.
+ * (In the presence of output rescaling, we might want to be smarter?)
+ */
+ post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
+ if (need_full_buffer) {
+ /* Two-pass color quantization: need full-image storage. */
+ /* We round up the number of rows to a multiple of the strip height. */
+#ifdef QUANT_2PASS_SUPPORTED
+ post->whole_image = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ cinfo->output_width * cinfo->out_color_components * SIZEOF(JSAMPLE16),
+ (JDIMENSION) jround_up((long) cinfo->output_height,
+ (long) post->strip_height),
+ post->strip_height);
+#else
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+#endif /* QUANT_2PASS_SUPPORTED */
+ } else {
+ /* One-pass color quantization: just make a strip buffer. */
+ post->buffer = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->output_width * cinfo->out_color_components * SIZEOF(JSAMPLE16),
+ post->strip_height);
+ }
+ }
+}
diff --git a/jpeg-6c/jdpred.c b/jpeg-6c/jdpred.c
new file mode 100644
index 0000000..215c4ae
--- /dev/null
+++ b/jpeg-6c/jdpred.c
@@ -0,0 +1,247 @@
+/*
+ * jdpred.c
+ *
+ * Copyright (C) 1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains sample undifferencing (reconstruction) for lossless JPEG.
+ *
+ * In order to avoid paying the performance penalty of having to check the
+ * predictor being used and the row being processed for each call of the
+ * undifferencer, and to promote optimization, we have separate undifferencing
+ * functions for each case.
+ *
+ * We are able to avoid duplicating source code by implementing the predictors
+ * and undifferencers as macros. Each of the undifferencing functions are
+ * simply wrappers around an UNDIFFERENCE macro with the appropriate PREDICTOR
+ * macro passed as an argument.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossls.h" /* Private declarations for lossless codec */
+
+
+#ifdef D_LOSSLESS_SUPPORTED
+
+/* Predictor for the first column of the first row: 2^(P-Pt-1) */
+#define INITIAL_PREDICTORx (1 << (cinfo->data_precision - cinfo->Al - 1))
+
+/* Predictor for the first column of the remaining rows: Rb */
+#define INITIAL_PREDICTOR2 GETJSAMPLE(prev_row[0])
+
+
+/*
+ * 1-Dimensional undifferencer routine.
+ *
+ * This macro implements the 1-D horizontal predictor (1). INITIAL_PREDICTOR
+ * is used as the special case predictor for the first column, which must be
+ * either INITIAL_PREDICTOR2 or INITIAL_PREDICTORx. The remaining samples
+ * use PREDICTOR1.
+ *
+ * The reconstructed sample is supposed to be calculated modulo 2^16, so we
+ * logically AND the result with 0xFFFF.
+*/
+
+#define UNDIFFERENCE_1D(INITIAL_PREDICTOR) \
+ int xindex; \
+ int Ra; \
+ \
+ Ra = (diff_buf[0] + INITIAL_PREDICTOR) & 0xFFFF; \
+ undiff_buf[0] = Ra; \
+ \
+ for (xindex = 1; xindex < width; xindex++) { \
+ Ra = (diff_buf[xindex] + PREDICTOR1) & 0xFFFF; \
+ undiff_buf[xindex] = Ra; \
+ }
+
+/*
+ * 2-Dimensional undifferencer routine.
+ *
+ * This macro implements the 2-D horizontal predictors (#2-7). PREDICTOR2 is
+ * used as the special case predictor for the first column. The remaining
+ * samples use PREDICTOR, which is a function of Ra, Rb, Rc.
+ *
+ * Because prev_row and output_buf may point to the same storage area (in an
+ * interleaved image with Vi=1, for example), we must take care to buffer Rb/Rc
+ * before writing the current reconstructed sample value into output_buf.
+ *
+ * The reconstructed sample is supposed to be calculated modulo 2^16, so we
+ * logically AND the result with 0xFFFF.
+ */
+
+#define UNDIFFERENCE_2D(PREDICTOR) \
+ int xindex; \
+ int Ra, Rb, Rc; \
+ \
+ Rb = GETJSAMPLE(prev_row[0]); \
+ Ra = (diff_buf[0] + PREDICTOR2) & 0xFFFF; \
+ undiff_buf[0] = Ra; \
+ \
+ for (xindex = 1; xindex < width; xindex++) { \
+ Rc = Rb; \
+ Rb = GETJSAMPLE(prev_row[xindex]); \
+ Ra = (diff_buf[xindex] + PREDICTOR) & 0xFFFF; \
+ undiff_buf[xindex] = Ra; \
+ }
+
+
+/*
+ * Undifferencers for the all rows but the first in a scan or restart interval.
+ * The first sample in the row is undifferenced using the vertical
+ * predictor (2). The rest of the samples are undifferenced using the
+ * predictor specified in the scan header.
+ */
+
+METHODDEF(void)
+jpeg_undifference1(j_decompress_ptr cinfo, int comp_index,
+ JDIFFROW diff_buf, JDIFFROW prev_row,
+ JDIFFROW undiff_buf, JDIMENSION width)
+{
+ UNDIFFERENCE_1D(INITIAL_PREDICTOR2);
+}
+
+METHODDEF(void)
+jpeg_undifference2(j_decompress_ptr cinfo, int comp_index,
+ JDIFFROW diff_buf, JDIFFROW prev_row,
+ JDIFFROW undiff_buf, JDIMENSION width)
+{
+ UNDIFFERENCE_2D(PREDICTOR2);
+}
+
+METHODDEF(void)
+jpeg_undifference3(j_decompress_ptr cinfo, int comp_index,
+ JDIFFROW diff_buf, JDIFFROW prev_row,
+ JDIFFROW undiff_buf, JDIMENSION width)
+{
+ UNDIFFERENCE_2D(PREDICTOR3);
+}
+
+METHODDEF(void)
+jpeg_undifference4(j_decompress_ptr cinfo, int comp_index,
+ JDIFFROW diff_buf, JDIFFROW prev_row,
+ JDIFFROW undiff_buf, JDIMENSION width)
+{
+ UNDIFFERENCE_2D(PREDICTOR4);
+}
+
+METHODDEF(void)
+jpeg_undifference5(j_decompress_ptr cinfo, int comp_index,
+ JDIFFROW diff_buf, JDIFFROW prev_row,
+ JDIFFROW undiff_buf, JDIMENSION width)
+{
+ UNDIFFERENCE_2D(PREDICTOR5);
+}
+
+METHODDEF(void)
+jpeg_undifference6(j_decompress_ptr cinfo, int comp_index,
+ JDIFFROW diff_buf, JDIFFROW prev_row,
+ JDIFFROW undiff_buf, JDIMENSION width)
+{
+ UNDIFFERENCE_2D(PREDICTOR6);
+}
+
+METHODDEF(void)
+jpeg_undifference7(j_decompress_ptr cinfo, int comp_index,
+ JDIFFROW diff_buf, JDIFFROW prev_row,
+ JDIFFROW undiff_buf, JDIMENSION width)
+{
+ UNDIFFERENCE_2D(PREDICTOR7);
+}
+
+
+/*
+ * Undifferencer for the first row in a scan or restart interval. The first
+ * sample in the row is undifferenced using the special predictor constant
+ * x=2^(P-Pt-1). The rest of the samples are undifferenced using the
+ * 1-D horizontal predictor (1).
+ */
+
+METHODDEF(void)
+jpeg_undifference_first_row(j_decompress_ptr cinfo, int comp_index,
+ JDIFFROW diff_buf, JDIFFROW prev_row,
+ JDIFFROW undiff_buf, JDIMENSION width)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+
+ UNDIFFERENCE_1D(INITIAL_PREDICTORx);
+
+ /*
+ * Now that we have undifferenced the first row, we want to use the
+ * undifferencer which corresponds to the predictor specified in the
+ * scan header.
+ */
+ switch (cinfo->Ss) {
+ case 1:
+ losslsd->predict_undifference[comp_index] = jpeg_undifference1;
+ break;
+ case 2:
+ losslsd->predict_undifference[comp_index] = jpeg_undifference2;
+ break;
+ case 3:
+ losslsd->predict_undifference[comp_index] = jpeg_undifference3;
+ break;
+ case 4:
+ losslsd->predict_undifference[comp_index] = jpeg_undifference4;
+ break;
+ case 5:
+ losslsd->predict_undifference[comp_index] = jpeg_undifference5;
+ break;
+ case 6:
+ losslsd->predict_undifference[comp_index] = jpeg_undifference6;
+ break;
+ case 7:
+ losslsd->predict_undifference[comp_index] = jpeg_undifference7;
+ break;
+ }
+}
+
+
+/*
+ * Initialize for an input processing pass.
+ */
+
+METHODDEF(void)
+predict_start_pass (j_decompress_ptr cinfo)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ int ci;
+
+ /* Check that the scan parameters Ss, Se, Ah, Al are OK for lossless JPEG.
+ *
+ * Ss is the predictor selection value (psv). Legal values for sequential
+ * lossless JPEG are: 1 <= psv <= 7.
+ *
+ * Se and Ah are not used and should be zero.
+ *
+ * Al specifies the point transform (Pt). Legal values are: 0 <= Pt <= 15.
+ */
+ if (cinfo->Ss < 1 || cinfo->Ss > 7 ||
+ cinfo->Se != 0 || cinfo->Ah != 0 ||
+ cinfo->Al > 15) /* need not check for < 0 */
+ ERREXIT4(cinfo, JERR_BAD_LOSSLESS,
+ cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
+
+ /* Set undifference functions to first row function */
+ for (ci = 0; ci < cinfo->num_components; ci++)
+ losslsd->predict_undifference[ci] = jpeg_undifference_first_row;
+}
+
+
+/*
+ * Module initialization routine for the undifferencer.
+ */
+
+GLOBAL(void)
+jinit_undifferencer (j_decompress_ptr cinfo)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+
+ losslsd->predict_start_pass = predict_start_pass;
+ losslsd->predict_process_restart = predict_start_pass;
+}
+
+#endif /* D_LOSSLESS_SUPPORTED */
+
diff --git a/jpeg-6c/jdsample.c b/jpeg-6c/jdsample.c
new file mode 100644
index 0000000..fd86daf
--- /dev/null
+++ b/jpeg-6c/jdsample.c
@@ -0,0 +1,479 @@
+/*
+ * jdsample.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains upsampling routines.
+ *
+ * Upsampling input data is counted in "row groups". A row group
+ * is defined to be (v_samp_factor * codec_data_unit / min_codec_data_unit)
+ * sample rows of each component. Upsampling will normally produce
+ * max_v_samp_factor pixel rows from each row group (but this could vary
+ * if the upsampler is applying a scale factor of its own).
+ *
+ * An excellent reference for image resampling is
+ * Digital Image Warping, George Wolberg, 1990.
+ * Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Pointer to routine to upsample a single component */
+typedef JMETHOD(void, upsample1_ptr,
+ (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 * output_data_ptr));
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_upsampler pub; /* public fields */
+
+ /* Color conversion buffer. When using separate upsampling and color
+ * conversion steps, this buffer holds one upsampled row group until it
+ * has been color converted and output.
+ * Note: we do not allocate any storage for component(s) which are full-size,
+ * ie do not need rescaling. The corresponding entry of color_buf[] is
+ * simply set to point to the input data array, thereby avoiding copying.
+ */
+ JSAMPARRAY16 color_buf[MAX_COMPONENTS];
+
+ /* Per-component upsampling method pointers */
+ upsample1_ptr methods[MAX_COMPONENTS];
+
+ int next_row_out; /* counts rows emitted from color_buf */
+ JDIMENSION rows_to_go; /* counts rows remaining in image */
+
+ /* Height of an input row group for each component. */
+ int rowgroup_height[MAX_COMPONENTS];
+
+ /* These arrays save pixel expansion factors so that int_expand need not
+ * recompute them each time. They are unused for other upsampling methods.
+ */
+ UINT8 h_expand[MAX_COMPONENTS];
+ UINT8 v_expand[MAX_COMPONENTS];
+} my_upsampler;
+
+typedef my_upsampler * my_upsample_ptr;
+
+
+/*
+ * Initialize for an upsampling pass.
+ */
+
+METHODDEF(void)
+start_pass_upsample (j_decompress_ptr cinfo)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+
+ /* Mark the conversion buffer empty */
+ upsample->next_row_out = cinfo->max_v_samp_factor;
+ /* Initialize total-height counter for detecting bottom of image */
+ upsample->rows_to_go = cinfo->output_height;
+}
+
+
+/*
+ * Control routine to do upsampling (and color conversion).
+ *
+ * In this version we upsample each component independently.
+ * We upsample one row group into the conversion buffer, then apply
+ * color conversion a row at a time.
+ */
+
+METHODDEF(void)
+sep_upsample (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY16 output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ int ci;
+ jpeg_component_info * compptr;
+ JDIMENSION num_rows;
+
+ /* Fill the conversion buffer, if it's empty */
+ if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Invoke per-component upsample method. Notice we pass a POINTER
+ * to color_buf[ci], so that fullsize_upsample can change it.
+ */
+ (*upsample->methods[ci]) (cinfo, compptr,
+ input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
+ upsample->color_buf + ci);
+ }
+ upsample->next_row_out = 0;
+ }
+
+ /* Color-convert and emit rows */
+
+ /* How many we have in the buffer: */
+ num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
+ /* Not more than the distance to the end of the image. Need this test
+ * in case the image height is not a multiple of max_v_samp_factor:
+ */
+ if (num_rows > upsample->rows_to_go)
+ num_rows = upsample->rows_to_go;
+ /* And not more than what the client can accept: */
+ out_rows_avail -= *out_row_ctr;
+ if (num_rows > out_rows_avail)
+ num_rows = out_rows_avail;
+
+ (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
+ (JDIMENSION) upsample->next_row_out,
+ output_buf + *out_row_ctr,
+ (int) num_rows);
+
+ /* Adjust counts */
+ *out_row_ctr += num_rows;
+ upsample->rows_to_go -= num_rows;
+ upsample->next_row_out += num_rows;
+ /* When the buffer is emptied, declare this input row group consumed */
+ if (upsample->next_row_out >= cinfo->max_v_samp_factor)
+ (*in_row_group_ctr)++;
+}
+
+
+/*
+ * These are the routines invoked by sep_upsample to upsample pixel values
+ * of a single component. One row group is processed per call.
+ */
+
+
+/*
+ * For full-size components, we just make color_buf[ci] point at the
+ * input buffer, and thus avoid copying any data. Note that this is
+ * safe only because sep_upsample doesn't declare the input row group
+ * "consumed" until we are done color converting and emitting it.
+ */
+
+METHODDEF(void)
+fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 * output_data_ptr)
+{
+ *output_data_ptr = input_data;
+}
+
+
+/*
+ * This is a no-op version used for "uninteresting" components.
+ * These components will not be referenced by color conversion.
+ */
+
+METHODDEF(void)
+noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 * output_data_ptr)
+{
+ *output_data_ptr = NULL; /* safety check */
+}
+
+
+/*
+ * This version handles any integral sampling ratios.
+ * This is not used for typical JPEG files, so it need not be fast.
+ * Nor, for that matter, is it particularly accurate: the algorithm is
+ * simple replication of the input pixel onto the corresponding output
+ * pixels. The hi-falutin sampling literature refers to this as a
+ * "box filter". A box filter tends to introduce visible artifacts,
+ * so if you are actually going to use 3:1 or 4:1 sampling ratios
+ * you would be well advised to improve this code.
+ */
+
+METHODDEF(void)
+int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 * output_data_ptr)
+{
+ my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
+ JSAMPARRAY16 output_data = *output_data_ptr;
+ register JSAMPROW16 inptr, outptr;
+ register JSAMPLE16 invalue;
+ register int h;
+ JSAMPROW16 outend;
+ int h_expand, v_expand;
+ int inrow, outrow;
+
+ h_expand = upsample->h_expand[compptr->component_index];
+ v_expand = upsample->v_expand[compptr->component_index];
+
+ inrow = outrow = 0;
+ while (outrow < cinfo->max_v_samp_factor) {
+ /* Generate one output row with proper horizontal expansion */
+ inptr = input_data[inrow];
+ outptr = output_data[outrow];
+ outend = outptr + cinfo->output_width;
+ while (outptr < outend) {
+ invalue = *inptr++; /* don't need GETJSAMPLE() here */
+ for (h = h_expand; h > 0; h--) {
+ *outptr++ = invalue;
+ }
+ }
+ /* Generate any additional output rows by duplicating the first one */
+ if (v_expand > 1) {
+ jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
+ v_expand-1, cinfo->output_width);
+ }
+ inrow++;
+ outrow += v_expand;
+ }
+}
+
+
+/*
+ * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
+ * It's still a box filter.
+ */
+
+METHODDEF(void)
+h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 * output_data_ptr)
+{
+ JSAMPARRAY16 output_data = *output_data_ptr;
+ register JSAMPROW16 inptr, outptr;
+ register JSAMPLE16 invalue;
+ JSAMPROW16 outend;
+ int inrow;
+
+ for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
+ inptr = input_data[inrow];
+ outptr = output_data[inrow];
+ outend = outptr + cinfo->output_width;
+ while (outptr < outend) {
+ invalue = *inptr++; /* don't need GETJSAMPLE() here */
+ *outptr++ = invalue;
+ *outptr++ = invalue;
+ }
+ }
+}
+
+
+/*
+ * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
+ * It's still a box filter.
+ */
+
+METHODDEF(void)
+h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 * output_data_ptr)
+{
+ JSAMPARRAY16 output_data = *output_data_ptr;
+ register JSAMPROW16 inptr, outptr;
+ register JSAMPLE16 invalue;
+ JSAMPROW16 outend;
+ int inrow, outrow;
+
+ inrow = outrow = 0;
+ while (outrow < cinfo->max_v_samp_factor) {
+ inptr = input_data[inrow];
+ outptr = output_data[outrow];
+ outend = outptr + cinfo->output_width;
+ while (outptr < outend) {
+ invalue = *inptr++; /* don't need GETJSAMPLE() here */
+ *outptr++ = invalue;
+ *outptr++ = invalue;
+ }
+ jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
+ 1, cinfo->output_width);
+ inrow++;
+ outrow += 2;
+ }
+}
+
+
+/*
+ * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
+ *
+ * The upsampling algorithm is linear interpolation between pixel centers,
+ * also known as a "triangle filter". This is a good compromise between
+ * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
+ * of the way between input pixel centers.
+ *
+ * A note about the "bias" calculations: when rounding fractional values to
+ * integer, we do not want to always round 0.5 up to the next integer.
+ * If we did that, we'd introduce a noticeable bias towards larger values.
+ * Instead, this code is arranged so that 0.5 will be rounded up or down at
+ * alternate pixel locations (a simple ordered dither pattern).
+ */
+
+METHODDEF(void)
+h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 * output_data_ptr)
+{
+ JSAMPARRAY16 output_data = *output_data_ptr;
+ register JSAMPROW16 inptr, outptr;
+ register int invalue;
+ register JDIMENSION colctr;
+ int inrow;
+
+ for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
+ inptr = input_data[inrow];
+ outptr = output_data[inrow];
+ /* Special case for first column */
+ invalue = GETJSAMPLE(*inptr++);
+ *outptr++ = (JSAMPLE16) invalue;
+ *outptr++ = (JSAMPLE16) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
+
+ for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
+ /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
+ invalue = GETJSAMPLE(*inptr++) * 3;
+ *outptr++ = (JSAMPLE16) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
+ *outptr++ = (JSAMPLE16) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
+ }
+
+ /* Special case for last column */
+ invalue = GETJSAMPLE(*inptr);
+ *outptr++ = (JSAMPLE16) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
+ *outptr++ = (JSAMPLE16) invalue;
+ }
+}
+
+
+/*
+ * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
+ * Again a triangle filter; see comments for h2v1 case, above.
+ *
+ * It is OK for us to reference the adjacent input rows because we demanded
+ * context from the main buffer controller (see initialization code).
+ */
+
+METHODDEF(void)
+h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JSAMPARRAY16 input_data, JSAMPARRAY16 * output_data_ptr)
+{
+ JSAMPARRAY16 output_data = *output_data_ptr;
+ register JSAMPROW16 inptr0, inptr1, outptr;
+/*#if BITS_IN_JSAMPLE == 8
+ register int thiscolsum, lastcolsum, nextcolsum;
+#else*/
+ register INT32 thiscolsum, lastcolsum, nextcolsum;
+/*#endif*/
+ register JDIMENSION colctr;
+ int inrow, outrow, v;
+
+ inrow = outrow = 0;
+ while (outrow < cinfo->max_v_samp_factor) {
+ for (v = 0; v < 2; v++) {
+ /* inptr0 points to nearest input row, inptr1 points to next nearest */
+ inptr0 = input_data[inrow];
+ if (v == 0) /* next nearest is row above */
+ inptr1 = input_data[inrow-1];
+ else /* next nearest is row below */
+ inptr1 = input_data[inrow+1];
+ outptr = output_data[outrow++];
+
+ /* Special case for first column */
+ thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
+ nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
+ *outptr++ = (JSAMPLE16) ((thiscolsum * 4 + 8) >> 4);
+ *outptr++ = (JSAMPLE16) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
+ lastcolsum = thiscolsum; thiscolsum = nextcolsum;
+
+ for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
+ /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
+ /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
+ nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
+ *outptr++ = (JSAMPLE16) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
+ *outptr++ = (JSAMPLE16) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
+ lastcolsum = thiscolsum; thiscolsum = nextcolsum;
+ }
+
+ /* Special case for last column */
+ *outptr++ = (JSAMPLE16) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
+ *outptr++ = (JSAMPLE16) ((thiscolsum * 4 + 7) >> 4);
+ }
+ inrow++;
+ }
+}
+
+
+/*
+ * Module initialization routine for upsampling.
+ */
+
+GLOBAL(void)
+jinit_upsampler (j_decompress_ptr cinfo)
+{
+ my_upsample_ptr upsample;
+ int ci;
+ jpeg_component_info * compptr;
+ boolean need_buffer, do_fancy;
+ int h_in_group, v_in_group, h_out_group, v_out_group;
+
+ upsample = (my_upsample_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_upsampler));
+ cinfo->upsample = (struct jpeg_upsampler *) upsample;
+ upsample->pub.start_pass = start_pass_upsample;
+ upsample->pub.upsample = sep_upsample;
+ upsample->pub.need_context_rows = FALSE; /* until we find out differently */
+
+ if (cinfo->CCIR601_sampling) /* this isn't supported */
+ ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
+
+ /* jdmainct.c doesn't support context rows when min_codec_data_unit = 1,
+ * so don't ask for it.
+ */
+ do_fancy = cinfo->do_fancy_upsampling && cinfo->min_codec_data_unit > 1;
+
+ /* Verify we can handle the sampling factors, select per-component methods,
+ * and create storage as needed.
+ */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Compute size of an "input group" after IDCT scaling. This many samples
+ * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
+ */
+ h_in_group = (compptr->h_samp_factor * compptr->codec_data_unit) /
+ cinfo->min_codec_data_unit;
+ v_in_group = (compptr->v_samp_factor * compptr->codec_data_unit) /
+ cinfo->min_codec_data_unit;
+ h_out_group = cinfo->max_h_samp_factor;
+ v_out_group = cinfo->max_v_samp_factor;
+ upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
+ need_buffer = TRUE;
+ if (! compptr->component_needed) {
+ /* Don't bother to upsample an uninteresting component. */
+ upsample->methods[ci] = noop_upsample;
+ need_buffer = FALSE;
+ } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
+ /* Fullsize components can be processed without any work. */
+ upsample->methods[ci] = fullsize_upsample;
+ need_buffer = FALSE;
+ } else if (h_in_group * 2 == h_out_group &&
+ v_in_group == v_out_group) {
+ /* Special cases for 2h1v upsampling */
+ if (do_fancy && compptr->downsampled_width > 2)
+ upsample->methods[ci] = h2v1_fancy_upsample;
+ else
+ upsample->methods[ci] = h2v1_upsample;
+ } else if (h_in_group * 2 == h_out_group &&
+ v_in_group * 2 == v_out_group) {
+ /* Special cases for 2h2v upsampling */
+ if (do_fancy && compptr->downsampled_width > 2) {
+ upsample->methods[ci] = h2v2_fancy_upsample;
+ upsample->pub.need_context_rows = TRUE;
+ } else
+ upsample->methods[ci] = h2v2_upsample;
+ } else if ((h_out_group % h_in_group) == 0 &&
+ (v_out_group % v_in_group) == 0) {
+ /* Generic integral-factors upsampling method */
+ upsample->methods[ci] = int_upsample;
+ upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
+ upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
+ } else
+ ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
+ if (need_buffer) {
+ upsample->color_buf[ci] = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) jround_up((long) cinfo->output_width * SIZEOF(JSAMPLE16),
+ (long) cinfo->max_h_samp_factor),
+ (JDIMENSION) cinfo->max_v_samp_factor);
+ }
+ }
+}
diff --git a/jpeg-6c/jdscale.c b/jpeg-6c/jdscale.c
new file mode 100644
index 0000000..e747f65
--- /dev/null
+++ b/jpeg-6c/jdscale.c
@@ -0,0 +1,119 @@
+/*
+ * jdscale.c
+ *
+ * Copyright (C) 1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains sample scaling for lossless JPEG. This is a
+ * combination of upscaling the undifferenced sample by 2^Pt and downscaling
+ * the sample to fit into JSAMPLE.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossls.h" /* Private declarations for lossless codec */
+
+
+#ifdef D_LOSSLESS_SUPPORTED
+
+/*
+ * Private scaler object for lossless decoding.
+ */
+
+typedef struct {
+ int scale_factor;
+} scaler;
+
+typedef scaler * scaler_ptr;
+
+
+/*
+ * Scalers for packing sample differences into JSAMPLEs.
+ */
+
+METHODDEF(void)
+simple_upscale(j_decompress_ptr cinfo,
+ JDIFFROW diff_buf, JSAMPROW16 output_buf,
+ JDIMENSION width)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ scaler_ptr scaler = (scaler_ptr) losslsd->scaler_private;
+ int scale_factor = scaler->scale_factor;
+ int xindex;
+
+ for (xindex = 0; xindex < width; xindex++)
+ output_buf[xindex] = (JSAMPLE16) (diff_buf[xindex] << scale_factor);
+}
+
+METHODDEF(void)
+simple_downscale(j_decompress_ptr cinfo,
+ JDIFFROW diff_buf, JSAMPROW16 output_buf,
+ JDIMENSION width)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ scaler_ptr scaler = (scaler_ptr) losslsd->scaler_private;
+ int scale_factor = scaler->scale_factor;
+ int xindex;
+
+ for (xindex = 0; xindex < width; xindex++)
+ output_buf[xindex] = (JSAMPLE16) RIGHT_SHIFT(diff_buf[xindex], scale_factor);
+}
+
+METHODDEF(void)
+noscale(j_decompress_ptr cinfo,
+ JDIFFROW diff_buf, JSAMPROW16 output_buf,
+ JDIMENSION width)
+{
+ int xindex;
+
+ for (xindex = 0; xindex < width; xindex++)
+ output_buf[xindex] = (JSAMPLE16) diff_buf[xindex];
+}
+
+
+METHODDEF(void)
+scaler_start_pass (j_decompress_ptr cinfo)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ scaler_ptr scaler = (scaler_ptr) losslsd->scaler_private;
+ int downscale;
+
+ /*
+ * Downscale by the difference in the input vs. output precision. If the
+ * output precision >= input precision, then do not downscale.
+ */
+ downscale = cinfo->data_precision < cinfo->data_precision_other ?
+ cinfo->data_precision - cinfo->data_precision_other : 0;
+
+ scaler->scale_factor = cinfo->Al - downscale;
+
+ /* Set scaler functions based on scale_factor (positive = left shift) */
+ if (scaler->scale_factor > 0)
+ losslsd->scaler_scale = simple_upscale;
+ else if (scaler->scale_factor < 0) {
+ scaler->scale_factor = -scaler->scale_factor;
+ losslsd->scaler_scale = simple_downscale;
+ }
+ else
+ losslsd->scaler_scale = noscale;
+}
+
+
+GLOBAL(void)
+jinit_d_scaler (j_decompress_ptr cinfo)
+{
+ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
+ scaler_ptr scaler;
+
+ scaler = (scaler_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(scaler));
+ losslsd->scaler_private = (void *) scaler;
+ losslsd->scaler_start_pass = scaler_start_pass;
+}
+
+#endif /* D_LOSSLESS_SUPPORTED */
+
diff --git a/jpeg-6c/jdshuff.c b/jpeg-6c/jdshuff.c
new file mode 100644
index 0000000..aec21c1
--- /dev/null
+++ b/jpeg-6c/jdshuff.c
@@ -0,0 +1,360 @@
+/*
+ * jdshuff.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains Huffman entropy decoding routines for sequential JPEG.
+ *
+ * Much of the complexity here has to do with supporting input suspension.
+ * If the data source module demands suspension, we want to be able to back
+ * up to the start of the current MCU. To do this, we copy state variables
+ * into local working storage, and update them back to the permanent
+ * storage only upon successful completion of an MCU.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h" /* Private declarations for lossy codec */
+#include "jdhuff.h" /* Declarations shared with jd*huff.c */
+
+
+/*
+ * Private entropy decoder object for Huffman decoding.
+ *
+ * The savable_state subrecord contains fields that change within an MCU,
+ * but must not be updated permanently until we complete the MCU.
+ */
+
+typedef struct {
+ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
+} savable_state;
+
+/* This macro is to work around compilers with missing or broken
+ * structure assignment. You'll need to fix this code if you have
+ * such a compiler and you change MAX_COMPS_IN_SCAN.
+ */
+
+#ifndef NO_STRUCT_ASSIGN
+#define ASSIGN_STATE(dest,src) ((dest) = (src))
+#else
+#if MAX_COMPS_IN_SCAN == 4
+#define ASSIGN_STATE(dest,src) \
+ ((dest).last_dc_val[0] = (src).last_dc_val[0], \
+ (dest).last_dc_val[1] = (src).last_dc_val[1], \
+ (dest).last_dc_val[2] = (src).last_dc_val[2], \
+ (dest).last_dc_val[3] = (src).last_dc_val[3])
+#endif
+#endif
+
+
+typedef struct {
+ huffd_common_fields; /* Fields shared with other entropy decoders */
+
+ /* These fields are loaded into local variables at start of each MCU.
+ * In case of suspension, we exit WITHOUT updating them.
+ */
+ savable_state saved; /* Other state at start of MCU */
+
+ /* These fields are NOT loaded into local working state. */
+ unsigned int restarts_to_go; /* MCUs left in this restart interval */
+
+ /* Pointers to derived tables (these workspaces have image lifespan) */
+ d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
+ d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
+
+ /* Precalculated info set up by start_pass for use in decode_mcu: */
+
+ /* Pointers to derived tables to be used for each block within an MCU */
+ d_derived_tbl * dc_cur_tbls[D_MAX_DATA_UNITS_IN_MCU];
+ d_derived_tbl * ac_cur_tbls[D_MAX_DATA_UNITS_IN_MCU];
+ /* Whether we care about the DC and AC coefficient values for each block */
+ boolean dc_needed[D_MAX_DATA_UNITS_IN_MCU];
+ boolean ac_needed[D_MAX_DATA_UNITS_IN_MCU];
+} shuff_entropy_decoder;
+
+typedef shuff_entropy_decoder * shuff_entropy_ptr;
+
+
+/*
+ * Initialize for a Huffman-compressed scan.
+ */
+
+METHODDEF(void)
+start_pass_huff_decoder (j_decompress_ptr cinfo)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyd->entropy_private;
+ int ci, blkn, dctbl, actbl;
+ jpeg_component_info * compptr;
+
+ /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
+ * This ought to be an error condition, but we make it a warning because
+ * there are some baseline files out there with all zeroes in these bytes.
+ */
+ if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
+ cinfo->Ah != 0 || cinfo->Al != 0)
+ WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+ dctbl = compptr->dc_tbl_no;
+ actbl = compptr->ac_tbl_no;
+ /* Compute derived values for Huffman tables */
+ /* We may do this more than once for a table, but it's not expensive */
+ jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
+ & entropy->dc_derived_tbls[dctbl]);
+ jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
+ & entropy->ac_derived_tbls[actbl]);
+ /* Initialize DC predictions to 0 */
+ entropy->saved.last_dc_val[ci] = 0;
+ }
+
+ /* Precalculate decoding info for each block in an MCU of this scan */
+ for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+ /* Precalculate which table to use for each block */
+ entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
+ entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
+ /* Decide whether we really care about the coefficient values */
+ if (compptr->component_needed) {
+ entropy->dc_needed[blkn] = TRUE;
+ /* we don't need the ACs if producing a 1/8th-size image */
+ entropy->ac_needed[blkn] = (compptr->codec_data_unit > 1);
+ } else {
+ entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
+ }
+ }
+
+ /* Initialize bitread state variables */
+ entropy->bitstate.bits_left = 0;
+ entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
+ entropy->insufficient_data = FALSE;
+
+ /* Initialize restart counter */
+ entropy->restarts_to_go = cinfo->restart_interval;
+}
+
+
+/*
+ * Figure F.12: extend sign bit.
+ * On some machines, a shift and add will be faster than a table lookup.
+ */
+
+#ifdef AVOID_TABLES
+
+#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
+
+#else
+
+#define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
+
+static const int extend_test[16] = /* entry n is 2**(n-1) */
+ { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
+ 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
+
+static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
+ { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
+ ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
+ ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
+ ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
+
+#endif /* AVOID_TABLES */
+
+
+/*
+ * Check for a restart marker & resynchronize decoder.
+ * Returns FALSE if must suspend.
+ */
+
+LOCAL(boolean)
+process_restart (j_decompress_ptr cinfo)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyd->entropy_private;
+ int ci;
+
+ /* Throw away any unused bits remaining in bit buffer; */
+ /* include any full bytes in next_marker's count of discarded bytes */
+ cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
+ entropy->bitstate.bits_left = 0;
+
+ /* Advance past the RSTn marker */
+ if (! (*cinfo->marker->read_restart_marker) (cinfo))
+ return FALSE;
+
+ /* Re-initialize DC predictions to 0 */
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++)
+ entropy->saved.last_dc_val[ci] = 0;
+
+ /* Reset restart counter */
+ entropy->restarts_to_go = cinfo->restart_interval;
+
+ /* Reset out-of-data flag, unless read_restart_marker left us smack up
+ * against a marker. In that case we will end up treating the next data
+ * segment as empty, and we can avoid producing bogus output pixels by
+ * leaving the flag set.
+ */
+ if (cinfo->unread_marker == 0)
+ entropy->insufficient_data = FALSE;
+
+ return TRUE;
+}
+
+
+/*
+ * Decode and return one MCU's worth of Huffman-compressed coefficients.
+ * The coefficients are reordered from zigzag order into natural array order,
+ * but are not dequantized.
+ *
+ * The i'th block of the MCU is stored into the block pointed to by
+ * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
+ * (Wholesale zeroing is usually a little faster than retail...)
+ *
+ * Returns FALSE if data source requested suspension. In that case no
+ * changes have been made to permanent state. (Exception: some output
+ * coefficients may already have been assigned. This is harmless for
+ * this module, since we'll just re-assign them on the next call.)
+ */
+
+METHODDEF(boolean)
+decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyd->entropy_private;
+ int blkn;
+ BITREAD_STATE_VARS;
+ savable_state state;
+
+ /* Process restart marker if needed; may have to suspend */
+ if (cinfo->restart_interval) {
+ if (entropy->restarts_to_go == 0)
+ if (! process_restart(cinfo))
+ return FALSE;
+ }
+
+ /* If we've run out of data, just leave the MCU set to zeroes.
+ * This way, we return uniform gray for the remainder of the segment.
+ */
+ if (! entropy->insufficient_data) {
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+ ASSIGN_STATE(state, entropy->saved);
+
+ /* Outer loop handles each block in the MCU */
+
+ for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
+ JBLOCKROW block = MCU_data[blkn];
+ d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
+ d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
+ register int s, k, r;
+
+ /* Decode a single block's worth of coefficients */
+
+ /* Section F.2.2.1: decode the DC coefficient difference */
+ HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
+ if (s) {
+ CHECK_BIT_BUFFER(br_state, s, return FALSE);
+ r = GET_BITS(s);
+ s = HUFF_EXTEND(r, s);
+ }
+
+ if (entropy->dc_needed[blkn]) {
+ /* Convert DC difference to actual value, update last_dc_val */
+ int ci = cinfo->MCU_membership[blkn];
+ s += state.last_dc_val[ci];
+ state.last_dc_val[ci] = s;
+ /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
+ (*block)[0] = (JCOEF) s;
+ }
+
+ if (entropy->ac_needed[blkn]) {
+
+ /* Section F.2.2.2: decode the AC coefficients */
+ /* Since zeroes are skipped, output area must be cleared beforehand */
+ for (k = 1; k < DCTSIZE2; k++) {
+ HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
+
+ r = s >> 4;
+ s &= 15;
+
+ if (s) {
+ k += r;
+ CHECK_BIT_BUFFER(br_state, s, return FALSE);
+ r = GET_BITS(s);
+ s = HUFF_EXTEND(r, s);
+ /* Output coefficient in natural (dezigzagged) order.
+ * Note: the extra entries in jpeg_natural_order[] will save us
+ * if k >= DCTSIZE2, which could happen if the data is corrupted.
+ */
+ (*block)[jpeg_natural_order[k]] = (JCOEF) s;
+ } else {
+ if (r != 15)
+ break;
+ k += 15;
+ }
+ }
+
+ } else {
+
+ /* Section F.2.2.2: decode the AC coefficients */
+ /* In this path we just discard the values */
+ for (k = 1; k < DCTSIZE2; k++) {
+ HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
+
+ r = s >> 4;
+ s &= 15;
+
+ if (s) {
+ k += r;
+ CHECK_BIT_BUFFER(br_state, s, return FALSE);
+ DROP_BITS(s);
+ } else {
+ if (r != 15)
+ break;
+ k += 15;
+ }
+ }
+
+ }
+ }
+
+ /* Completed MCU, so update state */
+ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
+ ASSIGN_STATE(entropy->saved, state);
+ }
+
+ /* Account for restart interval (no-op if not using restarts) */
+ entropy->restarts_to_go--;
+
+ return TRUE;
+}
+
+
+/*
+ * Module initialization routine for Huffman entropy decoding.
+ */
+
+GLOBAL(void)
+jinit_shuff_decoder (j_decompress_ptr cinfo)
+{
+ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ shuff_entropy_ptr entropy;
+ int i;
+
+ entropy = (shuff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(shuff_entropy_decoder));
+ lossyd->entropy_private = (void *) entropy;
+ lossyd->entropy_start_pass = start_pass_huff_decoder;
+ lossyd->entropy_decode_mcu = decode_mcu;
+
+ /* Mark tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+ entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
+ }
+}
diff --git a/jpeg-6c/jdtrans.c b/jpeg-6c/jdtrans.c
new file mode 100644
index 0000000..274e5ce
--- /dev/null
+++ b/jpeg-6c/jdtrans.c
@@ -0,0 +1,139 @@
+/*
+ * jdtrans.c
+ *
+ * Copyright (C) 1995-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains library routines for transcoding decompression,
+ * that is, reading raw DCT coefficient arrays from an input JPEG file.
+ * The routines in jdapimin.c will also be needed by a transcoder.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jlossy.h"
+
+
+/* Forward declarations */
+LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
+
+
+/*
+ * Read the coefficient arrays from a JPEG file.
+ * jpeg_read_header must be completed before calling this.
+ *
+ * The entire image is read into a set of virtual coefficient-block arrays,
+ * one per component. The return value is a pointer to the array of
+ * virtual-array descriptors. These can be manipulated directly via the
+ * JPEG memory manager, or handed off to jpeg_write_coefficients().
+ * To release the memory occupied by the virtual arrays, call
+ * jpeg_finish_decompress() when done with the data.
+ *
+ * An alternative usage is to simply obtain access to the coefficient arrays
+ * during a buffered-image-mode decompression operation. This is allowed
+ * after any jpeg_finish_output() call. The arrays can be accessed until
+ * jpeg_finish_decompress() is called. (Note that any call to the library
+ * may reposition the arrays, so don't rely on access_virt_barray() results
+ * to stay valid across library calls.)
+ *
+ * Returns NULL if suspended. This case need be checked only if
+ * a suspending data source is used.
+ */
+
+GLOBAL(jvirt_barray_ptr *)
+jpeg_read_coefficients (j_decompress_ptr cinfo)
+{
+/* j_lossy_d_ptr decomp;*/
+
+ /* Can't read coefficients from lossless streams */
+ if (cinfo->process == JPROC_LOSSLESS) {
+ ERREXIT(cinfo, JERR_CANT_TRANSCODE);
+ return NULL;
+ }
+
+ if (cinfo->global_state == DSTATE_READY) {
+ /* First call: initialize active modules */
+ transdecode_master_selection(cinfo);
+ cinfo->global_state = DSTATE_RDCOEFS;
+ }
+ if (cinfo->global_state == DSTATE_RDCOEFS) {
+ /* Absorb whole file into the coef buffer */
+ for (;;) {
+ int retcode;
+ /* Call progress monitor hook if present */
+ if (cinfo->progress != NULL)
+ (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+ /* Absorb some more input */
+ retcode = (*cinfo->inputctl->consume_input) (cinfo);
+ if (retcode == JPEG_SUSPENDED)
+ return NULL;
+ if (retcode == JPEG_REACHED_EOI)
+ break;
+ /* Advance progress counter if appropriate */
+ if (cinfo->progress != NULL &&
+ (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
+ if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
+ /* startup underestimated number of scans; ratchet up one scan */
+ cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
+ }
+ }
+ }
+ /* Set state so that jpeg_finish_decompress does the right thing */
+ cinfo->global_state = DSTATE_STOPPING;
+ }
+ /* At this point we should be in state DSTATE_STOPPING if being used
+ * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
+ * to the coefficients during a full buffered-image-mode decompression.
+ */
+ if ((cinfo->global_state == DSTATE_STOPPING ||
+ cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
+ return ((j_lossy_d_ptr) cinfo->codec)->coef_arrays;
+ }
+ /* Oops, improper usage */
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+ return NULL; /* keep compiler happy */
+}
+
+
+/*
+ * Master selection of decompression modules for transcoding.
+ * This substitutes for jdmaster.c's initialization of the full decompressor.
+ */
+
+LOCAL(void)
+transdecode_master_selection (j_decompress_ptr cinfo)
+{
+ /* This is effectively a buffered-image operation. */
+ cinfo->buffered_image = TRUE;
+
+ /* Initialize decompression codec */
+ jinit_d_codec(cinfo);
+
+ /* We can now tell the memory manager to allocate virtual arrays. */
+ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
+
+ /* Initialize input side of decompressor to consume first scan. */
+ (*cinfo->inputctl->start_input_pass) (cinfo);
+
+ /* Initialize progress monitoring. */
+ if (cinfo->progress != NULL) {
+ int nscans;
+ /* Estimate number of scans to set pass_limit. */
+ if (cinfo->process == JPROC_PROGRESSIVE) {
+ /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
+ nscans = 2 + 3 * cinfo->num_components;
+ } else if (cinfo->inputctl->has_multiple_scans) {
+ /* For a nonprogressive multiscan file, estimate 1 scan per component. */
+ nscans = cinfo->num_components;
+ } else {
+ nscans = 1;
+ }
+ cinfo->progress->pass_counter = 0L;
+ cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
+ cinfo->progress->completed_passes = 0;
+ cinfo->progress->total_passes = 1;
+ }
+}
diff --git a/jpeg-6c/jerror.c b/jpeg-6c/jerror.c
new file mode 100644
index 0000000..3da7be8
--- /dev/null
+++ b/jpeg-6c/jerror.c
@@ -0,0 +1,252 @@
+/*
+ * jerror.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains simple error-reporting and trace-message routines.
+ * These are suitable for Unix-like systems and others where writing to
+ * stderr is the right thing to do. Many applications will want to replace
+ * some or all of these routines.
+ *
+ * If you define USE_WINDOWS_MESSAGEBOX in jconfig.h or in the makefile,
+ * you get a Windows-specific hack to display error messages in a dialog box.
+ * It ain't much, but it beats dropping error messages into the bit bucket,
+ * which is what happens to output to stderr under most Windows C compilers.
+ *
+ * These routines are used by both the compression and decompression code.
+ */
+
+/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jversion.h"
+#include "jerror.h"
+
+#ifdef USE_WINDOWS_MESSAGEBOX
+#include <windows.h>
+#endif
+
+#ifndef EXIT_FAILURE /* define exit() codes if not provided */
+#define EXIT_FAILURE 1
+#endif
+
+
+/*
+ * Create the message string table.
+ * We do this from the master message list in jerror.h by re-reading
+ * jerror.h with a suitable definition for macro JMESSAGE.
+ * The message table is made an external symbol just in case any applications
+ * want to refer to it directly.
+ */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_std_message_table jMsgTable
+#endif
+
+#define JMESSAGE(code,string) string ,
+
+const char * const jpeg_std_message_table[] = {
+#include "jerror.h"
+ NULL
+};
+
+
+/*
+ * Error exit handler: must not return to caller.
+ *
+ * Applications may override this if they want to get control back after
+ * an error. Typically one would longjmp somewhere instead of exiting.
+ * The setjmp buffer can be made a private field within an expanded error
+ * handler object. Note that the info needed to generate an error message
+ * is stored in the error object, so you can generate the message now or
+ * later, at your convenience.
+ * You should make sure that the JPEG object is cleaned up (with jpeg_abort
+ * or jpeg_destroy) at some point.
+ */
+
+METHODDEF(void)
+error_exit (j_common_ptr cinfo)
+{
+ /* Always display the message */
+ (*cinfo->err->output_message) (cinfo);
+
+ /* Let the memory manager delete any temp files before we die */
+ jpeg_destroy(cinfo);
+
+ exit(EXIT_FAILURE);
+}
+
+
+/*
+ * Actual output of an error or trace message.
+ * Applications may override this method to send JPEG messages somewhere
+ * other than stderr.
+ *
+ * On Windows, printing to stderr is generally completely useless,
+ * so we provide optional code to produce an error-dialog popup.
+ * Most Windows applications will still prefer to override this routine,
+ * but if they don't, it'll do something at least marginally useful.
+ *
+ * NOTE: to use the library in an environment that doesn't support the
+ * C stdio library, you may have to delete the call to fprintf() entirely,
+ * not just not use this routine.
+ */
+
+METHODDEF(void)
+output_message (j_common_ptr cinfo)
+{
+ char buffer[JMSG_LENGTH_MAX];
+
+ /* Create the message */
+ (*cinfo->err->format_message) (cinfo, buffer);
+
+#ifdef USE_WINDOWS_MESSAGEBOX
+ /* Display it in a message dialog box */
+ MessageBox(GetActiveWindow(), buffer, "JPEG Library Error",
+ MB_OK | MB_ICONERROR);
+#else
+ /* Send it to stderr, adding a newline */
+ fprintf(stderr, "%s\n", buffer);
+#endif
+}
+
+
+/*
+ * Decide whether to emit a trace or warning message.
+ * msg_level is one of:
+ * -1: recoverable corrupt-data warning, may want to abort.
+ * 0: important advisory messages (always display to user).
+ * 1: first level of tracing detail.
+ * 2,3,...: successively more detailed tracing messages.
+ * An application might override this method if it wanted to abort on warnings
+ * or change the policy about which messages to display.
+ */
+
+METHODDEF(void)
+emit_message (j_common_ptr cinfo, int msg_level)
+{
+ struct jpeg_error_mgr * err = cinfo->err;
+
+ if (msg_level < 0) {
+ /* It's a warning message. Since corrupt files may generate many warnings,
+ * the policy implemented here is to show only the first warning,
+ * unless trace_level >= 3.
+ */
+ if (err->num_warnings == 0 || err->trace_level >= 3)
+ (*err->output_message) (cinfo);
+ /* Always count warnings in num_warnings. */
+ err->num_warnings++;
+ } else {
+ /* It's a trace message. Show it if trace_level >= msg_level. */
+ if (err->trace_level >= msg_level)
+ (*err->output_message) (cinfo);
+ }
+}
+
+
+/*
+ * Format a message string for the most recent JPEG error or message.
+ * The message is stored into buffer, which should be at least JMSG_LENGTH_MAX
+ * characters. Note that no '\n' character is added to the string.
+ * Few applications should need to override this method.
+ */
+
+METHODDEF(void)
+format_message (j_common_ptr cinfo, char * buffer)
+{
+ struct jpeg_error_mgr * err = cinfo->err;
+ int msg_code = err->msg_code;
+ const char * msgtext = NULL;
+ const char * msgptr;
+ char ch;
+ boolean isstring;
+
+ /* Look up message string in proper table */
+ if (msg_code > 0 && msg_code <= err->last_jpeg_message) {
+ msgtext = err->jpeg_message_table[msg_code];
+ } else if (err->addon_message_table != NULL &&
+ msg_code >= err->first_addon_message &&
+ msg_code <= err->last_addon_message) {
+ msgtext = err->addon_message_table[msg_code - err->first_addon_message];
+ }
+
+ /* Defend against bogus message number */
+ if (msgtext == NULL) {
+ err->msg_parm.i[0] = msg_code;
+ msgtext = err->jpeg_message_table[0];
+ }
+
+ /* Check for string parameter, as indicated by %s in the message text */
+ isstring = FALSE;
+ msgptr = msgtext;
+ while ((ch = *msgptr++) != '\0') {
+ if (ch == '%') {
+ if (*msgptr == 's') isstring = TRUE;
+ break;
+ }
+ }
+
+ /* Format the message into the passed buffer */
+ if (isstring)
+ sprintf(buffer, msgtext, err->msg_parm.s);
+ else
+ sprintf(buffer, msgtext,
+ err->msg_parm.i[0], err->msg_parm.i[1],
+ err->msg_parm.i[2], err->msg_parm.i[3],
+ err->msg_parm.i[4], err->msg_parm.i[5],
+ err->msg_parm.i[6], err->msg_parm.i[7]);
+}
+
+
+/*
+ * Reset error state variables at start of a new image.
+ * This is called during compression startup to reset trace/error
+ * processing to default state, without losing any application-specific
+ * method pointers. An application might possibly want to override
+ * this method if it has additional error processing state.
+ */
+
+METHODDEF(void)
+reset_error_mgr (j_common_ptr cinfo)
+{
+ cinfo->err->num_warnings = 0;
+ /* trace_level is not reset since it is an application-supplied parameter */
+ cinfo->err->msg_code = 0; /* may be useful as a flag for "no error" */
+}
+
+
+/*
+ * Fill in the standard error-handling methods in a jpeg_error_mgr object.
+ * Typical call is:
+ * struct jpeg_compress_struct cinfo;
+ * struct jpeg_error_mgr err;
+ *
+ * cinfo.err = jpeg_std_error(&err);
+ * after which the application may override some of the methods.
+ */
+
+GLOBAL(struct jpeg_error_mgr *)
+jpeg_std_error (struct jpeg_error_mgr * err)
+{
+ err->error_exit = error_exit;
+ err->emit_message = emit_message;
+ err->output_message = output_message;
+ err->format_message = format_message;
+ err->reset_error_mgr = reset_error_mgr;
+
+ err->trace_level = 0; /* default = no tracing */
+ err->num_warnings = 0; /* no warnings emitted yet */
+ err->msg_code = 0; /* may be useful as a flag for "no error" */
+
+ /* Initialize message table pointers */
+ err->jpeg_message_table = jpeg_std_message_table;
+ err->last_jpeg_message = (int) JMSG_LASTMSGCODE - 1;
+
+ err->addon_message_table = NULL;
+ err->first_addon_message = 0; /* for safety */
+ err->last_addon_message = 0;
+
+ return err;
+}
diff --git a/jpeg-6c/jerror.h b/jpeg-6c/jerror.h
new file mode 100644
index 0000000..1c856ab
--- /dev/null
+++ b/jpeg-6c/jerror.h
@@ -0,0 +1,319 @@
+/*
+ * jerror.h
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file defines the error and message codes for the JPEG library.
+ * Edit this file to add new codes, or to translate the message strings to
+ * some other language.
+ * A set of error-reporting macros are defined too. Some applications using
+ * the JPEG library may wish to include this file to get the error codes
+ * and/or the macros.
+ */
+
+/*
+ * To define the enum list of message codes, include this file without
+ * defining macro JMESSAGE. To create a message string table, include it
+ * again with a suitable JMESSAGE definition (see jerror.c for an example).
+ */
+#ifndef JMESSAGE
+#ifndef JERROR_H
+/* First time through, define the enum list */
+#define JMAKE_ENUM_LIST
+#else
+/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
+#define JMESSAGE(code,string)
+#endif /* JERROR_H */
+#endif /* JMESSAGE */
+
+#ifdef JMAKE_ENUM_LIST
+
+typedef enum {
+
+#define JMESSAGE(code,string) code ,
+
+#endif /* JMAKE_ENUM_LIST */
+
+JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
+
+/* For maintenance convenience, list is alphabetical by message code name */
+JMESSAGE(JERR_ARITH_NOTIMPL,
+ "Sorry, there are legal restrictions on arithmetic coding")
+JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
+JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
+JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
+JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
+JMESSAGE(JERR_BAD_CROP_SPEC, "Invalid crop request")
+JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
+JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
+JMESSAGE(JERR_BAD_DIFF, "spatial difference out of range")
+JMESSAGE(JERR_BAD_DROP_SAMPLING,
+ "Component index %d: mismatching sampling ratio %d:%d, %d:%d, %c")
+JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
+JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
+JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
+JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
+JMESSAGE(JERR_BAD_LIB_VERSION,
+ "Wrong JPEG library version: library is %d, caller expects %d")
+JMESSAGE(JERR_BAD_LOSSLESS,
+ "Invalid lossless parameters Ss=%d Se=%d Ah=%d Al=%d")
+JMESSAGE(JERR_BAD_LOSSLESS_SCRIPT,
+ "Invalid lossless parameters at scan script entry %d")
+JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
+JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
+JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
+JMESSAGE(JERR_BAD_PROGRESSION,
+ "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
+JMESSAGE(JERR_BAD_PROG_SCRIPT,
+ "Invalid progressive parameters at scan script entry %d")
+JMESSAGE(JERR_BAD_RESTART, "Invalid restart interval: %d, must be an integer multiple of the number of MCUs in an MCU_row (%d)")
+JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
+JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
+JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
+JMESSAGE(JERR_BAD_STRUCT_SIZE,
+ "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
+JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
+JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
+JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
+JMESSAGE(JERR_CANT_TRANSCODE,
+ "Cannot transcode to/from lossless JPEG datastreams")
+JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
+JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
+JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
+JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
+JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
+JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
+JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
+JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
+JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
+JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
+JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
+JMESSAGE(JERR_FILE_READ, "Input file read error")
+JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
+JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
+JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
+JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
+JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
+JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
+JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
+JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
+ "Cannot transcode due to multiple use of quantization table %d")
+JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
+JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
+JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
+JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
+JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
+JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
+JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
+JMESSAGE(JERR_NO_LOSSLESS_SCRIPT, "Lossless encoding was requested but no scan script was supplied")
+JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
+JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
+JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
+JMESSAGE(JERR_QUANT_COMPONENTS,
+ "Cannot quantize more than %d color components")
+JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
+JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
+JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
+JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
+JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
+JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
+JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
+JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
+JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
+JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
+JMESSAGE(JERR_TFILE_WRITE,
+ "Write failed on temporary file --- out of disk space?")
+JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
+JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
+JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
+JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
+JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
+JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
+JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
+JMESSAGE(JMSG_VERSION, JVERSION)
+JMESSAGE(JTRC_16BIT_TABLES,
+ "Caution: quantization tables are too coarse for baseline JPEG")
+JMESSAGE(JTRC_ADOBE,
+ "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
+JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
+JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
+JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
+JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
+JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
+JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
+JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
+JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
+JMESSAGE(JTRC_EOI, "End Of Image")
+JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
+JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
+JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
+ "Warning: thumbnail image size does not match data length %u")
+JMESSAGE(JTRC_JFIF_EXTENSION,
+ "JFIF extension marker: type 0x%02x, length %u")
+JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
+JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
+JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
+JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
+JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
+JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
+JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
+JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
+JMESSAGE(JTRC_RST, "RST%d")
+JMESSAGE(JTRC_SMOOTH_NOTIMPL,
+ "Smoothing not supported with nonstandard sampling ratios")
+JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
+JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
+JMESSAGE(JTRC_SOI, "Start of Image")
+JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
+JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
+JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
+JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
+JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
+JMESSAGE(JTRC_THUMB_JPEG,
+ "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
+JMESSAGE(JTRC_THUMB_PALETTE,
+ "JFIF extension marker: palette thumbnail image, length %u")
+JMESSAGE(JTRC_THUMB_RGB,
+ "JFIF extension marker: RGB thumbnail image, length %u")
+JMESSAGE(JTRC_UNKNOWN_LOSSLESS_IDS,
+ "Unrecognized component IDs %d %d %d, assuming RGB")
+JMESSAGE(JTRC_UNKNOWN_LOSSY_IDS,
+ "Unrecognized component IDs %d %d %d, assuming YCbCr")
+JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
+JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
+JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
+JMESSAGE(JWRN_BOGUS_PROGRESSION,
+ "Inconsistent progression sequence for component %d coefficient %d")
+JMESSAGE(JWRN_EXTRANEOUS_DATA,
+ "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
+JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
+JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
+JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
+JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
+JMESSAGE(JWRN_JPEG_PRECISION_CHANGED, "Data Precision changed from %d to %d")
+JMESSAGE(JWRN_MUST_DOWNSCALE,
+ "Must downscale data from %d bits to %d")
+JMESSAGE(JWRN_MUST_RESYNC,
+ "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
+JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
+JMESSAGE(JWRN_SCALED, "Data scaled from %d bits to %d bits")
+JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
+
+#ifdef JMAKE_ENUM_LIST
+
+ JMSG_LASTMSGCODE
+} J_MESSAGE_CODE;
+
+#undef JMAKE_ENUM_LIST
+#endif /* JMAKE_ENUM_LIST */
+
+/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
+#undef JMESSAGE
+
+
+#ifndef JERROR_H
+#define JERROR_H
+
+/* Macros to simplify using the error and trace message stuff */
+/* The first parameter is either type of cinfo pointer */
+
+/* Fatal errors (print message and exit) */
+#define ERREXIT(cinfo,code) \
+ ((cinfo)->err->msg_code = (code), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT1(cinfo,code,p1) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT2(cinfo,code,p1,p2) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT3(cinfo,code,p1,p2,p3) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (cinfo)->err->msg_parm.i[2] = (p3), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (cinfo)->err->msg_parm.i[2] = (p3), \
+ (cinfo)->err->msg_parm.i[3] = (p4), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT6(cinfo,code,p1,p2,p3,p4,p5,p6) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (cinfo)->err->msg_parm.i[2] = (p3), \
+ (cinfo)->err->msg_parm.i[3] = (p4), \
+ (cinfo)->err->msg_parm.i[4] = (p5), \
+ (cinfo)->err->msg_parm.i[5] = (p6), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXITS(cinfo,code,str) \
+ ((cinfo)->err->msg_code = (code), \
+ strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
+ (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+
+#define MAKESTMT(stuff) do { stuff } while (0)
+
+/* Nonfatal errors (we can keep going, but the data is probably corrupt) */
+#define WARNMS(cinfo,code) \
+ ((cinfo)->err->msg_code = (code), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+#define WARNMS1(cinfo,code,p1) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+#define WARNMS2(cinfo,code,p1,p2) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+
+/* Informational/debugging messages */
+#define TRACEMS(cinfo,lvl,code) \
+ ((cinfo)->err->msg_code = (code), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS1(cinfo,lvl,code,p1) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS2(cinfo,lvl,code,p1,p2) \
+ ((cinfo)->err->msg_code = (code), \
+ (cinfo)->err->msg_parm.i[0] = (p1), \
+ (cinfo)->err->msg_parm.i[1] = (p2), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
+ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
+ (cinfo)->err->msg_code = (code); \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
+ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
+ (cinfo)->err->msg_code = (code); \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
+ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
+ _mp[4] = (p5); \
+ (cinfo)->err->msg_code = (code); \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
+ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
+ _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
+ (cinfo)->err->msg_code = (code); \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMSS(cinfo,lvl,code,str) \
+ ((cinfo)->err->msg_code = (code), \
+ strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
+ (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+
+#endif /* JERROR_H */
diff --git a/jpeg-6c/jfdctflt.c b/jpeg-6c/jfdctflt.c
new file mode 100644
index 0000000..79d7a00
--- /dev/null
+++ b/jpeg-6c/jfdctflt.c
@@ -0,0 +1,168 @@
+/*
+ * jfdctflt.c
+ *
+ * Copyright (C) 1994-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a floating-point implementation of the
+ * forward DCT (Discrete Cosine Transform).
+ *
+ * This implementation should be more accurate than either of the integer
+ * DCT implementations. However, it may not give the same results on all
+ * machines because of differences in roundoff behavior. Speed will depend
+ * on the hardware's floating point capacity.
+ *
+ * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
+ * on each column. Direct algorithms are also available, but they are
+ * much more complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on Arai, Agui, and Nakajima's algorithm for
+ * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
+ * Japanese, but the algorithm is described in the Pennebaker & Mitchell
+ * JPEG textbook (see REFERENCES section in file README). The following code
+ * is based directly on figure 4-8 in P&M.
+ * While an 8-point DCT cannot be done in less than 11 multiplies, it is
+ * possible to arrange the computation so that many of the multiplies are
+ * simple scalings of the final outputs. These multiplies can then be
+ * folded into the multiplications or divisions by the JPEG quantization
+ * table entries. The AA&N method leaves only 5 multiplies and 29 adds
+ * to be done in the DCT itself.
+ * The primary disadvantage of this method is that with a fixed-point
+ * implementation, accuracy is lost due to imprecise representation of the
+ * scaled quantization values. However, that problem does not arise if
+ * we use floating point arithmetic.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_FLOAT_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/*
+ * Perform the forward DCT on one block of samples.
+ */
+
+GLOBAL(void)
+jpeg_fdct_float (FAST_FLOAT * data)
+{
+ FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+ FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
+ FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
+ FAST_FLOAT *dataptr;
+ int ctr;
+
+ /* Pass 1: process rows. */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[0] + dataptr[7];
+ tmp7 = dataptr[0] - dataptr[7];
+ tmp1 = dataptr[1] + dataptr[6];
+ tmp6 = dataptr[1] - dataptr[6];
+ tmp2 = dataptr[2] + dataptr[5];
+ tmp5 = dataptr[2] - dataptr[5];
+ tmp3 = dataptr[3] + dataptr[4];
+ tmp4 = dataptr[3] - dataptr[4];
+
+ /* Even part */
+
+ tmp10 = tmp0 + tmp3; /* phase 2 */
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[0] = tmp10 + tmp11; /* phase 3 */
+ dataptr[4] = tmp10 - tmp11;
+
+ z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
+ dataptr[2] = tmp13 + z1; /* phase 5 */
+ dataptr[6] = tmp13 - z1;
+
+ /* Odd part */
+
+ tmp10 = tmp4 + tmp5; /* phase 2 */
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ /* The rotator is modified from fig 4-8 to avoid extra negations. */
+ z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
+ z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
+ z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
+ z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
+
+ z11 = tmp7 + z3; /* phase 5 */
+ z13 = tmp7 - z3;
+
+ dataptr[5] = z13 + z2; /* phase 6 */
+ dataptr[3] = z13 - z2;
+ dataptr[1] = z11 + z4;
+ dataptr[7] = z11 - z4;
+
+ dataptr += DCTSIZE; /* advance pointer to next row */
+ }
+
+ /* Pass 2: process columns. */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
+ tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
+ tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
+ tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
+ tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
+ tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
+ tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
+ tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
+
+ /* Even part */
+
+ tmp10 = tmp0 + tmp3; /* phase 2 */
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
+ dataptr[DCTSIZE*4] = tmp10 - tmp11;
+
+ z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
+ dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
+ dataptr[DCTSIZE*6] = tmp13 - z1;
+
+ /* Odd part */
+
+ tmp10 = tmp4 + tmp5; /* phase 2 */
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ /* The rotator is modified from fig 4-8 to avoid extra negations. */
+ z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
+ z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
+ z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
+ z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
+
+ z11 = tmp7 + z3; /* phase 5 */
+ z13 = tmp7 - z3;
+
+ dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
+ dataptr[DCTSIZE*3] = z13 - z2;
+ dataptr[DCTSIZE*1] = z11 + z4;
+ dataptr[DCTSIZE*7] = z11 - z4;
+
+ dataptr++; /* advance pointer to next column */
+ }
+}
+
+#endif /* DCT_FLOAT_SUPPORTED */
diff --git a/jpeg-6c/jfdctfst.c b/jpeg-6c/jfdctfst.c
new file mode 100644
index 0000000..6b1d9c8
--- /dev/null
+++ b/jpeg-6c/jfdctfst.c
@@ -0,0 +1,225 @@
+/*
+ * jfdctfst.c
+ *
+ * Copyright (C) 1994-1996, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a fast, not so accurate integer implementation of the
+ * forward DCT (Discrete Cosine Transform).
+ *
+ * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
+ * on each column. Direct algorithms are also available, but they are
+ * much more complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on Arai, Agui, and Nakajima's algorithm for
+ * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
+ * Japanese, but the algorithm is described in the Pennebaker & Mitchell
+ * JPEG textbook (see REFERENCES section in file README). The following code
+ * is based directly on figure 4-8 in P&M.
+ * While an 8-point DCT cannot be done in less than 11 multiplies, it is
+ * possible to arrange the computation so that many of the multiplies are
+ * simple scalings of the final outputs. These multiplies can then be
+ * folded into the multiplications or divisions by the JPEG quantization
+ * table entries. The AA&N method leaves only 5 multiplies and 29 adds
+ * to be done in the DCT itself.
+ * The primary disadvantage of this method is that with fixed-point math,
+ * accuracy is lost due to imprecise representation of the scaled
+ * quantization values. The smaller the quantization table entry, the less
+ * precise the scaled value, so this implementation does worse with high-
+ * quality-setting files than with low-quality ones.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_IFAST_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/* Scaling decisions are generally the same as in the LL&M algorithm;
+ * see jfdctint.c for more details. However, we choose to descale
+ * (right shift) multiplication products as soon as they are formed,
+ * rather than carrying additional fractional bits into subsequent additions.
+ * This compromises accuracy slightly, but it lets us save a few shifts.
+ * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
+ * everywhere except in the multiplications proper; this saves a good deal
+ * of work on 16-bit-int machines.
+ *
+ * Again to save a few shifts, the intermediate results between pass 1 and
+ * pass 2 are not upscaled, but are represented only to integral precision.
+ *
+ * A final compromise is to represent the multiplicative constants to only
+ * 8 fractional bits, rather than 13. This saves some shifting work on some
+ * machines, and may also reduce the cost of multiplication (since there
+ * are fewer one-bits in the constants).
+ */
+
+#define CONST_BITS 8
+
+
+/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
+ * causing a lot of useless floating-point operations at run time.
+ * To get around this we use the following pre-calculated constants.
+ * If you change CONST_BITS you may want to add appropriate values.
+ * (With a reasonable C compiler, you can just rely on the FIX() macro...)
+ */
+
+#if CONST_BITS == 8
+#define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
+#define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
+#define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
+#define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
+#else
+#define FIX_0_382683433 FIX(0.382683433)
+#define FIX_0_541196100 FIX(0.541196100)
+#define FIX_0_707106781 FIX(0.707106781)
+#define FIX_1_306562965 FIX(1.306562965)
+#endif
+
+
+/* We can gain a little more speed, with a further compromise in accuracy,
+ * by omitting the addition in a descaling shift. This yields an incorrectly
+ * rounded result half the time...
+ */
+
+#ifndef USE_ACCURATE_ROUNDING
+#undef DESCALE
+#define DESCALE(x,n) RIGHT_SHIFT(x, n)
+#endif
+
+
+/* Multiply a DCTELEM variable by an INT32 constant, and immediately
+ * descale to yield a DCTELEM result.
+ */
+
+#define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
+
+
+/*
+ * Perform the forward DCT on one block of samples.
+ */
+
+GLOBAL(void)
+jpeg_fdct_ifast (DCTELEM * data,boolean jpeg8)
+{
+ DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+ DCTELEM tmp10, tmp11, tmp12, tmp13;
+ DCTELEM z1, z2, z3, z4, z5, z11, z13;
+ DCTELEM *dataptr;
+ int ctr;
+ SHIFT_TEMPS
+
+ /* Pass 1: process rows. */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[0] + dataptr[7];
+ tmp7 = dataptr[0] - dataptr[7];
+ tmp1 = dataptr[1] + dataptr[6];
+ tmp6 = dataptr[1] - dataptr[6];
+ tmp2 = dataptr[2] + dataptr[5];
+ tmp5 = dataptr[2] - dataptr[5];
+ tmp3 = dataptr[3] + dataptr[4];
+ tmp4 = dataptr[3] - dataptr[4];
+
+ /* Even part */
+
+ tmp10 = tmp0 + tmp3; /* phase 2 */
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[0] = tmp10 + tmp11; /* phase 3 */
+ dataptr[4] = tmp10 - tmp11;
+
+ z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
+ dataptr[2] = tmp13 + z1; /* phase 5 */
+ dataptr[6] = tmp13 - z1;
+
+ /* Odd part */
+
+ tmp10 = tmp4 + tmp5; /* phase 2 */
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ /* The rotator is modified from fig 4-8 to avoid extra negations. */
+ z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
+ z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
+ z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
+ z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
+
+ z11 = tmp7 + z3; /* phase 5 */
+ z13 = tmp7 - z3;
+
+ dataptr[5] = z13 + z2; /* phase 6 */
+ dataptr[3] = z13 - z2;
+ dataptr[1] = z11 + z4;
+ dataptr[7] = z11 - z4;
+
+ dataptr += DCTSIZE; /* advance pointer to next row */
+ }
+
+ /* Pass 2: process columns. */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
+ tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
+ tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
+ tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
+ tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
+ tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
+ tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
+ tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
+
+ /* Even part */
+
+ tmp10 = tmp0 + tmp3; /* phase 2 */
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
+ dataptr[DCTSIZE*4] = tmp10 - tmp11;
+
+ z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
+ dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
+ dataptr[DCTSIZE*6] = tmp13 - z1;
+
+ /* Odd part */
+
+ tmp10 = tmp4 + tmp5; /* phase 2 */
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ /* The rotator is modified from fig 4-8 to avoid extra negations. */
+ z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
+ z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
+ z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
+ z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
+
+ z11 = tmp7 + z3; /* phase 5 */
+ z13 = tmp7 - z3;
+
+ dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
+ dataptr[DCTSIZE*3] = z13 - z2;
+ dataptr[DCTSIZE*1] = z11 + z4;
+ dataptr[DCTSIZE*7] = z11 - z4;
+
+ dataptr++; /* advance pointer to next column */
+ }
+}
+
+#endif /* DCT_IFAST_SUPPORTED */
diff --git a/jpeg-6c/jfdctint.c b/jpeg-6c/jfdctint.c
new file mode 100644
index 0000000..64fc3db
--- /dev/null
+++ b/jpeg-6c/jfdctint.c
@@ -0,0 +1,329 @@
+/*
+ * jfdctint.c
+ *
+ * Copyright (C) 1991-1996, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a slow-but-accurate integer implementation of the
+ * forward DCT (Discrete Cosine Transform).
+ *
+ * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
+ * on each column. Direct algorithms are also available, but they are
+ * much more complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on an algorithm described in
+ * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
+ * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
+ * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
+ * The primary algorithm described there uses 11 multiplies and 29 adds.
+ * We use their alternate method with 12 multiplies and 32 adds.
+ * 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.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_ISLOW_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/*
+ * The poop on this scaling stuff is as follows:
+ *
+ * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
+ * larger than the true DCT outputs. The final outputs are therefore
+ * a factor of N larger than desired; since N=8 this can be cured by
+ * a simple right shift at the end of the algorithm. The advantage of
+ * this arrangement is that we save two multiplications per 1-D DCT,
+ * because the y0 and y4 outputs need not be divided by sqrt(N).
+ * In the IJG code, this factor of 8 is removed by the quantization step
+ * (in jcdctmgr.c), NOT in this module.
+ *
+ * We have to do addition and subtraction of the integer inputs, which
+ * is no problem, and multiplication by fractional constants, which is
+ * a problem to do in integer arithmetic. We multiply all the constants
+ * by CONST_SCALE and convert them to integer constants (thus retaining
+ * CONST_BITS bits of precision in the constants). After doing a
+ * multiplication we have to divide the product by CONST_SCALE, with proper
+ * rounding, to produce the correct output. This division can be done
+ * cheaply as a right shift of CONST_BITS bits. We postpone shifting
+ * as long as possible so that partial sums can be added together with
+ * full fractional precision.
+ *
+ * The outputs of the first pass are scaled up by PASS1_BITS bits so that
+ * they are represented to better-than-integral precision. These outputs
+ * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
+ * with the recommended scaling. (For 12-bit sample data, the intermediate
+ * array is INT32 anyway.)
+ *
+ * To avoid overflow of the 32-bit intermediate results in pass 2, we must
+ * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
+ * shows that the values given below are the most effective.
+ */
+
+/*#if BITS_IN_JSAMPLE == 8*/
+#define CONST_BITS 13
+/*#define PASS1_BITS 2
+#else
+#define CONST_BITS 13
+#define PASS1_BITS 1*/ /* lose a little precision to avoid overflow */
+/*#endif*/
+
+/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
+ * causing a lot of useless floating-point operations at run time.
+ * To get around this we use the following pre-calculated constants.
+ * If you change CONST_BITS you may want to add appropriate values.
+ * (With a reasonable C compiler, you can just rely on the FIX() macro...)
+ */
+
+#if CONST_BITS == 13
+#define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
+#define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
+#define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
+#define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
+#define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
+#define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
+#define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
+#define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
+#define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
+#define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
+#define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
+#define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
+#else
+#define FIX_0_298631336 FIX(0.298631336)
+#define FIX_0_390180644 FIX(0.390180644)
+#define FIX_0_541196100 FIX(0.541196100)
+#define FIX_0_765366865 FIX(0.765366865)
+#define FIX_0_899976223 FIX(0.899976223)
+#define FIX_1_175875602 FIX(1.175875602)
+#define FIX_1_501321110 FIX(1.501321110)
+#define FIX_1_847759065 FIX(1.847759065)
+#define FIX_1_961570560 FIX(1.961570560)
+#define FIX_2_053119869 FIX(2.053119869)
+#define FIX_2_562915447 FIX(2.562915447)
+#define FIX_3_072711026 FIX(3.072711026)
+#endif
+
+
+/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
+ * For 8-bit samples with the recommended scaling, all the variable
+ * and constant values involved are no more than 16 bits wide, so a
+ * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
+ * For 12-bit samples, a full 32-bit multiplication will be needed.
+ */
+
+/*#if BITS_IN_JSAMPLE == 8
+#define MULTIPLY(var,const) MULTIPLY16C16(var,const)
+#else
+#define MULTIPLY(var,const) ((var) * (const))
+#endif*/
+
+
+/*
+ * Perform the forward DCT on one block of samples.
+ */
+
+GLOBAL(void)
+jpeg_fdct_islow (DCTELEM * data, boolean jpeg8)
+{
+ INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+ INT32 tmp10, tmp11, tmp12, tmp13;
+ INT32 z1, z2, z3, z4, z5;
+ DCTELEM *dataptr;
+ int ctr, pass1_bits;
+
+ /* set pass1_bits */
+ if (jpeg8) pass1_bits = 2;
+ else pass1_bits = 1;
+
+ SHIFT_TEMPS
+
+ /* Pass 1: process rows. */
+ /* Note results are scaled up by sqrt(8) compared to a true DCT; */
+ /* furthermore, we scale the results by 2**PASS1_BITS. */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[0] + dataptr[7];
+ tmp7 = dataptr[0] - dataptr[7];
+ tmp1 = dataptr[1] + dataptr[6];
+ tmp6 = dataptr[1] - dataptr[6];
+ tmp2 = dataptr[2] + dataptr[5];
+ tmp5 = dataptr[2] - dataptr[5];
+ tmp3 = dataptr[3] + dataptr[4];
+ tmp4 = dataptr[3] - dataptr[4];
+
+ /* Even part per LL&M figure 1 --- note that published figure is faulty;
+ * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
+ */
+
+ tmp10 = tmp0 + tmp3;
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << pass1_bits);
+ dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << pass1_bits);
+
+ if (jpeg8){
+ z1 = MULTIPLY16C16(tmp12 + tmp13, FIX_0_541196100);
+ dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY16C16(tmp13, FIX_0_765366865),
+ CONST_BITS-pass1_bits);
+ dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY16C16(tmp12, - FIX_1_847759065),
+ CONST_BITS-pass1_bits);
+ } else {
+ z1 = (tmp12 + tmp13) * FIX_0_541196100;
+ dataptr[2] = (DCTELEM) DESCALE(z1 + ( tmp13 * FIX_0_765366865),
+ CONST_BITS-pass1_bits);
+ dataptr[6] = (DCTELEM) DESCALE(z1 + ( tmp12 * ( - FIX_1_847759065)),
+ CONST_BITS-pass1_bits); }
+
+ /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
+ * cK represents cos(K*pi/16).
+ * i0..i3 in the paper are tmp4..tmp7 here.
+ */
+
+ z1 = tmp4 + tmp7;
+ z2 = tmp5 + tmp6;
+ z3 = tmp4 + tmp6;
+ z4 = tmp5 + tmp7;
+ if (jpeg8) {
+ z5 = MULTIPLY16C16(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp4 = MULTIPLY16C16(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp5 = MULTIPLY16C16(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp6 = MULTIPLY16C16(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp7 = MULTIPLY16C16(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY16C16(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY16C16(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY16C16(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY16C16(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ } else {
+ z5 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */
+
+ tmp4 = tmp4 * FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp5 = tmp5 * FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp6 = tmp6 * FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp7 = tmp7 * FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = z1 * (- FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = z2 * (- FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = z3 * (- FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = z4 * (- FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ }
+
+ z3 += z5;
+ z4 += z5;
+
+ dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-pass1_bits);
+ dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-pass1_bits);
+ dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-pass1_bits);
+ dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-pass1_bits);
+
+ dataptr += DCTSIZE; /* advance pointer to next row */
+ }
+
+ /* Pass 2: process columns.
+ * We remove the PASS1_BITS scaling, but leave the results scaled up
+ * by an overall factor of 8.
+ */
+
+ dataptr = data;
+ for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
+ tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
+ tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
+ tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
+ tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
+ tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
+ tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
+ tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
+ tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
+
+ /* Even part per LL&M figure 1 --- note that published figure is faulty;
+ * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
+ */
+
+ tmp10 = tmp0 + tmp3;
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, pass1_bits);
+ dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, pass1_bits);
+
+ if (jpeg8) {
+ z1 = MULTIPLY16C16(tmp12 + tmp13, FIX_0_541196100);
+ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY16C16(tmp13, FIX_0_765366865),
+ CONST_BITS+pass1_bits);
+ dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY16C16(tmp12, - FIX_1_847759065),
+ CONST_BITS+pass1_bits);
+ } else {
+ z1 = (tmp12 + tmp13) * FIX_0_541196100;
+ dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + (tmp13 * FIX_0_765366865),
+ CONST_BITS+pass1_bits);
+ dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + (tmp12 * (- FIX_1_847759065)),
+ CONST_BITS+pass1_bits);
+ }
+
+ /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
+ * cK represents cos(K*pi/16).
+ * i0..i3 in the paper are tmp4..tmp7 here.
+ */
+
+ z1 = tmp4 + tmp7;
+ z2 = tmp5 + tmp6;
+ z3 = tmp4 + tmp6;
+ z4 = tmp5 + tmp7;
+ if (jpeg8) {
+ z5 = MULTIPLY16C16(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp4 = MULTIPLY16C16(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp5 = MULTIPLY16C16(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp6 = MULTIPLY16C16(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp7 = MULTIPLY16C16(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY16C16(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY16C16(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY16C16(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY16C16(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ } else {
+ z5 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */
+
+ tmp4 = tmp4 * FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp5 = tmp5 * FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp6 = tmp6 * FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp7 = tmp7 * FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = z1 * ( - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = z2 * ( - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = z3 * ( - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = z4 * ( - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ }
+ z3 += z5;
+ z4 += z5;
+
+ dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
+ CONST_BITS+pass1_bits);
+ dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
+ CONST_BITS+pass1_bits);
+ dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
+ CONST_BITS+pass1_bits);
+ dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
+ CONST_BITS+pass1_bits);
+
+ dataptr++; /* advance pointer to next column */
+ }
+}
+
+#endif /* DCT_ISLOW_SUPPORTED */
diff --git a/jpeg-6c/jidctflt.c b/jpeg-6c/jidctflt.c
new file mode 100644
index 0000000..47a8887
--- /dev/null
+++ b/jpeg-6c/jidctflt.c
@@ -0,0 +1,243 @@
+/*
+ * jidctflt.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a floating-point implementation of the
+ * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine
+ * must also perform dequantization of the input coefficients.
+ *
+ * This implementation should be more accurate than either of the integer
+ * IDCT implementations. However, it may not give the same results on all
+ * machines because of differences in roundoff behavior. Speed will depend
+ * on the hardware's floating point capacity.
+ *
+ * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
+ * on each row (or vice versa, but it's more convenient to emit a row at
+ * a time). Direct algorithms are also available, but they are much more
+ * complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on Arai, Agui, and Nakajima's algorithm for
+ * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
+ * Japanese, but the algorithm is described in the Pennebaker & Mitchell
+ * JPEG textbook (see REFERENCES section in file README). The following code
+ * is based directly on figure 4-8 in P&M.
+ * While an 8-point DCT cannot be done in less than 11 multiplies, it is
+ * possible to arrange the computation so that many of the multiplies are
+ * simple scalings of the final outputs. These multiplies can then be
+ * folded into the multiplications or divisions by the JPEG quantization
+ * table entries. The AA&N method leaves only 5 multiplies and 29 adds
+ * to be done in the DCT itself.
+ * The primary disadvantage of this method is that with a fixed-point
+ * implementation, accuracy is lost due to imprecise representation of the
+ * scaled quantization values. However, that problem does not arise if
+ * we use floating point arithmetic.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_FLOAT_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/* Dequantize a coefficient by multiplying it by the multiplier-table
+ * entry; produce a float result.
+ */
+
+#define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
+
+
+/*
+ * Perform dequantization and inverse DCT on one block of coefficients.
+ */
+
+GLOBAL(void)
+jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY16 output_buf, JDIMENSION output_col)
+{
+ FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+ FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
+ FAST_FLOAT z5, z10, z11, z12, z13;
+ JCOEFPTR inptr;
+ FLOAT_MULT_TYPE * quantptr;
+ FAST_FLOAT * wsptr;
+ JSAMPROW16 outptr;
+ JSAMPLE16 *range_limit = IDCT_range_limit(cinfo);
+ int ctr;
+ FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
+ SHIFT_TEMPS
+
+ /* Pass 1: process columns from input, store into work array. */
+
+ inptr = coef_block;
+ quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
+ wsptr = workspace;
+ for (ctr = DCTSIZE; ctr > 0; ctr--) {
+ /* Due to quantization, we will usually find that many of the input
+ * coefficients are zero, especially the AC terms. We can exploit this
+ * by short-circuiting the IDCT calculation for any column in which all
+ * the AC terms are zero. In that case each output is equal to the
+ * DC coefficient (with scale factor as needed).
+ * With typical images and quantization tables, half or more of the
+ * column DCT calculations can be simplified this way.
+ */
+
+ if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
+ inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
+ inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
+ inptr[DCTSIZE*7] == 0) {
+ /* AC terms all zero */
+ FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+
+ wsptr[DCTSIZE*0] = dcval;
+ wsptr[DCTSIZE*1] = dcval;
+ wsptr[DCTSIZE*2] = dcval;
+ wsptr[DCTSIZE*3] = dcval;
+ wsptr[DCTSIZE*4] = dcval;
+ wsptr[DCTSIZE*5] = dcval;
+ wsptr[DCTSIZE*6] = dcval;
+ wsptr[DCTSIZE*7] = dcval;
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ continue;
+ }
+
+ /* Even part */
+
+ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+ tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
+ tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
+ tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
+
+ tmp10 = tmp0 + tmp2; /* phase 3 */
+ tmp11 = tmp0 - tmp2;
+
+ tmp13 = tmp1 + tmp3; /* phases 5-3 */
+ tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
+
+ tmp0 = tmp10 + tmp13; /* phase 2 */
+ tmp3 = tmp10 - tmp13;
+ tmp1 = tmp11 + tmp12;
+ tmp2 = tmp11 - tmp12;
+
+ /* Odd part */
+
+ tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+ tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
+
+ z13 = tmp6 + tmp5; /* phase 6 */
+ z10 = tmp6 - tmp5;
+ z11 = tmp4 + tmp7;
+ z12 = tmp4 - tmp7;
+
+ tmp7 = z11 + z13; /* phase 5 */
+ tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
+
+ z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
+ tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
+ tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
+
+ tmp6 = tmp12 - tmp7; /* phase 2 */
+ tmp5 = tmp11 - tmp6;
+ tmp4 = tmp10 + tmp5;
+
+ wsptr[DCTSIZE*0] = tmp0 + tmp7;
+ wsptr[DCTSIZE*7] = tmp0 - tmp7;
+ wsptr[DCTSIZE*1] = tmp1 + tmp6;
+ wsptr[DCTSIZE*6] = tmp1 - tmp6;
+ wsptr[DCTSIZE*2] = tmp2 + tmp5;
+ wsptr[DCTSIZE*5] = tmp2 - tmp5;
+ wsptr[DCTSIZE*4] = tmp3 + tmp4;
+ wsptr[DCTSIZE*3] = tmp3 - tmp4;
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ }
+
+ /* Pass 2: process rows from work array, store into output array. */
+ /* Note that we must descale the results by a factor of 8 == 2**3. */
+
+ wsptr = workspace;
+ for (ctr = 0; ctr < DCTSIZE; ctr++) {
+ outptr = output_buf[ctr] + output_col;
+ /* Rows of zeroes can be exploited in the same way as we did with columns.
+ * However, the column calculation has created many nonzero AC terms, so
+ * the simplification applies less often (typically 5% to 10% of the time).
+ * And testing floats for zero is relatively expensive, so we don't bother.
+ */
+
+ /* Even part */
+
+ tmp10 = wsptr[0] + wsptr[4];
+ tmp11 = wsptr[0] - wsptr[4];
+
+ tmp13 = wsptr[2] + wsptr[6];
+ tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
+
+ tmp0 = tmp10 + tmp13;
+ tmp3 = tmp10 - tmp13;
+ tmp1 = tmp11 + tmp12;
+ tmp2 = tmp11 - tmp12;
+
+ /* Odd part */
+
+ z13 = wsptr[5] + wsptr[3];
+ z10 = wsptr[5] - wsptr[3];
+ z11 = wsptr[1] + wsptr[7];
+ z12 = wsptr[1] - wsptr[7];
+
+ tmp7 = z11 + z13;
+ tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
+
+ z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
+ tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
+ tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
+
+ tmp6 = tmp12 - tmp7;
+ tmp5 = tmp11 - tmp6;
+ tmp4 = tmp10 + tmp5;
+
+ /* Final output stage: scale down by a factor of 8 and range-limit */
+
+ outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
+ & RANGE_MASK];
+ outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
+ & RANGE_MASK];
+ outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
+ & RANGE_MASK];
+ outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
+ & RANGE_MASK];
+ outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
+ & RANGE_MASK];
+ outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
+ & RANGE_MASK];
+ outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
+ & RANGE_MASK];
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ }
+}
+
+#endif /* DCT_FLOAT_SUPPORTED */
diff --git a/jpeg-6c/jidctfst.c b/jpeg-6c/jidctfst.c
new file mode 100644
index 0000000..5029b3e
--- /dev/null
+++ b/jpeg-6c/jidctfst.c
@@ -0,0 +1,393 @@
+/*
+ * jidctfst.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a fast, not so accurate integer implementation of the
+ * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine
+ * must also perform dequantization of the input coefficients.
+ *
+ * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
+ * on each row (or vice versa, but it's more convenient to emit a row at
+ * a time). Direct algorithms are also available, but they are much more
+ * complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on Arai, Agui, and Nakajima's algorithm for
+ * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in
+ * Japanese, but the algorithm is described in the Pennebaker & Mitchell
+ * JPEG textbook (see REFERENCES section in file README). The following code
+ * is based directly on figure 4-8 in P&M.
+ * While an 8-point DCT cannot be done in less than 11 multiplies, it is
+ * possible to arrange the computation so that many of the multiplies are
+ * simple scalings of the final outputs. These multiplies can then be
+ * folded into the multiplications or divisions by the JPEG quantization
+ * table entries. The AA&N method leaves only 5 multiplies and 29 adds
+ * to be done in the DCT itself.
+ * The primary disadvantage of this method is that with fixed-point math,
+ * accuracy is lost due to imprecise representation of the scaled
+ * quantization values. The smaller the quantization table entry, the less
+ * precise the scaled value, so this implementation does worse with high-
+ * quality-setting files than with low-quality ones.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_IFAST_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/* Scaling decisions are generally the same as in the LL&M algorithm;
+ * see jidctint.c for more details. However, we choose to descale
+ * (right shift) multiplication products as soon as they are formed,
+ * rather than carrying additional fractional bits into subsequent additions.
+ * This compromises accuracy slightly, but it lets us save a few shifts.
+ * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
+ * everywhere except in the multiplications proper; this saves a good deal
+ * of work on 16-bit-int machines.
+ *
+ * The dequantized coefficients are not integers because the AA&N scaling
+ * factors have been incorporated. We represent them scaled up by PASS1_BITS,
+ * so that the first and second IDCT rounds have the same input scaling.
+ * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
+ * avoid a descaling shift; this compromises accuracy rather drastically
+ * for small quantization table entries, but it saves a lot of shifts.
+ * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
+ * so we use a much larger scaling factor to preserve accuracy.
+ *
+ * A final compromise is to represent the multiplicative constants to only
+ * 8 fractional bits, rather than 13. This saves some shifting work on some
+ * machines, and may also reduce the cost of multiplication (since there
+ * are fewer one-bits in the constants).
+ */
+
+/*#if BITS_IN_JSAMPLE == 8*/
+#define CONST_BITS 8
+/*#define PASS1_BITS 2
+#else
+#define CONST_BITS 8
+#define PASS1_BITS 1*/ /* lose a little precision to avoid overflow */
+/*#endif*/
+
+/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
+ * causing a lot of useless floating-point operations at run time.
+ * To get around this we use the following pre-calculated constants.
+ * If you change CONST_BITS you may want to add appropriate values.
+ * (With a reasonable C compiler, you can just rely on the FIX() macro...)
+ */
+
+#if CONST_BITS == 8
+#define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
+#define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
+#define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
+#define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
+#else
+#define FIX_1_082392200 FIX(1.082392200)
+#define FIX_1_414213562 FIX(1.414213562)
+#define FIX_1_847759065 FIX(1.847759065)
+#define FIX_2_613125930 FIX(2.613125930)
+#endif
+
+
+/* We can gain a little more speed, with a further compromise in accuracy,
+ * by omitting the addition in a descaling shift. This yields an incorrectly
+ * rounded result half the time...
+ */
+
+#ifndef USE_ACCURATE_ROUNDING
+#undef DESCALE
+#define DESCALE(x,n) RIGHT_SHIFT(x, n)
+#endif
+
+
+/* Multiply a DCTELEM variable by an INT32 constant, and immediately
+ * descale to yield a DCTELEM result.
+ */
+
+#define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
+
+
+/* Dequantize a coefficient by multiplying it by the multiplier-table
+ * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
+ * multiplication will do. For 12-bit data, the multiplier table is
+ * declared INT32, so a 32-bit multiply will be used.
+ */
+
+/*#if BITS_IN_JSAMPLE == 8
+#define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
+#else
+#define DEQUANTIZE(coef,quantval) \
+ DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
+#endif*/
+/* IFAST_SCALE_BITS-PASS1_BITS now isbMp1b */
+
+/* Like DESCALE, but applies to a DCTELEM and produces an int.
+ * We assume that int right shift is unsigned if INT32 right shift is.
+ */
+
+#ifdef RIGHT_SHIFT_IS_UNSIGNED
+#define ISHIFT_TEMPS DCTELEM ishift_temp;
+/*#if BITS_IN_JSAMPLE == 8
+#define DCTELEMBITS 16*/ /* DCTELEM may be 16 or 32 bits */
+/*#else*/
+#define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
+/*#endif*/
+#define IRIGHT_SHIFT(x,shft) \
+ ((ishift_temp = (x)) < 0 ? \
+ (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
+ (ishift_temp >> (shft)))
+#else
+#define ISHIFT_TEMPS
+#define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
+#endif
+
+#ifdef USE_ACCURATE_ROUNDING
+#define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
+#else
+#define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
+#endif
+
+
+/*
+ * Perform dequantization and inverse DCT on one block of coefficients.
+ */
+
+GLOBAL(void)
+jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY16 output_buf, JDIMENSION output_col)
+{
+ DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+ DCTELEM tmp10, tmp11, tmp12, tmp13;
+ DCTELEM z5, z10, z11, z12, z13;
+ JCOEFPTR inptr;
+ IFAST_MULT_TYPE * quantptr;
+ int * wsptr;
+ JSAMPROW16 outptr;
+ JSAMPLE16 *range_limit = IDCT_range_limit(cinfo);
+ int ctr, pass1_bits, dcval, isbMp1b;
+ boolean jpeg8;
+ int workspace[DCTSIZE2]; /* buffers data between passes */
+ SHIFT_TEMPS /* for DESCALE */
+ ISHIFT_TEMPS /* for IDESCALE */
+
+ /* set pass1_bits */
+ if (cinfo->data_precision <= 8) {
+ pass1_bits = 2;
+ isbMp1b = 0;/*was IFAST_SCALE_BITS-PASS1_BITS (2-2)*/
+ jpeg8 = TRUE;
+ } else {
+ pass1_bits = 1;
+ isbMp1b = 12;/*was IFAST_SCALE_BITS-PASS1_BITS (13-1)*/
+ jpeg8 = FALSE; }
+
+ /* Pass 1: process columns from input, store into work array. */
+
+ inptr = coef_block;
+ quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
+ wsptr = workspace;
+ for (ctr = DCTSIZE; ctr > 0; ctr--) {
+ /* Due to quantization, we will usually find that many of the input
+ * coefficients are zero, especially the AC terms. We can exploit this
+ * by short-circuiting the IDCT calculation for any column in which all
+ * the AC terms are zero. In that case each output is equal to the
+ * DC coefficient (with scale factor as needed).
+ * With typical images and quantization tables, half or more of the
+ * column DCT calculations can be simplified this way.
+ */
+
+ if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
+ inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
+ inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
+ inptr[DCTSIZE*7] == 0) {
+ /* AC terms all zero */
+ if( jpeg8 ) dcval = (int)((IFAST_MULT_TYPE)inptr[DCTSIZE*0] * quantptr[DCTSIZE*0]);
+ else dcval = (int)DESCALE(inptr[DCTSIZE*0] * quantptr[DCTSIZE*0], isbMp1b);
+
+ wsptr[DCTSIZE*0] = dcval;
+ wsptr[DCTSIZE*1] = dcval;
+ wsptr[DCTSIZE*2] = dcval;
+ wsptr[DCTSIZE*3] = dcval;
+ wsptr[DCTSIZE*4] = dcval;
+ wsptr[DCTSIZE*5] = dcval;
+ wsptr[DCTSIZE*6] = dcval;
+ wsptr[DCTSIZE*7] = dcval;
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ continue;
+ }
+
+ /* Even part */
+
+ if( jpeg8 ) {
+ tmp0 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*0] * quantptr[DCTSIZE*0]);
+ tmp1 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*2] * quantptr[DCTSIZE*2]);
+ tmp2 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*4] * quantptr[DCTSIZE*4]);
+ tmp3 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*6] * quantptr[DCTSIZE*6]);
+ } else {
+ tmp0 = DESCALE(inptr[DCTSIZE*0] * quantptr[DCTSIZE*0], isbMp1b);
+ tmp1 = DESCALE(inptr[DCTSIZE*2] * quantptr[DCTSIZE*2], isbMp1b);
+ tmp2 = DESCALE(inptr[DCTSIZE*4] * quantptr[DCTSIZE*4], isbMp1b);
+ tmp3 = DESCALE(inptr[DCTSIZE*6] * quantptr[DCTSIZE*6], isbMp1b); }
+
+ tmp10 = tmp0 + tmp2; /* phase 3 */
+ tmp11 = tmp0 - tmp2;
+
+ tmp13 = tmp1 + tmp3; /* phases 5-3 */
+ tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
+
+ tmp0 = tmp10 + tmp13; /* phase 2 */
+ tmp3 = tmp10 - tmp13;
+ tmp1 = tmp11 + tmp12;
+ tmp2 = tmp11 - tmp12;
+
+ /* Odd part */
+
+ if( jpeg8 ) {
+ tmp4 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*1] * quantptr[DCTSIZE*1]);
+ tmp5 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*3] * quantptr[DCTSIZE*3]);
+ tmp6 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*5] * quantptr[DCTSIZE*5]);
+ tmp7 = ((IFAST_MULT_TYPE)inptr[DCTSIZE*7] * quantptr[DCTSIZE*7]);
+ } else {
+ tmp4 = DESCALE(inptr[DCTSIZE*1] * quantptr[DCTSIZE*1], isbMp1b);
+ tmp5 = DESCALE(inptr[DCTSIZE*3] * quantptr[DCTSIZE*3], isbMp1b);
+ tmp6 = DESCALE(inptr[DCTSIZE*5] * quantptr[DCTSIZE*5], isbMp1b);
+ tmp7 = DESCALE(inptr[DCTSIZE*7] * quantptr[DCTSIZE*7], isbMp1b); }
+
+ z13 = tmp6 + tmp5; /* phase 6 */
+ z10 = tmp6 - tmp5;
+ z11 = tmp4 + tmp7;
+ z12 = tmp4 - tmp7;
+
+ tmp7 = z11 + z13; /* phase 5 */
+ tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
+
+ z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
+ tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
+ tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
+
+ tmp6 = tmp12 - tmp7; /* phase 2 */
+ tmp5 = tmp11 - tmp6;
+ tmp4 = tmp10 + tmp5;
+
+ wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
+ wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
+ wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
+ wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
+ wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
+ wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
+ wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
+ wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ }
+
+ /* Pass 2: process rows from work array, store into output array. */
+ /* Note that we must descale the results by a factor of 8 == 2**3, */
+ /* and also undo the PASS1_BITS scaling. */
+
+ wsptr = workspace;
+ for (ctr = 0; ctr < DCTSIZE; ctr++) {
+ outptr = output_buf[ctr] + output_col;
+ /* Rows of zeroes can be exploited in the same way as we did with columns.
+ * However, the column calculation has created many nonzero AC terms, so
+ * the simplification applies less often (typically 5% to 10% of the time).
+ * On machines with very fast multiplication, it's possible that the
+ * test takes more time than it's worth. In that case this section
+ * may be commented out.
+ */
+
+#ifndef NO_ZERO_ROW_TEST
+ if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
+ wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
+ /* AC terms all zero */
+ JSAMPLE16 dcval = range_limit[IDESCALE(wsptr[0], pass1_bits+3)
+ & RANGE_MASK];
+
+ outptr[0] = dcval;
+ outptr[1] = dcval;
+ outptr[2] = dcval;
+ outptr[3] = dcval;
+ outptr[4] = dcval;
+ outptr[5] = dcval;
+ outptr[6] = dcval;
+ outptr[7] = dcval;
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ continue;
+ }
+#endif
+
+ /* Even part */
+
+ tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
+ tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
+
+ tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
+ tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
+ - tmp13;
+
+ tmp0 = tmp10 + tmp13;
+ tmp3 = tmp10 - tmp13;
+ tmp1 = tmp11 + tmp12;
+ tmp2 = tmp11 - tmp12;
+
+ /* Odd part */
+
+ z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
+ z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
+ z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
+ z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
+
+ tmp7 = z11 + z13; /* phase 5 */
+ tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
+
+ z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
+ tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
+ tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
+
+ tmp6 = tmp12 - tmp7; /* phase 2 */
+ tmp5 = tmp11 - tmp6;
+ tmp4 = tmp10 + tmp5;
+
+ /* Final output stage: scale down by a factor of 8 and range-limit */
+
+ outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, pass1_bits+3)
+ & RANGE_MASK];
+ outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, pass1_bits+3)
+ & RANGE_MASK];
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ }
+}
+
+#endif /* DCT_IFAST_SUPPORTED */
diff --git a/jpeg-6c/jidctint.c b/jpeg-6c/jidctint.c
new file mode 100644
index 0000000..e3621da
--- /dev/null
+++ b/jpeg-6c/jidctint.c
@@ -0,0 +1,437 @@
+/*
+ * jidctint.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a slow-but-accurate integer implementation of the
+ * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine
+ * must also perform dequantization of the input coefficients.
+ *
+ * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
+ * on each row (or vice versa, but it's more convenient to emit a row at
+ * a time). Direct algorithms are also available, but they are much more
+ * complex and seem not to be any faster when reduced to code.
+ *
+ * This implementation is based on an algorithm described in
+ * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
+ * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
+ * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
+ * The primary algorithm described there uses 11 multiplies and 29 adds.
+ * We use their alternate method with 12 multiplies and 32 adds.
+ * 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.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef DCT_ISLOW_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/*
+ * The poop on this scaling stuff is as follows:
+ *
+ * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
+ * larger than the true IDCT outputs. The final outputs are therefore
+ * a factor of N larger than desired; since N=8 this can be cured by
+ * a simple right shift at the end of the algorithm. The advantage of
+ * this arrangement is that we save two multiplications per 1-D IDCT,
+ * because the y0 and y4 inputs need not be divided by sqrt(N).
+ *
+ * We have to do addition and subtraction of the integer inputs, which
+ * is no problem, and multiplication by fractional constants, which is
+ * a problem to do in integer arithmetic. We multiply all the constants
+ * by CONST_SCALE and convert them to integer constants (thus retaining
+ * CONST_BITS bits of precision in the constants). After doing a
+ * multiplication we have to divide the product by CONST_SCALE, with proper
+ * rounding, to produce the correct output. This division can be done
+ * cheaply as a right shift of CONST_BITS bits. We postpone shifting
+ * as long as possible so that partial sums can be added together with
+ * full fractional precision.
+ *
+ * The outputs of the first pass are scaled up by PASS1_BITS bits so that
+ * they are represented to better-than-integral precision. These outputs
+ * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
+ * with the recommended scaling. (To scale up 12-bit sample data further, an
+ * intermediate INT32 array would be needed.)
+ *
+ * To avoid overflow of the 32-bit intermediate results in pass 2, we must
+ * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
+ * shows that the values given below are the most effective.
+ */
+
+/*#if BITS_IN_JSAMPLE == 8*/
+#define CONST_BITS 13
+/*#define PASS1_BITS 2
+#else
+#define CONST_BITS 13
+#define PASS1_BITS 1*/ /* lose a little precision to avoid overflow */
+/*#endif*/
+
+/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
+ * causing a lot of useless floating-point operations at run time.
+ * To get around this we use the following pre-calculated constants.
+ * If you change CONST_BITS you may want to add appropriate values.
+ * (With a reasonable C compiler, you can just rely on the FIX() macro...)
+ */
+
+#if CONST_BITS == 13
+#define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
+#define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
+#define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
+#define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
+#define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
+#define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
+#define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
+#define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
+#define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
+#define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
+#define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
+#define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
+#else
+#define FIX_0_298631336 FIX(0.298631336)
+#define FIX_0_390180644 FIX(0.390180644)
+#define FIX_0_541196100 FIX(0.541196100)
+#define FIX_0_765366865 FIX(0.765366865)
+#define FIX_0_899976223 FIX(0.899976223)
+#define FIX_1_175875602 FIX(1.175875602)
+#define FIX_1_501321110 FIX(1.501321110)
+#define FIX_1_847759065 FIX(1.847759065)
+#define FIX_1_961570560 FIX(1.961570560)
+#define FIX_2_053119869 FIX(2.053119869)
+#define FIX_2_562915447 FIX(2.562915447)
+#define FIX_3_072711026 FIX(3.072711026)
+#endif
+
+
+/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
+ * For 8-bit samples with the recommended scaling, all the variable
+ * and constant values involved are no more than 16 bits wide, so a
+ * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
+ * For 12-bit samples, a full 32-bit multiplication will be needed.
+ */
+
+/*#if BITS_IN_JSAMPLE == 8
+#define MULTIPLY(var,const) MULTIPLY16C16(var,const)
+#else
+#define MULTIPLY(var,const) ((var) * (const))
+#endif*/
+
+
+/* Dequantize a coefficient by multiplying it by the multiplier-table
+ * entry; produce an int result. In this module, both inputs and result
+ * are 16 bits or less, so either int or short multiply will work.
+ */
+
+#define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
+
+
+/*
+ * Perform dequantization and inverse DCT on one block of coefficients.
+ */
+
+GLOBAL(void)
+jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY16 output_buf, JDIMENSION output_col)
+{
+ INT32 tmp0, tmp1, tmp2, tmp3;
+ INT32 tmp10, tmp11, tmp12, tmp13;
+ INT32 z1, z2, z3, z4, z5;
+ JCOEFPTR inptr;
+ ISLOW_MULT_TYPE * quantptr;
+ int * wsptr;
+ JSAMPROW16 outptr;
+ JSAMPLE16 *range_limit = IDCT_range_limit(cinfo);
+ int ctr, pass1_bits;
+ int workspace[DCTSIZE2]; /* buffers data between passes */
+ boolean jpeg8;
+ SHIFT_TEMPS
+
+ /* set pass1_bits */
+ if (cinfo->data_precision <= 8) {
+ pass1_bits = 2;
+ jpeg8 = TRUE;
+ } else {
+ pass1_bits = 1;
+ jpeg8 = FALSE; }
+
+ /* Pass 1: process columns from input, store into work array. */
+ /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
+ /* furthermore, we scale the results by 2**PASS1_BITS. */
+
+ inptr = coef_block;
+ quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
+ wsptr = workspace;
+ for (ctr = DCTSIZE; ctr > 0; ctr--) {
+ /* Due to quantization, we will usually find that many of the input
+ * coefficients are zero, especially the AC terms. We can exploit this
+ * by short-circuiting the IDCT calculation for any column in which all
+ * the AC terms are zero. In that case each output is equal to the
+ * DC coefficient (with scale factor as needed).
+ * With typical images and quantization tables, half or more of the
+ * column DCT calculations can be simplified this way.
+ */
+
+ if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
+ inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
+ inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
+ inptr[DCTSIZE*7] == 0) {
+ /* AC terms all zero */
+ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << pass1_bits;
+
+ wsptr[DCTSIZE*0] = dcval;
+ wsptr[DCTSIZE*1] = dcval;
+ wsptr[DCTSIZE*2] = dcval;
+ wsptr[DCTSIZE*3] = dcval;
+ wsptr[DCTSIZE*4] = dcval;
+ wsptr[DCTSIZE*5] = dcval;
+ wsptr[DCTSIZE*6] = dcval;
+ wsptr[DCTSIZE*7] = dcval;
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ continue;
+ }
+
+ /* Even part: reverse the even part of the forward DCT. */
+ /* The rotator is sqrt(2)*c(-6). */
+
+ z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
+ z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
+
+ if( jpeg8 ) {
+ z1 = MULTIPLY16C16(z2 + z3, FIX_0_541196100);
+ tmp2 = z1 + MULTIPLY16C16(z3, - FIX_1_847759065);
+ tmp3 = z1 + MULTIPLY16C16(z2, FIX_0_765366865);
+ } else {
+ z1 = (z2 + z3) * FIX_0_541196100;
+ tmp2 = z1 + (z3 * (- FIX_1_847759065));
+ tmp3 = z1 + (z2 * FIX_0_765366865);
+ }
+
+ z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+ z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
+
+ tmp0 = (z2 + z3) << CONST_BITS;
+ tmp1 = (z2 - z3) << CONST_BITS;
+
+ tmp10 = tmp0 + tmp3;
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ /* Odd part per figure 8; the matrix is unitary and hence its
+ * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
+ */
+
+ tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
+ tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+
+ z1 = tmp0 + tmp3;
+ z2 = tmp1 + tmp2;
+ z3 = tmp0 + tmp2;
+ z4 = tmp1 + tmp3;
+ if( jpeg8 ) {
+ z5 = MULTIPLY16C16(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp0 = MULTIPLY16C16(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = MULTIPLY16C16(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = MULTIPLY16C16(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = MULTIPLY16C16(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY16C16(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY16C16(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY16C16(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY16C16(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ } else {
+ z5 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */
+
+ tmp0 = tmp0 * FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = tmp1 * FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = tmp2 * FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = tmp3 * FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = z1 * ( - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = z2 * ( - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = z3 * ( - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = z4 * ( - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ }
+
+ z3 += z5;
+ z4 += z5;
+
+ tmp0 += z1 + z3;
+ tmp1 += z2 + z4;
+ tmp2 += z2 + z3;
+ tmp3 += z1 + z4;
+
+ /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
+
+ wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-pass1_bits);
+ wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-pass1_bits);
+
+ inptr++; /* advance pointers to next column */
+ quantptr++;
+ wsptr++;
+ }
+
+ /* Pass 2: process rows from work array, store into output array. */
+ /* Note that we must descale the results by a factor of 8 == 2**3, */
+ /* and also undo the PASS1_BITS scaling. */
+
+ wsptr = workspace;
+ for (ctr = 0; ctr < DCTSIZE; ctr++) {
+ outptr = output_buf[ctr] + output_col;
+ /* Rows of zeroes can be exploited in the same way as we did with columns.
+ * However, the column calculation has created many nonzero AC terms, so
+ * the simplification applies less often (typically 5% to 10% of the time).
+ * On machines with very fast multiplication, it's possible that the
+ * test takes more time than it's worth. In that case this section
+ * may be commented out.
+ */
+
+#ifndef NO_ZERO_ROW_TEST
+ if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
+ wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
+ /* AC terms all zero */
+ JSAMPLE16 dcval = range_limit[(int) DESCALE((INT32) wsptr[0], pass1_bits+3)
+ & RANGE_MASK];
+
+ outptr[0] = dcval;
+ outptr[1] = dcval;
+ outptr[2] = dcval;
+ outptr[3] = dcval;
+ outptr[4] = dcval;
+ outptr[5] = dcval;
+ outptr[6] = dcval;
+ outptr[7] = dcval;
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ continue;
+ }
+#endif
+
+ /* Even part: reverse the even part of the forward DCT. */
+ /* The rotator is sqrt(2)*c(-6). */
+
+ z2 = (INT32) wsptr[2];
+ z3 = (INT32) wsptr[6];
+
+ if( jpeg8 ) {
+ z1 = MULTIPLY16C16(z2 + z3, FIX_0_541196100);
+ tmp2 = z1 + MULTIPLY16C16(z3, - FIX_1_847759065);
+ tmp3 = z1 + MULTIPLY16C16(z2, FIX_0_765366865);
+ } else {
+ z1 = (z2 + z3) * FIX_0_541196100;
+ tmp2 = z1 + (z3 * ( - FIX_1_847759065));
+ tmp3 = z1 + (z2 * FIX_0_765366865);
+ }
+
+ tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
+ tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
+
+ tmp10 = tmp0 + tmp3;
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ /* Odd part per figure 8; the matrix is unitary and hence its
+ * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
+ */
+
+ tmp0 = (INT32) wsptr[7];
+ tmp1 = (INT32) wsptr[5];
+ tmp2 = (INT32) wsptr[3];
+ tmp3 = (INT32) wsptr[1];
+
+ z1 = tmp0 + tmp3;
+ z2 = tmp1 + tmp2;
+ z3 = tmp0 + tmp2;
+ z4 = tmp1 + tmp3;
+ if( jpeg8 ) {
+ z5 = MULTIPLY16C16(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
+
+ tmp0 = MULTIPLY16C16(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = MULTIPLY16C16(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = MULTIPLY16C16(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = MULTIPLY16C16(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = MULTIPLY16C16(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = MULTIPLY16C16(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = MULTIPLY16C16(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = MULTIPLY16C16(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ } else {
+ z5 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */
+
+ tmp0 = tmp0 * FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */
+ tmp1 = tmp1 * FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */
+ tmp2 = tmp2 * FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */
+ tmp3 = tmp3 * FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */
+ z1 = z1 * ( - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
+ z2 = z2 * ( - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
+ z3 = z3 * ( - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
+ z4 = z4 * ( - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
+ }
+
+ z3 += z5;
+ z4 += z5;
+
+ tmp0 += z1 + z3;
+ tmp1 += z2 + z4;
+ tmp2 += z2 + z3;
+ tmp3 += z1 + z4;
+
+ /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
+
+ outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+ outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
+ CONST_BITS+pass1_bits+3)
+ & RANGE_MASK];
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ }
+}
+
+#endif /* DCT_ISLOW_SUPPORTED */
diff --git a/jpeg-6c/jidctred.c b/jpeg-6c/jidctred.c
new file mode 100644
index 0000000..d54daf0
--- /dev/null
+++ b/jpeg-6c/jidctred.c
@@ -0,0 +1,458 @@
+/*
+ * jidctred.c
+ *
+ * Copyright (C) 1994-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains inverse-DCT routines that produce reduced-size output:
+ * either 4x4, 2x2, or 1x1 pixels from an 8x8 DCT block.
+ *
+ * The implementation is based on the Loeffler, Ligtenberg and Moschytz (LL&M)
+ * algorithm used in jidctint.c. We simply replace each 8-to-8 1-D IDCT step
+ * with an 8-to-4 step that produces the four averages of two adjacent outputs
+ * (or an 8-to-2 step producing two averages of four outputs, for 2x2 output).
+ * These steps were derived by computing the corresponding values at the end
+ * of the normal LL&M code, then simplifying as much as possible.
+ *
+ * 1x1 is trivial: just take the DC coefficient divided by 8.
+ *
+ * See jidctint.c for additional comments.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h" /* Private declarations for DCT subsystem */
+
+#ifdef IDCT_SCALING_SUPPORTED
+
+
+/*
+ * This module is specialized to the case DCTSIZE = 8.
+ */
+
+#if DCTSIZE != 8
+ Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
+#endif
+
+
+/* Scaling is the same as in jidctint.c. */
+
+/*#if BITS_IN_JSAMPLE == 8*/
+#define CONST_BITS 13
+/*#define PASS1_BITS 2
+#else
+#define CONST_BITS 13
+#define PASS1_BITS 1*/ /* lose a little precision to avoid overflow */
+/*#endif*/
+
+/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
+ * causing a lot of useless floating-point operations at run time.
+ * To get around this we use the following pre-calculated constants.
+ * If you change CONST_BITS you may want to add appropriate values.
+ * (With a reasonable C compiler, you can just rely on the FIX() macro...)
+ */
+
+#if CONST_BITS == 13
+#define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
+#define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
+#define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
+#define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
+#define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
+#define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
+#define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
+#define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
+#define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
+#define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
+#define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
+#define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
+#define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
+#define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
+#else
+#define FIX_0_211164243 FIX(0.211164243)
+#define FIX_0_509795579 FIX(0.509795579)
+#define FIX_0_601344887 FIX(0.601344887)
+#define FIX_0_720959822 FIX(0.720959822)
+#define FIX_0_765366865 FIX(0.765366865)
+#define FIX_0_850430095 FIX(0.850430095)
+#define FIX_0_899976223 FIX(0.899976223)
+#define FIX_1_061594337 FIX(1.061594337)
+#define FIX_1_272758580 FIX(1.272758580)
+#define FIX_1_451774981 FIX(1.451774981)
+#define FIX_1_847759065 FIX(1.847759065)
+#define FIX_2_172734803 FIX(2.172734803)
+#define FIX_2_562915447 FIX(2.562915447)
+#define FIX_3_624509785 FIX(3.624509785)
+#endif
+
+
+/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
+ * For 8-bit samples with the recommended scaling, all the variable
+ * and constant values involved are no more than 16 bits wide, so a
+ * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
+ * For 12-bit samples, a full 32-bit multiplication will be needed.
+ */
+
+/*#if BITS_IN_JSAMPLE == 8
+#define MULTIPLY(var,const) MULTIPLY16C16(var,const)
+#else
+#define MULTIPLY(var,const) ((var) * (const))
+#endif*/
+
+
+/* Dequantize a coefficient by multiplying it by the multiplier-table
+ * entry; produce an int result. In this module, both inputs and result
+ * are 16 bits or less, so either int or short multiply will work.
+ */
+
+#define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
+
+
+/*
+ * Perform dequantization and inverse DCT on one block of coefficients,
+ * producing a reduced-size 4x4 output block.
+ */
+
+GLOBAL(void)
+jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY16 output_buf, JDIMENSION output_col)
+{
+ INT32 tmp0, tmp2, tmp10, tmp12;
+ INT32 z1, z2, z3, z4;
+ JCOEFPTR inptr;
+ ISLOW_MULT_TYPE * quantptr;
+ int * wsptr;
+ JSAMPROW16 outptr;
+ JSAMPLE16 *range_limit = IDCT_range_limit(cinfo);
+ int ctr, pass1_bits;
+ int workspace[DCTSIZE*4]; /* buffers data between passes */
+ boolean jpeg8;
+ SHIFT_TEMPS
+
+ /* set pass1_bits */
+ if (cinfo->data_precision <= 8) {
+ pass1_bits = 2;
+ jpeg8 = TRUE;
+ } else {
+ pass1_bits = 1;
+ jpeg8 = FALSE; }
+
+ /* Pass 1: process columns from input, store into work array. */
+
+ inptr = coef_block;
+ quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
+ wsptr = workspace;
+ for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
+ /* Don't bother to process column 4, because second pass won't use it */
+ if (ctr == DCTSIZE-4)
+ continue;
+ if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
+ inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
+ inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
+ /* AC terms all zero; we need not examine term 4 for 4x4 output */
+ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << pass1_bits;
+
+ wsptr[DCTSIZE*0] = dcval;
+ wsptr[DCTSIZE*1] = dcval;
+ wsptr[DCTSIZE*2] = dcval;
+ wsptr[DCTSIZE*3] = dcval;
+
+ continue;
+ }
+
+ /* Even part */
+
+ tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+ tmp0 <<= (CONST_BITS+1);
+
+ z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
+ z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
+
+ if (jpeg8) tmp2 = MULTIPLY16C16(z2, FIX_1_847759065) + MULTIPLY16C16(z3, - FIX_0_765366865);
+ else tmp2 = (z2 * FIX_1_847759065) + (z3* ( - FIX_0_765366865));
+
+ tmp10 = tmp0 + tmp2;
+ tmp12 = tmp0 - tmp2;
+
+ /* Odd part */
+
+ z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
+ z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+
+ if (jpeg8) {
+ tmp0 = MULTIPLY16C16(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
+ + MULTIPLY16C16(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
+ + MULTIPLY16C16(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
+ + MULTIPLY16C16(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
+
+ tmp2 = MULTIPLY16C16(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
+ + MULTIPLY16C16(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
+ + MULTIPLY16C16(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
+ + MULTIPLY16C16(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
+ } else {
+ tmp0 = (z1 * ( - FIX_0_211164243)) /* sqrt(2) * (c3-c1) */
+ + (z2 * FIX_1_451774981) /* sqrt(2) * (c3+c7) */
+ + (z3 * ( - FIX_2_172734803)) /* sqrt(2) * (-c1-c5) */
+ + (z4 * FIX_1_061594337); /* sqrt(2) * (c5+c7) */
+
+ tmp2 = (z1 * ( - FIX_0_509795579)) /* sqrt(2) * (c7-c5) */
+ + (z2 * ( - FIX_0_601344887)) /* sqrt(2) * (c5-c1) */
+ + (z3 * FIX_0_899976223) /* sqrt(2) * (c3-c7) */
+ + (z4 * FIX_2_562915447); /* sqrt(2) * (c1+c3) */
+ }
+
+ /* Final output stage */
+
+ wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-pass1_bits+1);
+ wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-pass1_bits+1);
+ wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-pass1_bits+1);
+ wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-pass1_bits+1);
+ }
+
+ /* Pass 2: process 4 rows from work array, store into output array. */
+
+ wsptr = workspace;
+ for (ctr = 0; ctr < 4; ctr++) {
+ outptr = output_buf[ctr] + output_col;
+ /* It's not clear whether a zero row test is worthwhile here ... */
+
+#ifndef NO_ZERO_ROW_TEST
+ if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
+ wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
+ /* AC terms all zero */
+ JSAMPLE16 dcval = range_limit[(int) DESCALE((INT32) wsptr[0], pass1_bits+3)
+ & RANGE_MASK];
+
+ outptr[0] = dcval;
+ outptr[1] = dcval;
+ outptr[2] = dcval;
+ outptr[3] = dcval;
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ continue;
+ }
+#endif
+
+ /* Even part */
+
+ tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
+
+ if (jpeg8) tmp2 = MULTIPLY16C16((INT32) wsptr[2], FIX_1_847759065)
+ + MULTIPLY16C16((INT32) wsptr[6], - FIX_0_765366865);
+ else tmp2 = ((INT32) wsptr[2] * FIX_1_847759065)
+ + ((INT32) wsptr[6] * ( - FIX_0_765366865));
+
+ tmp10 = tmp0 + tmp2;
+ tmp12 = tmp0 - tmp2;
+
+ /* Odd part */
+
+ z1 = (INT32) wsptr[7];
+ z2 = (INT32) wsptr[5];
+ z3 = (INT32) wsptr[3];
+ z4 = (INT32) wsptr[1];
+
+ if (jpeg8) {
+ tmp0 = MULTIPLY16C16(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
+ + MULTIPLY16C16(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
+ + MULTIPLY16C16(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
+ + MULTIPLY16C16(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
+
+ tmp2 = MULTIPLY16C16(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
+ + MULTIPLY16C16(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
+ + MULTIPLY16C16(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
+ + MULTIPLY16C16(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
+ } else {
+ tmp0 = (z1 * ( - FIX_0_211164243)) /* sqrt(2) * (c3-c1) */
+ + (z2 * FIX_1_451774981) /* sqrt(2) * (c3+c7) */
+ + (z3 * ( - FIX_2_172734803)) /* sqrt(2) * (-c1-c5) */
+ + (z4 * FIX_1_061594337); /* sqrt(2) * (c5+c7) */
+
+ tmp2 = (z1 * ( - FIX_0_509795579)) /* sqrt(2) * (c7-c5) */
+ + (z2 * ( - FIX_0_601344887)) /* sqrt(2) * (c5-c1) */
+ + (z3 * FIX_0_899976223) /* sqrt(2) * (c3-c7) */
+ + (z4 * FIX_2_562915447); /* sqrt(2) * (c1+c3) */
+ }
+
+ /* Final output stage */
+
+ outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
+ CONST_BITS+pass1_bits+3+1)
+ & RANGE_MASK];
+ outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
+ CONST_BITS+pass1_bits+3+1)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
+ CONST_BITS+pass1_bits+3+1)
+ & RANGE_MASK];
+ outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
+ CONST_BITS+pass1_bits+3+1)
+ & RANGE_MASK];
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ }
+}
+
+
+/*
+ * Perform dequantization and inverse DCT on one block of coefficients,
+ * producing a reduced-size 2x2 output block.
+ */
+
+GLOBAL(void)
+jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY16 output_buf, JDIMENSION output_col)
+{
+ INT32 tmp0, tmp10, z1;
+ JCOEFPTR inptr;
+ ISLOW_MULT_TYPE * quantptr;
+ int * wsptr;
+ JSAMPROW16 outptr;
+ JSAMPLE16 *range_limit = IDCT_range_limit(cinfo);
+ int ctr, pass1_bits;
+ int workspace[DCTSIZE*2]; /* buffers data between passes */
+ boolean jpeg8;
+ SHIFT_TEMPS
+
+ /* set pass1_bits */
+ if (cinfo->data_precision <= 8) {
+ pass1_bits = 2;
+ jpeg8 = TRUE;
+ } else {
+ pass1_bits = 1;
+ jpeg8 = FALSE; }
+
+ /* Pass 1: process columns from input, store into work array. */
+
+ inptr = coef_block;
+ quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
+ wsptr = workspace;
+ for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
+ /* Don't bother to process columns 2,4,6 */
+ if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
+ continue;
+ if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
+ inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
+ /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
+ int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << pass1_bits;
+
+ wsptr[DCTSIZE*0] = dcval;
+ wsptr[DCTSIZE*1] = dcval;
+
+ continue;
+ }
+
+ /* Even part */
+
+ z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
+ tmp10 = z1 << (CONST_BITS+2);
+
+ /* Odd part */
+
+ z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
+ if (jpeg8) {
+ tmp0 = MULTIPLY16C16(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ tmp0 += MULTIPLY16C16(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ tmp0 += MULTIPLY16C16(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+ tmp0 += MULTIPLY16C16(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
+ } else {
+ tmp0 = z1 * ( - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
+ tmp0 += (z1 * FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
+ tmp0 += (z1 * ( - FIX_1_272758580)); /* sqrt(2) * (-c1+c3-c5-c7) */
+ z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
+ tmp0 += (z1 * FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
+ }
+
+ /* Final output stage */
+
+ wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-pass1_bits+2);
+ wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-pass1_bits+2);
+ }
+
+ /* Pass 2: process 2 rows from work array, store into output array. */
+
+ wsptr = workspace;
+ for (ctr = 0; ctr < 2; ctr++) {
+ outptr = output_buf[ctr] + output_col;
+ /* It's not clear whether a zero row test is worthwhile here ... */
+
+#ifndef NO_ZERO_ROW_TEST
+ if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
+ /* AC terms all zero */
+ JSAMPLE16 dcval = range_limit[(int) DESCALE((INT32) wsptr[0], pass1_bits+3)
+ & RANGE_MASK];
+
+ outptr[0] = dcval;
+ outptr[1] = dcval;
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ continue;
+ }
+#endif
+
+ /* Even part */
+
+ tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
+
+ /* Odd part */
+
+ if (jpeg8) tmp0 = MULTIPLY16C16((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
+ + MULTIPLY16C16((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
+ + MULTIPLY16C16((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
+ + MULTIPLY16C16((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
+ else tmp0 = ((INT32) wsptr[7] * ( - FIX_0_720959822)) /* sqrt(2) * (c7-c5+c3-c1) */
+ + ((INT32) wsptr[5] * FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
+ + ((INT32) wsptr[3] * ( - FIX_1_272758580)) /* sqrt(2) * (-c1+c3-c5-c7) */
+ + ((INT32) wsptr[1] * FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
+
+ /* Final output stage */
+
+ outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
+ CONST_BITS+pass1_bits+3+2)
+ & RANGE_MASK];
+ outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
+ CONST_BITS+pass1_bits+3+2)
+ & RANGE_MASK];
+
+ wsptr += DCTSIZE; /* advance pointer to next row */
+ }
+}
+
+
+/*
+ * Perform dequantization and inverse DCT on one block of coefficients,
+ * producing a reduced-size 1x1 output block.
+ */
+
+GLOBAL(void)
+jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY16 output_buf, JDIMENSION output_col)
+{
+ int dcval;
+ ISLOW_MULT_TYPE * quantptr;
+ JSAMPLE16 *range_limit = IDCT_range_limit(cinfo);
+ SHIFT_TEMPS
+
+ /* We hardly need an inverse DCT routine for this: just take the
+ * average pixel value, which is one-eighth of the DC coefficient.
+ */
+ quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
+ dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
+ dcval = (int) DESCALE((INT32) dcval, 3);
+
+ output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
+}
+
+#endif /* IDCT_SCALING_SUPPORTED */
diff --git a/jpeg-6c/jinclude.h b/jpeg-6c/jinclude.h
new file mode 100644
index 0000000..0a4f151
--- /dev/null
+++ b/jpeg-6c/jinclude.h
@@ -0,0 +1,91 @@
+/*
+ * jinclude.h
+ *
+ * Copyright (C) 1991-1994, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file exists to provide a single place to fix any problems with
+ * including the wrong system include files. (Common problems are taken
+ * care of by the standard jconfig symbols, but on really weird systems
+ * you may have to edit this file.)
+ *
+ * NOTE: this file is NOT intended to be included by applications using the
+ * JPEG library. Most applications need only include jpeglib.h.
+ */
+
+
+/* Include auto-config file to find out which system include files we need. */
+
+#include "jconfig.h" /* auto configuration options */
+#define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
+
+/*
+ * We need the NULL macro and size_t typedef.
+ * On an ANSI-conforming system it is sufficient to include <stddef.h>.
+ * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
+ * pull in <sys/types.h> as well.
+ * Note that the core JPEG library does not require <stdio.h>;
+ * only the default error handler and data source/destination modules do.
+ * But we must pull it in because of the references to FILE in jpeglib.h.
+ * You can remove those references if you want to compile without <stdio.h>.
+ */
+
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif
+
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+
+#ifdef NEED_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+#include <stdio.h>
+
+/*
+ * We need memory copying and zeroing functions, plus strncpy().
+ * ANSI and System V implementations declare these in <string.h>.
+ * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
+ * Some systems may declare memset and memcpy in <memory.h>.
+ *
+ * NOTE: we assume the size parameters to these functions are of type size_t.
+ * Change the casts in these macros if not!
+ */
+
+#ifdef NEED_BSD_STRINGS
+
+#include <strings.h>
+#define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
+#define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
+
+#else /* not BSD, assume ANSI/SysV string lib */
+
+#include <string.h>
+#define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
+#define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
+
+#endif
+
+/*
+ * In ANSI C, and indeed any rational implementation, size_t is also the
+ * type returned by sizeof(). However, it seems there are some irrational
+ * implementations out there, in which sizeof() returns an int even though
+ * size_t is defined as long or unsigned long. To ensure consistent results
+ * we always use this SIZEOF() macro in place of using sizeof() directly.
+ */
+
+#define SIZEOF(object) ((size_t) sizeof(object))
+
+/*
+ * The modules that use fread() and fwrite() always invoke them through
+ * these macros. On some systems you may need to twiddle the argument casts.
+ * CAUTION: argument order is different from underlying functions!
+ */
+
+#define JFREAD(file,buf,sizeofbuf) \
+ ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
+#define JFWRITE(file,buf,sizeofbuf) \
+ ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
diff --git a/jpeg-6c/jlossls.h b/jpeg-6c/jlossls.h
new file mode 100644
index 0000000..d41e0ea
--- /dev/null
+++ b/jpeg-6c/jlossls.h
@@ -0,0 +1,153 @@
+/*
+ * jlossls.h
+ *
+ * Copyright (C) 1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This include file contains common declarations for the lossless JPEG
+ * codec modules.
+ */
+
+#ifndef JLOSSLS_H
+#define JLOSSLS_H
+
+
+/*
+ * Table H.1: Predictors for lossless coding.
+ */
+
+#define PREDICTOR1 Ra
+#define PREDICTOR2 Rb
+#define PREDICTOR3 Rc
+#define PREDICTOR4 (int) ((INT32) Ra + (INT32) Rb - (INT32) Rc)
+#define PREDICTOR5 (int) ((INT32) Ra + RIGHT_SHIFT((INT32) Rb - (INT32) Rc, 1))
+#define PREDICTOR6 (int) ((INT32) Rb + RIGHT_SHIFT((INT32) Ra - (INT32) Rc, 1))
+#define PREDICTOR7 (int) RIGHT_SHIFT((INT32) Ra + (INT32) Rb, 1)
+
+
+typedef JMETHOD(void, predict_difference_method_ptr,
+ (j_compress_ptr cinfo, int ci,
+ JSAMPROW16 input_buf, JSAMPROW16 prev_row,
+ JDIFFROW diff_buf, JDIMENSION width));
+
+typedef JMETHOD(void, scaler_method_ptr,
+ (j_compress_ptr cinfo, int ci,
+ JSAMPROW16 input_buf, JSAMPROW16 output_buf,
+ JDIMENSION width));
+
+/* Lossless-specific compression codec (compressor proper) */
+typedef struct {
+ struct jpeg_c_codec pub; /* public fields */
+
+
+ /* Difference buffer control */
+ JMETHOD(void, diff_start_pass, (j_compress_ptr cinfo,
+ J_BUF_MODE pass_mode));
+
+ /* Pointer to data which is private to diff controller */
+ void *diff_private;
+
+
+ /* Entropy encoding */
+ JMETHOD(JDIMENSION, entropy_encode_mcus, (j_compress_ptr cinfo,
+ JDIFFIMAGE diff_buf,
+ JDIMENSION MCU_row_num,
+ JDIMENSION MCU_col_num,
+ JDIMENSION nMCU));
+
+ /* Pointer to data which is private to entropy module */
+ void *entropy_private;
+
+
+ /* Prediction, differencing */
+ JMETHOD(void, predict_start_pass, (j_compress_ptr cinfo));
+
+ /* It is useful to allow each component to have a separate diff method. */
+ predict_difference_method_ptr predict_difference[MAX_COMPONENTS];
+
+ /* Pointer to data which is private to predictor module */
+ void *pred_private;
+
+ /* Sample scaling */
+ JMETHOD(void, scaler_start_pass, (j_compress_ptr cinfo));
+ JMETHOD(void, scaler_scale, (j_compress_ptr cinfo,
+ JSAMPROW16 input_buf, JSAMPROW16 output_buf,
+ JDIMENSION width));
+
+ /* Pointer to data which is private to scaler module */
+ void *scaler_private;
+
+} jpeg_lossless_c_codec;
+
+typedef jpeg_lossless_c_codec * j_lossless_c_ptr;
+
+
+typedef JMETHOD(void, predict_undifference_method_ptr,
+ (j_decompress_ptr cinfo, int comp_index,
+ JDIFFROW diff_buf, JDIFFROW prev_row,
+ JDIFFROW undiff_buf, JDIMENSION width));
+
+/* Lossless-specific decompression codec (decompressor proper) */
+typedef struct {
+ struct jpeg_d_codec pub; /* public fields */
+
+
+ /* Difference buffer control */
+ JMETHOD(void, diff_start_input_pass, (j_decompress_ptr cinfo));
+
+ /* Pointer to data which is private to diff controller */
+ void *diff_private;
+
+
+ /* Entropy decoding */
+ JMETHOD(void, entropy_start_pass, (j_decompress_ptr cinfo));
+ JMETHOD(boolean, entropy_process_restart, (j_decompress_ptr cinfo));
+ JMETHOD(JDIMENSION, entropy_decode_mcus, (j_decompress_ptr cinfo,
+ JDIFFIMAGE diff_buf,
+ JDIMENSION MCU_row_num,
+ JDIMENSION MCU_col_num,
+ JDIMENSION nMCU));
+
+ /* Pointer to data which is private to entropy module */
+ void *entropy_private;
+
+
+ /* Prediction, undifferencing */
+ JMETHOD(void, predict_start_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, predict_process_restart, (j_decompress_ptr cinfo));
+
+ /* It is useful to allow each component to have a separate undiff method. */
+ predict_undifference_method_ptr predict_undifference[MAX_COMPONENTS];
+
+ /* Pointer to data which is private to predictor module */
+ void *pred_private;
+
+ /* Sample scaling */
+ JMETHOD(void, scaler_start_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, scaler_scale, (j_decompress_ptr cinfo,
+ JDIFFROW diff_buf, JSAMPROW16 output_buf,
+ JDIMENSION width));
+
+ /* Pointer to data which is private to scaler module */
+ void *scaler_private;
+
+} jpeg_lossless_d_codec;
+
+typedef jpeg_lossless_d_codec * j_lossless_d_ptr;
+
+
+/* Compression module initialization routines */
+EXTERN(void) jinit_lossless_c_codec JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_lhuff_encoder JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_differencer JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_c_scaler JPP((j_compress_ptr cinfo));
+/* Decompression module initialization routines */
+EXTERN(void) jinit_lossless_d_codec JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_lhuff_decoder JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_undifferencer JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_d_scaler JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_d_diff_controller JPP((j_decompress_ptr cinfo, boolean need_full_buffer));
+
+#endif /* JLOSSLS_H */
diff --git a/jpeg-6c/jlossy.h b/jpeg-6c/jlossy.h
new file mode 100644
index 0000000..08ac0cc
--- /dev/null
+++ b/jpeg-6c/jlossy.h
@@ -0,0 +1,121 @@
+/*
+ * jlossy.h
+ *
+ * Copyright (C) 1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This include file contains common declarations for the lossy (DCT-based)
+ * JPEG codec modules.
+ */
+
+#ifndef JLOSSY_H
+#define JLOSSY_H
+
+
+/* Lossy-specific compression codec (compressor proper) */
+typedef struct {
+ struct jpeg_c_codec pub; /* public fields */
+
+
+ /* Coefficient buffer control */
+ JMETHOD(void, coef_start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+ /* JMETHOD(boolean, coef_compress_data, (j_compress_ptr cinfo,
+ JSAMPIMAGE16 input_buf));*/
+
+ /* Pointer to data which is private to coef module */
+ void *coef_private;
+
+
+ /* Forward DCT (also controls coefficient quantization) */
+ JMETHOD(void, fdct_start_pass, (j_compress_ptr cinfo));
+ /* perhaps this should be an array??? */
+ JMETHOD(void, fdct_forward_DCT, (j_compress_ptr cinfo,
+ jpeg_component_info * compptr,
+ JSAMPARRAY16 sample_data, JBLOCKROW coef_blocks,
+ JDIMENSION start_row, JDIMENSION start_col,
+ JDIMENSION num_blocks));
+
+ /* Pointer to data which is private to fdct module */
+ void *fdct_private;
+
+
+ /* Entropy encoding */
+ JMETHOD(boolean, entropy_encode_mcu, (j_compress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+
+ /* Pointer to data which is private to entropy module */
+ void *entropy_private;
+
+} jpeg_lossy_c_codec;
+
+typedef jpeg_lossy_c_codec * j_lossy_c_ptr;
+
+
+
+typedef JMETHOD(void, inverse_DCT_method_ptr,
+ (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+ JCOEFPTR coef_block,
+ JSAMPARRAY16 output_buf, JDIMENSION output_col));
+
+/* Lossy-specific decompression codec (decompressor proper) */
+typedef struct {
+ struct jpeg_d_codec pub; /* public fields */
+
+
+ /* Coefficient buffer control */
+ JMETHOD(void, coef_start_input_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, coef_start_output_pass, (j_decompress_ptr cinfo));
+
+ /* Pointer to array of coefficient virtual arrays, or NULL if none */
+ jvirt_barray_ptr *coef_arrays;
+
+ /* Pointer to data which is private to coef module */
+ void *coef_private;
+
+
+ /* Entropy decoding */
+ JMETHOD(void, entropy_start_pass, (j_decompress_ptr cinfo));
+ JMETHOD(boolean, entropy_decode_mcu, (j_decompress_ptr cinfo,
+ JBLOCKROW *MCU_data));
+
+ /* This is here to share code between baseline and progressive decoders; */
+ /* other modules probably should not use it */
+ boolean entropy_insufficient_data; /* set TRUE after emitting warning */
+
+ /* Pointer to data which is private to entropy module */
+ void *entropy_private;
+
+
+ /* Inverse DCT (also performs dequantization) */
+ JMETHOD(void, idct_start_pass, (j_decompress_ptr cinfo));
+
+ /* It is useful to allow each component to have a separate IDCT method. */
+ inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
+
+ /* Pointer to data which is private to idct module */
+ void *idct_private;
+
+} jpeg_lossy_d_codec;
+
+typedef jpeg_lossy_d_codec * j_lossy_d_ptr;
+
+
+/* Compression module initialization routines */
+EXTERN(void) jinit_lossy_c_codec JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_shuff_encoder JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
+
+/* Decompression module initialization routines */
+EXTERN(void) jinit_lossy_d_codec JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN(void) jinit_shuff_decoder JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
+
+#endif /* JLOSSY_H */
diff --git a/jpeg-6c/jmemansi.c b/jpeg-6c/jmemansi.c
new file mode 100644
index 0000000..2d93e49
--- /dev/null
+++ b/jpeg-6c/jmemansi.c
@@ -0,0 +1,167 @@
+/*
+ * jmemansi.c
+ *
+ * Copyright (C) 1992-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file provides a simple generic implementation of the system-
+ * dependent portion of the JPEG memory manager. This implementation
+ * assumes that you have the ANSI-standard library routine tmpfile().
+ * Also, the problem of determining the amount of memory available
+ * is shoved onto the user.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h" /* import the system-dependent declarations */
+
+#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
+extern void * malloc JPP((size_t size));
+extern void free JPP((void *ptr));
+#endif
+
+#ifndef SEEK_SET /* pre-ANSI systems may not define this; */
+#define SEEK_SET 0 /* if not, assume 0 is correct */
+#endif
+
+
+/*
+ * Memory allocation and freeing are controlled by the regular library
+ * routines malloc() and free().
+ */
+
+GLOBAL(void *)
+jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void *) malloc(sizeofobject);
+}
+
+GLOBAL(void)
+jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * "Large" objects are treated the same as "small" ones.
+ * NB: although we include FAR keywords in the routine declarations,
+ * this file won't actually work in 80x86 small/medium model; at least,
+ * you probably won't be able to process useful-size images in only 64KB.
+ */
+
+GLOBAL(void FAR *)
+jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void FAR *) malloc(sizeofobject);
+}
+
+GLOBAL(void)
+jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * This routine computes the total memory space available for allocation.
+ * It's impossible to do this in a portable way; our current solution is
+ * to make the user tell us (with a default value set at compile time).
+ * If you can actually get the available space, it's a good idea to subtract
+ * a slop factor of 5% or so.
+ */
+
+#ifndef DEFAULT_MAX_MEM /* so can override from makefile */
+#define DEFAULT_MAX_MEM 1000000L /* default: one megabyte */
+#endif
+
+GLOBAL(long)
+jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
+ long max_bytes_needed, long already_allocated)
+{
+ return cinfo->mem->max_memory_to_use - already_allocated;
+}
+
+
+/*
+ * Backing store (temporary file) management.
+ * Backing store objects are only used when the value returned by
+ * jpeg_mem_available is less than the total space needed. You can dispense
+ * with these routines if you have plenty of virtual memory; see jmemnobs.c.
+ */
+
+
+METHODDEF(void)
+read_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ if (fseek(info->temp_file, file_offset, SEEK_SET))
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+ if (JFREAD(info->temp_file, buffer_address, byte_count)
+ != (size_t) byte_count)
+ ERREXIT(cinfo, JERR_TFILE_READ);
+}
+
+
+METHODDEF(void)
+write_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ if (fseek(info->temp_file, file_offset, SEEK_SET))
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+ if (JFWRITE(info->temp_file, buffer_address, byte_count)
+ != (size_t) byte_count)
+ ERREXIT(cinfo, JERR_TFILE_WRITE);
+}
+
+
+METHODDEF(void)
+close_backing_store (j_common_ptr cinfo, backing_store_ptr info)
+{
+ fclose(info->temp_file);
+ /* Since this implementation uses tmpfile() to create the file,
+ * no explicit file deletion is needed.
+ */
+}
+
+
+/*
+ * Initial opening of a backing-store object.
+ *
+ * This version uses tmpfile(), which constructs a suitable file name
+ * behind the scenes. We don't have to use info->temp_name[] at all;
+ * indeed, we can't even find out the actual name of the temp file.
+ */
+
+GLOBAL(void)
+jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ if ((info->temp_file = tmpfile()) == NULL)
+ ERREXITS(cinfo, JERR_TFILE_CREATE, "");
+ info->read_backing_store = read_backing_store;
+ info->write_backing_store = write_backing_store;
+ info->close_backing_store = close_backing_store;
+}
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required.
+ */
+
+GLOBAL(long)
+jpeg_mem_init (j_common_ptr cinfo)
+{
+ return DEFAULT_MAX_MEM; /* default for max_memory_to_use */
+}
+
+GLOBAL(void)
+jpeg_mem_term (j_common_ptr cinfo)
+{
+ /* no work */
+}
diff --git a/jpeg-6c/jmemdos.c b/jpeg-6c/jmemdos.c
new file mode 100644
index 0000000..60b45c6
--- /dev/null
+++ b/jpeg-6c/jmemdos.c
@@ -0,0 +1,638 @@
+/*
+ * jmemdos.c
+ *
+ * Copyright (C) 1992-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file provides an MS-DOS-compatible implementation of the system-
+ * dependent portion of the JPEG memory manager. Temporary data can be
+ * stored in extended or expanded memory as well as in regular DOS files.
+ *
+ * If you use this file, you must be sure that NEED_FAR_POINTERS is defined
+ * if you compile in a small-data memory model; it should NOT be defined if
+ * you use a large-data memory model. This file is not recommended if you
+ * are using a flat-memory-space 386 environment such as DJGCC or Watcom C.
+ * Also, this code will NOT work if struct fields are aligned on greater than
+ * 2-byte boundaries.
+ *
+ * Based on code contributed by Ge' Weijers.
+ */
+
+/*
+ * If you have both extended and expanded memory, you may want to change the
+ * order in which they are tried in jopen_backing_store. On a 286 machine
+ * expanded memory is usually faster, since extended memory access involves
+ * an expensive protected-mode-and-back switch. On 386 and better, extended
+ * memory is usually faster. As distributed, the code tries extended memory
+ * first (what? not everyone has a 386? :-).
+ *
+ * You can disable use of extended/expanded memory entirely by altering these
+ * definitions or overriding them from the Makefile (eg, -DEMS_SUPPORTED=0).
+ */
+
+#ifndef XMS_SUPPORTED
+#define XMS_SUPPORTED 1
+#endif
+#ifndef EMS_SUPPORTED
+#define EMS_SUPPORTED 1
+#endif
+
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h" /* import the system-dependent declarations */
+
+#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare these */
+extern void * malloc JPP((size_t size));
+extern void free JPP((void *ptr));
+extern char * getenv JPP((const char * name));
+#endif
+
+#ifdef NEED_FAR_POINTERS
+
+#ifdef __TURBOC__
+/* These definitions work for Borland C (Turbo C) */
+#include <alloc.h> /* need farmalloc(), farfree() */
+#define far_malloc(x) farmalloc(x)
+#define far_free(x) farfree(x)
+#else
+/* These definitions work for Microsoft C and compatible compilers */
+#include <malloc.h> /* need _fmalloc(), _ffree() */
+#define far_malloc(x) _fmalloc(x)
+#define far_free(x) _ffree(x)
+#endif
+
+#else /* not NEED_FAR_POINTERS */
+
+#define far_malloc(x) malloc(x)
+#define far_free(x) free(x)
+
+#endif /* NEED_FAR_POINTERS */
+
+#ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
+#define READ_BINARY "r"
+#else
+#define READ_BINARY "rb"
+#endif
+
+#ifndef USE_MSDOS_MEMMGR /* make sure user got configuration right */
+ You forgot to define USE_MSDOS_MEMMGR in jconfig.h. /* deliberate syntax error */
+#endif
+
+#if MAX_ALLOC_CHUNK >= 65535L /* make sure jconfig.h got this right */
+ MAX_ALLOC_CHUNK should be less than 64K. /* deliberate syntax error */
+#endif
+
+
+/*
+ * Declarations for assembly-language support routines (see jmemdosa.asm).
+ *
+ * The functions are declared "far" as are all their pointer arguments;
+ * this ensures the assembly source code will work regardless of the
+ * compiler memory model. We assume "short" is 16 bits, "long" is 32.
+ */
+
+typedef void far * XMSDRIVER; /* actually a pointer to code */
+typedef struct { /* registers for calling XMS driver */
+ unsigned short ax, dx, bx;
+ void far * ds_si;
+ } XMScontext;
+typedef struct { /* registers for calling EMS driver */
+ unsigned short ax, dx, bx;
+ void far * ds_si;
+ } EMScontext;
+
+extern short far jdos_open JPP((short far * handle, char far * filename));
+extern short far jdos_close JPP((short handle));
+extern short far jdos_seek JPP((short handle, long offset));
+extern short far jdos_read JPP((short handle, void far * buffer,
+ unsigned short count));
+extern short far jdos_write JPP((short handle, void far * buffer,
+ unsigned short count));
+extern void far jxms_getdriver JPP((XMSDRIVER far *));
+extern void far jxms_calldriver JPP((XMSDRIVER, XMScontext far *));
+extern short far jems_available JPP((void));
+extern void far jems_calldriver JPP((EMScontext far *));
+
+
+/*
+ * Selection of a file name for a temporary file.
+ * This is highly system-dependent, and you may want to customize it.
+ */
+
+static int next_file_num; /* to distinguish among several temp files */
+
+LOCAL(void)
+select_file_name (char * fname)
+{
+ const char * env;
+ char * ptr;
+ FILE * tfile;
+
+ /* Keep generating file names till we find one that's not in use */
+ for (;;) {
+ /* Get temp directory name from environment TMP or TEMP variable;
+ * if none, use "."
+ */
+ if ((env = (const char *) getenv("TMP")) == NULL)
+ if ((env = (const char *) getenv("TEMP")) == NULL)
+ env = ".";
+ if (*env == '\0') /* null string means "." */
+ env = ".";
+ ptr = fname; /* copy name to fname */
+ while (*env != '\0')
+ *ptr++ = *env++;
+ if (ptr[-1] != '\\' && ptr[-1] != '/')
+ *ptr++ = '\\'; /* append backslash if not in env variable */
+ /* Append a suitable file name */
+ next_file_num++; /* advance counter */
+ sprintf(ptr, "JPG%03d.TMP", next_file_num);
+ /* Probe to see if file name is already in use */
+ if ((tfile = fopen(fname, READ_BINARY)) == NULL)
+ break;
+ fclose(tfile); /* oops, it's there; close tfile & try again */
+ }
+}
+
+
+/*
+ * Near-memory allocation and freeing are controlled by the regular library
+ * routines malloc() and free().
+ */
+
+GLOBAL(void *)
+jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void *) malloc(sizeofobject);
+}
+
+GLOBAL(void)
+jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * "Large" objects are allocated in far memory, if possible
+ */
+
+GLOBAL(void FAR *)
+jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void FAR *) far_malloc(sizeofobject);
+}
+
+GLOBAL(void)
+jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
+{
+ far_free(object);
+}
+
+
+/*
+ * This routine computes the total memory space available for allocation.
+ * It's impossible to do this in a portable way; our current solution is
+ * to make the user tell us (with a default value set at compile time).
+ * If you can actually get the available space, it's a good idea to subtract
+ * a slop factor of 5% or so.
+ */
+
+#ifndef DEFAULT_MAX_MEM /* so can override from makefile */
+#define DEFAULT_MAX_MEM 300000L /* for total usage about 450K */
+#endif
+
+GLOBAL(long)
+jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
+ long max_bytes_needed, long already_allocated)
+{
+ return cinfo->mem->max_memory_to_use - already_allocated;
+}
+
+
+/*
+ * Backing store (temporary file) management.
+ * Backing store objects are only used when the value returned by
+ * jpeg_mem_available is less than the total space needed. You can dispense
+ * with these routines if you have plenty of virtual memory; see jmemnobs.c.
+ */
+
+/*
+ * For MS-DOS we support three types of backing storage:
+ * 1. Conventional DOS files. We access these by direct DOS calls rather
+ * than via the stdio package. This provides a bit better performance,
+ * but the real reason is that the buffers to be read or written are FAR.
+ * The stdio library for small-data memory models can't cope with that.
+ * 2. Extended memory, accessed per the XMS V2.0 specification.
+ * 3. Expanded memory, accessed per the LIM/EMS 4.0 specification.
+ * You'll need copies of those specs to make sense of the related code.
+ * The specs are available by Internet FTP from the SIMTEL archives
+ * (oak.oakland.edu and its various mirror sites). See files
+ * pub/msdos/microsoft/xms20.arc and pub/msdos/info/limems41.zip.
+ */
+
+
+/*
+ * Access methods for a DOS file.
+ */
+
+
+METHODDEF(void)
+read_file_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ if (jdos_seek(info->handle.file_handle, file_offset))
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+ /* Since MAX_ALLOC_CHUNK is less than 64K, byte_count will be too. */
+ if (byte_count > 65535L) /* safety check */
+ ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
+ if (jdos_read(info->handle.file_handle, buffer_address,
+ (unsigned short) byte_count))
+ ERREXIT(cinfo, JERR_TFILE_READ);
+}
+
+
+METHODDEF(void)
+write_file_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ if (jdos_seek(info->handle.file_handle, file_offset))
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+ /* Since MAX_ALLOC_CHUNK is less than 64K, byte_count will be too. */
+ if (byte_count > 65535L) /* safety check */
+ ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
+ if (jdos_write(info->handle.file_handle, buffer_address,
+ (unsigned short) byte_count))
+ ERREXIT(cinfo, JERR_TFILE_WRITE);
+}
+
+
+METHODDEF(void)
+close_file_store (j_common_ptr cinfo, backing_store_ptr info)
+{
+ jdos_close(info->handle.file_handle); /* close the file */
+ remove(info->temp_name); /* delete the file */
+/* If your system doesn't have remove(), try unlink() instead.
+ * remove() is the ANSI-standard name for this function, but
+ * unlink() was more common in pre-ANSI systems.
+ */
+ TRACEMSS(cinfo, 1, JTRC_TFILE_CLOSE, info->temp_name);
+}
+
+
+LOCAL(boolean)
+open_file_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ short handle;
+
+ select_file_name(info->temp_name);
+ if (jdos_open((short far *) & handle, (char far *) info->temp_name)) {
+ /* might as well exit since jpeg_open_backing_store will fail anyway */
+ ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name);
+ return FALSE;
+ }
+ info->handle.file_handle = handle;
+ info->read_backing_store = read_file_store;
+ info->write_backing_store = write_file_store;
+ info->close_backing_store = close_file_store;
+ TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name);
+ return TRUE; /* succeeded */
+}
+
+
+/*
+ * Access methods for extended memory.
+ */
+
+#if XMS_SUPPORTED
+
+static XMSDRIVER xms_driver; /* saved address of XMS driver */
+
+typedef union { /* either long offset or real-mode pointer */
+ long offset;
+ void far * ptr;
+ } XMSPTR;
+
+typedef struct { /* XMS move specification structure */
+ long length;
+ XMSH src_handle;
+ XMSPTR src;
+ XMSH dst_handle;
+ XMSPTR dst;
+ } XMSspec;
+
+#define ODD(X) (((X) & 1L) != 0)
+
+
+METHODDEF(void)
+read_xms_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ XMScontext ctx;
+ XMSspec spec;
+ char endbuffer[2];
+
+ /* The XMS driver can't cope with an odd length, so handle the last byte
+ * specially if byte_count is odd. We don't expect this to be common.
+ */
+
+ spec.length = byte_count & (~ 1L);
+ spec.src_handle = info->handle.xms_handle;
+ spec.src.offset = file_offset;
+ spec.dst_handle = 0;
+ spec.dst.ptr = buffer_address;
+
+ ctx.ds_si = (void far *) & spec;
+ ctx.ax = 0x0b00; /* EMB move */
+ jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
+ if (ctx.ax != 1)
+ ERREXIT(cinfo, JERR_XMS_READ);
+
+ if (ODD(byte_count)) {
+ read_xms_store(cinfo, info, (void FAR *) endbuffer,
+ file_offset + byte_count - 1L, 2L);
+ ((char FAR *) buffer_address)[byte_count - 1L] = endbuffer[0];
+ }
+}
+
+
+METHODDEF(void)
+write_xms_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ XMScontext ctx;
+ XMSspec spec;
+ char endbuffer[2];
+
+ /* The XMS driver can't cope with an odd length, so handle the last byte
+ * specially if byte_count is odd. We don't expect this to be common.
+ */
+
+ spec.length = byte_count & (~ 1L);
+ spec.src_handle = 0;
+ spec.src.ptr = buffer_address;
+ spec.dst_handle = info->handle.xms_handle;
+ spec.dst.offset = file_offset;
+
+ ctx.ds_si = (void far *) & spec;
+ ctx.ax = 0x0b00; /* EMB move */
+ jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
+ if (ctx.ax != 1)
+ ERREXIT(cinfo, JERR_XMS_WRITE);
+
+ if (ODD(byte_count)) {
+ read_xms_store(cinfo, info, (void FAR *) endbuffer,
+ file_offset + byte_count - 1L, 2L);
+ endbuffer[0] = ((char FAR *) buffer_address)[byte_count - 1L];
+ write_xms_store(cinfo, info, (void FAR *) endbuffer,
+ file_offset + byte_count - 1L, 2L);
+ }
+}
+
+
+METHODDEF(void)
+close_xms_store (j_common_ptr cinfo, backing_store_ptr info)
+{
+ XMScontext ctx;
+
+ ctx.dx = info->handle.xms_handle;
+ ctx.ax = 0x0a00;
+ jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
+ TRACEMS1(cinfo, 1, JTRC_XMS_CLOSE, info->handle.xms_handle);
+ /* we ignore any error return from the driver */
+}
+
+
+LOCAL(boolean)
+open_xms_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ XMScontext ctx;
+
+ /* Get address of XMS driver */
+ jxms_getdriver((XMSDRIVER far *) & xms_driver);
+ if (xms_driver == NULL)
+ return FALSE; /* no driver to be had */
+
+ /* Get version number, must be >= 2.00 */
+ ctx.ax = 0x0000;
+ jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
+ if (ctx.ax < (unsigned short) 0x0200)
+ return FALSE;
+
+ /* Try to get space (expressed in kilobytes) */
+ ctx.dx = (unsigned short) ((total_bytes_needed + 1023L) >> 10);
+ ctx.ax = 0x0900;
+ jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
+ if (ctx.ax != 1)
+ return FALSE;
+
+ /* Succeeded, save the handle and away we go */
+ info->handle.xms_handle = ctx.dx;
+ info->read_backing_store = read_xms_store;
+ info->write_backing_store = write_xms_store;
+ info->close_backing_store = close_xms_store;
+ TRACEMS1(cinfo, 1, JTRC_XMS_OPEN, ctx.dx);
+ return TRUE; /* succeeded */
+}
+
+#endif /* XMS_SUPPORTED */
+
+
+/*
+ * Access methods for expanded memory.
+ */
+
+#if EMS_SUPPORTED
+
+/* The EMS move specification structure requires word and long fields aligned
+ * at odd byte boundaries. Some compilers will align struct fields at even
+ * byte boundaries. While it's usually possible to force byte alignment,
+ * that causes an overall performance penalty and may pose problems in merging
+ * JPEG into a larger application. Instead we accept some rather dirty code
+ * here. Note this code would fail if the hardware did not allow odd-byte
+ * word & long accesses, but all 80x86 CPUs do.
+ */
+
+typedef void far * EMSPTR;
+
+typedef union { /* EMS move specification structure */
+ long length; /* It's easy to access first 4 bytes */
+ char bytes[18]; /* Misaligned fields in here! */
+ } EMSspec;
+
+/* Macros for accessing misaligned fields */
+#define FIELD_AT(spec,offset,type) (*((type *) &(spec.bytes[offset])))
+#define SRC_TYPE(spec) FIELD_AT(spec,4,char)
+#define SRC_HANDLE(spec) FIELD_AT(spec,5,EMSH)
+#define SRC_OFFSET(spec) FIELD_AT(spec,7,unsigned short)
+#define SRC_PAGE(spec) FIELD_AT(spec,9,unsigned short)
+#define SRC_PTR(spec) FIELD_AT(spec,7,EMSPTR)
+#define DST_TYPE(spec) FIELD_AT(spec,11,char)
+#define DST_HANDLE(spec) FIELD_AT(spec,12,EMSH)
+#define DST_OFFSET(spec) FIELD_AT(spec,14,unsigned short)
+#define DST_PAGE(spec) FIELD_AT(spec,16,unsigned short)
+#define DST_PTR(spec) FIELD_AT(spec,14,EMSPTR)
+
+#define EMSPAGESIZE 16384L /* gospel, see the EMS specs */
+
+#define HIBYTE(W) (((W) >> 8) & 0xFF)
+#define LOBYTE(W) ((W) & 0xFF)
+
+
+METHODDEF(void)
+read_ems_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ EMScontext ctx;
+ EMSspec spec;
+
+ spec.length = byte_count;
+ SRC_TYPE(spec) = 1;
+ SRC_HANDLE(spec) = info->handle.ems_handle;
+ SRC_PAGE(spec) = (unsigned short) (file_offset / EMSPAGESIZE);
+ SRC_OFFSET(spec) = (unsigned short) (file_offset % EMSPAGESIZE);
+ DST_TYPE(spec) = 0;
+ DST_HANDLE(spec) = 0;
+ DST_PTR(spec) = buffer_address;
+
+ ctx.ds_si = (void far *) & spec;
+ ctx.ax = 0x5700; /* move memory region */
+ jems_calldriver((EMScontext far *) & ctx);
+ if (HIBYTE(ctx.ax) != 0)
+ ERREXIT(cinfo, JERR_EMS_READ);
+}
+
+
+METHODDEF(void)
+write_ems_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ EMScontext ctx;
+ EMSspec spec;
+
+ spec.length = byte_count;
+ SRC_TYPE(spec) = 0;
+ SRC_HANDLE(spec) = 0;
+ SRC_PTR(spec) = buffer_address;
+ DST_TYPE(spec) = 1;
+ DST_HANDLE(spec) = info->handle.ems_handle;
+ DST_PAGE(spec) = (unsigned short) (file_offset / EMSPAGESIZE);
+ DST_OFFSET(spec) = (unsigned short) (file_offset % EMSPAGESIZE);
+
+ ctx.ds_si = (void far *) & spec;
+ ctx.ax = 0x5700; /* move memory region */
+ jems_calldriver((EMScontext far *) & ctx);
+ if (HIBYTE(ctx.ax) != 0)
+ ERREXIT(cinfo, JERR_EMS_WRITE);
+}
+
+
+METHODDEF(void)
+close_ems_store (j_common_ptr cinfo, backing_store_ptr info)
+{
+ EMScontext ctx;
+
+ ctx.ax = 0x4500;
+ ctx.dx = info->handle.ems_handle;
+ jems_calldriver((EMScontext far *) & ctx);
+ TRACEMS1(cinfo, 1, JTRC_EMS_CLOSE, info->handle.ems_handle);
+ /* we ignore any error return from the driver */
+}
+
+
+LOCAL(boolean)
+open_ems_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ EMScontext ctx;
+
+ /* Is EMS driver there? */
+ if (! jems_available())
+ return FALSE;
+
+ /* Get status, make sure EMS is OK */
+ ctx.ax = 0x4000;
+ jems_calldriver((EMScontext far *) & ctx);
+ if (HIBYTE(ctx.ax) != 0)
+ return FALSE;
+
+ /* Get version, must be >= 4.0 */
+ ctx.ax = 0x4600;
+ jems_calldriver((EMScontext far *) & ctx);
+ if (HIBYTE(ctx.ax) != 0 || LOBYTE(ctx.ax) < 0x40)
+ return FALSE;
+
+ /* Try to allocate requested space */
+ ctx.ax = 0x4300;
+ ctx.bx = (unsigned short) ((total_bytes_needed + EMSPAGESIZE-1L) / EMSPAGESIZE);
+ jems_calldriver((EMScontext far *) & ctx);
+ if (HIBYTE(ctx.ax) != 0)
+ return FALSE;
+
+ /* Succeeded, save the handle and away we go */
+ info->handle.ems_handle = ctx.dx;
+ info->read_backing_store = read_ems_store;
+ info->write_backing_store = write_ems_store;
+ info->close_backing_store = close_ems_store;
+ TRACEMS1(cinfo, 1, JTRC_EMS_OPEN, ctx.dx);
+ return TRUE; /* succeeded */
+}
+
+#endif /* EMS_SUPPORTED */
+
+
+/*
+ * Initial opening of a backing-store object.
+ */
+
+GLOBAL(void)
+jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ /* Try extended memory, then expanded memory, then regular file. */
+#if XMS_SUPPORTED
+ if (open_xms_store(cinfo, info, total_bytes_needed))
+ return;
+#endif
+#if EMS_SUPPORTED
+ if (open_ems_store(cinfo, info, total_bytes_needed))
+ return;
+#endif
+ if (open_file_store(cinfo, info, total_bytes_needed))
+ return;
+ ERREXITS(cinfo, JERR_TFILE_CREATE, "");
+}
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required.
+ */
+
+GLOBAL(long)
+jpeg_mem_init (j_common_ptr cinfo)
+{
+ next_file_num = 0; /* initialize temp file name generator */
+ return DEFAULT_MAX_MEM; /* default for max_memory_to_use */
+}
+
+GLOBAL(void)
+jpeg_mem_term (j_common_ptr cinfo)
+{
+ /* Microsoft C, at least in v6.00A, will not successfully reclaim freed
+ * blocks of size > 32Kbytes unless we give it a kick in the rear, like so:
+ */
+#ifdef NEED_FHEAPMIN
+ _fheapmin();
+#endif
+}
diff --git a/jpeg-6c/jmemdosa.asm b/jpeg-6c/jmemdosa.asm
new file mode 100644
index 0000000..ecd4372
--- /dev/null
+++ b/jpeg-6c/jmemdosa.asm
@@ -0,0 +1,379 @@
+;
+; jmemdosa.asm
+;
+; Copyright (C) 1992, Thomas G. Lane.
+; This file is part of the Independent JPEG Group's software.
+; For conditions of distribution and use, see the accompanying README file.
+;
+; This file contains low-level interface routines to support the MS-DOS
+; backing store manager (jmemdos.c). Routines are provided to access disk
+; files through direct DOS calls, and to access XMS and EMS drivers.
+;
+; This file should assemble with Microsoft's MASM or any compatible
+; assembler (including Borland's Turbo Assembler). If you haven't got
+; a compatible assembler, better fall back to jmemansi.c or jmemname.c.
+;
+; To minimize dependence on the C compiler's register usage conventions,
+; we save and restore all 8086 registers, even though most compilers only
+; require SI,DI,DS to be preserved. Also, we use only 16-bit-wide return
+; values, which everybody returns in AX.
+;
+; Based on code contributed by Ge' Weijers.
+;
+
+JMEMDOSA_TXT segment byte public 'CODE'
+
+ assume cs:JMEMDOSA_TXT
+
+ public _jdos_open
+ public _jdos_close
+ public _jdos_seek
+ public _jdos_read
+ public _jdos_write
+ public _jxms_getdriver
+ public _jxms_calldriver
+ public _jems_available
+ public _jems_calldriver
+
+;
+; short far jdos_open (short far * handle, char far * filename)
+;
+; Create and open a temporary file
+;
+_jdos_open proc far
+ push bp ; linkage
+ mov bp,sp
+ push si ; save all registers for safety
+ push di
+ push bx
+ push cx
+ push dx
+ push es
+ push ds
+ mov cx,0 ; normal file attributes
+ lds dx,dword ptr [bp+10] ; get filename pointer
+ mov ah,3ch ; create file
+ int 21h
+ jc open_err ; if failed, return error code
+ lds bx,dword ptr [bp+6] ; get handle pointer
+ mov word ptr [bx],ax ; save the handle
+ xor ax,ax ; return zero for OK
+open_err: pop ds ; restore registers and exit
+ pop es
+ pop dx
+ pop cx
+ pop bx
+ pop di
+ pop si
+ pop bp
+ ret
+_jdos_open endp
+
+
+;
+; short far jdos_close (short handle)
+;
+; Close the file handle
+;
+_jdos_close proc far
+ push bp ; linkage
+ mov bp,sp
+ push si ; save all registers for safety
+ push di
+ push bx
+ push cx
+ push dx
+ push es
+ push ds
+ mov bx,word ptr [bp+6] ; file handle
+ mov ah,3eh ; close file
+ int 21h
+ jc close_err ; if failed, return error code
+ xor ax,ax ; return zero for OK
+close_err: pop ds ; restore registers and exit
+ pop es
+ pop dx
+ pop cx
+ pop bx
+ pop di
+ pop si
+ pop bp
+ ret
+_jdos_close endp
+
+
+;
+; short far jdos_seek (short handle, long offset)
+;
+; Set file position
+;
+_jdos_seek proc far
+ push bp ; linkage
+ mov bp,sp
+ push si ; save all registers for safety
+ push di
+ push bx
+ push cx
+ push dx
+ push es
+ push ds
+ mov bx,word ptr [bp+6] ; file handle
+ mov dx,word ptr [bp+8] ; LS offset
+ mov cx,word ptr [bp+10] ; MS offset
+ mov ax,4200h ; absolute seek
+ int 21h
+ jc seek_err ; if failed, return error code
+ xor ax,ax ; return zero for OK
+seek_err: pop ds ; restore registers and exit
+ pop es
+ pop dx
+ pop cx
+ pop bx
+ pop di
+ pop si
+ pop bp
+ ret
+_jdos_seek endp
+
+
+;
+; short far jdos_read (short handle, void far * buffer, unsigned short count)
+;
+; Read from file
+;
+_jdos_read proc far
+ push bp ; linkage
+ mov bp,sp
+ push si ; save all registers for safety
+ push di
+ push bx
+ push cx
+ push dx
+ push es
+ push ds
+ mov bx,word ptr [bp+6] ; file handle
+ lds dx,dword ptr [bp+8] ; buffer address
+ mov cx,word ptr [bp+12] ; number of bytes
+ mov ah,3fh ; read file
+ int 21h
+ jc read_err ; if failed, return error code
+ cmp ax,word ptr [bp+12] ; make sure all bytes were read
+ je read_ok
+ mov ax,1 ; else return 1 for not OK
+ jmp short read_err
+read_ok: xor ax,ax ; return zero for OK
+read_err: pop ds ; restore registers and exit
+ pop es
+ pop dx
+ pop cx
+ pop bx
+ pop di
+ pop si
+ pop bp
+ ret
+_jdos_read endp
+
+
+;
+; short far jdos_write (short handle, void far * buffer, unsigned short count)
+;
+; Write to file
+;
+_jdos_write proc far
+ push bp ; linkage
+ mov bp,sp
+ push si ; save all registers for safety
+ push di
+ push bx
+ push cx
+ push dx
+ push es
+ push ds
+ mov bx,word ptr [bp+6] ; file handle
+ lds dx,dword ptr [bp+8] ; buffer address
+ mov cx,word ptr [bp+12] ; number of bytes
+ mov ah,40h ; write file
+ int 21h
+ jc write_err ; if failed, return error code
+ cmp ax,word ptr [bp+12] ; make sure all bytes written
+ je write_ok
+ mov ax,1 ; else return 1 for not OK
+ jmp short write_err
+write_ok: xor ax,ax ; return zero for OK
+write_err: pop ds ; restore registers and exit
+ pop es
+ pop dx
+ pop cx
+ pop bx
+ pop di
+ pop si
+ pop bp
+ ret
+_jdos_write endp
+
+
+;
+; void far jxms_getdriver (XMSDRIVER far *)
+;
+; Get the address of the XMS driver, or NULL if not available
+;
+_jxms_getdriver proc far
+ push bp ; linkage
+ mov bp,sp
+ push si ; save all registers for safety
+ push di
+ push bx
+ push cx
+ push dx
+ push es
+ push ds
+ mov ax,4300h ; call multiplex interrupt with
+ int 2fh ; a magic cookie, hex 4300
+ cmp al,80h ; AL should contain hex 80
+ je xmsavail
+ xor dx,dx ; no XMS driver available
+ xor ax,ax ; return a nil pointer
+ jmp short xmsavail_done
+xmsavail: mov ax,4310h ; fetch driver address with
+ int 2fh ; another magic cookie
+ mov dx,es ; copy address to dx:ax
+ mov ax,bx
+xmsavail_done: les bx,dword ptr [bp+6] ; get pointer to return value
+ mov word ptr es:[bx],ax
+ mov word ptr es:[bx+2],dx
+ pop ds ; restore registers and exit
+ pop es
+ pop dx
+ pop cx
+ pop bx
+ pop di
+ pop si
+ pop bp
+ ret
+_jxms_getdriver endp
+
+
+;
+; void far jxms_calldriver (XMSDRIVER, XMScontext far *)
+;
+; The XMScontext structure contains values for the AX,DX,BX,SI,DS registers.
+; These are loaded, the XMS call is performed, and the new values of the
+; AX,DX,BX registers are written back to the context structure.
+;
+_jxms_calldriver proc far
+ push bp ; linkage
+ mov bp,sp
+ push si ; save all registers for safety
+ push di
+ push bx
+ push cx
+ push dx
+ push es
+ push ds
+ les bx,dword ptr [bp+10] ; get XMScontext pointer
+ mov ax,word ptr es:[bx] ; load registers
+ mov dx,word ptr es:[bx+2]
+ mov si,word ptr es:[bx+6]
+ mov ds,word ptr es:[bx+8]
+ mov bx,word ptr es:[bx+4]
+ call dword ptr [bp+6] ; call the driver
+ mov cx,bx ; save returned BX for a sec
+ les bx,dword ptr [bp+10] ; get XMScontext pointer
+ mov word ptr es:[bx],ax ; put back ax,dx,bx
+ mov word ptr es:[bx+2],dx
+ mov word ptr es:[bx+4],cx
+ pop ds ; restore registers and exit
+ pop es
+ pop dx
+ pop cx
+ pop bx
+ pop di
+ pop si
+ pop bp
+ ret
+_jxms_calldriver endp
+
+
+;
+; short far jems_available (void)
+;
+; Have we got an EMS driver? (this comes straight from the EMS 4.0 specs)
+;
+_jems_available proc far
+ push si ; save all registers for safety
+ push di
+ push bx
+ push cx
+ push dx
+ push es
+ push ds
+ mov ax,3567h ; get interrupt vector 67h
+ int 21h
+ push cs
+ pop ds
+ mov di,000ah ; check offs 10 in returned seg
+ lea si,ASCII_device_name ; against literal string
+ mov cx,8
+ cld
+ repe cmpsb
+ jne no_ems
+ mov ax,1 ; match, it's there
+ jmp short avail_done
+no_ems: xor ax,ax ; it's not there
+avail_done: pop ds ; restore registers and exit
+ pop es
+ pop dx
+ pop cx
+ pop bx
+ pop di
+ pop si
+ ret
+
+ASCII_device_name db "EMMXXXX0"
+
+_jems_available endp
+
+
+;
+; void far jems_calldriver (EMScontext far *)
+;
+; The EMScontext structure contains values for the AX,DX,BX,SI,DS registers.
+; These are loaded, the EMS trap is performed, and the new values of the
+; AX,DX,BX registers are written back to the context structure.
+;
+_jems_calldriver proc far
+ push bp ; linkage
+ mov bp,sp
+ push si ; save all registers for safety
+ push di
+ push bx
+ push cx
+ push dx
+ push es
+ push ds
+ les bx,dword ptr [bp+6] ; get EMScontext pointer
+ mov ax,word ptr es:[bx] ; load registers
+ mov dx,word ptr es:[bx+2]
+ mov si,word ptr es:[bx+6]
+ mov ds,word ptr es:[bx+8]
+ mov bx,word ptr es:[bx+4]
+ int 67h ; call the EMS driver
+ mov cx,bx ; save returned BX for a sec
+ les bx,dword ptr [bp+6] ; get EMScontext pointer
+ mov word ptr es:[bx],ax ; put back ax,dx,bx
+ mov word ptr es:[bx+2],dx
+ mov word ptr es:[bx+4],cx
+ pop ds ; restore registers and exit
+ pop es
+ pop dx
+ pop cx
+ pop bx
+ pop di
+ pop si
+ pop bp
+ ret
+_jems_calldriver endp
+
+JMEMDOSA_TXT ends
+
+ end
diff --git a/jpeg-6c/jmemmac.c b/jpeg-6c/jmemmac.c
new file mode 100644
index 0000000..106f9be
--- /dev/null
+++ b/jpeg-6c/jmemmac.c
@@ -0,0 +1,289 @@
+/*
+ * jmemmac.c
+ *
+ * Copyright (C) 1992-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * jmemmac.c provides an Apple Macintosh implementation of the system-
+ * dependent portion of the JPEG memory manager.
+ *
+ * If you use jmemmac.c, then you must define USE_MAC_MEMMGR in the
+ * JPEG_INTERNALS part of jconfig.h.
+ *
+ * jmemmac.c uses the Macintosh toolbox routines NewPtr and DisposePtr
+ * instead of malloc and free. It accurately determines the amount of
+ * memory available by using CompactMem. Notice that if left to its
+ * own devices, this code can chew up all available space in the
+ * application's zone, with the exception of the rather small "slop"
+ * factor computed in jpeg_mem_available(). The application can ensure
+ * that more space is left over by reducing max_memory_to_use.
+ *
+ * Large images are swapped to disk using temporary files and System 7.0+'s
+ * temporary folder functionality.
+ *
+ * Note that jmemmac.c depends on two features of MacOS that were first
+ * introduced in System 7: FindFolder and the FSSpec-based calls.
+ * If your application uses jmemmac.c and is run under System 6 or earlier,
+ * and the jpeg library decides it needs a temporary file, it will abort,
+ * printing error messages about requiring System 7. (If no temporary files
+ * are created, it will run fine.)
+ *
+ * If you want to use jmemmac.c in an application that might be used with
+ * System 6 or earlier, then you should remove dependencies on FindFolder
+ * and the FSSpec calls. You will need to replace FindFolder with some
+ * other mechanism for finding a place to put temporary files, and you
+ * should replace the FSSpec calls with their HFS equivalents:
+ *
+ * FSpDelete -> HDelete
+ * FSpGetFInfo -> HGetFInfo
+ * FSpCreate -> HCreate
+ * FSpOpenDF -> HOpen *** Note: not HOpenDF ***
+ * FSMakeFSSpec -> (fill in spec by hand.)
+ *
+ * (Use HOpen instead of HOpenDF. HOpen is just a glue-interface to PBHOpen,
+ * which is on all HFS macs. HOpenDF is a System 7 addition which avoids the
+ * ages-old problem of names starting with a period.)
+ *
+ * Contributed by Sam Bushell (jsam at iagu.on.net) and
+ * Dan Gildor (gyld at in-touch.com).
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h" /* import the system-dependent declarations */
+
+#ifndef USE_MAC_MEMMGR /* make sure user got configuration right */
+ You forgot to define USE_MAC_MEMMGR in jconfig.h. /* deliberate syntax error */
+#endif
+
+#include <Memory.h> /* we use the MacOS memory manager */
+#include <Files.h> /* we use the MacOS File stuff */
+#include <Folders.h> /* we use the MacOS HFS stuff */
+#include <Script.h> /* for smSystemScript */
+#include <Gestalt.h> /* we use Gestalt to test for specific functionality */
+
+#ifndef TEMP_FILE_NAME /* can override from jconfig.h or Makefile */
+#define TEMP_FILE_NAME "JPG%03d.TMP"
+#endif
+
+static int next_file_num; /* to distinguish among several temp files */
+
+
+/*
+ * Memory allocation and freeing are controlled by the MacOS library
+ * routines NewPtr() and DisposePtr(), which allocate fixed-address
+ * storage. Unfortunately, the IJG library isn't smart enough to cope
+ * with relocatable storage.
+ */
+
+GLOBAL(void *)
+jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void *) NewPtr(sizeofobject);
+}
+
+GLOBAL(void)
+jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
+{
+ DisposePtr((Ptr) object);
+}
+
+
+/*
+ * "Large" objects are treated the same as "small" ones.
+ * NB: we include FAR keywords in the routine declarations simply for
+ * consistency with the rest of the IJG code; FAR should expand to empty
+ * on rational architectures like the Mac.
+ */
+
+GLOBAL(void FAR *)
+jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void FAR *) NewPtr(sizeofobject);
+}
+
+GLOBAL(void)
+jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
+{
+ DisposePtr((Ptr) object);
+}
+
+
+/*
+ * This routine computes the total memory space available for allocation.
+ */
+
+GLOBAL(long)
+jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
+ long max_bytes_needed, long already_allocated)
+{
+ long limit = cinfo->mem->max_memory_to_use - already_allocated;
+ long slop, mem;
+
+ /* Don't ask for more than what application has told us we may use */
+ if (max_bytes_needed > limit && limit > 0)
+ max_bytes_needed = limit;
+ /* Find whether there's a big enough free block in the heap.
+ * CompactMem tries to create a contiguous block of the requested size,
+ * and then returns the size of the largest free block (which could be
+ * much more or much less than we asked for).
+ * We add some slop to ensure we don't use up all available memory.
+ */
+ slop = max_bytes_needed / 16 + 32768L;
+ mem = CompactMem(max_bytes_needed + slop) - slop;
+ if (mem < 0)
+ mem = 0; /* sigh, couldn't even get the slop */
+ /* Don't take more than the application says we can have */
+ if (mem > limit && limit > 0)
+ mem = limit;
+ return mem;
+}
+
+
+/*
+ * Backing store (temporary file) management.
+ * Backing store objects are only used when the value returned by
+ * jpeg_mem_available is less than the total space needed. You can dispense
+ * with these routines if you have plenty of virtual memory; see jmemnobs.c.
+ */
+
+
+METHODDEF(void)
+read_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ long bytes = byte_count;
+ long retVal;
+
+ if ( SetFPos ( info->temp_file, fsFromStart, file_offset ) != noErr )
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+
+ retVal = FSRead ( info->temp_file, &bytes,
+ (unsigned char *) buffer_address );
+ if ( retVal != noErr || bytes != byte_count )
+ ERREXIT(cinfo, JERR_TFILE_READ);
+}
+
+
+METHODDEF(void)
+write_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ long bytes = byte_count;
+ long retVal;
+
+ if ( SetFPos ( info->temp_file, fsFromStart, file_offset ) != noErr )
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+
+ retVal = FSWrite ( info->temp_file, &bytes,
+ (unsigned char *) buffer_address );
+ if ( retVal != noErr || bytes != byte_count )
+ ERREXIT(cinfo, JERR_TFILE_WRITE);
+}
+
+
+METHODDEF(void)
+close_backing_store (j_common_ptr cinfo, backing_store_ptr info)
+{
+ FSClose ( info->temp_file );
+ FSpDelete ( &(info->tempSpec) );
+}
+
+
+/*
+ * Initial opening of a backing-store object.
+ *
+ * This version uses FindFolder to find the Temporary Items folder,
+ * and puts the temporary file in there.
+ */
+
+GLOBAL(void)
+jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ short tmpRef, vRefNum;
+ long dirID;
+ FInfo finderInfo;
+ FSSpec theSpec;
+ Str255 fName;
+ OSErr osErr;
+ long gestaltResponse = 0;
+
+ /* Check that FSSpec calls are available. */
+ osErr = Gestalt( gestaltFSAttr, &gestaltResponse );
+ if ( ( osErr != noErr )
+ || !( gestaltResponse & (1<<gestaltHasFSSpecCalls) ) )
+ ERREXITS(cinfo, JERR_TFILE_CREATE, "- System 7.0 or later required");
+ /* TO DO: add a proper error message to jerror.h. */
+
+ /* Check that FindFolder is available. */
+ osErr = Gestalt( gestaltFindFolderAttr, &gestaltResponse );
+ if ( ( osErr != noErr )
+ || !( gestaltResponse & (1<<gestaltFindFolderPresent) ) )
+ ERREXITS(cinfo, JERR_TFILE_CREATE, "- System 7.0 or later required.");
+ /* TO DO: add a proper error message to jerror.h. */
+
+ osErr = FindFolder ( kOnSystemDisk, kTemporaryFolderType, kCreateFolder,
+ &vRefNum, &dirID );
+ if ( osErr != noErr )
+ ERREXITS(cinfo, JERR_TFILE_CREATE, "- temporary items folder unavailable");
+ /* TO DO: Try putting the temp files somewhere else. */
+
+ /* Keep generating file names till we find one that's not in use */
+ for (;;) {
+ next_file_num++; /* advance counter */
+
+ sprintf(info->temp_name, TEMP_FILE_NAME, next_file_num);
+ strcpy ( (Ptr)fName+1, info->temp_name );
+ *fName = strlen (info->temp_name);
+ osErr = FSMakeFSSpec ( vRefNum, dirID, fName, &theSpec );
+
+ if ( (osErr = FSpGetFInfo ( &theSpec, &finderInfo ) ) != noErr )
+ break;
+ }
+
+ osErr = FSpCreate ( &theSpec, '????', '????', smSystemScript );
+ if ( osErr != noErr )
+ ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name);
+
+ osErr = FSpOpenDF ( &theSpec, fsRdWrPerm, &(info->temp_file) );
+ if ( osErr != noErr )
+ ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name);
+
+ info->tempSpec = theSpec;
+
+ info->read_backing_store = read_backing_store;
+ info->write_backing_store = write_backing_store;
+ info->close_backing_store = close_backing_store;
+ TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name);
+}
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required.
+ */
+
+GLOBAL(long)
+jpeg_mem_init (j_common_ptr cinfo)
+{
+ next_file_num = 0;
+
+ /* max_memory_to_use will be initialized to FreeMem()'s result;
+ * the calling application might later reduce it, for example
+ * to leave room to invoke multiple JPEG objects.
+ * Note that FreeMem returns the total number of free bytes;
+ * it may not be possible to allocate a single block of this size.
+ */
+ return FreeMem();
+}
+
+GLOBAL(void)
+jpeg_mem_term (j_common_ptr cinfo)
+{
+ /* no work */
+}
diff --git a/jpeg-6c/jmemmgr.c b/jpeg-6c/jmemmgr.c
new file mode 100644
index 0000000..f7ab826
--- /dev/null
+++ b/jpeg-6c/jmemmgr.c
@@ -0,0 +1,1175 @@
+/*
+ * jmemmgr.c
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the JPEG system-independent memory management
+ * routines. This code is usable across a wide variety of machines; most
+ * of the system dependencies have been isolated in a separate file.
+ * The major functions provided here are:
+ * * pool-based allocation and freeing of memory;
+ * * policy decisions about how to divide available memory among the
+ * virtual arrays;
+ * * control logic for swapping virtual arrays between main memory and
+ * backing storage.
+ * The separate system-dependent file provides the actual backing-storage
+ * access code, and it contains the policy decision about how much total
+ * main memory to use.
+ * This file is system-dependent in the sense that some of its functions
+ * are unnecessary in some systems. For example, if there is enough virtual
+ * memory so that backing storage will never be used, much of the virtual
+ * array control logic could be removed. (Of course, if you have that much
+ * memory then you shouldn't care about a little bit of unused code...)
+ */
+
+#define JPEG_INTERNALS
+#define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h" /* import the system-dependent declarations */
+
+#ifndef NO_GETENV
+#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
+extern char * getenv JPP((const char * name));
+#endif
+#endif
+
+
+/*
+ * Some important notes:
+ * The allocation routines provided here must never return NULL.
+ * They should exit to error_exit if unsuccessful.
+ *
+ * It's not a good idea to try to merge the sarray, barray and darray
+ * routines, even though they are textually almost the same, because
+ * samples are usually stored as bytes while coefficients and differenced
+ * are shorts or ints. Thus, in machines where byte pointers have a
+ * different representation from word pointers, the resulting machine
+ * code could not be the same.
+ */
+
+
+/*
+ * Many machines require storage alignment: longs must start on 4-byte
+ * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
+ * always returns pointers that are multiples of the worst-case alignment
+ * requirement, and we had better do so too.
+ * There isn't any really portable way to determine the worst-case alignment
+ * requirement. This module assumes that the alignment requirement is
+ * multiples of sizeof(ALIGN_TYPE).
+ * By default, we define ALIGN_TYPE as double. This is necessary on some
+ * workstations (where doubles really do need 8-byte alignment) and will work
+ * fine on nearly everything. If your machine has lesser alignment needs,
+ * you can save a few bytes by making ALIGN_TYPE smaller.
+ * The only place I know of where this will NOT work is certain Macintosh
+ * 680x0 compilers that define double as a 10-byte IEEE extended float.
+ * Doing 10-byte alignment is counterproductive because longwords won't be
+ * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
+ * such a compiler.
+ */
+
+#ifndef ALIGN_TYPE /* so can override from jconfig.h */
+#define ALIGN_TYPE double
+#endif
+
+
+/*
+ * We allocate objects from "pools", where each pool is gotten with a single
+ * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
+ * overhead within a pool, except for alignment padding. Each pool has a
+ * header with a link to the next pool of the same class.
+ * Small and large pool headers are identical except that the latter's
+ * link pointer must be FAR on 80x86 machines.
+ * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
+ * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
+ * of the alignment requirement of ALIGN_TYPE.
+ */
+
+typedef union small_pool_struct * small_pool_ptr;
+
+typedef union small_pool_struct {
+ struct {
+ small_pool_ptr next; /* next in list of pools */
+ size_t bytes_used; /* how many bytes already used within pool */
+ size_t bytes_left; /* bytes still available in this pool */
+ } hdr;
+ ALIGN_TYPE dummy; /* included in union to ensure alignment */
+} small_pool_hdr;
+
+typedef union large_pool_struct FAR * large_pool_ptr;
+
+typedef union large_pool_struct {
+ struct {
+ large_pool_ptr next; /* next in list of pools */
+ size_t bytes_used; /* how many bytes already used within pool */
+ size_t bytes_left; /* bytes still available in this pool */
+ } hdr;
+ ALIGN_TYPE dummy; /* included in union to ensure alignment */
+} large_pool_hdr;
+
+
+/*
+ * Here is the full definition of a memory manager object.
+ */
+
+typedef struct {
+ struct jpeg_memory_mgr pub; /* public fields */
+
+ /* Each pool identifier (lifetime class) names a linked list of pools. */
+ small_pool_ptr small_list[JPOOL_NUMPOOLS];
+ large_pool_ptr large_list[JPOOL_NUMPOOLS];
+
+ /* Since we only have one lifetime class of virtual arrays, only one
+ * linked list is necessary (for each datatype). Note that the virtual
+ * array control blocks being linked together are actually stored somewhere
+ * in the small-pool list.
+ */
+ jvirt_sarray_ptr virt_sarray_list;
+ jvirt_barray_ptr virt_barray_list;
+
+ /* This counts total space obtained from jpeg_get_small/large */
+ long total_space_allocated;
+
+ /* alloc_sarray and alloc_barray set this value for use by virtual
+ * array routines.
+ */
+ JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
+} my_memory_mgr;
+
+typedef my_memory_mgr * my_mem_ptr;
+
+
+/*
+ * The control blocks for virtual arrays.
+ * Note that these blocks are allocated in the "small" pool area.
+ * System-dependent info for the associated backing store (if any) is hidden
+ * inside the backing_store_info struct.
+ */
+
+struct jvirt_sarray_control {
+ JSAMPARRAY mem_buffer; /* => the in-memory buffer */
+ JDIMENSION rows_in_array; /* total virtual array height */
+ JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
+ JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
+ JDIMENSION rows_in_mem; /* height of memory buffer */
+ JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
+ JDIMENSION cur_start_row; /* first logical row # in the buffer */
+ JDIMENSION first_undef_row; /* row # of first uninitialized row */
+ boolean pre_zero; /* pre-zero mode requested? */
+ boolean dirty; /* do current buffer contents need written? */
+ boolean b_s_open; /* is backing-store data valid? */
+ jvirt_sarray_ptr next; /* link to next virtual sarray control block */
+ backing_store_info b_s_info; /* System-dependent control info */
+};
+
+struct jvirt_barray_control {
+ JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
+ JDIMENSION rows_in_array; /* total virtual array height */
+ JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
+ JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
+ JDIMENSION rows_in_mem; /* height of memory buffer */
+ JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
+ JDIMENSION cur_start_row; /* first logical row # in the buffer */
+ JDIMENSION first_undef_row; /* row # of first uninitialized row */
+ boolean pre_zero; /* pre-zero mode requested? */
+ boolean dirty; /* do current buffer contents need written? */
+ boolean b_s_open; /* is backing-store data valid? */
+ jvirt_barray_ptr next; /* link to next virtual barray control block */
+ backing_store_info b_s_info; /* System-dependent control info */
+};
+
+
+#ifdef MEM_STATS /* optional extra stuff for statistics */
+
+LOCAL(void)
+print_mem_stats (j_common_ptr cinfo, int pool_id)
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ small_pool_ptr shdr_ptr;
+ large_pool_ptr lhdr_ptr;
+
+ /* Since this is only a debugging stub, we can cheat a little by using
+ * fprintf directly rather than going through the trace message code.
+ * This is helpful because message parm array can't handle longs.
+ */
+ fprintf(stderr, "Freeing pool %d, total space = %ld\n",
+ pool_id, mem->total_space_allocated);
+
+ for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
+ lhdr_ptr = lhdr_ptr->hdr.next) {
+ fprintf(stderr, " Large chunk used %ld\n",
+ (long) lhdr_ptr->hdr.bytes_used);
+ }
+
+ for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
+ shdr_ptr = shdr_ptr->hdr.next) {
+ fprintf(stderr, " Small chunk used %ld free %ld\n",
+ (long) shdr_ptr->hdr.bytes_used,
+ (long) shdr_ptr->hdr.bytes_left);
+ }
+}
+
+#endif /* MEM_STATS */
+
+
+LOCAL(void)
+out_of_memory (j_common_ptr cinfo, int which)
+/* Report an out-of-memory error and stop execution */
+/* If we compiled MEM_STATS support, report alloc requests before dying */
+{
+#ifdef MEM_STATS
+ cinfo->err->trace_level = 2; /* force self_destruct to report stats */
+#endif
+ ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
+}
+
+
+/*
+ * Allocation of "small" objects.
+ *
+ * For these, we use pooled storage. When a new pool must be created,
+ * we try to get enough space for the current request plus a "slop" factor,
+ * where the slop will be the amount of leftover space in the new pool.
+ * The speed vs. space tradeoff is largely determined by the slop values.
+ * A different slop value is provided for each pool class (lifetime),
+ * and we also distinguish the first pool of a class from later ones.
+ * NOTE: the values given work fairly well on both 16- and 32-bit-int
+ * machines, but may be too small if longs are 64 bits or more.
+ */
+
+static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
+{
+ 1600, /* first PERMANENT pool */
+ 16000 /* first IMAGE pool */
+};
+
+static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
+{
+ 0, /* additional PERMANENT pools */
+ 5000 /* additional IMAGE pools */
+};
+
+#define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
+
+
+METHODDEF(void *)
+alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
+/* Allocate a "small" object */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ small_pool_ptr hdr_ptr, prev_hdr_ptr;
+ char * data_ptr;
+ size_t odd_bytes, min_request, slop;
+
+ /* Check for unsatisfiable request (do now to ensure no overflow below) */
+ if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
+ out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
+
+ /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
+ odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
+ if (odd_bytes > 0)
+ sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
+
+ /* See if space is available in any existing pool */
+ if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+ prev_hdr_ptr = NULL;
+ hdr_ptr = mem->small_list[pool_id];
+ while (hdr_ptr != NULL) {
+ if (hdr_ptr->hdr.bytes_left >= sizeofobject)
+ break; /* found pool with enough space */
+ prev_hdr_ptr = hdr_ptr;
+ hdr_ptr = hdr_ptr->hdr.next;
+ }
+
+ /* Time to make a new pool? */
+ if (hdr_ptr == NULL) {
+ /* min_request is what we need now, slop is what will be leftover */
+ min_request = sizeofobject + SIZEOF(small_pool_hdr);
+ if (prev_hdr_ptr == NULL) /* first pool in class? */
+ slop = first_pool_slop[pool_id];
+ else
+ slop = extra_pool_slop[pool_id];
+ /* Don't ask for more than MAX_ALLOC_CHUNK */
+ if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
+ slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
+ /* Try to get space, if fail reduce slop and try again */
+ for (;;) {
+ hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
+ if (hdr_ptr != NULL)
+ break;
+ slop /= 2;
+ if (slop < MIN_SLOP) /* give up when it gets real small */
+ out_of_memory(cinfo, 2); /* jpeg_get_small failed */
+ }
+ mem->total_space_allocated += min_request + slop;
+ /* Success, initialize the new pool header and add to end of list */
+ hdr_ptr->hdr.next = NULL;
+ hdr_ptr->hdr.bytes_used = 0;
+ hdr_ptr->hdr.bytes_left = sizeofobject + slop;
+ if (prev_hdr_ptr == NULL) /* first pool in class? */
+ mem->small_list[pool_id] = hdr_ptr;
+ else
+ prev_hdr_ptr->hdr.next = hdr_ptr;
+ }
+
+ /* OK, allocate the object from the current pool */
+ data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
+ data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
+ hdr_ptr->hdr.bytes_used += sizeofobject;
+ hdr_ptr->hdr.bytes_left -= sizeofobject;
+
+ return (void *) data_ptr;
+}
+
+
+/*
+ * Allocation of "large" objects.
+ *
+ * The external semantics of these are the same as "small" objects,
+ * except that FAR pointers are used on 80x86. However the pool
+ * management heuristics are quite different. We assume that each
+ * request is large enough that it may as well be passed directly to
+ * jpeg_get_large; the pool management just links everything together
+ * so that we can free it all on demand.
+ * Note: the major use of "large" objects is in JSAMPARRAY16 and JBLOCKARRAY
+ * structures. The routines that create these structures (see below)
+ * deliberately bunch rows together to ensure a large request size.
+ */
+
+METHODDEF(void FAR *)
+alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
+/* Allocate a "large" object */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ large_pool_ptr hdr_ptr;
+ size_t odd_bytes;
+
+ /* Check for unsatisfiable request (do now to ensure no overflow below) */
+ if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
+ out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
+
+ /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
+ odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
+ if (odd_bytes > 0)
+ sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
+
+ /* Always make a new pool */
+ if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+
+ hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
+ SIZEOF(large_pool_hdr));
+ if (hdr_ptr == NULL)
+ out_of_memory(cinfo, 4); /* jpeg_get_large failed */
+ mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
+
+ /* Success, initialize the new pool header and add to list */
+ hdr_ptr->hdr.next = mem->large_list[pool_id];
+ /* We maintain space counts in each pool header for statistical purposes,
+ * even though they are not needed for allocation.
+ */
+ hdr_ptr->hdr.bytes_used = sizeofobject;
+ hdr_ptr->hdr.bytes_left = 0;
+ mem->large_list[pool_id] = hdr_ptr;
+
+ return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
+}
+
+
+/*
+ * Creation of 2-D sample arrays.
+ * The pointers are in near heap, the samples themselves in FAR heap.
+ *
+ * To minimize allocation overhead and to allow I/O of large contiguous
+ * blocks, we allocate the sample rows in groups of as many rows as possible
+ * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
+ * NB: the virtual array control routines, later in this file, know about
+ * this chunking of rows. The rowsperchunk value is left in the mem manager
+ * object so that it can be saved away if this sarray is the workspace for
+ * a virtual array.
+ */
+
+METHODDEF(JSAMPARRAY)
+alloc_sarray (j_common_ptr cinfo, int pool_id,
+ JDIMENSION samplesperrow, JDIMENSION numrows)
+/* Allocate a 2-D sample array */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ JSAMPARRAY result;
+ JSAMPROW workspace;
+ JDIMENSION rowsperchunk, currow, i;
+ long ltemp;
+
+ /* Calculate max # of rows allowed in one allocation chunk */
+ ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
+ ((long) samplesperrow * SIZEOF(JSAMPLE));
+ if (ltemp <= 0)
+ ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
+ if (ltemp < (long) numrows)
+ rowsperchunk = (JDIMENSION) ltemp;
+ else
+ rowsperchunk = numrows;
+ mem->last_rowsperchunk = rowsperchunk;
+
+ /* Get space for row pointers (small object) */
+ result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
+ (size_t) (numrows * SIZEOF(JSAMPROW)));
+
+ /* Get the rows themselves (large objects) */
+ currow = 0;
+ while (currow < numrows) {
+ rowsperchunk = MIN(rowsperchunk, numrows - currow);
+ workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
+ (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
+ * SIZEOF(JSAMPLE)));
+ for (i = rowsperchunk; i > 0; i--) {
+ result[currow++] = workspace;
+ workspace += samplesperrow;
+ }
+ }
+
+ return result;
+}
+
+
+/*
+ * Creation of 2-D coefficient-block arrays.
+ * This is essentially the same as the code for sample arrays, above.
+ */
+
+METHODDEF(JBLOCKARRAY)
+alloc_barray (j_common_ptr cinfo, int pool_id,
+ JDIMENSION blocksperrow, JDIMENSION numrows)
+/* Allocate a 2-D coefficient-block array */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ JBLOCKARRAY result;
+ JBLOCKROW workspace;
+ JDIMENSION rowsperchunk, currow, i;
+ long ltemp;
+
+ /* Calculate max # of rows allowed in one allocation chunk */
+ ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
+ ((long) blocksperrow * SIZEOF(JBLOCK));
+ if (ltemp <= 0)
+ ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
+ if (ltemp < (long) numrows)
+ rowsperchunk = (JDIMENSION) ltemp;
+ else
+ rowsperchunk = numrows;
+ mem->last_rowsperchunk = rowsperchunk;
+
+ /* Get space for row pointers (small object) */
+ result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
+ (size_t) (numrows * SIZEOF(JBLOCKROW)));
+
+ /* Get the rows themselves (large objects) */
+ currow = 0;
+ while (currow < numrows) {
+ rowsperchunk = MIN(rowsperchunk, numrows - currow);
+ workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
+ (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
+ * SIZEOF(JBLOCK)));
+ for (i = rowsperchunk; i > 0; i--) {
+ result[currow++] = workspace;
+ workspace += blocksperrow;
+ }
+ }
+
+ return result;
+}
+
+
+#ifdef NEED_DARRAY
+
+/*
+ * Creation of 2-D difference arrays.
+ * This is essentially the same as the code for sample arrays, above.
+ */
+
+METHODDEF(JDIFFARRAY)
+alloc_darray (j_common_ptr cinfo, int pool_id,
+ JDIMENSION diffsperrow, JDIMENSION numrows)
+/* Allocate a 2-D difference array */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ JDIFFARRAY result;
+ JDIFFROW workspace;
+ JDIMENSION rowsperchunk, currow, i;
+ long ltemp;
+
+ /* Calculate max # of rows allowed in one allocation chunk */
+ ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
+ ((long) diffsperrow * SIZEOF(JDIFF));
+ if (ltemp <= 0)
+ ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
+ if (ltemp < (long) numrows)
+ rowsperchunk = (JDIMENSION) ltemp;
+ else
+ rowsperchunk = numrows;
+ mem->last_rowsperchunk = rowsperchunk;
+
+ /* Get space for row pointers (small object) */
+ result = (JDIFFARRAY) alloc_small(cinfo, pool_id,
+ (size_t) (numrows * SIZEOF(JDIFFROW)));
+
+ /* Get the rows themselves (large objects) */
+ currow = 0;
+ while (currow < numrows) {
+ rowsperchunk = MIN(rowsperchunk, numrows - currow);
+ workspace = (JDIFFROW) alloc_large(cinfo, pool_id,
+ (size_t) ((size_t) rowsperchunk * (size_t) diffsperrow
+ * SIZEOF(JDIFF)));
+ for (i = rowsperchunk; i > 0; i--) {
+ result[currow++] = workspace;
+ workspace += diffsperrow;
+ }
+ }
+
+ return result;
+}
+
+#endif
+
+
+/*
+ * About virtual array management:
+ *
+ * The above "normal" array routines are only used to allocate strip buffers
+ * (as wide as the image, but just a few rows high). Full-image-sized buffers
+ * are handled as "virtual" arrays. The array is still accessed a strip at a
+ * time, but the memory manager must save the whole array for repeated
+ * accesses. The intended implementation is that there is a strip buffer in
+ * memory (as high as is possible given the desired memory limit), plus a
+ * backing file that holds the rest of the array.
+ *
+ * The request_virt_array routines are told the total size of the image and
+ * the maximum number of rows that will be accessed at once. The in-memory
+ * buffer must be at least as large as the maxaccess value.
+ *
+ * The request routines create control blocks but not the in-memory buffers.
+ * That is postponed until realize_virt_arrays is called. At that time the
+ * total amount of space needed is known (approximately, anyway), so free
+ * memory can be divided up fairly.
+ *
+ * The access_virt_array routines are responsible for making a specific strip
+ * area accessible (after reading or writing the backing file, if necessary).
+ * Note that the access routines are told whether the caller intends to modify
+ * the accessed strip; during a read-only pass this saves having to rewrite
+ * data to disk. The access routines are also responsible for pre-zeroing
+ * any newly accessed rows, if pre-zeroing was requested.
+ *
+ * In current usage, the access requests are usually for nonoverlapping
+ * strips; that is, successive access start_row numbers differ by exactly
+ * num_rows = maxaccess. This means we can get good performance with simple
+ * buffer dump/reload logic, by making the in-memory buffer be a multiple
+ * of the access height; then there will never be accesses across bufferload
+ * boundaries. The code will still work with overlapping access requests,
+ * but it doesn't handle bufferload overlaps very efficiently.
+ */
+
+
+METHODDEF(jvirt_sarray_ptr)
+request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
+ JDIMENSION samplesperrow, JDIMENSION numrows,
+ JDIMENSION maxaccess)
+/* Request a virtual 2-D sample array */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ jvirt_sarray_ptr result;
+
+ /* Only IMAGE-lifetime virtual arrays are currently supported */
+ if (pool_id != JPOOL_IMAGE)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+
+ /* get control block */
+ result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
+ SIZEOF(struct jvirt_sarray_control));
+
+ result->mem_buffer = NULL; /* marks array not yet realized */
+ result->rows_in_array = numrows;
+ result->samplesperrow = samplesperrow;
+ result->maxaccess = maxaccess;
+ result->pre_zero = pre_zero;
+ result->b_s_open = FALSE; /* no associated backing-store object */
+ result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
+ mem->virt_sarray_list = result;
+
+ return result;
+}
+
+
+METHODDEF(jvirt_barray_ptr)
+request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
+ JDIMENSION blocksperrow, JDIMENSION numrows,
+ JDIMENSION maxaccess)
+/* Request a virtual 2-D coefficient-block array */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ jvirt_barray_ptr result;
+
+ /* Only IMAGE-lifetime virtual arrays are currently supported */
+ if (pool_id != JPOOL_IMAGE)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+
+ /* get control block */
+ result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
+ SIZEOF(struct jvirt_barray_control));
+
+ result->mem_buffer = NULL; /* marks array not yet realized */
+ result->rows_in_array = numrows;
+ result->blocksperrow = blocksperrow;
+ result->maxaccess = maxaccess;
+ result->pre_zero = pre_zero;
+ result->b_s_open = FALSE; /* no associated backing-store object */
+ result->next = mem->virt_barray_list; /* add to list of virtual arrays */
+ mem->virt_barray_list = result;
+
+ return result;
+}
+
+
+METHODDEF(void)
+realize_virt_arrays (j_common_ptr cinfo)
+/* Allocate the in-memory buffers for any unrealized virtual arrays */
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ long space_per_minheight, maximum_space, avail_mem;
+ long minheights, max_minheights;
+ jvirt_sarray_ptr sptr;
+ jvirt_barray_ptr bptr;
+
+ /* Compute the minimum space needed (maxaccess rows in each buffer)
+ * and the maximum space needed (full image height in each buffer).
+ * These may be of use to the system-dependent jpeg_mem_available routine.
+ */
+ space_per_minheight = 0;
+ maximum_space = 0;
+ for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
+ if (sptr->mem_buffer == NULL) { /* if not realized yet */
+ space_per_minheight += (long) sptr->maxaccess *
+ (long) sptr->samplesperrow * SIZEOF(JSAMPLE16);
+ maximum_space += (long) sptr->rows_in_array *
+ (long) sptr->samplesperrow * SIZEOF(JSAMPLE16);
+ }
+ }
+ for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
+ if (bptr->mem_buffer == NULL) { /* if not realized yet */
+ space_per_minheight += (long) bptr->maxaccess *
+ (long) bptr->blocksperrow * SIZEOF(JBLOCK);
+ maximum_space += (long) bptr->rows_in_array *
+ (long) bptr->blocksperrow * SIZEOF(JBLOCK);
+ }
+ }
+
+ if (space_per_minheight <= 0)
+ return; /* no unrealized arrays, no work */
+
+ /* Determine amount of memory to actually use; this is system-dependent. */
+ avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
+ mem->total_space_allocated);
+
+ /* If the maximum space needed is available, make all the buffers full
+ * height; otherwise parcel it out with the same number of minheights
+ * in each buffer.
+ */
+ if (avail_mem >= maximum_space)
+ max_minheights = 1000000000L;
+ else {
+ max_minheights = avail_mem / space_per_minheight;
+ /* If there doesn't seem to be enough space, try to get the minimum
+ * anyway. This allows a "stub" implementation of jpeg_mem_available().
+ */
+ if (max_minheights <= 0)
+ max_minheights = 1;
+ }
+
+ /* Allocate the in-memory buffers and initialize backing store as needed. */
+
+ for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
+ if (sptr->mem_buffer == NULL) { /* if not realized yet */
+ minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
+ if (minheights <= max_minheights) {
+ /* This buffer fits in memory */
+ sptr->rows_in_mem = sptr->rows_in_array;
+ } else {
+ /* It doesn't fit in memory, create backing store. */
+ sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
+ jpeg_open_backing_store(cinfo, & sptr->b_s_info,
+ (long) sptr->rows_in_array *
+ (long) sptr->samplesperrow *
+ (long) SIZEOF(JSAMPLE16));
+ sptr->b_s_open = TRUE;
+ }
+ sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
+ sptr->samplesperrow, sptr->rows_in_mem);
+ sptr->rowsperchunk = mem->last_rowsperchunk;
+ sptr->cur_start_row = 0;
+ sptr->first_undef_row = 0;
+ sptr->dirty = FALSE;
+ }
+ }
+
+ for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
+ if (bptr->mem_buffer == NULL) { /* if not realized yet */
+ minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
+ if (minheights <= max_minheights) {
+ /* This buffer fits in memory */
+ bptr->rows_in_mem = bptr->rows_in_array;
+ } else {
+ /* It doesn't fit in memory, create backing store. */
+ bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
+ jpeg_open_backing_store(cinfo, & bptr->b_s_info,
+ (long) bptr->rows_in_array *
+ (long) bptr->blocksperrow *
+ (long) SIZEOF(JBLOCK));
+ bptr->b_s_open = TRUE;
+ }
+ bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
+ bptr->blocksperrow, bptr->rows_in_mem);
+ bptr->rowsperchunk = mem->last_rowsperchunk;
+ bptr->cur_start_row = 0;
+ bptr->first_undef_row = 0;
+ bptr->dirty = FALSE;
+ }
+ }
+}
+
+
+LOCAL(void)
+do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
+/* Do backing store read or write of a virtual sample array */
+{
+ long bytesperrow, file_offset, byte_count, rows, thisrow, i;
+
+ bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE16);
+ file_offset = ptr->cur_start_row * bytesperrow;
+ /* Loop to read or write each allocation chunk in mem_buffer */
+ for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
+ /* One chunk, but check for short chunk at end of buffer */
+ rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
+ /* Transfer no more than is currently defined */
+ thisrow = (long) ptr->cur_start_row + i;
+ rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
+ /* Transfer no more than fits in file */
+ rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
+ if (rows <= 0) /* this chunk might be past end of file! */
+ break;
+ byte_count = rows * bytesperrow;
+ if (writing)
+ (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
+ (void FAR *) ptr->mem_buffer[i],
+ file_offset, byte_count);
+ else
+ (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
+ (void FAR *) ptr->mem_buffer[i],
+ file_offset, byte_count);
+ file_offset += byte_count;
+ }
+}
+
+
+LOCAL(void)
+do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
+/* Do backing store read or write of a virtual coefficient-block array */
+{
+ long bytesperrow, file_offset, byte_count, rows, thisrow, i;
+
+ bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
+ file_offset = ptr->cur_start_row * bytesperrow;
+ /* Loop to read or write each allocation chunk in mem_buffer */
+ for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
+ /* One chunk, but check for short chunk at end of buffer */
+ rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
+ /* Transfer no more than is currently defined */
+ thisrow = (long) ptr->cur_start_row + i;
+ rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
+ /* Transfer no more than fits in file */
+ rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
+ if (rows <= 0) /* this chunk might be past end of file! */
+ break;
+ byte_count = rows * bytesperrow;
+ if (writing)
+ (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
+ (void FAR *) ptr->mem_buffer[i],
+ file_offset, byte_count);
+ else
+ (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
+ (void FAR *) ptr->mem_buffer[i],
+ file_offset, byte_count);
+ file_offset += byte_count;
+ }
+}
+
+
+METHODDEF(JSAMPARRAY)
+access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
+ JDIMENSION start_row, JDIMENSION num_rows,
+ boolean writable)
+/* Access the part of a virtual sample array starting at start_row */
+/* and extending for num_rows rows. writable is true if */
+/* caller intends to modify the accessed area. */
+{
+ JDIMENSION end_row = start_row + num_rows;
+ JDIMENSION undef_row;
+
+ /* debugging check */
+ if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
+ ptr->mem_buffer == NULL)
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+
+ /* Make the desired part of the virtual array accessible */
+ if (start_row < ptr->cur_start_row ||
+ end_row > ptr->cur_start_row+ptr->rows_in_mem) {
+ if (! ptr->b_s_open)
+ ERREXIT(cinfo, JERR_VIRTUAL_BUG);
+ /* Flush old buffer contents if necessary */
+ if (ptr->dirty) {
+ do_sarray_io(cinfo, ptr, TRUE);
+ ptr->dirty = FALSE;
+ }
+ /* Decide what part of virtual array to access.
+ * Algorithm: if target address > current window, assume forward scan,
+ * load starting at target address. If target address < current window,
+ * assume backward scan, load so that target area is top of window.
+ * Note that when switching from forward write to forward read, will have
+ * start_row = 0, so the limiting case applies and we load from 0 anyway.
+ */
+ if (start_row > ptr->cur_start_row) {
+ ptr->cur_start_row = start_row;
+ } else {
+ /* use long arithmetic here to avoid overflow & unsigned problems */
+ long ltemp;
+
+ ltemp = (long) end_row - (long) ptr->rows_in_mem;
+ if (ltemp < 0)
+ ltemp = 0; /* don't fall off front end of file */
+ ptr->cur_start_row = (JDIMENSION) ltemp;
+ }
+ /* Read in the selected part of the array.
+ * During the initial write pass, we will do no actual read
+ * because the selected part is all undefined.
+ */
+ do_sarray_io(cinfo, ptr, FALSE);
+ }
+ /* Ensure the accessed part of the array is defined; prezero if needed.
+ * To improve locality of access, we only prezero the part of the array
+ * that the caller is about to access, not the entire in-memory array.
+ */
+ if (ptr->first_undef_row < end_row) {
+ if (ptr->first_undef_row < start_row) {
+ if (writable) /* writer skipped over a section of array */
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+ undef_row = start_row; /* but reader is allowed to read ahead */
+ } else {
+ undef_row = ptr->first_undef_row;
+ }
+ if (writable)
+ ptr->first_undef_row = end_row;
+ if (ptr->pre_zero) {
+ size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE16);
+ undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
+ end_row -= ptr->cur_start_row;
+ while (undef_row < end_row) {
+ jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
+ undef_row++;
+ }
+ } else {
+ if (! writable) /* reader looking at undefined data */
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+ }
+ }
+ /* Flag the buffer dirty if caller will write in it */
+ if (writable)
+ ptr->dirty = TRUE;
+ /* Return address of proper part of the buffer */
+ return ptr->mem_buffer + (start_row - ptr->cur_start_row);
+}
+
+
+METHODDEF(JBLOCKARRAY)
+access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
+ JDIMENSION start_row, JDIMENSION num_rows,
+ boolean writable)
+/* Access the part of a virtual block array starting at start_row */
+/* and extending for num_rows rows. writable is true if */
+/* caller intends to modify the accessed area. */
+{
+ JDIMENSION end_row = start_row + num_rows;
+ JDIMENSION undef_row;
+
+ /* debugging check */
+ if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
+ ptr->mem_buffer == NULL)
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+
+ /* Make the desired part of the virtual array accessible */
+ if (start_row < ptr->cur_start_row ||
+ end_row > ptr->cur_start_row+ptr->rows_in_mem) {
+ if (! ptr->b_s_open)
+ ERREXIT(cinfo, JERR_VIRTUAL_BUG);
+ /* Flush old buffer contents if necessary */
+ if (ptr->dirty) {
+ do_barray_io(cinfo, ptr, TRUE);
+ ptr->dirty = FALSE;
+ }
+ /* Decide what part of virtual array to access.
+ * Algorithm: if target address > current window, assume forward scan,
+ * load starting at target address. If target address < current window,
+ * assume backward scan, load so that target area is top of window.
+ * Note that when switching from forward write to forward read, will have
+ * start_row = 0, so the limiting case applies and we load from 0 anyway.
+ */
+ if (start_row > ptr->cur_start_row) {
+ ptr->cur_start_row = start_row;
+ } else {
+ /* use long arithmetic here to avoid overflow & unsigned problems */
+ long ltemp;
+
+ ltemp = (long) end_row - (long) ptr->rows_in_mem;
+ if (ltemp < 0)
+ ltemp = 0; /* don't fall off front end of file */
+ ptr->cur_start_row = (JDIMENSION) ltemp;
+ }
+ /* Read in the selected part of the array.
+ * During the initial write pass, we will do no actual read
+ * because the selected part is all undefined.
+ */
+ do_barray_io(cinfo, ptr, FALSE);
+ }
+ /* Ensure the accessed part of the array is defined; prezero if needed.
+ * To improve locality of access, we only prezero the part of the array
+ * that the caller is about to access, not the entire in-memory array.
+ */
+ if (ptr->first_undef_row < end_row) {
+ if (ptr->first_undef_row < start_row) {
+ if (writable) /* writer skipped over a section of array */
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+ undef_row = start_row; /* but reader is allowed to read ahead */
+ } else {
+ undef_row = ptr->first_undef_row;
+ }
+ if (writable)
+ ptr->first_undef_row = end_row;
+ if (ptr->pre_zero) {
+ size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
+ undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
+ end_row -= ptr->cur_start_row;
+ while (undef_row < end_row) {
+ jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
+ undef_row++;
+ }
+ } else {
+ if (! writable) /* reader looking at undefined data */
+ ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
+ }
+ }
+ /* Flag the buffer dirty if caller will write in it */
+ if (writable)
+ ptr->dirty = TRUE;
+ /* Return address of proper part of the buffer */
+ return ptr->mem_buffer + (start_row - ptr->cur_start_row);
+}
+
+
+/*
+ * Release all objects belonging to a specified pool.
+ */
+
+METHODDEF(void)
+free_pool (j_common_ptr cinfo, int pool_id)
+{
+ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
+ small_pool_ptr shdr_ptr;
+ large_pool_ptr lhdr_ptr;
+ size_t space_freed;
+
+ if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
+ ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
+
+#ifdef MEM_STATS
+ if (cinfo->err->trace_level > 1)
+ print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
+#endif
+
+ /* If freeing IMAGE pool, close any virtual arrays first */
+ if (pool_id == JPOOL_IMAGE) {
+ jvirt_sarray_ptr sptr;
+ jvirt_barray_ptr bptr;
+
+ for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
+ if (sptr->b_s_open) { /* there may be no backing store */
+ sptr->b_s_open = FALSE; /* prevent recursive close if error */
+ (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
+ }
+ }
+ mem->virt_sarray_list = NULL;
+ for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
+ if (bptr->b_s_open) { /* there may be no backing store */
+ bptr->b_s_open = FALSE; /* prevent recursive close if error */
+ (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
+ }
+ }
+ mem->virt_barray_list = NULL;
+ }
+
+ /* Release large objects */
+ lhdr_ptr = mem->large_list[pool_id];
+ mem->large_list[pool_id] = NULL;
+
+ while (lhdr_ptr != NULL) {
+ large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
+ space_freed = lhdr_ptr->hdr.bytes_used +
+ lhdr_ptr->hdr.bytes_left +
+ SIZEOF(large_pool_hdr);
+ jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
+ mem->total_space_allocated -= space_freed;
+ lhdr_ptr = next_lhdr_ptr;
+ }
+
+ /* Release small objects */
+ shdr_ptr = mem->small_list[pool_id];
+ mem->small_list[pool_id] = NULL;
+
+ while (shdr_ptr != NULL) {
+ small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
+ space_freed = shdr_ptr->hdr.bytes_used +
+ shdr_ptr->hdr.bytes_left +
+ SIZEOF(small_pool_hdr);
+ jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
+ mem->total_space_allocated -= space_freed;
+ shdr_ptr = next_shdr_ptr;
+ }
+}
+
+
+/*
+ * Close up shop entirely.
+ * Note that this cannot be called unless cinfo->mem is non-NULL.
+ */
+
+METHODDEF(void)
+self_destruct (j_common_ptr cinfo)
+{
+ int pool;
+
+ /* Close all backing store, release all memory.
+ * Releasing pools in reverse order might help avoid fragmentation
+ * with some (brain-damaged) malloc libraries.
+ */
+ for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
+ free_pool(cinfo, pool);
+ }
+
+ /* Release the memory manager control block too. */
+ jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
+ cinfo->mem = NULL; /* ensures I will be called only once */
+
+ jpeg_mem_term(cinfo); /* system-dependent cleanup */
+}
+
+
+/*
+ * Memory manager initialization.
+ * When this is called, only the error manager pointer is valid in cinfo!
+ */
+
+GLOBAL(void)
+jinit_memory_mgr (j_common_ptr cinfo)
+{
+ my_mem_ptr mem;
+ long max_to_use;
+ int pool;
+ size_t test_mac;
+
+ cinfo->mem = NULL; /* for safety if init fails */
+
+ /* Check for configuration errors.
+ * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
+ * doesn't reflect any real hardware alignment requirement.
+ * The test is a little tricky: for X>0, X and X-1 have no one-bits
+ * in common if and only if X is a power of 2, ie has only one one-bit.
+ * Some compilers may give an "unreachable code" warning here; ignore it.
+ */
+ if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
+ ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
+ /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
+ * a multiple of SIZEOF(ALIGN_TYPE).
+ * Again, an "unreachable code" warning may be ignored here.
+ * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
+ */
+ test_mac = (size_t) MAX_ALLOC_CHUNK;
+ if ((long) test_mac != MAX_ALLOC_CHUNK ||
+ (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
+ ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
+
+ max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
+
+ /* Attempt to allocate memory manager's control block */
+ mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
+
+ if (mem == NULL) {
+ jpeg_mem_term(cinfo); /* system-dependent cleanup */
+ ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
+ }
+
+ /* OK, fill in the method pointers */
+ mem->pub.alloc_small = alloc_small;
+ mem->pub.alloc_large = alloc_large;
+ mem->pub.alloc_sarray = alloc_sarray;
+ mem->pub.alloc_barray = alloc_barray;
+#ifdef NEED_DARRAY
+ mem->pub.alloc_darray = alloc_darray;
+#endif
+ mem->pub.request_virt_sarray = request_virt_sarray;
+ mem->pub.request_virt_barray = request_virt_barray;
+ mem->pub.realize_virt_arrays = realize_virt_arrays;
+ mem->pub.access_virt_sarray = access_virt_sarray;
+ mem->pub.access_virt_barray = access_virt_barray;
+ mem->pub.free_pool = free_pool;
+ mem->pub.self_destruct = self_destruct;
+
+ /* Make MAX_ALLOC_CHUNK accessible to other modules */
+ mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
+
+ /* Initialize working state */
+ mem->pub.max_memory_to_use = max_to_use;
+
+ for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
+ mem->small_list[pool] = NULL;
+ mem->large_list[pool] = NULL;
+ }
+ mem->virt_sarray_list = NULL;
+ mem->virt_barray_list = NULL;
+
+ mem->total_space_allocated = SIZEOF(my_memory_mgr);
+
+ /* Declare ourselves open for business */
+ cinfo->mem = & mem->pub;
+
+ /* Check for an environment variable JPEGMEM; if found, override the
+ * default max_memory setting from jpeg_mem_init. Note that the
+ * surrounding application may again override this value.
+ * If your system doesn't support getenv(), define NO_GETENV to disable
+ * this feature.
+ */
+#ifndef NO_GETENV
+ { char * memenv;
+
+ if ((memenv = getenv("JPEGMEM")) != NULL) {
+ char ch = 'x';
+
+ if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
+ if (ch == 'm' || ch == 'M')
+ max_to_use *= 1000L;
+ mem->pub.max_memory_to_use = max_to_use * 1000L;
+ }
+ }
+ }
+#endif
+
+}
diff --git a/jpeg-6c/jmemname.c b/jpeg-6c/jmemname.c
new file mode 100644
index 0000000..ed96dee
--- /dev/null
+++ b/jpeg-6c/jmemname.c
@@ -0,0 +1,276 @@
+/*
+ * jmemname.c
+ *
+ * Copyright (C) 1992-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file provides a generic implementation of the system-dependent
+ * portion of the JPEG memory manager. This implementation assumes that
+ * you must explicitly construct a name for each temp file.
+ * Also, the problem of determining the amount of memory available
+ * is shoved onto the user.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h" /* import the system-dependent declarations */
+
+#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
+extern void * malloc JPP((size_t size));
+extern void free JPP((void *ptr));
+#endif
+
+#ifndef SEEK_SET /* pre-ANSI systems may not define this; */
+#define SEEK_SET 0 /* if not, assume 0 is correct */
+#endif
+
+#ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
+#define READ_BINARY "r"
+#define RW_BINARY "w+"
+#else
+#ifdef VMS /* VMS is very nonstandard */
+#define READ_BINARY "rb", "ctx=stm"
+#define RW_BINARY "w+b", "ctx=stm"
+#else /* standard ANSI-compliant case */
+#define READ_BINARY "rb"
+#define RW_BINARY "w+b"
+#endif
+#endif
+
+
+/*
+ * Selection of a file name for a temporary file.
+ * This is system-dependent!
+ *
+ * The code as given is suitable for most Unix systems, and it is easily
+ * modified for most non-Unix systems. Some notes:
+ * 1. The temp file is created in the directory named by TEMP_DIRECTORY.
+ * The default value is /usr/tmp, which is the conventional place for
+ * creating large temp files on Unix. On other systems you'll probably
+ * want to change the file location. You can do this by editing the
+ * #define, or (preferred) by defining TEMP_DIRECTORY in jconfig.h.
+ *
+ * 2. If you need to change the file name as well as its location,
+ * you can override the TEMP_FILE_NAME macro. (Note that this is
+ * actually a printf format string; it must contain %s and %d.)
+ * Few people should need to do this.
+ *
+ * 3. mktemp() is used to ensure that multiple processes running
+ * simultaneously won't select the same file names. If your system
+ * doesn't have mktemp(), define NO_MKTEMP to do it the hard way.
+ * (If you don't have <errno.h>, also define NO_ERRNO_H.)
+ *
+ * 4. You probably want to define NEED_SIGNAL_CATCHER so that cjpeg.c/djpeg.c
+ * will cause the temp files to be removed if you stop the program early.
+ */
+
+#ifndef TEMP_DIRECTORY /* can override from jconfig.h or Makefile */
+#define TEMP_DIRECTORY "/usr/tmp/" /* recommended setting for Unix */
+#endif
+
+static int next_file_num; /* to distinguish among several temp files */
+
+#ifdef NO_MKTEMP
+
+#ifndef TEMP_FILE_NAME /* can override from jconfig.h or Makefile */
+#define TEMP_FILE_NAME "%sJPG%03d.TMP"
+#endif
+
+#ifndef NO_ERRNO_H
+#include <errno.h> /* to define ENOENT */
+#endif
+
+/* ANSI C specifies that errno is a macro, but on older systems it's more
+ * likely to be a plain int variable. And not all versions of errno.h
+ * bother to declare it, so we have to in order to be most portable. Thus:
+ */
+#ifndef errno
+extern int errno;
+#endif
+
+
+LOCAL(void)
+select_file_name (char * fname)
+{
+ FILE * tfile;
+
+ /* Keep generating file names till we find one that's not in use */
+ for (;;) {
+ next_file_num++; /* advance counter */
+ sprintf(fname, TEMP_FILE_NAME, TEMP_DIRECTORY, next_file_num);
+ if ((tfile = fopen(fname, READ_BINARY)) == NULL) {
+ /* fopen could have failed for a reason other than the file not
+ * being there; for example, file there but unreadable.
+ * If <errno.h> isn't available, then we cannot test the cause.
+ */
+#ifdef ENOENT
+ if (errno != ENOENT)
+ continue;
+#endif
+ break;
+ }
+ fclose(tfile); /* oops, it's there; close tfile & try again */
+ }
+}
+
+#else /* ! NO_MKTEMP */
+
+/* Note that mktemp() requires the initial filename to end in six X's */
+#ifndef TEMP_FILE_NAME /* can override from jconfig.h or Makefile */
+#define TEMP_FILE_NAME "%sJPG%dXXXXXX"
+#endif
+
+LOCAL(void)
+select_file_name (char * fname)
+{
+ next_file_num++; /* advance counter */
+ sprintf(fname, TEMP_FILE_NAME, TEMP_DIRECTORY, next_file_num);
+ mktemp(fname); /* make sure file name is unique */
+ /* mktemp replaces the trailing XXXXXX with a unique string of characters */
+}
+
+#endif /* NO_MKTEMP */
+
+
+/*
+ * Memory allocation and freeing are controlled by the regular library
+ * routines malloc() and free().
+ */
+
+GLOBAL(void *)
+jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void *) malloc(sizeofobject);
+}
+
+GLOBAL(void)
+jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * "Large" objects are treated the same as "small" ones.
+ * NB: although we include FAR keywords in the routine declarations,
+ * this file won't actually work in 80x86 small/medium model; at least,
+ * you probably won't be able to process useful-size images in only 64KB.
+ */
+
+GLOBAL(void FAR *)
+jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void FAR *) malloc(sizeofobject);
+}
+
+GLOBAL(void)
+jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * This routine computes the total memory space available for allocation.
+ * It's impossible to do this in a portable way; our current solution is
+ * to make the user tell us (with a default value set at compile time).
+ * If you can actually get the available space, it's a good idea to subtract
+ * a slop factor of 5% or so.
+ */
+
+#ifndef DEFAULT_MAX_MEM /* so can override from makefile */
+#define DEFAULT_MAX_MEM 1000000L /* default: one megabyte */
+#endif
+
+GLOBAL(long)
+jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
+ long max_bytes_needed, long already_allocated)
+{
+ return cinfo->mem->max_memory_to_use - already_allocated;
+}
+
+
+/*
+ * Backing store (temporary file) management.
+ * Backing store objects are only used when the value returned by
+ * jpeg_mem_available is less than the total space needed. You can dispense
+ * with these routines if you have plenty of virtual memory; see jmemnobs.c.
+ */
+
+
+METHODDEF(void)
+read_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ if (fseek(info->temp_file, file_offset, SEEK_SET))
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+ if (JFREAD(info->temp_file, buffer_address, byte_count)
+ != (size_t) byte_count)
+ ERREXIT(cinfo, JERR_TFILE_READ);
+}
+
+
+METHODDEF(void)
+write_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count)
+{
+ if (fseek(info->temp_file, file_offset, SEEK_SET))
+ ERREXIT(cinfo, JERR_TFILE_SEEK);
+ if (JFWRITE(info->temp_file, buffer_address, byte_count)
+ != (size_t) byte_count)
+ ERREXIT(cinfo, JERR_TFILE_WRITE);
+}
+
+
+METHODDEF(void)
+close_backing_store (j_common_ptr cinfo, backing_store_ptr info)
+{
+ fclose(info->temp_file); /* close the file */
+ unlink(info->temp_name); /* delete the file */
+/* If your system doesn't have unlink(), use remove() instead.
+ * remove() is the ANSI-standard name for this function, but if
+ * your system was ANSI you'd be using jmemansi.c, right?
+ */
+ TRACEMSS(cinfo, 1, JTRC_TFILE_CLOSE, info->temp_name);
+}
+
+
+/*
+ * Initial opening of a backing-store object.
+ */
+
+GLOBAL(void)
+jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ select_file_name(info->temp_name);
+ if ((info->temp_file = fopen(info->temp_name, RW_BINARY)) == NULL)
+ ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name);
+ info->read_backing_store = read_backing_store;
+ info->write_backing_store = write_backing_store;
+ info->close_backing_store = close_backing_store;
+ TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name);
+}
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required.
+ */
+
+GLOBAL(long)
+jpeg_mem_init (j_common_ptr cinfo)
+{
+ next_file_num = 0; /* initialize temp file name generator */
+ return DEFAULT_MAX_MEM; /* default for max_memory_to_use */
+}
+
+GLOBAL(void)
+jpeg_mem_term (j_common_ptr cinfo)
+{
+ /* no work */
+}
diff --git a/jpeg-6c/jmemnobs.c b/jpeg-6c/jmemnobs.c
new file mode 100644
index 0000000..eb8c337
--- /dev/null
+++ b/jpeg-6c/jmemnobs.c
@@ -0,0 +1,109 @@
+/*
+ * jmemnobs.c
+ *
+ * Copyright (C) 1992-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file provides a really simple implementation of the system-
+ * dependent portion of the JPEG memory manager. This implementation
+ * assumes that no backing-store files are needed: all required space
+ * can be obtained from malloc().
+ * This is very portable in the sense that it'll compile on almost anything,
+ * but you'd better have lots of main memory (or virtual memory) if you want
+ * to process big images.
+ * Note that the max_memory_to_use option is ignored by this implementation.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h" /* import the system-dependent declarations */
+
+#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
+extern void * malloc JPP((size_t size));
+extern void free JPP((void *ptr));
+#endif
+
+
+/*
+ * Memory allocation and freeing are controlled by the regular library
+ * routines malloc() and free().
+ */
+
+GLOBAL(void *)
+jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void *) malloc(sizeofobject);
+}
+
+GLOBAL(void)
+jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * "Large" objects are treated the same as "small" ones.
+ * NB: although we include FAR keywords in the routine declarations,
+ * this file won't actually work in 80x86 small/medium model; at least,
+ * you probably won't be able to process useful-size images in only 64KB.
+ */
+
+GLOBAL(void FAR *)
+jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
+{
+ return (void FAR *) malloc(sizeofobject);
+}
+
+GLOBAL(void)
+jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
+{
+ free(object);
+}
+
+
+/*
+ * This routine computes the total memory space available for allocation.
+ * Here we always say, "we got all you want bud!"
+ */
+
+GLOBAL(long)
+jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
+ long max_bytes_needed, long already_allocated)
+{
+ return max_bytes_needed;
+}
+
+
+/*
+ * Backing store (temporary file) management.
+ * Since jpeg_mem_available always promised the moon,
+ * this should never be called and we can just error out.
+ */
+
+GLOBAL(void)
+jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
+ long total_bytes_needed)
+{
+ ERREXIT(cinfo, JERR_NO_BACKING_STORE);
+}
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required. Here, there isn't any.
+ */
+
+GLOBAL(long)
+jpeg_mem_init (j_common_ptr cinfo)
+{
+ return 0; /* just set max_memory_to_use to 0 */
+}
+
+GLOBAL(void)
+jpeg_mem_term (j_common_ptr cinfo)
+{
+ /* no work */
+}
diff --git a/jpeg-6c/jmemsys.h b/jpeg-6c/jmemsys.h
new file mode 100644
index 0000000..6c3c6d3
--- /dev/null
+++ b/jpeg-6c/jmemsys.h
@@ -0,0 +1,198 @@
+/*
+ * jmemsys.h
+ *
+ * Copyright (C) 1992-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This include file defines the interface between the system-independent
+ * and system-dependent portions of the JPEG memory manager. No other
+ * modules need include it. (The system-independent portion is jmemmgr.c;
+ * there are several different versions of the system-dependent portion.)
+ *
+ * This file works as-is for the system-dependent memory managers supplied
+ * in the IJG distribution. You may need to modify it if you write a
+ * custom memory manager. If system-dependent changes are needed in
+ * this file, the best method is to #ifdef them based on a configuration
+ * symbol supplied in jconfig.h, as we have done with USE_MSDOS_MEMMGR
+ * and USE_MAC_MEMMGR.
+ */
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_get_small jGetSmall
+#define jpeg_free_small jFreeSmall
+#define jpeg_get_large jGetLarge
+#define jpeg_free_large jFreeLarge
+#define jpeg_mem_available jMemAvail
+#define jpeg_open_backing_store jOpenBackStore
+#define jpeg_mem_init jMemInit
+#define jpeg_mem_term jMemTerm
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/*
+ * These two functions are used to allocate and release small chunks of
+ * memory. (Typically the total amount requested through jpeg_get_small is
+ * no more than 20K or so; this will be requested in chunks of a few K each.)
+ * Behavior should be the same as for the standard library functions malloc
+ * and free; in particular, jpeg_get_small must return NULL on failure.
+ * On most systems, these ARE malloc and free. jpeg_free_small is passed the
+ * size of the object being freed, just in case it's needed.
+ * On an 80x86 machine using small-data memory model, these manage near heap.
+ */
+
+EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
+EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
+ size_t sizeofobject));
+
+/*
+ * These two functions are used to allocate and release large chunks of
+ * memory (up to the total free space designated by jpeg_mem_available).
+ * The interface is the same as above, except that on an 80x86 machine,
+ * far pointers are used. On most other machines these are identical to
+ * the jpeg_get/free_small routines; but we keep them separate anyway,
+ * in case a different allocation strategy is desirable for large chunks.
+ */
+
+EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
+ size_t sizeofobject));
+EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
+ size_t sizeofobject));
+
+/*
+ * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
+ * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
+ * matter, but that case should never come into play). This macro is needed
+ * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
+ * On those machines, we expect that jconfig.h will provide a proper value.
+ * On machines with 32-bit flat address spaces, any large constant may be used.
+ *
+ * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
+ * size_t and will be a multiple of sizeof(align_type).
+ */
+
+#ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
+#define MAX_ALLOC_CHUNK 1000000000L
+#endif
+
+/*
+ * This routine computes the total space still available for allocation by
+ * jpeg_get_large. If more space than this is needed, backing store will be
+ * used. NOTE: any memory already allocated must not be counted.
+ *
+ * There is a minimum space requirement, corresponding to the minimum
+ * feasible buffer sizes; jmemmgr.c will request that much space even if
+ * jpeg_mem_available returns zero. The maximum space needed, enough to hold
+ * all working storage in memory, is also passed in case it is useful.
+ * Finally, the total space already allocated is passed. If no better
+ * method is available, cinfo->mem->max_memory_to_use - already_allocated
+ * is often a suitable calculation.
+ *
+ * It is OK for jpeg_mem_available to underestimate the space available
+ * (that'll just lead to more backing-store access than is really necessary).
+ * However, an overestimate will lead to failure. Hence it's wise to subtract
+ * a slop factor from the true available space. 5% should be enough.
+ *
+ * On machines with lots of virtual memory, any large constant may be returned.
+ * Conversely, zero may be returned to always use the minimum amount of memory.
+ */
+
+EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
+ long min_bytes_needed,
+ long max_bytes_needed,
+ long already_allocated));
+
+
+/*
+ * This structure holds whatever state is needed to access a single
+ * backing-store object. The read/write/close method pointers are called
+ * by jmemmgr.c to manipulate the backing-store object; all other fields
+ * are private to the system-dependent backing store routines.
+ */
+
+#define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
+
+
+#ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
+
+typedef unsigned short XMSH; /* type of extended-memory handles */
+typedef unsigned short EMSH; /* type of expanded-memory handles */
+
+typedef union {
+ short file_handle; /* DOS file handle if it's a temp file */
+ XMSH xms_handle; /* handle if it's a chunk of XMS */
+ EMSH ems_handle; /* handle if it's a chunk of EMS */
+} handle_union;
+
+#endif /* USE_MSDOS_MEMMGR */
+
+#ifdef USE_MAC_MEMMGR /* Mac-specific junk */
+#include <Files.h>
+#endif /* USE_MAC_MEMMGR */
+
+
+typedef struct backing_store_struct * backing_store_ptr;
+
+typedef struct backing_store_struct {
+ /* Methods for reading/writing/closing this backing-store object */
+ JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
+ backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count));
+ JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
+ backing_store_ptr info,
+ void FAR * buffer_address,
+ long file_offset, long byte_count));
+ JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
+ backing_store_ptr info));
+
+ /* Private fields for system-dependent backing-store management */
+#ifdef USE_MSDOS_MEMMGR
+ /* For the MS-DOS manager (jmemdos.c), we need: */
+ handle_union handle; /* reference to backing-store storage object */
+ char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
+#else
+#ifdef USE_MAC_MEMMGR
+ /* For the Mac manager (jmemmac.c), we need: */
+ short temp_file; /* file reference number to temp file */
+ FSSpec tempSpec; /* the FSSpec for the temp file */
+ char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
+#else
+ /* For a typical implementation with temp files, we need: */
+ FILE * temp_file; /* stdio reference to temp file */
+ char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
+#endif
+#endif
+} backing_store_info;
+
+
+/*
+ * Initial opening of a backing-store object. This must fill in the
+ * read/write/close pointers in the object. The read/write routines
+ * may take an error exit if the specified maximum file size is exceeded.
+ * (If jpeg_mem_available always returns a large value, this routine can
+ * just take an error exit.)
+ */
+
+EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
+ backing_store_ptr info,
+ long total_bytes_needed));
+
+
+/*
+ * These routines take care of any system-dependent initialization and
+ * cleanup required. jpeg_mem_init will be called before anything is
+ * allocated (and, therefore, nothing in cinfo is of use except the error
+ * manager pointer). It should return a suitable default value for
+ * max_memory_to_use; this may subsequently be overridden by the surrounding
+ * application. (Note that max_memory_to_use is only important if
+ * jpeg_mem_available chooses to consult it ... no one else will.)
+ * jpeg_mem_term may assume that all requested memory has been freed and that
+ * all opened backing-store objects have been closed.
+ */
+
+EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
+EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
diff --git a/jpeg-6c/jmorecfg.h b/jpeg-6c/jmorecfg.h
new file mode 100644
index 0000000..1afa68e
--- /dev/null
+++ b/jpeg-6c/jmorecfg.h
@@ -0,0 +1,407 @@
+/*
+ * jmorecfg.h
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains additional configuration options that customize the
+ * JPEG software for special applications or support machine-dependent
+ * optimizations. Most users will not need to touch this file.
+ */
+
+
+/*
+ * Define BITS_IN_JSAMPLE as either
+ * 8 for 8-bit sample values (the usual setting)
+ * 12 for 12-bit sample values
+ * Only 8 and 12 are legal data precisions for lossy JPEG according to the
+ * JPEG standard, and the IJG code does not support anything else!
+ * We do not support run-time selection of data precision, sorry.
+ */
+
+#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
+/* Now is 16 for defines and cinfo->data_precision or
+ * cinfo->data_precision_other for data values,
+ * but is left at 8 for compatibility. */
+
+/*
+ * Maximum number of components (color channels) allowed in JPEG image.
+ * To meet the letter of the JPEG spec, set this to 255. However, darn
+ * few applications need more than 4 channels (maybe 5 for CMYK + alpha
+ * mask). We recommend 10 as a reasonable compromise; use 4 if you are
+ * really short on memory. (Each allowed component costs a hundred or so
+ * bytes of storage, whether actually used in an image or not.)
+ */
+
+#define MAX_COMPONENTS 10 /* maximum number of image components */
+
+
+/*
+ * Basic data types.
+ * You may need to change these if you have a machine with unusual data
+ * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
+ * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
+ * but it had better be at least 16.
+ */
+
+/* Representation of a single sample (pixel element value).
+ * We frequently allocate large arrays of these, so it's important to keep
+ * them small. But if you have memory to burn and access to char or short
+ * arrays is very slow on your hardware, you might want to change these.
+ */
+
+/*#if BITS_IN_JSAMPLE == 8*/
+/* JSAMPLE should be the smallest type that will hold the values 0..255.
+ * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
+ */
+
+#ifdef HAVE_UNSIGNED_CHAR
+
+typedef unsigned char JSAMPLE;
+/*#define GETJSAMPLE(value) ((int) (value))*/
+
+#else /* not HAVE_UNSIGNED_CHAR */
+
+typedef char JSAMPLE;
+/*#ifdef CHAR_IS_UNSIGNED
+#define GETJSAMPLE(value) ((int) (value))
+#else
+#define GETJSAMPLE(value) ((int) (value) & 0xFF)
+#endif*/ /* CHAR_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_CHAR */
+
+/*#define MAXJSAMPLE 255
+#define CENTERJSAMPLE 128
+
+#endif*/ /* BITS_IN_JSAMPLE == 8 */
+
+
+/*#if BITS_IN_JSAMPLE == 12*/
+/* JSAMPLE should be the smallest type that will hold the values 0..4095.
+ * On nearly all machines "short" will do nicely.
+ */
+
+/*typedef short JSAMPLE;
+#define GETJSAMPLE(value) ((int) (value))
+
+#define MAXJSAMPLE 4095
+#define CENTERJSAMPLE 2048
+
+#endif*/ /* BITS_IN_JSAMPLE == 12 */
+
+
+/*#if BITS_IN_JSAMPLE == 16*/
+/* JSAMPLE16 should be the smallest type that will hold the values 0..65535.
+ * You can use a signed short by having GETJSAMPLE mask it with 0xFFFF.
+ */
+/* Always 16 now. 0xFFFF is now mask ( 0xFF, 0xFFF or 0xFFFF )*/
+/* Added 12 bit mask, may not be needed. */
+#ifdef HAVE_UNSIGNED_SHORT
+
+typedef unsigned short JSAMPLE16;
+#define GETJSAMPLE(value) ((int) (value))
+
+#else /* not HAVE_UNSIGNED_SHORT */
+
+typedef short JSAMPLE16;
+#ifdef SHORT_IS_UNSIGNED
+#define GETJSAMPLE(value) ((int) (value))
+#else
+#define GETJSAMPLE(value) ((int) (value) & cinfo->maskjsample)
+#define HAVE_GETJSAMPLE_MASK 1
+#endif /* SHORT_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_SHORT */
+
+#define JSAMPLEMAX 16 /* Maximum bits in JSAMPLE16 */
+
+/*#define MAXJSAMPLE 65535
+#define CENTERJSAMPLE 32768
+
+#endif*/ /* BITS_IN_JSAMPLE == 16 */
+
+
+/* Representation of a DCT frequency coefficient.
+ * This should be a signed value of at least 16 bits; "short" is usually OK.
+ * Again, we allocate large arrays of these, but you can change to int
+ * if you have memory to burn and "short" is really slow.
+ */
+
+typedef short JCOEF;
+
+
+/* Representation of a spatial difference value.
+ * This should be a signed value of at least 16 bits; int is usually OK.
+ */
+
+typedef int JDIFF;
+
+
+/* Compressed datastreams are represented as arrays of JOCTET.
+ * These must be EXACTLY 8 bits wide, at least once they are written to
+ * external storage. Note that when using the stdio data source/destination
+ * managers, this is also the data type passed to fread/fwrite.
+ */
+
+#ifdef HAVE_UNSIGNED_CHAR
+
+typedef unsigned char JOCTET;
+#define GETJOCTET(value) (value)
+
+#else /* not HAVE_UNSIGNED_CHAR */
+
+typedef char JOCTET;
+#ifdef CHAR_IS_UNSIGNED
+#define GETJOCTET(value) (value)
+#else
+#define GETJOCTET(value) ((value) & 0xFF)
+#endif /* CHAR_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_CHAR */
+
+
+/* These typedefs are used for various table entries and so forth.
+ * They must be at least as wide as specified; but making them too big
+ * won't cost a huge amount of memory, so we don't provide special
+ * extraction code like we did for JSAMPLE. (In other words, these
+ * typedefs live at a different point on the speed/space tradeoff curve.)
+ */
+
+/* UINT8 must hold at least the values 0..255. */
+
+#ifdef HAVE_UNSIGNED_CHAR
+typedef unsigned char UINT8;
+#else /* not HAVE_UNSIGNED_CHAR */
+#ifdef CHAR_IS_UNSIGNED
+typedef char UINT8;
+#else /* not CHAR_IS_UNSIGNED */
+typedef short UINT8;
+#endif /* CHAR_IS_UNSIGNED */
+#endif /* HAVE_UNSIGNED_CHAR */
+
+/* UINT16 must hold at least the values 0..65535. */
+
+#ifdef HAVE_UNSIGNED_SHORT
+typedef unsigned short UINT16;
+#else /* not HAVE_UNSIGNED_SHORT */
+typedef unsigned int UINT16;
+#endif /* HAVE_UNSIGNED_SHORT */
+
+/* INT16 must hold at least the values -32768..32767. */
+
+#ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
+typedef short INT16;
+#endif
+
+/* INT32 must hold at least signed 32-bit values. */
+
+#ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
+typedef int INT32; /* mvh 20100125 changed long to int */
+#endif
+
+/* Datatype used for image dimensions. The JPEG standard only supports
+ * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
+ * "unsigned int" is sufficient on all machines. However, if you need to
+ * handle larger images and you don't mind deviating from the spec, you
+ * can change this datatype.
+ */
+
+typedef unsigned int JDIMENSION;
+
+#define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
+
+
+/* These macros are used in all function definitions and extern declarations.
+ * You could modify them if you need to change function linkage conventions;
+ * in particular, you'll need to do that to make the library a Windows DLL.
+ * Another application is to make all functions global for use with debuggers
+ * or code profilers that require it.
+ */
+
+/* a function called through method pointers: */
+#define METHODDEF(type) static type
+/* a function used only in its module: */
+#define LOCAL(type) static type
+/* a function referenced thru EXTERNs: */
+#define GLOBAL(type) type
+/* a reference to a GLOBAL function: */
+#define EXTERN(type) extern type
+
+
+/* This macro is used to declare a "method", that is, a function pointer.
+ * We want to supply prototype parameters if the compiler can cope.
+ * Note that the arglist parameter must be parenthesized!
+ * Again, you can customize this if you need special linkage keywords.
+ */
+
+#ifdef HAVE_PROTOTYPES
+#define JMETHOD(type,methodname,arglist) type (*methodname) arglist
+#else
+#define JMETHOD(type,methodname,arglist) type (*methodname) ()
+#endif
+
+
+/* Here is the pseudo-keyword for declaring pointers that must be "far"
+ * on 80x86 machines. Most of the specialized coding for 80x86 is handled
+ * by just saying "FAR *" where such a pointer is needed. In a few places
+ * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
+ */
+
+#ifdef NEED_FAR_POINTERS
+#define FAR far
+#else
+#define FAR
+#endif
+
+
+/*
+ * On a few systems, type boolean and/or its values FALSE, TRUE may appear
+ * in standard header files. Or you may have conflicts with application-
+ * specific header files that you want to include together with these files.
+ * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
+ */
+
+#ifndef HAVE_BOOLEAN
+typedef int boolean;
+#endif
+#ifndef FALSE /* in case these macros already exist */
+#define FALSE 0 /* values of boolean */
+#endif
+#ifndef TRUE
+#define TRUE 1
+#endif
+
+
+/*
+ * The remaining options affect code selection within the JPEG library,
+ * but they don't need to be visible to most applications using the library.
+ * To minimize application namespace pollution, the symbols won't be
+ * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
+ */
+
+#ifdef JPEG_INTERNALS
+#define JPEG_INTERNAL_OPTIONS
+#endif
+
+#ifdef JPEG_INTERNAL_OPTIONS
+
+
+/*
+ * These defines indicate whether to include various optional functions.
+ * Undefining some of these symbols will produce a smaller but less capable
+ * library. Note that you can leave certain source files out of the
+ * compilation/linking process if you've #undef'd the corresponding symbols.
+ * (You may HAVE to do that if your compiler doesn't like null source files.)
+ */
+
+/* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
+
+/* Capability options common to encoder and decoder: */
+
+#define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
+#define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
+#define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
+
+/* Encoder capability options: */
+
+#undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
+#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
+#define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
+#define C_LOSSLESS_SUPPORTED /* Lossless JPEG? */
+#define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
+/* Note: if you selected 12-bit data precision, it is dangerous to turn off
+ * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
+ * precision, so jcshuff.c normally uses entropy optimization to compute
+ * usable tables for higher precision. If you don't want to do optimization,
+ * you'll have to supply different default Huffman tables.
+ * The exact same statements apply for progressive and lossless JPEG:
+ * the default tables don't work for progressive mode or lossless mode.
+ * (This may get fixed, however.)
+ */
+#define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
+
+/* Decoder capability options: */
+
+#undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
+#define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
+#define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
+#define D_LOSSLESS_SUPPORTED /* Lossless JPEG? */
+#define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
+#define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
+#define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
+#undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
+#define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
+#define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
+#define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
+
+/* more capability options later, no doubt */
+
+
+/*
+ * Ordering of RGB data in scanlines passed to or from the application.
+ * If your application wants to deal with data in the order B,G,R, just
+ * change these macros. You can also deal with formats such as R,G,B,X
+ * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
+ * the offsets will also change the order in which colormap data is organized.
+ * RESTRICTIONS:
+ * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
+ * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
+ * useful if you are using JPEG color spaces other than YCbCr or grayscale.
+ * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
+ * is not 3 (they don't understand about dummy color components!). So you
+ * can't use color quantization if you change that value.
+ */
+
+#define RGB_RED 0 /* Offset of Red in an RGB scanline element */
+#define RGB_GREEN 1 /* Offset of Green */
+#define RGB_BLUE 2 /* Offset of Blue */
+#define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
+
+
+/* Definitions for speed-related optimizations. */
+
+
+/* If your compiler supports inline functions, define INLINE
+ * as the inline keyword; otherwise define it as empty.
+ */
+
+#ifndef INLINE
+#ifdef __GNUC__ /* for instance, GNU C knows about inline */
+#define INLINE __inline__
+#endif
+#ifndef INLINE
+#define INLINE /* default is to define it as empty */
+#endif
+#endif
+
+
+/* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
+ * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
+ * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
+ */
+
+#ifndef MULTIPLIER
+#define MULTIPLIER int /* type for fastest integer multiply */
+#endif
+
+
+/* FAST_FLOAT should be either float or double, whichever is done faster
+ * by your compiler. (Note that this type is only used in the floating point
+ * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
+ * Typically, float is faster in ANSI C compilers, while double is faster in
+ * pre-ANSI compilers (because they insist on converting to double anyway).
+ * The code below therefore chooses float if we have ANSI-style prototypes.
+ */
+
+#ifndef FAST_FLOAT
+#ifdef HAVE_PROTOTYPES
+#define FAST_FLOAT float
+#else
+#define FAST_FLOAT double
+#endif
+#endif
+
+#endif /* JPEG_INTERNAL_OPTIONS */
diff --git a/jpeg-6c/jpegint.h b/jpeg-6c/jpegint.h
new file mode 100644
index 0000000..18c8d0b
--- /dev/null
+++ b/jpeg-6c/jpegint.h
@@ -0,0 +1,363 @@
+/*
+ * jpegint.h
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file provides common declarations for the various JPEG modules.
+ * These declarations are considered internal to the JPEG library; most
+ * applications using the library shouldn't need to include this file.
+ */
+
+
+/* Declarations for both compression & decompression */
+
+typedef enum { /* Operating modes for buffer controllers */
+ JBUF_PASS_THRU, /* Plain stripwise operation */
+ /* Remaining modes require a full-image buffer to have been created */
+ JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
+ JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
+ JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
+} J_BUF_MODE;
+
+/* Values of global_state field (jdapi.c has some dependencies on ordering!) */
+#define CSTATE_START 100 /* after create_compress */
+#define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
+#define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
+#define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
+#define DSTATE_START 200 /* after create_decompress */
+#define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
+#define DSTATE_READY 202 /* found SOS, ready for start_decompress */
+#define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
+#define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
+#define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
+#define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
+#define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
+#define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
+#define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
+#define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
+
+
+/* Declarations for compression modules */
+
+/* Master control module */
+struct jpeg_comp_master {
+ JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
+ JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
+ JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
+
+ /* State variables made visible to other modules */
+ boolean call_pass_startup; /* True if pass_startup must be called */
+ boolean is_last_pass; /* True during last pass */
+};
+
+/* Main buffer control (downsampled-data buffer) */
+struct jpeg_c_main_controller {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(void, process_data, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail));
+};
+
+/* Compression preprocessing (downsampling input buffer control) */
+struct jpeg_c_prep_controller {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf,
+ JDIMENSION *in_row_ctr,
+ JDIMENSION in_rows_avail,
+ JSAMPIMAGE16 output_buf,
+ JDIMENSION *out_row_group_ctr,
+ JDIMENSION out_row_groups_avail));
+};
+
+/* Compression codec (compressor proper) */
+struct jpeg_c_codec {
+ JMETHOD(void, entropy_start_pass, (j_compress_ptr cinfo,
+ boolean gather_statistics));
+ JMETHOD(void, entropy_finish_pass, (j_compress_ptr cinfo));
+ JMETHOD(boolean, need_optimization_pass, (j_compress_ptr cinfo));
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
+ JSAMPIMAGE16 input_buf));
+};
+
+/* Colorspace conversion */
+struct jpeg_color_converter {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo));
+ JMETHOD(void, color_convert, (j_compress_ptr cinfo,
+ JSAMPARRAY input_buf, JSAMPIMAGE16 output_buf,
+ JDIMENSION output_row, int num_rows));
+};
+
+/* Downsampling */
+struct jpeg_downsampler {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo));
+ JMETHOD(void, downsample, (j_compress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION in_row_index,
+ JSAMPIMAGE16 output_buf,
+ JDIMENSION out_row_group_index));
+
+ boolean need_context_rows; /* TRUE if need rows above & below */
+};
+
+/* Marker writing */
+struct jpeg_marker_writer {
+ JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
+ JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
+ JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
+ JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
+ JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
+ /* These routines are exported to allow insertion of extra markers */
+ /* Probably only COM and APPn markers should be written this way */
+ JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
+ unsigned int datalen));
+ JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
+};
+
+
+/* Declarations for decompression modules */
+
+/* Master control module */
+struct jpeg_decomp_master {
+ JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
+
+ /* State variables made visible to other modules */
+ boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
+};
+
+/* Input control module */
+struct jpeg_input_controller {
+ JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
+ JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
+ JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
+
+ /* State variables made visible to other modules */
+ boolean has_multiple_scans; /* True if file has multiple scans */
+ boolean eoi_reached; /* True when EOI has been consumed */
+};
+
+/* Main buffer control (downsampled-data buffer) */
+struct jpeg_d_main_controller {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(void, process_data, (j_decompress_ptr cinfo,
+ JSAMPARRAY16 output_buf, JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+};
+
+/* Decompression codec (decompressor proper) */
+struct jpeg_d_codec {
+ JMETHOD(void, calc_output_dimensions, (j_decompress_ptr cinfo));
+ JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
+ JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
+ JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
+ JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 output_buf));
+};
+
+/* Decompression postprocessing (color quantization buffer control) */
+struct jpeg_d_post_controller {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf,
+ JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY16 output_buf,
+ JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+};
+
+/* Marker reading & parsing */
+struct jpeg_marker_reader {
+ JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
+ /* Read markers until SOS or EOI.
+ * Returns same codes as are defined for jpeg_consume_input:
+ * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
+ */
+ JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
+ /* Read a restart marker --- exported for use by entropy decoder only */
+ jpeg_marker_parser_method read_restart_marker;
+
+ /* State of marker reader --- nominally internal, but applications
+ * supplying COM or APPn handlers might like to know the state.
+ */
+ boolean saw_SOI; /* found SOI? */
+ boolean saw_SOF; /* found SOF? */
+ int next_restart_num; /* next restart number expected (0-7) */
+ unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
+};
+
+/* Upsampling (note that upsampler must also call color converter) */
+struct jpeg_upsampler {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, upsample, (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf,
+ JDIMENSION *in_row_group_ctr,
+ JDIMENSION in_row_groups_avail,
+ JSAMPARRAY16 output_buf,
+ JDIMENSION *out_row_ctr,
+ JDIMENSION out_rows_avail));
+
+ boolean need_context_rows; /* TRUE if need rows above & below */
+};
+
+/* Colorspace conversion */
+struct jpeg_color_deconverter {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
+ JSAMPIMAGE16 input_buf, JDIMENSION input_row,
+ JSAMPARRAY16 output_buf, int num_rows));
+};
+
+/* Color quantization or color precision reduction */
+struct jpeg_color_quantizer {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
+ JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
+ JSAMPARRAY16 input_buf, JSAMPARRAY16 output_buf,
+ int num_rows));
+ JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
+ JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
+};
+
+
+/* Miscellaneous useful macros */
+
+#undef MAX
+#define MAX(a,b) ((a) > (b) ? (a) : (b))
+#undef MIN
+#define MIN(a,b) ((a) < (b) ? (a) : (b))
+
+
+/* We assume that right shift corresponds to signed division by 2 with
+ * rounding towards minus infinity. This is correct for typical "arithmetic
+ * shift" instructions that shift in copies of the sign bit. But some
+ * C compilers implement >> with an unsigned shift. For these machines you
+ * must define RIGHT_SHIFT_IS_UNSIGNED.
+ * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
+ * It is only applied with constant shift counts. SHIFT_TEMPS must be
+ * included in the variables of any routine using RIGHT_SHIFT.
+ */
+
+#ifdef RIGHT_SHIFT_IS_UNSIGNED
+#define SHIFT_TEMPS INT32 shift_temp;
+#define RIGHT_SHIFT(x,shft) \
+ ((shift_temp = (x)) < 0 ? \
+ (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
+ (shift_temp >> (shft)))
+#else
+#define SHIFT_TEMPS
+#define RIGHT_SHIFT(x,shft) ((x) >> (shft))
+#endif
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jinit_c_codec jICCodec
+#define jinit_lossy_c_codec jILossyC
+#define jinit_compress_master jICompress
+#define jinit_c_master_control jICMaster
+#define jinit_c_main_controller jICMainC
+#define jinit_c_prep_controller jICPrepC
+#define jinit_c_coef_controller jICCoefC
+#define jinit_color_converter jICColor
+#define jinit_downsampler jIDownsampler
+#define jinit_forward_dct jIFDCT
+#define jinit_shuff_encoder jISHEncoder
+#define jinit_phuff_encoder jIPHEncoder
+#define jinit_marker_writer jIMWriter
+#define jinit_d_codec jIDCodec
+#define jinit_lossy_d_codec jILossyD
+#define jinit_lossless_d_codec jILosslsD
+#define jinit_master_decompress jIDMaster
+#define jinit_d_main_controller jIDMainC
+#define jinit_d_coef_controller jIDCoefC
+#define jinit_d_diff_controller jIDDiffC
+#define jinit_d_post_controller jIDPostC
+#define jinit_input_controller jIInCtlr
+#define jinit_marker_reader jIMReader
+#define jinit_shuff_decoder jISHDecoder
+#define jinit_phuff_decoder jIPHDecoder
+#define jinit_lhuff_decoder jILHDecoder
+#define jinit_undifferencer jIUndiff
+#define jinit_d_scaler jIDScaler
+#define jinit_inverse_dct jIIDCT
+#define jinit_upsampler jIUpsampler
+#define jinit_color_deconverter jIDColor
+#define jinit_1pass_quantizer jI1Quant
+#define jinit_2pass_quantizer jI2Quant
+#define jinit_merged_upsampler jIMUpsampler
+#define jinit_memory_mgr jIMemMgr
+#define jdiv_round_up jDivRound
+#define jround_up jRound
+#define jcopy_sample_rows jCopySamples
+#define jcopy_block_row jCopyBlocks
+#define jzero_far jZeroFar
+#define jpeg_zigzag_order jZIGTable
+#define jpeg_natural_order jZAGTable
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/* Compression module initialization routines */
+EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
+ boolean transcode_only));
+EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN(void) jinit_compressor JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
+/* Decompression module initialization routines */
+EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN(void) jinit_decompressor JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
+ boolean need_full_buffer));
+EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
+EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
+/* Memory manager initialization */
+EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
+
+/* Utility routines in jutils.c */
+EXTERN(long) jdiv_round_up JPP((long a, long b));
+EXTERN(long) jround_up JPP((long a, long b));
+EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY16 input_array, int source_row,
+ JSAMPARRAY16 output_array, int dest_row,
+ int num_rows, JDIMENSION num_cols));
+EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
+ JDIMENSION num_blocks));
+EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
+/* Constant tables in jutils.c */
+#if 0 /* This table is not actually needed in v6a */
+extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
+#endif
+extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
+
+/* Other routines added to stop GCC4.1 warnings */
+/* Other routines in jcodec.c */
+EXTERN(void) jinit_c_codec JPP((j_compress_ptr cinfo));
+EXTERN(void) jinit_d_codec JPP((j_decompress_ptr cinfo));
+/* Other routines in jcdiffct.c */
+EXTERN(void) jinit_c_diff_controller JPP((j_compress_ptr cinfo, boolean need_full_buffer));
+
+/* Suppress undefined-structure complaints if necessary. */
+
+#ifdef INCOMPLETE_TYPES_BROKEN
+#ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
+struct jvirt_sarray_control { long dummy; };
+struct jvirt_barray_control { long dummy; };
+#endif
+#endif /* INCOMPLETE_TYPES_BROKEN */
diff --git a/jpeg-6c/jpeglib.h b/jpeg-6c/jpeglib.h
new file mode 100644
index 0000000..2907fcd
--- /dev/null
+++ b/jpeg-6c/jpeglib.h
@@ -0,0 +1,1162 @@
+/*
+ * jpeglib.h
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file defines the application interface for the JPEG library.
+ * Most applications using the library need only include this file,
+ * and perhaps jerror.h if they want to know the exact error codes.
+ */
+
+#ifndef JPEGLIB_H
+#define JPEGLIB_H
+
+/*
+ * First we include the configuration files that record how this
+ * installation of the JPEG library is set up. jconfig.h can be
+ * generated automatically for many systems. jmorecfg.h contains
+ * manual configuration options that most people need not worry about.
+ */
+
+#ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
+#include "jconfig.h" /* widely used configuration options */
+#endif
+#include "jmorecfg.h" /* seldom changed options */
+
+
+/* Version ID for the JPEG library.
+ * Might be useful for tests like "#if JPEG_LIB_VERSION >= 70".
+ */
+
+#define JPEG_LIB_VERSION 63 /* Version 6c */
+
+
+/* Various constants determining the sizes of things.
+ * All of these are specified by the JPEG standard, so don't change them
+ * if you want to be compatible.
+ */
+
+#define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
+#define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
+#define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
+#define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
+#define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
+#define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
+#define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
+/* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
+ * the PostScript DCT filter can emit files with many more than 10 data units
+ * per MCU.
+ * If you happen to run across such a file, you can up D_MAX_DATA_UNITS_IN_MCU
+ * to handle it. We even let you do this from the jconfig.h file. However,
+ * we strongly discourage changing C_MAX_DATA_UNITS_IN_MCU; just because Adobe
+ * sometimes emits noncompliant files doesn't mean you should too.
+ */
+#define C_MAX_DATA_UNITS_IN_MCU 10 /* compressor's limit on data units/MCU */
+#ifndef D_MAX_DATA_UNITS_IN_MCU
+#define D_MAX_DATA_UNITS_IN_MCU 10 /* decompressor's limit on data units/MCU */
+#endif
+
+
+/* Data structures for images (arrays of samples and of DCT coefficients).
+ * On 80x86 machines, the image arrays are too big for near pointers,
+ * but the pointer arrays can fit in near memory.
+ */
+
+typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
+typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
+typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
+typedef JSAMPLE16 FAR *JSAMPROW16; /* ptr to one image row of pixel samples. */
+typedef JSAMPROW16 *JSAMPARRAY16; /* ptr to some rows (a 2-D sample array) */
+typedef JSAMPARRAY16 *JSAMPIMAGE16; /* a 3-D sample array: top index is color */
+
+typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
+typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
+typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
+typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
+
+typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
+
+typedef JDIFF FAR *JDIFFROW; /* pointer to one row of difference values */
+typedef JDIFFROW *JDIFFARRAY; /* ptr to some rows (a 2-D diff array) */
+typedef JDIFFARRAY *JDIFFIMAGE; /* a 3-D diff array: top index is color */
+
+
+/* Types for JPEG compression parameters and working tables. */
+
+
+/* DCT coefficient quantization tables. */
+
+typedef struct {
+ /* This array gives the coefficient quantizers in natural array order
+ * (not the zigzag order in which they are stored in a JPEG DQT marker).
+ * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
+ */
+ UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
+ /* This field is used only during compression. It's initialized FALSE when
+ * the table is created, and set TRUE when it's been output to the file.
+ * You could suppress output of a table by setting this to TRUE.
+ * (See jpeg_suppress_tables for an example.)
+ */
+ boolean sent_table; /* TRUE when table has been output */
+} JQUANT_TBL;
+
+
+/* Huffman coding tables. */
+
+typedef struct {
+ /* These two fields directly represent the contents of a JPEG DHT marker */
+ UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
+ /* length k bits; bits[0] is unused */
+ UINT8 huffval[256]; /* The symbols, in order of incr code length */
+ /* This field is used only during compression. It's initialized FALSE when
+ * the table is created, and set TRUE when it's been output to the file.
+ * You could suppress output of a table by setting this to TRUE.
+ * (See jpeg_suppress_tables for an example.)
+ */
+ boolean sent_table; /* TRUE when table has been output */
+} JHUFF_TBL;
+
+
+/* Basic info about one component (color channel). */
+
+typedef struct {
+ /* These values are fixed over the whole image. */
+ /* For compression, they must be supplied by parameter setup; */
+ /* for decompression, they are read from the SOF marker. */
+ int component_id; /* identifier for this component (0..255) */
+ int component_index; /* its index in SOF or cinfo->comp_info[] */
+ int h_samp_factor; /* horizontal sampling factor (1..4) */
+ int v_samp_factor; /* vertical sampling factor (1..4) */
+ int quant_tbl_no; /* quantization table selector (0..3) */
+ /* These values may vary between scans. */
+ /* For compression, they must be supplied by parameter setup; */
+ /* for decompression, they are read from the SOS marker. */
+ /* The decompressor output side may not use these variables. */
+ int dc_tbl_no; /* DC entropy table selector (0..3) */
+ int ac_tbl_no; /* AC entropy table selector (0..3) */
+
+ /* Remaining fields should be treated as private by applications. */
+
+ /* These values are computed during compression or decompression startup: */
+ /* Component's size in data units.
+ * Any dummy data units added to complete an MCU are not counted; therefore
+ * these values do not depend on whether a scan is interleaved or not.
+ */
+ JDIMENSION width_in_data_units;
+ JDIMENSION height_in_data_units;
+ /* Size of a data unit in/output by the codec (in samples). Always
+ * data_unit for compression. For decompression this is the size of the
+ * output from one data_unit, reflecting any processing performed by the
+ * codec. For example, in the DCT-based codec, scaling may be applied
+ * during the IDCT step. Values of 1,2,4,8 are likely to be supported.
+ * Note that different components may have different codec_data_unit sizes.
+ */
+ int codec_data_unit;
+ /* The downsampled dimensions are the component's actual, unpadded number
+ * of samples at the main buffer (preprocessing/compression interface), thus
+ * downsampled_width = ceil(image_width * Hi/Hmax)
+ * and similarly for height. For decompression, codec-based processing is
+ * included (ie, IDCT scaling), so
+ * downsampled_width = ceil(image_width * Hi/Hmax * codec_data_unit/data_unit)
+ */
+ JDIMENSION downsampled_width; /* actual width in samples */
+ JDIMENSION downsampled_height; /* actual height in samples */
+ /* This flag is used only for decompression. In cases where some of the
+ * components will be ignored (eg grayscale output from YCbCr image),
+ * we can skip most computations for the unused components.
+ */
+ boolean component_needed; /* do we need the value of this component? */
+
+ /* These values are computed before starting a scan of the component. */
+ /* The decompressor output side may not use these variables. */
+ int MCU_width; /* number of data units per MCU, horizontally */
+ int MCU_height; /* number of data units per MCU, vertically */
+ int MCU_data_units; /* MCU_width * MCU_height */
+ int MCU_sample_width; /* MCU width in samples, MCU_width*codec_data_unit */
+ int last_col_width; /* # of non-dummy data_units across in last MCU */
+ int last_row_height; /* # of non-dummy data_units down in last MCU */
+
+ /* Saved quantization table for component; NULL if none yet saved.
+ * See jdinput.c comments about the need for this information.
+ * This field is currently used only for decompression.
+ */
+ JQUANT_TBL * quant_table;
+
+ /* Private per-component storage for DCT or IDCT subsystem. */
+ void * dct_table;
+} jpeg_component_info;
+
+
+/* The script for encoding a multiple-scan file is an array of these: */
+
+typedef struct {
+ int comps_in_scan; /* number of components encoded in this scan */
+ int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
+ int Ss, Se; /* progressive JPEG spectral selection parms
+ lossless JPEG predictor select parm (Ss) */
+ int Ah, Al; /* progressive JPEG successive approx. parms
+ lossless JPEG point transform parm (Al) */
+} jpeg_scan_info;
+
+/* The decompressor can save APPn and COM markers in a list of these: */
+
+typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
+
+struct jpeg_marker_struct {
+ jpeg_saved_marker_ptr next; /* next in list, or NULL */
+ UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
+ unsigned int original_length; /* # bytes of data in the file */
+ unsigned int data_length; /* # bytes of data saved at data[] */
+ JOCTET FAR * data; /* the data contained in the marker */
+ /* the marker length word is not counted in data_length or original_length */
+};
+
+/* Known codec processes. */
+
+typedef enum {
+ JPROC_SEQUENTIAL, /* baseline/extended sequential DCT */
+ JPROC_PROGRESSIVE, /* progressive DCT */
+ JPROC_LOSSLESS /* lossless (sequential) */
+} J_CODEC_PROCESS;
+
+/* Known color spaces. */
+
+typedef enum {
+ JCS_UNKNOWN, /* error/unspecified */
+ JCS_GRAYSCALE, /* monochrome */
+ JCS_RGB, /* red/green/blue */
+ JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
+ JCS_CMYK, /* C/M/Y/K */
+ JCS_YCCK /* Y/Cb/Cr/K */
+} J_COLOR_SPACE;
+
+/* DCT/IDCT algorithm options. */
+
+typedef enum {
+ JDCT_ISLOW, /* slow but accurate integer algorithm */
+ JDCT_IFAST, /* faster, less accurate integer method */
+ JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
+} J_DCT_METHOD;
+
+#ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
+#define JDCT_DEFAULT JDCT_ISLOW
+#endif
+#ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
+#define JDCT_FASTEST JDCT_IFAST
+#endif
+
+/* Dithering options for decompression. */
+
+typedef enum {
+ JDITHER_NONE, /* no dithering */
+ JDITHER_ORDERED, /* simple ordered dither */
+ JDITHER_FS /* Floyd-Steinberg error diffusion dither */
+} J_DITHER_MODE;
+
+
+/* Common fields between JPEG compression and decompression master structs. */
+
+#define jpeg_common_fields \
+ struct jpeg_error_mgr * err; /* Error handler module */\
+ struct jpeg_memory_mgr * mem; /* Memory manager module */\
+ struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
+ void * client_data; /* Available for use by application */\
+ boolean is_decompressor; /* So common code can tell which is which */\
+ int global_state /* For checking call sequence validity */
+
+/* Routines that are to be used by both halves of the library are declared
+ * to receive a pointer to this structure. There are no actual instances of
+ * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
+ */
+struct jpeg_common_struct {
+ jpeg_common_fields; /* Fields common to both master struct types */
+ /* Additional fields follow in an actual jpeg_compress_struct or
+ * jpeg_decompress_struct. All three structs must agree on these
+ * initial fields! (This would be a lot cleaner in C++.)
+ */
+};
+
+typedef struct jpeg_common_struct * j_common_ptr;
+typedef struct jpeg_compress_struct * j_compress_ptr;
+typedef struct jpeg_decompress_struct * j_decompress_ptr;
+
+
+/* Master record for a compression instance */
+
+struct jpeg_compress_struct {
+ jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
+
+ /* Destination for compressed data */
+ struct jpeg_destination_mgr * dest;
+
+ /* Description of source image --- these fields must be filled in by
+ * outer application before starting compression. in_color_space must
+ * be correct before you can even call jpeg_set_defaults().
+ */
+
+ JDIMENSION image_width; /* input image width */
+ JDIMENSION image_height; /* input image height */
+ int input_components; /* # of color components in input image */
+ J_COLOR_SPACE in_color_space; /* colorspace of input image */
+
+ double input_gamma; /* image gamma of input image */
+
+ /* Compression parameters --- these fields must be set before calling
+ * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
+ * initialize everything to reasonable defaults, then changing anything
+ * the application specifically wants to change. That way you won't get
+ * burnt when new parameters are added. Also note that there are several
+ * helper routines to simplify changing parameters.
+ */
+
+ boolean lossless; /* TRUE=lossless encoding, FALSE=lossy */
+ boolean lossless_scaling; /* If lossless is allowed to scale */
+
+ UINT8 data_precision; /* bits of precision in jpeg image data */
+ UINT8 data_precision_other; /* bits of precision in input image data */
+ UINT16 maxjsample; /* max value of jpeg bits ( 255,4095 or 65535 ) */
+ UINT16 centerjsample; /* center value of jpeg bits ( 128,2048 or 32768 ) */
+#ifdef HAVE_GETJSAMPLE_MASK
+ UINT16 maskjsample; /* mask value of the sample */
+#endif
+
+ int num_components; /* # of color components in JPEG image */
+ J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
+
+ jpeg_component_info * comp_info;
+ /* comp_info[i] describes component that appears i'th in SOF */
+
+ JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
+ /* ptrs to coefficient quantization tables, or NULL if not defined */
+
+ JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
+ JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
+ /* ptrs to Huffman coding tables, or NULL if not defined */
+
+ UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
+ UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
+ UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
+
+ int num_scans; /* # of entries in scan_info array */
+ const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
+ /* The default value of scan_info is NULL, which causes a single-scan
+ * sequential JPEG file to be emitted. To create a multi-scan file,
+ * set num_scans and scan_info to point to an array of scan definitions.
+ */
+
+ boolean raw_data_in; /* TRUE=caller supplies downsampled data */
+ JSAMPIMAGE16 raw_data_buffer; /* 8 to 16 raw data buffer */
+ boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
+ boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
+ boolean CCIR601_sampling; /* TRUE=first samples are cosited */
+ int smoothing_factor; /* 1..100, or 0 for no input smoothing */
+ J_DCT_METHOD dct_method; /* DCT algorithm selector */
+
+ /* The restart interval can be specified in absolute MCUs by setting
+ * restart_interval, or in MCU rows by setting restart_in_rows
+ * (in which case the correct restart_interval will be figured
+ * for each scan).
+ */
+ unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
+ int restart_in_rows; /* if > 0, MCU rows per restart interval */
+
+ /* Parameters controlling emission of special markers. */
+
+ boolean write_JFIF_header; /* should a JFIF marker be written? */
+ UINT8 JFIF_major_version; /* What to write for the JFIF version number */
+ UINT8 JFIF_minor_version;
+ /* These three values are not used by the JPEG code, merely copied */
+ /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
+ /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
+ /* ratio is defined by X_density/Y_density even when density_unit=0. */
+ UINT8 density_unit; /* JFIF code for pixel size units */
+ UINT16 X_density; /* Horizontal pixel density */
+ UINT16 Y_density; /* Vertical pixel density */
+ boolean write_Adobe_marker; /* should an Adobe marker be written? */
+
+ /* State variable: index of next scanline to be written to
+ * jpeg_write_scanlines(). Application may use this to control its
+ * processing loop, e.g., "while (next_scanline < image_height)".
+ */
+
+ JDIMENSION next_scanline; /* 0 .. image_height-1 */
+
+ /* Remaining fields are known throughout compressor, but generally
+ * should not be touched by a surrounding application.
+ */
+
+ /*
+ * These fields are computed during compression startup
+ */
+ int data_unit; /* size of data unit in samples */
+ J_CODEC_PROCESS process; /* encoding process of JPEG image */
+
+ int max_h_samp_factor; /* largest h_samp_factor */
+ int max_v_samp_factor; /* largest v_samp_factor */
+
+ JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to codec */
+ /* The codec receives data in units of MCU rows as defined for fully
+ * interleaved scans (whether the JPEG file is interleaved or not).
+ * There are v_samp_factor * data_unit sample rows of each component in an
+ * "iMCU" (interleaved MCU) row.
+ */
+
+ /*
+ * These fields are valid during any one scan.
+ * They describe the components and MCUs actually appearing in the scan.
+ */
+ int comps_in_scan; /* # of JPEG components in this scan */
+ jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
+ /* *cur_comp_info[i] describes component that appears i'th in SOS */
+
+ JDIMENSION MCUs_per_row; /* # of MCUs across the image */
+ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
+
+ int data_units_in_MCU; /* # of data units per MCU */
+ int MCU_membership[C_MAX_DATA_UNITS_IN_MCU];
+ /* MCU_membership[i] is index in cur_comp_info of component owning */
+ /* i'th block in an MCU */
+
+ int Ss, Se, Ah, Al; /* progressive/lossless JPEG parameters for scan */
+
+ /*
+ * Links to compression subobjects (methods and private variables of modules)
+ */
+ struct jpeg_comp_master * master;
+ struct jpeg_c_main_controller * mainp;
+ struct jpeg_c_prep_controller * prep;
+ struct jpeg_c_codec * codec;
+ struct jpeg_marker_writer * marker;
+ struct jpeg_color_converter * cconvert;
+ struct jpeg_downsampler * downsample;
+ jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
+ int script_space_size;
+};
+
+
+/* Master record for a decompression instance */
+
+struct jpeg_decompress_struct {
+ jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
+
+ /* Source of compressed data */
+ struct jpeg_source_mgr * src;
+
+ /* Basic description of image --- filled in by jpeg_read_header(). */
+ /* Application may inspect these values to decide how to process image. */
+
+ JDIMENSION image_width; /* nominal image width (from SOF marker) */
+ JDIMENSION image_height; /* nominal image height */
+ int num_components; /* # of color components in JPEG image */
+ J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
+
+ /* Decompression processing parameters --- these fields must be set before
+ * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
+ * them to default values.
+ */
+
+ J_COLOR_SPACE out_color_space; /* colorspace for output */
+
+ unsigned int scale_num, scale_denom; /* fraction by which to scale image */
+
+ double output_gamma; /* image gamma wanted in output */
+
+ boolean buffered_image; /* TRUE=multiple output passes */
+ boolean raw_data_out; /* TRUE=downsampled data wanted */
+
+ J_DCT_METHOD dct_method; /* IDCT algorithm selector */
+ boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
+ boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
+
+ boolean quantize_colors; /* TRUE=colormapped output wanted */
+ /* the following are ignored if not quantize_colors: */
+ J_DITHER_MODE dither_mode; /* type of color dithering to use */
+ boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
+ int desired_number_of_colors; /* max # colors to use in created colormap */
+ /* these are significant only in buffered-image mode: */
+ boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
+ boolean enable_external_quant;/* enable future use of external colormap */
+ boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
+
+ /* Description of actual output image that will be returned to application.
+ * These fields are computed by jpeg_start_decompress().
+ * You can also use jpeg_calc_output_dimensions() to determine these values
+ * in advance of calling jpeg_start_decompress().
+ */
+
+ JDIMENSION output_width; /* scaled image width */
+ JDIMENSION output_height; /* scaled image height */
+ int out_color_components; /* # of color components in out_color_space */
+ int output_components; /* # of color components returned */
+ /* output_components is 1 (a colormap index) when quantizing colors;
+ * otherwise it equals out_color_components.
+ */
+ int rec_outbuf_height; /* min recommended height of scanline buffer */
+ /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
+ * high, space and time will be wasted due to unnecessary data copying.
+ * Usually rec_outbuf_height will be 1 or 2, at most 4.
+ */
+
+ /* When quantizing colors, the output colormap is described by these fields.
+ * The application can supply a colormap by setting colormap non-NULL before
+ * calling jpeg_start_decompress; otherwise a colormap is created during
+ * jpeg_start_decompress or jpeg_start_output.
+ * The map has out_color_components rows and actual_number_of_colors columns.
+ */
+ int actual_number_of_colors; /* number of entries in use */
+ JSAMPARRAY colormap; /* The color map as a 2-D pixel array of 8 bits */
+ JSAMPARRAY16 colormap16; /* The color map as a 2-D pixel array of 16 bits */
+
+ /* State variables: these variables indicate the progress of decompression.
+ * The application may examine these but must not modify them.
+ */
+
+ /* Row index of next scanline to be read from jpeg_read_scanlines().
+ * Application may use this to control its processing loop, e.g.,
+ * "while (output_scanline < output_height)".
+ */
+ JDIMENSION output_scanline; /* 0 .. output_height-1 */
+
+ /* Current input scan number and number of iMCU rows completed in scan.
+ * These indicate the progress of the decompressor input side.
+ */
+ int input_scan_number; /* Number of SOS markers seen so far */
+ JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
+
+ /* The "output scan number" is the notional scan being displayed by the
+ * output side. The decompressor will not allow output scan/row number
+ * to get ahead of input scan/row, but it can fall arbitrarily far behind.
+ */
+ int output_scan_number; /* Nominal scan number being displayed */
+ JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
+
+ /* Current progression status. coef_bits[c][i] indicates the precision
+ * with which component c's DCT coefficient i (in zigzag order) is known.
+ * It is -1 when no data has yet been received, otherwise it is the point
+ * transform (shift) value for the most recent scan of the coefficient
+ * (thus, 0 at completion of the progression).
+ * This pointer is NULL when reading a non-progressive file.
+ */
+ int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
+
+ /* Internal JPEG parameters --- the application usually need not look at
+ * these fields. Note that the decompressor output side may not use
+ * any parameters that can change between scans.
+ */
+
+ /* Quantization and Huffman tables are carried forward across input
+ * datastreams when processing abbreviated JPEG datastreams.
+ */
+
+ JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
+ /* ptrs to coefficient quantization tables, or NULL if not defined */
+
+ JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
+ JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
+ /* ptrs to Huffman coding tables, or NULL if not defined */
+
+ /* These parameters are never carried across datastreams, since they
+ * are given in SOF/SOS markers or defined to be reset by SOI.
+ */
+
+ UINT8 data_precision; /* bits of precision in jpeg image data */
+ UINT8 data_precision_other; /* bits of precision in output image data */
+ boolean buffer_size_char; /* each output pixel is char wide, default TRUE */
+ UINT16 maxjsample; /* max value of jpeg bits ( 255,4095 or 65535 ) */
+ UINT16 centerjsample; /* center value of jpeg bits ( 128,2048 or 32768 ) */
+#ifdef HAVE_GETJSAMPLE_MASK
+ UINT16 maskjsample; /* mask value of the sample */
+#endif
+ /* Used to shift data to a char. */
+ int shft;
+
+ jpeg_component_info * comp_info;
+ /* comp_info[i] describes component that appears i'th in SOF */
+
+ boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
+
+ UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
+ UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
+ UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
+
+ unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
+
+ /* These fields record data obtained from optional markers recognized by
+ * the JPEG library.
+ */
+ boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
+ /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
+ UINT8 JFIF_major_version; /* JFIF version number */
+ UINT8 JFIF_minor_version;
+ UINT8 density_unit; /* JFIF code for pixel size units */
+ UINT16 X_density; /* Horizontal pixel density */
+ UINT16 Y_density; /* Vertical pixel density */
+ boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
+ UINT8 Adobe_transform; /* Color transform code from Adobe marker */
+
+ boolean CCIR601_sampling; /* TRUE=first samples are cosited */
+
+ /* Aside from the specific data retained from APPn markers known to the
+ * library, the uninterpreted contents of any or all APPn and COM markers
+ * can be saved in a list for examination by the application.
+ */
+ jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
+
+ /* Remaining fields are known throughout decompressor, but generally
+ * should not be touched by a surrounding application.
+ */
+
+ /*
+ * These fields are computed during decompression startup
+ */
+ int data_unit; /* size of data unit in samples */
+ J_CODEC_PROCESS process; /* decoding process of JPEG image */
+
+ int max_h_samp_factor; /* largest h_samp_factor */
+ int max_v_samp_factor; /* largest v_samp_factor */
+
+ int min_codec_data_unit; /* smallest codec_data_unit of any component */
+
+ JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
+ /* The codec's input and output progress is measured in units of "iMCU"
+ * (interleaved MCU) rows. These are the same as MCU rows in fully
+ * interleaved JPEG scans, but are used whether the scan is interleaved
+ * or not. We define an iMCU row as v_samp_factor data_unit rows of each
+ * component. Therefore, the codec output contains
+ * v_samp_factor*codec_data_unit sample rows of a component per iMCU row.
+ */
+
+ JSAMPLE16 * sample_range_limit; /* table for fast range-limiting */
+
+ /*
+ * These fields are valid during any one scan.
+ * They describe the components and MCUs actually appearing in the scan.
+ * Note that the decompressor output side must not use these fields.
+ */
+ int comps_in_scan; /* # of JPEG components in this scan */
+ jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
+ /* *cur_comp_info[i] describes component that appears i'th in SOS */
+
+ JDIMENSION MCUs_per_row; /* # of MCUs across the image */
+ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
+
+ int data_units_in_MCU; /* # of data _units per MCU */
+ int MCU_membership[D_MAX_DATA_UNITS_IN_MCU];
+ /* MCU_membership[i] is index in cur_comp_info of component owning */
+ /* i'th data unit in an MCU */
+
+ int Ss, Se, Ah, Al; /* progressive/lossless JPEG parms for scan */
+
+ /* This field is shared between entropy decoder and marker parser.
+ * It is either zero or the code of a JPEG marker that has been
+ * read from the data source, but has not yet been processed.
+ */
+ int unread_marker;
+
+ /*
+ * Links to decompression subobjects (methods, private variables of modules)
+ */
+ struct jpeg_decomp_master * master;
+ struct jpeg_d_main_controller * mainp;
+ struct jpeg_d_codec * codec;
+ struct jpeg_d_post_controller * post;
+ struct jpeg_input_controller * inputctl;
+ struct jpeg_marker_reader * marker;
+ struct jpeg_upsampler * upsample;
+ struct jpeg_color_deconverter * cconvert;
+ struct jpeg_color_quantizer * cquantize;
+};
+
+
+/* "Object" declarations for JPEG modules that may be supplied or called
+ * directly by the surrounding application.
+ * As with all objects in the JPEG library, these structs only define the
+ * publicly visible methods and state variables of a module. Additional
+ * private fields may exist after the public ones.
+ */
+
+
+/* Error handler object */
+
+struct jpeg_error_mgr {
+ /* Error exit handler: does not return to caller */
+ JMETHOD(void, error_exit, (j_common_ptr cinfo));
+ /* Conditionally emit a trace or warning message */
+ JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
+ /* Routine that actually outputs a trace or error message */
+ JMETHOD(void, output_message, (j_common_ptr cinfo));
+ /* Format a message string for the most recent JPEG error or message */
+ JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
+#define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
+ /* Reset error state variables at start of a new image */
+ JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
+
+ /* The message ID code and any parameters are saved here.
+ * A message can have one string parameter or up to 8 int parameters.
+ */
+ int msg_code;
+#define JMSG_STR_PARM_MAX 80
+ union {
+ int i[8];
+ char s[JMSG_STR_PARM_MAX];
+ } msg_parm;
+
+ /* Standard state variables for error facility */
+
+ int trace_level; /* max msg_level that will be displayed */
+
+ /* For recoverable corrupt-data errors, we emit a warning message,
+ * but keep going unless emit_message chooses to abort. emit_message
+ * should count warnings in num_warnings. The surrounding application
+ * can check for bad data by seeing if num_warnings is nonzero at the
+ * end of processing.
+ */
+ long num_warnings; /* number of corrupt-data warnings */
+
+ /* These fields point to the table(s) of error message strings.
+ * An application can change the table pointer to switch to a different
+ * message list (typically, to change the language in which errors are
+ * reported). Some applications may wish to add additional error codes
+ * that will be handled by the JPEG library error mechanism; the second
+ * table pointer is used for this purpose.
+ *
+ * First table includes all errors generated by JPEG library itself.
+ * Error code 0 is reserved for a "no such error string" message.
+ */
+ const char * const * jpeg_message_table; /* Library errors */
+ int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
+ /* Second table can be added by application (see cjpeg/djpeg for example).
+ * It contains strings numbered first_addon_message..last_addon_message.
+ */
+ const char * const * addon_message_table; /* Non-library errors */
+ int first_addon_message; /* code for first string in addon table */
+ int last_addon_message; /* code for last string in addon table */
+};
+
+
+/* Progress monitor object */
+
+struct jpeg_progress_mgr {
+ JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
+
+ long pass_counter; /* work units completed in this pass */
+ long pass_limit; /* total number of work units in this pass */
+ int completed_passes; /* passes completed so far */
+ int total_passes; /* total number of passes expected */
+};
+
+
+/* Data destination object for compression */
+
+struct jpeg_destination_mgr {
+ JOCTET * next_output_byte; /* => next byte to write in buffer */
+ size_t free_in_buffer; /* # of byte spaces remaining in buffer */
+
+ JMETHOD(void, init_destination, (j_compress_ptr cinfo));
+ JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
+ JMETHOD(void, term_destination, (j_compress_ptr cinfo));
+};
+
+
+/* Data source object for decompression */
+
+struct jpeg_source_mgr {
+ const JOCTET * next_input_byte; /* => next byte to read from buffer */
+ size_t bytes_in_buffer; /* # of bytes remaining in buffer */
+
+ JMETHOD(void, init_source, (j_decompress_ptr cinfo));
+ JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
+ JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
+ JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
+ JMETHOD(void, term_source, (j_decompress_ptr cinfo));
+};
+
+
+/* Memory manager object.
+ * Allocates "small" objects (a few K total), "large" objects (tens of K),
+ * and "really big" objects (virtual arrays with backing store if needed).
+ * The memory manager does not allow individual objects to be freed; rather,
+ * each created object is assigned to a pool, and whole pools can be freed
+ * at once. This is faster and more convenient than remembering exactly what
+ * to free, especially where malloc()/free() are not too speedy.
+ * NB: alloc routines never return NULL. They exit to error_exit if not
+ * successful.
+ */
+
+#define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
+#define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
+#define JPOOL_IMAGE_BUF 2 /* lasts until done with jpeg_write_raw_data */
+#define JPOOL_NUMPOOLS 3
+
+typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
+typedef struct jvirt_barray_control * jvirt_barray_ptr;
+
+
+#ifdef C_LOSSLESS_SUPPORTED
+#define NEED_DARRAY
+#else
+#ifdef D_LOSSLESS_SUPPORTED
+#define NEED_DARRAY
+#endif
+#endif
+
+struct jpeg_memory_mgr {
+ /* Method pointers */
+ JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
+ size_t sizeofobject));
+ JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
+ size_t sizeofobject));
+ JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
+ JDIMENSION samplesperrow,
+ JDIMENSION numrows));
+ JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
+ JDIMENSION blocksperrow,
+ JDIMENSION numrows));
+#ifdef NEED_DARRAY
+ JMETHOD(JDIFFARRAY, alloc_darray, (j_common_ptr cinfo, int pool_id,
+ JDIMENSION diffsperrow,
+ JDIMENSION numrows));
+#endif
+ JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
+ int pool_id,
+ boolean pre_zero,
+ JDIMENSION samplesperrow,
+ JDIMENSION numrows,
+ JDIMENSION maxaccess));
+ JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
+ int pool_id,
+ boolean pre_zero,
+ JDIMENSION blocksperrow,
+ JDIMENSION numrows,
+ JDIMENSION maxaccess));
+ JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
+ JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
+ jvirt_sarray_ptr ptr,
+ JDIMENSION start_row,
+ JDIMENSION num_rows,
+ boolean writable));
+ JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
+ jvirt_barray_ptr ptr,
+ JDIMENSION start_row,
+ JDIMENSION num_rows,
+ boolean writable));
+ JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
+ JMETHOD(void, self_destruct, (j_common_ptr cinfo));
+
+ /* Limit on memory allocation for this JPEG object. (Note that this is
+ * merely advisory, not a guaranteed maximum; it only affects the space
+ * used for virtual-array buffers.) May be changed by outer application
+ * after creating the JPEG object.
+ */
+ long max_memory_to_use;
+
+ /* Maximum allocation request accepted by alloc_large. */
+ long max_alloc_chunk;
+};
+
+
+/* Routine signature for application-supplied marker processing methods.
+ * Need not pass marker code since it is stored in cinfo->unread_marker.
+ */
+typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
+
+
+/* Declarations for routines called by application.
+ * The JPP macro hides prototype parameters from compilers that can't cope.
+ * Note JPP requires double parentheses.
+ */
+
+#ifdef HAVE_PROTOTYPES
+#define JPP(arglist) arglist
+#else
+#define JPP(arglist) ()
+#endif
+
+/* The fix for CPP */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Short forms of external names for systems with brain-damaged linkers.
+ * We shorten external names to be unique in the first six letters, which
+ * is good enough for all known systems.
+ * (If your compiler itself needs names to be unique in less than 15
+ * characters, you are out of luck. Get a better compiler.)
+ */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_std_error jStdError
+#define jpeg_CreateCompress jCreaCompress
+#define jpeg_CreateDecompress jCreaDecompress
+#define jpeg_destroy_compress jDestCompress
+#define jpeg_destroy_decompress jDestDecompress
+#define jpeg_stdio_dest jStdDest
+#define jpeg_stdio_src jStdSrc
+#define jpeg_set_defaults jSetDefaults
+#define jpeg_set_colorspace jSetColorspace
+#define jpeg_default_colorspace jDefColorspace
+#define jpeg_set_quality jSetQuality
+#define jpeg_set_linear_quality jSetLQuality
+#define jpeg_add_quant_table jAddQuantTable
+#define jpeg_quality_scaling jQualityScaling
+#define jpeg_simple_lossless jSimLossless
+#define jpeg_simple_progression jSimProgress
+#define jpeg_suppress_tables jSuppressTables
+#define jpeg_alloc_quant_table jAlcQTable
+#define jpeg_alloc_huff_table jAlcHTable
+#define jpeg_start_compress jStrtCompress
+#define jpeg_write_scanlines jWrtScanlines
+#define jpeg_finish_compress jFinCompress
+#define jpeg_write_raw_data jWrtRawData
+#define jpeg_write_marker jWrtMarker
+#define jpeg_write_m_header jWrtMHeader
+#define jpeg_write_m_byte jWrtMByte
+#define jpeg_write_tables jWrtTables
+#define jpeg_read_header jReadHeader
+#define jpeg_start_decompress jStrtDecompress
+#define jpeg_read_scanlines jReadScanlines
+#define jpeg_finish_decompress jFinDecompress
+#define jpeg_read_raw_data jReadRawData
+#define jpeg_has_multiple_scans jHasMultScn
+#define jpeg_start_output jStrtOutput
+#define jpeg_finish_output jFinOutput
+#define jpeg_input_complete jInComplete
+#define jpeg_new_colormap jNewCMap
+#define jpeg_consume_input jConsumeInput
+#define jpeg_calc_output_dimensions jCalcDimensions
+#define jpeg_save_markers jSaveMarkers
+#define jpeg_set_marker_processor jSetMarker
+#define jpeg_read_coefficients jReadCoefs
+#define jpeg_write_coefficients jWrtCoefs
+#define jpeg_copy_critical_parameters jCopyCrit
+#define jpeg_abort_compress jAbrtCompress
+#define jpeg_abort_decompress jAbrtDecompress
+#define jpeg_abort jAbort
+#define jpeg_destroy jDestroy
+#define jpeg_resync_to_restart jResyncRestart
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/* Default error-management setup */
+EXTERN(struct jpeg_error_mgr *) jpeg_std_error
+ JPP((struct jpeg_error_mgr * err));
+
+/* Initialization of JPEG compression objects.
+ * jpeg_create_compress() and jpeg_create_decompress() are the exported
+ * names that applications should call. These expand to calls on
+ * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
+ * passed for version mismatch checking.
+ * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
+ */
+#define jpeg_create_compress(cinfo) \
+ jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
+ (size_t) sizeof(struct jpeg_compress_struct))
+#define jpeg_create_decompress(cinfo) \
+ jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
+ (size_t) sizeof(struct jpeg_decompress_struct))
+EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
+ int version, size_t structsize));
+EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
+ int version, size_t structsize));
+/* Destruction of JPEG compression objects */
+EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
+EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
+
+/* Standard data source and destination managers: stdio streams. */
+/* Caller is responsible for opening the file before and closing after. */
+EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
+EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
+
+/* Default parameter setup for compression */
+EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
+/* Compression parameter setup aids */
+EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
+ J_COLOR_SPACE colorspace));
+EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
+EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
+ boolean force_baseline));
+EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
+ int scale_factor,
+ boolean force_baseline));
+EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
+ const unsigned int *basic_table,
+ int scale_factor,
+ boolean force_baseline));
+EXTERN(int) jpeg_quality_scaling JPP((int quality));
+EXTERN(void) jpeg_simple_lossless JPP((j_compress_ptr cinfo,
+ int predictor, int point_transform));
+EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
+EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
+ boolean suppress));
+EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
+EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
+
+/* Main entry points for compression */
+EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
+ boolean write_all_tables));
+EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
+ JSAMPARRAY scanlines,
+ JDIMENSION num_lines));
+EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
+
+/* Replaces jpeg_write_scanlines when writing raw downsampled data. */
+EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
+ JSAMPIMAGE data,
+ JDIMENSION num_lines));
+
+/* Write a special marker. See libjpeg.doc concerning safe usage. */
+EXTERN(void) jpeg_write_marker
+ JPP((j_compress_ptr cinfo, int marker,
+ const JOCTET * dataptr, unsigned int datalen));
+/* Same, but piecemeal. */
+EXTERN(void) jpeg_write_m_header
+ JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
+EXTERN(void) jpeg_write_m_byte
+ JPP((j_compress_ptr cinfo, int val));
+
+/* Alternate compression function: just write an abbreviated table file */
+EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
+
+/* Decompression startup: read start of JPEG datastream to see what's there */
+EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
+ boolean require_image));
+/* Return value is one of: */
+#define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
+#define JPEG_HEADER_OK 1 /* Found valid image datastream */
+#define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
+/* If you pass require_image = TRUE (normal case), you need not check for
+ * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
+ * JPEG_SUSPENDED is only possible if you use a data source module that can
+ * give a suspension return (the stdio source module doesn't).
+ */
+
+/* Main entry points for decompression */
+EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
+EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
+ JSAMPARRAY scanlines,
+ JDIMENSION max_lines));
+EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
+
+/* Replaces jpeg_read_scanlines when reading raw downsampled data. */
+EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
+ JSAMPIMAGE data,
+ JDIMENSION max_lines));
+
+/* Additional entry points for buffered-image mode. */
+EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
+EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
+ int scan_number));
+EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
+EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
+EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
+EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
+/* Return value is one of: */
+/* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
+#define JPEG_REACHED_SOS 1 /* Reached start of new scan */
+#define JPEG_REACHED_EOI 2 /* Reached end of image */
+#define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
+#define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
+
+/* Precalculate output dimensions for current decompression parameters. */
+EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
+
+/* Control saving of COM and APPn markers into marker_list. */
+EXTERN(void) jpeg_save_markers
+ JPP((j_decompress_ptr cinfo, int marker_code,
+ unsigned int length_limit));
+
+/* Install a special processing method for COM or APPn markers. */
+EXTERN(void) jpeg_set_marker_processor
+ JPP((j_decompress_ptr cinfo, int marker_code,
+ jpeg_marker_parser_method routine));
+
+/* Read or write raw DCT coefficients --- useful for lossless transcoding. */
+EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
+EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
+ jvirt_barray_ptr * coef_arrays));
+EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
+ j_compress_ptr dstinfo));
+
+/* If you choose to abort compression or decompression before completing
+ * jpeg_finish_(de)compress, then you need to clean up to release memory,
+ * temporary files, etc. You can just call jpeg_destroy_(de)compress
+ * if you're done with the JPEG object, but if you want to clean it up and
+ * reuse it, call this:
+ */
+EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
+EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
+
+/* Generic versions of jpeg_abort and jpeg_destroy that work on either
+ * flavor of JPEG object. These may be more convenient in some places.
+ */
+EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
+EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
+
+/* Default restart-marker-resync procedure for use by data source modules */
+EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
+ int desired));
+
+/* End of CPP fix */
+#ifdef __cplusplus
+}
+#endif
+
+/* These marker codes are exported since applications and data source modules
+ * are likely to want to use them.
+ */
+
+#define JPEG_RST0 0xD0 /* RST0 marker code */
+#define JPEG_EOI 0xD9 /* EOI marker code */
+#define JPEG_APP0 0xE0 /* APP0 marker code */
+#define JPEG_COM 0xFE /* COM marker code */
+
+
+/* If we have a brain-damaged compiler that emits warnings (or worse, errors)
+ * for structure definitions that are never filled in, keep it quiet by
+ * supplying dummy definitions for the various substructures.
+ */
+
+#ifdef INCOMPLETE_TYPES_BROKEN
+#ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
+struct jvirt_sarray_control { long dummy; };
+struct jvirt_barray_control { long dummy; };
+struct jpeg_comp_master { long dummy; };
+struct jpeg_c_main_controller { long dummy; };
+struct jpeg_c_prep_controller { long dummy; };
+struct jpeg_c_coef_controller { long dummy; };
+struct jpeg_marker_writer { long dummy; };
+struct jpeg_color_converter { long dummy; };
+struct jpeg_downsampler { long dummy; };
+struct jpeg_forward_dct { long dummy; };
+struct jpeg_entropy_encoder { long dummy; };
+struct jpeg_decomp_master { long dummy; };
+struct jpeg_d_main_controller { long dummy; };
+struct jpeg_d_coef_controller { long dummy; };
+struct jpeg_d_post_controller { long dummy; };
+struct jpeg_input_controller { long dummy; };
+struct jpeg_marker_reader { long dummy; };
+struct jpeg_entropy_decoder { long dummy; };
+struct jpeg_inverse_dct { long dummy; };
+struct jpeg_upsampler { long dummy; };
+struct jpeg_color_deconverter { long dummy; };
+struct jpeg_color_quantizer { long dummy; };
+#endif /* JPEG_INTERNALS */
+#endif /* INCOMPLETE_TYPES_BROKEN */
+
+
+/*
+ * The JPEG library modules define JPEG_INTERNALS before including this file.
+ * The internal structure declarations are read only when that is true.
+ * Applications using the library should not include jpegint.h, but may wish
+ * to include jerror.h.
+ */
+
+#ifdef JPEG_INTERNALS
+#include "jpegint.h" /* fetch private declarations */
+#include "jerror.h" /* fetch error codes too */
+#endif
+
+#endif /* JPEGLIB_H */
diff --git a/jpeg-6c/jpegtran.1 b/jpeg-6c/jpegtran.1
new file mode 100644
index 0000000..6de18e2
--- /dev/null
+++ b/jpeg-6c/jpegtran.1
@@ -0,0 +1,238 @@
+.TH JPEGTRAN 1 "3 August 1997"
+.SH NAME
+jpegtran \- lossless transformation of JPEG files
+.SH SYNOPSIS
+.B jpegtran
+[
+.I options
+]
+[
+.I filename
+]
+.LP
+.SH DESCRIPTION
+.LP
+.B jpegtran
+performs various useful transformations of JPEG files.
+It can translate the coded representation from one variant of JPEG to another,
+for example from baseline JPEG to progressive JPEG or vice versa. It can also
+perform some rearrangements of the image data, for example turning an image
+from landscape to portrait format by rotation.
+.PP
+.B jpegtran
+works by rearranging the compressed data (DCT coefficients), without
+ever fully decoding the image. Therefore, its transformations are lossless:
+there is no image degradation at all, which would not be true if you used
+.B djpeg
+followed by
+.B cjpeg
+to accomplish the same conversion. But by the same token,
+.B jpegtran
+cannot perform lossy operations such as changing the image quality.
+.PP
+.B jpegtran
+reads the named JPEG/JFIF file, or the standard input if no file is
+named, and produces a JPEG/JFIF file on the standard output.
+.SH OPTIONS
+All switch names may be abbreviated; for example,
+.B \-optimize
+may be written
+.B \-opt
+or
+.BR \-o .
+Upper and lower case are equivalent.
+British spellings are also accepted (e.g.,
+.BR \-optimise ),
+though for brevity these are not mentioned below.
+.PP
+To specify the coded JPEG representation used in the output file,
+.B jpegtran
+accepts a subset of the switches recognized by
+.BR cjpeg :
+.TP
+.B \-optimize
+Perform optimization of entropy encoding parameters.
+.TP
+.B \-progressive
+Create progressive JPEG file.
+.TP
+.BI \-restart " N"
+Emit a JPEG restart marker every N MCU rows, or every N MCU blocks if "B" is
+attached to the number.
+.TP
+.BI \-scans " file"
+Use the scan script given in the specified text file.
+.PP
+See
+.BR cjpeg (1)
+for more details about these switches.
+If you specify none of these switches, you get a plain baseline-JPEG output
+file. The quality setting and so forth are determined by the input file.
+.PP
+The image can be losslessly transformed by giving one of these switches:
+.TP
+.B \-flip horizontal
+Mirror image horizontally (left-right).
+.TP
+.B \-flip vertical
+Mirror image vertically (top-bottom).
+.TP
+.B \-rotate 90
+Rotate image 90 degrees clockwise.
+.TP
+.B \-rotate 180
+Rotate image 180 degrees.
+.TP
+.B \-rotate 270
+Rotate image 270 degrees clockwise (or 90 ccw).
+.TP
+.B \-transpose
+Transpose image (across UL-to-LR axis).
+.TP
+.B \-transverse
+Transverse transpose (across UR-to-LL axis).
+.PP
+The transpose transformation has no restrictions regarding image dimensions.
+The other transformations operate rather oddly if the image dimensions are not
+a multiple of the iMCU size (usually 8 or 16 pixels), because they can only
+transform complete blocks of DCT coefficient data in the desired way.
+.PP
+.BR jpegtran 's
+default behavior when transforming an odd-size image is designed
+to preserve exact reversibility and mathematical consistency of the
+transformation set. As stated, transpose is able to flip the entire image
+area. Horizontal mirroring leaves any partial iMCU column at the right edge
+untouched, but is able to flip all rows of the image. Similarly, vertical
+mirroring leaves any partial iMCU row at the bottom edge untouched, but is
+able to flip all columns. The other transforms can be built up as sequences
+of transpose and flip operations; for consistency, their actions on edge
+pixels are defined to be the same as the end result of the corresponding
+transpose-and-flip sequence.
+.PP
+For practical use, you may prefer to discard any untransformable edge pixels
+rather than having a strange-looking strip along the right and/or bottom edges
+of a transformed image. To do this, add the
+.B \-trim
+switch:
+.TP
+.B \-trim
+Drop non-transformable edge blocks.
+.PP
+Obviously, a transformation with
+.B \-trim
+is not reversible, so strictly speaking
+.B jpegtran
+with this switch is not lossless. Also, the expected mathematical
+equivalences between the transformations no longer hold. For example,
+.B \-rot 270 -trim
+trims only the bottom edge, but
+.B \-rot 90 -trim
+followed by
+.B \-rot 180 -trim
+trims both edges.
+.PP
+Another not-strictly-lossless transformation switch is:
+.TP
+.B \-grayscale
+Force grayscale output.
+.PP
+This option discards the chrominance channels if the input image is YCbCr
+(ie, a standard color JPEG), resulting in a grayscale JPEG file. The
+luminance channel is preserved exactly, so this is a better method of reducing
+to grayscale than decompression, conversion, and recompression. This switch
+is particularly handy for fixing a monochrome picture that was mistakenly
+encoded as a color JPEG. (In such a case, the space savings from getting rid
+of the near-empty chroma channels won't be large; but the decoding time for
+a grayscale JPEG is substantially less than that for a color JPEG.)
+.PP
+.B jpegtran
+also recognizes these switches that control what to do with "extra" markers,
+such as comment blocks:
+.TP
+.B \-copy none
+Copy no extra markers from source file. This setting suppresses all
+comments and other excess baggage present in the source file.
+.TP
+.B \-copy comments
+Copy only comment markers. This setting copies comments from the source file,
+but discards any other inessential data.
+.TP
+.B \-copy all
+Copy all extra markers. This setting preserves miscellaneous markers
+found in the source file, such as JFIF thumbnails and Photoshop settings.
+In some files these extra markers can be sizable.
+.PP
+The default behavior is
+.BR "\-copy comments" .
+(Note: in IJG releases v6 and v6a,
+.B jpegtran
+always did the equivalent of
+.BR "\-copy none" .)
+.PP
+Additional switches recognized by jpegtran are:
+.TP
+.BI \-maxmemory " N"
+Set limit for amount of memory to use in processing large images. Value is
+in thousands of bytes, or millions of bytes if "M" is attached to the
+number. For example,
+.B \-max 4m
+selects 4000000 bytes. If more space is needed, temporary files will be used.
+.TP
+.BI \-outfile " name"
+Send output image to the named file, not to standard output.
+.TP
+.B \-verbose
+Enable debug printout. More
+.BR \-v 's
+give more output. Also, version information is printed at startup.
+.TP
+.B \-debug
+Same as
+.BR \-verbose .
+.SH EXAMPLES
+.LP
+This example converts a baseline JPEG file to progressive form:
+.IP
+.B jpegtran \-progressive
+.I foo.jpg
+.B >
+.I fooprog.jpg
+.PP
+This example rotates an image 90 degrees clockwise, discarding any
+unrotatable edge pixels:
+.IP
+.B jpegtran \-rot 90 -trim
+.I foo.jpg
+.B >
+.I foo90.jpg
+.SH ENVIRONMENT
+.TP
+.B JPEGMEM
+If this environment variable is set, its value is the default memory limit.
+The value is specified as described for the
+.B \-maxmemory
+switch.
+.B JPEGMEM
+overrides the default value specified when the program was compiled, and
+itself is overridden by an explicit
+.BR \-maxmemory .
+.SH SEE ALSO
+.BR cjpeg (1),
+.BR djpeg (1),
+.BR rdjpgcom (1),
+.BR wrjpgcom (1)
+.br
+Wallace, Gregory K. "The JPEG Still Picture Compression Standard",
+Communications of the ACM, April 1991 (vol. 34, no. 4), pp. 30-44.
+.SH AUTHOR
+Independent JPEG Group
+.SH BUGS
+Arithmetic coding is not supported for legal reasons.
+.PP
+The transform options can't transform odd-size images perfectly. Use
+.B \-trim
+if you don't like the results without it.
+.PP
+The entire image is read into memory and then written out again, even in
+cases where this isn't really necessary. Expect swapping on large images,
+especially when using the more complex transform options.
diff --git a/jpeg-6c/jpegtran.c b/jpeg-6c/jpegtran.c
new file mode 100644
index 0000000..e50a111
--- /dev/null
+++ b/jpeg-6c/jpegtran.c
@@ -0,0 +1,624 @@
+/*
+ * jpegtran.c
+ *
+ * Copyright (C) 1995-2001, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a command-line user interface for JPEG transcoding.
+ * It is very similar to cjpeg.c, but provides lossless transcoding between
+ * different JPEG file formats. It also provides some lossless and sort-of-
+ * lossless transformations of JPEG data.
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+#include "transupp.h" /* Support routines for jpegtran */
+#include "jversion.h" /* for version message */
+
+#ifdef USE_CCOMMAND /* command-line reader for Macintosh */
+#ifdef __MWERKS__
+#include <SIOUX.h> /* Metrowerks needs this */
+#include <console.h> /* ... and this */
+#endif
+#ifdef THINK_C
+#include <console.h> /* Think declares it here */
+#endif
+#endif
+
+
+/*
+ * Argument-parsing code.
+ * The switch parser is designed to be useful with DOS-style command line
+ * syntax, ie, intermixed switches and file names, where only the switches
+ * to the left of a given file name affect processing of that file.
+ * The main program in this file doesn't actually use this capability...
+ */
+
+
+static const char * progname; /* program name for error messages */
+static char * outfilename; /* for -outfile switch */
+static char * dropfilename; /* for -drop switch */
+static JCOPY_OPTION copyoption; /* -copy switch */
+static jpeg_transform_info transformoption; /* image transformation options */
+
+
+LOCAL(void)
+usage (void)
+/* complain about bad command line */
+{
+ fprintf(stderr, "usage: %s [switches] ", progname);
+#ifdef TWO_FILE_COMMANDLINE
+ fprintf(stderr, "inputfile outputfile\n");
+#else
+ fprintf(stderr, "[inputfile]\n");
+#endif
+
+ fprintf(stderr, "Switches (names may be abbreviated):\n");
+ fprintf(stderr, " -copy none Copy no extra markers from source file\n");
+ fprintf(stderr, " -copy comments Copy only comment markers (default)\n");
+ fprintf(stderr, " -copy all Copy all extra markers\n");
+#ifdef ENTROPY_OPT_SUPPORTED
+ fprintf(stderr, " -optimize Optimize Huffman table (smaller file, but slow compression)\n");
+#endif
+#ifdef C_PROGRESSIVE_SUPPORTED
+ fprintf(stderr, " -progressive Create progressive JPEG file\n");
+#endif
+#if TRANSFORMS_SUPPORTED
+ fprintf(stderr, "Switches for modifying the image:\n");
+ fprintf(stderr, " -crop WxH+X+Y Crop to a rectangular subarea\n");
+ fprintf(stderr, " -drop +X+Y filename Drop another image\n");
+ fprintf(stderr, " -grayscale Reduce to grayscale (omit color data)\n");
+ fprintf(stderr, " -flip [horizontal|vertical] Mirror image (left-right or top-bottom)\n");
+ fprintf(stderr, " -perfect Fail if there is non-transformable edge blocks\n");
+ fprintf(stderr, " -rotate [90|180|270] Rotate image (degrees clockwise)\n");
+ fprintf(stderr, " -transpose Transpose image\n");
+ fprintf(stderr, " -transverse Transverse transpose image\n");
+ fprintf(stderr, " -trim Drop non-transformable edge blocks or\n");
+ fprintf(stderr, " with -drop: Requantize drop file to source file\n");
+#endif /* TRANSFORMS_SUPPORTED */
+ fprintf(stderr, "Switches for advanced users:\n");
+ fprintf(stderr, " -restart N Set restart interval in rows, or in blocks with B\n");
+ fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
+ fprintf(stderr, " -outfile name Specify name for output file\n");
+ fprintf(stderr, " -verbose or -debug Emit debug output\n");
+ fprintf(stderr, "Switches for wizards:\n");
+#ifdef C_ARITH_CODING_SUPPORTED
+ fprintf(stderr, " -arithmetic Use arithmetic coding\n");
+#endif
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+ fprintf(stderr, " -scans file Create multi-scan JPEG per script file\n");
+#endif
+ exit(EXIT_FAILURE);
+}
+
+
+LOCAL(void)
+select_transform (JXFORM_CODE transform)
+/* Silly little routine to detect multiple transform options,
+ * which we can't handle.
+ */
+{
+#if TRANSFORMS_SUPPORTED
+ if (transformoption.transform == JXFORM_NONE ||
+ transformoption.transform == transform) {
+ transformoption.transform = transform;
+ } else {
+ fprintf(stderr, "%s: can only do one image transformation at a time\n",
+ progname);
+ usage();
+ }
+#else
+ fprintf(stderr, "%s: sorry, image transformation was not compiled\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+}
+
+
+LOCAL(int)
+parse_switches (j_compress_ptr cinfo, int argc, char **argv,
+ int last_file_arg_seen, boolean for_real)
+/* Parse optional switches.
+ * Returns argv[] index of first file-name argument (== argc if none).
+ * Any file names with indexes <= last_file_arg_seen are ignored;
+ * they have presumably been processed in a previous iteration.
+ * (Pass 0 for last_file_arg_seen on the first or only iteration.)
+ * for_real is FALSE on the first (dummy) pass; we may skip any expensive
+ * processing.
+ */
+{
+ int argn;
+ char * arg;
+ boolean simple_progressive;
+ char * scansarg = NULL; /* saves -scans parm if any */
+
+ /* Set up default JPEG parameters. */
+ simple_progressive = FALSE;
+ outfilename = NULL;
+ dropfilename = NULL;
+ copyoption = JCOPYOPT_DEFAULT;
+ transformoption.transform = JXFORM_NONE;
+ transformoption.trim = FALSE;
+ transformoption.perfect = FALSE;
+ transformoption.force_grayscale = FALSE;
+ transformoption.crop = FALSE;
+ cinfo->err->trace_level = 0;
+
+ /* Scan command line options, adjust parameters */
+
+ for (argn = 1; argn < argc; argn++) {
+ arg = argv[argn];
+ if (*arg != '-') {
+ /* Not a switch, must be a file name argument */
+ if (argn <= last_file_arg_seen) {
+ outfilename = NULL; /* -outfile applies to just one input file */
+ continue; /* ignore this name if previously processed */
+ }
+ break; /* else done parsing switches */
+ }
+ arg++; /* advance past switch marker character */
+
+ if (keymatch(arg, "arithmetic", 1)) {
+ /* Use arithmetic coding. */
+#ifdef C_ARITH_CODING_SUPPORTED
+ cinfo->arith_code = TRUE;
+#else
+ fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+
+ } else if (keymatch(arg, "copy", 2)) {
+ /* Select which extra markers to copy. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (keymatch(argv[argn], "none", 1)) {
+ copyoption = JCOPYOPT_NONE;
+ } else if (keymatch(argv[argn], "comments", 1)) {
+ copyoption = JCOPYOPT_COMMENTS;
+ } else if (keymatch(argv[argn], "all", 1)) {
+ copyoption = JCOPYOPT_ALL;
+ } else
+ usage();
+
+ } else if (keymatch(arg, "crop", 2)) {
+ /* Perform lossless cropping. */
+#if TRANSFORMS_SUPPORTED
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (transformoption.crop /* reject multiple crop/drop requests */ ||
+ ! jtransform_parse_crop_spec(&transformoption, argv[argn])) {
+ fprintf(stderr, "%s: bogus -crop argument '%s'\n",
+ progname, argv[argn]);
+ exit(EXIT_FAILURE);
+ }
+#else
+ select_transform(JXFORM_NONE); /* force an error */
+#endif
+
+ } else if (keymatch(arg, "drop", 2)) {
+#if TRANSFORMS_SUPPORTED
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (transformoption.crop /* reject multiple crop/drop requests */ ||
+ ! jtransform_parse_crop_spec(&transformoption, argv[argn]) ||
+ transformoption.crop_width_set != JCROP_UNSET ||
+ transformoption.crop_height_set != JCROP_UNSET) {
+ fprintf(stderr, "%s: bogus -drop argument '%s'\n",
+ progname, argv[argn]);
+ exit(EXIT_FAILURE);
+ }
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ dropfilename = argv[argn];
+ select_transform(JXFORM_DROP);
+#else
+ select_transform(JXFORM_NONE); /* force an error */
+#endif
+
+ } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
+ /* Enable debug printouts. */
+ /* On first -d, print version identification */
+ static boolean printed_version = FALSE;
+
+ if (! printed_version) {
+ fprintf(stderr, "Independent JPEG Group's JPEGTRAN, version %s\n%s\n",
+ JVERSION, JCOPYRIGHT);
+ printed_version = TRUE;
+ }
+ cinfo->err->trace_level++;
+
+ } else if (keymatch(arg, "flip", 1)) {
+ /* Mirror left-right or top-bottom. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (keymatch(argv[argn], "horizontal", 1))
+ select_transform(JXFORM_FLIP_H);
+ else if (keymatch(argv[argn], "vertical", 1))
+ select_transform(JXFORM_FLIP_V);
+ else
+ usage();
+
+ } else if (keymatch(arg, "grayscale", 1) || keymatch(arg, "greyscale",1)) {
+ /* Force to grayscale. */
+#if TRANSFORMS_SUPPORTED
+ transformoption.force_grayscale = TRUE;
+#else
+ select_transform(JXFORM_NONE); /* force an error */
+#endif
+
+ } else if (keymatch(arg, "maxmemory", 3)) {
+ /* Maximum memory in Kb (or Mb with 'm'). */
+ long lval;
+ char ch = 'x';
+
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
+ usage();
+ if (ch == 'm' || ch == 'M')
+ lval *= 1000L;
+ cinfo->mem->max_memory_to_use = lval * 1000L;
+
+ } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
+ /* Enable entropy parm optimization. */
+#ifdef ENTROPY_OPT_SUPPORTED
+ cinfo->optimize_coding = TRUE;
+#else
+ fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+
+ } else if (keymatch(arg, "outfile", 4)) {
+ /* Set output file name. */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ outfilename = argv[argn]; /* save it away for later use */
+
+ } else if (keymatch(arg, "perfect", 2)) {
+ /* Fail if there is any partial edge MCUs that the transform can't
+ * handle. */
+ transformoption.perfect = TRUE;
+
+ } else if (keymatch(arg, "progressive", 2)) {
+ /* Select simple progressive mode. */
+#ifdef C_PROGRESSIVE_SUPPORTED
+ simple_progressive = TRUE;
+ /* We must postpone execution until num_components is known. */
+#else
+ fprintf(stderr, "%s: sorry, progressive output was not compiled\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+
+ } else if (keymatch(arg, "restart", 1)) {
+ /* Restart interval in MCU rows (or in MCUs with 'b'). */
+ long lval;
+ char ch = 'x';
+
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
+ usage();
+ if (lval < 0 || lval > 65535L)
+ usage();
+ if (ch == 'b' || ch == 'B') {
+ cinfo->restart_interval = (unsigned int) lval;
+ cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
+ } else {
+ cinfo->restart_in_rows = (int) lval;
+ /* restart_interval will be computed during startup */
+ }
+
+ } else if (keymatch(arg, "rotate", 2)) {
+ /* Rotate 90, 180, or 270 degrees (measured clockwise). */
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ if (keymatch(argv[argn], "90", 2))
+ select_transform(JXFORM_ROT_90);
+ else if (keymatch(argv[argn], "180", 3))
+ select_transform(JXFORM_ROT_180);
+ else if (keymatch(argv[argn], "270", 3))
+ select_transform(JXFORM_ROT_270);
+ else
+ usage();
+
+ } else if (keymatch(arg, "scans", 1)) {
+ /* Set scan script. */
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+ if (++argn >= argc) /* advance to next argument */
+ usage();
+ scansarg = argv[argn];
+ /* We must postpone reading the file in case -progressive appears. */
+#else
+ fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n",
+ progname);
+ exit(EXIT_FAILURE);
+#endif
+
+ } else if (keymatch(arg, "transpose", 1)) {
+ /* Transpose (across UL-to-LR axis). */
+ select_transform(JXFORM_TRANSPOSE);
+
+ } else if (keymatch(arg, "transverse", 6)) {
+ /* Transverse transpose (across UR-to-LL axis). */
+ select_transform(JXFORM_TRANSVERSE);
+
+ } else if (keymatch(arg, "trim", 3)) {
+ /* Trim off any partial edge MCUs that the transform can't handle. */
+ transformoption.trim = TRUE;
+
+ } else {
+ usage(); /* bogus switch */
+ }
+ }
+
+ /* Post-switch-scanning cleanup */
+
+ if (for_real) {
+
+#ifdef C_PROGRESSIVE_SUPPORTED
+ if (simple_progressive) /* process -progressive; -scans can override */
+ jpeg_simple_progression(cinfo);
+#endif
+
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+ if (scansarg != NULL) /* process -scans if it was present */
+ if (! read_scan_script(cinfo, scansarg))
+ usage();
+#endif
+ }
+
+ return argn; /* return index of next arg (file name) */
+}
+
+
+/*
+ * The main program.
+ */
+
+int
+main (int argc, char **argv)
+{
+ struct jpeg_decompress_struct srcinfo;
+ struct jpeg_error_mgr jsrcerr;
+#if TRANSFORMS_SUPPORTED
+ struct jpeg_decompress_struct dropinfo;
+ struct jpeg_error_mgr jdroperr;
+ FILE * drop_file;
+#endif
+ struct jpeg_compress_struct dstinfo;
+ struct jpeg_error_mgr jdsterr;
+#ifdef PROGRESS_REPORT
+ struct cdjpeg_progress_mgr progress;
+#endif
+ jvirt_barray_ptr * src_coef_arrays;
+ jvirt_barray_ptr * dst_coef_arrays;
+ int file_index;
+ /* We assume all-in-memory processing and can therefore use only a
+ * single file pointer for sequential input and output operation.
+ */
+ FILE * fp;
+
+ /* On Mac, fetch a command line. */
+#ifdef USE_CCOMMAND
+ argc = ccommand(&argv);
+#endif
+
+ progname = argv[0];
+ if (progname == NULL || progname[0] == 0)
+ progname = "jpegtran"; /* in case C library doesn't provide it */
+
+ /* Initialize the JPEG decompression object with default error handling. */
+ srcinfo.err = jpeg_std_error(&jsrcerr);
+ jpeg_create_decompress(&srcinfo);
+ /* Initialize the JPEG compression object with default error handling. */
+ dstinfo.err = jpeg_std_error(&jdsterr);
+ jpeg_create_compress(&dstinfo);
+
+ /* Now safe to enable signal catcher.
+ * Note: we assume only the decompression object will have virtual arrays.
+ */
+#ifdef NEED_SIGNAL_CATCHER
+ enable_signal_catcher((j_common_ptr) &srcinfo);
+#endif
+
+ /* Scan command line to find file names.
+ * It is convenient to use just one switch-parsing routine, but the switch
+ * values read here are mostly ignored; we will rescan the switches after
+ * opening the input file. Also note that most of the switches affect the
+ * destination JPEG object, so we parse into that and then copy over what
+ * needs to affects the source too.
+ */
+
+ file_index = parse_switches(&dstinfo, argc, argv, 0, FALSE);
+ jsrcerr.trace_level = jdsterr.trace_level;
+ srcinfo.mem->max_memory_to_use = dstinfo.mem->max_memory_to_use;
+
+#ifdef TWO_FILE_COMMANDLINE
+ /* Must have either -outfile switch or explicit output file name */
+ if (outfilename == NULL) {
+ if (file_index != argc-2) {
+ fprintf(stderr, "%s: must name one input and one output file\n",
+ progname);
+ usage();
+ }
+ outfilename = argv[file_index+1];
+ } else {
+ if (file_index != argc-1) {
+ fprintf(stderr, "%s: must name one input and one output file\n",
+ progname);
+ usage();
+ }
+ }
+#else
+ /* Unix style: expect zero or one file name */
+ if (file_index < argc-1) {
+ fprintf(stderr, "%s: only one input file\n", progname);
+ usage();
+ }
+#endif /* TWO_FILE_COMMANDLINE */
+
+ /* Open the input file. */
+ if (file_index < argc) {
+ if ((fp = fopen(argv[file_index], READ_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open %s for reading\n", progname, argv[file_index]);
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ /* default input file is stdin */
+ fp = read_stdin();
+ }
+
+#if TRANSFORMS_SUPPORTED
+ /* Open the drop file. */
+ if (dropfilename != NULL) {
+ if ((drop_file = fopen(dropfilename, READ_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open %s for reading\n", progname, dropfilename);
+ exit(EXIT_FAILURE);
+ }
+ dropinfo.err = jpeg_std_error(&jdroperr);
+ jpeg_create_decompress(&dropinfo);
+ jpeg_stdio_src(&dropinfo, drop_file);
+ } else {
+ drop_file = NULL;
+ }
+#endif
+
+#ifdef PROGRESS_REPORT
+ start_progress_monitor((j_common_ptr) &dstinfo, &progress);
+#endif
+
+ /* Specify data source for decompression */
+ jpeg_stdio_src(&srcinfo, fp);
+
+ /* Enable saving of extra markers that we want to copy */
+ jcopy_markers_setup(&srcinfo, copyoption);
+
+ /* Read file header */
+ (void) jpeg_read_header(&srcinfo, TRUE);
+
+#if TRANSFORMS_SUPPORTED
+ if (dropfilename != NULL) {
+ (void) jpeg_read_header(&dropinfo, TRUE);
+ transformoption.crop_width = dropinfo.image_width;
+ transformoption.crop_width_set = JCROP_POS;
+ transformoption.crop_height = dropinfo.image_height;
+ transformoption.crop_height_set = JCROP_POS;
+ transformoption.drop_ptr = &dropinfo;
+ }
+#endif
+
+ /* Any space needed by a transform option must be requested before
+ * jpeg_read_coefficients so that memory allocation will be done right.
+ */
+#if TRANSFORMS_SUPPORTED
+ /* Fails right away if -perfect is given and transformation is not perfect.
+ */
+ if (transformoption.perfect &&
+ !jtransform_perfect_transform(srcinfo.image_width, srcinfo.image_height,
+ srcinfo.max_h_samp_factor * DCTSIZE, srcinfo.max_v_samp_factor * DCTSIZE,
+ transformoption.transform)) {
+ fprintf(stderr, "%s: transformation is not perfect\n", progname);
+ exit(EXIT_FAILURE);
+ }
+ jtransform_request_workspace(&srcinfo, &transformoption);
+#endif
+
+ /* Read source file as DCT coefficients */
+ src_coef_arrays = jpeg_read_coefficients(&srcinfo);
+
+#if TRANSFORMS_SUPPORTED
+ if (dropfilename != NULL) {
+ transformoption.drop_coef_arrays = jpeg_read_coefficients(&dropinfo);
+ }
+#endif
+
+ /* Initialize destination compression parameters from source values */
+ jpeg_copy_critical_parameters(&srcinfo, &dstinfo);
+
+ /* Adjust destination parameters if required by transform options;
+ * also find out which set of coefficient arrays will hold the output.
+ */
+#if TRANSFORMS_SUPPORTED
+ dst_coef_arrays = jtransform_adjust_parameters(&srcinfo, &dstinfo,
+ src_coef_arrays,
+ &transformoption);
+#else
+ dst_coef_arrays = src_coef_arrays;
+#endif
+
+ /* Close input file, if we opened it.
+ * Note: we assume that jpeg_read_coefficients consumed all input
+ * until JPEG_REACHED_EOI, and that jpeg_finish_decompress will
+ * only consume more while (! cinfo->inputctl->eoi_reached).
+ * We cannot call jpeg_finish_decompress here since we still need the
+ * virtual arrays allocated from the source object for processing.
+ */
+ if (fp != stdin)
+ fclose(fp);
+
+ /* Open the output file. */
+ if (outfilename != NULL) {
+ if ((fp = fopen(outfilename, WRITE_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open %s for writing\n", progname, outfilename);
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ /* default output file is stdout */
+ fp = write_stdout();
+ }
+
+ /* Adjust default compression parameters by re-parsing the options */
+ file_index = parse_switches(&dstinfo, argc, argv, 0, TRUE);
+
+ /* Specify data destination for compression */
+ jpeg_stdio_dest(&dstinfo, fp);
+
+ /* Start compressor (note no image data is actually written here) */
+ jpeg_write_coefficients(&dstinfo, dst_coef_arrays);
+
+ /* Copy to the output file any extra markers that we want to preserve */
+ jcopy_markers_execute(&srcinfo, &dstinfo, copyoption);
+
+ /* Execute image transformation, if any */
+#if TRANSFORMS_SUPPORTED
+ jtransform_execute_transform(&srcinfo, &dstinfo,
+ src_coef_arrays,
+ &transformoption);
+#endif
+
+ /* Finish compression and release memory */
+ jpeg_finish_compress(&dstinfo);
+ jpeg_destroy_compress(&dstinfo);
+#if TRANSFORMS_SUPPORTED
+ if (dropfilename != NULL) {
+ (void) jpeg_finish_decompress(&dropinfo);
+ jpeg_destroy_decompress(&dropinfo);
+ }
+#endif
+ (void) jpeg_finish_decompress(&srcinfo);
+ jpeg_destroy_decompress(&srcinfo);
+
+ /* Close files, if we opened them */
+ if (fp != stdout)
+ fclose(fp);
+#if TRANSFORMS_SUPPORTED
+ if (drop_file != NULL)
+ fclose(drop_file);
+#endif
+
+#ifdef PROGRESS_REPORT
+ end_progress_monitor((j_common_ptr) &dstinfo);
+#endif
+
+ /* All done. */
+#if TRANSFORMS_SUPPORTED
+ if (dropfilename != NULL)
+ exit(jsrcerr.num_warnings + jdroperr.num_warnings + jdsterr.num_warnings ?
+ EXIT_WARNING : EXIT_SUCCESS);
+#endif
+ exit(jsrcerr.num_warnings + jdsterr.num_warnings ?EXIT_WARNING:EXIT_SUCCESS);
+ return 0; /* suppress no-return-value warnings */
+}
diff --git a/jpeg-6c/jquant1.c b/jpeg-6c/jquant1.c
new file mode 100644
index 0000000..db712ee
--- /dev/null
+++ b/jpeg-6c/jquant1.c
@@ -0,0 +1,865 @@
+/*
+ * jquant1.c
+ *
+ * Copyright (C) 1991-1996, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains 1-pass color quantization (color mapping) routines.
+ * These routines provide mapping to a fixed color map using equally spaced
+ * color values. Optional Floyd-Steinberg or ordered dithering is available.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+#ifdef QUANT_1PASS_SUPPORTED
+
+
+/*
+ * The main purpose of 1-pass quantization is to provide a fast, if not very
+ * high quality, colormapped output capability. A 2-pass quantizer usually
+ * gives better visual quality; however, for quantized grayscale output this
+ * quantizer is perfectly adequate. Dithering is highly recommended with this
+ * quantizer, though you can turn it off if you really want to.
+ *
+ * In 1-pass quantization the colormap must be chosen in advance of seeing the
+ * image. We use a map consisting of all combinations of Ncolors[i] color
+ * values for the i'th component. The Ncolors[] values are chosen so that
+ * their product, the total number of colors, is no more than that requested.
+ * (In most cases, the product will be somewhat less.)
+ *
+ * Since the colormap is orthogonal, the representative value for each color
+ * component can be determined without considering the other components;
+ * then these indexes can be combined into a colormap index by a standard
+ * N-dimensional-array-subscript calculation. Most of the arithmetic involved
+ * can be precalculated and stored in the lookup table colorindex[].
+ * colorindex[i][j] maps pixel value j in component i to the nearest
+ * representative value (grid plane) for that component; this index is
+ * multiplied by the array stride for component i, so that the
+ * index of the colormap entry closest to a given pixel value is just
+ * sum( colorindex[component-number][pixel-component-value] )
+ * Aside from being fast, this scheme allows for variable spacing between
+ * representative values with no additional lookup cost.
+ *
+ * If gamma correction has been applied in color conversion, it might be wise
+ * to adjust the color grid spacing so that the representative colors are
+ * equidistant in linear space. At this writing, gamma correction is not
+ * implemented by jdcolor, so nothing is done here.
+ */
+
+
+/* Declarations for ordered dithering.
+ *
+ * We use a standard 16x16 ordered dither array. The basic concept of ordered
+ * dithering is described in many references, for instance Dale Schumacher's
+ * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
+ * In place of Schumacher's comparisons against a "threshold" value, we add a
+ * "dither" value to the input pixel and then round the result to the nearest
+ * output value. The dither value is equivalent to (0.5 - threshold) times
+ * the distance between output values. For ordered dithering, we assume that
+ * the output colors are equally spaced; if not, results will probably be
+ * worse, since the dither may be too much or too little at a given point.
+ *
+ * The normal calculation would be to form pixel value + dither, range-limit
+ * this to 0..cinfo->maxjsample, and then index into the colorindex table as usual.
+ * We can skip the separate range-limiting step by extending the colorindex
+ * table in both directions.
+ */
+
+#define ODITHER_SIZE 16 /* dimension of dither matrix */
+/* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
+#define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
+#define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
+
+typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
+typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
+
+static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
+ /* Bayer's order-4 dither array. Generated by the code given in
+ * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
+ * The values in this array must range from 0 to ODITHER_CELLS-1.
+ */
+ { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
+ { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
+ { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
+ { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
+ { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
+ { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
+ { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
+ { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
+ { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
+ { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
+ { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
+ { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
+ { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
+ { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
+ { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
+ { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
+};
+
+
+/* Declarations for Floyd-Steinberg dithering.
+ *
+ * Errors are accumulated into the array fserrors[], at a resolution of
+ * 1/16th of a pixel count. The error at a given pixel is propagated
+ * to its not-yet-processed neighbors using the standard F-S fractions,
+ * ... (here) 7/16
+ * 3/16 5/16 1/16
+ * We work left-to-right on even rows, right-to-left on odd rows.
+ *
+ * We can get away with a single array (holding one row's worth of errors)
+ * by using it to store the current row's errors at pixel columns not yet
+ * processed, but the next row's errors at columns already processed. We
+ * need only a few extra variables to hold the errors immediately around the
+ * current column. (If we are lucky, those variables are in registers, but
+ * even if not, they're probably cheaper to access than array elements are.)
+ *
+ * The fserrors[] array is indexed [component#][position].
+ * We provide (#columns + 2) entries per component; the extra entry at each
+ * end saves us from special-casing the first and last pixels.
+ *
+ * Note: on a wide image, we might not have enough room in a PC's near data
+ * segment to hold the error array; so it is allocated with alloc_large.
+ */
+
+/*#if BITS_IN_JSAMPLE == 8
+typedef INT16 FSERROR;*/ /* 16 bits should be enough */
+/*typedef int LOCFSERROR;*/ /* use 'int' for calculation temps */
+/*#else*/
+typedef INT32 FSERROR; /* may need more than 16 bits */
+typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
+/*#endif*/
+
+typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
+
+
+/* Private subobject */
+
+#define MAX_Q_COMPS 4 /* max components I can handle */
+
+typedef struct {
+ struct jpeg_color_quantizer pub; /* public fields */
+
+ /* Initially allocated colormap is saved here */
+ JSAMPARRAY16 sv_colormap; /* The color map as a 2-D pixel array */
+ int sv_actual; /* number of entries in use */
+
+ JSAMPARRAY16 colorindex; /* Precomputed mapping for speed */
+ /* colorindex[i][j] = index of color closest to pixel value j in component i,
+ * premultiplied as described above. Since colormap indexes must fit into
+ * JSAMPLEs, the entries of this array will too.
+ */
+ boolean is_padded; /* is the colorindex padded for odither? */
+
+ int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
+
+ /* Variables for ordered dithering */
+ int row_index; /* cur row's vertical index in dither matrix */
+ ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
+
+ /* Variables for Floyd-Steinberg dithering */
+ FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
+ boolean on_odd_row; /* flag to remember which row we are on */
+} my_cquantizer;
+
+typedef my_cquantizer * my_cquantize_ptr;
+
+
+/*
+ * Policy-making subroutines for create_colormap and create_colorindex.
+ * These routines determine the colormap to be used. The rest of the module
+ * only assumes that the colormap is orthogonal.
+ *
+ * * select_ncolors decides how to divvy up the available colors
+ * among the components.
+ * * output_value defines the set of representative values for a component.
+ * * largest_input_value defines the mapping from input values to
+ * representative values for a component.
+ * Note that the latter two routines may impose different policies for
+ * different components, though this is not currently done.
+ */
+
+
+LOCAL(int)
+select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
+/* Determine allocation of desired colors to components, */
+/* and fill in Ncolors[] array to indicate choice. */
+/* Return value is total number of colors (product of Ncolors[] values). */
+{
+ int nc = cinfo->out_color_components; /* number of color components */
+ int max_colors = cinfo->desired_number_of_colors;
+ int total_colors, iroot, i, j;
+ boolean changed;
+ long temp;
+ static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
+
+ /* We can allocate at least the nc'th root of max_colors per component. */
+ /* Compute floor(nc'th root of max_colors). */
+ iroot = 1;
+ do {
+ iroot++;
+ temp = iroot; /* set temp = iroot ** nc */
+ for (i = 1; i < nc; i++)
+ temp *= iroot;
+ } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
+ iroot--; /* now iroot = floor(root) */
+
+ /* Must have at least 2 color values per component */
+ if (iroot < 2)
+ ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
+
+ /* Initialize to iroot color values for each component */
+ total_colors = 1;
+ for (i = 0; i < nc; i++) {
+ Ncolors[i] = iroot;
+ total_colors *= iroot;
+ }
+ /* We may be able to increment the count for one or more components without
+ * exceeding max_colors, though we know not all can be incremented.
+ * Sometimes, the first component can be incremented more than once!
+ * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
+ * In RGB colorspace, try to increment G first, then R, then B.
+ */
+ do {
+ changed = FALSE;
+ for (i = 0; i < nc; i++) {
+ j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
+ /* calculate new total_colors if Ncolors[j] is incremented */
+ temp = total_colors / Ncolors[j];
+ temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
+ if (temp > (long) max_colors)
+ break; /* won't fit, done with this pass */
+ Ncolors[j]++; /* OK, apply the increment */
+ total_colors = (int) temp;
+ changed = TRUE;
+ }
+ } while (changed);
+
+ return total_colors;
+}
+
+
+LOCAL(int)
+output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
+/* Return j'th output value, where j will range from 0 to maxj */
+/* The output values must fall in 0..cinfo->maxjsample in increasing order */
+{
+ /* We always provide values 0 and cinfo->maxjsample for each component;
+ * any additional values are equally spaced between these limits.
+ * (Forcing the upper and lower values to the limits ensures that
+ * dithering can't produce a color outside the selected gamut.)
+ */
+ return (int) (((INT32) j * cinfo->maxjsample + maxj/2) / maxj);
+}
+
+
+LOCAL(int)
+largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
+/* Return largest input value that should map to j'th output value */
+/* Must have largest(j=0) >= 0, and largest(j=maxj) >= cinfo->maxjsample */
+{
+ /* Breakpoints are halfway between values returned by output_value */
+ return (int) (((INT32) (2*j + 1) * cinfo->maxjsample + maxj) / (2*maxj));
+}
+
+
+/*
+ * Create the colormap.
+ */
+
+LOCAL(void)
+create_colormap (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ JSAMPARRAY16 colormap16; /* Created colormap */
+ JSAMPARRAY colormap; /* Created 8 bit colormap */
+ int total_colors; /* Number of distinct output colors */
+ int i,j,k, nci, blksize, blkdist, ptr, val;
+
+ /* Select number of colors for each component */
+ total_colors = select_ncolors(cinfo, cquantize->Ncolors);
+
+ /* Report selected color counts */
+ if (cinfo->out_color_components == 3)
+ TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
+ total_colors, cquantize->Ncolors[0],
+ cquantize->Ncolors[1], cquantize->Ncolors[2]);
+ else
+ TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
+
+ /* Allocate and fill in the colormaps. */
+ /* The colors are ordered in the map in standard row-major order, */
+ /* i.e. rightmost (highest-indexed) color changes most rapidly. */
+
+ colormap16 = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) total_colors * SIZEOF(JSAMPLE16),
+ (JDIMENSION) cinfo->out_color_components);
+
+ colormap = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) total_colors * SIZEOF(JSAMPLE),
+ (JDIMENSION) cinfo->out_color_components);
+
+ /* blksize is number of adjacent repeated entries for a component */
+ /* blkdist is distance between groups of identical entries for a component */
+ blkdist = total_colors;
+
+ for (i = 0; i < cinfo->out_color_components; i++) {
+ /* fill in colormap entries for i'th color component */
+ nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
+ blksize = blkdist / nci;
+ for (j = 0; j < nci; j++) {
+ /* Compute j'th output value (out of nci) for component */
+ val = output_value(cinfo, i, j, nci-1);
+ /* Fill in all colormap entries that have this value of this component */
+ for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
+ /* fill in blksize entries beginning at ptr */
+ for (k = 0; k < blksize; k++)
+ colormap16[i][ptr+k] = (JSAMPLE16) val;
+ colormap[i][ptr+k] = (JSAMPLE)(val & 0xFF);/* 8 bit too. */
+ }
+ }
+ blkdist = blksize; /* blksize of this color is blkdist of next */
+ }
+
+ /* Save the colormap in private storage,
+ * where it will survive color quantization mode changes.
+ */
+ cquantize->sv_colormap = colormap16;
+ cquantize->sv_actual = total_colors;
+}
+
+
+/*
+ * Create the color index table.
+ */
+
+LOCAL(void)
+create_colorindex (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ JSAMPROW16 indexptr;
+ int i,j,k, nci, blksize, val, pad;
+
+ /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
+ * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
+ * This is not necessary in the other dithering modes. However, we
+ * flag whether it was done in case user changes dithering mode.
+ */
+ if (cinfo->dither_mode == JDITHER_ORDERED) {
+ pad = cinfo->maxjsample*2;
+ cquantize->is_padded = TRUE;
+ } else {
+ pad = 0;
+ cquantize->is_padded = FALSE;
+ }
+
+ cquantize->colorindex = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) (cinfo->maxjsample+1 + pad) * SIZEOF(JSAMPLE16),
+ (JDIMENSION) cinfo->out_color_components);
+
+ /* blksize is number of adjacent repeated entries for a component */
+ blksize = cquantize->sv_actual;
+
+ for (i = 0; i < cinfo->out_color_components; i++) {
+ /* fill in colorindex entries for i'th color component */
+ nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
+ blksize = blksize / nci;
+
+ /* adjust colorindex pointers to provide padding at negative indexes. */
+ if (pad)
+ cquantize->colorindex[i] += cinfo->maxjsample;
+
+ /* in loop, val = index of current output value, */
+ /* and k = largest j that maps to current val */
+ indexptr = cquantize->colorindex[i];
+ val = 0;
+ k = largest_input_value(cinfo, i, 0, nci-1);
+ for (j = 0; j <= cinfo->maxjsample; j++) {
+ while (j > k) /* advance val if past boundary */
+ k = largest_input_value(cinfo, i, ++val, nci-1);
+ /* premultiply so that no multiplication needed in main processing */
+ indexptr[j] = (JSAMPLE16) (val * blksize);
+ }
+ /* Pad at both ends if necessary */
+ if (pad)
+ for (j = 1; j <= cinfo->maxjsample; j++) {
+ indexptr[-j] = indexptr[0];
+ indexptr[cinfo->maxjsample+j] = indexptr[cinfo->maxjsample];
+ }
+ }
+}
+
+
+/*
+ * Create an ordered-dither array for a component having ncolors
+ * distinct output values.
+ */
+
+LOCAL(ODITHER_MATRIX_PTR)
+make_odither_array (j_decompress_ptr cinfo, int ncolors)
+{
+ ODITHER_MATRIX_PTR odither;
+ int j,k;
+ INT32 num,den;
+
+ odither = (ODITHER_MATRIX_PTR)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(ODITHER_MATRIX));
+ /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
+ * Hence the dither value for the matrix cell with fill order f
+ * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
+ * On 16-bit-int machine, be careful to avoid overflow.
+ */
+ den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
+ for (j = 0; j < ODITHER_SIZE; j++) {
+ for (k = 0; k < ODITHER_SIZE; k++) {
+ num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
+ * cinfo->maxjsample;
+ /* Ensure round towards zero despite C's lack of consistency
+ * about rounding negative values in integer division...
+ */
+ odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
+ }
+ }
+ return odither;
+}
+
+
+/*
+ * Create the ordered-dither tables.
+ * Components having the same number of representative colors may
+ * share a dither table.
+ */
+
+LOCAL(void)
+create_odither_tables (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ ODITHER_MATRIX_PTR odither;
+ int i, j, nci;
+
+ for (i = 0; i < cinfo->out_color_components; i++) {
+ nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
+ odither = NULL; /* search for matching prior component */
+ for (j = 0; j < i; j++) {
+ if (nci == cquantize->Ncolors[j]) {
+ odither = cquantize->odither[j];
+ break;
+ }
+ }
+ if (odither == NULL) /* need a new table? */
+ odither = make_odither_array(cinfo, nci);
+ cquantize->odither[i] = odither;
+ }
+}
+
+
+/*
+ * Map some rows of pixels to the output colormapped representation.
+ */
+
+METHODDEF(void)
+color_quantize (j_decompress_ptr cinfo, JSAMPARRAY16 input_buf,
+ JSAMPARRAY16 output_buf, int num_rows)
+/* General case, no dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ JSAMPARRAY16 colorindex = cquantize->colorindex;
+ register int pixcode, ci;
+ register JSAMPROW16 ptrin, ptrout;
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+ register int nc = cinfo->out_color_components;
+
+ for (row = 0; row < num_rows; row++) {
+ ptrin = input_buf[row];
+ ptrout = output_buf[row];
+ for (col = width; col > 0; col--) {
+ pixcode = 0;
+ for (ci = 0; ci < nc; ci++) {
+ pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
+ }
+ *ptrout++ = (JSAMPLE16) pixcode;
+ }
+ }
+}
+
+
+METHODDEF(void)
+color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY16 input_buf,
+ JSAMPARRAY16 output_buf, int num_rows)
+/* Fast path for out_color_components==3, no dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ register int pixcode;
+ register JSAMPROW16 ptrin, ptrout;
+ JSAMPROW16 colorindex0 = cquantize->colorindex[0];
+ JSAMPROW16 colorindex1 = cquantize->colorindex[1];
+ JSAMPROW16 colorindex2 = cquantize->colorindex[2];
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+
+ for (row = 0; row < num_rows; row++) {
+ ptrin = input_buf[row];
+ ptrout = output_buf[row];
+ for (col = width; col > 0; col--) {
+ pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
+ pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
+ pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
+ *ptrout++ = (JSAMPLE16) pixcode;
+ }
+ }
+}
+
+
+METHODDEF(void)
+quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY16 input_buf,
+ JSAMPARRAY16 output_buf, int num_rows)
+/* General case, with ordered dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ register JSAMPROW16 input_ptr;
+ register JSAMPROW16 output_ptr;
+ JSAMPROW16 colorindex_ci;
+ int * dither; /* points to active row of dither matrix */
+ int row_index, col_index; /* current indexes into dither matrix */
+ int nc = cinfo->out_color_components;
+ int ci;
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+
+ for (row = 0; row < num_rows; row++) {
+ /* Initialize output values to 0 so can process components separately */
+ jzero_far((void FAR *) output_buf[row],
+ (size_t) (width * SIZEOF(JSAMPLE16)));
+ row_index = cquantize->row_index;
+ for (ci = 0; ci < nc; ci++) {
+ input_ptr = input_buf[row] + ci;
+ output_ptr = output_buf[row];
+ colorindex_ci = cquantize->colorindex[ci];
+ dither = cquantize->odither[ci][row_index];
+ col_index = 0;
+
+ for (col = width; col > 0; col--) {
+ /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
+ * select output value, accumulate into output code for this pixel.
+ * Range-limiting need not be done explicitly, as we have extended
+ * the colorindex table to produce the right answers for out-of-range
+ * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
+ * required amount of padding.
+ */
+ *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
+ input_ptr += nc;
+ output_ptr++;
+ col_index = (col_index + 1) & ODITHER_MASK;
+ }
+ }
+ /* Advance row index for next row */
+ row_index = (row_index + 1) & ODITHER_MASK;
+ cquantize->row_index = row_index;
+ }
+}
+
+
+METHODDEF(void)
+quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY16 input_buf,
+ JSAMPARRAY16 output_buf, int num_rows)
+/* Fast path for out_color_components==3, with ordered dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ register int pixcode;
+ register JSAMPROW16 input_ptr;
+ register JSAMPROW16 output_ptr;
+ JSAMPROW16 colorindex0 = cquantize->colorindex[0];
+ JSAMPROW16 colorindex1 = cquantize->colorindex[1];
+ JSAMPROW16 colorindex2 = cquantize->colorindex[2];
+ int * dither0; /* points to active row of dither matrix */
+ int * dither1;
+ int * dither2;
+ int row_index, col_index; /* current indexes into dither matrix */
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+
+ for (row = 0; row < num_rows; row++) {
+ row_index = cquantize->row_index;
+ input_ptr = input_buf[row];
+ output_ptr = output_buf[row];
+ dither0 = cquantize->odither[0][row_index];
+ dither1 = cquantize->odither[1][row_index];
+ dither2 = cquantize->odither[2][row_index];
+ col_index = 0;
+
+ for (col = width; col > 0; col--) {
+ pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
+ dither0[col_index]]);
+ pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
+ dither1[col_index]]);
+ pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
+ dither2[col_index]]);
+ *output_ptr++ = (JSAMPLE16) pixcode;
+ col_index = (col_index + 1) & ODITHER_MASK;
+ }
+ row_index = (row_index + 1) & ODITHER_MASK;
+ cquantize->row_index = row_index;
+ }
+}
+
+
+METHODDEF(void)
+quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY16 input_buf,
+ JSAMPARRAY16 output_buf, int num_rows)
+/* General case, with Floyd-Steinberg dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ register LOCFSERROR cur; /* current error or pixel value */
+ LOCFSERROR belowerr; /* error for pixel below cur */
+ LOCFSERROR bpreverr; /* error for below/prev col */
+ LOCFSERROR bnexterr; /* error for below/next col */
+ LOCFSERROR delta;
+ register FSERRPTR errorptr; /* => fserrors[] at column before current */
+ register JSAMPROW16 input_ptr;
+ register JSAMPROW16 output_ptr;
+ JSAMPROW16 colorindex_ci;
+ JSAMPROW16 colormap_ci;
+ int pixcode;
+ int nc = cinfo->out_color_components;
+ int dir; /* 1 for left-to-right, -1 for right-to-left */
+ int dirnc; /* dir * nc */
+ int ci;
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+ JSAMPLE16 *range_limit = cinfo->sample_range_limit;
+ SHIFT_TEMPS
+
+ for (row = 0; row < num_rows; row++) {
+ /* Initialize output values to 0 so can process components separately */
+ jzero_far((void FAR *) output_buf[row],
+ (size_t) (width * SIZEOF(JSAMPLE16)));
+ for (ci = 0; ci < nc; ci++) {
+ input_ptr = input_buf[row] + ci;
+ output_ptr = output_buf[row];
+ if (cquantize->on_odd_row) {
+ /* work right to left in this row */
+ input_ptr += (width-1) * nc; /* so point to rightmost pixel */
+ output_ptr += width-1;
+ dir = -1;
+ dirnc = -nc;
+ errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
+ } else {
+ /* work left to right in this row */
+ dir = 1;
+ dirnc = nc;
+ errorptr = cquantize->fserrors[ci]; /* => entry before first column */
+ }
+ colorindex_ci = cquantize->colorindex[ci];
+ colormap_ci = cquantize->sv_colormap[ci];
+ /* Preset error values: no error propagated to first pixel from left */
+ cur = 0;
+ /* and no error propagated to row below yet */
+ belowerr = bpreverr = 0;
+
+ for (col = width; col > 0; col--) {
+ /* cur holds the error propagated from the previous pixel on the
+ * current line. Add the error propagated from the previous line
+ * to form the complete error correction term for this pixel, and
+ * round the error term (which is expressed * 16) to an integer.
+ * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
+ * for either sign of the error value.
+ * Note: errorptr points to *previous* column's array entry.
+ */
+ cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
+ /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
+ * The maximum error is +- MAXJSAMPLE; this sets the required size
+ * of the range_limit array.
+ */
+ cur += GETJSAMPLE(*input_ptr);
+ cur = GETJSAMPLE(range_limit[cur]);
+ /* Select output value, accumulate into output code for this pixel */
+ pixcode = GETJSAMPLE(colorindex_ci[cur]);
+ *output_ptr += (JSAMPLE16) pixcode;
+ /* Compute actual representation error at this pixel */
+ /* Note: we can do this even though we don't have the final */
+ /* pixel code, because the colormap is orthogonal. */
+ cur -= GETJSAMPLE(colormap_ci[pixcode]);
+ /* Compute error fractions to be propagated to adjacent pixels.
+ * Add these into the running sums, and simultaneously shift the
+ * next-line error sums left by 1 column.
+ */
+ bnexterr = cur;
+ delta = cur * 2;
+ cur += delta; /* form error * 3 */
+ errorptr[0] = (FSERROR) (bpreverr + cur);
+ cur += delta; /* form error * 5 */
+ bpreverr = belowerr + cur;
+ belowerr = bnexterr;
+ cur += delta; /* form error * 7 */
+ /* At this point cur contains the 7/16 error value to be propagated
+ * to the next pixel on the current line, and all the errors for the
+ * next line have been shifted over. We are therefore ready to move on.
+ */
+ input_ptr += dirnc; /* advance input ptr to next column */
+ output_ptr += dir; /* advance output ptr to next column */
+ errorptr += dir; /* advance errorptr to current column */
+ }
+ /* Post-loop cleanup: we must unload the final error value into the
+ * final fserrors[] entry. Note we need not unload belowerr because
+ * it is for the dummy column before or after the actual array.
+ */
+ errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
+ }
+ cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
+ }
+}
+
+
+/*
+ * Allocate workspace for Floyd-Steinberg errors.
+ */
+
+LOCAL(void)
+alloc_fs_workspace (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ size_t arraysize;
+ int i;
+
+ arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
+ for (i = 0; i < cinfo->out_color_components; i++) {
+ cquantize->fserrors[i] = (FSERRPTR)
+ (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
+ }
+}
+
+
+/*
+ * Initialize for one-pass color quantization.
+ */
+
+METHODDEF(void)
+start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ size_t arraysize;
+ int i;
+
+ /* Install my colormap. */
+ cinfo->colormap16 = cquantize->sv_colormap;
+ cinfo->actual_number_of_colors = cquantize->sv_actual;
+
+ /* Initialize for desired dithering mode. */
+ switch (cinfo->dither_mode) {
+ case JDITHER_NONE:
+ if (cinfo->out_color_components == 3)
+ cquantize->pub.color_quantize = color_quantize3;
+ else
+ cquantize->pub.color_quantize = color_quantize;
+ break;
+ case JDITHER_ORDERED:
+ if (cinfo->out_color_components == 3)
+ cquantize->pub.color_quantize = quantize3_ord_dither;
+ else
+ cquantize->pub.color_quantize = quantize_ord_dither;
+ cquantize->row_index = 0; /* initialize state for ordered dither */
+ /* If user changed to ordered dither from another mode,
+ * we must recreate the color index table with padding.
+ * This will cost extra space, but probably isn't very likely.
+ */
+ if (! cquantize->is_padded)
+ create_colorindex(cinfo);
+ /* Create ordered-dither tables if we didn't already. */
+ if (cquantize->odither[0] == NULL)
+ create_odither_tables(cinfo);
+ break;
+ case JDITHER_FS:
+ cquantize->pub.color_quantize = quantize_fs_dither;
+ cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
+ /* Allocate Floyd-Steinberg workspace if didn't already. */
+ if (cquantize->fserrors[0] == NULL)
+ alloc_fs_workspace(cinfo);
+ /* Initialize the propagated errors to zero. */
+ arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
+ for (i = 0; i < cinfo->out_color_components; i++)
+ jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
+ break;
+ default:
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ break;
+ }
+}
+
+
+/*
+ * Finish up at the end of the pass.
+ */
+
+METHODDEF(void)
+finish_pass_1_quant (j_decompress_ptr cinfo)
+{
+ /* no work in 1-pass case */
+}
+
+
+/*
+ * Switch to a new external colormap between output passes.
+ * Shouldn't get to this module!
+ */
+
+METHODDEF(void)
+new_color_map_1_quant (j_decompress_ptr cinfo)
+{
+ ERREXIT(cinfo, JERR_MODE_CHANGE);
+}
+
+
+/*
+ * Module initialization routine for 1-pass color quantization.
+ */
+
+GLOBAL(void)
+jinit_1pass_quantizer (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize;
+
+ cquantize = (my_cquantize_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_cquantizer));
+ cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
+ cquantize->pub.start_pass = start_pass_1_quant;
+ cquantize->pub.finish_pass = finish_pass_1_quant;
+ cquantize->pub.new_color_map = new_color_map_1_quant;
+ cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
+ cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
+
+ /* Make sure my internal arrays won't overflow */
+ if (cinfo->out_color_components > MAX_Q_COMPS)
+ ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
+ /* Make sure colormap indexes can be represented by JSAMPLEs */
+ if (cinfo->desired_number_of_colors > (cinfo->maxjsample+1))
+ ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, cinfo->maxjsample+1);
+
+ /* Create the colormap and color index table. */
+ create_colormap(cinfo);
+ create_colorindex(cinfo);
+
+ /* Allocate Floyd-Steinberg workspace now if requested.
+ * We do this now since it is FAR storage and may affect the memory
+ * manager's space calculations. If the user changes to FS dither
+ * mode in a later pass, we will allocate the space then, and will
+ * possibly overrun the max_memory_to_use setting.
+ */
+ if (cinfo->dither_mode == JDITHER_FS)
+ alloc_fs_workspace(cinfo);
+}
+
+#endif /* QUANT_1PASS_SUPPORTED */
diff --git a/jpeg-6c/jquant2.c b/jpeg-6c/jquant2.c
new file mode 100644
index 0000000..1b1bd68
--- /dev/null
+++ b/jpeg-6c/jquant2.c
@@ -0,0 +1,1331 @@
+/*
+ * jquant2.c
+ *
+ * Copyright (C) 1991-1996, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * Memory fix by Marcel van Herk (mvh) of the Netherlands Cancer Institute.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains 2-pass color quantization (color mapping) routines.
+ * These routines provide selection of a custom color map for an image,
+ * followed by mapping of the image to that color map, with optional
+ * Floyd-Steinberg dithering.
+ * It is also possible to use just the second pass to map to an arbitrary
+ * externally-given color map.
+ *
+ * Note: ordered dithering is not supported, since there isn't any fast
+ * way to compute intercolor distances; it's unclear that ordered dither's
+ * fundamental assumptions even hold with an irregularly spaced color map.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jmemsys.h"
+
+#ifdef QUANT_2PASS_SUPPORTED
+
+
+/*
+ * This module implements the well-known Heckbert paradigm for color
+ * quantization. Most of the ideas used here can be traced back to
+ * Heckbert's seminal paper
+ * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
+ * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
+ *
+ * In the first pass over the image, we accumulate a histogram showing the
+ * usage count of each possible color. To keep the histogram to a reasonable
+ * size, we reduce the precision of the input; typical practice is to retain
+ * 5 or 6 bits per color, so that 8 or 4 different input values are counted
+ * in the same histogram cell.
+ *
+ * Next, the color-selection step begins with a box representing the whole
+ * color space, and repeatedly splits the "largest" remaining box until we
+ * have as many boxes as desired colors. Then the mean color in each
+ * remaining box becomes one of the possible output colors.
+ *
+ * The second pass over the image maps each input pixel to the closest output
+ * color (optionally after applying a Floyd-Steinberg dithering correction).
+ * This mapping is logically trivial, but making it go fast enough requires
+ * considerable care.
+ *
+ * Heckbert-style quantizers vary a good deal in their policies for choosing
+ * the "largest" box and deciding where to cut it. The particular policies
+ * used here have proved out well in experimental comparisons, but better ones
+ * may yet be found.
+ *
+ * In earlier versions of the IJG code, this module quantized in YCbCr color
+ * space, processing the raw upsampled data without a color conversion step.
+ * This allowed the color conversion math to be done only once per colormap
+ * entry, not once per pixel. However, that optimization precluded other
+ * useful optimizations (such as merging color conversion with upsampling)
+ * and it also interfered with desired capabilities such as quantizing to an
+ * externally-supplied colormap. We have therefore abandoned that approach.
+ * The present code works in the post-conversion color space, typically RGB.
+ *
+ * To improve the visual quality of the results, we actually work in scaled
+ * RGB space, giving G distances more weight than R, and R in turn more than
+ * B. To do everything in integer math, we must use integer scale factors.
+ * The 2/3/1 scale factors used here correspond loosely to the relative
+ * weights of the colors in the NTSC grayscale equation.
+ * If you want to use this code to quantize a non-RGB color space, you'll
+ * probably need to change these scale factors.
+ */
+
+#define R_SCALE 2 /* scale R distances by this much */
+#define G_SCALE 3 /* scale G distances by this much */
+#define B_SCALE 1 /* and B by this much */
+
+/* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
+ * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
+ * and B,G,R orders. If you define some other weird order in jmorecfg.h,
+ * you'll get compile errors until you extend this logic. In that case
+ * you'll probably want to tweak the histogram sizes too.
+ */
+
+#if RGB_RED == 0
+#define C0_SCALE R_SCALE
+#endif
+#if RGB_BLUE == 0
+#define C0_SCALE B_SCALE
+#endif
+#if RGB_GREEN == 1
+#define C1_SCALE G_SCALE
+#endif
+#if RGB_RED == 2
+#define C2_SCALE R_SCALE
+#endif
+#if RGB_BLUE == 2
+#define C2_SCALE B_SCALE
+#endif
+
+
+/*
+ * First we have the histogram data structure and routines for creating it.
+ *
+ * The number of bits of precision can be adjusted by changing these symbols.
+ * We recommend keeping 6 bits for G and 5 each for R and B.
+ * If you have plenty of memory and cycles, 6 bits all around gives marginally
+ * better results; if you are short of memory, 5 bits all around will save
+ * some space but degrade the results.
+ * To maintain a fully accurate histogram, we'd need to allocate a "long"
+ * (preferably unsigned long) for each cell. In practice this is overkill;
+ * we can get by with 16 bits per cell. Few of the cell counts will overflow,
+ * and clamping those that do overflow to the maximum value will give close-
+ * enough results. This reduces the recommended histogram size from 256Kb
+ * to 128Kb, which is a useful savings on PC-class machines.
+ * (In the second pass the histogram space is re-used for pixel mapping data;
+ * in that capacity, each cell must be able to store zero to the number of
+ * desired colors. 16 bits/cell is plenty for that too.)
+ * Since the JPEG code is intended to run in small memory model on 80x86
+ * machines, we can't just allocate the histogram in one chunk. Instead
+ * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
+ * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
+ * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
+ * on 80x86 machines, the pointer row is in near memory but the actual
+ * arrays are in far memory (same arrangement as we use for image arrays).
+ */
+
+#define MAXNUMCOLORS (cinfo->maxjsample+1) /* maximum size of colormap */
+
+/* These will do the right thing for either R,G,B or B,G,R color order,
+ * but you may not like the results for other color orders.
+ */
+#define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
+#define HIST_C1_BITS 6 /* bits of precision in G histogram */
+#define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
+
+/* Number of elements along histogram axes. */
+#define HIST_C0_ELEMS (1<<HIST_C0_BITS)
+#define HIST_C1_ELEMS (1<<HIST_C1_BITS)
+#define HIST_C2_ELEMS (1<<HIST_C2_BITS)
+
+/* These are the amounts to shift an input value to get a histogram index. */
+#define C0_SHIFT (cinfo->data_precision - HIST_C0_BITS)
+#define C1_SHIFT (cinfo->data_precision - HIST_C1_BITS)
+#define C2_SHIFT (cinfo->data_precision - HIST_C2_BITS)
+
+
+typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
+
+typedef histcell FAR * histptr; /* for pointers to histogram cells */
+
+typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
+typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
+typedef hist2d * hist3d; /* type for top-level pointer */
+
+
+/* Declarations for Floyd-Steinberg dithering.
+ *
+ * Errors are accumulated into the array fserrors[], at a resolution of
+ * 1/16th of a pixel count. The error at a given pixel is propagated
+ * to its not-yet-processed neighbors using the standard F-S fractions,
+ * ... (here) 7/16
+ * 3/16 5/16 1/16
+ * We work left-to-right on even rows, right-to-left on odd rows.
+ *
+ * We can get away with a single array (holding one row's worth of errors)
+ * by using it to store the current row's errors at pixel columns not yet
+ * processed, but the next row's errors at columns already processed. We
+ * need only a few extra variables to hold the errors immediately around the
+ * current column. (If we are lucky, those variables are in registers, but
+ * even if not, they're probably cheaper to access than array elements are.)
+ *
+ * The fserrors[] array has (#columns + 2) entries; the extra entry at
+ * each end saves us from special-casing the first and last pixels.
+ * Each entry is three values long, one value for each color component.
+ *
+ * Note: on a wide image, we might not have enough room in a PC's near data
+ * segment to hold the error array; so it is allocated with alloc_large.
+ */
+
+/*#if BITS_IN_JSAMPLE == 8
+typedef INT16 FSERROR;*/ /* 16 bits should be enough */
+/*typedef int LOCFSERROR;*/ /* use 'int' for calculation temps */
+/*#else*/
+typedef INT32 FSERROR; /* may need more than 16 bits */
+typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
+/*#endif*/
+
+typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
+
+
+/* Private subobject */
+
+typedef struct {
+ struct jpeg_color_quantizer pub; /* public fields */
+
+ /* Space for the eventually created colormap is stashed here */
+ JSAMPARRAY16 sv_colormap; /* colormap allocated at init time */
+ JSAMPARRAY sv_colormap8; /* colormap allocated at init time */
+ int desired; /* desired # of colors = size of colormap */
+
+ /* Variables for accumulating image statistics */
+ hist3d histogram; /* pointer to the histogram */
+
+ boolean needs_zeroed; /* TRUE if next pass must zero histogram */
+
+ /* Variables for Floyd-Steinberg dithering */
+ FSERRPTR fserrors; /* accumulated errors */
+ boolean on_odd_row; /* flag to remember which row we are on */
+ int * error_limiter; /* table for clamping the applied error */
+} my_cquantizer;
+
+typedef my_cquantizer * my_cquantize_ptr;
+
+
+/*
+ * Prescan some rows of pixels.
+ * In this module the prescan simply updates the histogram, which has been
+ * initialized to zeroes by start_pass.
+ * An output_buf parameter is required by the method signature, but no data
+ * is actually output (in fact the buffer controller is probably passing a
+ * NULL pointer).
+ */
+
+METHODDEF(void)
+prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY16 input_buf,
+ JSAMPARRAY16 output_buf, int num_rows)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ register JSAMPROW16 ptr;
+ register histptr histp;
+ register hist3d histogram = cquantize->histogram;
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+
+ for (row = 0; row < num_rows; row++) {
+ ptr = input_buf[row];
+ for (col = width; col > 0; col--) {
+ /* get pixel value and index into the histogram */
+ histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
+ [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
+ [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
+ /* increment, check for overflow and undo increment if so. */
+ if (++(*histp) <= 0)
+ (*histp)--;
+ ptr += 3;
+ }
+ }
+}
+
+
+/*
+ * Next we have the really interesting routines: selection of a colormap
+ * given the completed histogram.
+ * These routines work with a list of "boxes", each representing a rectangular
+ * subset of the input color space (to histogram precision).
+ */
+
+typedef struct {
+ /* The bounds of the box (inclusive); expressed as histogram indexes */
+ int c0min, c0max;
+ int c1min, c1max;
+ int c2min, c2max;
+ /* The volume (actually 2-norm) of the box */
+ INT32 volume;
+ /* The number of nonzero histogram cells within this box */
+ long colorcount;
+} box;
+
+typedef box * boxptr;
+
+
+LOCAL(boxptr)
+find_biggest_color_pop (boxptr boxlist, int numboxes)
+/* Find the splittable box with the largest color population */
+/* Returns NULL if no splittable boxes remain */
+{
+ register boxptr boxp;
+ register int i;
+ register long maxc = 0;
+ boxptr which = NULL;
+
+ for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
+ if (boxp->colorcount > maxc && boxp->volume > 0) {
+ which = boxp;
+ maxc = boxp->colorcount;
+ }
+ }
+ return which;
+}
+
+
+LOCAL(boxptr)
+find_biggest_volume (boxptr boxlist, int numboxes)
+/* Find the splittable box with the largest (scaled) volume */
+/* Returns NULL if no splittable boxes remain */
+{
+ register boxptr boxp;
+ register int i;
+ register INT32 maxv = 0;
+ boxptr which = NULL;
+
+ for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
+ if (boxp->volume > maxv) {
+ which = boxp;
+ maxv = boxp->volume;
+ }
+ }
+ return which;
+}
+
+
+LOCAL(void)
+update_box (j_decompress_ptr cinfo, boxptr boxp)
+/* Shrink the min/max bounds of a box to enclose only nonzero elements, */
+/* and recompute its volume and population */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ hist3d histogram = cquantize->histogram;
+ histptr histp;
+ int c0,c1,c2;
+ int c0min,c0max,c1min,c1max,c2min,c2max;
+ INT32 dist0,dist1,dist2;
+ long ccount;
+
+ c0min = boxp->c0min; c0max = boxp->c0max;
+ c1min = boxp->c1min; c1max = boxp->c1max;
+ c2min = boxp->c2min; c2max = boxp->c2max;
+
+ if (c0max > c0min)
+ for (c0 = c0min; c0 <= c0max; c0++)
+ for (c1 = c1min; c1 <= c1max; c1++) {
+ histp = & histogram[c0][c1][c2min];
+ for (c2 = c2min; c2 <= c2max; c2++)
+ if (*histp++ != 0) {
+ boxp->c0min = c0min = c0;
+ goto have_c0min;
+ }
+ }
+ have_c0min:
+ if (c0max > c0min)
+ for (c0 = c0max; c0 >= c0min; c0--)
+ for (c1 = c1min; c1 <= c1max; c1++) {
+ histp = & histogram[c0][c1][c2min];
+ for (c2 = c2min; c2 <= c2max; c2++)
+ if (*histp++ != 0) {
+ boxp->c0max = c0max = c0;
+ goto have_c0max;
+ }
+ }
+ have_c0max:
+ if (c1max > c1min)
+ for (c1 = c1min; c1 <= c1max; c1++)
+ for (c0 = c0min; c0 <= c0max; c0++) {
+ histp = & histogram[c0][c1][c2min];
+ for (c2 = c2min; c2 <= c2max; c2++)
+ if (*histp++ != 0) {
+ boxp->c1min = c1min = c1;
+ goto have_c1min;
+ }
+ }
+ have_c1min:
+ if (c1max > c1min)
+ for (c1 = c1max; c1 >= c1min; c1--)
+ for (c0 = c0min; c0 <= c0max; c0++) {
+ histp = & histogram[c0][c1][c2min];
+ for (c2 = c2min; c2 <= c2max; c2++)
+ if (*histp++ != 0) {
+ boxp->c1max = c1max = c1;
+ goto have_c1max;
+ }
+ }
+ have_c1max:
+ if (c2max > c2min)
+ for (c2 = c2min; c2 <= c2max; c2++)
+ for (c0 = c0min; c0 <= c0max; c0++) {
+ histp = & histogram[c0][c1min][c2];
+ for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
+ if (*histp != 0) {
+ boxp->c2min = c2min = c2;
+ goto have_c2min;
+ }
+ }
+ have_c2min:
+ if (c2max > c2min)
+ for (c2 = c2max; c2 >= c2min; c2--)
+ for (c0 = c0min; c0 <= c0max; c0++) {
+ histp = & histogram[c0][c1min][c2];
+ for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
+ if (*histp != 0) {
+ boxp->c2max = c2max = c2;
+ goto have_c2max;
+ }
+ }
+ have_c2max:
+
+ /* Update box volume.
+ * We use 2-norm rather than real volume here; this biases the method
+ * against making long narrow boxes, and it has the side benefit that
+ * a box is splittable iff norm > 0.
+ * Since the differences are expressed in histogram-cell units,
+ * we have to shift back to JSAMPLE16 units to get consistent distances;
+ * after which, we scale according to the selected distance scale factors.
+ */
+ dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
+ dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
+ dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
+ boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
+
+ /* Now scan remaining volume of box and compute population */
+ ccount = 0;
+ for (c0 = c0min; c0 <= c0max; c0++)
+ for (c1 = c1min; c1 <= c1max; c1++) {
+ histp = & histogram[c0][c1][c2min];
+ for (c2 = c2min; c2 <= c2max; c2++, histp++)
+ if (*histp != 0) {
+ ccount++;
+ }
+ }
+ boxp->colorcount = ccount;
+}
+
+
+LOCAL(int)
+median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
+ int desired_colors)
+/* Repeatedly select and split the largest box until we have enough boxes */
+{
+ int n,lb;
+ int c0,c1,c2,cmax;
+ register boxptr b1,b2;
+
+ while (numboxes < desired_colors) {
+ /* Select box to split.
+ * Current algorithm: by population for first half, then by volume.
+ */
+ if (numboxes*2 <= desired_colors) {
+ b1 = find_biggest_color_pop(boxlist, numboxes);
+ } else {
+ b1 = find_biggest_volume(boxlist, numboxes);
+ }
+ if (b1 == NULL) /* no splittable boxes left! */
+ break;
+ b2 = &boxlist[numboxes]; /* where new box will go */
+ /* Copy the color bounds to the new box. */
+ b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
+ b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
+ /* Choose which axis to split the box on.
+ * Current algorithm: longest scaled axis.
+ * See notes in update_box about scaling distances.
+ */
+ c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
+ c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
+ c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
+ /* We want to break any ties in favor of green, then red, blue last.
+ * This code does the right thing for R,G,B or B,G,R color orders only.
+ */
+#if RGB_RED == 0
+ cmax = c1; n = 1;
+ if (c0 > cmax) { cmax = c0; n = 0; }
+ if (c2 > cmax) { n = 2; }
+#else
+ cmax = c1; n = 1;
+ if (c2 > cmax) { cmax = c2; n = 2; }
+ if (c0 > cmax) { n = 0; }
+#endif
+ /* Choose split point along selected axis, and update box bounds.
+ * Current algorithm: split at halfway point.
+ * (Since the box has been shrunk to minimum volume,
+ * any split will produce two nonempty subboxes.)
+ * Note that lb value is max for lower box, so must be < old max.
+ */
+ switch (n) {
+ case 0:
+ lb = (b1->c0max + b1->c0min) / 2;
+ b1->c0max = lb;
+ b2->c0min = lb+1;
+ break;
+ case 1:
+ lb = (b1->c1max + b1->c1min) / 2;
+ b1->c1max = lb;
+ b2->c1min = lb+1;
+ break;
+ case 2:
+ lb = (b1->c2max + b1->c2min) / 2;
+ b1->c2max = lb;
+ b2->c2min = lb+1;
+ break;
+ }
+ /* Update stats for boxes */
+ update_box(cinfo, b1);
+ update_box(cinfo, b2);
+ numboxes++;
+ }
+ return numboxes;
+}
+
+
+LOCAL(void)
+compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
+/* Compute representative color for a box, put it in colormap[icolor] */
+{
+ /* Current algorithm: mean weighted by pixels (not colors) */
+ /* Note it is important to get the rounding correct! */
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ hist3d histogram = cquantize->histogram;
+ histptr histp;
+ int c0,c1,c2;
+ int c0min,c0max,c1min,c1max,c2min,c2max;
+ long count;
+ long total = 0;
+ long c0total = 0;
+ long c1total = 0;
+ long c2total = 0;
+
+ c0min = boxp->c0min; c0max = boxp->c0max;
+ c1min = boxp->c1min; c1max = boxp->c1max;
+ c2min = boxp->c2min; c2max = boxp->c2max;
+
+ for (c0 = c0min; c0 <= c0max; c0++)
+ for (c1 = c1min; c1 <= c1max; c1++) {
+ histp = & histogram[c0][c1][c2min];
+ for (c2 = c2min; c2 <= c2max; c2++) {
+ if ((count = *histp++) != 0) {
+ total += count;
+ c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
+ c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
+ c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
+ }
+ }
+ }
+
+ cinfo->colormap16[0][icolor] = (JSAMPLE16) ((c0total + (total>>1)) / total);
+ cinfo->colormap16[1][icolor] = (JSAMPLE16) ((c1total + (total>>1)) / total);
+ cinfo->colormap16[2][icolor] = (JSAMPLE16) ((c2total + (total>>1)) / total);
+ /* Now for the 8 bits color map. */
+ cinfo->colormap[0][icolor] = (JSAMPLE) (((c0total + (total>>1)) / total) & 0xFF);
+ cinfo->colormap[1][icolor] = (JSAMPLE) (((c1total + (total>>1)) / total) & 0xFF);
+ cinfo->colormap[2][icolor] = (JSAMPLE) (((c2total + (total>>1)) / total) & 0xFF);
+}
+
+
+LOCAL(void)
+select_colors (j_decompress_ptr cinfo, int desired_colors)
+/* Master routine for color selection */
+{
+ boxptr boxlist;
+ int numboxes;
+ int i;
+
+ /* Allocate workspace for box list */
+ boxlist = (boxptr) (*cinfo->mem->alloc_small)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
+ /* Initialize one box containing whole space */
+ numboxes = 1;
+ boxlist[0].c0min = 0;
+ boxlist[0].c0max = cinfo->maxjsample >> C0_SHIFT;
+ boxlist[0].c1min = 0;
+ boxlist[0].c1max = cinfo->maxjsample >> C1_SHIFT;
+ boxlist[0].c2min = 0;
+ boxlist[0].c2max = cinfo->maxjsample >> C2_SHIFT;
+ /* Shrink it to actually-used volume and set its statistics */
+ update_box(cinfo, & boxlist[0]);
+ /* Perform median-cut to produce final box list */
+ numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
+ /* Compute the representative color for each box, fill colormap */
+ for (i = 0; i < numboxes; i++)
+ compute_color(cinfo, & boxlist[i], i);
+ cinfo->actual_number_of_colors = numboxes;
+ TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
+}
+
+
+/*
+ * These routines are concerned with the time-critical task of mapping input
+ * colors to the nearest color in the selected colormap.
+ *
+ * We re-use the histogram space as an "inverse color map", essentially a
+ * cache for the results of nearest-color searches. All colors within a
+ * histogram cell will be mapped to the same colormap entry, namely the one
+ * closest to the cell's center. This may not be quite the closest entry to
+ * the actual input color, but it's almost as good. A zero in the cache
+ * indicates we haven't found the nearest color for that cell yet; the array
+ * is cleared to zeroes before starting the mapping pass. When we find the
+ * nearest color for a cell, its colormap index plus one is recorded in the
+ * cache for future use. The pass2 scanning routines call fill_inverse_cmap
+ * when they need to use an unfilled entry in the cache.
+ *
+ * Our method of efficiently finding nearest colors is based on the "locally
+ * sorted search" idea described by Heckbert and on the incremental distance
+ * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
+ * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
+ * the distances from a given colormap entry to each cell of the histogram can
+ * be computed quickly using an incremental method: the differences between
+ * distances to adjacent cells themselves differ by a constant. This allows a
+ * fairly fast implementation of the "brute force" approach of computing the
+ * distance from every colormap entry to every histogram cell. Unfortunately,
+ * it needs a work array to hold the best-distance-so-far for each histogram
+ * cell (because the inner loop has to be over cells, not colormap entries).
+ * The work array elements have to be INT32s, so the work array would need
+ * 256Kb at our recommended precision. This is not feasible in DOS machines.
+ *
+ * To get around these problems, we apply Thomas' method to compute the
+ * nearest colors for only the cells within a small subbox of the histogram.
+ * The work array need be only as big as the subbox, so the memory usage
+ * problem is solved. Furthermore, we need not fill subboxes that are never
+ * referenced in pass2; many images use only part of the color gamut, so a
+ * fair amount of work is saved. An additional advantage of this
+ * approach is that we can apply Heckbert's locality criterion to quickly
+ * eliminate colormap entries that are far away from the subbox; typically
+ * three-fourths of the colormap entries are rejected by Heckbert's criterion,
+ * and we need not compute their distances to individual cells in the subbox.
+ * The speed of this approach is heavily influenced by the subbox size: too
+ * small means too much overhead, too big loses because Heckbert's criterion
+ * can't eliminate as many colormap entries. Empirically the best subbox
+ * size seems to be about 1/512th of the histogram (1/8th in each direction).
+ *
+ * Thomas' article also describes a refined method which is asymptotically
+ * faster than the brute-force method, but it is also far more complex and
+ * cannot efficiently be applied to small subboxes. It is therefore not
+ * useful for programs intended to be portable to DOS machines. On machines
+ * with plenty of memory, filling the whole histogram in one shot with Thomas'
+ * refined method might be faster than the present code --- but then again,
+ * it might not be any faster, and it's certainly more complicated.
+ */
+
+
+/* log2(histogram cells in update box) for each axis; this can be adjusted */
+#define BOX_C0_LOG (HIST_C0_BITS-3)
+#define BOX_C1_LOG (HIST_C1_BITS-3)
+#define BOX_C2_LOG (HIST_C2_BITS-3)
+
+#define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
+#define BOX_C1_ELEMS (1<<BOX_C1_LOG)
+#define BOX_C2_ELEMS (1<<BOX_C2_LOG)
+
+#define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
+#define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
+#define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
+
+
+/*
+ * The next three routines implement inverse colormap filling. They could
+ * all be folded into one big routine, but splitting them up this way saves
+ * some stack space (the mindist[] and bestdist[] arrays need not coexist)
+ * and may allow some compilers to produce better code by registerizing more
+ * inner-loop variables.
+ */
+
+LOCAL(int)
+find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
+ JSAMPLE16 colorlist[])
+/* Locate the colormap entries close enough to an update box to be candidates
+ * for the nearest entry to some cell(s) in the update box. The update box
+ * is specified by the center coordinates of its first cell. The number of
+ * candidate colormap entries is returned, and their colormap indexes are
+ * placed in colorlist[].
+ * This routine uses Heckbert's "locally sorted search" criterion to select
+ * the colors that need further consideration.
+ */
+{
+ int numcolors = cinfo->actual_number_of_colors;
+ int maxc0, maxc1, maxc2;
+ int centerc0, centerc1, centerc2;
+ int i, x, ncolors;
+ INT32 minmaxdist, min_dist, max_dist, tdist;
+ /* mvh,bcb 20100121 Allocate and free mindist */
+ INT32 * mindist = (INT32*)jpeg_get_large((j_common_ptr)cinfo,
+ MAXNUMCOLORS * sizeof(INT32)); /* min distance to colormap entry i */
+
+ /* Compute true coordinates of update box's upper corner and center.
+ * Actually we compute the coordinates of the center of the upper-corner
+ * histogram cell, which are the upper bounds of the volume we care about.
+ * Note that since ">>" rounds down, the "center" values may be closer to
+ * min than to max; hence comparisons to them must be "<=", not "<".
+ */
+ maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
+ centerc0 = (minc0 + maxc0) >> 1;
+ maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
+ centerc1 = (minc1 + maxc1) >> 1;
+ maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
+ centerc2 = (minc2 + maxc2) >> 1;
+
+ /* For each color in colormap, find:
+ * 1. its minimum squared-distance to any point in the update box
+ * (zero if color is within update box);
+ * 2. its maximum squared-distance to any point in the update box.
+ * Both of these can be found by considering only the corners of the box.
+ * We save the minimum distance for each color in mindist[];
+ * only the smallest maximum distance is of interest.
+ */
+ minmaxdist = 0x7FFFFFFFL;
+
+ for (i = 0; i < numcolors; i++) {
+ /* We compute the squared-c0-distance term, then add in the other two. */
+ x = GETJSAMPLE(cinfo->colormap16[0][i]);
+ if (x < minc0) {
+ tdist = (x - minc0) * C0_SCALE;
+ min_dist = tdist*tdist;
+ tdist = (x - maxc0) * C0_SCALE;
+ max_dist = tdist*tdist;
+ } else if (x > maxc0) {
+ tdist = (x - maxc0) * C0_SCALE;
+ min_dist = tdist*tdist;
+ tdist = (x - minc0) * C0_SCALE;
+ max_dist = tdist*tdist;
+ } else {
+ /* within cell range so no contribution to min_dist */
+ min_dist = 0;
+ if (x <= centerc0) {
+ tdist = (x - maxc0) * C0_SCALE;
+ max_dist = tdist*tdist;
+ } else {
+ tdist = (x - minc0) * C0_SCALE;
+ max_dist = tdist*tdist;
+ }
+ }
+
+ x = GETJSAMPLE(cinfo->colormap16[1][i]);
+ if (x < minc1) {
+ tdist = (x - minc1) * C1_SCALE;
+ min_dist += tdist*tdist;
+ tdist = (x - maxc1) * C1_SCALE;
+ max_dist += tdist*tdist;
+ } else if (x > maxc1) {
+ tdist = (x - maxc1) * C1_SCALE;
+ min_dist += tdist*tdist;
+ tdist = (x - minc1) * C1_SCALE;
+ max_dist += tdist*tdist;
+ } else {
+ /* within cell range so no contribution to min_dist */
+ if (x <= centerc1) {
+ tdist = (x - maxc1) * C1_SCALE;
+ max_dist += tdist*tdist;
+ } else {
+ tdist = (x - minc1) * C1_SCALE;
+ max_dist += tdist*tdist;
+ }
+ }
+
+ x = GETJSAMPLE(cinfo->colormap16[2][i]);
+ if (x < minc2) {
+ tdist = (x - minc2) * C2_SCALE;
+ min_dist += tdist*tdist;
+ tdist = (x - maxc2) * C2_SCALE;
+ max_dist += tdist*tdist;
+ } else if (x > maxc2) {
+ tdist = (x - maxc2) * C2_SCALE;
+ min_dist += tdist*tdist;
+ tdist = (x - minc2) * C2_SCALE;
+ max_dist += tdist*tdist;
+ } else {
+ /* within cell range so no contribution to min_dist */
+ if (x <= centerc2) {
+ tdist = (x - maxc2) * C2_SCALE;
+ max_dist += tdist*tdist;
+ } else {
+ tdist = (x - minc2) * C2_SCALE;
+ max_dist += tdist*tdist;
+ }
+ }
+
+ mindist[i] = min_dist; /* save away the results */
+ if (max_dist < minmaxdist)
+ minmaxdist = max_dist;
+ }
+
+ /* Now we know that no cell in the update box is more than minmaxdist
+ * away from some colormap entry. Therefore, only colors that are
+ * within minmaxdist of some part of the box need be considered.
+ */
+ ncolors = 0;
+ for (i = 0; i < numcolors; i++) {
+ if (mindist[i] <= minmaxdist)
+ colorlist[ncolors++] = (JSAMPLE16) i;
+ }
+ /* mvh,bcb 20100121 Allocate and free mindist */
+ jpeg_free_large((j_common_ptr)cinfo, mindist, MAXNUMCOLORS * sizeof(INT32));
+ return ncolors;
+}
+
+
+LOCAL(void)
+find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
+ int numcolors, JSAMPLE16 colorlist[], JSAMPLE16 bestcolor[])
+/* Find the closest colormap entry for each cell in the update box,
+ * given the list of candidate colors prepared by find_nearby_colors.
+ * Return the indexes of the closest entries in the bestcolor[] array.
+ * This routine uses Thomas' incremental distance calculation method to
+ * find the distance from a colormap entry to successive cells in the box.
+ */
+{
+ int ic0, ic1, ic2;
+ int i, icolor;
+ register INT32 * bptr; /* pointer into bestdist[] array */
+ JSAMPLE16 * cptr; /* pointer into bestcolor[] array */
+ INT32 dist0, dist1; /* initial distance values */
+ register INT32 dist2; /* current distance in inner loop */
+ INT32 xx0, xx1; /* distance increments */
+ register INT32 xx2;
+ INT32 inc0, inc1, inc2; /* initial values for increments */
+ /* This array holds the distance to the nearest-so-far color for each cell */
+ INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
+
+ /* Initialize best-distance for each cell of the update box */
+ bptr = bestdist;
+ for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
+ *bptr++ = 0x7FFFFFFFL;
+
+ /* For each color selected by find_nearby_colors,
+ * compute its distance to the center of each cell in the box.
+ * If that's less than best-so-far, update best distance and color number.
+ */
+
+ /* Nominal steps between cell centers ("x" in Thomas article) */
+#define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
+#define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
+#define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
+
+ for (i = 0; i < numcolors; i++) {
+ icolor = GETJSAMPLE(colorlist[i]);
+ /* Compute (square of) distance from minc0/c1/c2 to this color */
+ inc0 = (minc0 - GETJSAMPLE(cinfo->colormap16[0][icolor])) * C0_SCALE;
+ dist0 = inc0*inc0;
+ inc1 = (minc1 - GETJSAMPLE(cinfo->colormap16[1][icolor])) * C1_SCALE;
+ dist0 += inc1*inc1;
+ inc2 = (minc2 - GETJSAMPLE(cinfo->colormap16[2][icolor])) * C2_SCALE;
+ dist0 += inc2*inc2;
+ /* Form the initial difference increments */
+ inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
+ inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
+ inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
+ /* Now loop over all cells in box, updating distance per Thomas method */
+ bptr = bestdist;
+ cptr = bestcolor;
+ xx0 = inc0;
+ for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
+ dist1 = dist0;
+ xx1 = inc1;
+ for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
+ dist2 = dist1;
+ xx2 = inc2;
+ for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
+ if (dist2 < *bptr) {
+ *bptr = dist2;
+ *cptr = (JSAMPLE16) icolor;
+ }
+ dist2 += xx2;
+ xx2 += 2 * STEP_C2 * STEP_C2;
+ bptr++;
+ cptr++;
+ }
+ dist1 += xx1;
+ xx1 += 2 * STEP_C1 * STEP_C1;
+ }
+ dist0 += xx0;
+ xx0 += 2 * STEP_C0 * STEP_C0;
+ }
+ }
+}
+
+
+LOCAL(void)
+fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
+/* Fill the inverse-colormap entries in the update box that contains */
+/* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
+/* we can fill as many others as we wish.) */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ hist3d histogram = cquantize->histogram;
+ int minc0, minc1, minc2; /* lower left corner of update box */
+ int ic0, ic1, ic2;
+ register JSAMPLE16 * cptr; /* pointer into bestcolor[] array */
+ register histptr cachep; /* pointer into main cache array */
+ /* This array lists the candidate colormap indexes. */
+ /* mvh,bcb 20100121 Allocate and free colorlist */
+ JSAMPLE16 *colorlist = (JSAMPLE16 *)jpeg_get_large((j_common_ptr)cinfo,
+ MAXNUMCOLORS * sizeof(INT32)); /* min distance to colormap entry i */
+ int numcolors; /* number of candidate colors */
+ /* This array holds the actually closest colormap index for each cell. */
+ JSAMPLE16 bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
+
+ /* Convert cell coordinates to update box ID */
+ c0 >>= BOX_C0_LOG;
+ c1 >>= BOX_C1_LOG;
+ c2 >>= BOX_C2_LOG;
+
+ /* Compute true coordinates of update box's origin corner.
+ * Actually we compute the coordinates of the center of the corner
+ * histogram cell, which are the lower bounds of the volume we care about.
+ */
+ minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
+ minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
+ minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
+
+ /* Determine which colormap entries are close enough to be candidates
+ * for the nearest entry to some cell in the update box.
+ */
+ numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
+
+ /* Determine the actually nearest colors. */
+ find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
+ bestcolor);
+
+ /* Save the best color numbers (plus 1) in the main cache array */
+ c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
+ c1 <<= BOX_C1_LOG;
+ c2 <<= BOX_C2_LOG;
+ cptr = bestcolor;
+ for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
+ for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
+ cachep = & histogram[c0+ic0][c1+ic1][c2];
+ for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
+ *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
+ }
+ }
+ }
+ /* mvh,bcb 20100121 Allocate and free colorlist */
+ jpeg_free_large((j_common_ptr)cinfo, colorlist, MAXNUMCOLORS * sizeof(INT32));
+}
+
+
+/*
+ * Map some rows of pixels to the output colormapped representation.
+ */
+
+METHODDEF(void)
+pass2_no_dither (j_decompress_ptr cinfo,
+ JSAMPARRAY16 input_buf, JSAMPARRAY16 output_buf, int num_rows)
+/* This version performs no dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ hist3d histogram = cquantize->histogram;
+ register JSAMPROW16 inptr, outptr;
+ register histptr cachep;
+ register int c0, c1, c2;
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+
+ for (row = 0; row < num_rows; row++) {
+ inptr = input_buf[row];
+ outptr = output_buf[row];
+ for (col = width; col > 0; col--) {
+ /* get pixel value and index into the cache */
+ c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
+ c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
+ c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
+ cachep = & histogram[c0][c1][c2];
+ /* If we have not seen this color before, find nearest colormap entry */
+ /* and update the cache */
+ if (*cachep == 0)
+ fill_inverse_cmap(cinfo, c0,c1,c2);
+ /* Now emit the colormap index for this cell */
+ *outptr++ = (JSAMPLE16) (*cachep - 1);
+ }
+ }
+}
+
+
+METHODDEF(void)
+pass2_fs_dither (j_decompress_ptr cinfo,
+ JSAMPARRAY16 input_buf, JSAMPARRAY16 output_buf, int num_rows)
+/* This version performs Floyd-Steinberg dithering */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ hist3d histogram = cquantize->histogram;
+ register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
+ LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
+ LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
+ register FSERRPTR errorptr; /* => fserrors[] at column before current */
+ JSAMPROW16 inptr; /* => current input pixel */
+ JSAMPROW16 outptr; /* => current output pixel */
+ histptr cachep;
+ int dir; /* +1 or -1 depending on direction */
+ int dir3; /* 3*dir, for advancing inptr & errorptr */
+ int row;
+ JDIMENSION col;
+ JDIMENSION width = cinfo->output_width;
+ JSAMPLE16 *range_limit = cinfo->sample_range_limit;
+ int *error_limit = cquantize->error_limiter;
+ JSAMPROW16 colormap0 = cinfo->colormap16[0];
+ JSAMPROW16 colormap1 = cinfo->colormap16[1];
+ JSAMPROW16 colormap2 = cinfo->colormap16[2];
+ SHIFT_TEMPS
+
+ for (row = 0; row < num_rows; row++) {
+ inptr = input_buf[row];
+ outptr = output_buf[row];
+ if (cquantize->on_odd_row) {
+ /* work right to left in this row */
+ inptr += (width-1) * 3; /* so point to rightmost pixel */
+ outptr += width-1;
+ dir = -1;
+ dir3 = -3;
+ errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
+ cquantize->on_odd_row = FALSE; /* flip for next time */
+ } else {
+ /* work left to right in this row */
+ dir = 1;
+ dir3 = 3;
+ errorptr = cquantize->fserrors; /* => entry before first real column */
+ cquantize->on_odd_row = TRUE; /* flip for next time */
+ }
+ /* Preset error values: no error propagated to first pixel from left */
+ cur0 = cur1 = cur2 = 0;
+ /* and no error propagated to row below yet */
+ belowerr0 = belowerr1 = belowerr2 = 0;
+ bpreverr0 = bpreverr1 = bpreverr2 = 0;
+
+ for (col = width; col > 0; col--) {
+ /* curN holds the error propagated from the previous pixel on the
+ * current line. Add the error propagated from the previous line
+ * to form the complete error correction term for this pixel, and
+ * round the error term (which is expressed * 16) to an integer.
+ * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
+ * for either sign of the error value.
+ * Note: errorptr points to *previous* column's array entry.
+ */
+ cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
+ cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
+ cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
+ /* Limit the error using transfer function set by init_error_limit.
+ * See comments with init_error_limit for rationale.
+ */
+ cur0 = error_limit[cur0];
+ cur1 = error_limit[cur1];
+ cur2 = error_limit[cur2];
+ /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
+ * The maximum error is +- MAXJSAMPLE (or less with error limiting);
+ * this sets the required size of the range_limit array.
+ */
+ cur0 += GETJSAMPLE(inptr[0]);
+ cur1 += GETJSAMPLE(inptr[1]);
+ cur2 += GETJSAMPLE(inptr[2]);
+ cur0 = GETJSAMPLE(range_limit[cur0]);
+ cur1 = GETJSAMPLE(range_limit[cur1]);
+ cur2 = GETJSAMPLE(range_limit[cur2]);
+ /* Index into the cache with adjusted pixel value */
+ cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
+ /* If we have not seen this color before, find nearest colormap */
+ /* entry and update the cache */
+ if (*cachep == 0)
+ fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
+ /* Now emit the colormap index for this cell */
+ { register int pixcode = *cachep - 1;
+ *outptr = (JSAMPLE16) pixcode;
+ /* Compute representation error for this pixel */
+ cur0 -= GETJSAMPLE(colormap0[pixcode]);
+ cur1 -= GETJSAMPLE(colormap1[pixcode]);
+ cur2 -= GETJSAMPLE(colormap2[pixcode]);
+ }
+ /* Compute error fractions to be propagated to adjacent pixels.
+ * Add these into the running sums, and simultaneously shift the
+ * next-line error sums left by 1 column.
+ */
+ { register LOCFSERROR bnexterr, delta;
+
+ bnexterr = cur0; /* Process component 0 */
+ delta = cur0 * 2;
+ cur0 += delta; /* form error * 3 */
+ errorptr[0] = (FSERROR) (bpreverr0 + cur0);
+ cur0 += delta; /* form error * 5 */
+ bpreverr0 = belowerr0 + cur0;
+ belowerr0 = bnexterr;
+ cur0 += delta; /* form error * 7 */
+ bnexterr = cur1; /* Process component 1 */
+ delta = cur1 * 2;
+ cur1 += delta; /* form error * 3 */
+ errorptr[1] = (FSERROR) (bpreverr1 + cur1);
+ cur1 += delta; /* form error * 5 */
+ bpreverr1 = belowerr1 + cur1;
+ belowerr1 = bnexterr;
+ cur1 += delta; /* form error * 7 */
+ bnexterr = cur2; /* Process component 2 */
+ delta = cur2 * 2;
+ cur2 += delta; /* form error * 3 */
+ errorptr[2] = (FSERROR) (bpreverr2 + cur2);
+ cur2 += delta; /* form error * 5 */
+ bpreverr2 = belowerr2 + cur2;
+ belowerr2 = bnexterr;
+ cur2 += delta; /* form error * 7 */
+ }
+ /* At this point curN contains the 7/16 error value to be propagated
+ * to the next pixel on the current line, and all the errors for the
+ * next line have been shifted over. We are therefore ready to move on.
+ */
+ inptr += dir3; /* Advance pixel pointers to next column */
+ outptr += dir;
+ errorptr += dir3; /* advance errorptr to current column */
+ }
+ /* Post-loop cleanup: we must unload the final error values into the
+ * final fserrors[] entry. Note we need not unload belowerrN because
+ * it is for the dummy column before or after the actual array.
+ */
+ errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
+ errorptr[1] = (FSERROR) bpreverr1;
+ errorptr[2] = (FSERROR) bpreverr2;
+ }
+}
+
+
+/*
+ * Initialize the error-limiting transfer function (lookup table).
+ * The raw F-S error computation can potentially compute error values of up to
+ * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
+ * much less, otherwise obviously wrong pixels will be created. (Typical
+ * effects include weird fringes at color-area boundaries, isolated bright
+ * pixels in a dark area, etc.) The standard advice for avoiding this problem
+ * is to ensure that the "corners" of the color cube are allocated as output
+ * colors; then repeated errors in the same direction cannot cause cascading
+ * error buildup. However, that only prevents the error from getting
+ * completely out of hand; Aaron Giles reports that error limiting improves
+ * the results even with corner colors allocated.
+ * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
+ * well, but the smoother transfer function used below is even better. Thanks
+ * to Aaron Giles for this idea.
+ */
+
+LOCAL(void)
+init_error_limit (j_decompress_ptr cinfo)
+/* Allocate and fill in the error_limiter table */
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ int * table;
+ int in, out;
+
+ table = (int *) (*cinfo->mem->alloc_small)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, (cinfo->maxjsample*2+1) * SIZEOF(int));
+ table += cinfo->maxjsample; /* so can index -cinfo->maxjsample .. +cinfo->maxjsample */
+ cquantize->error_limiter = table;
+
+#define STEPSIZE ((cinfo->maxjsample+1)/16)
+ /* Map errors 1:1 up to +- cinfo->maxjsample/16 */
+ out = 0;
+ for (in = 0; in < STEPSIZE; in++, out++) {
+ table[in] = out; table[-in] = -out;
+ }
+ /* Map errors 1:2 up to +- 3*cinfo->maxjsample/16 */
+ for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
+ table[in] = out; table[-in] = -out;
+ }
+ /* Clamp the rest to final out value (which is (cinfo->maxjsample+1)/8) */
+ for (; in <= cinfo->maxjsample; in++) {
+ table[in] = out; table[-in] = -out;
+ }
+#undef STEPSIZE
+}
+
+
+/*
+ * Finish up at the end of each pass.
+ */
+
+METHODDEF(void)
+finish_pass1 (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+
+ /* Select the representative colors and fill in cinfo->colormap */
+ cinfo->colormap16 = cquantize->sv_colormap;
+ cinfo->colormap = cquantize->sv_colormap8;
+ select_colors(cinfo, cquantize->desired);
+ /* Force next pass to zero the color index table */
+ cquantize->needs_zeroed = TRUE;
+}
+
+
+METHODDEF(void)
+finish_pass2 (j_decompress_ptr cinfo)
+{
+ /* no work */
+}
+
+
+/*
+ * Initialize for each processing pass.
+ */
+
+METHODDEF(void)
+start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+ hist3d histogram = cquantize->histogram;
+ int i;
+
+ /* Only F-S dithering or no dithering is supported. */
+ /* If user asks for ordered dither, give him F-S. */
+ if (cinfo->dither_mode != JDITHER_NONE)
+ cinfo->dither_mode = JDITHER_FS;
+
+ if (is_pre_scan) {
+ /* Set up method pointers */
+ cquantize->pub.color_quantize = prescan_quantize;
+ cquantize->pub.finish_pass = finish_pass1;
+ cquantize->needs_zeroed = TRUE; /* Always zero histogram */
+ } else {
+ /* Set up method pointers */
+ if (cinfo->dither_mode == JDITHER_FS)
+ cquantize->pub.color_quantize = pass2_fs_dither;
+ else
+ cquantize->pub.color_quantize = pass2_no_dither;
+ cquantize->pub.finish_pass = finish_pass2;
+
+ /* Make sure color count is acceptable */
+ i = cinfo->actual_number_of_colors;
+ if (i < 1)
+ ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
+ if (i > MAXNUMCOLORS)
+ ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
+
+ if (cinfo->dither_mode == JDITHER_FS) {
+ size_t arraysize = (size_t) ((cinfo->output_width + 2) *
+ (3 * SIZEOF(FSERROR)));
+ /* Allocate Floyd-Steinberg workspace if we didn't already. */
+ if (cquantize->fserrors == NULL)
+ cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
+ /* Initialize the propagated errors to zero. */
+ jzero_far((void FAR *) cquantize->fserrors, arraysize);
+ /* Make the error-limit table if we didn't already. */
+ if (cquantize->error_limiter == NULL)
+ init_error_limit(cinfo);
+ cquantize->on_odd_row = FALSE;
+ }
+
+ }
+ /* Zero the histogram or inverse color map, if necessary */
+ if (cquantize->needs_zeroed) {
+ for (i = 0; i < HIST_C0_ELEMS; i++) {
+ jzero_far((void FAR *) histogram[i],
+ HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
+ }
+ cquantize->needs_zeroed = FALSE;
+ }
+}
+
+
+/*
+ * Switch to a new external colormap between output passes.
+ */
+
+METHODDEF(void)
+new_color_map_2_quant (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
+
+ /* Reset the inverse color map */
+ cquantize->needs_zeroed = TRUE;
+}
+
+
+/*
+ * Module initialization routine for 2-pass color quantization.
+ */
+
+GLOBAL(void)
+jinit_2pass_quantizer (j_decompress_ptr cinfo)
+{
+ my_cquantize_ptr cquantize;
+ int i;
+
+ cquantize = (my_cquantize_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(my_cquantizer));
+ cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
+ cquantize->pub.start_pass = start_pass_2_quant;
+ cquantize->pub.new_color_map = new_color_map_2_quant;
+ cquantize->fserrors = NULL; /* flag optional arrays not allocated */
+ cquantize->error_limiter = NULL;
+
+ /* Make sure jdmaster didn't give me a case I can't handle */
+ if (cinfo->out_color_components != 3)
+ ERREXIT(cinfo, JERR_NOTIMPL);
+
+ /* Allocate the histogram/inverse colormap storage */
+ cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
+ for (i = 0; i < HIST_C0_ELEMS; i++) {
+ cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
+ }
+ cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
+
+ /* Allocate storage for the completed colormap, if required.
+ * We do this now since it is FAR storage and may affect
+ * the memory manager's space calculations.
+ */
+ if (cinfo->enable_2pass_quant) {
+ /* Make sure color count is acceptable */
+ int desired = cinfo->desired_number_of_colors;
+ /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
+ if (desired < 8)
+ ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
+ /* Make sure colormap indexes can be represented by JSAMPLEs */
+ if (desired > MAXNUMCOLORS)
+ ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
+ cquantize->sv_colormap = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired
+ * SIZEOF(JSAMPLE16), (JDIMENSION) 3);
+ cquantize->sv_colormap8 = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired
+ * SIZEOF(JSAMPLE), (JDIMENSION) 3);
+ cquantize->desired = desired;
+ } else
+ cquantize->sv_colormap = NULL;
+
+ /* Only F-S dithering or no dithering is supported. */
+ /* If user asks for ordered dither, give him F-S. */
+ if (cinfo->dither_mode != JDITHER_NONE)
+ cinfo->dither_mode = JDITHER_FS;
+
+ /* Allocate Floyd-Steinberg workspace if necessary.
+ * This isn't really needed until pass 2, but again it is FAR storage.
+ * Although we will cope with a later change in dither_mode,
+ * we do not promise to honor max_memory_to_use if dither_mode changes.
+ */
+ if (cinfo->dither_mode == JDITHER_FS) {
+ cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
+ /* Might as well create the error-limiting table too. */
+ init_error_limit(cinfo);
+ }
+}
+
+#endif /* QUANT_2PASS_SUPPORTED */
diff --git a/jpeg-6c/jutils.c b/jpeg-6c/jutils.c
new file mode 100644
index 0000000..eb85442
--- /dev/null
+++ b/jpeg-6c/jutils.c
@@ -0,0 +1,180 @@
+/*
+ * jutils.c
+ *
+ * Copyright (C) 1991-1996, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains tables and miscellaneous utility routines needed
+ * for both compression and decompression.
+ * Note we prefix all global names with "j" to minimize conflicts with
+ * a surrounding application.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
+ * of a DCT block read in natural order (left to right, top to bottom).
+ */
+
+#if 0 /* This table is not actually needed in v6a */
+
+const int jpeg_zigzag_order[DCTSIZE2] = {
+ 0, 1, 5, 6, 14, 15, 27, 28,
+ 2, 4, 7, 13, 16, 26, 29, 42,
+ 3, 8, 12, 17, 25, 30, 41, 43,
+ 9, 11, 18, 24, 31, 40, 44, 53,
+ 10, 19, 23, 32, 39, 45, 52, 54,
+ 20, 22, 33, 38, 46, 51, 55, 60,
+ 21, 34, 37, 47, 50, 56, 59, 61,
+ 35, 36, 48, 49, 57, 58, 62, 63
+};
+
+#endif
+
+/*
+ * jpeg_natural_order[i] is the natural-order position of the i'th element
+ * of zigzag order.
+ *
+ * When reading corrupted data, the Huffman decoders could attempt
+ * to reference an entry beyond the end of this array (if the decoded
+ * zero run length reaches past the end of the block). To prevent
+ * wild stores without adding an inner-loop test, we put some extra
+ * "63"s after the real entries. This will cause the extra coefficient
+ * to be stored in location 63 of the block, not somewhere random.
+ * The worst case would be a run-length of 15, which means we need 16
+ * fake entries.
+ */
+
+const int jpeg_natural_order[DCTSIZE2+16] = {
+ 0, 1, 8, 16, 9, 2, 3, 10,
+ 17, 24, 32, 25, 18, 11, 4, 5,
+ 12, 19, 26, 33, 40, 48, 41, 34,
+ 27, 20, 13, 6, 7, 14, 21, 28,
+ 35, 42, 49, 56, 57, 50, 43, 36,
+ 29, 22, 15, 23, 30, 37, 44, 51,
+ 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63,
+ 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
+ 63, 63, 63, 63, 63, 63, 63, 63
+};
+
+
+/*
+ * Arithmetic utilities
+ */
+
+GLOBAL(long)
+jdiv_round_up (long a, long b)
+/* Compute a/b rounded up to next integer, ie, ceil(a/b) */
+/* Assumes a >= 0, b > 0 */
+{
+ return (a + b - 1L) / b;
+}
+
+
+GLOBAL(long)
+jround_up (long a, long b)
+/* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
+/* Assumes a >= 0, b > 0 */
+{
+ a += b - 1L;
+ return a - (a % b);
+}
+
+
+/* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
+ * and coefficient-block arrays. This won't work on 80x86 because the arrays
+ * are FAR and we're assuming a small-pointer memory model. However, some
+ * DOS compilers provide far-pointer versions of memcpy() and memset() even
+ * in the small-model libraries. These will be used if USE_FMEM is defined.
+ * Otherwise, the routines below do it the hard way. (The performance cost
+ * is not all that great, because these routines aren't very heavily used.)
+ */
+
+#ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
+#define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
+#define FMEMZERO(target,size) MEMZERO(target,size)
+#else /* 80x86 case, define if we can */
+#ifdef USE_FMEM
+#define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
+#define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
+#endif
+#endif
+
+
+GLOBAL(void)
+jcopy_sample_rows (JSAMPARRAY16 input_array, int source_row,
+ JSAMPARRAY16 output_array, int dest_row,
+ int num_rows, JDIMENSION num_cols)
+/* Copy some rows of samples from one place to another.
+ * num_rows rows are copied from input_array[source_row++]
+ * to output_array[dest_row++]; these areas may overlap for duplication.
+ * The source and destination arrays must be at least as wide as num_cols.
+ */
+{
+ register JSAMPROW16 inptr, outptr;
+#ifdef FMEMCOPY
+ register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE16));
+#else
+ register JDIMENSION count;
+#endif
+ register int row;
+
+ input_array += source_row;
+ output_array += dest_row;
+
+ for (row = num_rows; row > 0; row--) {
+ inptr = *input_array++;
+ outptr = *output_array++;
+#ifdef FMEMCOPY
+ FMEMCOPY(outptr, inptr, count);
+#else
+ for (count = num_cols; count > 0; count--)
+ *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
+#endif
+ }
+}
+
+
+GLOBAL(void)
+jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
+ JDIMENSION num_blocks)
+/* Copy a row of coefficient blocks from one place to another. */
+{
+#ifdef FMEMCOPY
+ FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
+#else
+ register JCOEFPTR inptr, outptr;
+ register long count;
+
+ inptr = (JCOEFPTR) input_row;
+ outptr = (JCOEFPTR) output_row;
+ for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
+ *outptr++ = *inptr++;
+ }
+#endif
+}
+
+
+GLOBAL(void)
+jzero_far (void FAR * target, size_t bytestozero)
+/* Zero out a chunk of FAR memory. */
+/* This might be sample-array data, block-array data, or alloc_large data. */
+{
+#ifdef FMEMZERO
+ FMEMZERO(target, bytestozero);
+#else
+ register char FAR * ptr = (char FAR *) target;
+ register size_t count;
+
+ for (count = bytestozero; count > 0; count--) {
+ *ptr++ = 0;
+ }
+#endif
+}
diff --git a/jpeg-6c/jversion.h b/jpeg-6c/jversion.h
new file mode 100644
index 0000000..bf28e87
--- /dev/null
+++ b/jpeg-6c/jversion.h
@@ -0,0 +1,15 @@
+/*
+ * jversion.h
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains software version identification.
+ */
+
+
+#define JVERSION "6c 29-Jun-2009"
+
+#define JCOPYRIGHT "Copyright (C) 1998, Thomas G. Lane"
diff --git a/jpeg-6c/libjpeg.doc b/jpeg-6c/libjpeg.doc
new file mode 100644
index 0000000..e740eba
Binary files /dev/null and b/jpeg-6c/libjpeg.doc differ
diff --git a/jpeg-6c/ljpeg-6b.patch b/jpeg-6c/ljpeg-6b.patch
new file mode 100644
index 0000000..068a778
--- /dev/null
+++ b/jpeg-6c/ljpeg-6b.patch
@@ -0,0 +1,12790 @@
+diff -cN ../jpeg-6b/README ./README
+*** ../jpeg-6b/README Fri Mar 27 18:34:59 1998
+--- ./README Tue Apr 27 14:58:14 1999
+***************
+*** 74,85 ****
+ low-quality image. For more details, see the references, or just experiment
+ with various compression settings.
+
+! This software implements JPEG baseline, extended-sequential, and progressive
+! compression processes. Provision is made for supporting all variants of these
+! processes, although some uncommon parameter settings aren't implemented yet.
+! For legal reasons, we are not distributing code for the arithmetic-coding
+! variants of JPEG; see LEGAL ISSUES. We have made no provision for supporting
+! the hierarchical or lossless processes defined in the standard.
+
+ We provide a set of library routines for reading and writing JPEG image files,
+ plus two sample applications "cjpeg" and "djpeg", which use the library to
+--- 74,85 ----
+ low-quality image. For more details, see the references, or just experiment
+ with various compression settings.
+
+! This software implements JPEG baseline, extended-sequential, progressive
+! and lossless compression processes. Provision is made for supporting all
+! variants of these processes, although some uncommon parameter settings aren't
+! implemented yet. For legal reasons, we are not distributing code for the
+! arithmetic-coding variants of JPEG; see LEGAL ISSUES. We have made no
+! provision for supporting the hierarchical processes defined in the standard.
+
+ We provide a set of library routines for reading and writing JPEG image files,
+ plus two sample applications "cjpeg" and "djpeg", which use the library to
+diff -cN ../jpeg-6b/TODO ./TODO
+*** ../jpeg-6b/TODO
+--- ./TODO Tue Apr 27 14:58:15 1999
+***************
+*** 0 ****
+--- 1,13 ----
++ List of things to complete for lossless codec:
++
++ * How to deal with data_precision vs. BITS_PER_JSAMPLE for compression codec.
++
++ * Re-visit use of insufficient_data - see jdhuff.c and jdlhuff.c.
++
++ * How to check BITS_PER_JSAMPLE for lossy mode (ie, 16-bit data)? -
++ see jdinput.c.
++
++ * Check comment blocks for errors/changes.
++
++ * Review new filenames. Try to avoid filename conflicts with possible JPEG-LS
++ codec.
+diff -cN ../jpeg-6b/cjpeg.1 ./cjpeg.1
+*** ../jpeg-6b/cjpeg.1 Fri Mar 20 20:29:01 1998
+--- ./cjpeg.1 Tue Apr 27 14:58:15 1999
+***************
+*** 62,67 ****
+--- 62,74 ----
+ .B \-progressive
+ Create progressive JPEG file (see below).
+ .TP
++ .BI \-lossless " psv[,Pt]"
++ Create a lossless JPEG file using the specified predictor selection value (1-7)
++ and optional point transform.
++ .B Caution:
++ lossless JPEG is not widely implemented, so many decoders will be
++ unable to view a lossless JPEG file at all.
++ .TP
+ .B \-targa
+ Input file is Targa format. Targa files that contain an "identification"
+ field will not be automatically recognized by
+diff -cN ../jpeg-6b/cjpeg.c ./cjpeg.c
+*** ../jpeg-6b/cjpeg.c Fri Mar 20 20:21:49 1998
+--- ./cjpeg.c Tue Apr 27 14:58:15 1999
+***************
+*** 157,162 ****
+--- 157,165 ----
+ #ifdef C_PROGRESSIVE_SUPPORTED
+ fprintf(stderr, " -progressive Create progressive JPEG file\n");
+ #endif
++ #ifdef C_LOSSLESS_SUPPORTED
++ fprintf(stderr, " -lossless psv[,Pt] Create lossless JPEG file\n");
++ #endif
+ #ifdef TARGA_SUPPORTED
+ fprintf(stderr, " -targa Input file is Targa format (usually not needed)\n");
+ #endif
+***************
+*** 217,222 ****
+--- 220,226 ----
+ char * qslotsarg = NULL; /* saves -qslots parm if any */
+ char * samplearg = NULL; /* saves -sample parm if any */
+ char * scansarg = NULL; /* saves -scans parm if any */
++ char * losslsarg = NULL; /* saves -lossless parm if any */
+
+ /* Set up default JPEG parameters. */
+ /* Note that default -quality level need not, and does not,
+***************
+*** 287,292 ****
+--- 291,309 ----
+ /* Force a monochrome JPEG file to be generated. */
+ jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
+
++ } else if (keymatch(arg, "lossless", 1)) {
++ /* Select simple lossless mode. */
++ #ifdef C_LOSSLESS_SUPPORTED
++ if (++argn >= argc) /* advance to next argument */
++ usage();
++ losslsarg = argv[argn];
++ /* We must postpone execution until num_components is known. */
++ #else
++ fprintf(stderr, "%s: sorry, lossless output was not compiled\n",
++ progname);
++ exit(EXIT_FAILURE);
++ #endif
++
+ } else if (keymatch(arg, "maxmemory", 3)) {
+ /* Maximum memory in Kb (or Mb with 'm'). */
+ long lval;
+***************
+*** 440,445 ****
+--- 457,468 ----
+ #ifdef C_PROGRESSIVE_SUPPORTED
+ if (simple_progressive) /* process -progressive; -scans can override */
+ jpeg_simple_progression(cinfo);
++ #endif
++
++ #ifdef C_LOSSLESS_SUPPORTED
++ if (losslsarg != NULL) /* process -lossless if it was present */
++ if (! set_simple_lossless(cinfo, losslsarg))
++ usage();
+ #endif
+
+ #ifdef C_MULTISCAN_FILES_SUPPORTED
+diff -cN ../jpeg-6b/filelist.doc ./filelist.doc
+*** ../jpeg-6b/filelist.doc Sun Mar 15 13:57:38 1998
+--- ./filelist.doc Tue Apr 27 14:58:15 1999
+***************
+*** 1,6 ****
+ IJG JPEG LIBRARY: FILE LIST
+
+! Copyright (C) 1994-1998, Thomas G. Lane.
+ This file is part of the Independent JPEG Group's software.
+ For conditions of distribution and use, see the accompanying README file.
+
+--- 1,6 ----
+ IJG JPEG LIBRARY: FILE LIST
+
+! Copyright (C) 1994-1997, Thomas G. Lane.
+ This file is part of the Independent JPEG Group's software.
+ For conditions of distribution and use, see the accompanying README file.
+
+***************
+*** 28,33 ****
+--- 28,35 ----
+ jinclude.h Central include file used by all IJG .c files to reference
+ system include files.
+ jpegint.h JPEG library's internal data structures.
++ jlossls.h JPEG library's lossless codec data structures.
++ jlossy.h JPEG library's lossy codec structures.
+ jchuff.h Private declarations for Huffman encoder modules.
+ jdhuff.h Private declarations for Huffman decoder modules.
+ jdct.h Private declarations for forward & reverse DCT subsystems.
+***************
+*** 64,97 ****
+ jcinit.c Initialization: determines which other modules to use.
+ jcmaster.c Master control: setup and inter-pass sequencing logic.
+ jcmainct.c Main buffer controller (preprocessor => JPEG compressor).
+ jcprepct.c Preprocessor buffer controller.
+- jccoefct.c Buffer controller for DCT coefficient buffer.
+ jccolor.c Color space conversion.
+ jcsample.c Downsampling.
+ jcdctmgr.c DCT manager (DCT implementation selection & control).
+ jfdctint.c Forward DCT using slow-but-accurate integer method.
+ jfdctfst.c Forward DCT using faster, less accurate integer method.
+ jfdctflt.c Forward DCT using floating-point arithmetic.
+! jchuff.c Huffman entropy coding for sequential JPEG.
+ jcphuff.c Huffman entropy coding for progressive JPEG.
+! jcmarker.c JPEG marker writing.
+! jdatadst.c Data destination manager for stdio output.
+
+ Decompression side of the library:
+
+ jdmaster.c Master control: determines which other modules to use.
+ jdinput.c Input controller: controls input processing modules.
+ jdmainct.c Main buffer controller (JPEG decompressor => postprocessor).
+! jdcoefct.c Buffer controller for DCT coefficient buffer.
+ jdpostct.c Postprocessor buffer controller.
+ jdmarker.c JPEG marker reading.
+- jdhuff.c Huffman entropy decoding for sequential JPEG.
+- jdphuff.c Huffman entropy decoding for progressive JPEG.
+- jddctmgr.c IDCT manager (IDCT implementation selection & control).
+- jidctint.c Inverse DCT using slow-but-accurate integer method.
+- jidctfst.c Inverse DCT using faster, less accurate integer method.
+- jidctflt.c Inverse DCT using floating-point arithmetic.
+- jidctred.c Inverse DCTs with reduced-size outputs.
+ jdsample.c Upsampling.
+ jdcolor.c Color space conversion.
+ jdmerge.c Merged upsampling/color conversion (faster, lower quality).
+--- 66,105 ----
+ jcinit.c Initialization: determines which other modules to use.
+ jcmaster.c Master control: setup and inter-pass sequencing logic.
+ jcmainct.c Main buffer controller (preprocessor => JPEG compressor).
++ jchuff.c Codec-independent Huffman entropy encoding routines.
+ jcprepct.c Preprocessor buffer controller.
+ jccolor.c Color space conversion.
+ jcsample.c Downsampling.
++ jcmarker.c JPEG marker writing.
++ jdatadst.c Data destination manager for stdio output.
++
++ Lossy (DCT) codec:
++
++ jlossy.c Lossy compressor proper.
++ jccoefct.c Buffer controller for DCT coefficient buffer.
+ jcdctmgr.c DCT manager (DCT implementation selection & control).
+ jfdctint.c Forward DCT using slow-but-accurate integer method.
+ jfdctfst.c Forward DCT using faster, less accurate integer method.
+ jfdctflt.c Forward DCT using floating-point arithmetic.
+! jcshuff.c Huffman entropy coding for sequential JPEG.
+ jcphuff.c Huffman entropy coding for progressive JPEG.
+!
+! Lossless (spatial) codec:
+
++ jclossls.c Lossless compressor proper.
++ jcdiffct.c Buffer controller for difference buffer.
++ jcscale.c Point transformation.
++ jcpred.c Sample predictor and differencer.
++ jclhuff.c Huffman entropy encoding for lossless JPEG.
++
+ Decompression side of the library:
+
+ jdmaster.c Master control: determines which other modules to use.
+ jdinput.c Input controller: controls input processing modules.
+ jdmainct.c Main buffer controller (JPEG decompressor => postprocessor).
+! jdhuff.c Codec-independent Huffman entropy decoding routines.
+ jdpostct.c Postprocessor buffer controller.
+ jdmarker.c JPEG marker reading.
+ jdsample.c Upsampling.
+ jdcolor.c Color space conversion.
+ jdmerge.c Merged upsampling/color conversion (faster, lower quality).
+***************
+*** 100,109 ****
+--- 108,138 ----
+ Also handles one-pass quantization to an externally given map.
+ jdatasrc.c Data source manager for stdio input.
+
++ Lossy (DCT) codec:
++
++ jdlossy.c Lossy decompressor proper.
++ jdcoefct.c Buffer controller for DCT coefficient buffer.
++ jdshuff.c Huffman entropy decoding for sequential JPEG.
++ jdphuff.c Huffman entropy decoding for progressive JPEG.
++ jddctmgr.c IDCT manager (IDCT implementation selection & control).
++ jidctint.c Inverse DCT using slow-but-accurate integer method.
++ jidctfst.c Inverse DCT using faster, less accurate integer method.
++ jidctflt.c Inverse DCT using floating-point arithmetic.
++ jidctred.c Inverse DCTs with reduced-size outputs.
++
++ Lossless (spatial) codec:
++
++ jdlossls.c Lossless decompressor proper.
++ jddiffct.c Buffer controller for difference buffers.
++ jdlhuff.c Huffman entropy decoding for lossless JPEG.
++ jdpred.c Sample predictor and undifferencer.
++ jdscale.c Point transformation, sample size scaling.
++
+ Support files for both compression and decompression:
+
+ jerror.c Standard error handling routines (application replaceable).
+ jmemmgr.c System-independent (more or less) memory management code.
++ jcodec.c Codec-independent utility routines.
+ jutils.c Miscellaneous utility routines.
+
+ jmemmgr.c relies on a system-dependent memory management module. The IJG
+diff -cN ../jpeg-6b/jcapimin.c ./jcapimin.c
+*** ../jpeg-6b/jcapimin.c Sat Jan 24 16:21:30 1998
+--- ./jcapimin.c Tue Apr 27 14:58:16 1999
+***************
+*** 168,174 ****
+ /* We bypass the main controller and invoke coef controller directly;
+ * all work is being done from the coefficient buffer.
+ */
+! if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
+ ERREXIT(cinfo, JERR_CANT_SUSPEND);
+ }
+ (*cinfo->master->finish_pass) (cinfo);
+--- 168,174 ----
+ /* We bypass the main controller and invoke coef controller directly;
+ * all work is being done from the coefficient buffer.
+ */
+! if (! (*cinfo->codec->compress_data) (cinfo, (JSAMPIMAGE) NULL))
+ ERREXIT(cinfo, JERR_CANT_SUSPEND);
+ }
+ (*cinfo->master->finish_pass) (cinfo);
+diff -cN ../jpeg-6b/jcapistd.c ./jcapistd.c
+*** ../jpeg-6b/jcapistd.c Sat Jan 6 18:24:10 1996
+--- ./jcapistd.c Tue Apr 27 14:58:16 1999
+***************
+*** 145,156 ****
+ (*cinfo->master->pass_startup) (cinfo);
+
+ /* Verify that at least one iMCU row has been passed. */
+! lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
+ if (num_lines < lines_per_iMCU_row)
+ ERREXIT(cinfo, JERR_BUFFER_SIZE);
+
+ /* Directly compress the row. */
+! if (! (*cinfo->coef->compress_data) (cinfo, data)) {
+ /* If compressor did not consume the whole row, suspend processing. */
+ return 0;
+ }
+--- 145,156 ----
+ (*cinfo->master->pass_startup) (cinfo);
+
+ /* Verify that at least one iMCU row has been passed. */
+! lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->data_unit;
+ if (num_lines < lines_per_iMCU_row)
+ ERREXIT(cinfo, JERR_BUFFER_SIZE);
+
+ /* Directly compress the row. */
+! if (! (*cinfo->codec->compress_data) (cinfo, data)) {
+ /* If compressor did not consume the whole row, suspend processing. */
+ return 0;
+ }
+diff -cN ../jpeg-6b/jccoefct.c ./jccoefct.c
+*** ../jpeg-6b/jccoefct.c Sat Nov 15 21:25:09 1997
+--- ./jccoefct.c Tue Apr 27 14:58:16 1999
+***************
+*** 1,7 ****
+ /*
+ * jccoefct.c
+ *
+! * Copyright (C) 1994-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jccoefct.c
+ *
+! * Copyright (C) 1994-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 13,18 ****
+--- 13,19 ----
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
++ #include "jlossy.h" /* Private declarations for lossy codec */
+
+
+ /* We use a full-image coefficient buffer when doing Huffman optimization,
+***************
+*** 32,39 ****
+ /* Private buffer controller object */
+
+ typedef struct {
+- struct jpeg_c_coef_controller pub; /* public fields */
+-
+ JDIMENSION iMCU_row_num; /* iMCU row # within image */
+ JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
+ int MCU_vert_offset; /* counts MCU rows within iMCU row */
+--- 33,38 ----
+***************
+*** 41,60 ****
+
+ /* For single-pass compression, it's sufficient to buffer just one MCU
+ * (although this may prove a bit slow in practice). We allocate a
+! * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
+! * MCU constructed and sent. (On 80x86, the workspace is FAR even though
+! * it's not really very big; this is to keep the module interfaces unchanged
+! * when a large coefficient buffer is necessary.)
+ * In multi-pass modes, this array points to the current MCU's blocks
+ * within the virtual arrays.
+ */
+! JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
+
+ /* In multi-pass modes, we need a virtual block array for each component. */
+ jvirt_barray_ptr whole_image[MAX_COMPONENTS];
+! } my_coef_controller;
+
+! typedef my_coef_controller * my_coef_ptr;
+
+
+ /* Forward declarations */
+--- 40,59 ----
+
+ /* For single-pass compression, it's sufficient to buffer just one MCU
+ * (although this may prove a bit slow in practice). We allocate a
+! * workspace of C_MAX_DATA_UNITS_IN_MCU coefficient blocks, and reuse it for
+! * each MCU constructed and sent. (On 80x86, the workspace is FAR even
+! * though it's not really very big; this is to keep the module interfaces
+! * unchanged when a large coefficient buffer is necessary.)
+ * In multi-pass modes, this array points to the current MCU's blocks
+ * within the virtual arrays.
+ */
+! JBLOCKROW MCU_buffer[C_MAX_DATA_UNITS_IN_MCU];
+
+ /* In multi-pass modes, we need a virtual block array for each component. */
+ jvirt_barray_ptr whole_image[MAX_COMPONENTS];
+! } c_coef_controller;
+
+! typedef c_coef_controller * c_coef_ptr;
+
+
+ /* Forward declarations */
+***************
+*** 72,78 ****
+ start_iMCU_row (j_compress_ptr cinfo)
+ /* Reset within-iMCU-row counters for a new row */
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+--- 71,78 ----
+ start_iMCU_row (j_compress_ptr cinfo)
+ /* Reset within-iMCU-row counters for a new row */
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+***************
+*** 99,105 ****
+ METHODDEF(void)
+ start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ coef->iMCU_row_num = 0;
+ start_iMCU_row(cinfo);
+--- 99,106 ----
+ METHODDEF(void)
+ start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+
+ coef->iMCU_row_num = 0;
+ start_iMCU_row(cinfo);
+***************
+*** 108,125 ****
+ case JBUF_PASS_THRU:
+ if (coef->whole_image[0] != NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+! coef->pub.compress_data = compress_data;
+ break;
+ #ifdef FULL_COEF_BUFFER_SUPPORTED
+ case JBUF_SAVE_AND_PASS:
+ if (coef->whole_image[0] == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+! coef->pub.compress_data = compress_first_pass;
+ break;
+ case JBUF_CRANK_DEST:
+ if (coef->whole_image[0] == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+! coef->pub.compress_data = compress_output;
+ break;
+ #endif
+ default:
+--- 109,126 ----
+ case JBUF_PASS_THRU:
+ if (coef->whole_image[0] != NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+! lossyc->pub.compress_data = compress_data;
+ break;
+ #ifdef FULL_COEF_BUFFER_SUPPORTED
+ case JBUF_SAVE_AND_PASS:
+ if (coef->whole_image[0] == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+! lossyc->pub.compress_data = compress_first_pass;
+ break;
+ case JBUF_CRANK_DEST:
+ if (coef->whole_image[0] == NULL)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+! lossyc->pub.compress_data = compress_output;
+ break;
+ #endif
+ default:
+***************
+*** 142,148 ****
+ METHODDEF(boolean)
+ compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+--- 143,150 ----
+ METHODDEF(boolean)
+ compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+***************
+*** 174,183 ****
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ if (coef->iMCU_row_num < last_iMCU_row ||
+ yoffset+yindex < compptr->last_row_height) {
+! (*cinfo->fdct->forward_DCT) (cinfo, compptr,
+! input_buf[compptr->component_index],
+! coef->MCU_buffer[blkn],
+! ypos, xpos, (JDIMENSION) blockcnt);
+ if (blockcnt < compptr->MCU_width) {
+ /* Create some dummy blocks at the right edge of the image. */
+ jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
+--- 176,185 ----
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ if (coef->iMCU_row_num < last_iMCU_row ||
+ yoffset+yindex < compptr->last_row_height) {
+! (*lossyc->fdct_forward_DCT) (cinfo, compptr,
+! input_buf[compptr->component_index],
+! coef->MCU_buffer[blkn],
+! ypos, xpos, (JDIMENSION) blockcnt);
+ if (blockcnt < compptr->MCU_width) {
+ /* Create some dummy blocks at the right edge of the image. */
+ jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
+***************
+*** 201,207 ****
+ /* Try to write the MCU. In event of a suspension failure, we will
+ * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
+ */
+! if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->mcu_ctr = MCU_col_num;
+--- 203,209 ----
+ /* Try to write the MCU. In event of a suspension failure, we will
+ * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
+ */
+! if (! (*lossyc->entropy_encode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->mcu_ctr = MCU_col_num;
+***************
+*** 244,250 ****
+ METHODDEF(boolean)
+ compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION blocks_across, MCUs_across, MCUindex;
+ int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
+--- 246,253 ----
+ METHODDEF(boolean)
+ compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION blocks_across, MCUs_across, MCUindex;
+ int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
+***************
+*** 265,274 ****
+ block_rows = compptr->v_samp_factor;
+ else {
+ /* NB: can't use last_row_height here, since may not be set! */
+! block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ }
+! blocks_across = compptr->width_in_blocks;
+ h_samp_factor = compptr->h_samp_factor;
+ /* Count number of dummy blocks to be added at the right margin. */
+ ndummy = (int) (blocks_across % h_samp_factor);
+--- 268,277 ----
+ block_rows = compptr->v_samp_factor;
+ else {
+ /* NB: can't use last_row_height here, since may not be set! */
+! block_rows = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ }
+! blocks_across = compptr->width_in_data_units;
+ h_samp_factor = compptr->h_samp_factor;
+ /* Count number of dummy blocks to be added at the right margin. */
+ ndummy = (int) (blocks_across % h_samp_factor);
+***************
+*** 279,285 ****
+ */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+ thisblockrow = buffer[block_row];
+! (*cinfo->fdct->forward_DCT) (cinfo, compptr,
+ input_buf[ci], thisblockrow,
+ (JDIMENSION) (block_row * DCTSIZE),
+ (JDIMENSION) 0, blocks_across);
+--- 282,288 ----
+ */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+ thisblockrow = buffer[block_row];
+! (*lossyc->fdct_forward_DCT) (cinfo, compptr,
+ input_buf[ci], thisblockrow,
+ (JDIMENSION) (block_row * DCTSIZE),
+ (JDIMENSION) 0, blocks_across);
+***************
+*** 340,346 ****
+ METHODDEF(boolean)
+ compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ int blkn, ci, xindex, yindex, yoffset;
+ JDIMENSION start_col;
+--- 343,350 ----
+ METHODDEF(boolean)
+ compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ int blkn, ci, xindex, yindex, yoffset;
+ JDIMENSION start_col;
+***************
+*** 378,384 ****
+ }
+ }
+ /* Try to write the MCU. */
+! if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->mcu_ctr = MCU_col_num;
+--- 382,388 ----
+ }
+ }
+ /* Try to write the MCU. */
+! if (! (*lossyc->entropy_encode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->mcu_ctr = MCU_col_num;
+***************
+*** 404,416 ****
+ GLOBAL(void)
+ jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
+ {
+! my_coef_ptr coef;
+
+! coef = (my_coef_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! SIZEOF(my_coef_controller));
+! cinfo->coef = (struct jpeg_c_coef_controller *) coef;
+! coef->pub.start_pass = start_pass_coef;
+
+ /* Create the coefficient buffer. */
+ if (need_full_buffer) {
+--- 408,421 ----
+ GLOBAL(void)
+ jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! c_coef_ptr coef;
+
+! coef = (c_coef_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! SIZEOF(c_coef_controller));
+! lossyc->coef_private = (struct jpeg_c_coef_controller *) coef;
+! lossyc->coef_start_pass = start_pass_coef;
+
+ /* Create the coefficient buffer. */
+ if (need_full_buffer) {
+***************
+*** 424,432 ****
+ ci++, compptr++) {
+ coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+! (JDIMENSION) jround_up((long) compptr->width_in_blocks,
+ (long) compptr->h_samp_factor),
+! (JDIMENSION) jround_up((long) compptr->height_in_blocks,
+ (long) compptr->v_samp_factor),
+ (JDIMENSION) compptr->v_samp_factor);
+ }
+--- 429,437 ----
+ ci++, compptr++) {
+ coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+! (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor),
+! (JDIMENSION) jround_up((long) compptr->height_in_data_units,
+ (long) compptr->v_samp_factor),
+ (JDIMENSION) compptr->v_samp_factor);
+ }
+***************
+*** 440,447 ****
+
+ buffer = (JBLOCKROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
+! for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
+ coef->MCU_buffer[i] = buffer + i;
+ }
+ coef->whole_image[0] = NULL; /* flag for no virtual arrays */
+--- 445,452 ----
+
+ buffer = (JBLOCKROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! C_MAX_DATA_UNITS_IN_MCU * SIZEOF(JBLOCK));
+! for (i = 0; i < C_MAX_DATA_UNITS_IN_MCU; i++) {
+ coef->MCU_buffer[i] = buffer + i;
+ }
+ coef->whole_image[0] = NULL; /* flag for no virtual arrays */
+diff -cN ../jpeg-6b/jcdctmgr.c ./jcdctmgr.c
+*** ../jpeg-6b/jcdctmgr.c Sat Jan 13 14:15:12 1996
+--- ./jcdctmgr.c Tue Apr 27 14:58:16 1999
+***************
+*** 1,7 ****
+ /*
+ * jcdctmgr.c
+ *
+! * Copyright (C) 1994-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jcdctmgr.c
+ *
+! * Copyright (C) 1994-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 14,19 ****
+--- 14,20 ----
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
++ #include "jlossy.h" /* Private declarations for lossy codec */
+ #include "jdct.h" /* Private declarations for DCT subsystem */
+
+
+***************
+*** 20,27 ****
+ /* Private subobject for this module */
+
+ typedef struct {
+- struct jpeg_forward_dct pub; /* public fields */
+-
+ /* Pointer to the DCT routine actually in use */
+ forward_DCT_method_ptr do_dct;
+
+--- 21,26 ----
+***************
+*** 36,44 ****
+ float_DCT_method_ptr do_float_dct;
+ FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
+ #endif
+! } my_fdct_controller;
+
+! typedef my_fdct_controller * my_fdct_ptr;
+
+
+ /*
+--- 35,43 ----
+ float_DCT_method_ptr do_float_dct;
+ FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
+ #endif
+! } fdct_controller;
+
+! typedef fdct_controller * fdct_ptr;
+
+
+ /*
+***************
+*** 53,59 ****
+ METHODDEF(void)
+ start_pass_fdctmgr (j_compress_ptr cinfo)
+ {
+! my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
+ int ci, qtblno, i;
+ jpeg_component_info *compptr;
+ JQUANT_TBL * qtbl;
+--- 52,59 ----
+ METHODDEF(void)
+ start_pass_fdctmgr (j_compress_ptr cinfo)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! fdct_ptr fdct = (fdct_ptr) lossyc->fdct_private;
+ int ci, qtblno, i;
+ jpeg_component_info *compptr;
+ JQUANT_TBL * qtbl;
+***************
+*** 184,190 ****
+ /* This version is used for integer DCT implementations. */
+ {
+ /* This routine is heavily used, so it's worth coding it tightly. */
+! my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
+ forward_DCT_method_ptr do_dct = fdct->do_dct;
+ DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
+ DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
+--- 184,191 ----
+ /* This version is used for integer DCT implementations. */
+ {
+ /* This routine is heavily used, so it's worth coding it tightly. */
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! fdct_ptr fdct = (fdct_ptr) lossyc->fdct_private;
+ forward_DCT_method_ptr do_dct = fdct->do_dct;
+ DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
+ DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
+***************
+*** 274,280 ****
+ /* This version is used for floating-point DCT implementations. */
+ {
+ /* This routine is heavily used, so it's worth coding it tightly. */
+! my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
+ float_DCT_method_ptr do_dct = fdct->do_float_dct;
+ FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
+ FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
+--- 275,282 ----
+ /* This version is used for floating-point DCT implementations. */
+ {
+ /* This routine is heavily used, so it's worth coding it tightly. */
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! fdct_ptr fdct = (fdct_ptr) lossyc->fdct_private;
+ float_DCT_method_ptr do_dct = fdct->do_float_dct;
+ FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
+ FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
+***************
+*** 344,374 ****
+ GLOBAL(void)
+ jinit_forward_dct (j_compress_ptr cinfo)
+ {
+! my_fdct_ptr fdct;
+ int i;
+
+! fdct = (my_fdct_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! SIZEOF(my_fdct_controller));
+! cinfo->fdct = (struct jpeg_forward_dct *) fdct;
+! fdct->pub.start_pass = start_pass_fdctmgr;
+
+ switch (cinfo->dct_method) {
+ #ifdef DCT_ISLOW_SUPPORTED
+ case JDCT_ISLOW:
+! fdct->pub.forward_DCT = forward_DCT;
+ fdct->do_dct = jpeg_fdct_islow;
+ break;
+ #endif
+ #ifdef DCT_IFAST_SUPPORTED
+ case JDCT_IFAST:
+! fdct->pub.forward_DCT = forward_DCT;
+ fdct->do_dct = jpeg_fdct_ifast;
+ break;
+ #endif
+ #ifdef DCT_FLOAT_SUPPORTED
+ case JDCT_FLOAT:
+! fdct->pub.forward_DCT = forward_DCT_float;
+ fdct->do_float_dct = jpeg_fdct_float;
+ break;
+ #endif
+--- 346,377 ----
+ GLOBAL(void)
+ jinit_forward_dct (j_compress_ptr cinfo)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! fdct_ptr fdct;
+ int i;
+
+! fdct = (fdct_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! SIZEOF(fdct_controller));
+! lossyc->fdct_private = (struct jpeg_forward_dct *) fdct;
+! lossyc->fdct_start_pass = start_pass_fdctmgr;
+
+ switch (cinfo->dct_method) {
+ #ifdef DCT_ISLOW_SUPPORTED
+ case JDCT_ISLOW:
+! lossyc->fdct_forward_DCT = forward_DCT;
+ fdct->do_dct = jpeg_fdct_islow;
+ break;
+ #endif
+ #ifdef DCT_IFAST_SUPPORTED
+ case JDCT_IFAST:
+! lossyc->fdct_forward_DCT = forward_DCT;
+ fdct->do_dct = jpeg_fdct_ifast;
+ break;
+ #endif
+ #ifdef DCT_FLOAT_SUPPORTED
+ case JDCT_FLOAT:
+! lossyc->fdct_forward_DCT = forward_DCT_float;
+ fdct->do_float_dct = jpeg_fdct_float;
+ break;
+ #endif
+diff -cN ../jpeg-6b/jcdiffct.c ./jcdiffct.c
+*** ../jpeg-6b/jcdiffct.c
+--- ./jcdiffct.c Tue Apr 27 14:58:17 1999
+***************
+*** 0 ****
+--- 1,409 ----
++ /*
++ * jcdiffct.c
++ *
++ * Copyright (C) 1994-1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains the difference buffer controller for compression.
++ * This controller is the top level of the lossless JPEG compressor proper.
++ * The difference buffer lies between prediction/differencing and entropy
++ * encoding.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossls.h" /* Private declarations for lossless codec */
++
++
++ #ifdef C_LOSSLESS_SUPPORTED
++
++ /* We use a full-image sample buffer when doing Huffman optimization,
++ * and also for writing multiple-scan JPEG files. In all cases, the
++ * full-image buffer is filled during the first pass, and the scaling,
++ * prediction and differencing steps are run during subsequent passes.
++ */
++ #ifdef ENTROPY_OPT_SUPPORTED
++ #define FULL_SAMP_BUFFER_SUPPORTED
++ #else
++ #ifdef C_MULTISCAN_FILES_SUPPORTED
++ #define FULL_SAMP_BUFFER_SUPPORTED
++ #endif
++ #endif
++
++
++ /* Private buffer controller object */
++
++ typedef struct {
++ JDIMENSION iMCU_row_num; /* iMCU row # within image */
++ JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
++ int MCU_vert_offset; /* counts MCU rows within iMCU row */
++ int MCU_rows_per_iMCU_row; /* number of such rows needed */
++
++ JSAMPROW cur_row[MAX_COMPONENTS]; /* row of point transformed samples */
++ JSAMPROW prev_row[MAX_COMPONENTS]; /* previous row of Pt'd samples */
++ JDIFFARRAY diff_buf[MAX_COMPONENTS]; /* iMCU row of differences */
++
++ /* In multi-pass modes, we need a virtual sample array for each component. */
++ jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
++ } c_diff_controller;
++
++ typedef c_diff_controller * c_diff_ptr;
++
++
++ /* Forward declarations */
++ METHODDEF(boolean) compress_data
++ JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
++ #ifdef FULL_SAMP_BUFFER_SUPPORTED
++ METHODDEF(boolean) compress_first_pass
++ JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
++ METHODDEF(boolean) compress_output
++ JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
++ #endif
++
++
++ LOCAL(void)
++ start_iMCU_row (j_compress_ptr cinfo)
++ /* Reset within-iMCU-row counters for a new row */
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ c_diff_ptr diff = (c_diff_ptr) losslsc->diff_private;
++
++ /* In an interleaved scan, an MCU row is the same as an iMCU row.
++ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
++ * But at the bottom of the image, process only what's left.
++ */
++ if (cinfo->comps_in_scan > 1) {
++ diff->MCU_rows_per_iMCU_row = 1;
++ } else {
++ if (diff->iMCU_row_num < (cinfo->total_iMCU_rows-1))
++ diff->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
++ else
++ diff->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
++ }
++
++ diff->mcu_ctr = 0;
++ diff->MCU_vert_offset = 0;
++ }
++
++
++ /*
++ * Initialize for a processing pass.
++ */
++
++ METHODDEF(void)
++ start_pass_diff (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ c_diff_ptr diff = (c_diff_ptr) losslsc->diff_private;
++
++ diff->iMCU_row_num = 0;
++ start_iMCU_row(cinfo);
++
++ switch (pass_mode) {
++ case JBUF_PASS_THRU:
++ if (diff->whole_image[0] != NULL)
++ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
++ losslsc->pub.compress_data = compress_data;
++ break;
++ #ifdef FULL_SAMP_BUFFER_SUPPORTED
++ case JBUF_SAVE_AND_PASS:
++ if (diff->whole_image[0] == NULL)
++ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
++ losslsc->pub.compress_data = compress_first_pass;
++ break;
++ case JBUF_CRANK_DEST:
++ if (diff->whole_image[0] == NULL)
++ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
++ losslsc->pub.compress_data = compress_output;
++ break;
++ #endif
++ default:
++ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
++ break;
++ }
++ }
++
++
++ #define SWAP_ROWS(rowa,rowb) {JSAMPROW temp; temp=rowa; rowa=rowb; rowb=temp;}
++
++ /*
++ * Process some data in the single-pass case.
++ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
++ * per call, ie, v_samp_factor rows for each component in the image.
++ * Returns TRUE if the iMCU row is completed, FALSE if suspended.
++ *
++ * NB: input_buf contains a plane for each component in image,
++ * which we index according to the component's SOF position.
++ */
++
++ METHODDEF(boolean)
++ compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ c_diff_ptr diff = (c_diff_ptr) losslsc->diff_private;
++ JDIMENSION MCU_col_num; /* index of current MCU within row */
++ JDIMENSION MCU_count; /* number of MCUs encoded */
++ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
++ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
++ int comp, ci, yoffset, samp_row, samp_rows, samps_across;
++ jpeg_component_info *compptr;
++
++ /* Loop to write as much as one whole iMCU row */
++ for (yoffset = diff->MCU_vert_offset; yoffset < diff->MCU_rows_per_iMCU_row;
++ yoffset++) {
++
++ MCU_col_num = diff->mcu_ctr;
++
++ /* Scale and predict each scanline of the MCU-row separately.
++ *
++ * Note: We only do this if we are at the start of a MCU-row, ie,
++ * we don't want to reprocess a row suspended by the output.
++ */
++ if (MCU_col_num == 0) {
++ for (comp = 0; comp < cinfo->comps_in_scan; comp++) {
++ compptr = cinfo->cur_comp_info[comp];
++ ci = compptr->component_index;
++ if (diff->iMCU_row_num < last_iMCU_row)
++ samp_rows = compptr->v_samp_factor;
++ else {
++ /* NB: can't use last_row_height here, since may not be set! */
++ samp_rows = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
++ if (samp_rows == 0) samp_rows = compptr->v_samp_factor;
++ else {
++ /* Fill dummy difference rows at the bottom edge with zeros, which
++ * will encode to the smallest amount of data.
++ */
++ for (samp_row = samp_rows; samp_row < compptr->v_samp_factor;
++ samp_row++)
++ MEMZERO(diff->diff_buf[ci][samp_row],
++ jround_up((long) compptr->width_in_data_units,
++ (long) compptr->h_samp_factor) * SIZEOF(JDIFF));
++ }
++ }
++ samps_across = compptr->width_in_data_units;
++
++ for (samp_row = 0; samp_row < samp_rows; samp_row++) {
++ (*losslsc->scaler_scale) (cinfo,
++ input_buf[ci][samp_row],
++ diff->cur_row[ci], samps_across);
++ (*losslsc->predict_difference[ci]) (cinfo, ci,
++ diff->cur_row[ci],
++ diff->prev_row[ci],
++ diff->diff_buf[ci][samp_row],
++ samps_across);
++ SWAP_ROWS(diff->cur_row[ci], diff->prev_row[ci]);
++ }
++ }
++ }
++
++ /* Try to write the MCU-row (or remaining portion of suspended MCU-row). */
++ MCU_count =
++ (*losslsc->entropy_encode_mcus) (cinfo,
++ diff->diff_buf, yoffset, MCU_col_num,
++ cinfo->MCUs_per_row - MCU_col_num);
++ if (MCU_count != cinfo->MCUs_per_row - MCU_col_num) {
++ /* Suspension forced; update state counters and exit */
++ diff->MCU_vert_offset = yoffset;
++ diff->mcu_ctr += MCU_col_num;
++ return FALSE;
++ }
++
++ /* Completed an MCU row, but perhaps not an iMCU row */
++ diff->mcu_ctr = 0;
++ }
++
++ /* Completed the iMCU row, advance counters for next one */
++ diff->iMCU_row_num++;
++ start_iMCU_row(cinfo);
++ return TRUE;
++ }
++
++
++ #ifdef FULL_SAMP_BUFFER_SUPPORTED
++
++ /*
++ * Process some data in the first pass of a multi-pass case.
++ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
++ * per call, ie, v_samp_factor rows for each component in the image.
++ * This amount of data is read from the source buffer and saved into the
++ * virtual arrays.
++ *
++ * We must also emit the data to the compressor. This is conveniently
++ * done by calling compress_output() after we've loaded the current strip
++ * of the virtual arrays.
++ *
++ * NB: input_buf contains a plane for each component in image. All components
++ * are loaded into the virtual arrays in this pass. However, it may be that
++ * only a subset of the components are emitted to the compressor during
++ * this first pass; be careful about looking at the scan-dependent variables
++ * (MCU dimensions, etc).
++ */
++
++ METHODDEF(boolean)
++ compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ c_diff_ptr diff = (c_diff_ptr) losslsc->diff_private;
++ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
++ JDIMENSION samps_across;
++ int ci, samp_row, samp_rows;
++ JSAMPARRAY buffer[MAX_COMPONENTS];
++ jpeg_component_info *compptr;
++
++ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
++ ci++, compptr++) {
++ /* Align the virtual buffers for this component. */
++ buffer[ci] = (*cinfo->mem->access_virt_sarray)
++ ((j_common_ptr) cinfo, diff->whole_image[ci],
++ diff->iMCU_row_num * compptr->v_samp_factor,
++ (JDIMENSION) compptr->v_samp_factor, TRUE);
++
++ /* Count non-dummy sample rows in this iMCU row. */
++ if (diff->iMCU_row_num < last_iMCU_row)
++ samp_rows = compptr->v_samp_factor;
++ else {
++ /* NB: can't use last_row_height here, since may not be set! */
++ samp_rows = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
++ if (samp_rows == 0) samp_rows = compptr->v_samp_factor;
++ }
++ samps_across = compptr->width_in_data_units;
++
++ /* Perform point transform scaling and prediction/differencing for all
++ * non-dummy rows in this iMCU row. Each call on these functions
++ * process a complete row of samples.
++ */
++ for (samp_row = 0; samp_row < samp_rows; samp_row++) {
++ MEMCOPY(buffer[ci][samp_row], input_buf[ci][samp_row],
++ samps_across * SIZEOF(JSAMPLE));
++ }
++ }
++
++ /* NB: compress_output will increment iMCU_row_num if successful.
++ * A suspension return will result in redoing all the work above next time.
++ */
++
++ /* Emit data to the compressor, sharing code with subsequent passes */
++ return compress_output(cinfo, input_buf);
++ }
++
++
++ /*
++ * Process some data in subsequent passes of a multi-pass case.
++ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
++ * per call, ie, v_samp_factor rows for each component in the scan.
++ * The data is obtained from the virtual arrays and fed to the compressor.
++ * Returns TRUE if the iMCU row is completed, FALSE if suspended.
++ *
++ * NB: input_buf is ignored; it is likely to be a NULL pointer.
++ */
++
++ METHODDEF(boolean)
++ compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ c_diff_ptr diff = (c_diff_ptr) losslsc->diff_private;
++ JDIMENSION MCU_col_num; /* index of current MCU within row */
++ JDIMENSION MCU_count; /* number of MCUs encoded */
++ int comp, ci, yoffset;
++ JSAMPARRAY buffer[MAX_COMPONENTS];
++ jpeg_component_info *compptr;
++
++ /* Align the virtual buffers for the components used in this scan.
++ * NB: during first pass, this is safe only because the buffers will
++ * already be aligned properly, so jmemmgr.c won't need to do any I/O.
++ */
++ for (comp = 0; comp < cinfo->comps_in_scan; comp++) {
++ compptr = cinfo->cur_comp_info[comp];
++ ci = compptr->component_index;
++ buffer[ci] = (*cinfo->mem->access_virt_sarray)
++ ((j_common_ptr) cinfo, diff->whole_image[ci],
++ diff->iMCU_row_num * compptr->v_samp_factor,
++ (JDIMENSION) compptr->v_samp_factor, FALSE);
++ }
++
++ return compress_data(cinfo, buffer);
++ }
++
++ #endif /* FULL_SAMP_BUFFER_SUPPORTED */
++
++
++ /*
++ * Initialize difference buffer controller.
++ */
++
++ GLOBAL(void)
++ jinit_c_diff_controller (j_compress_ptr cinfo, boolean need_full_buffer)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ c_diff_ptr diff;
++ int ci, row;
++ jpeg_component_info *compptr;
++
++ diff = (c_diff_ptr)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ SIZEOF(c_diff_controller));
++ losslsc->diff_private = (void *) diff;
++ losslsc->diff_start_pass = start_pass_diff;
++
++ /* Create the prediction row buffers. */
++ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
++ ci++, compptr++) {
++ diff->cur_row[ci] = *(*cinfo->mem->alloc_sarray)
++ ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
++ (long) compptr->h_samp_factor),
++ (JDIMENSION) 1);
++ diff->prev_row[ci] = *(*cinfo->mem->alloc_sarray)
++ ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
++ (long) compptr->h_samp_factor),
++ (JDIMENSION) 1);
++ }
++
++ /* Create the difference buffer. */
++ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
++ ci++, compptr++) {
++ diff->diff_buf[ci] = (*cinfo->mem->alloc_darray)
++ ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
++ (long) compptr->h_samp_factor),
++ (JDIMENSION) compptr->v_samp_factor);
++ /* Prefill difference rows with zeros. We do this because only actual
++ * data is placed in the buffers during prediction/differencing, leaving
++ * any dummy differences at the right edge as zeros, which will encode
++ * to the smallest amount of data.
++ */
++ for (row = 0; row < compptr->v_samp_factor; row++)
++ MEMZERO(diff->diff_buf[ci][row],
++ jround_up((long) compptr->width_in_data_units,
++ (long) compptr->h_samp_factor) * SIZEOF(JDIFF));
++ }
++
++ /* Create the sample buffer. */
++ if (need_full_buffer) {
++ #ifdef FULL_SAMP_BUFFER_SUPPORTED
++ /* Allocate a full-image virtual array for each component, */
++ /* padded to a multiple of samp_factor differences in each direction. */
++ int ci;
++ jpeg_component_info *compptr;
++
++ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
++ ci++, compptr++) {
++ diff->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
++ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
++ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
++ (long) compptr->h_samp_factor),
++ (JDIMENSION) jround_up((long) compptr->height_in_data_units,
++ (long) compptr->v_samp_factor),
++ (JDIMENSION) compptr->v_samp_factor);
++ }
++ #else
++ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
++ #endif
++ } else
++ diff->whole_image[0] = NULL; /* flag for no virtual arrays */
++ }
++
++ #endif /* C_LOSSLESS_SUPPORTED */
+diff -cN ../jpeg-6b/jchuff.c ./jchuff.c
+*** ../jpeg-6b/jchuff.c Mon Oct 20 20:20:39 1997
+--- ./jchuff.c Tue Apr 27 14:58:17 1999
+***************
+*** 1,178 ****
+ /*
+ * jchuff.c
+ *
+! * Copyright (C) 1991-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+! * This file contains Huffman entropy encoding routines.
+! *
+! * Much of the complexity here has to do with supporting output suspension.
+! * If the data destination module demands suspension, we want to be able to
+! * back up to the start of the current MCU. To do this, we copy state
+! * variables into local working storage, and update them back to the
+! * permanent JPEG objects only upon successful completion of an MCU.
+ */
+
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
+! #include "jchuff.h" /* Declarations shared with jcphuff.c */
+!
+!
+! /* Expanded entropy encoder object for Huffman encoding.
+! *
+! * The savable_state subrecord contains fields that change within an MCU,
+! * but must not be updated permanently until we complete the MCU.
+! */
+!
+! typedef struct {
+! INT32 put_buffer; /* current bit-accumulation buffer */
+! int put_bits; /* # of bits now in it */
+! int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
+! } savable_state;
+!
+! /* This macro is to work around compilers with missing or broken
+! * structure assignment. You'll need to fix this code if you have
+! * such a compiler and you change MAX_COMPS_IN_SCAN.
+! */
+!
+! #ifndef NO_STRUCT_ASSIGN
+! #define ASSIGN_STATE(dest,src) ((dest) = (src))
+! #else
+! #if MAX_COMPS_IN_SCAN == 4
+! #define ASSIGN_STATE(dest,src) \
+! ((dest).put_buffer = (src).put_buffer, \
+! (dest).put_bits = (src).put_bits, \
+! (dest).last_dc_val[0] = (src).last_dc_val[0], \
+! (dest).last_dc_val[1] = (src).last_dc_val[1], \
+! (dest).last_dc_val[2] = (src).last_dc_val[2], \
+! (dest).last_dc_val[3] = (src).last_dc_val[3])
+! #endif
+! #endif
+!
+!
+! typedef struct {
+! struct jpeg_entropy_encoder pub; /* public fields */
+!
+! savable_state saved; /* Bit buffer & DC state at start of MCU */
+!
+! /* These fields are NOT loaded into local working state. */
+! unsigned int restarts_to_go; /* MCUs left in this restart interval */
+! int next_restart_num; /* next restart number to write (0-7) */
+!
+! /* Pointers to derived tables (these workspaces have image lifespan) */
+! c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
+! c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
+!
+! #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
+! long * dc_count_ptrs[NUM_HUFF_TBLS];
+! long * ac_count_ptrs[NUM_HUFF_TBLS];
+! #endif
+! } huff_entropy_encoder;
+!
+! typedef huff_entropy_encoder * huff_entropy_ptr;
+!
+! /* Working state while writing an MCU.
+! * This struct contains all the fields that are needed by subroutines.
+! */
+!
+! typedef struct {
+! JOCTET * next_output_byte; /* => next byte to write in buffer */
+! size_t free_in_buffer; /* # of byte spaces remaining in buffer */
+! savable_state cur; /* Current bit buffer & DC state */
+! j_compress_ptr cinfo; /* dump_buffer needs access to this */
+! } working_state;
+!
+!
+! /* Forward declarations */
+! METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
+! JBLOCKROW *MCU_data));
+! METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
+! #ifdef ENTROPY_OPT_SUPPORTED
+! METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
+! JBLOCKROW *MCU_data));
+! METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
+! #endif
+!
+!
+! /*
+! * Initialize for a Huffman-compressed scan.
+! * If gather_statistics is TRUE, we do not output anything during the scan,
+! * just count the Huffman symbols used and generate Huffman code tables.
+! */
+!
+! METHODDEF(void)
+! start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
+! {
+! huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+! int ci, dctbl, actbl;
+! jpeg_component_info * compptr;
+!
+! if (gather_statistics) {
+! #ifdef ENTROPY_OPT_SUPPORTED
+! entropy->pub.encode_mcu = encode_mcu_gather;
+! entropy->pub.finish_pass = finish_pass_gather;
+! #else
+! ERREXIT(cinfo, JERR_NOT_COMPILED);
+! #endif
+! } else {
+! entropy->pub.encode_mcu = encode_mcu_huff;
+! entropy->pub.finish_pass = finish_pass_huff;
+! }
+!
+! for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+! compptr = cinfo->cur_comp_info[ci];
+! dctbl = compptr->dc_tbl_no;
+! actbl = compptr->ac_tbl_no;
+! if (gather_statistics) {
+! #ifdef ENTROPY_OPT_SUPPORTED
+! /* Check for invalid table indexes */
+! /* (make_c_derived_tbl does this in the other path) */
+! if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
+! ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
+! if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
+! ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
+! /* Allocate and zero the statistics tables */
+! /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
+! if (entropy->dc_count_ptrs[dctbl] == NULL)
+! entropy->dc_count_ptrs[dctbl] = (long *)
+! (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! 257 * SIZEOF(long));
+! MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
+! if (entropy->ac_count_ptrs[actbl] == NULL)
+! entropy->ac_count_ptrs[actbl] = (long *)
+! (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! 257 * SIZEOF(long));
+! MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
+! #endif
+! } else {
+! /* Compute derived values for Huffman tables */
+! /* We may do this more than once for a table, but it's not expensive */
+! jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
+! & entropy->dc_derived_tbls[dctbl]);
+! jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
+! & entropy->ac_derived_tbls[actbl]);
+! }
+! /* Initialize DC predictions to 0 */
+! entropy->saved.last_dc_val[ci] = 0;
+! }
+!
+! /* Initialize bit buffer to empty */
+! entropy->saved.put_buffer = 0;
+! entropy->saved.put_bits = 0;
+!
+! /* Initialize restart stuff */
+! entropy->restarts_to_go = cinfo->restart_interval;
+! entropy->next_restart_num = 0;
+! }
+
+
+ /*
+ * Compute the derived values for a Huffman table.
+ * This routine also performs some validation checks on the table.
+- *
+- * Note this is also used by jcphuff.c.
+ */
+
+ GLOBAL(void)
+--- 1,23 ----
+ /*
+ * jchuff.c
+ *
+! * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+! * This file contains Huffman entropy decoding routines which are shared
+! * by the sequential, progressive and lossless decoders.
+ */
+
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
+! #include "jchuff.h" /* Declarations shared with jc*huff.c */
+
+
+ /*
+ * Compute the derived values for a Huffman table.
+ * This routine also performs some validation checks on the table.
+ */
+
+ GLOBAL(void)
+***************
+*** 249,258 ****
+
+ /* This is also a convenient place to check for out-of-range
+ * and duplicated VAL entries. We allow 0..255 for AC symbols
+! * but only 0..15 for DC. (We could constrain them further
+ * based on data depth and mode, but this seems enough.)
+ */
+! maxsymbol = isDC ? 15 : 255;
+
+ for (p = 0; p < lastp; p++) {
+ i = htbl->huffval[p];
+--- 94,103 ----
+
+ /* This is also a convenient place to check for out-of-range
+ * and duplicated VAL entries. We allow 0..255 for AC symbols
+! * but only 0..16 for DC. (We could constrain them further
+ * based on data depth and mode, but this seems enough.)
+ */
+! maxsymbol = isDC ? 16 : 255;
+
+ for (p = 0; p < lastp; p++) {
+ i = htbl->huffval[p];
+***************
+*** 264,681 ****
+ }
+
+
+- /* Outputting bytes to the file */
+-
+- /* Emit a byte, taking 'action' if must suspend. */
+- #define emit_byte(state,val,action) \
+- { *(state)->next_output_byte++ = (JOCTET) (val); \
+- if (--(state)->free_in_buffer == 0) \
+- if (! dump_buffer(state)) \
+- { action; } }
+-
+-
+- LOCAL(boolean)
+- dump_buffer (working_state * state)
+- /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
+- {
+- struct jpeg_destination_mgr * dest = state->cinfo->dest;
+-
+- if (! (*dest->empty_output_buffer) (state->cinfo))
+- return FALSE;
+- /* After a successful buffer dump, must reset buffer pointers */
+- state->next_output_byte = dest->next_output_byte;
+- state->free_in_buffer = dest->free_in_buffer;
+- return TRUE;
+- }
+-
+-
+- /* Outputting bits to the file */
+-
+- /* Only the right 24 bits of put_buffer are used; the valid bits are
+- * left-justified in this part. At most 16 bits can be passed to emit_bits
+- * in one call, and we never retain more than 7 bits in put_buffer
+- * between calls, so 24 bits are sufficient.
+- */
+-
+- INLINE
+- LOCAL(boolean)
+- emit_bits (working_state * state, unsigned int code, int size)
+- /* Emit some bits; return TRUE if successful, FALSE if must suspend */
+- {
+- /* This routine is heavily used, so it's worth coding tightly. */
+- register INT32 put_buffer = (INT32) code;
+- register int put_bits = state->cur.put_bits;
+-
+- /* if size is 0, caller used an invalid Huffman table entry */
+- if (size == 0)
+- ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
+-
+- put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
+-
+- put_bits += size; /* new number of bits in buffer */
+-
+- put_buffer <<= 24 - put_bits; /* align incoming bits */
+-
+- put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
+-
+- while (put_bits >= 8) {
+- int c = (int) ((put_buffer >> 16) & 0xFF);
+-
+- emit_byte(state, c, return FALSE);
+- if (c == 0xFF) { /* need to stuff a zero byte? */
+- emit_byte(state, 0, return FALSE);
+- }
+- put_buffer <<= 8;
+- put_bits -= 8;
+- }
+-
+- state->cur.put_buffer = put_buffer; /* update state variables */
+- state->cur.put_bits = put_bits;
+-
+- return TRUE;
+- }
+-
+-
+- LOCAL(boolean)
+- flush_bits (working_state * state)
+- {
+- if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
+- return FALSE;
+- state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
+- state->cur.put_bits = 0;
+- return TRUE;
+- }
+-
+-
+- /* Encode a single block's worth of coefficients */
+-
+- LOCAL(boolean)
+- encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
+- c_derived_tbl *dctbl, c_derived_tbl *actbl)
+- {
+- register int temp, temp2;
+- register int nbits;
+- register int k, r, i;
+-
+- /* Encode the DC coefficient difference per section F.1.2.1 */
+-
+- temp = temp2 = block[0] - last_dc_val;
+-
+- if (temp < 0) {
+- temp = -temp; /* temp is abs value of input */
+- /* For a negative input, want temp2 = bitwise complement of abs(input) */
+- /* This code assumes we are on a two's complement machine */
+- temp2--;
+- }
+-
+- /* Find the number of bits needed for the magnitude of the coefficient */
+- nbits = 0;
+- while (temp) {
+- nbits++;
+- temp >>= 1;
+- }
+- /* Check for out-of-range coefficient values.
+- * Since we're encoding a difference, the range limit is twice as much.
+- */
+- if (nbits > MAX_COEF_BITS+1)
+- ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
+-
+- /* Emit the Huffman-coded symbol for the number of bits */
+- if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
+- return FALSE;
+-
+- /* Emit that number of bits of the value, if positive, */
+- /* or the complement of its magnitude, if negative. */
+- if (nbits) /* emit_bits rejects calls with size 0 */
+- if (! emit_bits(state, (unsigned int) temp2, nbits))
+- return FALSE;
+-
+- /* Encode the AC coefficients per section F.1.2.2 */
+-
+- r = 0; /* r = run length of zeros */
+-
+- for (k = 1; k < DCTSIZE2; k++) {
+- if ((temp = block[jpeg_natural_order[k]]) == 0) {
+- r++;
+- } else {
+- /* if run length > 15, must emit special run-length-16 codes (0xF0) */
+- while (r > 15) {
+- if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
+- return FALSE;
+- r -= 16;
+- }
+-
+- temp2 = temp;
+- if (temp < 0) {
+- temp = -temp; /* temp is abs value of input */
+- /* This code assumes we are on a two's complement machine */
+- temp2--;
+- }
+-
+- /* Find the number of bits needed for the magnitude of the coefficient */
+- nbits = 1; /* there must be at least one 1 bit */
+- while ((temp >>= 1))
+- nbits++;
+- /* Check for out-of-range coefficient values */
+- if (nbits > MAX_COEF_BITS)
+- ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
+-
+- /* Emit Huffman symbol for run length / number of bits */
+- i = (r << 4) + nbits;
+- if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
+- return FALSE;
+-
+- /* Emit that number of bits of the value, if positive, */
+- /* or the complement of its magnitude, if negative. */
+- if (! emit_bits(state, (unsigned int) temp2, nbits))
+- return FALSE;
+-
+- r = 0;
+- }
+- }
+-
+- /* If the last coef(s) were zero, emit an end-of-block code */
+- if (r > 0)
+- if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
+- return FALSE;
+-
+- return TRUE;
+- }
+-
+-
+- /*
+- * Emit a restart marker & resynchronize predictions.
+- */
+-
+- LOCAL(boolean)
+- emit_restart (working_state * state, int restart_num)
+- {
+- int ci;
+-
+- if (! flush_bits(state))
+- return FALSE;
+-
+- emit_byte(state, 0xFF, return FALSE);
+- emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
+-
+- /* Re-initialize DC predictions to 0 */
+- for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
+- state->cur.last_dc_val[ci] = 0;
+-
+- /* The restart counter is not updated until we successfully write the MCU. */
+-
+- return TRUE;
+- }
+-
+-
+- /*
+- * Encode and output one MCU's worth of Huffman-compressed coefficients.
+- */
+-
+- METHODDEF(boolean)
+- encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+- {
+- huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+- working_state state;
+- int blkn, ci;
+- jpeg_component_info * compptr;
+-
+- /* Load up working state */
+- state.next_output_byte = cinfo->dest->next_output_byte;
+- state.free_in_buffer = cinfo->dest->free_in_buffer;
+- ASSIGN_STATE(state.cur, entropy->saved);
+- state.cinfo = cinfo;
+-
+- /* Emit restart marker if needed */
+- if (cinfo->restart_interval) {
+- if (entropy->restarts_to_go == 0)
+- if (! emit_restart(&state, entropy->next_restart_num))
+- return FALSE;
+- }
+-
+- /* Encode the MCU data blocks */
+- for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+- ci = cinfo->MCU_membership[blkn];
+- compptr = cinfo->cur_comp_info[ci];
+- if (! encode_one_block(&state,
+- MCU_data[blkn][0], state.cur.last_dc_val[ci],
+- entropy->dc_derived_tbls[compptr->dc_tbl_no],
+- entropy->ac_derived_tbls[compptr->ac_tbl_no]))
+- return FALSE;
+- /* Update last_dc_val */
+- state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
+- }
+-
+- /* Completed MCU, so update state */
+- cinfo->dest->next_output_byte = state.next_output_byte;
+- cinfo->dest->free_in_buffer = state.free_in_buffer;
+- ASSIGN_STATE(entropy->saved, state.cur);
+-
+- /* Update restart-interval state too */
+- if (cinfo->restart_interval) {
+- if (entropy->restarts_to_go == 0) {
+- entropy->restarts_to_go = cinfo->restart_interval;
+- entropy->next_restart_num++;
+- entropy->next_restart_num &= 7;
+- }
+- entropy->restarts_to_go--;
+- }
+-
+- return TRUE;
+- }
+-
+-
+- /*
+- * Finish up at the end of a Huffman-compressed scan.
+- */
+-
+- METHODDEF(void)
+- finish_pass_huff (j_compress_ptr cinfo)
+- {
+- huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+- working_state state;
+-
+- /* Load up working state ... flush_bits needs it */
+- state.next_output_byte = cinfo->dest->next_output_byte;
+- state.free_in_buffer = cinfo->dest->free_in_buffer;
+- ASSIGN_STATE(state.cur, entropy->saved);
+- state.cinfo = cinfo;
+-
+- /* Flush out the last data */
+- if (! flush_bits(&state))
+- ERREXIT(cinfo, JERR_CANT_SUSPEND);
+-
+- /* Update state */
+- cinfo->dest->next_output_byte = state.next_output_byte;
+- cinfo->dest->free_in_buffer = state.free_in_buffer;
+- ASSIGN_STATE(entropy->saved, state.cur);
+- }
+-
+-
+- /*
+- * Huffman coding optimization.
+- *
+- * We first scan the supplied data and count the number of uses of each symbol
+- * that is to be Huffman-coded. (This process MUST agree with the code above.)
+- * Then we build a Huffman coding tree for the observed counts.
+- * Symbols which are not needed at all for the particular image are not
+- * assigned any code, which saves space in the DHT marker as well as in
+- * the compressed data.
+- */
+-
+- #ifdef ENTROPY_OPT_SUPPORTED
+-
+-
+- /* Process a single block's worth of coefficients */
+-
+- LOCAL(void)
+- htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
+- long dc_counts[], long ac_counts[])
+- {
+- register int temp;
+- register int nbits;
+- register int k, r;
+-
+- /* Encode the DC coefficient difference per section F.1.2.1 */
+-
+- temp = block[0] - last_dc_val;
+- if (temp < 0)
+- temp = -temp;
+-
+- /* Find the number of bits needed for the magnitude of the coefficient */
+- nbits = 0;
+- while (temp) {
+- nbits++;
+- temp >>= 1;
+- }
+- /* Check for out-of-range coefficient values.
+- * Since we're encoding a difference, the range limit is twice as much.
+- */
+- if (nbits > MAX_COEF_BITS+1)
+- ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+-
+- /* Count the Huffman symbol for the number of bits */
+- dc_counts[nbits]++;
+-
+- /* Encode the AC coefficients per section F.1.2.2 */
+-
+- r = 0; /* r = run length of zeros */
+-
+- for (k = 1; k < DCTSIZE2; k++) {
+- if ((temp = block[jpeg_natural_order[k]]) == 0) {
+- r++;
+- } else {
+- /* if run length > 15, must emit special run-length-16 codes (0xF0) */
+- while (r > 15) {
+- ac_counts[0xF0]++;
+- r -= 16;
+- }
+-
+- /* Find the number of bits needed for the magnitude of the coefficient */
+- if (temp < 0)
+- temp = -temp;
+-
+- /* Find the number of bits needed for the magnitude of the coefficient */
+- nbits = 1; /* there must be at least one 1 bit */
+- while ((temp >>= 1))
+- nbits++;
+- /* Check for out-of-range coefficient values */
+- if (nbits > MAX_COEF_BITS)
+- ERREXIT(cinfo, JERR_BAD_DCT_COEF);
+-
+- /* Count Huffman symbol for run length / number of bits */
+- ac_counts[(r << 4) + nbits]++;
+-
+- r = 0;
+- }
+- }
+-
+- /* If the last coef(s) were zero, emit an end-of-block code */
+- if (r > 0)
+- ac_counts[0]++;
+- }
+-
+-
+- /*
+- * Trial-encode one MCU's worth of Huffman-compressed coefficients.
+- * No data is actually output, so no suspension return is possible.
+- */
+-
+- METHODDEF(boolean)
+- encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+- {
+- huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+- int blkn, ci;
+- jpeg_component_info * compptr;
+-
+- /* Take care of restart intervals if needed */
+- if (cinfo->restart_interval) {
+- if (entropy->restarts_to_go == 0) {
+- /* Re-initialize DC predictions to 0 */
+- for (ci = 0; ci < cinfo->comps_in_scan; ci++)
+- entropy->saved.last_dc_val[ci] = 0;
+- /* Update restart state */
+- entropy->restarts_to_go = cinfo->restart_interval;
+- }
+- entropy->restarts_to_go--;
+- }
+-
+- for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+- ci = cinfo->MCU_membership[blkn];
+- compptr = cinfo->cur_comp_info[ci];
+- htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
+- entropy->dc_count_ptrs[compptr->dc_tbl_no],
+- entropy->ac_count_ptrs[compptr->ac_tbl_no]);
+- entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
+- }
+-
+- return TRUE;
+- }
+-
+-
+ /*
+ * Generate the best Huffman code table for the given counts, fill htbl.
+- * Note this is also used by jcphuff.c.
+ *
+ * The JPEG standard requires that no symbol be assigned a codeword of all
+ * one bits (so that padding bits added at the end of a compressed segment
+--- 109,116 ----
+***************
+*** 835,909 ****
+
+ /* Set sent_table FALSE so updated table will be written to JPEG file. */
+ htbl->sent_table = FALSE;
+- }
+-
+-
+- /*
+- * Finish up a statistics-gathering pass and create the new Huffman tables.
+- */
+-
+- METHODDEF(void)
+- finish_pass_gather (j_compress_ptr cinfo)
+- {
+- huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+- int ci, dctbl, actbl;
+- jpeg_component_info * compptr;
+- JHUFF_TBL **htblptr;
+- boolean did_dc[NUM_HUFF_TBLS];
+- boolean did_ac[NUM_HUFF_TBLS];
+-
+- /* It's important not to apply jpeg_gen_optimal_table more than once
+- * per table, because it clobbers the input frequency counts!
+- */
+- MEMZERO(did_dc, SIZEOF(did_dc));
+- MEMZERO(did_ac, SIZEOF(did_ac));
+-
+- for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+- compptr = cinfo->cur_comp_info[ci];
+- dctbl = compptr->dc_tbl_no;
+- actbl = compptr->ac_tbl_no;
+- if (! did_dc[dctbl]) {
+- htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
+- if (*htblptr == NULL)
+- *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+- jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
+- did_dc[dctbl] = TRUE;
+- }
+- if (! did_ac[actbl]) {
+- htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
+- if (*htblptr == NULL)
+- *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+- jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
+- did_ac[actbl] = TRUE;
+- }
+- }
+- }
+-
+-
+- #endif /* ENTROPY_OPT_SUPPORTED */
+-
+-
+- /*
+- * Module initialization routine for Huffman entropy encoding.
+- */
+-
+- GLOBAL(void)
+- jinit_huff_encoder (j_compress_ptr cinfo)
+- {
+- huff_entropy_ptr entropy;
+- int i;
+-
+- entropy = (huff_entropy_ptr)
+- (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+- SIZEOF(huff_entropy_encoder));
+- cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
+- entropy->pub.start_pass = start_pass_huff;
+-
+- /* Mark tables unallocated */
+- for (i = 0; i < NUM_HUFF_TBLS; i++) {
+- entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
+- #ifdef ENTROPY_OPT_SUPPORTED
+- entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
+- #endif
+- }
+ }
+--- 270,273 ----
+diff -cN ../jpeg-6b/jchuff.h ./jchuff.h
+*** ../jpeg-6b/jchuff.h Mon Oct 20 19:12:57 1997
+--- ./jchuff.h Tue Apr 27 14:58:17 1999
+***************
+*** 22,27 ****
+--- 22,34 ----
+ #define MAX_COEF_BITS 14
+ #endif
+
++ /* The legal range of a spatial difference is
++ * -32767 .. +32768.
++ * Hence the magnitude should always fit in 16 bits.
++ */
++
++ #define MAX_DIFF_BITS 16
++
+ /* Derived data constructed for each Huffman table */
+
+ typedef struct {
+diff -cN ../jpeg-6b/jcinit.c ./jcinit.c
+*** ../jpeg-6b/jcinit.c Sun Sep 7 16:50:40 1997
+--- ./jcinit.c Tue Apr 27 14:58:17 1999
+***************
+*** 32,37 ****
+--- 32,40 ----
+ /* Initialize master control (includes parameter checking/processing) */
+ jinit_c_master_control(cinfo, FALSE /* full compression */);
+
++ /* Initialize compression codec */
++ jinit_c_codec(cinfo);
++
+ /* Preprocessing */
+ if (! cinfo->raw_data_in) {
+ jinit_color_converter(cinfo);
+***************
+*** 38,62 ****
+ jinit_downsampler(cinfo);
+ jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
+ }
+- /* Forward DCT */
+- jinit_forward_dct(cinfo);
+- /* Entropy encoding: either Huffman or arithmetic coding. */
+- if (cinfo->arith_code) {
+- ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+- } else {
+- if (cinfo->progressive_mode) {
+- #ifdef C_PROGRESSIVE_SUPPORTED
+- jinit_phuff_encoder(cinfo);
+- #else
+- ERREXIT(cinfo, JERR_NOT_COMPILED);
+- #endif
+- } else
+- jinit_huff_encoder(cinfo);
+- }
+
+- /* Need a full-image coefficient buffer in any multi-pass mode. */
+- jinit_c_coef_controller(cinfo,
+- (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
+ jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
+
+ jinit_marker_writer(cinfo);
+--- 41,47 ----
+diff -cN ../jpeg-6b/jclhuff.c ./jclhuff.c
+*** ../jpeg-6b/jclhuff.c
+--- ./jclhuff.c Tue Apr 27 14:58:18 1999
+***************
+*** 0 ****
+--- 1,599 ----
++ /*
++ * jclhuff.c
++ *
++ * Copyright (C) 1991-1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains Huffman entropy encoding routines for lossless JPEG.
++ *
++ * Much of the complexity here has to do with supporting output suspension.
++ * If the data destination module demands suspension, we want to be able to
++ * back up to the start of the current MCU. To do this, we copy state
++ * variables into local working storage, and update them back to the
++ * permanent JPEG objects only upon successful completion of an MCU.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossls.h" /* Private declarations for lossless codec */
++ #include "jchuff.h" /* Declarations shared with jc*huff.c */
++
++
++ /* Expanded entropy encoder object for Huffman encoding.
++ *
++ * The savable_state subrecord contains fields that change within an MCU,
++ * but must not be updated permanently until we complete the MCU.
++ */
++
++ typedef struct {
++ INT32 put_buffer; /* current bit-accumulation buffer */
++ int put_bits; /* # of bits now in it */
++ } savable_state;
++
++ /* This macro is to work around compilers with missing or broken
++ * structure assignment. You'll need to fix this code if you have
++ * such a compiler and you change MAX_COMPS_IN_SCAN.
++ */
++
++ #ifndef NO_STRUCT_ASSIGN
++ #define ASSIGN_STATE(dest,src) ((dest) = (src))
++ #else
++ #define ASSIGN_STATE(dest,src) \
++ ((dest).put_buffer = (src).put_buffer, \
++ (dest).put_bits = (src).put_bits)
++ #endif
++
++
++ typedef struct {
++ int ci, yoffset, MCU_width;
++ } lhe_input_ptr_info;
++
++
++ typedef struct {
++ savable_state saved; /* Bit buffer at start of MCU */
++
++ /* These fields are NOT loaded into local working state. */
++ unsigned int restarts_to_go; /* MCUs left in this restart interval */
++ int next_restart_num; /* next restart number to write (0-7) */
++
++ /* Pointers to derived tables (these workspaces have image lifespan) */
++ c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
++
++ /* Pointers to derived tables to be used for each data unit within an MCU */
++ c_derived_tbl * cur_tbls[C_MAX_DATA_UNITS_IN_MCU];
++
++ #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
++ long * count_ptrs[NUM_HUFF_TBLS];
++
++ /* Pointers to stats tables to be used for each data unit within an MCU */
++ long * cur_counts[C_MAX_DATA_UNITS_IN_MCU];
++ #endif
++
++ /* Pointers to the proper input difference row for each group of data units
++ * within an MCU. For each component, there are Vi groups of Hi data units.
++ */
++ JDIFFROW input_ptr[C_MAX_DATA_UNITS_IN_MCU];
++
++ /* Number of input pointers in use for the current MCU. This is the sum
++ * of all Vi in the MCU.
++ */
++ int num_input_ptrs;
++
++ /* Information used for positioning the input pointers within the input
++ * difference rows.
++ */
++ lhe_input_ptr_info input_ptr_info[C_MAX_DATA_UNITS_IN_MCU];
++
++ /* Index of the proper input pointer for each data unit within an MCU */
++ int input_ptr_index[C_MAX_DATA_UNITS_IN_MCU];
++
++ } lhuff_entropy_encoder;
++
++ typedef lhuff_entropy_encoder * lhuff_entropy_ptr;
++
++ /* Working state while writing an MCU.
++ * This struct contains all the fields that are needed by subroutines.
++ */
++
++ typedef struct {
++ JOCTET * next_output_byte; /* => next byte to write in buffer */
++ size_t free_in_buffer; /* # of byte spaces remaining in buffer */
++ savable_state cur; /* Current bit buffer & DC state */
++ j_compress_ptr cinfo; /* dump_buffer needs access to this */
++ } working_state;
++
++
++ /* Forward declarations */
++ METHODDEF(JDIMENSION) encode_mcus_huff (j_compress_ptr cinfo,
++ JDIFFIMAGE diff_buf,
++ JDIMENSION MCU_row_num,
++ JDIMENSION MCU_col_num,
++ JDIMENSION nMCU);
++ METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
++ #ifdef ENTROPY_OPT_SUPPORTED
++ METHODDEF(JDIMENSION) encode_mcus_gather (j_compress_ptr cinfo,
++ JDIFFIMAGE diff_buf,
++ JDIMENSION MCU_row_num,
++ JDIMENSION MCU_col_num,
++ JDIMENSION nMCU);
++ METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
++ #endif
++
++
++ /*
++ * Initialize for a Huffman-compressed scan.
++ * If gather_statistics is TRUE, we do not output anything during the scan,
++ * just count the Huffman symbols used and generate Huffman code tables.
++ */
++
++ METHODDEF(void)
++ start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private;
++ int ci, dctbl, sampn, ptrn, yoffset, xoffset;
++ jpeg_component_info * compptr;
++
++ if (gather_statistics) {
++ #ifdef ENTROPY_OPT_SUPPORTED
++ losslsc->entropy_encode_mcus = encode_mcus_gather;
++ losslsc->pub.entropy_finish_pass = finish_pass_gather;
++ #else
++ ERREXIT(cinfo, JERR_NOT_COMPILED);
++ #endif
++ } else {
++ losslsc->entropy_encode_mcus = encode_mcus_huff;
++ losslsc->pub.entropy_finish_pass = finish_pass_huff;
++ }
++
++ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
++ compptr = cinfo->cur_comp_info[ci];
++ dctbl = compptr->dc_tbl_no;
++ if (gather_statistics) {
++ #ifdef ENTROPY_OPT_SUPPORTED
++ /* Check for invalid table indexes */
++ /* (make_c_derived_tbl does this in the other path) */
++ if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
++ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
++ /* Allocate and zero the statistics tables */
++ /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
++ if (entropy->count_ptrs[dctbl] == NULL)
++ entropy->count_ptrs[dctbl] = (long *)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ 257 * SIZEOF(long));
++ MEMZERO(entropy->count_ptrs[dctbl], 257 * SIZEOF(long));
++ #endif
++ } else {
++ /* Compute derived values for Huffman tables */
++ /* We may do this more than once for a table, but it's not expensive */
++ jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
++ & entropy->derived_tbls[dctbl]);
++ }
++ }
++
++ /* Precalculate encoding info for each sample in an MCU of this scan */
++ for (sampn = 0, ptrn = 0; sampn < cinfo->data_units_in_MCU;) {
++ compptr = cinfo->cur_comp_info[cinfo->MCU_membership[sampn]];
++ ci = compptr->component_index;
++ /* ci = cinfo->MCU_membership[sampn];
++ compptr = cinfo->cur_comp_info[ci];*/
++ for (yoffset = 0; yoffset < compptr->MCU_height; yoffset++, ptrn++) {
++ /* Precalculate the setup info for each input pointer */
++ entropy->input_ptr_info[ptrn].ci = ci;
++ entropy->input_ptr_info[ptrn].yoffset = yoffset;
++ entropy->input_ptr_info[ptrn].MCU_width = compptr->MCU_width;
++ for (xoffset = 0; xoffset < compptr->MCU_width; xoffset++, sampn++) {
++ /* Precalculate the input pointer index for each sample */
++ entropy->input_ptr_index[sampn] = ptrn;
++ /* Precalculate which tables to use for each sample */
++ entropy->cur_tbls[sampn] = entropy->derived_tbls[compptr->dc_tbl_no];
++ entropy->cur_counts[sampn] = entropy->count_ptrs[compptr->dc_tbl_no];
++ }
++ }
++ }
++ entropy->num_input_ptrs = ptrn;
++
++ /* Initialize bit buffer to empty */
++ entropy->saved.put_buffer = 0;
++ entropy->saved.put_bits = 0;
++
++ /* Initialize restart stuff */
++ entropy->restarts_to_go = cinfo->restart_interval;
++ entropy->next_restart_num = 0;
++ }
++
++
++ /* Outputting bytes to the file */
++
++ /* Emit a byte, taking 'action' if must suspend. */
++ #define emit_byte(state,val,action) \
++ { *(state)->next_output_byte++ = (JOCTET) (val); \
++ if (--(state)->free_in_buffer == 0) \
++ if (! dump_buffer(state)) \
++ { action; } }
++
++
++ LOCAL(boolean)
++ dump_buffer (working_state * state)
++ /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
++ {
++ struct jpeg_destination_mgr * dest = state->cinfo->dest;
++
++ if (! (*dest->empty_output_buffer) (state->cinfo))
++ return FALSE;
++ /* After a successful buffer dump, must reset buffer pointers */
++ state->next_output_byte = dest->next_output_byte;
++ state->free_in_buffer = dest->free_in_buffer;
++ return TRUE;
++ }
++
++
++ /* Outputting bits to the file */
++
++ /* Only the right 24 bits of put_buffer are used; the valid bits are
++ * left-justified in this part. At most 16 bits can be passed to emit_bits
++ * in one call, and we never retain more than 7 bits in put_buffer
++ * between calls, so 24 bits are sufficient.
++ */
++
++ INLINE
++ LOCAL(boolean)
++ emit_bits (working_state * state, unsigned int code, int size)
++ /* Emit some bits; return TRUE if successful, FALSE if must suspend */
++ {
++ /* This routine is heavily used, so it's worth coding tightly. */
++ register INT32 put_buffer = (INT32) code;
++ register int put_bits = state->cur.put_bits;
++
++ /* if size is 0, caller used an invalid Huffman table entry */
++ if (size == 0)
++ ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
++
++ put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
++
++ put_bits += size; /* new number of bits in buffer */
++
++ put_buffer <<= 24 - put_bits; /* align incoming bits */
++
++ put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
++
++ while (put_bits >= 8) {
++ int c = (int) ((put_buffer >> 16) & 0xFF);
++
++ emit_byte(state, c, return FALSE);
++ if (c == 0xFF) { /* need to stuff a zero byte? */
++ emit_byte(state, 0, return FALSE);
++ }
++ put_buffer <<= 8;
++ put_bits -= 8;
++ }
++
++ state->cur.put_buffer = put_buffer; /* update state variables */
++ state->cur.put_bits = put_bits;
++
++ return TRUE;
++ }
++
++
++ LOCAL(boolean)
++ flush_bits (working_state * state)
++ {
++ if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
++ return FALSE;
++ state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
++ state->cur.put_bits = 0;
++ return TRUE;
++ }
++
++
++ /*
++ * Emit a restart marker & resynchronize predictions.
++ */
++
++ LOCAL(boolean)
++ emit_restart (working_state * state, int restart_num)
++ {
++ int ci;
++
++ if (! flush_bits(state))
++ return FALSE;
++
++ emit_byte(state, 0xFF, return FALSE);
++ emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
++
++ /* The restart counter is not updated until we successfully write the MCU. */
++
++ return TRUE;
++ }
++
++
++ /*
++ * Encode and output one nMCU's worth of Huffman-compressed differences.
++ */
++
++ METHODDEF(JDIMENSION)
++ encode_mcus_huff (j_compress_ptr cinfo, JDIFFIMAGE diff_buf,
++ JDIMENSION MCU_row_num, JDIMENSION MCU_col_num,
++ JDIMENSION nMCU)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private;
++ working_state state;
++ int mcu_num, sampn, ci, yoffset, MCU_width, ptrn;
++ jpeg_component_info * compptr;
++
++ /* Load up working state */
++ state.next_output_byte = cinfo->dest->next_output_byte;
++ state.free_in_buffer = cinfo->dest->free_in_buffer;
++ ASSIGN_STATE(state.cur, entropy->saved);
++ state.cinfo = cinfo;
++
++ /* Emit restart marker if needed */
++ if (cinfo->restart_interval) {
++ if (entropy->restarts_to_go == 0)
++ if (! emit_restart(&state, entropy->next_restart_num))
++ return 0;
++ }
++
++ /* Set input pointer locations based on MCU_col_num */
++ for (ptrn = 0; ptrn < entropy->num_input_ptrs; ptrn++) {
++ ci = entropy->input_ptr_info[ptrn].ci;
++ yoffset = entropy->input_ptr_info[ptrn].yoffset;
++ MCU_width = entropy->input_ptr_info[ptrn].MCU_width;
++ entropy->input_ptr[ptrn] =
++ diff_buf[ci][MCU_row_num + yoffset] + (MCU_col_num * MCU_width);
++ }
++
++ for (mcu_num = 0; mcu_num < nMCU; mcu_num++) {
++
++ /* Inner loop handles the samples in the MCU */
++ for (sampn = 0; sampn < cinfo->data_units_in_MCU; sampn++) {
++ register int temp, temp2, temp3;
++ register int nbits;
++ c_derived_tbl *dctbl = entropy->cur_tbls[sampn];
++
++ /* Encode the difference per section H.1.2.2 */
++
++ /* Input the sample difference */
++ temp = *entropy->input_ptr[entropy->input_ptr_index[sampn]]++;
++
++ if (temp & 0x8000) { /* instead of temp < 0 */
++ temp = (-temp) & 0x7FFF; /* absolute value, mod 2^16 */
++ if (temp == 0) /* special case: magnitude = 32768 */
++ temp2 = temp = 0x8000;
++ temp2 = ~ temp; /* one's complement of magnitude */
++ } else {
++ temp &= 0x7FFF; /* abs value mod 2^16 */
++ temp2 = temp; /* magnitude */
++ }
++
++ /* Find the number of bits needed for the magnitude of the difference */
++ nbits = 0;
++ while (temp) {
++ nbits++;
++ temp >>= 1;
++ }
++ /* Check for out-of-range difference values.
++ */
++ if (nbits > MAX_DIFF_BITS)
++ ERREXIT(cinfo, JERR_BAD_DIFF);
++
++ /* Emit the Huffman-coded symbol for the number of bits */
++ if (! emit_bits(&state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
++ return mcu_num;
++
++ /* Emit that number of bits of the value, if positive, */
++ /* or the complement of its magnitude, if negative. */
++ if (nbits && /* emit_bits rejects calls with size 0 */
++ nbits != 16) /* special case: no bits should be emitted */
++ if (! emit_bits(&state, (unsigned int) temp2, nbits))
++ return mcu_num;
++ }
++
++ /* Completed MCU, so update state */
++ cinfo->dest->next_output_byte = state.next_output_byte;
++ cinfo->dest->free_in_buffer = state.free_in_buffer;
++ ASSIGN_STATE(entropy->saved, state.cur);
++
++ /* Update restart-interval state too */
++ if (cinfo->restart_interval) {
++ if (entropy->restarts_to_go == 0) {
++ entropy->restarts_to_go = cinfo->restart_interval;
++ entropy->next_restart_num++;
++ entropy->next_restart_num &= 7;
++ }
++ entropy->restarts_to_go--;
++ }
++
++ }
++
++ return nMCU;
++ }
++
++
++ /*
++ * Finish up at the end of a Huffman-compressed scan.
++ */
++
++ METHODDEF(void)
++ finish_pass_huff (j_compress_ptr cinfo)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private;
++ working_state state;
++
++ /* Load up working state ... flush_bits needs it */
++ state.next_output_byte = cinfo->dest->next_output_byte;
++ state.free_in_buffer = cinfo->dest->free_in_buffer;
++ ASSIGN_STATE(state.cur, entropy->saved);
++ state.cinfo = cinfo;
++
++ /* Flush out the last data */
++ if (! flush_bits(&state))
++ ERREXIT(cinfo, JERR_CANT_SUSPEND);
++
++ /* Update state */
++ cinfo->dest->next_output_byte = state.next_output_byte;
++ cinfo->dest->free_in_buffer = state.free_in_buffer;
++ ASSIGN_STATE(entropy->saved, state.cur);
++ }
++
++
++ /*
++ * Huffman coding optimization.
++ *
++ * We first scan the supplied data and count the number of uses of each symbol
++ * that is to be Huffman-coded. (This process MUST agree with the code above.)
++ * Then we build a Huffman coding tree for the observed counts.
++ * Symbols which are not needed at all for the particular image are not
++ * assigned any code, which saves space in the DHT marker as well as in
++ * the compressed data.
++ */
++
++ #ifdef ENTROPY_OPT_SUPPORTED
++
++ /*
++ * Trial-encode one nMCU's worth of Huffman-compressed differences.
++ * No data is actually output, so no suspension return is possible.
++ */
++
++ METHODDEF(JDIMENSION)
++ encode_mcus_gather (j_compress_ptr cinfo, JDIFFIMAGE diff_buf,
++ JDIMENSION MCU_row_num, JDIMENSION MCU_col_num,
++ JDIMENSION nMCU)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private;
++ int mcu_num, sampn, ci, yoffset, MCU_width, ptrn;
++ jpeg_component_info * compptr;
++
++ /* Take care of restart intervals if needed */
++ if (cinfo->restart_interval) {
++ if (entropy->restarts_to_go == 0) {
++ /* Update restart state */
++ entropy->restarts_to_go = cinfo->restart_interval;
++ }
++ entropy->restarts_to_go--;
++ }
++
++ /* Set input pointer locations based on MCU_col_num */
++ for (ptrn = 0; ptrn < entropy->num_input_ptrs; ptrn++) {
++ ci = entropy->input_ptr_info[ptrn].ci;
++ yoffset = entropy->input_ptr_info[ptrn].yoffset;
++ MCU_width = entropy->input_ptr_info[ptrn].MCU_width;
++ entropy->input_ptr[ptrn] =
++ diff_buf[ci][MCU_row_num + yoffset] + (MCU_col_num * MCU_width);
++ }
++
++ for (mcu_num = 0; mcu_num < nMCU; mcu_num++) {
++
++ /* Inner loop handles the samples in the MCU */
++ for (sampn = 0; sampn < cinfo->data_units_in_MCU; sampn++) {
++ register int temp;
++ register int nbits;
++ c_derived_tbl *dctbl = entropy->cur_tbls[sampn];
++ long * counts = entropy->cur_counts[sampn];
++
++ /* Encode the difference per section H.1.2.2 */
++
++ /* Input the sample difference */
++ temp = *entropy->input_ptr[entropy->input_ptr_index[sampn]]++;
++
++ if (temp & 0x8000) { /* instead of temp < 0 */
++ temp = (-temp) & 0x7FFF; /* absolute value, mod 2^16 */
++ if (temp == 0) /* special case: magnitude = 32768 */
++ temp = 0x8000;
++ } else
++ temp &= 0x7FFF; /* abs value mod 2^16 */
++
++ /* Find the number of bits needed for the magnitude of the difference */
++ nbits = 0;
++ while (temp) {
++ nbits++;
++ temp >>= 1;
++ }
++ /* Check for out-of-range difference values.
++ */
++ if (nbits > MAX_DIFF_BITS)
++ ERREXIT(cinfo, JERR_BAD_DIFF);
++
++ /* Count the Huffman symbol for the number of bits */
++ counts[nbits]++;
++ }
++ }
++
++ return nMCU;
++ }
++
++
++ /*
++ * Finish up a statistics-gathering pass and create the new Huffman tables.
++ */
++
++ METHODDEF(void)
++ finish_pass_gather (j_compress_ptr cinfo)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private;
++ int ci, dctbl;
++ jpeg_component_info * compptr;
++ JHUFF_TBL **htblptr;
++ boolean did_dc[NUM_HUFF_TBLS];
++
++ /* It's important not to apply jpeg_gen_optimal_table more than once
++ * per table, because it clobbers the input frequency counts!
++ */
++ MEMZERO(did_dc, SIZEOF(did_dc));
++
++ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
++ compptr = cinfo->cur_comp_info[ci];
++ dctbl = compptr->dc_tbl_no;
++ if (! did_dc[dctbl]) {
++ htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
++ if (*htblptr == NULL)
++ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
++ jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[dctbl]);
++ did_dc[dctbl] = TRUE;
++ }
++ }
++ }
++
++
++ #endif /* ENTROPY_OPT_SUPPORTED */
++
++
++ METHODDEF(boolean)
++ need_optimization_pass (j_compress_ptr cinfo)
++ {
++ return TRUE;
++ }
++
++
++ /*
++ * Module initialization routine for Huffman entropy encoding.
++ */
++
++ GLOBAL(void)
++ jinit_lhuff_encoder (j_compress_ptr cinfo)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ lhuff_entropy_ptr entropy;
++ int i;
++
++ entropy = (lhuff_entropy_ptr)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ SIZEOF(lhuff_entropy_encoder));
++ losslsc->entropy_private = (struct jpeg_entropy_encoder *) entropy;
++ losslsc->pub.entropy_start_pass = start_pass_huff;
++ losslsc->pub.need_optimization_pass = need_optimization_pass;
++
++ /* Mark tables unallocated */
++ for (i = 0; i < NUM_HUFF_TBLS; i++) {
++ entropy->derived_tbls[i] = NULL;
++ #ifdef ENTROPY_OPT_SUPPORTED
++ entropy->count_ptrs[i] = NULL;
++ #endif
++ }
++ }
+diff -cN ../jpeg-6b/jclossls.c ./jclossls.c
+*** ../jpeg-6b/jclossls.c
+--- ./jclossls.c Tue Apr 27 14:58:18 1999
+***************
+*** 0 ****
+--- 1,78 ----
++ /*
++ * jclossls.c
++ *
++ * Copyright (C) 1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains the control logic for the lossless JPEG compressor.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossls.h"
++
++
++ #ifdef C_LOSSLESS_SUPPORTED
++
++ /*
++ * Initialize for a processing pass.
++ */
++
++ METHODDEF(void)
++ start_pass (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++
++ (*losslsc->scaler_start_pass) (cinfo);
++ (*losslsc->predict_start_pass) (cinfo);
++ (*losslsc->diff_start_pass) (cinfo, pass_mode);
++ }
++
++
++ /*
++ * Initialize the lossless compression codec.
++ * This is called only once, during master selection.
++ */
++
++ GLOBAL(void)
++ jinit_lossless_c_codec(j_compress_ptr cinfo)
++ {
++ j_lossless_c_ptr losslsc;
++
++ /* Create subobject in permanent pool */
++ losslsc = (j_lossless_c_ptr)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
++ SIZEOF(jpeg_lossless_c_codec));
++ cinfo->codec = (struct jpeg_c_codec *) losslsc;
++
++ /* Initialize sub-modules */
++
++ /* Scaler */
++ jinit_c_scaler(cinfo);
++
++ /* Differencer */
++ jinit_differencer(cinfo);
++
++ /* Entropy encoding: either Huffman or arithmetic coding. */
++ if (cinfo->arith_code) {
++ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
++ } else {
++ jinit_lhuff_encoder(cinfo);
++ }
++
++ /* Need a full-image difference buffer in any multi-pass mode. */
++ jinit_c_diff_controller(cinfo,
++ (boolean) (cinfo->num_scans > 1 ||
++ cinfo->optimize_coding));
++
++ /* Initialize method pointers.
++ *
++ * Note: entropy_start_pass and entropy_finish_pass are assigned in
++ * jclhuff.c and compress_data is assigned in jcdiffct.c.
++ */
++ losslsc->pub.start_pass = start_pass;
++ }
++
++ #endif /* C_LOSSLESS_SUPPORTED */
+diff -cN ../jpeg-6b/jclossy.c ./jclossy.c
+*** ../jpeg-6b/jclossy.c
+--- ./jclossy.c Tue Apr 27 14:58:18 1999
+***************
+*** 0 ****
+--- 1,76 ----
++ /*
++ * jclossy.c
++ *
++ * Copyright (C) 1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains the control logic for the lossy JPEG compressor.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossy.h"
++
++
++ /*
++ * Initialize for a processing pass.
++ */
++
++ METHODDEF(void)
++ start_pass (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
++ {
++ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
++
++ (*lossyc->fdct_start_pass) (cinfo);
++ (*lossyc->coef_start_pass) (cinfo, pass_mode);
++ }
++
++
++ /*
++ * Initialize the lossy compression codec.
++ * This is called only once, during master selection.
++ */
++
++ GLOBAL(void)
++ jinit_lossy_c_codec (j_compress_ptr cinfo)
++ {
++ j_lossy_c_ptr lossyc;
++
++ /* Create subobject in permanent pool */
++ lossyc = (j_lossy_c_ptr)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
++ SIZEOF(jpeg_lossy_c_codec));
++ cinfo->codec = (struct jpeg_c_codec *) lossyc;
++
++ /* Initialize sub-modules */
++
++ /* Forward DCT */
++ jinit_forward_dct(cinfo);
++ /* Entropy encoding: either Huffman or arithmetic coding. */
++ if (cinfo->arith_code) {
++ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
++ } else {
++ if (cinfo->process == JPROC_PROGRESSIVE) {
++ #ifdef C_PROGRESSIVE_SUPPORTED
++ jinit_phuff_encoder(cinfo);
++ #else
++ ERREXIT(cinfo, JERR_NOT_COMPILED);
++ #endif
++ } else
++ jinit_shuff_encoder(cinfo);
++ }
++
++ /* Need a full-image coefficient buffer in any multi-pass mode. */
++ jinit_c_coef_controller(cinfo,
++ (boolean) (cinfo->num_scans > 1 ||
++ cinfo->optimize_coding));
++
++ /* Initialize method pointers.
++ *
++ * Note: entropy_start_pass and entropy_finish_pass are assigned in
++ * jcshuff.c or jcphuff.c and compress_data is assigned in jccoefct.c.
++ */
++ lossyc->pub.start_pass = start_pass;
++ }
+diff -cN ../jpeg-6b/jcmainct.c ./jcmainct.c
+*** ../jpeg-6b/jcmainct.c Sat Jan 6 18:24:59 1996
+--- ./jcmainct.c Tue Apr 27 14:58:18 1999
+***************
+*** 1,7 ****
+ /*
+ * jcmainct.c
+ *
+! * Copyright (C) 1994-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jcmainct.c
+ *
+! * Copyright (C) 1994-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 115,138 ****
+ JDIMENSION in_rows_avail)
+ {
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+
+ while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
+ /* Read input data if we haven't filled the main buffer yet */
+! if (main->rowgroup_ctr < DCTSIZE)
+ (*cinfo->prep->pre_process_data) (cinfo,
+ input_buf, in_row_ctr, in_rows_avail,
+ main->buffer, &main->rowgroup_ctr,
+! (JDIMENSION) DCTSIZE);
+
+ /* If we don't have a full iMCU row buffered, return to application for
+ * more data. Note that preprocessor will always pad to fill the iMCU row
+ * at the bottom of the image.
+ */
+! if (main->rowgroup_ctr != DCTSIZE)
+ return;
+
+ /* Send the completed row to the compressor */
+! if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
+ /* If compressor did not consume the whole row, then we must need to
+ * suspend processing and return to the application. In this situation
+ * we pretend we didn't yet consume the last input row; otherwise, if
+--- 115,139 ----
+ JDIMENSION in_rows_avail)
+ {
+ my_main_ptr main = (my_main_ptr) cinfo->main;
++ int data_unit = cinfo->data_unit;
+
+ while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
+ /* Read input data if we haven't filled the main buffer yet */
+! if (main->rowgroup_ctr < data_unit)
+ (*cinfo->prep->pre_process_data) (cinfo,
+ input_buf, in_row_ctr, in_rows_avail,
+ main->buffer, &main->rowgroup_ctr,
+! (JDIMENSION) data_unit);
+
+ /* If we don't have a full iMCU row buffered, return to application for
+ * more data. Note that preprocessor will always pad to fill the iMCU row
+ * at the bottom of the image.
+ */
+! if (main->rowgroup_ctr != data_unit)
+ return;
+
+ /* Send the completed row to the compressor */
+! if (! (*cinfo->codec->compress_data) (cinfo, main->buffer)) {
+ /* If compressor did not consume the whole row, then we must need to
+ * suspend processing and return to the application. In this situation
+ * we pretend we didn't yet consume the last input row; otherwise, if
+***************
+*** 174,179 ****
+--- 175,181 ----
+ int ci;
+ jpeg_component_info *compptr;
+ boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
++ int data_unit = cinfo->data_unit;
+
+ while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
+ /* Realign the virtual buffers if at the start of an iMCU row. */
+***************
+*** 182,194 ****
+ ci++, compptr++) {
+ main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, main->whole_image[ci],
+! main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
+! (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
+ }
+ /* In a read pass, pretend we just read some source data. */
+ if (! writing) {
+! *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
+! main->rowgroup_ctr = DCTSIZE;
+ }
+ }
+
+--- 184,196 ----
+ ci++, compptr++) {
+ main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, main->whole_image[ci],
+! main->cur_iMCU_row * (compptr->v_samp_factor * data_unit),
+! (JDIMENSION) (compptr->v_samp_factor * data_unit), writing);
+ }
+ /* In a read pass, pretend we just read some source data. */
+ if (! writing) {
+! *in_row_ctr += cinfo->max_v_samp_factor * data_unit;
+! main->rowgroup_ctr = data_unit;
+ }
+ }
+
+***************
+*** 198,212 ****
+ (*cinfo->prep->pre_process_data) (cinfo,
+ input_buf, in_row_ctr, in_rows_avail,
+ main->buffer, &main->rowgroup_ctr,
+! (JDIMENSION) DCTSIZE);
+ /* Return to application if we need more data to fill the iMCU row. */
+! if (main->rowgroup_ctr < DCTSIZE)
+ return;
+ }
+
+ /* Emit data, unless this is a sink-only pass. */
+ if (main->pass_mode != JBUF_SAVE_SOURCE) {
+! if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
+ /* If compressor did not consume the whole row, then we must need to
+ * suspend processing and return to the application. In this situation
+ * we pretend we didn't yet consume the last input row; otherwise, if
+--- 200,214 ----
+ (*cinfo->prep->pre_process_data) (cinfo,
+ input_buf, in_row_ctr, in_rows_avail,
+ main->buffer, &main->rowgroup_ctr,
+! (JDIMENSION) data_unit);
+ /* Return to application if we need more data to fill the iMCU row. */
+! if (main->rowgroup_ctr < data_unit)
+ return;
+ }
+
+ /* Emit data, unless this is a sink-only pass. */
+ if (main->pass_mode != JBUF_SAVE_SOURCE) {
+! if (! (*cinfo->codec->compress_data) (cinfo, main->buffer)) {
+ /* If compressor did not consume the whole row, then we must need to
+ * suspend processing and return to the application. In this situation
+ * we pretend we didn't yet consume the last input row; otherwise, if
+***************
+*** 247,252 ****
+--- 249,255 ----
+ my_main_ptr main;
+ int ci;
+ jpeg_component_info *compptr;
++ int data_unit = cinfo->data_unit;
+
+ main = (my_main_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+***************
+*** 269,278 ****
+ ci++, compptr++) {
+ main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+! compptr->width_in_blocks * DCTSIZE,
+! (JDIMENSION) jround_up((long) compptr->height_in_blocks,
+! (long) compptr->v_samp_factor) * DCTSIZE,
+! (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
+ }
+ #else
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+--- 272,281 ----
+ ci++, compptr++) {
+ main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+! compptr->width_in_data_units * data_unit,
+! (JDIMENSION) jround_up((long) compptr->height_in_data_units,
+! (long) compptr->v_samp_factor) * data_unit,
+! (JDIMENSION) (compptr->v_samp_factor * data_unit));
+ }
+ #else
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+***************
+*** 286,293 ****
+ ci++, compptr++) {
+ main->buffer[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! compptr->width_in_blocks * DCTSIZE,
+! (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
+ }
+ }
+ }
+--- 289,296 ----
+ ci++, compptr++) {
+ main->buffer[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! compptr->width_in_data_units * data_unit,
+! (JDIMENSION) (compptr->v_samp_factor * data_unit));
+ }
+ }
+ }
+diff -cN ../jpeg-6b/jcmarker.c ./jcmarker.c
+*** ../jpeg-6b/jcmarker.c Sat Feb 21 16:54:00 1998
+--- ./jcmarker.c Tue Apr 27 14:58:19 1999
+***************
+*** 322,328 ****
+ emit_byte(cinfo, compptr->component_id);
+ td = compptr->dc_tbl_no;
+ ta = compptr->ac_tbl_no;
+! if (cinfo->progressive_mode) {
+ /* Progressive mode: only DC or only AC tables are used in one scan;
+ * furthermore, Huffman coding of DC refinement uses no table at all.
+ * We emit 0 for unused field(s); this is recommended by the P&M text
+--- 322,328 ----
+ emit_byte(cinfo, compptr->component_id);
+ td = compptr->dc_tbl_no;
+ ta = compptr->ac_tbl_no;
+! if (cinfo->process == JPROC_PROGRESSIVE) {
+ /* Progressive mode: only DC or only AC tables are used in one scan;
+ * furthermore, Huffman coding of DC refinement uses no table at all.
+ * We emit 0 for unused field(s); this is recommended by the P&M text
+***************
+*** 496,516 ****
+ int ci, prec;
+ boolean is_baseline;
+ jpeg_component_info *compptr;
+!
+! /* Emit DQT for each quantization table.
+! * Note that emit_dqt() suppresses any duplicate tables.
+! */
+! prec = 0;
+! for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+! ci++, compptr++) {
+! prec += emit_dqt(cinfo, compptr->quant_tbl_no);
+ }
+- /* now prec is nonzero iff there are any 16-bit quant tables. */
+
+ /* Check for a non-baseline specification.
+ * Note we assume that Huffman table numbers won't be changed later.
+ */
+! if (cinfo->arith_code || cinfo->progressive_mode ||
+ cinfo->data_precision != 8) {
+ is_baseline = FALSE;
+ } else {
+--- 496,518 ----
+ int ci, prec;
+ boolean is_baseline;
+ jpeg_component_info *compptr;
+!
+! if (cinfo->process != JPROC_LOSSLESS) {
+! /* Emit DQT for each quantization table.
+! * Note that emit_dqt() suppresses any duplicate tables.
+! */
+! prec = 0;
+! for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+! ci++, compptr++) {
+! prec += emit_dqt(cinfo, compptr->quant_tbl_no);
+! }
+! /* now prec is nonzero iff there are any 16-bit quant tables. */
+ }
+
+ /* Check for a non-baseline specification.
+ * Note we assume that Huffman table numbers won't be changed later.
+ */
+! if (cinfo->arith_code || cinfo->process != JPROC_SEQUENTIAL ||
+ cinfo->data_precision != 8) {
+ is_baseline = FALSE;
+ } else {
+***************
+*** 531,538 ****
+ if (cinfo->arith_code) {
+ emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
+ } else {
+! if (cinfo->progressive_mode)
+ emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
+ else if (is_baseline)
+ emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
+ else
+--- 533,542 ----
+ if (cinfo->arith_code) {
+ emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
+ } else {
+! if (cinfo->process == JPROC_PROGRESSIVE)
+ emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
++ else if (cinfo->process == JPROC_LOSSLESS)
++ emit_sof(cinfo, M_SOF3); /* SOF code for lossless Huffman */
+ else if (is_baseline)
+ emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
+ else
+***************
+*** 566,572 ****
+ */
+ for (i = 0; i < cinfo->comps_in_scan; i++) {
+ compptr = cinfo->cur_comp_info[i];
+! if (cinfo->progressive_mode) {
+ /* Progressive mode: only DC or only AC tables are used in one scan */
+ if (cinfo->Ss == 0) {
+ if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
+--- 570,576 ----
+ */
+ for (i = 0; i < cinfo->comps_in_scan; i++) {
+ compptr = cinfo->cur_comp_info[i];
+! if (cinfo->process == JPROC_PROGRESSIVE) {
+ /* Progressive mode: only DC or only AC tables are used in one scan */
+ if (cinfo->Ss == 0) {
+ if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
+***************
+*** 574,579 ****
+--- 578,586 ----
+ } else {
+ emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
+ }
++ } else if (cinfo->process == JPROC_LOSSLESS) {
++ /* Lossless mode: only DC tables are used */
++ emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
+ } else {
+ /* Sequential mode: need both DC and AC tables */
+ emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
+diff -cN ../jpeg-6b/jcmaster.c ./jcmaster.c
+*** ../jpeg-6b/jcmaster.c Sun Aug 10 19:40:57 1997
+--- ./jcmaster.c Tue Apr 27 14:58:19 1999
+***************
+*** 1,7 ****
+ /*
+ * jcmaster.c
+ *
+! * Copyright (C) 1991-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jcmaster.c
+ *
+! * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 14,19 ****
+--- 14,20 ----
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
++ #include "jlossy.h" /* Private declarations for lossy codec */
+
+
+ /* Private state */
+***************
+*** 50,55 ****
+--- 51,57 ----
+ jpeg_component_info *compptr;
+ long samplesperrow;
+ JDIMENSION jd_samplesperrow;
++ int data_unit = cinfo->data_unit;
+
+ /* Sanity check on image dimensions */
+ if (cinfo->image_height <= 0 || cinfo->image_width <= 0
+***************
+*** 95,109 ****
+ ci++, compptr++) {
+ /* Fill in the correct component_index value; don't rely on application */
+ compptr->component_index = ci;
+! /* For compression, we never do DCT scaling. */
+! compptr->DCT_scaled_size = DCTSIZE;
+! /* Size in DCT blocks */
+! compptr->width_in_blocks = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+! (long) (cinfo->max_h_samp_factor * DCTSIZE));
+! compptr->height_in_blocks = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+! (long) (cinfo->max_v_samp_factor * DCTSIZE));
+ /* Size in samples */
+ compptr->downsampled_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+--- 97,111 ----
+ ci++, compptr++) {
+ /* Fill in the correct component_index value; don't rely on application */
+ compptr->component_index = ci;
+! /* For compression, we never do any codec-based processing. */
+! compptr->codec_data_unit = data_unit;
+! /* Size in data units */
+! compptr->width_in_data_units = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+! (long) (cinfo->max_h_samp_factor * data_unit));
+! compptr->height_in_data_units = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+! (long) (cinfo->max_v_samp_factor * data_unit));
+ /* Size in samples */
+ compptr->downsampled_width = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+***************
+*** 120,135 ****
+ */
+ cinfo->total_iMCU_rows = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+! (long) (cinfo->max_v_samp_factor*DCTSIZE));
+ }
+
+-
+ #ifdef C_MULTISCAN_FILES_SUPPORTED
+
+ LOCAL(void)
+ validate_script (j_compress_ptr cinfo)
+ /* Verify that the scan script in cinfo->scan_info[] is valid; also
+! * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
+ */
+ {
+ const jpeg_scan_info * scanptr;
+--- 122,144 ----
+ */
+ cinfo->total_iMCU_rows = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+! (long) (cinfo->max_v_samp_factor*data_unit));
+ }
+
+ #ifdef C_MULTISCAN_FILES_SUPPORTED
++ #define NEED_SCAN_SCRIPT
++ #else
++ #ifdef C_LOSSLESS_SUPPORTED
++ #define NEED_SCAN_SCRIPT
++ #endif
++ #endif
++
++ #ifdef NEED_SCAN_SCRIPT
+
+ LOCAL(void)
+ validate_script (j_compress_ptr cinfo)
+ /* Verify that the scan script in cinfo->scan_info[] is valid; also
+! * determine whether it uses progressive JPEG, and set cinfo->process.
+ */
+ {
+ const jpeg_scan_info * scanptr;
+***************
+*** 145,157 ****
+ if (cinfo->num_scans <= 0)
+ ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
+
+ /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
+ * for progressive JPEG, no scan can have this.
+ */
+! scanptr = cinfo->scan_info;
+! if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
+ #ifdef C_PROGRESSIVE_SUPPORTED
+! cinfo->progressive_mode = TRUE;
+ last_bitpos_ptr = & last_bitpos[0][0];
+ for (ci = 0; ci < cinfo->num_components; ci++)
+ for (coefi = 0; coefi < DCTSIZE2; coefi++)
+--- 154,180 ----
+ if (cinfo->num_scans <= 0)
+ ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
+
++ #ifndef C_MULTISCAN_FILES_SUPPORTED
++ if (cinfo->num_scans > 1)
++ ERREXIT(cinfo, JERR_NOT_COMPILED);
++ #endif
++
++ scanptr = cinfo->scan_info;
++ if (cinfo->lossless) {
++ #ifdef C_LOSSLESS_SUPPORTED
++ cinfo->process = JPROC_LOSSLESS;
++ for (ci = 0; ci < cinfo->num_components; ci++)
++ component_sent[ci] = FALSE;
++ #else
++ ERREXIT(cinfo, JERR_NOT_COMPILED);
++ #endif
++ }
+ /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
+ * for progressive JPEG, no scan can have this.
+ */
+! else if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
+ #ifdef C_PROGRESSIVE_SUPPORTED
+! cinfo->process = JPROC_PROGRESSIVE;
+ last_bitpos_ptr = & last_bitpos[0][0];
+ for (ci = 0; ci < cinfo->num_components; ci++)
+ for (coefi = 0; coefi < DCTSIZE2; coefi++)
+***************
+*** 160,166 ****
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ #endif
+ } else {
+! cinfo->progressive_mode = FALSE;
+ for (ci = 0; ci < cinfo->num_components; ci++)
+ component_sent[ci] = FALSE;
+ }
+--- 183,189 ----
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ #endif
+ } else {
+! cinfo->process = JPROC_SEQUENTIAL;
+ for (ci = 0; ci < cinfo->num_components; ci++)
+ component_sent[ci] = FALSE;
+ }
+***************
+*** 183,189 ****
+ Se = scanptr->Se;
+ Ah = scanptr->Ah;
+ Al = scanptr->Al;
+! if (cinfo->progressive_mode) {
+ #ifdef C_PROGRESSIVE_SUPPORTED
+ /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
+ * seems wrong: the upper bound ought to depend on data precision.
+--- 206,231 ----
+ Se = scanptr->Se;
+ Ah = scanptr->Ah;
+ Al = scanptr->Al;
+! if (cinfo->process == JPROC_LOSSLESS) {
+! #ifdef C_LOSSLESS_SUPPORTED
+! /* The JPEG spec simply gives the range 0..15 for Al (Pt), but that
+! * seems wrong: the upper bound ought to depend on data precision.
+! * Perhaps they really meant 0..N-1 for N-bit precision, which is what
+! * we allow here.
+! */
+! if (Ss < 1 || Ss > 7 || /* predictor selector */
+! Se != 0 || Ah != 0 ||
+! Al < 0 || Al >= cinfo->data_precision) /* point transform */
+! ERREXIT1(cinfo, JERR_BAD_LOSSLESS_SCRIPT, scanno);
+! /* Make sure components are not sent twice */
+! for (ci = 0; ci < ncomps; ci++) {
+! thisi = scanptr->component_index[ci];
+! if (component_sent[thisi])
+! ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
+! component_sent[thisi] = TRUE;
+! }
+! #endif
+! } else if (cinfo->process == JPROC_PROGRESSIVE) {
+ #ifdef C_PROGRESSIVE_SUPPORTED
+ /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
+ * seems wrong: the upper bound ought to depend on data precision.
+***************
+*** 240,246 ****
+ }
+
+ /* Now verify that everything got sent. */
+! if (cinfo->progressive_mode) {
+ #ifdef C_PROGRESSIVE_SUPPORTED
+ /* For progressive mode, we only check that at least some DC data
+ * got sent for each component; the spec does not require that all bits
+--- 282,288 ----
+ }
+
+ /* Now verify that everything got sent. */
+! if (cinfo->process == JPROC_PROGRESSIVE) {
+ #ifdef C_PROGRESSIVE_SUPPORTED
+ /* For progressive mode, we only check that at least some DC data
+ * got sent for each component; the spec does not require that all bits
+***************
+*** 260,266 ****
+ }
+ }
+
+! #endif /* C_MULTISCAN_FILES_SUPPORTED */
+
+
+ LOCAL(void)
+--- 302,308 ----
+ }
+ }
+
+! #endif /* NEED_SCAN_SCRIPT */
+
+
+ LOCAL(void)
+***************
+*** 269,275 ****
+ {
+ int ci;
+
+! #ifdef C_MULTISCAN_FILES_SUPPORTED
+ if (cinfo->scan_info != NULL) {
+ /* Prepare for current scan --- the script is already validated */
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+--- 311,317 ----
+ {
+ int ci;
+
+! #ifdef NEED_SCAN_SCRIPT
+ if (cinfo->scan_info != NULL) {
+ /* Prepare for current scan --- the script is already validated */
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+***************
+*** 284,291 ****
+ cinfo->Se = scanptr->Se;
+ cinfo->Ah = scanptr->Ah;
+ cinfo->Al = scanptr->Al;
+! }
+! else
+ #endif
+ {
+ /* Prepare for single sequential-JPEG scan containing all components */
+--- 326,332 ----
+ cinfo->Se = scanptr->Se;
+ cinfo->Ah = scanptr->Ah;
+ cinfo->Al = scanptr->Al;
+! } else
+ #endif
+ {
+ /* Prepare for single sequential-JPEG scan containing all components */
+***************
+*** 296,305 ****
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
+ }
+! cinfo->Ss = 0;
+! cinfo->Se = DCTSIZE2-1;
+! cinfo->Ah = 0;
+! cinfo->Al = 0;
+ }
+ }
+
+--- 337,356 ----
+ for (ci = 0; ci < cinfo->num_components; ci++) {
+ cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
+ }
+! if (cinfo->lossless) {
+! #ifdef C_LOSSLESS_SUPPORTED
+! /* If we fall through to here, the user specified lossless, but did not
+! * provide a scan script.
+! */
+! ERREXIT(cinfo, JERR_NO_LOSSLESS_SCRIPT);
+! #endif
+! } else {
+! cinfo->process = JPROC_SEQUENTIAL;
+! cinfo->Ss = 0;
+! cinfo->Se = DCTSIZE2-1;
+! cinfo->Ah = 0;
+! cinfo->Al = 0;
+! }
+ }
+ }
+
+***************
+*** 311,316 ****
+--- 362,368 ----
+ {
+ int ci, mcublks, tmp;
+ jpeg_component_info *compptr;
++ int data_unit = cinfo->data_unit;
+
+ if (cinfo->comps_in_scan == 1) {
+
+***************
+*** 318,341 ****
+ compptr = cinfo->cur_comp_info[0];
+
+ /* Overall image size in MCUs */
+! cinfo->MCUs_per_row = compptr->width_in_blocks;
+! cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
+
+ /* For noninterleaved scan, always one block per MCU */
+ compptr->MCU_width = 1;
+ compptr->MCU_height = 1;
+! compptr->MCU_blocks = 1;
+! compptr->MCU_sample_width = DCTSIZE;
+ compptr->last_col_width = 1;
+ /* For noninterleaved scans, it is convenient to define last_row_height
+ * as the number of block rows present in the last iMCU row.
+ */
+! tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+ if (tmp == 0) tmp = compptr->v_samp_factor;
+ compptr->last_row_height = tmp;
+
+ /* Prepare array describing MCU composition */
+! cinfo->blocks_in_MCU = 1;
+ cinfo->MCU_membership[0] = 0;
+
+ } else {
+--- 370,393 ----
+ compptr = cinfo->cur_comp_info[0];
+
+ /* Overall image size in MCUs */
+! cinfo->MCUs_per_row = compptr->width_in_data_units;
+! cinfo->MCU_rows_in_scan = compptr->height_in_data_units;
+
+ /* For noninterleaved scan, always one block per MCU */
+ compptr->MCU_width = 1;
+ compptr->MCU_height = 1;
+! compptr->MCU_data_units = 1;
+! compptr->MCU_sample_width = data_unit;
+ compptr->last_col_width = 1;
+ /* For noninterleaved scans, it is convenient to define last_row_height
+ * as the number of block rows present in the last iMCU row.
+ */
+! tmp = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
+ if (tmp == 0) tmp = compptr->v_samp_factor;
+ compptr->last_row_height = tmp;
+
+ /* Prepare array describing MCU composition */
+! cinfo->data_units_in_MCU = 1;
+ cinfo->MCU_membership[0] = 0;
+
+ } else {
+***************
+*** 348,359 ****
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width,
+! (long) (cinfo->max_h_samp_factor*DCTSIZE));
+ cinfo->MCU_rows_in_scan = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+! (long) (cinfo->max_v_samp_factor*DCTSIZE));
+
+! cinfo->blocks_in_MCU = 0;
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+--- 400,411 ----
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width,
+! (long) (cinfo->max_h_samp_factor*data_unit));
+ cinfo->MCU_rows_in_scan = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+! (long) (cinfo->max_v_samp_factor*data_unit));
+
+! cinfo->data_units_in_MCU = 0;
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+***************
+*** 360,380 ****
+ /* Sampling factors give # of blocks of component in each MCU */
+ compptr->MCU_width = compptr->h_samp_factor;
+ compptr->MCU_height = compptr->v_samp_factor;
+! compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
+! compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
+ /* Figure number of non-dummy blocks in last MCU column & row */
+! tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
+ if (tmp == 0) tmp = compptr->MCU_width;
+ compptr->last_col_width = tmp;
+! tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
+ if (tmp == 0) tmp = compptr->MCU_height;
+ compptr->last_row_height = tmp;
+ /* Prepare array describing MCU composition */
+! mcublks = compptr->MCU_blocks;
+! if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
+ ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
+ while (mcublks-- > 0) {
+! cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
+ }
+ }
+
+--- 412,432 ----
+ /* Sampling factors give # of blocks of component in each MCU */
+ compptr->MCU_width = compptr->h_samp_factor;
+ compptr->MCU_height = compptr->v_samp_factor;
+! compptr->MCU_data_units = compptr->MCU_width * compptr->MCU_height;
+! compptr->MCU_sample_width = compptr->MCU_width * data_unit;
+ /* Figure number of non-dummy blocks in last MCU column & row */
+! tmp = (int) (compptr->width_in_data_units % compptr->MCU_width);
+ if (tmp == 0) tmp = compptr->MCU_width;
+ compptr->last_col_width = tmp;
+! tmp = (int) (compptr->height_in_data_units % compptr->MCU_height);
+ if (tmp == 0) tmp = compptr->MCU_height;
+ compptr->last_row_height = tmp;
+ /* Prepare array describing MCU composition */
+! mcublks = compptr->MCU_data_units;
+! if (cinfo->data_units_in_MCU + mcublks > C_MAX_DATA_UNITS_IN_MCU)
+ ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
+ while (mcublks-- > 0) {
+! cinfo->MCU_membership[cinfo->data_units_in_MCU++] = ci;
+ }
+ }
+
+***************
+*** 400,405 ****
+--- 452,458 ----
+ METHODDEF(void)
+ prepare_for_pass (j_compress_ptr cinfo)
+ {
++ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ switch (master->pass_type) {
+***************
+*** 414,424 ****
+ (*cinfo->downsample->start_pass) (cinfo);
+ (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
+ }
+! (*cinfo->fdct->start_pass) (cinfo);
+! (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
+! (*cinfo->coef->start_pass) (cinfo,
+! (master->total_passes > 1 ?
+! JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
+ (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
+ if (cinfo->optimize_coding) {
+ /* No immediate data output; postpone writing frame/scan headers */
+--- 467,476 ----
+ (*cinfo->downsample->start_pass) (cinfo);
+ (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
+ }
+! (*cinfo->codec->entropy_start_pass) (cinfo, cinfo->optimize_coding);
+! (*cinfo->codec->start_pass) (cinfo,
+! (master->total_passes > 1 ?
+! JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
+ (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
+ if (cinfo->optimize_coding) {
+ /* No immediate data output; postpone writing frame/scan headers */
+***************
+*** 433,441 ****
+ /* Do Huffman optimization for a scan after the first one. */
+ select_scan_parameters(cinfo);
+ per_scan_setup(cinfo);
+! if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
+! (*cinfo->entropy->start_pass) (cinfo, TRUE);
+! (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
+ master->pub.call_pass_startup = FALSE;
+ break;
+ }
+--- 485,493 ----
+ /* Do Huffman optimization for a scan after the first one. */
+ select_scan_parameters(cinfo);
+ per_scan_setup(cinfo);
+! if ((*cinfo->codec->need_optimization_pass) (cinfo) || cinfo->arith_code) {
+! (*cinfo->codec->entropy_start_pass) (cinfo, TRUE);
+! (*cinfo->codec->start_pass) (cinfo, JBUF_CRANK_DEST);
+ master->pub.call_pass_startup = FALSE;
+ break;
+ }
+***************
+*** 453,460 ****
+ select_scan_parameters(cinfo);
+ per_scan_setup(cinfo);
+ }
+! (*cinfo->entropy->start_pass) (cinfo, FALSE);
+! (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
+ /* We emit frame/scan headers now */
+ if (master->scan_number == 0)
+ (*cinfo->marker->write_frame_header) (cinfo);
+--- 505,512 ----
+ select_scan_parameters(cinfo);
+ per_scan_setup(cinfo);
+ }
+! (*cinfo->codec->entropy_start_pass) (cinfo, FALSE);
+! (*cinfo->codec->start_pass) (cinfo, JBUF_CRANK_DEST);
+ /* We emit frame/scan headers now */
+ if (master->scan_number == 0)
+ (*cinfo->marker->write_frame_header) (cinfo);
+***************
+*** 502,513 ****
+ METHODDEF(void)
+ finish_pass_master (j_compress_ptr cinfo)
+ {
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ /* The entropy coder always needs an end-of-pass call,
+ * either to analyze statistics or to flush its output buffer.
+ */
+! (*cinfo->entropy->finish_pass) (cinfo);
+
+ /* Update state for next pass */
+ switch (master->pass_type) {
+--- 554,566 ----
+ METHODDEF(void)
+ finish_pass_master (j_compress_ptr cinfo)
+ {
++ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+
+ /* The entropy coder always needs an end-of-pass call,
+ * either to analyze statistics or to flush its output buffer.
+ */
+! (*lossyc->pub.entropy_finish_pass) (cinfo);
+
+ /* Update state for next pass */
+ switch (master->pass_type) {
+***************
+*** 553,574 ****
+ master->pub.finish_pass = finish_pass_master;
+ master->pub.is_last_pass = FALSE;
+
+ /* Validate parameters, determine derived values */
+ initial_setup(cinfo);
+
+ if (cinfo->scan_info != NULL) {
+! #ifdef C_MULTISCAN_FILES_SUPPORTED
+ validate_script(cinfo);
+ #else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ #endif
+ } else {
+! cinfo->progressive_mode = FALSE;
+ cinfo->num_scans = 1;
+ }
+
+! if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
+! cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
+
+ /* Initialize my private state */
+ if (transcode_only) {
+--- 606,631 ----
+ master->pub.finish_pass = finish_pass_master;
+ master->pub.is_last_pass = FALSE;
+
++ cinfo->data_unit = cinfo->lossless ? 1 : DCTSIZE;
++
+ /* Validate parameters, determine derived values */
+ initial_setup(cinfo);
+
+ if (cinfo->scan_info != NULL) {
+! #ifdef NEED_SCAN_SCRIPT
+ validate_script(cinfo);
+ #else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ #endif
+ } else {
+! cinfo->process = JPROC_SEQUENTIAL;
+ cinfo->num_scans = 1;
+ }
+
+! if (cinfo->process == JPROC_PROGRESSIVE || /* TEMPORARY HACK ??? */
+! cinfo->process == JPROC_LOSSLESS)
+! cinfo->optimize_coding = TRUE; /* assume default tables no good for
+! * progressive mode or lossless mode */
+
+ /* Initialize my private state */
+ if (transcode_only) {
+diff -cN ../jpeg-6b/jcodec.c ./jcodec.c
+*** ../jpeg-6b/jcodec.c
+--- ./jcodec.c Tue Apr 27 14:58:19 1999
+***************
+*** 0 ****
+--- 1,53 ----
++ /*
++ * jcodec.c
++ *
++ * Copyright (C) 1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains utility functions for the JPEG codec(s).
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossy.h"
++ #include "jlossls.h"
++
++
++ /*
++ * Initialize the compression codec.
++ * This is called only once, during master selection.
++ */
++
++ GLOBAL(void)
++ jinit_c_codec (j_compress_ptr cinfo)
++ {
++ if (cinfo->process == JPROC_LOSSLESS) {
++ #ifdef C_LOSSLESS_SUPPORTED
++ jinit_lossless_c_codec(cinfo);
++ #else
++ ERREXIT(cinfo, JERR_NOT_COMPILED);
++ #endif
++ } else
++ jinit_lossy_c_codec(cinfo);
++ }
++
++
++ /*
++ * Initialize the decompression codec.
++ * This is called only once, during master selection.
++ */
++
++ GLOBAL(void)
++ jinit_d_codec (j_decompress_ptr cinfo)
++ {
++ if (cinfo->process == JPROC_LOSSLESS) {
++ #ifdef D_LOSSLESS_SUPPORTED
++ jinit_lossless_d_codec(cinfo);
++ #else
++ ERREXIT(cinfo, JERR_NOT_COMPILED);
++ #endif
++ } else
++ jinit_lossy_d_codec(cinfo);
++ }
+diff -cN ../jpeg-6b/jcparam.c ./jcparam.c
+*** ../jpeg-6b/jcparam.c Sat Feb 21 14:59:42 1998
+--- ./jcparam.c Tue Apr 27 14:58:19 1999
+***************
+*** 284,289 ****
+--- 284,290 ----
+
+ /* Initialize everything not dependent on the color space */
+
++ cinfo->lossless = FALSE;
+ cinfo->data_precision = BITS_IN_JSAMPLE;
+ /* Set up two quantization tables using default quality of 75 */
+ jpeg_set_quality(cinfo, 75, TRUE);
+***************
+*** 358,384 ****
+ GLOBAL(void)
+ jpeg_default_colorspace (j_compress_ptr cinfo)
+ {
+! switch (cinfo->in_color_space) {
+! case JCS_GRAYSCALE:
+! jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
+! break;
+! case JCS_RGB:
+! jpeg_set_colorspace(cinfo, JCS_YCbCr);
+! break;
+! case JCS_YCbCr:
+! jpeg_set_colorspace(cinfo, JCS_YCbCr);
+! break;
+! case JCS_CMYK:
+! jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
+! break;
+! case JCS_YCCK:
+! jpeg_set_colorspace(cinfo, JCS_YCCK);
+! break;
+! case JCS_UNKNOWN:
+! jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
+! break;
+! default:
+! ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+ }
+ }
+
+--- 359,389 ----
+ GLOBAL(void)
+ jpeg_default_colorspace (j_compress_ptr cinfo)
+ {
+! if (cinfo->lossless)
+! jpeg_set_colorspace(cinfo, cinfo->in_color_space);
+! else { /* lossy */
+! switch (cinfo->in_color_space) {
+! case JCS_GRAYSCALE:
+! jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
+! break;
+! case JCS_RGB:
+! jpeg_set_colorspace(cinfo, JCS_YCbCr);
+! break;
+! case JCS_YCbCr:
+! jpeg_set_colorspace(cinfo, JCS_YCbCr);
+! break;
+! case JCS_CMYK:
+! jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
+! break;
+! case JCS_YCCK:
+! jpeg_set_colorspace(cinfo, JCS_YCCK);
+! break;
+! case JCS_UNKNOWN:
+! jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
+! break;
+! default:
+! ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+! }
+ }
+ }
+
+***************
+*** 433,442 ****
+ cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
+ cinfo->num_components = 3;
+ /* JFIF specifies component IDs 1,2,3 */
+! /* We default to 2x2 subsamples of chrominance */
+! SET_COMP(0, 1, 2,2, 0, 0,0);
+! SET_COMP(1, 2, 1,1, 1, 1,1);
+! SET_COMP(2, 3, 1,1, 1, 1,1);
+ break;
+ case JCS_CMYK:
+ cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
+--- 438,453 ----
+ cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
+ cinfo->num_components = 3;
+ /* JFIF specifies component IDs 1,2,3 */
+! if (cinfo->lossless) {
+! SET_COMP(0, 1, 1,1, 0, 0,0);
+! SET_COMP(1, 2, 1,1, 1, 1,1);
+! SET_COMP(2, 3, 1,1, 1, 1,1);
+! } else { /* lossy */
+! /* We default to 2x2 subsamples of chrominance */
+! SET_COMP(0, 1, 2,2, 0, 0,0);
+! SET_COMP(1, 2, 1,1, 1, 1,1);
+! SET_COMP(2, 3, 1,1, 1, 1,1);
+! }
+ break;
+ case JCS_CMYK:
+ cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
+***************
+*** 449,458 ****
+ case JCS_YCCK:
+ cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
+ cinfo->num_components = 4;
+! SET_COMP(0, 1, 2,2, 0, 0,0);
+! SET_COMP(1, 2, 1,1, 1, 1,1);
+! SET_COMP(2, 3, 1,1, 1, 1,1);
+! SET_COMP(3, 4, 2,2, 0, 0,0);
+ break;
+ case JCS_UNKNOWN:
+ cinfo->num_components = cinfo->input_components;
+--- 460,476 ----
+ case JCS_YCCK:
+ cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
+ cinfo->num_components = 4;
+! if (cinfo->lossless) {
+! SET_COMP(0, 1, 1,1, 0, 0,0);
+! SET_COMP(1, 2, 1,1, 1, 1,1);
+! SET_COMP(2, 3, 1,1, 1, 1,1);
+! SET_COMP(3, 4, 1,1, 0, 0,0);
+! } else { /* lossy */
+! SET_COMP(0, 1, 2,2, 0, 0,0);
+! SET_COMP(1, 2, 1,1, 1, 1,1);
+! SET_COMP(2, 3, 1,1, 1, 1,1);
+! SET_COMP(3, 4, 2,2, 0, 0,0);
+! }
+ break;
+ case JCS_UNKNOWN:
+ cinfo->num_components = cinfo->input_components;
+***************
+*** 472,492 ****
+ #ifdef C_PROGRESSIVE_SUPPORTED
+
+ LOCAL(jpeg_scan_info *)
+- fill_a_scan (jpeg_scan_info * scanptr, int ci,
+- int Ss, int Se, int Ah, int Al)
+- /* Support routine: generate one scan for specified component */
+- {
+- scanptr->comps_in_scan = 1;
+- scanptr->component_index[0] = ci;
+- scanptr->Ss = Ss;
+- scanptr->Se = Se;
+- scanptr->Ah = Ah;
+- scanptr->Al = Al;
+- scanptr++;
+- return scanptr;
+- }
+-
+- LOCAL(jpeg_scan_info *)
+ fill_scans (jpeg_scan_info * scanptr, int ncomps,
+ int Ss, int Se, int Ah, int Al)
+ /* Support routine: generate one scan for each component */
+--- 490,495 ----
+***************
+*** 505,510 ****
+--- 508,529 ----
+ return scanptr;
+ }
+
++
++ LOCAL(jpeg_scan_info *)
++ fill_a_scan (jpeg_scan_info * scanptr, int ci,
++ int Ss, int Se, int Ah, int Al)
++ /* Support routine: generate one scan for specified component */
++ {
++ scanptr->comps_in_scan = 1;
++ scanptr->component_index[0] = ci;
++ scanptr->Ss = Ss;
++ scanptr->Se = Se;
++ scanptr->Ah = Ah;
++ scanptr->Al = Al;
++ scanptr++;
++ return scanptr;
++ }
++
+ LOCAL(jpeg_scan_info *)
+ fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
+ /* Support routine: generate interleaved DC scan if possible, else N scans */
+***************
+*** 608,610 ****
+--- 627,687 ----
+ }
+
+ #endif /* C_PROGRESSIVE_SUPPORTED */
++
++
++ #ifdef C_LOSSLESS_SUPPORTED
++
++ /*
++ * Create a single-entry lossless-JPEG script containing all components.
++ * cinfo->num_components must be correct.
++ */
++
++ GLOBAL(void)
++ jpeg_simple_lossless (j_compress_ptr cinfo, int predictor, int point_transform)
++ {
++ int ncomps = cinfo->num_components;
++ int nscans = 1;
++ int ci;
++ jpeg_scan_info * scanptr;
++
++ /* Safety check to ensure start_compress not called yet. */
++ if (cinfo->global_state != CSTATE_START)
++ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
++
++ cinfo->lossless = TRUE;
++
++ /* Set jpeg_color_space. */
++ jpeg_default_colorspace(cinfo);
++
++ /* Check to ensure that all components will fit in one scan. */
++ if (cinfo->num_components > MAX_COMPS_IN_SCAN)
++ ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
++ MAX_COMPS_IN_SCAN);
++
++ /* Allocate space for script.
++ * We need to put it in the permanent pool in case the application performs
++ * multiple compressions without changing the settings. To avoid a memory
++ * leak if jpeg_simple_lossless is called repeatedly for the same JPEG
++ * object, we try to re-use previously allocated space.
++ */
++ if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
++ cinfo->script_space_size = nscans;
++ cinfo->script_space = (jpeg_scan_info *)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
++ cinfo->script_space_size * SIZEOF(jpeg_scan_info));
++ }
++ scanptr = cinfo->script_space;
++ cinfo->scan_info = scanptr;
++ cinfo->num_scans = nscans;
++
++ /* Fill the script. */
++ scanptr->comps_in_scan = ncomps;
++ for (ci = 0; ci < ncomps; ci++)
++ scanptr->component_index[ci] = ci;
++ scanptr->Ss = predictor;
++ scanptr->Se = 0;
++ scanptr->Ah = 0;
++ scanptr->Al = point_transform;
++ }
++
++ #endif /* C_LOSSLESS_SUPPORTED */
+diff -cN ../jpeg-6b/jcphuff.c ./jcphuff.c
+*** ../jpeg-6b/jcphuff.c Mon Oct 20 20:21:14 1997
+--- ./jcphuff.c Tue Apr 27 14:58:20 1999
+***************
+*** 1,7 ****
+ /*
+ * jcphuff.c
+ *
+! * Copyright (C) 1995-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jcphuff.c
+ *
+! * Copyright (C) 1995-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 15,21 ****
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
+! #include "jchuff.h" /* Declarations shared with jchuff.c */
+
+ #ifdef C_PROGRESSIVE_SUPPORTED
+
+--- 15,22 ----
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
+! #include "jlossy.h" /* Private declarations for lossy codec */
+! #include "jchuff.h" /* Declarations shared with jc*huff.c */
+
+ #ifdef C_PROGRESSIVE_SUPPORTED
+
+***************
+*** 22,29 ****
+ /* Expanded entropy encoder object for progressive Huffman encoding. */
+
+ typedef struct {
+- struct jpeg_entropy_encoder pub; /* public fields */
+-
+ /* Mode flag: TRUE for optimization, FALSE for actual data output */
+ boolean gather_statistics;
+
+--- 23,28 ----
+***************
+*** 105,111 ****
+ METHODDEF(void)
+ start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
+ {
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ boolean is_DC_band;
+ int ci, tbl;
+ jpeg_component_info * compptr;
+--- 104,111 ----
+ METHODDEF(void)
+ start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+ boolean is_DC_band;
+ int ci, tbl;
+ jpeg_component_info * compptr;
+***************
+*** 120,133 ****
+ /* Select execution routines */
+ if (cinfo->Ah == 0) {
+ if (is_DC_band)
+! entropy->pub.encode_mcu = encode_mcu_DC_first;
+ else
+! entropy->pub.encode_mcu = encode_mcu_AC_first;
+ } else {
+ if (is_DC_band)
+! entropy->pub.encode_mcu = encode_mcu_DC_refine;
+ else {
+! entropy->pub.encode_mcu = encode_mcu_AC_refine;
+ /* AC refinement needs a correction bit buffer */
+ if (entropy->bit_buffer == NULL)
+ entropy->bit_buffer = (char *)
+--- 120,133 ----
+ /* Select execution routines */
+ if (cinfo->Ah == 0) {
+ if (is_DC_band)
+! lossyc->entropy_encode_mcu = encode_mcu_DC_first;
+ else
+! lossyc->entropy_encode_mcu = encode_mcu_AC_first;
+ } else {
+ if (is_DC_band)
+! lossyc->entropy_encode_mcu = encode_mcu_DC_refine;
+ else {
+! lossyc->entropy_encode_mcu = encode_mcu_AC_refine;
+ /* AC refinement needs a correction bit buffer */
+ if (entropy->bit_buffer == NULL)
+ entropy->bit_buffer = (char *)
+***************
+*** 136,144 ****
+ }
+ }
+ if (gather_statistics)
+! entropy->pub.finish_pass = finish_pass_gather_phuff;
+ else
+! entropy->pub.finish_pass = finish_pass_phuff;
+
+ /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
+ * for AC coefficients.
+--- 136,144 ----
+ }
+ }
+ if (gather_statistics)
+! lossyc->pub.entropy_finish_pass = finish_pass_gather_phuff;
+ else
+! lossyc->pub.entropy_finish_pass = finish_pass_phuff;
+
+ /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
+ * for AC coefficients.
+***************
+*** 376,382 ****
+ METHODDEF(boolean)
+ encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ register int temp, temp2;
+ register int nbits;
+ int blkn, ci;
+--- 376,383 ----
+ METHODDEF(boolean)
+ encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+ register int temp, temp2;
+ register int nbits;
+ int blkn, ci;
+***************
+*** 394,400 ****
+ emit_restart(entropy, entropy->next_restart_num);
+
+ /* Encode the MCU data blocks */
+! for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+--- 395,401 ----
+ emit_restart(entropy, entropy->next_restart_num);
+
+ /* Encode the MCU data blocks */
+! for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+***************
+*** 463,469 ****
+ METHODDEF(boolean)
+ encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ register int temp, temp2;
+ register int nbits;
+ register int r, k;
+--- 464,471 ----
+ METHODDEF(boolean)
+ encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+ register int temp, temp2;
+ register int nbits;
+ register int r, k;
+***************
+*** 570,576 ****
+ METHODDEF(boolean)
+ encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ register int temp;
+ int blkn;
+ int Al = cinfo->Al;
+--- 572,579 ----
+ METHODDEF(boolean)
+ encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+ register int temp;
+ int blkn;
+ int Al = cinfo->Al;
+***************
+*** 585,591 ****
+ emit_restart(entropy, entropy->next_restart_num);
+
+ /* Encode the MCU data blocks */
+! for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+
+ /* We simply emit the Al'th bit of the DC coefficient value. */
+--- 588,594 ----
+ emit_restart(entropy, entropy->next_restart_num);
+
+ /* Encode the MCU data blocks */
+! for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+
+ /* We simply emit the Al'th bit of the DC coefficient value. */
+***************
+*** 617,623 ****
+ METHODDEF(boolean)
+ encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ register int temp;
+ register int r, k;
+ int EOB;
+--- 620,627 ----
+ METHODDEF(boolean)
+ encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+ register int temp;
+ register int r, k;
+ int EOB;
+***************
+*** 745,751 ****
+ METHODDEF(void)
+ finish_pass_phuff (j_compress_ptr cinfo)
+ {
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+
+ entropy->next_output_byte = cinfo->dest->next_output_byte;
+ entropy->free_in_buffer = cinfo->dest->free_in_buffer;
+--- 749,756 ----
+ METHODDEF(void)
+ finish_pass_phuff (j_compress_ptr cinfo)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+
+ entropy->next_output_byte = cinfo->dest->next_output_byte;
+ entropy->free_in_buffer = cinfo->dest->free_in_buffer;
+***************
+*** 766,772 ****
+ METHODDEF(void)
+ finish_pass_gather_phuff (j_compress_ptr cinfo)
+ {
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ boolean is_DC_band;
+ int ci, tbl;
+ jpeg_component_info * compptr;
+--- 771,778 ----
+ METHODDEF(void)
+ finish_pass_gather_phuff (j_compress_ptr cinfo)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyc->entropy_private;
+ boolean is_DC_band;
+ int ci, tbl;
+ jpeg_component_info * compptr;
+***************
+*** 806,811 ****
+--- 812,824 ----
+ }
+
+
++ METHODDEF(boolean)
++ need_optimization_pass (j_compress_ptr cinfo)
++ {
++ return (cinfo->Ss != 0 || cinfo->Ah == 0);
++ }
++
++
+ /*
+ * Module initialization routine for progressive Huffman entropy encoding.
+ */
+***************
+*** 813,818 ****
+--- 826,832 ----
+ GLOBAL(void)
+ jinit_phuff_encoder (j_compress_ptr cinfo)
+ {
++ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy;
+ int i;
+
+***************
+*** 819,826 ****
+ entropy = (phuff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(phuff_entropy_encoder));
+! cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
+! entropy->pub.start_pass = start_pass_phuff;
+
+ /* Mark tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+--- 833,841 ----
+ entropy = (phuff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(phuff_entropy_encoder));
+! lossyc->entropy_private = (struct jpeg_entropy_encoder *) entropy;
+! lossyc->pub.entropy_start_pass = start_pass_phuff;
+! lossyc->pub.need_optimization_pass = need_optimization_pass;
+
+ /* Mark tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+diff -cN ../jpeg-6b/jcpred.c ./jcpred.c
+*** ../jpeg-6b/jcpred.c
+--- ./jcpred.c Tue Apr 27 14:58:20 1999
+***************
+*** 0 ****
+--- 1,297 ----
++ /*
++ * jcpred.c
++ *
++ * Copyright (C) 1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains sample differencing for lossless JPEG.
++ *
++ * In order to avoid paying the performance penalty of having to check the
++ * predictor being used and the row being processed for each call of the
++ * undifferencer, and to promote optimization, we have separate differencing
++ * functions for each case.
++ *
++ * We are able to avoid duplicating source code by implementing the predictors
++ * and differencers as macros. Each of the differencing functions are
++ * simply wrappers around a DIFFERENCE macro with the appropriate PREDICTOR
++ * macro passed as an argument.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossls.h" /* Private declarations for lossless codec */
++
++
++ #ifdef C_LOSSLESS_SUPPORTED
++
++ /* Private predictor object */
++
++ typedef struct {
++ /* MCU-rows left in the restart interval for each component */
++ unsigned int restart_rows_to_go[MAX_COMPONENTS];
++ } c_predictor;
++
++ typedef c_predictor * c_pred_ptr;
++
++ /* Forward declarations */
++ LOCAL(void) reset_predictor
++ JPP((j_compress_ptr cinfo, int ci));
++ METHODDEF(void) start_pass
++ JPP((j_compress_ptr cinfo));
++
++
++ /* Predictor for the first column of the first row: 2^(P-Pt-1) */
++ #define INITIAL_PREDICTORx (1 << (cinfo->data_precision - cinfo->Al - 1))
++
++ /* Predictor for the first column of the remaining rows: Rb */
++ #define INITIAL_PREDICTOR2 GETJSAMPLE(prev_row[0])
++
++
++ /*
++ * 1-Dimensional differencer routine.
++ *
++ * This macro implements the 1-D horizontal predictor (1). INITIAL_PREDICTOR
++ * is used as the special case predictor for the first column, which must be
++ * either INITIAL_PREDICTOR2 or INITIAL_PREDICTORx. The remaining samples
++ * use PREDICTOR1.
++ */
++
++ #define DIFFERENCE_1D(INITIAL_PREDICTOR) \
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec; \
++ c_pred_ptr pred = (c_pred_ptr) losslsc->pred_private; \
++ boolean restart = FALSE; \
++ int xindex; \
++ int samp, Ra; \
++ \
++ samp = GETJSAMPLE(input_buf[0]); \
++ diff_buf[0] = samp - INITIAL_PREDICTOR; \
++ \
++ for (xindex = 1; xindex < width; xindex++) { \
++ Ra = samp; \
++ samp = GETJSAMPLE(input_buf[xindex]); \
++ diff_buf[xindex] = samp - PREDICTOR1; \
++ } \
++ \
++ /* Account for restart interval (no-op if not using restarts) */ \
++ if (cinfo->restart_interval) { \
++ if (--(pred->restart_rows_to_go[ci]) == 0) { \
++ reset_predictor(cinfo, ci); \
++ restart = TRUE; \
++ } \
++ }
++
++
++ /*
++ * 2-Dimensional differencer routine.
++ *
++ * This macro implements the 2-D horizontal predictors (#2-7). PREDICTOR2 is
++ * used as the special case predictor for the first column. The remaining
++ * samples use PREDICTOR, which is a function of Ra, Rb, Rc.
++ *
++ * Because prev_row and output_buf may point to the same storage area (in an
++ * interleaved image with Vi=1, for example), we must take care to buffer Rb/Rc
++ * before writing the current reconstructed sample value into output_buf.
++ */
++
++ #define DIFFERENCE_2D(PREDICTOR) \
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec; \
++ c_pred_ptr pred = (c_pred_ptr) losslsc->pred_private; \
++ int xindex; \
++ int samp, Ra, Rb, Rc; \
++ \
++ Rb = GETJSAMPLE(prev_row[0]); \
++ samp = GETJSAMPLE(input_buf[0]); \
++ diff_buf[0] = samp - PREDICTOR2; \
++ \
++ for (xindex = 1; xindex < width; xindex++) { \
++ Rc = Rb; \
++ Rb = GETJSAMPLE(prev_row[xindex]); \
++ Ra = samp; \
++ samp = GETJSAMPLE(input_buf[xindex]); \
++ diff_buf[xindex] = samp - PREDICTOR; \
++ } \
++ \
++ /* Account for restart interval (no-op if not using restarts) */ \
++ if (cinfo->restart_interval) { \
++ if (--pred->restart_rows_to_go[ci] == 0) \
++ reset_predictor(cinfo, ci); \
++ }
++
++
++ /*
++ * Differencers for the all rows but the first in a scan or restart interval.
++ * The first sample in the row is differenced using the vertical
++ * predictor (2). The rest of the samples are differenced using the
++ * predictor specified in the scan header.
++ */
++
++ METHODDEF(void)
++ jpeg_difference1(j_compress_ptr cinfo, int ci,
++ JSAMPROW input_buf, JSAMPROW prev_row,
++ JDIFFROW diff_buf, JDIMENSION width)
++ {
++ DIFFERENCE_1D(INITIAL_PREDICTOR2);
++ }
++
++ METHODDEF(void)
++ jpeg_difference2(j_compress_ptr cinfo, int ci,
++ JSAMPROW input_buf, JSAMPROW prev_row,
++ JDIFFROW diff_buf, JDIMENSION width)
++ {
++ DIFFERENCE_2D(PREDICTOR2);
++ }
++
++ METHODDEF(void)
++ jpeg_difference3(j_compress_ptr cinfo, int ci,
++ JSAMPROW input_buf, JSAMPROW prev_row,
++ JDIFFROW diff_buf, JDIMENSION width)
++ {
++ DIFFERENCE_2D(PREDICTOR3);
++ }
++
++ METHODDEF(void)
++ jpeg_difference4(j_compress_ptr cinfo, int ci,
++ JSAMPROW input_buf, JSAMPROW prev_row,
++ JDIFFROW diff_buf, JDIMENSION width)
++ {
++ DIFFERENCE_2D(PREDICTOR4);
++ }
++
++ METHODDEF(void)
++ jpeg_difference5(j_compress_ptr cinfo, int ci,
++ JSAMPROW input_buf, JSAMPROW prev_row,
++ JDIFFROW diff_buf, JDIMENSION width)
++ {
++ DIFFERENCE_2D(PREDICTOR5);
++ }
++
++ METHODDEF(void)
++ jpeg_difference6(j_compress_ptr cinfo, int ci,
++ JSAMPROW input_buf, JSAMPROW prev_row,
++ JDIFFROW diff_buf, JDIMENSION width)
++ {
++ DIFFERENCE_2D(PREDICTOR6);
++ }
++
++ METHODDEF(void)
++ jpeg_difference7(j_compress_ptr cinfo, int ci,
++ JSAMPROW input_buf, JSAMPROW prev_row,
++ JDIFFROW diff_buf, JDIMENSION width)
++ {
++ DIFFERENCE_2D(PREDICTOR7);
++ }
++
++
++ /*
++ * Differencer for the first row in a scan or restart interval. The first
++ * sample in the row is differenced using the special predictor constant
++ * x=2^(P-Pt-1). The rest of the samples are differenced using the
++ * 1-D horizontal predictor (1).
++ */
++
++ METHODDEF(void)
++ jpeg_difference_first_row(j_compress_ptr cinfo, int ci,
++ JSAMPROW input_buf, JSAMPROW prev_row,
++ JDIFFROW diff_buf, JDIMENSION width)
++ {
++ DIFFERENCE_1D(INITIAL_PREDICTORx);
++
++ /*
++ * Now that we have differenced the first row, we want to use the
++ * differencer which corresponds to the predictor specified in the
++ * scan header.
++ *
++ * Note that we don't to do this if we have just reset the predictor
++ * for a new restart interval.
++ */
++ if (!restart) {
++ switch (cinfo->Ss) {
++ case 1:
++ losslsc->predict_difference[ci] = jpeg_difference1;
++ break;
++ case 2:
++ losslsc->predict_difference[ci] = jpeg_difference2;
++ break;
++ case 3:
++ losslsc->predict_difference[ci] = jpeg_difference3;
++ break;
++ case 4:
++ losslsc->predict_difference[ci] = jpeg_difference4;
++ break;
++ case 5:
++ losslsc->predict_difference[ci] = jpeg_difference5;
++ break;
++ case 6:
++ losslsc->predict_difference[ci] = jpeg_difference6;
++ break;
++ case 7:
++ losslsc->predict_difference[ci] = jpeg_difference7;
++ break;
++ }
++ }
++ }
++
++ /*
++ * Reset predictor at the start of a pass or restart interval.
++ */
++
++ LOCAL(void)
++ reset_predictor (j_compress_ptr cinfo, int ci)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ c_pred_ptr pred = (c_pred_ptr) losslsc->pred_private;
++
++ /* Initialize restart counter */
++ pred->restart_rows_to_go[ci] =
++ cinfo->restart_interval / cinfo->MCUs_per_row;
++
++ /* Set difference function to first row function */
++ losslsc->predict_difference[ci] = jpeg_difference_first_row;
++ }
++
++
++ /*
++ * Initialize for an input processing pass.
++ */
++
++ METHODDEF(void)
++ start_pass (j_compress_ptr cinfo)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ c_pred_ptr pred = (c_pred_ptr) losslsc->pred_private;
++ int ci;
++
++ /* Check that the restart interval is an integer multiple of the number
++ * of MCU in an MCU-row.
++ */
++ if (cinfo->restart_interval % cinfo->MCUs_per_row != 0)
++ ERREXIT2(cinfo, JERR_BAD_RESTART,
++ cinfo->restart_interval, cinfo->MCUs_per_row);
++
++ /* Set predictors for start of pass */
++ for (ci = 0; ci < cinfo->num_components; ci++)
++ reset_predictor(cinfo, ci);
++ }
++
++
++ /*
++ * Module initialization routine for the differencer.
++ */
++
++ GLOBAL(void)
++ jinit_differencer (j_compress_ptr cinfo)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ c_pred_ptr pred;
++
++ pred = (c_pred_ptr)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ SIZEOF(c_predictor));
++ losslsc->pred_private = (void *) pred;
++ losslsc->predict_start_pass = start_pass;
++ }
++
++ #endif /* C_LOSSLESS_SUPPORTED */
++
+diff -cN ../jpeg-6b/jcprepct.c ./jcprepct.c
+*** ../jpeg-6b/jcprepct.c Sat Jan 6 18:25:51 1996
+--- ./jcprepct.c Tue Apr 27 14:58:20 1999
+***************
+*** 1,7 ****
+ /*
+ * jcprepct.c
+ *
+! * Copyright (C) 1994-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jcprepct.c
+ *
+! * Copyright (C) 1994-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 174,180 ****
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ expand_bottom_edge(output_buf[ci],
+! compptr->width_in_blocks * DCTSIZE,
+ (int) (*out_row_group_ctr * compptr->v_samp_factor),
+ (int) (out_row_groups_avail * compptr->v_samp_factor));
+ }
+--- 174,180 ----
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ expand_bottom_edge(output_buf[ci],
+! compptr->width_in_data_units * cinfo->data_unit,
+ (int) (*out_row_group_ctr * compptr->v_samp_factor),
+ (int) (out_row_groups_avail * compptr->v_samp_factor));
+ }
+***************
+*** 288,294 ****
+ */
+ true_buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
+ cinfo->max_h_samp_factor) / compptr->h_samp_factor),
+ (JDIMENSION) (3 * rgroup_height));
+ /* Copy true buffer row pointers into the middle of the fake row array */
+--- 288,294 ----
+ */
+ true_buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! (JDIMENSION) (((long) compptr->width_in_data_units * cinfo->data_unit *
+ cinfo->max_h_samp_factor) / compptr->h_samp_factor),
+ (JDIMENSION) (3 * rgroup_height));
+ /* Copy true buffer row pointers into the middle of the fake row array */
+***************
+*** 346,352 ****
+ ci++, compptr++) {
+ prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
+ cinfo->max_h_samp_factor) / compptr->h_samp_factor),
+ (JDIMENSION) cinfo->max_v_samp_factor);
+ }
+--- 346,352 ----
+ ci++, compptr++) {
+ prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! (JDIMENSION) (((long) compptr->width_in_data_units * cinfo->data_unit *
+ cinfo->max_h_samp_factor) / compptr->h_samp_factor),
+ (JDIMENSION) cinfo->max_v_samp_factor);
+ }
+diff -cN ../jpeg-6b/jcsample.c ./jcsample.c
+*** ../jpeg-6b/jcsample.c Sat Jan 6 18:25:54 1996
+--- ./jcsample.c Tue Apr 27 14:58:20 1999
+***************
+*** 1,7 ****
+ /*
+ * jcsample.c
+ *
+! * Copyright (C) 1991-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jcsample.c
+ *
+! * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 142,148 ****
+ {
+ int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
+ JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
+! JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
+ JSAMPROW inptr, outptr;
+ INT32 outvalue;
+
+--- 142,148 ----
+ {
+ int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
+ JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
+! JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit;
+ JSAMPROW inptr, outptr;
+ INT32 outvalue;
+
+***************
+*** 192,198 ****
+ cinfo->max_v_samp_factor, cinfo->image_width);
+ /* Edge-expand */
+ expand_right_edge(output_data, cinfo->max_v_samp_factor,
+! cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
+ }
+
+
+--- 192,198 ----
+ cinfo->max_v_samp_factor, cinfo->image_width);
+ /* Edge-expand */
+ expand_right_edge(output_data, cinfo->max_v_samp_factor,
+! cinfo->image_width, compptr->width_in_data_units * cinfo->data_unit);
+ }
+
+
+***************
+*** 214,220 ****
+ {
+ int outrow;
+ JDIMENSION outcol;
+! JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
+ register JSAMPROW inptr, outptr;
+ register int bias;
+
+--- 214,220 ----
+ {
+ int outrow;
+ JDIMENSION outcol;
+! JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit;
+ register JSAMPROW inptr, outptr;
+ register int bias;
+
+***************
+*** 251,257 ****
+ {
+ int inrow, outrow;
+ JDIMENSION outcol;
+! JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
+ register JSAMPROW inptr0, inptr1, outptr;
+ register int bias;
+
+--- 251,257 ----
+ {
+ int inrow, outrow;
+ JDIMENSION outcol;
+! JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit;
+ register JSAMPROW inptr0, inptr1, outptr;
+ register int bias;
+
+***************
+*** 294,300 ****
+ {
+ int inrow, outrow;
+ JDIMENSION colctr;
+! JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
+ register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
+ INT32 membersum, neighsum, memberscale, neighscale;
+
+--- 294,300 ----
+ {
+ int inrow, outrow;
+ JDIMENSION colctr;
+! JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit;
+ register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
+ INT32 membersum, neighsum, memberscale, neighscale;
+
+***************
+*** 394,400 ****
+ {
+ int outrow;
+ JDIMENSION colctr;
+! JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
+ register JSAMPROW inptr, above_ptr, below_ptr, outptr;
+ INT32 membersum, neighsum, memberscale, neighscale;
+ int colsum, lastcolsum, nextcolsum;
+--- 394,400 ----
+ {
+ int outrow;
+ JDIMENSION colctr;
+! JDIMENSION output_cols = compptr->width_in_data_units * cinfo->data_unit;
+ register JSAMPROW inptr, above_ptr, below_ptr, outptr;
+ INT32 membersum, neighsum, memberscale, neighscale;
+ int colsum, lastcolsum, nextcolsum;
+diff -cN ../jpeg-6b/jcscale.c ./jcscale.c
+*** ../jpeg-6b/jcscale.c
+--- ./jcscale.c Tue Apr 27 14:58:21 1999
+***************
+*** 0 ****
+--- 1,62 ----
++ /*
++ * jcscale.c
++ *
++ * Copyright (C) 1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains sample downscaling by 2^Pt for lossless JPEG.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossls.h" /* Private declarations for lossless codec */
++
++
++ #ifdef C_LOSSLESS_SUPPORTED
++
++ METHODDEF(void)
++ simple_downscale(j_compress_ptr cinfo,
++ JSAMPROW input_buf, JSAMPROW output_buf, JDIMENSION width)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++ int xindex;
++
++ for (xindex = 0; xindex < width; xindex++)
++ output_buf[xindex] = (JSAMPLE) RIGHT_SHIFT(GETJSAMPLE(input_buf[xindex]),
++ cinfo->Al);
++ }
++
++
++ METHODDEF(void)
++ noscale(j_compress_ptr cinfo,
++ JSAMPROW input_buf, JSAMPROW output_buf, JDIMENSION width)
++ {
++ MEMCOPY(output_buf, input_buf, width * SIZEOF(JSAMPLE));
++ return;
++ }
++
++
++ METHODDEF(void)
++ scaler_start_pass (j_compress_ptr cinfo)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++
++ /* Set scaler function based on Pt */
++ if (cinfo->Al)
++ losslsc->scaler_scale = simple_downscale;
++ else
++ losslsc->scaler_scale = noscale;
++ }
++
++
++ GLOBAL(void)
++ jinit_c_scaler (j_compress_ptr cinfo)
++ {
++ j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec;
++
++ losslsc->scaler_start_pass = scaler_start_pass;
++ }
++
++ #endif /* C_LOSSLESS_SUPPORTED */
+diff -cN ../jpeg-6b/jcshuff.c ./jcshuff.c
+*** ../jpeg-6b/jcshuff.c
+--- ./jcshuff.c Tue Apr 27 14:58:21 1999
+***************
+*** 0 ****
+--- 1,661 ----
++ /*
++ * jcshuff.c
++ *
++ * Copyright (C) 1991-1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains Huffman entropy encoding routines for sequential JPEG.
++ *
++ * Much of the complexity here has to do with supporting output suspension.
++ * If the data destination module demands suspension, we want to be able to
++ * back up to the start of the current MCU. To do this, we copy state
++ * variables into local working storage, and update them back to the
++ * permanent JPEG objects only upon successful completion of an MCU.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossy.h" /* Private declarations for lossy codec */
++ #include "jchuff.h" /* Declarations shared with jc*huff.c */
++
++
++ /* Expanded entropy encoder object for Huffman encoding.
++ *
++ * The savable_state subrecord contains fields that change within an MCU,
++ * but must not be updated permanently until we complete the MCU.
++ */
++
++ typedef struct {
++ INT32 put_buffer; /* current bit-accumulation buffer */
++ int put_bits; /* # of bits now in it */
++ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
++ } savable_state;
++
++ /* This macro is to work around compilers with missing or broken
++ * structure assignment. You'll need to fix this code if you have
++ * such a compiler and you change MAX_COMPS_IN_SCAN.
++ */
++
++ #ifndef NO_STRUCT_ASSIGN
++ #define ASSIGN_STATE(dest,src) ((dest) = (src))
++ #else
++ #if MAX_COMPS_IN_SCAN == 4
++ #define ASSIGN_STATE(dest,src) \
++ ((dest).put_buffer = (src).put_buffer, \
++ (dest).put_bits = (src).put_bits, \
++ (dest).last_dc_val[0] = (src).last_dc_val[0], \
++ (dest).last_dc_val[1] = (src).last_dc_val[1], \
++ (dest).last_dc_val[2] = (src).last_dc_val[2], \
++ (dest).last_dc_val[3] = (src).last_dc_val[3])
++ #endif
++ #endif
++
++
++ typedef struct {
++ savable_state saved; /* Bit buffer & DC state at start of MCU */
++
++ /* These fields are NOT loaded into local working state. */
++ unsigned int restarts_to_go; /* MCUs left in this restart interval */
++ int next_restart_num; /* next restart number to write (0-7) */
++
++ /* Pointers to derived tables (these workspaces have image lifespan) */
++ c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
++ c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
++
++ #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
++ long * dc_count_ptrs[NUM_HUFF_TBLS];
++ long * ac_count_ptrs[NUM_HUFF_TBLS];
++ #endif
++ } shuff_entropy_encoder;
++
++ typedef shuff_entropy_encoder * shuff_entropy_ptr;
++
++ /* Working state while writing an MCU.
++ * This struct contains all the fields that are needed by subroutines.
++ */
++
++ typedef struct {
++ JOCTET * next_output_byte; /* => next byte to write in buffer */
++ size_t free_in_buffer; /* # of byte spaces remaining in buffer */
++ savable_state cur; /* Current bit buffer & DC state */
++ j_compress_ptr cinfo; /* dump_buffer needs access to this */
++ } working_state;
++
++
++ /* Forward declarations */
++ METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
++ JBLOCKROW *MCU_data));
++ METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
++ #ifdef ENTROPY_OPT_SUPPORTED
++ METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
++ JBLOCKROW *MCU_data));
++ METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
++ #endif
++
++
++ /*
++ * Initialize for a Huffman-compressed scan.
++ * If gather_statistics is TRUE, we do not output anything during the scan,
++ * just count the Huffman symbols used and generate Huffman code tables.
++ */
++
++ METHODDEF(void)
++ start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
++ {
++ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
++ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
++ int ci, dctbl, actbl;
++ jpeg_component_info * compptr;
++
++ if (gather_statistics) {
++ #ifdef ENTROPY_OPT_SUPPORTED
++ lossyc->entropy_encode_mcu = encode_mcu_gather;
++ lossyc->pub.entropy_finish_pass = finish_pass_gather;
++ #else
++ ERREXIT(cinfo, JERR_NOT_COMPILED);
++ #endif
++ } else {
++ lossyc->entropy_encode_mcu = encode_mcu_huff;
++ lossyc->pub.entropy_finish_pass = finish_pass_huff;
++ }
++
++ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
++ compptr = cinfo->cur_comp_info[ci];
++ dctbl = compptr->dc_tbl_no;
++ actbl = compptr->ac_tbl_no;
++ if (gather_statistics) {
++ #ifdef ENTROPY_OPT_SUPPORTED
++ /* Check for invalid table indexes */
++ /* (make_c_derived_tbl does this in the other path) */
++ if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
++ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
++ if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
++ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
++ /* Allocate and zero the statistics tables */
++ /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
++ if (entropy->dc_count_ptrs[dctbl] == NULL)
++ entropy->dc_count_ptrs[dctbl] = (long *)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ 257 * SIZEOF(long));
++ MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
++ if (entropy->ac_count_ptrs[actbl] == NULL)
++ entropy->ac_count_ptrs[actbl] = (long *)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ 257 * SIZEOF(long));
++ MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
++ #endif
++ } else {
++ /* Compute derived values for Huffman tables */
++ /* We may do this more than once for a table, but it's not expensive */
++ jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
++ & entropy->dc_derived_tbls[dctbl]);
++ jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
++ & entropy->ac_derived_tbls[actbl]);
++ }
++ /* Initialize DC predictions to 0 */
++ entropy->saved.last_dc_val[ci] = 0;
++ }
++
++ /* Initialize bit buffer to empty */
++ entropy->saved.put_buffer = 0;
++ entropy->saved.put_bits = 0;
++
++ /* Initialize restart stuff */
++ entropy->restarts_to_go = cinfo->restart_interval;
++ entropy->next_restart_num = 0;
++ }
++
++
++ /* Outputting bytes to the file */
++
++ /* Emit a byte, taking 'action' if must suspend. */
++ #define emit_byte(state,val,action) \
++ { *(state)->next_output_byte++ = (JOCTET) (val); \
++ if (--(state)->free_in_buffer == 0) \
++ if (! dump_buffer(state)) \
++ { action; } }
++
++
++ LOCAL(boolean)
++ dump_buffer (working_state * state)
++ /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
++ {
++ struct jpeg_destination_mgr * dest = state->cinfo->dest;
++
++ if (! (*dest->empty_output_buffer) (state->cinfo))
++ return FALSE;
++ /* After a successful buffer dump, must reset buffer pointers */
++ state->next_output_byte = dest->next_output_byte;
++ state->free_in_buffer = dest->free_in_buffer;
++ return TRUE;
++ }
++
++
++ /* Outputting bits to the file */
++
++ /* Only the right 24 bits of put_buffer are used; the valid bits are
++ * left-justified in this part. At most 16 bits can be passed to emit_bits
++ * in one call, and we never retain more than 7 bits in put_buffer
++ * between calls, so 24 bits are sufficient.
++ */
++
++ INLINE
++ LOCAL(boolean)
++ emit_bits (working_state * state, unsigned int code, int size)
++ /* Emit some bits; return TRUE if successful, FALSE if must suspend */
++ {
++ /* This routine is heavily used, so it's worth coding tightly. */
++ register INT32 put_buffer = (INT32) code;
++ register int put_bits = state->cur.put_bits;
++
++ /* if size is 0, caller used an invalid Huffman table entry */
++ if (size == 0)
++ ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
++
++ put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
++
++ put_bits += size; /* new number of bits in buffer */
++
++ put_buffer <<= 24 - put_bits; /* align incoming bits */
++
++ put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
++
++ while (put_bits >= 8) {
++ int c = (int) ((put_buffer >> 16) & 0xFF);
++
++ emit_byte(state, c, return FALSE);
++ if (c == 0xFF) { /* need to stuff a zero byte? */
++ emit_byte(state, 0, return FALSE);
++ }
++ put_buffer <<= 8;
++ put_bits -= 8;
++ }
++
++ state->cur.put_buffer = put_buffer; /* update state variables */
++ state->cur.put_bits = put_bits;
++
++ return TRUE;
++ }
++
++
++ LOCAL(boolean)
++ flush_bits (working_state * state)
++ {
++ if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
++ return FALSE;
++ state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
++ state->cur.put_bits = 0;
++ return TRUE;
++ }
++
++
++ /* Encode a single block's worth of coefficients */
++
++ LOCAL(boolean)
++ encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
++ c_derived_tbl *dctbl, c_derived_tbl *actbl)
++ {
++ register int temp, temp2;
++ register int nbits;
++ register int k, r, i;
++
++ /* Encode the DC coefficient difference per section F.1.2.1 */
++
++ temp = temp2 = block[0] - last_dc_val;
++
++ if (temp < 0) {
++ temp = -temp; /* temp is abs value of input */
++ /* For a negative input, want temp2 = bitwise complement of abs(input) */
++ /* This code assumes we are on a two's complement machine */
++ temp2--;
++ }
++
++ /* Find the number of bits needed for the magnitude of the coefficient */
++ nbits = 0;
++ while (temp) {
++ nbits++;
++ temp >>= 1;
++ }
++ /* Check for out-of-range coefficient values.
++ * Since we're encoding a difference, the range limit is twice as much.
++ */
++ if (nbits > MAX_COEF_BITS+1)
++ ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
++
++ /* Emit the Huffman-coded symbol for the number of bits */
++ if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
++ return FALSE;
++
++ /* Emit that number of bits of the value, if positive, */
++ /* or the complement of its magnitude, if negative. */
++ if (nbits) /* emit_bits rejects calls with size 0 */
++ if (! emit_bits(state, (unsigned int) temp2, nbits))
++ return FALSE;
++
++ /* Encode the AC coefficients per section F.1.2.2 */
++
++ r = 0; /* r = run length of zeros */
++
++ for (k = 1; k < DCTSIZE2; k++) {
++ if ((temp = block[jpeg_natural_order[k]]) == 0) {
++ r++;
++ } else {
++ /* if run length > 15, must emit special run-length-16 codes (0xF0) */
++ while (r > 15) {
++ if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
++ return FALSE;
++ r -= 16;
++ }
++
++ temp2 = temp;
++ if (temp < 0) {
++ temp = -temp; /* temp is abs value of input */
++ /* This code assumes we are on a two's complement machine */
++ temp2--;
++ }
++
++ /* Find the number of bits needed for the magnitude of the coefficient */
++ nbits = 1; /* there must be at least one 1 bit */
++ while ((temp >>= 1))
++ nbits++;
++ /* Check for out-of-range coefficient values */
++ if (nbits > MAX_COEF_BITS)
++ ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
++
++ /* Emit Huffman symbol for run length / number of bits */
++ i = (r << 4) + nbits;
++ if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
++ return FALSE;
++
++ /* Emit that number of bits of the value, if positive, */
++ /* or the complement of its magnitude, if negative. */
++ if (! emit_bits(state, (unsigned int) temp2, nbits))
++ return FALSE;
++
++ r = 0;
++ }
++ }
++
++ /* If the last coef(s) were zero, emit an end-of-block code */
++ if (r > 0)
++ if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
++ return FALSE;
++
++ return TRUE;
++ }
++
++
++ /*
++ * Emit a restart marker & resynchronize predictions.
++ */
++
++ LOCAL(boolean)
++ emit_restart (working_state * state, int restart_num)
++ {
++ int ci;
++
++ if (! flush_bits(state))
++ return FALSE;
++
++ emit_byte(state, 0xFF, return FALSE);
++ emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
++
++ /* Re-initialize DC predictions to 0 */
++ for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
++ state->cur.last_dc_val[ci] = 0;
++
++ /* The restart counter is not updated until we successfully write the MCU. */
++
++ return TRUE;
++ }
++
++
++ /*
++ * Encode and output one MCU's worth of Huffman-compressed coefficients.
++ */
++
++ METHODDEF(boolean)
++ encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
++ {
++ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
++ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
++ working_state state;
++ int blkn, ci;
++ jpeg_component_info * compptr;
++
++ /* Load up working state */
++ state.next_output_byte = cinfo->dest->next_output_byte;
++ state.free_in_buffer = cinfo->dest->free_in_buffer;
++ ASSIGN_STATE(state.cur, entropy->saved);
++ state.cinfo = cinfo;
++
++ /* Emit restart marker if needed */
++ if (cinfo->restart_interval) {
++ if (entropy->restarts_to_go == 0)
++ if (! emit_restart(&state, entropy->next_restart_num))
++ return FALSE;
++ }
++
++ /* Encode the MCU data blocks */
++ for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
++ ci = cinfo->MCU_membership[blkn];
++ compptr = cinfo->cur_comp_info[ci];
++ if (! encode_one_block(&state,
++ MCU_data[blkn][0], state.cur.last_dc_val[ci],
++ entropy->dc_derived_tbls[compptr->dc_tbl_no],
++ entropy->ac_derived_tbls[compptr->ac_tbl_no]))
++ return FALSE;
++ /* Update last_dc_val */
++ state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
++ }
++
++ /* Completed MCU, so update state */
++ cinfo->dest->next_output_byte = state.next_output_byte;
++ cinfo->dest->free_in_buffer = state.free_in_buffer;
++ ASSIGN_STATE(entropy->saved, state.cur);
++
++ /* Update restart-interval state too */
++ if (cinfo->restart_interval) {
++ if (entropy->restarts_to_go == 0) {
++ entropy->restarts_to_go = cinfo->restart_interval;
++ entropy->next_restart_num++;
++ entropy->next_restart_num &= 7;
++ }
++ entropy->restarts_to_go--;
++ }
++
++ return TRUE;
++ }
++
++
++ /*
++ * Finish up at the end of a Huffman-compressed scan.
++ */
++
++ METHODDEF(void)
++ finish_pass_huff (j_compress_ptr cinfo)
++ {
++ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
++ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
++ working_state state;
++
++ /* Load up working state ... flush_bits needs it */
++ state.next_output_byte = cinfo->dest->next_output_byte;
++ state.free_in_buffer = cinfo->dest->free_in_buffer;
++ ASSIGN_STATE(state.cur, entropy->saved);
++ state.cinfo = cinfo;
++
++ /* Flush out the last data */
++ if (! flush_bits(&state))
++ ERREXIT(cinfo, JERR_CANT_SUSPEND);
++
++ /* Update state */
++ cinfo->dest->next_output_byte = state.next_output_byte;
++ cinfo->dest->free_in_buffer = state.free_in_buffer;
++ ASSIGN_STATE(entropy->saved, state.cur);
++ }
++
++
++ /*
++ * Huffman coding optimization.
++ *
++ * We first scan the supplied data and count the number of uses of each symbol
++ * that is to be Huffman-coded. (This process MUST agree with the code above.)
++ * Then we build a Huffman coding tree for the observed counts.
++ * Symbols which are not needed at all for the particular image are not
++ * assigned any code, which saves space in the DHT marker as well as in
++ * the compressed data.
++ */
++
++ #ifdef ENTROPY_OPT_SUPPORTED
++
++
++ /* Process a single block's worth of coefficients */
++
++ LOCAL(void)
++ htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
++ long dc_counts[], long ac_counts[])
++ {
++ register int temp;
++ register int nbits;
++ register int k, r;
++
++ /* Encode the DC coefficient difference per section F.1.2.1 */
++
++ temp = block[0] - last_dc_val;
++ if (temp < 0)
++ temp = -temp;
++
++ /* Find the number of bits needed for the magnitude of the coefficient */
++ nbits = 0;
++ while (temp) {
++ nbits++;
++ temp >>= 1;
++ }
++ /* Check for out-of-range coefficient values.
++ * Since we're encoding a difference, the range limit is twice as much.
++ */
++ if (nbits > MAX_COEF_BITS+1)
++ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
++
++ /* Count the Huffman symbol for the number of bits */
++ dc_counts[nbits]++;
++
++ /* Encode the AC coefficients per section F.1.2.2 */
++
++ r = 0; /* r = run length of zeros */
++
++ for (k = 1; k < DCTSIZE2; k++) {
++ if ((temp = block[jpeg_natural_order[k]]) == 0) {
++ r++;
++ } else {
++ /* if run length > 15, must emit special run-length-16 codes (0xF0) */
++ while (r > 15) {
++ ac_counts[0xF0]++;
++ r -= 16;
++ }
++
++ /* Find the number of bits needed for the magnitude of the coefficient */
++ if (temp < 0)
++ temp = -temp;
++
++ /* Find the number of bits needed for the magnitude of the coefficient */
++ nbits = 1; /* there must be at least one 1 bit */
++ while ((temp >>= 1))
++ nbits++;
++ /* Check for out-of-range coefficient values */
++ if (nbits > MAX_COEF_BITS)
++ ERREXIT(cinfo, JERR_BAD_DCT_COEF);
++
++ /* Count Huffman symbol for run length / number of bits */
++ ac_counts[(r << 4) + nbits]++;
++
++ r = 0;
++ }
++ }
++
++ /* If the last coef(s) were zero, emit an end-of-block code */
++ if (r > 0)
++ ac_counts[0]++;
++ }
++
++
++ /*
++ * Trial-encode one MCU's worth of Huffman-compressed coefficients.
++ * No data is actually output, so no suspension return is possible.
++ */
++
++ METHODDEF(boolean)
++ encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
++ {
++ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
++ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
++ int blkn, ci;
++ jpeg_component_info * compptr;
++
++ /* Take care of restart intervals if needed */
++ if (cinfo->restart_interval) {
++ if (entropy->restarts_to_go == 0) {
++ /* Re-initialize DC predictions to 0 */
++ for (ci = 0; ci < cinfo->comps_in_scan; ci++)
++ entropy->saved.last_dc_val[ci] = 0;
++ /* Update restart state */
++ entropy->restarts_to_go = cinfo->restart_interval;
++ }
++ entropy->restarts_to_go--;
++ }
++
++ for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
++ ci = cinfo->MCU_membership[blkn];
++ compptr = cinfo->cur_comp_info[ci];
++ htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
++ entropy->dc_count_ptrs[compptr->dc_tbl_no],
++ entropy->ac_count_ptrs[compptr->ac_tbl_no]);
++ entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
++ }
++
++ return TRUE;
++ }
++
++
++ /*
++ * Finish up a statistics-gathering pass and create the new Huffman tables.
++ */
++
++ METHODDEF(void)
++ finish_pass_gather (j_compress_ptr cinfo)
++ {
++ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
++ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
++ int ci, dctbl, actbl;
++ jpeg_component_info * compptr;
++ JHUFF_TBL **htblptr;
++ boolean did_dc[NUM_HUFF_TBLS];
++ boolean did_ac[NUM_HUFF_TBLS];
++
++ /* It's important not to apply jpeg_gen_optimal_table more than once
++ * per table, because it clobbers the input frequency counts!
++ */
++ MEMZERO(did_dc, SIZEOF(did_dc));
++ MEMZERO(did_ac, SIZEOF(did_ac));
++
++ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
++ compptr = cinfo->cur_comp_info[ci];
++ dctbl = compptr->dc_tbl_no;
++ actbl = compptr->ac_tbl_no;
++ if (! did_dc[dctbl]) {
++ htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
++ if (*htblptr == NULL)
++ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
++ jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
++ did_dc[dctbl] = TRUE;
++ }
++ if (! did_ac[actbl]) {
++ htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
++ if (*htblptr == NULL)
++ *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
++ jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
++ did_ac[actbl] = TRUE;
++ }
++ }
++ }
++
++
++ #endif /* ENTROPY_OPT_SUPPORTED */
++
++
++ METHODDEF(boolean)
++ need_optimization_pass (j_compress_ptr cinfo)
++ {
++ return TRUE;
++ }
++
++
++ /*
++ * Module initialization routine for Huffman entropy encoding.
++ */
++
++ GLOBAL(void)
++ jinit_shuff_encoder (j_compress_ptr cinfo)
++ {
++ j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
++ shuff_entropy_ptr entropy;
++ int i;
++
++ entropy = (shuff_entropy_ptr)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ SIZEOF(shuff_entropy_encoder));
++ lossyc->entropy_private = (struct jpeg_entropy_encoder *) entropy;
++ lossyc->pub.entropy_start_pass = start_pass_huff;
++ lossyc->pub.need_optimization_pass = need_optimization_pass;
++
++ /* Mark tables unallocated */
++ for (i = 0; i < NUM_HUFF_TBLS; i++) {
++ entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
++ #ifdef ENTROPY_OPT_SUPPORTED
++ entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
++ #endif
++ }
++ }
+diff -cN ../jpeg-6b/jctrans.c ./jctrans.c
+*** ../jpeg-6b/jctrans.c Sat Feb 21 15:03:25 1998
+--- ./jctrans.c Tue Apr 27 14:58:21 1999
+***************
+*** 13,23 ****
+--- 13,26 ----
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
++ #include "jlossy.h" /* Private declarations for lossy codec */
+
+
+ /* Forward declarations */
+ LOCAL(void) transencode_master_selection
+ JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
++ LOCAL(void) transencode_codec
++ JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
+ LOCAL(void) transencode_coef_controller
+ JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
+
+***************
+*** 158,163 ****
+--- 161,167 ----
+ transencode_master_selection (j_compress_ptr cinfo,
+ jvirt_barray_ptr * coef_arrays)
+ {
++ cinfo->data_unit = DCTSIZE;
+ /* Although we don't actually use input_components for transcoding,
+ * jcmaster.c's initial_setup will complain if input_components is 0.
+ */
+***************
+*** 165,186 ****
+ /* Initialize master control (includes parameter checking/processing) */
+ jinit_c_master_control(cinfo, TRUE /* transcode only */);
+
+! /* Entropy encoding: either Huffman or arithmetic coding. */
+! if (cinfo->arith_code) {
+! ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+! } else {
+! if (cinfo->progressive_mode) {
+! #ifdef C_PROGRESSIVE_SUPPORTED
+! jinit_phuff_encoder(cinfo);
+! #else
+! ERREXIT(cinfo, JERR_NOT_COMPILED);
+! #endif
+! } else
+! jinit_huff_encoder(cinfo);
+! }
+!
+! /* We need a special coefficient buffer controller. */
+! transencode_coef_controller(cinfo, coef_arrays);
+
+ jinit_marker_writer(cinfo);
+
+--- 169,176 ----
+ /* Initialize master control (includes parameter checking/processing) */
+ jinit_c_master_control(cinfo, TRUE /* transcode only */);
+
+! /* We need a special compression codec. */
+! transencode_codec(cinfo, coef_arrays);
+
+ jinit_marker_writer(cinfo);
+
+***************
+*** 206,213 ****
+ /* Private buffer controller object */
+
+ typedef struct {
+- struct jpeg_c_coef_controller pub; /* public fields */
+-
+ JDIMENSION iMCU_row_num; /* iMCU row # within image */
+ JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
+ int MCU_vert_offset; /* counts MCU rows within iMCU row */
+--- 196,201 ----
+***************
+*** 217,226 ****
+ jvirt_barray_ptr * whole_image;
+
+ /* Workspace for constructing dummy blocks at right/bottom edges. */
+! JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
+! } my_coef_controller;
+
+! typedef my_coef_controller * my_coef_ptr;
+
+
+ LOCAL(void)
+--- 205,214 ----
+ jvirt_barray_ptr * whole_image;
+
+ /* Workspace for constructing dummy blocks at right/bottom edges. */
+! JBLOCKROW dummy_buffer[C_MAX_DATA_UNITS_IN_MCU];
+! } c_coef_controller;
+
+! typedef c_coef_controller * c_coef_ptr;
+
+
+ LOCAL(void)
+***************
+*** 227,233 ****
+ start_iMCU_row (j_compress_ptr cinfo)
+ /* Reset within-iMCU-row counters for a new row */
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+--- 215,222 ----
+ start_iMCU_row (j_compress_ptr cinfo)
+ /* Reset within-iMCU-row counters for a new row */
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+***************
+*** 254,260 ****
+ METHODDEF(void)
+ start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ if (pass_mode != JBUF_CRANK_DEST)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+--- 243,250 ----
+ METHODDEF(void)
+ start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+
+ if (pass_mode != JBUF_CRANK_DEST)
+ ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+***************
+*** 277,283 ****
+ METHODDEF(boolean)
+ compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+--- 267,274 ----
+ METHODDEF(boolean)
+ compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! c_coef_ptr coef = (c_coef_ptr) lossyc->coef_private;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+***************
+*** 284,290 ****
+ int blkn, ci, xindex, yindex, yoffset, blockcnt;
+ JDIMENSION start_col;
+ JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
+! JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
+ JBLOCKROW buffer_ptr;
+ jpeg_component_info *compptr;
+
+--- 275,281 ----
+ int blkn, ci, xindex, yindex, yoffset, blockcnt;
+ JDIMENSION start_col;
+ JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
+! JBLOCKROW MCU_buffer[C_MAX_DATA_UNITS_IN_MCU];
+ JBLOCKROW buffer_ptr;
+ jpeg_component_info *compptr;
+
+***************
+*** 334,340 ****
+ }
+ }
+ /* Try to write the MCU. */
+! if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->mcu_ctr = MCU_col_num;
+--- 325,331 ----
+ }
+ }
+ /* Try to write the MCU. */
+! if (! (*lossyc->entropy_encode_mcu) (cinfo, MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->mcu_ctr = MCU_col_num;
+***************
+*** 355,361 ****
+ * Initialize coefficient buffer controller.
+ *
+ * Each passed coefficient array must be the right size for that
+! * coefficient: width_in_blocks wide and height_in_blocks high,
+ * with unitheight at least v_samp_factor.
+ */
+
+--- 346,352 ----
+ * Initialize coefficient buffer controller.
+ *
+ * Each passed coefficient array must be the right size for that
+! * coefficient: width_in_data_units wide and height_in_data_units high,
+ * with unitheight at least v_samp_factor.
+ */
+
+***************
+*** 363,378 ****
+ transencode_coef_controller (j_compress_ptr cinfo,
+ jvirt_barray_ptr * coef_arrays)
+ {
+! my_coef_ptr coef;
+ JBLOCKROW buffer;
+ int i;
+
+! coef = (my_coef_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! SIZEOF(my_coef_controller));
+! cinfo->coef = (struct jpeg_c_coef_controller *) coef;
+! coef->pub.start_pass = start_pass_coef;
+! coef->pub.compress_data = compress_output;
+
+ /* Save pointer to virtual arrays */
+ coef->whole_image = coef_arrays;
+--- 354,368 ----
+ transencode_coef_controller (j_compress_ptr cinfo,
+ jvirt_barray_ptr * coef_arrays)
+ {
+! j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
+! c_coef_ptr coef;
+ JBLOCKROW buffer;
+ int i;
+
+! coef = (c_coef_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! SIZEOF(c_coef_controller));
+! lossyc->coef_private = (struct jpeg_c_coef_controller *) coef;
+
+ /* Save pointer to virtual arrays */
+ coef->whole_image = coef_arrays;
+***************
+*** 380,388 ****
+ /* Allocate and pre-zero space for dummy DCT blocks. */
+ buffer = (JBLOCKROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
+! jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
+! for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
+ coef->dummy_buffer[i] = buffer + i;
+ }
+ }
+--- 370,420 ----
+ /* Allocate and pre-zero space for dummy DCT blocks. */
+ buffer = (JBLOCKROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! C_MAX_DATA_UNITS_IN_MCU * SIZEOF(JBLOCK));
+! jzero_far((void FAR *) buffer, C_MAX_DATA_UNITS_IN_MCU * SIZEOF(JBLOCK));
+! for (i = 0; i < C_MAX_DATA_UNITS_IN_MCU; i++) {
+ coef->dummy_buffer[i] = buffer + i;
+ }
++ }
++
++
++ /*
++ * Initialize the transencoer codec.
++ * This is called only once, during master selection.
++ */
++
++ LOCAL(void)
++ transencode_codec (j_compress_ptr cinfo,
++ jvirt_barray_ptr * coef_arrays)
++ {
++ j_lossy_c_ptr lossyc;
++
++ /* Create subobject in permanent pool */
++ lossyc = (j_lossy_c_ptr)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
++ SIZEOF(jpeg_lossy_c_codec));
++ cinfo->codec = (struct jpeg_c_codec *) lossyc;
++
++ /* Initialize sub-modules */
++
++ /* Entropy encoding: either Huffman or arithmetic coding. */
++ if (cinfo->arith_code) {
++ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
++ } else {
++ if (cinfo->process == JPROC_PROGRESSIVE) {
++ #ifdef C_PROGRESSIVE_SUPPORTED
++ jinit_phuff_encoder(cinfo);
++ #else
++ ERREXIT(cinfo, JERR_NOT_COMPILED);
++ #endif
++ } else
++ jinit_shuff_encoder(cinfo);
++ }
++
++ /* We need a special coefficient buffer controller. */
++ transencode_coef_controller(cinfo, coef_arrays);
++
++ /* Initialize method pointers */
++ lossyc->pub.start_pass = start_pass_coef;
++ lossyc->pub.compress_data = compress_output;
+ }
+diff -cN ../jpeg-6b/jdapimin.c ./jdapimin.c
+*** ../jpeg-6b/jdapimin.c Sat Jan 24 16:22:44 1998
+--- ./jdapimin.c Tue Apr 27 14:58:21 1999
+***************
+*** 149,156 ****
+ else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
+ cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
+ else {
+! TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
+! cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
+ }
+ }
+ /* Always guess RGB is proper output colorspace. */
+--- 149,162 ----
+ else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
+ cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
+ else {
+! if (cinfo->process == JPROC_LOSSLESS) {
+! TRACEMS3(cinfo, 1, JTRC_UNKNOWN_LOSSLESS_IDS, cid0, cid1, cid2);
+! cinfo->jpeg_color_space = JCS_RGB; /* assume it's RGB */
+! }
+! else { /* Lossy processes */
+! TRACEMS3(cinfo, 1, JTRC_UNKNOWN_LOSSY_IDS, cid0, cid1, cid2);
+! cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
+! }
+ }
+ }
+ /* Always guess RGB is proper output colorspace. */
+diff -cN ../jpeg-6b/jdapistd.c ./jdapistd.c
+*** ../jpeg-6b/jdapistd.c Sat Jan 6 18:26:28 1996
+--- ./jdapistd.c Tue Apr 27 14:58:22 1999
+***************
+*** 1,7 ****
+ /*
+ * jdapistd.c
+ *
+! * Copyright (C) 1994-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jdapistd.c
+ *
+! * Copyright (C) 1994-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 202,213 ****
+ }
+
+ /* Verify that at least one iMCU row can be returned. */
+! lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
+ if (max_lines < lines_per_iMCU_row)
+ ERREXIT(cinfo, JERR_BUFFER_SIZE);
+
+ /* Decompress directly into user's buffer. */
+! if (! (*cinfo->coef->decompress_data) (cinfo, data))
+ return 0; /* suspension forced, can do nothing more */
+
+ /* OK, we processed one iMCU row. */
+--- 202,213 ----
+ }
+
+ /* Verify that at least one iMCU row can be returned. */
+! lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_codec_data_unit;
+ if (max_lines < lines_per_iMCU_row)
+ ERREXIT(cinfo, JERR_BUFFER_SIZE);
+
+ /* Decompress directly into user's buffer. */
+! if (! (*cinfo->codec->decompress_data) (cinfo, data))
+ return 0; /* suspension forced, can do nothing more */
+
+ /* OK, we processed one iMCU row. */
+diff -cN ../jpeg-6b/jdcoefct.c ./jdcoefct.c
+*** ../jpeg-6b/jdcoefct.c Mon Oct 27 22:12:10 1997
+--- ./jdcoefct.c Tue Apr 27 14:58:22 1999
+***************
+*** 1,12 ****
+ /*
+ * jdcoefct.c
+ *
+! * Copyright (C) 1994-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the coefficient buffer controller for decompression.
+! * This controller is the top level of the JPEG decompressor proper.
+ * The coefficient buffer lies between entropy decoding and inverse-DCT steps.
+ *
+ * In buffered-image mode, this controller is the interface between
+--- 1,12 ----
+ /*
+ * jdcoefct.c
+ *
+! * Copyright (C) 1994-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains the coefficient buffer controller for decompression.
+! * This controller is the top level of the lossy JPEG decompressor proper.
+ * The coefficient buffer lies between entropy decoding and inverse-DCT steps.
+ *
+ * In buffered-image mode, this controller is the interface between
+***************
+*** 17,22 ****
+--- 17,23 ----
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
++ #include "jlossy.h"
+
+ /* Block smoothing is only applicable for progressive JPEG, so: */
+ #ifndef D_PROGRESSIVE_SUPPORTED
+***************
+*** 26,33 ****
+ /* Private buffer controller object */
+
+ typedef struct {
+- struct jpeg_d_coef_controller pub; /* public fields */
+-
+ /* These variables keep track of the current location of the input side. */
+ /* cinfo->input_iMCU_row is also used for this. */
+ JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
+--- 27,32 ----
+***************
+*** 37,43 ****
+ /* The output side's location is represented by cinfo->output_iMCU_row. */
+
+ /* In single-pass modes, it's sufficient to buffer just one MCU.
+! * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
+ * and let the entropy decoder write into that workspace each time.
+ * (On 80x86, the workspace is FAR even though it's not really very big;
+ * this is to keep the module interfaces unchanged when a large coefficient
+--- 36,42 ----
+ /* The output side's location is represented by cinfo->output_iMCU_row. */
+
+ /* In single-pass modes, it's sufficient to buffer just one MCU.
+! * We allocate a workspace of D_MAX_DATA_UNITS_IN_MCU coefficient blocks,
+ * and let the entropy decoder write into that workspace each time.
+ * (On 80x86, the workspace is FAR even though it's not really very big;
+ * this is to keep the module interfaces unchanged when a large coefficient
+***************
+*** 45,51 ****
+ * In multi-pass modes, this array points to the current MCU's blocks
+ * within the virtual arrays; it is used only by the input side.
+ */
+! JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
+
+ #ifdef D_MULTISCAN_FILES_SUPPORTED
+ /* In multi-pass modes, we need a virtual block array for each component. */
+--- 44,50 ----
+ * In multi-pass modes, this array points to the current MCU's blocks
+ * within the virtual arrays; it is used only by the input side.
+ */
+! JBLOCKROW MCU_buffer[D_MAX_DATA_UNITS_IN_MCU];
+
+ #ifdef D_MULTISCAN_FILES_SUPPORTED
+ /* In multi-pass modes, we need a virtual block array for each component. */
+***************
+*** 57,65 ****
+ int * coef_bits_latch;
+ #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
+ #endif
+! } my_coef_controller;
+
+! typedef my_coef_controller * my_coef_ptr;
+
+ /* Forward declarations */
+ METHODDEF(int) decompress_onepass
+--- 56,64 ----
+ int * coef_bits_latch;
+ #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
+ #endif
+! } d_coef_controller;
+
+! typedef d_coef_controller * d_coef_ptr;
+
+ /* Forward declarations */
+ METHODDEF(int) decompress_onepass
+***************
+*** 79,85 ****
+ start_iMCU_row (j_decompress_ptr cinfo)
+ /* Reset within-iMCU-row counters for a new row (input side) */
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+--- 78,85 ----
+ start_iMCU_row (j_decompress_ptr cinfo)
+ /* Reset within-iMCU-row counters for a new row (input side) */
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+
+ /* In an interleaved scan, an MCU row is the same as an iMCU row.
+ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
+***************
+*** 119,132 ****
+ start_output_pass (j_decompress_ptr cinfo)
+ {
+ #ifdef BLOCK_SMOOTHING_SUPPORTED
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+ /* If multipass, check to see whether to use block smoothing on this pass */
+! if (coef->pub.coef_arrays != NULL) {
+ if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
+! coef->pub.decompress_data = decompress_smooth_data;
+ else
+! coef->pub.decompress_data = decompress_data;
+ }
+ #endif
+ cinfo->output_iMCU_row = 0;
+--- 119,133 ----
+ start_output_pass (j_decompress_ptr cinfo)
+ {
+ #ifdef BLOCK_SMOOTHING_SUPPORTED
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+
+ /* If multipass, check to see whether to use block smoothing on this pass */
+! if (lossyd->coef_arrays != NULL) {
+ if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
+! lossyd->pub.decompress_data = decompress_smooth_data;
+ else
+! lossyd->pub.decompress_data = decompress_data;
+ }
+ #endif
+ cinfo->output_iMCU_row = 0;
+***************
+*** 146,152 ****
+ METHODDEF(int)
+ decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+--- 147,154 ----
+ METHODDEF(int)
+ decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+***************
+*** 163,170 ****
+ MCU_col_num++) {
+ /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
+ jzero_far((void FAR *) coef->MCU_buffer[0],
+! (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
+! if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->MCU_ctr = MCU_col_num;
+--- 165,172 ----
+ MCU_col_num++) {
+ /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
+ jzero_far((void FAR *) coef->MCU_buffer[0],
+! (size_t) (cinfo->data_units_in_MCU * SIZEOF(JBLOCK)));
+! if (! (*lossyd->entropy_decode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->MCU_ctr = MCU_col_num;
+***************
+*** 180,193 ****
+ compptr = cinfo->cur_comp_info[ci];
+ /* Don't bother to IDCT an uninteresting component. */
+ if (! compptr->component_needed) {
+! blkn += compptr->MCU_blocks;
+ continue;
+ }
+! inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
+ useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
+ : compptr->last_col_width;
+ output_ptr = output_buf[compptr->component_index] +
+! yoffset * compptr->DCT_scaled_size;
+ start_col = MCU_col_num * compptr->MCU_sample_width;
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ if (cinfo->input_iMCU_row < last_iMCU_row ||
+--- 182,195 ----
+ compptr = cinfo->cur_comp_info[ci];
+ /* Don't bother to IDCT an uninteresting component. */
+ if (! compptr->component_needed) {
+! blkn += compptr->MCU_data_units;
+ continue;
+ }
+! inverse_DCT = lossyd->inverse_DCT[compptr->component_index];
+ useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
+ : compptr->last_col_width;
+ output_ptr = output_buf[compptr->component_index] +
+! yoffset * compptr->codec_data_unit;
+ start_col = MCU_col_num * compptr->MCU_sample_width;
+ for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+ if (cinfo->input_iMCU_row < last_iMCU_row ||
+***************
+*** 197,207 ****
+ (*inverse_DCT) (cinfo, compptr,
+ (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
+ output_ptr, output_col);
+! output_col += compptr->DCT_scaled_size;
+ }
+ }
+ blkn += compptr->MCU_width;
+! output_ptr += compptr->DCT_scaled_size;
+ }
+ }
+ }
+--- 199,209 ----
+ (*inverse_DCT) (cinfo, compptr,
+ (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
+ output_ptr, output_col);
+! output_col += compptr->codec_data_unit;
+ }
+ }
+ blkn += compptr->MCU_width;
+! output_ptr += compptr->codec_data_unit;
+ }
+ }
+ }
+***************
+*** 243,249 ****
+ METHODDEF(int)
+ consume_data (j_decompress_ptr cinfo)
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ int blkn, ci, xindex, yindex, yoffset;
+ JDIMENSION start_col;
+--- 245,252 ----
+ METHODDEF(int)
+ consume_data (j_decompress_ptr cinfo)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+ JDIMENSION MCU_col_num; /* index of current MCU within row */
+ int blkn, ci, xindex, yindex, yoffset;
+ JDIMENSION start_col;
+***************
+*** 282,288 ****
+ }
+ }
+ /* Try to fetch the MCU. */
+! if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->MCU_ctr = MCU_col_num;
+--- 285,291 ----
+ }
+ }
+ /* Try to fetch the MCU. */
+! if (! (*lossyd->entropy_decode_mcu) (cinfo, coef->MCU_buffer)) {
+ /* Suspension forced; update state counters and exit */
+ coef->MCU_vert_offset = yoffset;
+ coef->MCU_ctr = MCU_col_num;
+***************
+*** 314,320 ****
+ METHODDEF(int)
+ decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION block_num;
+ int ci, block_row, block_rows;
+--- 317,324 ----
+ METHODDEF(int)
+ decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION block_num;
+ int ci, block_row, block_rows;
+***************
+*** 349,370 ****
+ block_rows = compptr->v_samp_factor;
+ else {
+ /* NB: can't use last_row_height here; it is input-side-dependent! */
+! block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ }
+! inverse_DCT = cinfo->idct->inverse_DCT[ci];
+ output_ptr = output_buf[ci];
+ /* Loop over all DCT blocks to be processed. */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+ buffer_ptr = buffer[block_row];
+ output_col = 0;
+! for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
+ (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
+ output_ptr, output_col);
+ buffer_ptr++;
+! output_col += compptr->DCT_scaled_size;
+ }
+! output_ptr += compptr->DCT_scaled_size;
+ }
+ }
+
+--- 353,374 ----
+ block_rows = compptr->v_samp_factor;
+ else {
+ /* NB: can't use last_row_height here; it is input-side-dependent! */
+! block_rows = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ }
+! inverse_DCT = lossyd->inverse_DCT[ci];
+ output_ptr = output_buf[ci];
+ /* Loop over all DCT blocks to be processed. */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+ buffer_ptr = buffer[block_row];
+ output_col = 0;
+! for (block_num = 0; block_num < compptr->width_in_data_units; block_num++) {
+ (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
+ output_ptr, output_col);
+ buffer_ptr++;
+! output_col += compptr->codec_data_unit;
+ }
+! output_ptr += compptr->codec_data_unit;
+ }
+ }
+
+***************
+*** 404,410 ****
+ LOCAL(boolean)
+ smoothing_ok (j_decompress_ptr cinfo)
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ boolean smoothing_useful = FALSE;
+ int ci, coefi;
+ jpeg_component_info *compptr;
+--- 408,415 ----
+ LOCAL(boolean)
+ smoothing_ok (j_decompress_ptr cinfo)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+ boolean smoothing_useful = FALSE;
+ int ci, coefi;
+ jpeg_component_info *compptr;
+***************
+*** 412,418 ****
+ int * coef_bits;
+ int * coef_bits_latch;
+
+! if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
+ return FALSE;
+
+ /* Allocate latch area if not already done */
+--- 417,423 ----
+ int * coef_bits;
+ int * coef_bits_latch;
+
+! if (! cinfo->process == JPROC_PROGRESSIVE || cinfo->coef_bits == NULL)
+ return FALSE;
+
+ /* Allocate latch area if not already done */
+***************
+*** 460,466 ****
+ METHODDEF(int)
+ decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
+ {
+! my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION block_num, last_block_column;
+ int ci, block_row, block_rows, access_rows;
+--- 465,472 ----
+ METHODDEF(int)
+ decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! d_coef_ptr coef = (d_coef_ptr) lossyd->coef_private;
+ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
+ JDIMENSION block_num, last_block_column;
+ int ci, block_row, block_rows, access_rows;
+***************
+*** 508,514 ****
+ last_row = FALSE;
+ } else {
+ /* NB: can't use last_row_height here; it is input-side-dependent! */
+! block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ access_rows = block_rows; /* this iMCU row only */
+ last_row = TRUE;
+--- 514,520 ----
+ last_row = FALSE;
+ } else {
+ /* NB: can't use last_row_height here; it is input-side-dependent! */
+! block_rows = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
+ if (block_rows == 0) block_rows = compptr->v_samp_factor;
+ access_rows = block_rows; /* this iMCU row only */
+ last_row = TRUE;
+***************
+*** 537,543 ****
+ Q20 = quanttbl->quantval[Q20_POS];
+ Q11 = quanttbl->quantval[Q11_POS];
+ Q02 = quanttbl->quantval[Q02_POS];
+! inverse_DCT = cinfo->idct->inverse_DCT[ci];
+ output_ptr = output_buf[ci];
+ /* Loop over all DCT blocks to be processed. */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+--- 543,549 ----
+ Q20 = quanttbl->quantval[Q20_POS];
+ Q11 = quanttbl->quantval[Q11_POS];
+ Q02 = quanttbl->quantval[Q02_POS];
+! inverse_DCT = lossyd->inverse_DCT[ci];
+ output_ptr = output_buf[ci];
+ /* Loop over all DCT blocks to be processed. */
+ for (block_row = 0; block_row < block_rows; block_row++) {
+***************
+*** 557,563 ****
+ DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
+ DC7 = DC8 = DC9 = (int) next_block_row[0][0];
+ output_col = 0;
+! last_block_column = compptr->width_in_blocks - 1;
+ for (block_num = 0; block_num <= last_block_column; block_num++) {
+ /* Fetch current DCT block into workspace so we can modify it. */
+ jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
+--- 563,569 ----
+ DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
+ DC7 = DC8 = DC9 = (int) next_block_row[0][0];
+ output_col = 0;
+! last_block_column = compptr->width_in_data_units - 1;
+ for (block_num = 0; block_num <= last_block_column; block_num++) {
+ /* Fetch current DCT block into workspace so we can modify it. */
+ jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
+***************
+*** 654,662 ****
+ DC4 = DC5; DC5 = DC6;
+ DC7 = DC8; DC8 = DC9;
+ buffer_ptr++, prev_block_row++, next_block_row++;
+! output_col += compptr->DCT_scaled_size;
+ }
+! output_ptr += compptr->DCT_scaled_size;
+ }
+ }
+
+--- 660,668 ----
+ DC4 = DC5; DC5 = DC6;
+ DC7 = DC8; DC8 = DC9;
+ buffer_ptr++, prev_block_row++, next_block_row++;
+! output_col += compptr->codec_data_unit;
+ }
+! output_ptr += compptr->codec_data_unit;
+ }
+ }
+
+***************
+*** 675,688 ****
+ GLOBAL(void)
+ jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
+ {
+! my_coef_ptr coef;
+
+! coef = (my_coef_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! SIZEOF(my_coef_controller));
+! cinfo->coef = (struct jpeg_d_coef_controller *) coef;
+! coef->pub.start_input_pass = start_input_pass;
+! coef->pub.start_output_pass = start_output_pass;
+ #ifdef BLOCK_SMOOTHING_SUPPORTED
+ coef->coef_bits_latch = NULL;
+ #endif
+--- 681,695 ----
+ GLOBAL(void)
+ jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! d_coef_ptr coef;
+
+! coef = (d_coef_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! SIZEOF(d_coef_controller));
+! lossyd->coef_private = (void *) coef;
+! lossyd->coef_start_input_pass = start_input_pass;
+! lossyd->coef_start_output_pass = start_output_pass;
+ #ifdef BLOCK_SMOOTHING_SUPPORTED
+ coef->coef_bits_latch = NULL;
+ #endif
+***************
+*** 701,720 ****
+ access_rows = compptr->v_samp_factor;
+ #ifdef BLOCK_SMOOTHING_SUPPORTED
+ /* If block smoothing could be used, need a bigger window */
+! if (cinfo->progressive_mode)
+ access_rows *= 3;
+ #endif
+ coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
+! (JDIMENSION) jround_up((long) compptr->width_in_blocks,
+ (long) compptr->h_samp_factor),
+! (JDIMENSION) jround_up((long) compptr->height_in_blocks,
+ (long) compptr->v_samp_factor),
+ (JDIMENSION) access_rows);
+ }
+! coef->pub.consume_data = consume_data;
+! coef->pub.decompress_data = decompress_data;
+! coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
+ #else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ #endif
+--- 708,727 ----
+ access_rows = compptr->v_samp_factor;
+ #ifdef BLOCK_SMOOTHING_SUPPORTED
+ /* If block smoothing could be used, need a bigger window */
+! if (cinfo->process == JPROC_PROGRESSIVE)
+ access_rows *= 3;
+ #endif
+ coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
+! (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor),
+! (JDIMENSION) jround_up((long) compptr->height_in_data_units,
+ (long) compptr->v_samp_factor),
+ (JDIMENSION) access_rows);
+ }
+! lossyd->pub.consume_data = consume_data;
+! lossyd->pub.decompress_data = decompress_data;
+! lossyd->coef_arrays = coef->whole_image; /* link to virtual arrays */
+ #else
+ ERREXIT(cinfo, JERR_NOT_COMPILED);
+ #endif
+***************
+*** 725,736 ****
+
+ buffer = (JBLOCKROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
+! for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
+ coef->MCU_buffer[i] = buffer + i;
+ }
+! coef->pub.consume_data = dummy_consume_data;
+! coef->pub.decompress_data = decompress_onepass;
+! coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
+ }
+ }
+--- 732,743 ----
+
+ buffer = (JBLOCKROW)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! D_MAX_DATA_UNITS_IN_MCU * SIZEOF(JBLOCK));
+! for (i = 0; i < D_MAX_DATA_UNITS_IN_MCU; i++) {
+ coef->MCU_buffer[i] = buffer + i;
+ }
+! lossyd->pub.consume_data = dummy_consume_data;
+! lossyd->pub.decompress_data = decompress_onepass;
+! lossyd->coef_arrays = NULL; /* flag for no virtual arrays */
+ }
+ }
+diff -cN ../jpeg-6b/jddctmgr.c ./jddctmgr.c
+*** ../jpeg-6b/jddctmgr.c Sat Jan 13 14:38:21 1996
+--- ./jddctmgr.c Tue Apr 27 14:58:22 1999
+***************
+*** 1,7 ****
+ /*
+ * jddctmgr.c
+ *
+! * Copyright (C) 1994-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jddctmgr.c
+ *
+! * Copyright (C) 1994-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 18,23 ****
+--- 18,24 ----
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
++ #include "jlossy.h" /* Private declarations for lossy subsystem */
+ #include "jdct.h" /* Private declarations for DCT subsystem */
+
+
+***************
+*** 41,48 ****
+ /* Private subobject for this module */
+
+ typedef struct {
+- struct jpeg_inverse_dct pub; /* public fields */
+-
+ /* This array contains the IDCT method code that each multiplier table
+ * is currently set up for, or -1 if it's not yet set up.
+ * The actual multiplier tables are pointed to by dct_table in the
+--- 42,47 ----
+***************
+*** 49,57 ****
+ * per-component comp_info structures.
+ */
+ int cur_method[MAX_COMPONENTS];
+! } my_idct_controller;
+
+! typedef my_idct_controller * my_idct_ptr;
+
+
+ /* Allocated multiplier tables: big enough for any supported variant */
+--- 48,56 ----
+ * per-component comp_info structures.
+ */
+ int cur_method[MAX_COMPONENTS];
+! } idct_controller;
+
+! typedef idct_controller * idct_ptr;
+
+
+ /* Allocated multiplier tables: big enough for any supported variant */
+***************
+*** 88,94 ****
+ METHODDEF(void)
+ start_pass (j_decompress_ptr cinfo)
+ {
+! my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
+ int ci, i;
+ jpeg_component_info *compptr;
+ int method = 0;
+--- 87,94 ----
+ METHODDEF(void)
+ start_pass (j_decompress_ptr cinfo)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! idct_ptr idct = (idct_ptr) lossyd->idct_private;
+ int ci, i;
+ jpeg_component_info *compptr;
+ int method = 0;
+***************
+*** 98,104 ****
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Select the proper IDCT routine for this component's scaling */
+! switch (compptr->DCT_scaled_size) {
+ #ifdef IDCT_SCALING_SUPPORTED
+ case 1:
+ method_ptr = jpeg_idct_1x1;
+--- 98,104 ----
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Select the proper IDCT routine for this component's scaling */
+! switch (compptr->codec_data_unit) {
+ #ifdef IDCT_SCALING_SUPPORTED
+ case 1:
+ method_ptr = jpeg_idct_1x1;
+***************
+*** 139,148 ****
+ }
+ break;
+ default:
+! ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
+ break;
+ }
+! idct->pub.inverse_DCT[ci] = method_ptr;
+ /* Create multiplier table from quant table.
+ * However, we can skip this if the component is uninteresting
+ * or if we already built the table. Also, if no quant table
+--- 139,148 ----
+ }
+ break;
+ default:
+! ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->codec_data_unit);
+ break;
+ }
+! lossyd->inverse_DCT[ci] = method_ptr;
+ /* Create multiplier table from quant table.
+ * However, we can skip this if the component is uninteresting
+ * or if we already built the table. Also, if no quant table
+***************
+*** 246,260 ****
+ GLOBAL(void)
+ jinit_inverse_dct (j_decompress_ptr cinfo)
+ {
+! my_idct_ptr idct;
+ int ci;
+ jpeg_component_info *compptr;
+
+! idct = (my_idct_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! SIZEOF(my_idct_controller));
+! cinfo->idct = (struct jpeg_inverse_dct *) idct;
+! idct->pub.start_pass = start_pass;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+--- 246,261 ----
+ GLOBAL(void)
+ jinit_inverse_dct (j_decompress_ptr cinfo)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! idct_ptr idct;
+ int ci;
+ jpeg_component_info *compptr;
+
+! idct = (idct_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! SIZEOF(idct_controller));
+! lossyd->idct_private = (void *) idct;
+! lossyd->idct_start_pass = start_pass;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+diff -cN ../jpeg-6b/jddiffct.c ./jddiffct.c
+*** ../jpeg-6b/jddiffct.c
+--- ./jddiffct.c Tue Apr 27 14:58:23 1999
+***************
+*** 0 ****
+--- 1,398 ----
++ /*
++ * jddiffct.c
++ *
++ * Copyright (C) 1994-1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains the [un]difference buffer controller for decompression.
++ * This controller is the top level of the lossless JPEG decompressor proper.
++ * The difference buffer lies between the entropy decoding and
++ * prediction/undifferencing steps. The undifference buffer lies between the
++ * prediction/undifferencing and scaling steps.
++ *
++ * In buffered-image mode, this controller is the interface between
++ * input-oriented processing and output-oriented processing.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossls.h"
++
++
++ #ifdef D_LOSSLESS_SUPPORTED
++
++ /* Private buffer controller object */
++
++ typedef struct {
++ /* These variables keep track of the current location of the input side. */
++ /* cinfo->input_iMCU_row is also used for this. */
++ JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
++ unsigned int restart_rows_to_go; /* MCU-rows left in this restart interval */
++ unsigned int MCU_vert_offset; /* counts MCU rows within iMCU row */
++ unsigned int MCU_rows_per_iMCU_row; /* number of such rows needed */
++
++ /* The output side's location is represented by cinfo->output_iMCU_row. */
++
++ JDIFFARRAY diff_buf[MAX_COMPONENTS]; /* iMCU row of differences */
++ JDIFFARRAY undiff_buf[MAX_COMPONENTS]; /* iMCU row of undiff'd samples */
++
++ #ifdef D_MULTISCAN_FILES_SUPPORTED
++ /* In multi-pass modes, we need a virtual sample array for each component. */
++ jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
++ #endif
++ } d_diff_controller;
++
++ typedef d_diff_controller * d_diff_ptr;
++
++ /* Forward declarations */
++ METHODDEF(int) decompress_data
++ JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
++ #ifdef D_MULTISCAN_FILES_SUPPORTED
++ METHODDEF(int) output_data
++ JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
++ #endif
++
++
++ LOCAL(void)
++ start_iMCU_row (j_decompress_ptr cinfo)
++ /* Reset within-iMCU-row counters for a new row (input side) */
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ d_diff_ptr diff = (d_diff_ptr) losslsd->diff_private;
++
++ /* In an interleaved scan, an MCU row is the same as an iMCU row.
++ * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
++ * But at the bottom of the image, process only what's left.
++ */
++ if (cinfo->comps_in_scan > 1) {
++ diff->MCU_rows_per_iMCU_row = 1;
++ } else {
++ if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
++ diff->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
++ else
++ diff->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
++ }
++
++ diff->MCU_ctr = 0;
++ diff->MCU_vert_offset = 0;
++ }
++
++
++ /*
++ * Initialize for an input processing pass.
++ */
++
++ METHODDEF(void)
++ start_input_pass (j_decompress_ptr cinfo)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ d_diff_ptr diff = (d_diff_ptr) losslsd->diff_private;
++
++ /* Check that the restart interval is an integer multiple of the number
++ * of MCU in an MCU-row.
++ */
++ if (cinfo->restart_interval % cinfo->MCUs_per_row != 0)
++ ERREXIT2(cinfo, JERR_BAD_RESTART,
++ cinfo->restart_interval, cinfo->MCUs_per_row);
++
++ /* Initialize restart counter */
++ diff->restart_rows_to_go = cinfo->restart_interval / cinfo->MCUs_per_row;
++
++ cinfo->input_iMCU_row = 0;
++ start_iMCU_row(cinfo);
++ }
++
++
++ /*
++ * Check for a restart marker & resynchronize decoder, undifferencer.
++ * Returns FALSE if must suspend.
++ */
++
++ METHODDEF(boolean)
++ process_restart (j_decompress_ptr cinfo)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ d_diff_ptr diff = (d_diff_ptr) losslsd->diff_private;
++
++ if (! (*losslsd->entropy_process_restart) (cinfo))
++ return FALSE;
++
++ (*losslsd->predict_process_restart) (cinfo);
++
++ /* Reset restart counter */
++ diff->restart_rows_to_go = cinfo->restart_interval / cinfo->MCUs_per_row;
++
++ return TRUE;
++ }
++
++
++ /*
++ * Initialize for an output processing pass.
++ */
++
++ METHODDEF(void)
++ start_output_pass (j_decompress_ptr cinfo)
++ {
++ cinfo->output_iMCU_row = 0;
++ }
++
++
++ /*
++ * Decompress and return some data in the supplied buffer.
++ * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
++ * Input and output must run in lockstep since we have only a one-MCU buffer.
++ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
++ *
++ * NB: output_buf contains a plane for each component in image,
++ * which we index according to the component's SOF position.
++ */
++
++ METHODDEF(int)
++ decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ d_diff_ptr diff = (d_diff_ptr) losslsd->diff_private;
++ JDIMENSION MCU_col_num; /* index of current MCU within row */
++ JDIMENSION MCU_count; /* number of MCUs decoded */
++ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
++ int comp, ci, yoffset, row, prev_row;
++ jpeg_component_info *compptr;
++
++ /* Loop to process as much as one whole iMCU row */
++ for (yoffset = diff->MCU_vert_offset; yoffset < diff->MCU_rows_per_iMCU_row;
++ yoffset++) {
++
++ /* Process restart marker if needed; may have to suspend */
++ if (cinfo->restart_interval) {
++ if (diff->restart_rows_to_go == 0)
++ if (! process_restart(cinfo))
++ return JPEG_SUSPENDED;
++ }
++
++ MCU_col_num = diff->MCU_ctr;
++ /* Try to fetch an MCU-row (or remaining portion of suspended MCU-row). */
++ MCU_count =
++ (*losslsd->entropy_decode_mcus) (cinfo,
++ diff->diff_buf, yoffset, MCU_col_num,
++ cinfo->MCUs_per_row - MCU_col_num);
++ if (MCU_count != cinfo->MCUs_per_row - MCU_col_num) {
++ /* Suspension forced; update state counters and exit */
++ diff->MCU_vert_offset = yoffset;
++ diff->MCU_ctr += MCU_count;
++ return JPEG_SUSPENDED;
++ }
++
++ /* Account for restart interval (no-op if not using restarts) */
++ diff->restart_rows_to_go--;
++
++ /* Completed an MCU row, but perhaps not an iMCU row */
++ diff->MCU_ctr = 0;
++ }
++
++ /*
++ * Undifference and scale each scanline of the disassembled MCU-row
++ * separately. We do not process dummy samples at the end of a scanline
++ * or dummy rows at the end of the image.
++ */
++ for (comp = 0; comp < cinfo->comps_in_scan; comp++) {
++ compptr = cinfo->cur_comp_info[comp];
++ ci = compptr->component_index;
++ for (row = 0, prev_row = compptr->v_samp_factor - 1;
++ row < (cinfo->input_iMCU_row == last_iMCU_row ?
++ compptr->last_row_height : compptr->v_samp_factor);
++ prev_row = row, row++) {
++ (*losslsd->predict_undifference[ci]) (cinfo, ci,
++ diff->diff_buf[ci][row],
++ diff->undiff_buf[ci][prev_row],
++ diff->undiff_buf[ci][row],
++ compptr->width_in_data_units);
++ (*losslsd->scaler_scale) (cinfo, diff->undiff_buf[ci][row],
++ output_buf[ci][row],
++ compptr->width_in_data_units);
++ }
++ }
++
++ /* Completed the iMCU row, advance counters for next one.
++ *
++ * NB: output_data will increment output_iMCU_row.
++ * This counter is not needed for the single-pass case
++ * or the input side of the multi-pass case.
++ */
++ if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
++ start_iMCU_row(cinfo);
++ return JPEG_ROW_COMPLETED;
++ }
++ /* Completed the scan */
++ (*cinfo->inputctl->finish_input_pass) (cinfo);
++ return JPEG_SCAN_COMPLETED;
++ }
++
++
++ /*
++ * Dummy consume-input routine for single-pass operation.
++ */
++
++ METHODDEF(int)
++ dummy_consume_data (j_decompress_ptr cinfo)
++ {
++ return JPEG_SUSPENDED; /* Always indicate nothing was done */
++ }
++
++
++ #ifdef D_MULTISCAN_FILES_SUPPORTED
++
++ /*
++ * Consume input data and store it in the full-image sample buffer.
++ * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
++ * ie, v_samp_factor rows for each component in the scan.
++ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
++ */
++
++ METHODDEF(int)
++ consume_data (j_decompress_ptr cinfo)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ d_diff_ptr diff = (d_diff_ptr) losslsd->diff_private;
++ JDIMENSION MCU_col_num; /* index of current MCU within row */
++ JDIMENSION MCU_count; /* number of MCUs decoded */
++ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
++ int comp, ci, yoffset, row, prev_row;
++ JSAMPARRAY buffer[MAX_COMPS_IN_SCAN];
++ jpeg_component_info *compptr;
++
++ /* Align the virtual buffers for the components used in this scan. */
++ for (comp = 0; comp < cinfo->comps_in_scan; comp++) {
++ compptr = cinfo->cur_comp_info[comp];
++ ci = compptr->component_index;
++ buffer[ci] = (*cinfo->mem->access_virt_sarray)
++ ((j_common_ptr) cinfo, diff->whole_image[ci],
++ cinfo->input_iMCU_row * compptr->v_samp_factor,
++ (JDIMENSION) compptr->v_samp_factor, TRUE);
++ }
++
++ return decompress_data(cinfo, buffer);
++ }
++
++
++ /*
++ * Output some data from the full-image buffer sample in the multi-pass case.
++ * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
++ * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
++ *
++ * NB: output_buf contains a plane for each component in image.
++ */
++
++ METHODDEF(int)
++ output_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ d_diff_ptr diff = (d_diff_ptr) losslsd->diff_private;
++ JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
++ int ci, samp_rows, row;
++ JSAMPARRAY buffer;
++ jpeg_component_info *compptr;
++
++ /* Force some input to be done if we are getting ahead of the input. */
++ while (cinfo->input_scan_number < cinfo->output_scan_number ||
++ (cinfo->input_scan_number == cinfo->output_scan_number &&
++ cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
++ if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
++ return JPEG_SUSPENDED;
++ }
++
++ /* OK, output from the virtual arrays. */
++ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
++ ci++, compptr++) {
++ /* Align the virtual buffer for this component. */
++ buffer = (*cinfo->mem->access_virt_sarray)
++ ((j_common_ptr) cinfo, diff->whole_image[ci],
++ cinfo->output_iMCU_row * compptr->v_samp_factor,
++ (JDIMENSION) compptr->v_samp_factor, FALSE);
++
++ if (cinfo->output_iMCU_row < last_iMCU_row)
++ samp_rows = compptr->v_samp_factor;
++ else {
++ /* NB: can't use last_row_height here; it is input-side-dependent! */
++ samp_rows = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
++ if (samp_rows == 0) samp_rows = compptr->v_samp_factor;
++ }
++
++ for (row = 0; row < samp_rows; row++) {
++ MEMCOPY(output_buf[ci][row], buffer[row],
++ compptr->width_in_data_units * SIZEOF(JSAMPLE));
++ }
++ }
++
++ if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
++ return JPEG_ROW_COMPLETED;
++ return JPEG_SCAN_COMPLETED;
++ }
++
++ #endif /* D_MULTISCAN_FILES_SUPPORTED */
++
++
++ /*
++ * Initialize difference buffer controller.
++ */
++
++ GLOBAL(void)
++ jinit_d_diff_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ d_diff_ptr diff;
++ int ci;
++ jpeg_component_info *compptr;
++
++ diff = (d_diff_ptr)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ SIZEOF(d_diff_controller));
++ losslsd->diff_private = (void *) diff;
++ losslsd->diff_start_input_pass = start_input_pass;
++ losslsd->pub.start_output_pass = start_output_pass;
++
++ /* Create the [un]difference buffers. */
++ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
++ ci++, compptr++) {
++ diff->diff_buf[ci] = (*cinfo->mem->alloc_darray)
++ ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
++ (long) compptr->h_samp_factor),
++ (JDIMENSION) compptr->v_samp_factor);
++ diff->undiff_buf[ci] = (*cinfo->mem->alloc_darray)
++ ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
++ (long) compptr->h_samp_factor),
++ (JDIMENSION) compptr->v_samp_factor);
++ }
++
++ if (need_full_buffer) {
++ #ifdef D_MULTISCAN_FILES_SUPPORTED
++ /* Allocate a full-image virtual array for each component. */
++ int access_rows;
++
++ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
++ ci++, compptr++) {
++ access_rows = compptr->v_samp_factor;
++ diff->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
++ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
++ (JDIMENSION) jround_up((long) compptr->width_in_data_units,
++ (long) compptr->h_samp_factor),
++ (JDIMENSION) jround_up((long) compptr->height_in_data_units,
++ (long) compptr->v_samp_factor),
++ (JDIMENSION) access_rows);
++ }
++ losslsd->pub.consume_data = consume_data;
++ losslsd->pub.decompress_data = output_data;
++ #else
++ ERREXIT(cinfo, JERR_NOT_COMPILED);
++ #endif
++ } else {
++ losslsd->pub.consume_data = dummy_consume_data;
++ losslsd->pub.decompress_data = decompress_data;
++ diff->whole_image[0] = NULL; /* flag for no virtual arrays */
++ }
++ }
++
++ #endif /* D_LOSSLESS_SUPPORTED */
+diff -cN ../jpeg-6b/jdhuff.c ./jdhuff.c
+*** ../jpeg-6b/jdhuff.c Mon Oct 20 20:51:10 1997
+--- ./jdhuff.c Tue Apr 27 14:58:23 1999
+***************
+*** 1,148 ****
+ /*
+ * jdhuff.c
+ *
+! * Copyright (C) 1991-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+! * This file contains Huffman entropy decoding routines.
+! *
+! * Much of the complexity here has to do with supporting input suspension.
+! * If the data source module demands suspension, we want to be able to back
+! * up to the start of the current MCU. To do this, we copy state variables
+! * into local working storage, and update them back to the permanent
+! * storage only upon successful completion of an MCU.
+ */
+
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
+! #include "jdhuff.h" /* Declarations shared with jdphuff.c */
+!
+!
+! /*
+! * Expanded entropy decoder object for Huffman decoding.
+! *
+! * The savable_state subrecord contains fields that change within an MCU,
+! * but must not be updated permanently until we complete the MCU.
+! */
+!
+! typedef struct {
+! int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
+! } savable_state;
+!
+! /* This macro is to work around compilers with missing or broken
+! * structure assignment. You'll need to fix this code if you have
+! * such a compiler and you change MAX_COMPS_IN_SCAN.
+! */
+!
+! #ifndef NO_STRUCT_ASSIGN
+! #define ASSIGN_STATE(dest,src) ((dest) = (src))
+! #else
+! #if MAX_COMPS_IN_SCAN == 4
+! #define ASSIGN_STATE(dest,src) \
+! ((dest).last_dc_val[0] = (src).last_dc_val[0], \
+! (dest).last_dc_val[1] = (src).last_dc_val[1], \
+! (dest).last_dc_val[2] = (src).last_dc_val[2], \
+! (dest).last_dc_val[3] = (src).last_dc_val[3])
+! #endif
+! #endif
+!
+!
+! typedef struct {
+! struct jpeg_entropy_decoder pub; /* public fields */
+!
+! /* These fields are loaded into local variables at start of each MCU.
+! * In case of suspension, we exit WITHOUT updating them.
+! */
+! bitread_perm_state bitstate; /* Bit buffer at start of MCU */
+! savable_state saved; /* Other state at start of MCU */
+!
+! /* These fields are NOT loaded into local working state. */
+! unsigned int restarts_to_go; /* MCUs left in this restart interval */
+!
+! /* Pointers to derived tables (these workspaces have image lifespan) */
+! d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
+! d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
+!
+! /* Precalculated info set up by start_pass for use in decode_mcu: */
+!
+! /* Pointers to derived tables to be used for each block within an MCU */
+! d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
+! d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
+! /* Whether we care about the DC and AC coefficient values for each block */
+! boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
+! boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
+! } huff_entropy_decoder;
+!
+! typedef huff_entropy_decoder * huff_entropy_ptr;
+!
+!
+! /*
+! * Initialize for a Huffman-compressed scan.
+! */
+!
+! METHODDEF(void)
+! start_pass_huff_decoder (j_decompress_ptr cinfo)
+! {
+! huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+! int ci, blkn, dctbl, actbl;
+! jpeg_component_info * compptr;
+!
+! /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
+! * This ought to be an error condition, but we make it a warning because
+! * there are some baseline files out there with all zeroes in these bytes.
+! */
+! if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
+! cinfo->Ah != 0 || cinfo->Al != 0)
+! WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
+!
+! for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+! compptr = cinfo->cur_comp_info[ci];
+! dctbl = compptr->dc_tbl_no;
+! actbl = compptr->ac_tbl_no;
+! /* Compute derived values for Huffman tables */
+! /* We may do this more than once for a table, but it's not expensive */
+! jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
+! & entropy->dc_derived_tbls[dctbl]);
+! jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
+! & entropy->ac_derived_tbls[actbl]);
+! /* Initialize DC predictions to 0 */
+! entropy->saved.last_dc_val[ci] = 0;
+! }
+!
+! /* Precalculate decoding info for each block in an MCU of this scan */
+! for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+! ci = cinfo->MCU_membership[blkn];
+! compptr = cinfo->cur_comp_info[ci];
+! /* Precalculate which table to use for each block */
+! entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
+! entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
+! /* Decide whether we really care about the coefficient values */
+! if (compptr->component_needed) {
+! entropy->dc_needed[blkn] = TRUE;
+! /* we don't need the ACs if producing a 1/8th-size image */
+! entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
+! } else {
+! entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
+! }
+! }
+!
+! /* Initialize bitread state variables */
+! entropy->bitstate.bits_left = 0;
+! entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
+! entropy->pub.insufficient_data = FALSE;
+
+- /* Initialize restart counter */
+- entropy->restarts_to_go = cinfo->restart_interval;
+- }
+-
+
+ /*
+ * Compute the derived values for a Huffman table.
+ * This routine also performs some validation checks on the table.
+- *
+- * Note this is also used by jdphuff.c.
+ */
+
+ GLOBAL(void)
+--- 1,25 ----
+ /*
+ * jdhuff.c
+ *
+! * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+! * This file contains Huffman entropy decoding routines which are shared
+! * by the sequential, progressive and lossless decoders.
+ */
+
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
+! #include "jlossy.h" /* Private declarations for lossy codec */
+! #include "jlossls.h" /* Private declarations for lossless codec */
+! #include "jdhuff.h" /* Declarations shared with jd*huff.c */
+
+
+ /*
+ * Compute the derived values for a Huffman table.
+ * This routine also performs some validation checks on the table.
+ */
+
+ GLOBAL(void)
+***************
+*** 252,258 ****
+
+ /* Validate symbols as being reasonable.
+ * For AC tables, we make no check, but accept all byte values 0..255.
+! * For DC tables, we require the symbols to be in range 0..15.
+ * (Tighter bounds could be applied depending on the data depth and mode,
+ * but this is sufficient to ensure safe decoding.)
+ */
+--- 129,135 ----
+
+ /* Validate symbols as being reasonable.
+ * For AC tables, we make no check, but accept all byte values 0..255.
+! * For DC tables, we require the symbols to be in range 0..16.
+ * (Tighter bounds could be applied depending on the data depth and mode,
+ * but this is sufficient to ensure safe decoding.)
+ */
+***************
+*** 259,265 ****
+ if (isDC) {
+ for (i = 0; i < numsymbols; i++) {
+ int sym = htbl->huffval[i];
+! if (sym < 0 || sym > 15)
+ ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
+ }
+ }
+--- 136,142 ----
+ if (isDC) {
+ for (i = 0; i < numsymbols; i++) {
+ int sym = htbl->huffval[i];
+! if (sym < 0 || sym > 16)
+ ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
+ }
+ }
+***************
+*** 267,273 ****
+
+
+ /*
+! * Out-of-line code for bit fetching (shared with jdphuff.c).
+ * See jdhuff.h for info about usage.
+ * Note: current values of get_buffer and bits_left are passed as parameters,
+ * but are returned in the corresponding fields of the state struct.
+--- 144,150 ----
+
+
+ /*
+! * Out-of-line code for bit fetching.
+ * See jdhuff.h for info about usage.
+ * Note: current values of get_buffer and bits_left are passed as parameters,
+ * but are returned in the corresponding fields of the state struct.
+***************
+*** 369,377 ****
+ * We use a nonvolatile flag to ensure that only one warning message
+ * appears per data segment.
+ */
+! if (! cinfo->entropy->insufficient_data) {
+ WARNMS(cinfo, JWRN_HIT_MARKER);
+! cinfo->entropy->insufficient_data = TRUE;
+ }
+ /* Fill the buffer with zero bits */
+ get_buffer <<= MIN_GET_BITS - bits_left;
+--- 246,259 ----
+ * We use a nonvolatile flag to ensure that only one warning message
+ * appears per data segment.
+ */
+! huffd_common_ptr huffd;
+! if (cinfo->process == JPROC_LOSSLESS)
+! huffd = (huffd_common_ptr) ((j_lossless_d_ptr) cinfo->codec)->entropy_private;
+! else
+! huffd = (huffd_common_ptr) ((j_lossy_d_ptr) cinfo->codec)->entropy_private;
+! if (! huffd->insufficient_data) {
+ WARNMS(cinfo, JWRN_HIT_MARKER);
+! huffd->insufficient_data = TRUE;
+ }
+ /* Fill the buffer with zero bits */
+ get_buffer <<= MIN_GET_BITS - bits_left;
+***************
+*** 430,651 ****
+ }
+
+ return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
+- }
+-
+-
+- /*
+- * Figure F.12: extend sign bit.
+- * On some machines, a shift and add will be faster than a table lookup.
+- */
+-
+- #ifdef AVOID_TABLES
+-
+- #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
+-
+- #else
+-
+- #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
+-
+- static const int extend_test[16] = /* entry n is 2**(n-1) */
+- { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
+- 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
+-
+- static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
+- { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
+- ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
+- ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
+- ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
+-
+- #endif /* AVOID_TABLES */
+-
+-
+- /*
+- * Check for a restart marker & resynchronize decoder.
+- * Returns FALSE if must suspend.
+- */
+-
+- LOCAL(boolean)
+- process_restart (j_decompress_ptr cinfo)
+- {
+- huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+- int ci;
+-
+- /* Throw away any unused bits remaining in bit buffer; */
+- /* include any full bytes in next_marker's count of discarded bytes */
+- cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
+- entropy->bitstate.bits_left = 0;
+-
+- /* Advance past the RSTn marker */
+- if (! (*cinfo->marker->read_restart_marker) (cinfo))
+- return FALSE;
+-
+- /* Re-initialize DC predictions to 0 */
+- for (ci = 0; ci < cinfo->comps_in_scan; ci++)
+- entropy->saved.last_dc_val[ci] = 0;
+-
+- /* Reset restart counter */
+- entropy->restarts_to_go = cinfo->restart_interval;
+-
+- /* Reset out-of-data flag, unless read_restart_marker left us smack up
+- * against a marker. In that case we will end up treating the next data
+- * segment as empty, and we can avoid producing bogus output pixels by
+- * leaving the flag set.
+- */
+- if (cinfo->unread_marker == 0)
+- entropy->pub.insufficient_data = FALSE;
+-
+- return TRUE;
+- }
+-
+-
+- /*
+- * Decode and return one MCU's worth of Huffman-compressed coefficients.
+- * The coefficients are reordered from zigzag order into natural array order,
+- * but are not dequantized.
+- *
+- * The i'th block of the MCU is stored into the block pointed to by
+- * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
+- * (Wholesale zeroing is usually a little faster than retail...)
+- *
+- * Returns FALSE if data source requested suspension. In that case no
+- * changes have been made to permanent state. (Exception: some output
+- * coefficients may already have been assigned. This is harmless for
+- * this module, since we'll just re-assign them on the next call.)
+- */
+-
+- METHODDEF(boolean)
+- decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+- {
+- huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+- int blkn;
+- BITREAD_STATE_VARS;
+- savable_state state;
+-
+- /* Process restart marker if needed; may have to suspend */
+- if (cinfo->restart_interval) {
+- if (entropy->restarts_to_go == 0)
+- if (! process_restart(cinfo))
+- return FALSE;
+- }
+-
+- /* If we've run out of data, just leave the MCU set to zeroes.
+- * This way, we return uniform gray for the remainder of the segment.
+- */
+- if (! entropy->pub.insufficient_data) {
+-
+- /* Load up working state */
+- BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+- ASSIGN_STATE(state, entropy->saved);
+-
+- /* Outer loop handles each block in the MCU */
+-
+- for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+- JBLOCKROW block = MCU_data[blkn];
+- d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
+- d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
+- register int s, k, r;
+-
+- /* Decode a single block's worth of coefficients */
+-
+- /* Section F.2.2.1: decode the DC coefficient difference */
+- HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
+- if (s) {
+- CHECK_BIT_BUFFER(br_state, s, return FALSE);
+- r = GET_BITS(s);
+- s = HUFF_EXTEND(r, s);
+- }
+-
+- if (entropy->dc_needed[blkn]) {
+- /* Convert DC difference to actual value, update last_dc_val */
+- int ci = cinfo->MCU_membership[blkn];
+- s += state.last_dc_val[ci];
+- state.last_dc_val[ci] = s;
+- /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
+- (*block)[0] = (JCOEF) s;
+- }
+-
+- if (entropy->ac_needed[blkn]) {
+-
+- /* Section F.2.2.2: decode the AC coefficients */
+- /* Since zeroes are skipped, output area must be cleared beforehand */
+- for (k = 1; k < DCTSIZE2; k++) {
+- HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
+-
+- r = s >> 4;
+- s &= 15;
+-
+- if (s) {
+- k += r;
+- CHECK_BIT_BUFFER(br_state, s, return FALSE);
+- r = GET_BITS(s);
+- s = HUFF_EXTEND(r, s);
+- /* Output coefficient in natural (dezigzagged) order.
+- * Note: the extra entries in jpeg_natural_order[] will save us
+- * if k >= DCTSIZE2, which could happen if the data is corrupted.
+- */
+- (*block)[jpeg_natural_order[k]] = (JCOEF) s;
+- } else {
+- if (r != 15)
+- break;
+- k += 15;
+- }
+- }
+-
+- } else {
+-
+- /* Section F.2.2.2: decode the AC coefficients */
+- /* In this path we just discard the values */
+- for (k = 1; k < DCTSIZE2; k++) {
+- HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
+-
+- r = s >> 4;
+- s &= 15;
+-
+- if (s) {
+- k += r;
+- CHECK_BIT_BUFFER(br_state, s, return FALSE);
+- DROP_BITS(s);
+- } else {
+- if (r != 15)
+- break;
+- k += 15;
+- }
+- }
+-
+- }
+- }
+-
+- /* Completed MCU, so update state */
+- BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
+- ASSIGN_STATE(entropy->saved, state);
+- }
+-
+- /* Account for restart interval (no-op if not using restarts) */
+- entropy->restarts_to_go--;
+-
+- return TRUE;
+- }
+-
+-
+- /*
+- * Module initialization routine for Huffman entropy decoding.
+- */
+-
+- GLOBAL(void)
+- jinit_huff_decoder (j_decompress_ptr cinfo)
+- {
+- huff_entropy_ptr entropy;
+- int i;
+-
+- entropy = (huff_entropy_ptr)
+- (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+- SIZEOF(huff_entropy_decoder));
+- cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
+- entropy->pub.start_pass = start_pass_huff_decoder;
+- entropy->pub.decode_mcu = decode_mcu;
+-
+- /* Mark tables unallocated */
+- for (i = 0; i < NUM_HUFF_TBLS; i++) {
+- entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
+- }
+ }
+--- 312,315 ----
+diff -cN ../jpeg-6b/jdhuff.h ./jdhuff.h
+*** ../jpeg-6b/jdhuff.h Mon Oct 20 20:37:22 1997
+--- ./jdhuff.h Tue Apr 27 14:58:23 1999
+***************
+*** 1,13 ****
+ /*
+ * jdhuff.h
+ *
+! * Copyright (C) 1991-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains declarations for Huffman entropy decoding routines
+! * that are shared between the sequential decoder (jdhuff.c) and the
+! * progressive decoder (jdphuff.c). No other modules need to see these.
+ */
+
+ /* Short forms of external names for systems with brain-damaged linkers. */
+--- 1,14 ----
+ /*
+ * jdhuff.h
+ *
+! * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains declarations for Huffman entropy decoding routines
+! * that are shared between the sequential decoder (jdhuff.c), the
+! * progressive decoder (jdphuff.c) and the lossless decoder (jdlhuff.c).
+! * No other modules need to see these.
+ */
+
+ /* Short forms of external names for systems with brain-damaged linkers. */
+***************
+*** 199,201 ****
+--- 200,229 ----
+ EXTERN(int) jpeg_huff_decode
+ JPP((bitread_working_state * state, register bit_buf_type get_buffer,
+ register int bits_left, d_derived_tbl * htbl, int min_bits));
++
++
++ /* Common fields between sequential, progressive and lossless Huffman entropy
++ * decoder master structs.
++ */
++
++ #define huffd_common_fields \
++ boolean insufficient_data; /* set TRUE after emmitting warning */ \
++ /* These fields are loaded into local variables at start of each MCU. \
++ * In case of suspension, we exit WITHOUT updating them. \
++ */ \
++ bitread_perm_state bitstate /* Bit buffer at start of MCU */
++
++ /* Routines that are to be used by any or all of the entropy decoders are
++ * declared to receive a pointer to this structure. There are no actual
++ * instances of huffd_common_struct, only of shuff_entropy_decoder,
++ * phuff_entropy_decoder and lhuff_entropy_decoder.
++ */
++ struct huffd_common_struct {
++ huffd_common_fields; /* Fields common to all decoder struct types */
++ /* Additional fields follow in an actual shuff_entropy_decoder,
++ * phuff_entropy_decoder or lhuff_entropy_decoder struct. All four structs
++ * must agree on these initial fields! (This would be a lot cleaner in C++.)
++ */
++ };
++
++ typedef struct huffd_common_struct * huffd_common_ptr;
+diff -cN ../jpeg-6b/jdinput.c ./jdinput.c
+*** ../jpeg-6b/jdinput.c Fri Nov 7 11:26:04 1997
+--- ./jdinput.c Tue Apr 27 14:58:26 1999
+***************
+*** 1,14 ****
+ /*
+ * jdinput.c
+ *
+! * Copyright (C) 1991-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains input control logic for the JPEG decompressor.
+ * These routines are concerned with controlling the decompressor's input
+! * processing (marker reading and coefficient decoding). The actual input
+! * reading is done in jdmarker.c, jdhuff.c, and jdphuff.c.
+ */
+
+ #define JPEG_INTERNALS
+--- 1,15 ----
+ /*
+ * jdinput.c
+ *
+! * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains input control logic for the JPEG decompressor.
+ * These routines are concerned with controlling the decompressor's input
+! * processing (marker reading and coefficient/difference decoding).
+! * The actual input reading is done in jdmarker.c, jdhuff.c, jdphuff.c,
+! * and jdlhuff.c.
+ */
+
+ #define JPEG_INTERNALS
+***************
+*** 47,55 ****
+ (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
+ ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
+
+! /* For now, precision must match compiled-in value... */
+! if (cinfo->data_precision != BITS_IN_JSAMPLE)
+! ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
+
+ /* Check that number of components won't exceed internal array sizes */
+ if (cinfo->num_components > MAX_COMPONENTS)
+--- 48,64 ----
+ (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
+ ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
+
+! if (cinfo->process == JPROC_LOSSLESS) {
+! /* If precision > compiled-in value, we must downscale */
+! if (cinfo->data_precision > BITS_IN_JSAMPLE)
+! WARNMS2(cinfo, JWRN_MUST_DOWNSCALE,
+! cinfo->data_precision, BITS_IN_JSAMPLE);
+! }
+! else { /* Lossy processes */
+! /* For now, precision must match compiled-in value... */
+! if (cinfo->data_precision != BITS_IN_JSAMPLE)
+! ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
+! }
+
+ /* Check that number of components won't exceed internal array sizes */
+ if (cinfo->num_components > MAX_COMPONENTS)
+***************
+*** 70,92 ****
+ compptr->v_samp_factor);
+ }
+
+! /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
+ * In the full decompressor, this will be overridden by jdmaster.c;
+ * but in the transcoder, jdmaster.c is not used, so we must do it here.
+ */
+! cinfo->min_DCT_scaled_size = DCTSIZE;
+
+ /* Compute dimensions of components */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+! compptr->DCT_scaled_size = DCTSIZE;
+! /* Size in DCT blocks */
+! compptr->width_in_blocks = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+! (long) (cinfo->max_h_samp_factor * DCTSIZE));
+! compptr->height_in_blocks = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+! (long) (cinfo->max_v_samp_factor * DCTSIZE));
+ /* downsampled_width and downsampled_height will also be overridden by
+ * jdmaster.c if we are doing full decompression. The transcoder library
+ * doesn't use these values, but the calling application might.
+--- 79,101 ----
+ compptr->v_samp_factor);
+ }
+
+! /* We initialize codec_data_unit and min_codec_data_unit to data_unit.
+ * In the full decompressor, this will be overridden by jdmaster.c;
+ * but in the transcoder, jdmaster.c is not used, so we must do it here.
+ */
+! cinfo->min_codec_data_unit = cinfo->data_unit;
+
+ /* Compute dimensions of components */
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+! compptr->codec_data_unit = cinfo->data_unit;
+! /* Size in data units */
+! compptr->width_in_data_units = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
+! (long) (cinfo->max_h_samp_factor * cinfo->data_unit));
+! compptr->height_in_data_units = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
+! (long) (cinfo->max_v_samp_factor * cinfo->data_unit));
+ /* downsampled_width and downsampled_height will also be overridden by
+ * jdmaster.c if we are doing full decompression. The transcoder library
+ * doesn't use these values, but the calling application might.
+***************
+*** 107,116 ****
+ /* Compute number of fully interleaved MCU rows. */
+ cinfo->total_iMCU_rows = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+! (long) (cinfo->max_v_samp_factor*DCTSIZE));
+
+ /* Decide whether file contains multiple scans */
+! if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
+ cinfo->inputctl->has_multiple_scans = TRUE;
+ else
+ cinfo->inputctl->has_multiple_scans = FALSE;
+--- 116,126 ----
+ /* Compute number of fully interleaved MCU rows. */
+ cinfo->total_iMCU_rows = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+! (long) (cinfo->max_v_samp_factor*cinfo->data_unit));
+
+ /* Decide whether file contains multiple scans */
+! if (cinfo->comps_in_scan < cinfo->num_components ||
+! cinfo->process == JPROC_PROGRESSIVE)
+ cinfo->inputctl->has_multiple_scans = TRUE;
+ else
+ cinfo->inputctl->has_multiple_scans = FALSE;
+***************
+*** 124,130 ****
+ {
+ int ci, mcublks, tmp;
+ jpeg_component_info *compptr;
+!
+ if (cinfo->comps_in_scan == 1) {
+
+ /* Noninterleaved (single-component) scan */
+--- 134,140 ----
+ {
+ int ci, mcublks, tmp;
+ jpeg_component_info *compptr;
+!
+ if (cinfo->comps_in_scan == 1) {
+
+ /* Noninterleaved (single-component) scan */
+***************
+*** 131,154 ****
+ compptr = cinfo->cur_comp_info[0];
+
+ /* Overall image size in MCUs */
+! cinfo->MCUs_per_row = compptr->width_in_blocks;
+! cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
+
+! /* For noninterleaved scan, always one block per MCU */
+ compptr->MCU_width = 1;
+ compptr->MCU_height = 1;
+! compptr->MCU_blocks = 1;
+! compptr->MCU_sample_width = compptr->DCT_scaled_size;
+ compptr->last_col_width = 1;
+ /* For noninterleaved scans, it is convenient to define last_row_height
+! * as the number of block rows present in the last iMCU row.
+ */
+! tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+ if (tmp == 0) tmp = compptr->v_samp_factor;
+ compptr->last_row_height = tmp;
+
+ /* Prepare array describing MCU composition */
+! cinfo->blocks_in_MCU = 1;
+ cinfo->MCU_membership[0] = 0;
+
+ } else {
+--- 141,164 ----
+ compptr = cinfo->cur_comp_info[0];
+
+ /* Overall image size in MCUs */
+! cinfo->MCUs_per_row = compptr->width_in_data_units;
+! cinfo->MCU_rows_in_scan = compptr->height_in_data_units;
+
+! /* For noninterleaved scan, always one data unit per MCU */
+ compptr->MCU_width = 1;
+ compptr->MCU_height = 1;
+! compptr->MCU_data_units = 1;
+! compptr->MCU_sample_width = compptr->codec_data_unit;
+ compptr->last_col_width = 1;
+ /* For noninterleaved scans, it is convenient to define last_row_height
+! * as the number of data unit rows present in the last iMCU row.
+ */
+! tmp = (int) (compptr->height_in_data_units % compptr->v_samp_factor);
+ if (tmp == 0) tmp = compptr->v_samp_factor;
+ compptr->last_row_height = tmp;
+
+ /* Prepare array describing MCU composition */
+! cinfo->data_units_in_MCU = 1;
+ cinfo->MCU_membership[0] = 0;
+
+ } else {
+***************
+*** 161,193 ****
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width,
+! (long) (cinfo->max_h_samp_factor*DCTSIZE));
+ cinfo->MCU_rows_in_scan = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+! (long) (cinfo->max_v_samp_factor*DCTSIZE));
+
+! cinfo->blocks_in_MCU = 0;
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+! /* Sampling factors give # of blocks of component in each MCU */
+ compptr->MCU_width = compptr->h_samp_factor;
+ compptr->MCU_height = compptr->v_samp_factor;
+! compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
+! compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
+! /* Figure number of non-dummy blocks in last MCU column & row */
+! tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
+ if (tmp == 0) tmp = compptr->MCU_width;
+ compptr->last_col_width = tmp;
+! tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
+ if (tmp == 0) tmp = compptr->MCU_height;
+ compptr->last_row_height = tmp;
+ /* Prepare array describing MCU composition */
+! mcublks = compptr->MCU_blocks;
+! if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
+ ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
+ while (mcublks-- > 0) {
+! cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
+ }
+ }
+
+--- 171,203 ----
+ /* Overall image size in MCUs */
+ cinfo->MCUs_per_row = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_width,
+! (long) (cinfo->max_h_samp_factor*cinfo->data_unit));
+ cinfo->MCU_rows_in_scan = (JDIMENSION)
+ jdiv_round_up((long) cinfo->image_height,
+! (long) (cinfo->max_v_samp_factor*cinfo->data_unit));
+
+! cinfo->data_units_in_MCU = 0;
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+ compptr = cinfo->cur_comp_info[ci];
+! /* Sampling factors give # of data units of component in each MCU */
+ compptr->MCU_width = compptr->h_samp_factor;
+ compptr->MCU_height = compptr->v_samp_factor;
+! compptr->MCU_data_units = compptr->MCU_width * compptr->MCU_height;
+! compptr->MCU_sample_width = compptr->MCU_width * compptr->codec_data_unit;
+! /* Figure number of non-dummy data units in last MCU column & row */
+! tmp = (int) (compptr->width_in_data_units % compptr->MCU_width);
+ if (tmp == 0) tmp = compptr->MCU_width;
+ compptr->last_col_width = tmp;
+! tmp = (int) (compptr->height_in_data_units % compptr->MCU_height);
+ if (tmp == 0) tmp = compptr->MCU_height;
+ compptr->last_row_height = tmp;
+ /* Prepare array describing MCU composition */
+! mcublks = compptr->MCU_data_units;
+! if (cinfo->data_units_in_MCU + mcublks > D_MAX_DATA_UNITS_IN_MCU)
+ ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
+ while (mcublks-- > 0) {
+! cinfo->MCU_membership[cinfo->data_units_in_MCU++] = ci;
+ }
+ }
+
+***************
+*** 196,249 ****
+
+
+ /*
+- * Save away a copy of the Q-table referenced by each component present
+- * in the current scan, unless already saved during a prior scan.
+- *
+- * In a multiple-scan JPEG file, the encoder could assign different components
+- * the same Q-table slot number, but change table definitions between scans
+- * so that each component uses a different Q-table. (The IJG encoder is not
+- * currently capable of doing this, but other encoders might.) Since we want
+- * to be able to dequantize all the components at the end of the file, this
+- * means that we have to save away the table actually used for each component.
+- * We do this by copying the table at the start of the first scan containing
+- * the component.
+- * The JPEG spec prohibits the encoder from changing the contents of a Q-table
+- * slot between scans of a component using that slot. If the encoder does so
+- * anyway, this decoder will simply use the Q-table values that were current
+- * at the start of the first scan for the component.
+- *
+- * The decompressor output side looks only at the saved quant tables,
+- * not at the current Q-table slots.
+- */
+-
+- LOCAL(void)
+- latch_quant_tables (j_decompress_ptr cinfo)
+- {
+- int ci, qtblno;
+- jpeg_component_info *compptr;
+- JQUANT_TBL * qtbl;
+-
+- for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+- compptr = cinfo->cur_comp_info[ci];
+- /* No work if we already saved Q-table for this component */
+- if (compptr->quant_table != NULL)
+- continue;
+- /* Make sure specified quantization table is present */
+- qtblno = compptr->quant_tbl_no;
+- if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
+- cinfo->quant_tbl_ptrs[qtblno] == NULL)
+- ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
+- /* OK, save away the quantization table */
+- qtbl = (JQUANT_TBL *)
+- (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+- SIZEOF(JQUANT_TBL));
+- MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
+- compptr->quant_table = qtbl;
+- }
+- }
+-
+-
+- /*
+ * Initialize the input modules to read a scan of compressed data.
+ * The first call to this is done by jdmaster.c after initializing
+ * the entire decompressor (during jpeg_start_decompress).
+--- 206,211 ----
+***************
+*** 254,263 ****
+ start_input_pass (j_decompress_ptr cinfo)
+ {
+ per_scan_setup(cinfo);
+! latch_quant_tables(cinfo);
+! (*cinfo->entropy->start_pass) (cinfo);
+! (*cinfo->coef->start_input_pass) (cinfo);
+! cinfo->inputctl->consume_input = cinfo->coef->consume_data;
+ }
+
+
+--- 216,223 ----
+ start_input_pass (j_decompress_ptr cinfo)
+ {
+ per_scan_setup(cinfo);
+! (*cinfo->codec->start_input_pass) (cinfo);
+! cinfo->inputctl->consume_input = cinfo->codec->consume_data;
+ }
+
+
+***************
+*** 299,304 ****
+--- 259,270 ----
+ case JPEG_REACHED_SOS: /* Found SOS */
+ if (inputctl->inheaders) { /* 1st SOS */
+ initial_setup(cinfo);
++ /*
++ * Initialize the decompression codec. We need to do this here so that
++ * any codec-specific fields and function pointers are available to
++ * the rest of the library.
++ */
++ jinit_d_codec(cinfo);
+ inputctl->inheaders = FALSE;
+ /* Note: start_input_pass must be called by jdmaster.c
+ * before any more input can be consumed. jdapimin.c is
+diff -cN ../jpeg-6b/jdlhuff.c ./jdlhuff.c
+*** ../jpeg-6b/jdlhuff.c
+--- ./jdlhuff.c Tue Apr 27 14:58:26 1999
+***************
+*** 0 ****
+--- 1,290 ----
++ /*
++ * jdlhuff.c
++ *
++ * Copyright (C) 1991-1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains Huffman entropy decoding routines for lossless JPEG.
++ *
++ * Much of the complexity here has to do with supporting input suspension.
++ * If the data source module demands suspension, we want to be able to back
++ * up to the start of the current MCU. To do this, we copy state variables
++ * into local working storage, and update them back to the permanent
++ * storage only upon successful completion of an MCU.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossls.h" /* Private declarations for lossless codec */
++ #include "jdhuff.h" /* Declarations shared with jd*huff.c */
++
++
++ #ifdef D_LOSSLESS_SUPPORTED
++
++ typedef struct {
++ int ci, yoffset, MCU_width;
++ } lhd_output_ptr_info;
++
++ /*
++ * Private entropy decoder object for lossless Huffman decoding.
++ */
++
++ typedef struct {
++ huffd_common_fields; /* Fields shared with other entropy decoders */
++
++ /* Pointers to derived tables (these workspaces have image lifespan) */
++ d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
++
++ /* Precalculated info set up by start_pass for use in decode_mcus: */
++
++ /* Pointers to derived tables to be used for each data unit within an MCU */
++ d_derived_tbl * cur_tbls[D_MAX_DATA_UNITS_IN_MCU];
++
++ /* Pointers to the proper output difference row for each group of data units
++ * within an MCU. For each component, there are Vi groups of Hi data units.
++ */
++ JDIFFROW output_ptr[D_MAX_DATA_UNITS_IN_MCU];
++
++ /* Number of output pointers in use for the current MCU. This is the sum
++ * of all Vi in the MCU.
++ */
++ int num_output_ptrs;
++
++ /* Information used for positioning the output pointers within the output
++ * difference rows.
++ */
++ lhd_output_ptr_info output_ptr_info[D_MAX_DATA_UNITS_IN_MCU];
++
++ /* Index of the proper output pointer for each data unit within an MCU */
++ int output_ptr_index[D_MAX_DATA_UNITS_IN_MCU];
++
++ } lhuff_entropy_decoder;
++
++ typedef lhuff_entropy_decoder * lhuff_entropy_ptr;
++
++
++ /*
++ * Initialize for a Huffman-compressed scan.
++ */
++
++ METHODDEF(void)
++ start_pass_lhuff_decoder (j_decompress_ptr cinfo)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsd->entropy_private;
++ int ci, dctbl, sampn, ptrn, yoffset, xoffset;
++ jpeg_component_info * compptr;
++
++ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
++ compptr = cinfo->cur_comp_info[ci];
++ dctbl = compptr->dc_tbl_no;
++ /* Make sure requested tables are present */
++ if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS ||
++ cinfo->dc_huff_tbl_ptrs[dctbl] == NULL)
++ ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
++ /* Compute derived values for Huffman tables */
++ /* We may do this more than once for a table, but it's not expensive */
++ jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
++ & entropy->derived_tbls[dctbl]);
++ }
++
++ /* Precalculate decoding info for each sample in an MCU of this scan */
++ for (sampn = 0, ptrn = 0; sampn < cinfo->data_units_in_MCU;) {
++ compptr = cinfo->cur_comp_info[cinfo->MCU_membership[sampn]];
++ ci = compptr->component_index;
++ for (yoffset = 0; yoffset < compptr->MCU_height; yoffset++, ptrn++) {
++ /* Precalculate the setup info for each output pointer */
++ entropy->output_ptr_info[ptrn].ci = ci;
++ entropy->output_ptr_info[ptrn].yoffset = yoffset;
++ entropy->output_ptr_info[ptrn].MCU_width = compptr->MCU_width;
++ for (xoffset = 0; xoffset < compptr->MCU_width; xoffset++, sampn++) {
++ /* Precalculate the output pointer index for each sample */
++ entropy->output_ptr_index[sampn] = ptrn;
++ /* Precalculate which table to use for each sample */
++ entropy->cur_tbls[sampn] = entropy->derived_tbls[compptr->dc_tbl_no];
++ }
++ }
++ }
++ entropy->num_output_ptrs = ptrn;
++
++ /* Initialize bitread state variables */
++ entropy->bitstate.bits_left = 0;
++ entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
++ entropy->insufficient_data = FALSE;
++ }
++
++
++ /*
++ * Figure F.12: extend sign bit.
++ * On some machines, a shift and add will be faster than a table lookup.
++ */
++
++ #ifdef AVOID_TABLES
++
++ #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
++
++ #else
++
++ #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
++
++ static const int extend_test[16] = /* entry n is 2**(n-1) */
++ { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
++ 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
++
++ static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
++ { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
++ ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
++ ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
++ ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
++
++ #endif /* AVOID_TABLES */
++
++
++ /*
++ * Check for a restart marker & resynchronize decoder.
++ * Returns FALSE if must suspend.
++ */
++
++ METHODDEF(boolean)
++ process_restart (j_decompress_ptr cinfo)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsd->entropy_private;
++ int ci;
++
++ /* Throw away any unused bits remaining in bit buffer; */
++ /* include any full bytes in next_marker's count of discarded bytes */
++ cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
++ entropy->bitstate.bits_left = 0;
++
++ /* Advance past the RSTn marker */
++ if (! (*cinfo->marker->read_restart_marker) (cinfo))
++ return FALSE;
++
++ /* Reset out-of-data flag, unless read_restart_marker left us smack up
++ * against a marker. In that case we will end up treating the next data
++ * segment as empty, and we can avoid producing bogus output pixels by
++ * leaving the flag set.
++ */
++ if (cinfo->unread_marker == 0)
++ entropy->insufficient_data = FALSE;
++
++ return TRUE;
++ }
++
++
++ /*
++ * Decode and return nMCU's worth of Huffman-compressed differences.
++ * Each MCU is also disassembled and placed accordingly in diff_buf.
++ *
++ * MCU_col_num specifies the column of the first MCU being requested within
++ * the MCU-row. This tells us where to position the output row pointers in
++ * diff_buf.
++ *
++ * Returns the number of MCUs decoded. This may be less than nMCU if data
++ * source requested suspension. In that case no changes have been made to
++ * permanent state. (Exception: some output differences may already have
++ * been assigned. This is harmless for this module, since we'll just
++ * re-assign them on the next call.)
++ */
++
++ METHODDEF(JDIMENSION)
++ decode_mcus (j_decompress_ptr cinfo, JDIFFIMAGE diff_buf,
++ JDIMENSION MCU_row_num, JDIMENSION MCU_col_num, JDIMENSION nMCU)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsd->entropy_private;
++ int mcu_num, sampn, ci, yoffset, MCU_width, ptrn;
++ BITREAD_STATE_VARS;
++
++ /* Set output pointer locations based on MCU_col_num */
++ for (ptrn = 0; ptrn < entropy->num_output_ptrs; ptrn++) {
++ ci = entropy->output_ptr_info[ptrn].ci;
++ yoffset = entropy->output_ptr_info[ptrn].yoffset;
++ MCU_width = entropy->output_ptr_info[ptrn].MCU_width;
++ entropy->output_ptr[ptrn] =
++ diff_buf[ci][MCU_row_num + yoffset] + (MCU_col_num * MCU_width);
++ }
++
++ /*
++ * If we've run out of data, zero out the buffers and return.
++ * By resetting the undifferencer, the output samples will be CENTERJSAMPLE.
++ *
++ * NB: We should find a way to do this without interacting with the
++ * undifferencer module directly.
++ */
++ if (entropy->insufficient_data) {
++ for (ptrn = 0; ptrn < entropy->num_output_ptrs; ptrn++)
++ jzero_far((void FAR *) entropy->output_ptr[ptrn],
++ nMCU * entropy->output_ptr_info[ptrn].MCU_width * SIZEOF(JDIFF));
++
++ (*losslsd->predict_process_restart) (cinfo);
++ }
++
++ else {
++
++ /* Load up working state */
++ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
++
++ /* Outer loop handles the number of MCU requested */
++
++ for (mcu_num = 0; mcu_num < nMCU; mcu_num++) {
++
++ /* Inner loop handles the samples in the MCU */
++ for (sampn = 0; sampn < cinfo->data_units_in_MCU; sampn++) {
++ d_derived_tbl * dctbl = entropy->cur_tbls[sampn];
++ register int s, r;
++
++ /* Section H.2.2: decode the sample difference */
++ HUFF_DECODE(s, br_state, dctbl, return mcu_num, label1);
++ if (s) {
++ if (s == 16) /* special case: always output 32768 */
++ s = 32768;
++ else { /* normal case: fetch subsequent bits */
++ CHECK_BIT_BUFFER(br_state, s, return mcu_num);
++ r = GET_BITS(s);
++ s = HUFF_EXTEND(r, s);
++ }
++ }
++
++ /* Output the sample difference */
++ *entropy->output_ptr[entropy->output_ptr_index[sampn]]++ = (JDIFF) s;
++ }
++
++ /* Completed MCU, so update state */
++ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
++ }
++ }
++
++ return nMCU;
++ }
++
++
++ /*
++ * Module initialization routine for lossless Huffman entropy decoding.
++ */
++
++ GLOBAL(void)
++ jinit_lhuff_decoder (j_decompress_ptr cinfo)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ lhuff_entropy_ptr entropy;
++ int i;
++
++ entropy = (lhuff_entropy_ptr)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ SIZEOF(lhuff_entropy_decoder));
++ losslsd->entropy_private = (void *) entropy;
++ losslsd->entropy_start_pass = start_pass_lhuff_decoder;
++ losslsd->entropy_process_restart = process_restart;
++ losslsd->entropy_decode_mcus = decode_mcus;
++
++ /* Mark tables unallocated */
++ for (i = 0; i < NUM_HUFF_TBLS; i++) {
++ entropy->derived_tbls[i] = NULL;
++ }
++ }
++
++ #endif /* D_LOSSLESS_SUPPORTED */
+diff -cN ../jpeg-6b/jdlossls.c ./jdlossls.c
+*** ../jpeg-6b/jdlossls.c
+--- ./jdlossls.c Tue Apr 27 14:58:26 1999
+***************
+*** 0 ****
+--- 1,94 ----
++ /*
++ * jdlossls.c
++ *
++ * Copyright (C) 1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains the control logic for the lossless JPEG decompressor.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossls.h"
++
++
++ #ifdef D_LOSSLESS_SUPPORTED
++
++ /*
++ * Compute output image dimensions and related values.
++ */
++
++ METHODDEF(void)
++ calc_output_dimensions (j_decompress_ptr cinfo)
++ {
++ /* Hardwire it to "no scaling" */
++ cinfo->output_width = cinfo->image_width;
++ cinfo->output_height = cinfo->image_height;
++ /* jdinput.c has already initialized codec_data_unit to 1,
++ * and has computed unscaled downsampled_width and downsampled_height.
++ */
++ }
++
++
++ /*
++ * Initialize for an input processing pass.
++ */
++
++ METHODDEF(void)
++ start_input_pass (j_decompress_ptr cinfo)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++
++ (*losslsd->entropy_start_pass) (cinfo);
++ (*losslsd->predict_start_pass) (cinfo);
++ (*losslsd->scaler_start_pass) (cinfo);
++ (*losslsd->diff_start_input_pass) (cinfo);
++ }
++
++
++ /*
++ * Initialize the lossless decompression codec.
++ * This is called only once, during master selection.
++ */
++
++ GLOBAL(void)
++ jinit_lossless_d_codec(j_decompress_ptr cinfo)
++ {
++ j_lossless_d_ptr losslsd;
++ boolean use_c_buffer;
++
++ /* Create subobject in permanent pool */
++ losslsd = (j_lossless_d_ptr)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
++ SIZEOF(jpeg_lossless_d_codec));
++ cinfo->codec = (struct jpeg_d_codec *) losslsd;
++
++ /* Initialize sub-modules */
++ /* Entropy decoding: either Huffman or arithmetic coding. */
++ if (cinfo->arith_code) {
++ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
++ } else {
++ jinit_lhuff_decoder(cinfo);
++ }
++
++ /* Undifferencer */
++ jinit_undifferencer(cinfo);
++
++ /* Scaler */
++ jinit_d_scaler(cinfo);
++
++ use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
++ jinit_d_diff_controller(cinfo, use_c_buffer);
++
++ /* Initialize method pointers.
++ *
++ * Note: consume_data, start_output_pass and decompress_data are
++ * assigned in jddiffct.c.
++ */
++ losslsd->pub.calc_output_dimensions = calc_output_dimensions;
++ losslsd->pub.start_input_pass = start_input_pass;
++ }
++
++ #endif /* D_LOSSLESS_SUPPORTED */
+diff -cN ../jpeg-6b/jdlossy.c ./jdlossy.c
+*** ../jpeg-6b/jdlossy.c
+--- ./jdlossy.c Tue Apr 27 14:58:27 1999
+***************
+*** 0 ****
+--- 1,228 ----
++ /*
++ * jdlossy.c
++ *
++ * Copyright (C) 1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains the control logic for the lossy JPEG decompressor.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossy.h"
++
++
++ /*
++ * Compute output image dimensions and related values.
++ */
++
++ METHODDEF(void)
++ calc_output_dimensions (j_decompress_ptr cinfo)
++ {
++ #ifdef IDCT_SCALING_SUPPORTED
++ int ci;
++ jpeg_component_info *compptr;
++
++ /* Compute actual output image dimensions and DCT scaling choices. */
++ if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
++ /* Provide 1/8 scaling */
++ cinfo->output_width = (JDIMENSION)
++ jdiv_round_up((long) cinfo->image_width, 8L);
++ cinfo->output_height = (JDIMENSION)
++ jdiv_round_up((long) cinfo->image_height, 8L);
++ cinfo->min_codec_data_unit = 1;
++ } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
++ /* Provide 1/4 scaling */
++ cinfo->output_width = (JDIMENSION)
++ jdiv_round_up((long) cinfo->image_width, 4L);
++ cinfo->output_height = (JDIMENSION)
++ jdiv_round_up((long) cinfo->image_height, 4L);
++ cinfo->min_codec_data_unit = 2;
++ } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
++ /* Provide 1/2 scaling */
++ cinfo->output_width = (JDIMENSION)
++ jdiv_round_up((long) cinfo->image_width, 2L);
++ cinfo->output_height = (JDIMENSION)
++ jdiv_round_up((long) cinfo->image_height, 2L);
++ cinfo->min_codec_data_unit = 4;
++ } else {
++ /* Provide 1/1 scaling */
++ cinfo->output_width = cinfo->image_width;
++ cinfo->output_height = cinfo->image_height;
++ cinfo->min_codec_data_unit = DCTSIZE;
++ }
++ /* In selecting the actual DCT scaling for each component, we try to
++ * scale up the chroma components via IDCT scaling rather than upsampling.
++ * This saves time if the upsampler gets to use 1:1 scaling.
++ * Note this code assumes that the supported DCT scalings are powers of 2.
++ */
++ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
++ ci++, compptr++) {
++ int ssize = cinfo->min_codec_data_unit;
++ while (ssize < DCTSIZE &&
++ (compptr->h_samp_factor * ssize * 2 <=
++ cinfo->max_h_samp_factor * cinfo->min_codec_data_unit) &&
++ (compptr->v_samp_factor * ssize * 2 <=
++ cinfo->max_v_samp_factor * cinfo->min_codec_data_unit)) {
++ ssize = ssize * 2;
++ }
++ compptr->codec_data_unit = ssize;
++ }
++
++ /* Recompute downsampled dimensions of components;
++ * application needs to know these if using raw downsampled data.
++ */
++ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
++ ci++, compptr++) {
++ /* Size in samples, after IDCT scaling */
++ compptr->downsampled_width = (JDIMENSION)
++ jdiv_round_up((long) cinfo->image_width *
++ (long) (compptr->h_samp_factor * compptr->codec_data_unit),
++ (long) (cinfo->max_h_samp_factor * DCTSIZE));
++ compptr->downsampled_height = (JDIMENSION)
++ jdiv_round_up((long) cinfo->image_height *
++ (long) (compptr->v_samp_factor * compptr->codec_data_unit),
++ (long) (cinfo->max_v_samp_factor * DCTSIZE));
++ }
++
++ #else /* !IDCT_SCALING_SUPPORTED */
++
++ /* Hardwire it to "no scaling" */
++ cinfo->output_width = cinfo->image_width;
++ cinfo->output_height = cinfo->image_height;
++ /* jdinput.c has already initialized codec_data_unit to DCTSIZE,
++ * and has computed unscaled downsampled_width and downsampled_height.
++ */
++
++ #endif /* IDCT_SCALING_SUPPORTED */
++ }
++
++
++ /*
++ * Save away a copy of the Q-table referenced by each component present
++ * in the current scan, unless already saved during a prior scan.
++ *
++ * In a multiple-scan JPEG file, the encoder could assign different components
++ * the same Q-table slot number, but change table definitions between scans
++ * so that each component uses a different Q-table. (The IJG encoder is not
++ * currently capable of doing this, but other encoders might.) Since we want
++ * to be able to dequantize all the components at the end of the file, this
++ * means that we have to save away the table actually used for each component.
++ * We do this by copying the table at the start of the first scan containing
++ * the component.
++ * The JPEG spec prohibits the encoder from changing the contents of a Q-table
++ * slot between scans of a component using that slot. If the encoder does so
++ * anyway, this decoder will simply use the Q-table values that were current
++ * at the start of the first scan for the component.
++ *
++ * The decompressor output side looks only at the saved quant tables,
++ * not at the current Q-table slots.
++ */
++
++ LOCAL(void)
++ latch_quant_tables (j_decompress_ptr cinfo)
++ {
++ int ci, qtblno;
++ jpeg_component_info *compptr;
++ JQUANT_TBL * qtbl;
++
++ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
++ compptr = cinfo->cur_comp_info[ci];
++ /* No work if we already saved Q-table for this component */
++ if (compptr->quant_table != NULL)
++ continue;
++ /* Make sure specified quantization table is present */
++ qtblno = compptr->quant_tbl_no;
++ if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
++ cinfo->quant_tbl_ptrs[qtblno] == NULL)
++ ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
++ /* OK, save away the quantization table */
++ qtbl = (JQUANT_TBL *)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ SIZEOF(JQUANT_TBL));
++ MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
++ compptr->quant_table = qtbl;
++ }
++ }
++
++
++ /*
++ * Initialize for an input processing pass.
++ */
++
++ METHODDEF(void)
++ start_input_pass (j_decompress_ptr cinfo)
++ {
++ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
++
++ latch_quant_tables(cinfo);
++ (*lossyd->entropy_start_pass) (cinfo);
++ (*lossyd->coef_start_input_pass) (cinfo);
++ }
++
++
++ /*
++ * Initialize for an output processing pass.
++ */
++
++ METHODDEF(void)
++ start_output_pass (j_decompress_ptr cinfo)
++ {
++ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
++
++ (*lossyd->idct_start_pass) (cinfo);
++ (*lossyd->coef_start_output_pass) (cinfo);
++ }
++
++ /*
++ * Initialize the lossy decompression codec.
++ * This is called only once, during master selection.
++ */
++
++ GLOBAL(void)
++ jinit_lossy_d_codec (j_decompress_ptr cinfo)
++ {
++ j_lossy_d_ptr lossyd;
++ boolean use_c_buffer;
++
++ /* Create subobject in permanent pool */
++ lossyd = (j_lossy_d_ptr)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
++ SIZEOF(jpeg_lossy_d_codec));
++ cinfo->codec = (struct jpeg_d_codec *) lossyd;
++
++ /* Initialize sub-modules */
++
++ /* Inverse DCT */
++ jinit_inverse_dct(cinfo);
++ /* Entropy decoding: either Huffman or arithmetic coding. */
++ if (cinfo->arith_code) {
++ ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
++ } else {
++ if (cinfo->process == JPROC_PROGRESSIVE) {
++ #ifdef D_PROGRESSIVE_SUPPORTED
++ jinit_phuff_decoder(cinfo);
++ #else
++ ERREXIT(cinfo, JERR_NOT_COMPILED);
++ #endif
++ } else
++ jinit_shuff_decoder(cinfo);
++ }
++
++ use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
++ jinit_d_coef_controller(cinfo, use_c_buffer);
++
++ /* Initialize method pointers.
++ *
++ * Note: consume_data and decompress_data are assigned in jdcoefct.c.
++ */
++ lossyd->pub.calc_output_dimensions = calc_output_dimensions;
++ lossyd->pub.start_input_pass = start_input_pass;
++ lossyd->pub.start_output_pass = start_output_pass;
++ }
++
++
++
++
+diff -cN ../jpeg-6b/jdmainct.c ./jdmainct.c
+*** ../jpeg-6b/jdmainct.c Sat Jan 6 18:27:17 1996
+--- ./jdmainct.c Tue Apr 27 14:58:27 1999
+***************
+*** 1,7 ****
+ /*
+ * jdmainct.c
+ *
+! * Copyright (C) 1994-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jdmainct.c
+ *
+! * Copyright (C) 1994-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 26,43 ****
+ * rescaling, and doing this in an efficient fashion is a bit tricky.
+ *
+ * Postprocessor input data is counted in "row groups". A row group
+! * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
+! * sample rows of each component. (We require DCT_scaled_size values to be
+! * chosen such that these numbers are integers. In practice DCT_scaled_size
+ * values will likely be powers of two, so we actually have the stronger
+! * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
+ * Upsampling will typically produce max_v_samp_factor pixel rows from each
+ * row group (times any additional scale factor that the upsampler is
+ * applying).
+ *
+! * The coefficient controller will deliver data to us one iMCU row at a time;
+! * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
+! * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
+ * to one row of MCUs when the image is fully interleaved.) Note that the
+ * number of sample rows varies across components, but the number of row
+ * groups does not. Some garbage sample rows may be included in the last iMCU
+--- 26,43 ----
+ * rescaling, and doing this in an efficient fashion is a bit tricky.
+ *
+ * Postprocessor input data is counted in "row groups". A row group
+! * is defined to be (v_samp_factor * codec_data_unit / min_codec_data_unit)
+! * sample rows of each component. (We require codec_data_unit values to be
+! * chosen such that these numbers are integers. In practice codec_data_unit
+ * values will likely be powers of two, so we actually have the stronger
+! * condition that codec_data_unit / min_codec_data_unit is an integer.)
+ * Upsampling will typically produce max_v_samp_factor pixel rows from each
+ * row group (times any additional scale factor that the upsampler is
+ * applying).
+ *
+! * The decompression codec will deliver data to us one iMCU row at a time;
+! * each iMCU row contains v_samp_factor * codec_data_unit sample rows, or
+! * exactly min_codec_data_unit row groups. (This amount of data corresponds
+ * to one row of MCUs when the image is fully interleaved.) Note that the
+ * number of sample rows varies across components, but the number of row
+ * groups does not. Some garbage sample rows may be included in the last iMCU
+***************
+*** 64,70 ****
+ * supporting arbitrary output rescaling might wish for more than one row
+ * group of context when shrinking the image; tough, we don't handle that.
+ * (This is justified by the assumption that downsizing will be handled mostly
+! * by adjusting the DCT_scaled_size values, so that the actual scale factor at
+ * the upsample step needn't be much less than one.)
+ *
+ * To provide the desired context, we have to retain the last two row groups
+--- 64,70 ----
+ * supporting arbitrary output rescaling might wish for more than one row
+ * group of context when shrinking the image; tough, we don't handle that.
+ * (This is justified by the assumption that downsizing will be handled mostly
+! * by adjusting the codec_data_unit values, so that the actual scale factor at
+ * the upsample step needn't be much less than one.)
+ *
+ * To provide the desired context, we have to retain the last two row groups
+***************
+*** 74,80 ****
+ * We could do this most simply by copying data around in our buffer, but
+ * that'd be very slow. We can avoid copying any data by creating a rather
+ * strange pointer structure. Here's how it works. We allocate a workspace
+! * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
+ * of row groups per iMCU row). We create two sets of redundant pointers to
+ * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
+ * pointer lists look like this:
+--- 74,80 ----
+ * We could do this most simply by copying data around in our buffer, but
+ * that'd be very slow. We can avoid copying any data by creating a rather
+ * strange pointer structure. Here's how it works. We allocate a workspace
+! * consisting of M+2 row groups (where M = min_codec_data_unit is the number
+ * of row groups per iMCU row). We create two sets of redundant pointers to
+ * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
+ * pointer lists look like this:
+***************
+*** 99,109 ****
+ * the first or last sample row as necessary (this is cheaper than copying
+ * sample rows around).
+ *
+! * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
+ * situation each iMCU row provides only one row group so the buffering logic
+ * must be different (eg, we must read two iMCU rows before we can emit the
+ * first row group). For now, we simply do not support providing context
+! * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
+ * be worth providing --- if someone wants a 1/8th-size preview, they probably
+ * want it quick and dirty, so a context-free upsampler is sufficient.
+ */
+--- 99,109 ----
+ * the first or last sample row as necessary (this is cheaper than copying
+ * sample rows around).
+ *
+! * This scheme breaks down if M < 2, ie, min_codec_data_unit is 1. In that
+ * situation each iMCU row provides only one row group so the buffering logic
+ * must be different (eg, we must read two iMCU rows before we can emit the
+ * first row group). For now, we simply do not support providing context
+! * rows when min_codec_data_unit is 1. That combination seems unlikely to
+ * be worth providing --- if someone wants a 1/8th-size preview, they probably
+ * want it quick and dirty, so a context-free upsampler is sufficient.
+ */
+***************
+*** 161,167 ****
+ {
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+ int ci, rgroup;
+! int M = cinfo->min_DCT_scaled_size;
+ jpeg_component_info *compptr;
+ JSAMPARRAY xbuf;
+
+--- 161,167 ----
+ {
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+ int ci, rgroup;
+! int M = cinfo->min_codec_data_unit;
+ jpeg_component_info *compptr;
+ JSAMPARRAY xbuf;
+
+***************
+*** 175,182 ****
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+! rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+! cinfo->min_DCT_scaled_size; /* height of a row group of component */
+ /* Get space for pointer lists --- M+4 row groups in each list.
+ * We alloc both pointer lists with one call to save a few cycles.
+ */
+--- 175,182 ----
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+! rgroup = (compptr->v_samp_factor * compptr->codec_data_unit) /
+! cinfo->min_codec_data_unit; /* height of a row group of component */
+ /* Get space for pointer lists --- M+4 row groups in each list.
+ * We alloc both pointer lists with one call to save a few cycles.
+ */
+***************
+*** 202,215 ****
+ {
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+ int ci, i, rgroup;
+! int M = cinfo->min_DCT_scaled_size;
+ jpeg_component_info *compptr;
+ JSAMPARRAY buf, xbuf0, xbuf1;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+! rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+! cinfo->min_DCT_scaled_size; /* height of a row group of component */
+ xbuf0 = main->xbuffer[0][ci];
+ xbuf1 = main->xbuffer[1][ci];
+ /* First copy the workspace pointers as-is */
+--- 202,215 ----
+ {
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+ int ci, i, rgroup;
+! int M = cinfo->min_codec_data_unit;
+ jpeg_component_info *compptr;
+ JSAMPARRAY buf, xbuf0, xbuf1;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+! rgroup = (compptr->v_samp_factor * compptr->codec_data_unit) /
+! cinfo->min_codec_data_unit; /* height of a row group of component */
+ xbuf0 = main->xbuffer[0][ci];
+ xbuf1 = main->xbuffer[1][ci];
+ /* First copy the workspace pointers as-is */
+***************
+*** 242,255 ****
+ {
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+ int ci, i, rgroup;
+! int M = cinfo->min_DCT_scaled_size;
+ jpeg_component_info *compptr;
+ JSAMPARRAY xbuf0, xbuf1;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+! rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+! cinfo->min_DCT_scaled_size; /* height of a row group of component */
+ xbuf0 = main->xbuffer[0][ci];
+ xbuf1 = main->xbuffer[1][ci];
+ for (i = 0; i < rgroup; i++) {
+--- 242,255 ----
+ {
+ my_main_ptr main = (my_main_ptr) cinfo->main;
+ int ci, i, rgroup;
+! int M = cinfo->min_codec_data_unit;
+ jpeg_component_info *compptr;
+ JSAMPARRAY xbuf0, xbuf1;
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+! rgroup = (compptr->v_samp_factor * compptr->codec_data_unit) /
+! cinfo->min_codec_data_unit; /* height of a row group of component */
+ xbuf0 = main->xbuffer[0][ci];
+ xbuf1 = main->xbuffer[1][ci];
+ for (i = 0; i < rgroup; i++) {
+***************
+*** 277,284 ****
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Count sample rows in one iMCU row and in one row group */
+! iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
+! rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
+ /* Count nondummy sample rows remaining for this component */
+ rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
+ if (rows_left == 0) rows_left = iMCUheight;
+--- 277,284 ----
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+ /* Count sample rows in one iMCU row and in one row group */
+! iMCUheight = compptr->v_samp_factor * compptr->codec_data_unit;
+! rgroup = iMCUheight / cinfo->min_codec_data_unit;
+ /* Count nondummy sample rows remaining for this component */
+ rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
+ if (rows_left == 0) rows_left = iMCUheight;
+***************
+*** 351,363 ****
+
+ /* Read input data if we haven't filled the main buffer yet */
+ if (! main->buffer_full) {
+! if (! (*cinfo->coef->decompress_data) (cinfo, main->buffer))
+ return; /* suspension forced, can do nothing more */
+ main->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
+ }
+
+! /* There are always min_DCT_scaled_size row groups in an iMCU row. */
+! rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
+ /* Note: at the bottom of the image, we may pass extra garbage row groups
+ * to the postprocessor. The postprocessor has to check for bottom
+ * of image anyway (at row resolution), so no point in us doing it too.
+--- 351,363 ----
+
+ /* Read input data if we haven't filled the main buffer yet */
+ if (! main->buffer_full) {
+! if (! (*cinfo->codec->decompress_data) (cinfo, main->buffer))
+ return; /* suspension forced, can do nothing more */
+ main->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
+ }
+
+! /* There are always min_codec_data_unit row groups in an iMCU row. */
+! rowgroups_avail = (JDIMENSION) cinfo->min_codec_data_unit;
+ /* Note: at the bottom of the image, we may pass extra garbage row groups
+ * to the postprocessor. The postprocessor has to check for bottom
+ * of image anyway (at row resolution), so no point in us doing it too.
+***************
+*** 390,396 ****
+
+ /* Read input data if we haven't filled the main buffer yet */
+ if (! main->buffer_full) {
+! if (! (*cinfo->coef->decompress_data) (cinfo,
+ main->xbuffer[main->whichptr]))
+ return; /* suspension forced, can do nothing more */
+ main->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
+--- 390,396 ----
+
+ /* Read input data if we haven't filled the main buffer yet */
+ if (! main->buffer_full) {
+! if (! (*cinfo->codec->decompress_data) (cinfo,
+ main->xbuffer[main->whichptr]))
+ return; /* suspension forced, can do nothing more */
+ main->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
+***************
+*** 417,423 ****
+ case CTX_PREPARE_FOR_IMCU:
+ /* Prepare to process first M-1 row groups of this iMCU row */
+ main->rowgroup_ctr = 0;
+! main->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
+ /* Check for bottom of image: if so, tweak pointers to "duplicate"
+ * the last sample row, and adjust rowgroups_avail to ignore padding rows.
+ */
+--- 417,423 ----
+ case CTX_PREPARE_FOR_IMCU:
+ /* Prepare to process first M-1 row groups of this iMCU row */
+ main->rowgroup_ctr = 0;
+! main->rowgroups_avail = (JDIMENSION) (cinfo->min_codec_data_unit - 1);
+ /* Check for bottom of image: if so, tweak pointers to "duplicate"
+ * the last sample row, and adjust rowgroups_avail to ignore padding rows.
+ */
+***************
+*** 440,447 ****
+ main->buffer_full = FALSE;
+ /* Still need to process last row group of this iMCU row, */
+ /* which is saved at index M+1 of the other xbuffer */
+! main->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
+! main->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
+ main->context_state = CTX_POSTPONED_ROW;
+ }
+ }
+--- 440,447 ----
+ main->buffer_full = FALSE;
+ /* Still need to process last row group of this iMCU row, */
+ /* which is saved at index M+1 of the other xbuffer */
+! main->rowgroup_ctr = (JDIMENSION) (cinfo->min_codec_data_unit + 1);
+! main->rowgroups_avail = (JDIMENSION) (cinfo->min_codec_data_unit + 2);
+ main->context_state = CTX_POSTPONED_ROW;
+ }
+ }
+***************
+*** 492,512 ****
+ * ngroups is the number of row groups we need.
+ */
+ if (cinfo->upsample->need_context_rows) {
+! if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
+ ERREXIT(cinfo, JERR_NOTIMPL);
+ alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
+! ngroups = cinfo->min_DCT_scaled_size + 2;
+ } else {
+! ngroups = cinfo->min_DCT_scaled_size;
+ }
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+! rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+! cinfo->min_DCT_scaled_size; /* height of a row group of component */
+ main->buffer[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! compptr->width_in_blocks * compptr->DCT_scaled_size,
+ (JDIMENSION) (rgroup * ngroups));
+ }
+ }
+--- 492,512 ----
+ * ngroups is the number of row groups we need.
+ */
+ if (cinfo->upsample->need_context_rows) {
+! if (cinfo->min_codec_data_unit < 2) /* unsupported, see comments above */
+ ERREXIT(cinfo, JERR_NOTIMPL);
+ alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
+! ngroups = cinfo->min_codec_data_unit + 2;
+ } else {
+! ngroups = cinfo->min_codec_data_unit;
+ }
+
+ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+ ci++, compptr++) {
+! rgroup = (compptr->v_samp_factor * compptr->codec_data_unit) /
+! cinfo->min_codec_data_unit; /* height of a row group of component */
+ main->buffer[ci] = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+! compptr->width_in_data_units * compptr->codec_data_unit,
+ (JDIMENSION) (rgroup * ngroups));
+ }
+ }
+diff -cN ../jpeg-6b/jdmarker.c ./jdmarker.c
+*** ../jpeg-6b/jdmarker.c Sat Feb 21 15:24:50 1998
+--- ./jdmarker.c Tue Apr 27 14:58:27 1999
+***************
+*** 234,240 ****
+
+
+ LOCAL(boolean)
+! get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
+ /* Process a SOFn marker */
+ {
+ INT32 length;
+--- 234,241 ----
+
+
+ LOCAL(boolean)
+! get_sof (j_decompress_ptr cinfo, J_CODEC_PROCESS process, boolean is_arith,
+! int data_unit)
+ /* Process a SOFn marker */
+ {
+ INT32 length;
+***************
+*** 242,248 ****
+ jpeg_component_info * compptr;
+ INPUT_VARS(cinfo);
+
+! cinfo->progressive_mode = is_prog;
+ cinfo->arith_code = is_arith;
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+--- 243,250 ----
+ jpeg_component_info * compptr;
+ INPUT_VARS(cinfo);
+
+! cinfo->data_unit = data_unit;
+! cinfo->process = process;
+ cinfo->arith_code = is_arith;
+
+ INPUT_2BYTES(cinfo, length, return FALSE);
+***************
+*** 976,1007 ****
+
+ case M_SOF0: /* Baseline */
+ case M_SOF1: /* Extended sequential, Huffman */
+! if (! get_sof(cinfo, FALSE, FALSE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF2: /* Progressive, Huffman */
+! if (! get_sof(cinfo, TRUE, FALSE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF9: /* Extended sequential, arithmetic */
+! if (! get_sof(cinfo, FALSE, TRUE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF10: /* Progressive, arithmetic */
+! if (! get_sof(cinfo, TRUE, TRUE))
+ return JPEG_SUSPENDED;
+ break;
+
+ /* Currently unsupported SOFn types */
+- case M_SOF3: /* Lossless, Huffman */
+ case M_SOF5: /* Differential sequential, Huffman */
+ case M_SOF6: /* Differential progressive, Huffman */
+ case M_SOF7: /* Differential lossless, Huffman */
+ case M_JPG: /* Reserved for JPEG extensions */
+- case M_SOF11: /* Lossless, arithmetic */
+ case M_SOF13: /* Differential sequential, arithmetic */
+ case M_SOF14: /* Differential progressive, arithmetic */
+ case M_SOF15: /* Differential lossless, arithmetic */
+--- 978,1017 ----
+
+ case M_SOF0: /* Baseline */
+ case M_SOF1: /* Extended sequential, Huffman */
+! if (! get_sof(cinfo, JPROC_SEQUENTIAL, FALSE, DCTSIZE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF2: /* Progressive, Huffman */
+! if (! get_sof(cinfo, JPROC_PROGRESSIVE, FALSE, DCTSIZE))
+ return JPEG_SUSPENDED;
+ break;
+
++ case M_SOF3: /* Lossless, Huffman */
++ if (! get_sof(cinfo, JPROC_LOSSLESS, FALSE, 1))
++ return JPEG_SUSPENDED;
++ break;
++
+ case M_SOF9: /* Extended sequential, arithmetic */
+! if (! get_sof(cinfo, JPROC_SEQUENTIAL, TRUE, DCTSIZE))
+ return JPEG_SUSPENDED;
+ break;
+
+ case M_SOF10: /* Progressive, arithmetic */
+! if (! get_sof(cinfo, JPROC_PROGRESSIVE, TRUE, DCTSIZE))
+! return JPEG_SUSPENDED;
+! break;
+!
+! case M_SOF11: /* Lossless, arithmetic */
+! if (! get_sof(cinfo, JPROC_LOSSLESS, TRUE, 1))
+ return JPEG_SUSPENDED;
+ break;
+
+ /* Currently unsupported SOFn types */
+ case M_SOF5: /* Differential sequential, Huffman */
+ case M_SOF6: /* Differential progressive, Huffman */
+ case M_SOF7: /* Differential lossless, Huffman */
+ case M_JPG: /* Reserved for JPEG extensions */
+ case M_SOF13: /* Differential sequential, arithmetic */
+ case M_SOF14: /* Differential progressive, arithmetic */
+ case M_SOF15: /* Differential lossless, arithmetic */
+diff -cN ../jpeg-6b/jdmaster.c ./jdmaster.c
+*** ../jpeg-6b/jdmaster.c Fri Nov 7 11:25:45 1997
+--- ./jdmaster.c Tue Apr 27 14:58:27 1999
+***************
+*** 1,7 ****
+ /*
+ * jdmaster.c
+ *
+! * Copyright (C) 1991-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jdmaster.c
+ *
+! * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 60,69 ****
+ cinfo->comp_info[1].v_samp_factor != 1 ||
+ cinfo->comp_info[2].v_samp_factor != 1)
+ return FALSE;
+! /* furthermore, it doesn't work if we've scaled the IDCTs differently */
+! if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
+! cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
+! cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
+ return FALSE;
+ /* ??? also need to test for upsample-time rescaling, when & if supported */
+ return TRUE; /* by golly, it'll work... */
+--- 60,70 ----
+ cinfo->comp_info[1].v_samp_factor != 1 ||
+ cinfo->comp_info[2].v_samp_factor != 1)
+ return FALSE;
+! /* furthermore, it doesn't work if each component has been
+! processed differently */
+! if (cinfo->comp_info[0].codec_data_unit != cinfo->min_codec_data_unit ||
+! cinfo->comp_info[1].codec_data_unit != cinfo->min_codec_data_unit ||
+! cinfo->comp_info[2].codec_data_unit != cinfo->min_codec_data_unit)
+ return FALSE;
+ /* ??? also need to test for upsample-time rescaling, when & if supported */
+ return TRUE; /* by golly, it'll work... */
+***************
+*** 84,172 ****
+ jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
+ /* Do computations that are needed before master selection phase */
+ {
+- #ifdef IDCT_SCALING_SUPPORTED
+- int ci;
+- jpeg_component_info *compptr;
+- #endif
+-
+ /* Prevent application from calling me at wrong times */
+ if (cinfo->global_state != DSTATE_READY)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+! #ifdef IDCT_SCALING_SUPPORTED
+!
+! /* Compute actual output image dimensions and DCT scaling choices. */
+! if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
+! /* Provide 1/8 scaling */
+! cinfo->output_width = (JDIMENSION)
+! jdiv_round_up((long) cinfo->image_width, 8L);
+! cinfo->output_height = (JDIMENSION)
+! jdiv_round_up((long) cinfo->image_height, 8L);
+! cinfo->min_DCT_scaled_size = 1;
+! } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
+! /* Provide 1/4 scaling */
+! cinfo->output_width = (JDIMENSION)
+! jdiv_round_up((long) cinfo->image_width, 4L);
+! cinfo->output_height = (JDIMENSION)
+! jdiv_round_up((long) cinfo->image_height, 4L);
+! cinfo->min_DCT_scaled_size = 2;
+! } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
+! /* Provide 1/2 scaling */
+! cinfo->output_width = (JDIMENSION)
+! jdiv_round_up((long) cinfo->image_width, 2L);
+! cinfo->output_height = (JDIMENSION)
+! jdiv_round_up((long) cinfo->image_height, 2L);
+! cinfo->min_DCT_scaled_size = 4;
+! } else {
+! /* Provide 1/1 scaling */
+! cinfo->output_width = cinfo->image_width;
+! cinfo->output_height = cinfo->image_height;
+! cinfo->min_DCT_scaled_size = DCTSIZE;
+! }
+! /* In selecting the actual DCT scaling for each component, we try to
+! * scale up the chroma components via IDCT scaling rather than upsampling.
+! * This saves time if the upsampler gets to use 1:1 scaling.
+! * Note this code assumes that the supported DCT scalings are powers of 2.
+! */
+! for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+! ci++, compptr++) {
+! int ssize = cinfo->min_DCT_scaled_size;
+! while (ssize < DCTSIZE &&
+! (compptr->h_samp_factor * ssize * 2 <=
+! cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
+! (compptr->v_samp_factor * ssize * 2 <=
+! cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
+! ssize = ssize * 2;
+! }
+! compptr->DCT_scaled_size = ssize;
+! }
+!
+! /* Recompute downsampled dimensions of components;
+! * application needs to know these if using raw downsampled data.
+! */
+! for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+! ci++, compptr++) {
+! /* Size in samples, after IDCT scaling */
+! compptr->downsampled_width = (JDIMENSION)
+! jdiv_round_up((long) cinfo->image_width *
+! (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
+! (long) (cinfo->max_h_samp_factor * DCTSIZE));
+! compptr->downsampled_height = (JDIMENSION)
+! jdiv_round_up((long) cinfo->image_height *
+! (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
+! (long) (cinfo->max_v_samp_factor * DCTSIZE));
+! }
+!
+! #else /* !IDCT_SCALING_SUPPORTED */
+!
+! /* Hardwire it to "no scaling" */
+! cinfo->output_width = cinfo->image_width;
+! cinfo->output_height = cinfo->image_height;
+! /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
+! * and has computed unscaled downsampled_width and downsampled_height.
+! */
+!
+! #endif /* IDCT_SCALING_SUPPORTED */
+
+ /* Report number of components in selected colorspace. */
+ /* Probably this should be in the color conversion module... */
+--- 85,95 ----
+ jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
+ /* Do computations that are needed before master selection phase */
+ {
+ /* Prevent application from calling me at wrong times */
+ if (cinfo->global_state != DSTATE_READY)
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+! (*cinfo->codec->calc_output_dimensions) (cinfo);
+
+ /* Report number of components in selected colorspace. */
+ /* Probably this should be in the color conversion module... */
+***************
+*** 288,294 ****
+ master_selection (j_decompress_ptr cinfo)
+ {
+ my_master_ptr master = (my_master_ptr) cinfo->master;
+- boolean use_c_buffer;
+ long samplesperrow;
+ JDIMENSION jd_samplesperrow;
+
+--- 211,216 ----
+***************
+*** 369,394 ****
+ }
+ jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
+ }
+- /* Inverse DCT */
+- jinit_inverse_dct(cinfo);
+- /* Entropy decoding: either Huffman or arithmetic coding. */
+- if (cinfo->arith_code) {
+- ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+- } else {
+- if (cinfo->progressive_mode) {
+- #ifdef D_PROGRESSIVE_SUPPORTED
+- jinit_phuff_decoder(cinfo);
+- #else
+- ERREXIT(cinfo, JERR_NOT_COMPILED);
+- #endif
+- } else
+- jinit_huff_decoder(cinfo);
+- }
+
+ /* Initialize principal buffer controllers. */
+- use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
+- jinit_d_coef_controller(cinfo, use_c_buffer);
+-
+ if (! cinfo->raw_data_out)
+ jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
+
+--- 291,298 ----
+***************
+*** 407,413 ****
+ cinfo->inputctl->has_multiple_scans) {
+ int nscans;
+ /* Estimate number of scans to set pass_limit. */
+! if (cinfo->progressive_mode) {
+ /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
+ nscans = 2 + 3 * cinfo->num_components;
+ } else {
+--- 311,317 ----
+ cinfo->inputctl->has_multiple_scans) {
+ int nscans;
+ /* Estimate number of scans to set pass_limit. */
+! if (cinfo->process == JPROC_PROGRESSIVE) {
+ /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
+ nscans = 2 + 3 * cinfo->num_components;
+ } else {
+***************
+*** 461,468 ****
+ ERREXIT(cinfo, JERR_MODE_CHANGE);
+ }
+ }
+! (*cinfo->idct->start_pass) (cinfo);
+! (*cinfo->coef->start_output_pass) (cinfo);
+ if (! cinfo->raw_data_out) {
+ if (! master->using_merged_upsample)
+ (*cinfo->cconvert->start_pass) (cinfo);
+--- 365,371 ----
+ ERREXIT(cinfo, JERR_MODE_CHANGE);
+ }
+ }
+! (*cinfo->codec->start_output_pass) (cinfo);
+ if (! cinfo->raw_data_out) {
+ if (! master->using_merged_upsample)
+ (*cinfo->cconvert->start_pass) (cinfo);
+diff -cN ../jpeg-6b/jdphuff.c ./jdphuff.c
+*** ../jpeg-6b/jdphuff.c Mon Oct 20 20:42:33 1997
+--- ./jdphuff.c Tue Apr 27 14:58:30 1999
+***************
+*** 1,7 ****
+ /*
+ * jdphuff.c
+ *
+! * Copyright (C) 1995-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jdphuff.c
+ *
+! * Copyright (C) 1995-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 17,29 ****
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
+! #include "jdhuff.h" /* Declarations shared with jdhuff.c */
+
+
+ #ifdef D_PROGRESSIVE_SUPPORTED
+
+ /*
+! * Expanded entropy decoder object for progressive Huffman decoding.
+ *
+ * The savable_state subrecord contains fields that change within an MCU,
+ * but must not be updated permanently until we complete the MCU.
+--- 17,30 ----
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
+! #include "jlossy.h" /* Private declarations for lossy subsystem */
+! #include "jdhuff.h" /* Declarations shared with jd*huff.c */
+
+
+ #ifdef D_PROGRESSIVE_SUPPORTED
+
+ /*
+! * Private entropy decoder object for progressive Huffman decoding.
+ *
+ * The savable_state subrecord contains fields that change within an MCU,
+ * but must not be updated permanently until we complete the MCU.
+***************
+*** 54,65 ****
+
+
+ typedef struct {
+! struct jpeg_entropy_decoder pub; /* public fields */
+
+ /* These fields are loaded into local variables at start of each MCU.
+ * In case of suspension, we exit WITHOUT updating them.
+ */
+- bitread_perm_state bitstate; /* Bit buffer at start of MCU */
+ savable_state saved; /* Other state at start of MCU */
+
+ /* These fields are NOT loaded into local working state. */
+--- 55,65 ----
+
+
+ typedef struct {
+! huffd_common_fields; /* Fields shared with other entropy decoders */
+
+ /* These fields are loaded into local variables at start of each MCU.
+ * In case of suspension, we exit WITHOUT updating them.
+ */
+ savable_state saved; /* Other state at start of MCU */
+
+ /* These fields are NOT loaded into local working state. */
+***************
+*** 91,97 ****
+ METHODDEF(void)
+ start_pass_phuff_decoder (j_decompress_ptr cinfo)
+ {
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ boolean is_DC_band, bad;
+ int ci, coefi, tbl;
+ int *coef_bit_ptr;
+--- 91,98 ----
+ METHODDEF(void)
+ start_pass_phuff_decoder (j_decompress_ptr cinfo)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyd->entropy_private;
+ boolean is_DC_band, bad;
+ int ci, coefi, tbl;
+ int *coef_bit_ptr;
+***************
+*** 148,161 ****
+ /* Select MCU decoding routine */
+ if (cinfo->Ah == 0) {
+ if (is_DC_band)
+! entropy->pub.decode_mcu = decode_mcu_DC_first;
+ else
+! entropy->pub.decode_mcu = decode_mcu_AC_first;
+ } else {
+ if (is_DC_band)
+! entropy->pub.decode_mcu = decode_mcu_DC_refine;
+ else
+! entropy->pub.decode_mcu = decode_mcu_AC_refine;
+ }
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+--- 149,162 ----
+ /* Select MCU decoding routine */
+ if (cinfo->Ah == 0) {
+ if (is_DC_band)
+! lossyd->entropy_decode_mcu = decode_mcu_DC_first;
+ else
+! lossyd->entropy_decode_mcu = decode_mcu_AC_first;
+ } else {
+ if (is_DC_band)
+! lossyd->entropy_decode_mcu = decode_mcu_DC_refine;
+ else
+! lossyd->entropy_decode_mcu = decode_mcu_AC_refine;
+ }
+
+ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+***************
+*** 183,189 ****
+ /* Initialize bitread state variables */
+ entropy->bitstate.bits_left = 0;
+ entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
+! entropy->pub.insufficient_data = FALSE;
+
+ /* Initialize private state variables */
+ entropy->saved.EOBRUN = 0;
+--- 184,190 ----
+ /* Initialize bitread state variables */
+ entropy->bitstate.bits_left = 0;
+ entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
+! entropy->insufficient_data = FALSE;
+
+ /* Initialize private state variables */
+ entropy->saved.EOBRUN = 0;
+***************
+*** 227,233 ****
+ LOCAL(boolean)
+ process_restart (j_decompress_ptr cinfo)
+ {
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ int ci;
+
+ /* Throw away any unused bits remaining in bit buffer; */
+--- 228,235 ----
+ LOCAL(boolean)
+ process_restart (j_decompress_ptr cinfo)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyd->entropy_private;
+ int ci;
+
+ /* Throw away any unused bits remaining in bit buffer; */
+***************
+*** 254,260 ****
+ * leaving the flag set.
+ */
+ if (cinfo->unread_marker == 0)
+! entropy->pub.insufficient_data = FALSE;
+
+ return TRUE;
+ }
+--- 256,262 ----
+ * leaving the flag set.
+ */
+ if (cinfo->unread_marker == 0)
+! entropy->insufficient_data = FALSE;
+
+ return TRUE;
+ }
+***************
+*** 285,291 ****
+ METHODDEF(boolean)
+ decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ int Al = cinfo->Al;
+ register int s, r;
+ int blkn, ci;
+--- 287,294 ----
+ METHODDEF(boolean)
+ decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyd->entropy_private;
+ int Al = cinfo->Al;
+ register int s, r;
+ int blkn, ci;
+***************
+*** 305,311 ****
+ /* If we've run out of data, just leave the MCU set to zeroes.
+ * This way, we return uniform gray for the remainder of the segment.
+ */
+! if (! entropy->pub.insufficient_data) {
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+--- 308,314 ----
+ /* If we've run out of data, just leave the MCU set to zeroes.
+ * This way, we return uniform gray for the remainder of the segment.
+ */
+! if (! entropy->insufficient_data) {
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+***************
+*** 313,319 ****
+
+ /* Outer loop handles each block in the MCU */
+
+! for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+--- 316,322 ----
+
+ /* Outer loop handles each block in the MCU */
+
+! for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+ ci = cinfo->MCU_membership[blkn];
+ compptr = cinfo->cur_comp_info[ci];
+***************
+*** 356,362 ****
+ METHODDEF(boolean)
+ decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ int Se = cinfo->Se;
+ int Al = cinfo->Al;
+ register int s, k, r;
+--- 359,366 ----
+ METHODDEF(boolean)
+ decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyd->entropy_private;
+ int Se = cinfo->Se;
+ int Al = cinfo->Al;
+ register int s, k, r;
+***************
+*** 375,381 ****
+ /* If we've run out of data, just leave the MCU set to zeroes.
+ * This way, we return uniform gray for the remainder of the segment.
+ */
+! if (! entropy->pub.insufficient_data) {
+
+ /* Load up working state.
+ * We can avoid loading/saving bitread state if in an EOB run.
+--- 379,385 ----
+ /* If we've run out of data, just leave the MCU set to zeroes.
+ * This way, we return uniform gray for the remainder of the segment.
+ */
+! if (! entropy->insufficient_data) {
+
+ /* Load up working state.
+ * We can avoid loading/saving bitread state if in an EOB run.
+***************
+*** 441,447 ****
+ METHODDEF(boolean)
+ decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
+ int blkn;
+ JBLOCKROW block;
+--- 445,452 ----
+ METHODDEF(boolean)
+ decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyd->entropy_private;
+ int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
+ int blkn;
+ JBLOCKROW block;
+***************
+*** 463,469 ****
+
+ /* Outer loop handles each block in the MCU */
+
+! for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+
+ /* Encoded data is simply the next bit of the two's-complement DC value */
+--- 468,474 ----
+
+ /* Outer loop handles each block in the MCU */
+
+! for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
+ block = MCU_data[blkn];
+
+ /* Encoded data is simply the next bit of the two's-complement DC value */
+***************
+*** 490,496 ****
+ METHODDEF(boolean)
+ decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
+ int Se = cinfo->Se;
+ int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
+ int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
+--- 495,502 ----
+ METHODDEF(boolean)
+ decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
+ {
+! j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+! phuff_entropy_ptr entropy = (phuff_entropy_ptr) lossyd->entropy_private;
+ int Se = cinfo->Se;
+ int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
+ int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
+***************
+*** 512,518 ****
+
+ /* If we've run out of data, don't modify the MCU.
+ */
+! if (! entropy->pub.insufficient_data) {
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+--- 518,524 ----
+
+ /* If we've run out of data, don't modify the MCU.
+ */
+! if (! entropy->insufficient_data) {
+
+ /* Load up working state */
+ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
+***************
+*** 640,645 ****
+--- 646,652 ----
+ GLOBAL(void)
+ jinit_phuff_decoder (j_decompress_ptr cinfo)
+ {
++ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
+ phuff_entropy_ptr entropy;
+ int *coef_bit_ptr;
+ int ci, i;
+***************
+*** 647,654 ****
+ entropy = (phuff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(phuff_entropy_decoder));
+! cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
+! entropy->pub.start_pass = start_pass_phuff_decoder;
+
+ /* Mark derived tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+--- 654,661 ----
+ entropy = (phuff_entropy_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(phuff_entropy_decoder));
+! lossyd->entropy_private = (void *) entropy;
+! lossyd->entropy_start_pass = start_pass_phuff_decoder;
+
+ /* Mark derived tables unallocated */
+ for (i = 0; i < NUM_HUFF_TBLS; i++) {
+diff -cN ../jpeg-6b/jdpred.c ./jdpred.c
+*** ../jpeg-6b/jdpred.c
+--- ./jdpred.c Tue Apr 27 14:58:30 1999
+***************
+*** 0 ****
+--- 1,247 ----
++ /*
++ * jdpred.c
++ *
++ * Copyright (C) 1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains sample undifferencing (reconstruction) for lossless JPEG.
++ *
++ * In order to avoid paying the performance penalty of having to check the
++ * predictor being used and the row being processed for each call of the
++ * undifferencer, and to promote optimization, we have separate undifferencing
++ * functions for each case.
++ *
++ * We are able to avoid duplicating source code by implementing the predictors
++ * and undifferencers as macros. Each of the undifferencing functions are
++ * simply wrappers around an UNDIFFERENCE macro with the appropriate PREDICTOR
++ * macro passed as an argument.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossls.h" /* Private declarations for lossless codec */
++
++
++ #ifdef D_LOSSLESS_SUPPORTED
++
++ /* Predictor for the first column of the first row: 2^(P-Pt-1) */
++ #define INITIAL_PREDICTORx (1 << (cinfo->data_precision - cinfo->Al - 1))
++
++ /* Predictor for the first column of the remaining rows: Rb */
++ #define INITIAL_PREDICTOR2 GETJSAMPLE(prev_row[0])
++
++
++ /*
++ * 1-Dimensional undifferencer routine.
++ *
++ * This macro implements the 1-D horizontal predictor (1). INITIAL_PREDICTOR
++ * is used as the special case predictor for the first column, which must be
++ * either INITIAL_PREDICTOR2 or INITIAL_PREDICTORx. The remaining samples
++ * use PREDICTOR1.
++ *
++ * The reconstructed sample is supposed to be calculated modulo 2^16, so we
++ * logically AND the result with 0xFFFF.
++ */
++
++ #define UNDIFFERENCE_1D(INITIAL_PREDICTOR) \
++ int xindex; \
++ int Ra; \
++ \
++ Ra = (diff_buf[0] + INITIAL_PREDICTOR) & 0xFFFF; \
++ undiff_buf[0] = Ra; \
++ \
++ for (xindex = 1; xindex < width; xindex++) { \
++ Ra = (diff_buf[xindex] + PREDICTOR1) & 0xFFFF; \
++ undiff_buf[xindex] = Ra; \
++ }
++
++ /*
++ * 2-Dimensional undifferencer routine.
++ *
++ * This macro implements the 2-D horizontal predictors (#2-7). PREDICTOR2 is
++ * used as the special case predictor for the first column. The remaining
++ * samples use PREDICTOR, which is a function of Ra, Rb, Rc.
++ *
++ * Because prev_row and output_buf may point to the same storage area (in an
++ * interleaved image with Vi=1, for example), we must take care to buffer Rb/Rc
++ * before writing the current reconstructed sample value into output_buf.
++ *
++ * The reconstructed sample is supposed to be calculated modulo 2^16, so we
++ * logically AND the result with 0xFFFF.
++ */
++
++ #define UNDIFFERENCE_2D(PREDICTOR) \
++ int xindex; \
++ int Ra, Rb, Rc; \
++ \
++ Rb = GETJSAMPLE(prev_row[0]); \
++ Ra = (diff_buf[0] + PREDICTOR2) & 0xFFFF; \
++ undiff_buf[0] = Ra; \
++ \
++ for (xindex = 1; xindex < width; xindex++) { \
++ Rc = Rb; \
++ Rb = GETJSAMPLE(prev_row[xindex]); \
++ Ra = (diff_buf[xindex] + PREDICTOR) & 0xFFFF; \
++ undiff_buf[xindex] = Ra; \
++ }
++
++
++ /*
++ * Undifferencers for the all rows but the first in a scan or restart interval.
++ * The first sample in the row is undifferenced using the vertical
++ * predictor (2). The rest of the samples are undifferenced using the
++ * predictor specified in the scan header.
++ */
++
++ METHODDEF(void)
++ jpeg_undifference1(j_decompress_ptr cinfo, int comp_index,
++ JDIFFROW diff_buf, JDIFFROW prev_row,
++ JDIFFROW undiff_buf, JDIMENSION width)
++ {
++ UNDIFFERENCE_1D(INITIAL_PREDICTOR2);
++ }
++
++ METHODDEF(void)
++ jpeg_undifference2(j_decompress_ptr cinfo, int comp_index,
++ JDIFFROW diff_buf, JDIFFROW prev_row,
++ JDIFFROW undiff_buf, JDIMENSION width)
++ {
++ UNDIFFERENCE_2D(PREDICTOR2);
++ }
++
++ METHODDEF(void)
++ jpeg_undifference3(j_decompress_ptr cinfo, int comp_index,
++ JDIFFROW diff_buf, JDIFFROW prev_row,
++ JDIFFROW undiff_buf, JDIMENSION width)
++ {
++ UNDIFFERENCE_2D(PREDICTOR3);
++ }
++
++ METHODDEF(void)
++ jpeg_undifference4(j_decompress_ptr cinfo, int comp_index,
++ JDIFFROW diff_buf, JDIFFROW prev_row,
++ JDIFFROW undiff_buf, JDIMENSION width)
++ {
++ UNDIFFERENCE_2D(PREDICTOR4);
++ }
++
++ METHODDEF(void)
++ jpeg_undifference5(j_decompress_ptr cinfo, int comp_index,
++ JDIFFROW diff_buf, JDIFFROW prev_row,
++ JDIFFROW undiff_buf, JDIMENSION width)
++ {
++ UNDIFFERENCE_2D(PREDICTOR5);
++ }
++
++ METHODDEF(void)
++ jpeg_undifference6(j_decompress_ptr cinfo, int comp_index,
++ JDIFFROW diff_buf, JDIFFROW prev_row,
++ JDIFFROW undiff_buf, JDIMENSION width)
++ {
++ UNDIFFERENCE_2D(PREDICTOR6);
++ }
++
++ METHODDEF(void)
++ jpeg_undifference7(j_decompress_ptr cinfo, int comp_index,
++ JDIFFROW diff_buf, JDIFFROW prev_row,
++ JDIFFROW undiff_buf, JDIMENSION width)
++ {
++ UNDIFFERENCE_2D(PREDICTOR7);
++ }
++
++
++ /*
++ * Undifferencer for the first row in a scan or restart interval. The first
++ * sample in the row is undifferenced using the special predictor constant
++ * x=2^(P-Pt-1). The rest of the samples are undifferenced using the
++ * 1-D horizontal predictor (1).
++ */
++
++ METHODDEF(void)
++ jpeg_undifference_first_row(j_decompress_ptr cinfo, int comp_index,
++ JDIFFROW diff_buf, JDIFFROW prev_row,
++ JDIFFROW undiff_buf, JDIMENSION width)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++
++ UNDIFFERENCE_1D(INITIAL_PREDICTORx);
++
++ /*
++ * Now that we have undifferenced the first row, we want to use the
++ * undifferencer which corresponds to the predictor specified in the
++ * scan header.
++ */
++ switch (cinfo->Ss) {
++ case 1:
++ losslsd->predict_undifference[comp_index] = jpeg_undifference1;
++ break;
++ case 2:
++ losslsd->predict_undifference[comp_index] = jpeg_undifference2;
++ break;
++ case 3:
++ losslsd->predict_undifference[comp_index] = jpeg_undifference3;
++ break;
++ case 4:
++ losslsd->predict_undifference[comp_index] = jpeg_undifference4;
++ break;
++ case 5:
++ losslsd->predict_undifference[comp_index] = jpeg_undifference5;
++ break;
++ case 6:
++ losslsd->predict_undifference[comp_index] = jpeg_undifference6;
++ break;
++ case 7:
++ losslsd->predict_undifference[comp_index] = jpeg_undifference7;
++ break;
++ }
++ }
++
++
++ /*
++ * Initialize for an input processing pass.
++ */
++
++ METHODDEF(void)
++ predict_start_pass (j_decompress_ptr cinfo)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ int ci;
++
++ /* Check that the scan parameters Ss, Se, Ah, Al are OK for lossless JPEG.
++ *
++ * Ss is the predictor selection value (psv). Legal values for sequential
++ * lossless JPEG are: 1 <= psv <= 7.
++ *
++ * Se and Ah are not used and should be zero.
++ *
++ * Al specifies the point transform (Pt). Legal values are: 0 <= Pt <= 15.
++ */
++ if (cinfo->Ss < 1 || cinfo->Ss > 7 ||
++ cinfo->Se != 0 || cinfo->Ah != 0 ||
++ cinfo->Al > 15) /* need not check for < 0 */
++ ERREXIT4(cinfo, JERR_BAD_LOSSLESS,
++ cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
++
++ /* Set undifference functions to first row function */
++ for (ci = 0; ci < cinfo->num_components; ci++)
++ losslsd->predict_undifference[ci] = jpeg_undifference_first_row;
++ }
++
++
++ /*
++ * Module initialization routine for the undifferencer.
++ */
++
++ GLOBAL(void)
++ jinit_undifferencer (j_decompress_ptr cinfo)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++
++ losslsd->predict_start_pass = predict_start_pass;
++ losslsd->predict_process_restart = predict_start_pass;
++ }
++
++ #endif /* D_LOSSLESS_SUPPORTED */
++
+diff -cN ../jpeg-6b/jdsample.c ./jdsample.c
+*** ../jpeg-6b/jdsample.c Sat Jan 6 18:27:47 1996
+--- ./jdsample.c Tue Apr 27 14:58:31 1999
+***************
+*** 1,7 ****
+ /*
+ * jdsample.c
+ *
+! * Copyright (C) 1991-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jdsample.c
+ *
+! * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 8,14 ****
+ * This file contains upsampling routines.
+ *
+ * Upsampling input data is counted in "row groups". A row group
+! * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
+ * sample rows of each component. Upsampling will normally produce
+ * max_v_samp_factor pixel rows from each row group (but this could vary
+ * if the upsampler is applying a scale factor of its own).
+--- 8,14 ----
+ * This file contains upsampling routines.
+ *
+ * Upsampling input data is counted in "row groups". A row group
+! * is defined to be (v_samp_factor * codec_data_unit / min_codec_data_unit)
+ * sample rows of each component. Upsampling will normally produce
+ * max_v_samp_factor pixel rows from each row group (but this could vary
+ * if the upsampler is applying a scale factor of its own).
+***************
+*** 415,424 ****
+ if (cinfo->CCIR601_sampling) /* this isn't supported */
+ ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
+
+! /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
+ * so don't ask for it.
+ */
+! do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
+
+ /* Verify we can handle the sampling factors, select per-component methods,
+ * and create storage as needed.
+--- 415,424 ----
+ if (cinfo->CCIR601_sampling) /* this isn't supported */
+ ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
+
+! /* jdmainct.c doesn't support context rows when min_codec_data_unit = 1,
+ * so don't ask for it.
+ */
+! do_fancy = cinfo->do_fancy_upsampling && cinfo->min_codec_data_unit > 1;
+
+ /* Verify we can handle the sampling factors, select per-component methods,
+ * and create storage as needed.
+***************
+*** 428,437 ****
+ /* Compute size of an "input group" after IDCT scaling. This many samples
+ * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
+ */
+! h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
+! cinfo->min_DCT_scaled_size;
+! v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
+! cinfo->min_DCT_scaled_size;
+ h_out_group = cinfo->max_h_samp_factor;
+ v_out_group = cinfo->max_v_samp_factor;
+ upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
+--- 428,437 ----
+ /* Compute size of an "input group" after IDCT scaling. This many samples
+ * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
+ */
+! h_in_group = (compptr->h_samp_factor * compptr->codec_data_unit) /
+! cinfo->min_codec_data_unit;
+! v_in_group = (compptr->v_samp_factor * compptr->codec_data_unit) /
+! cinfo->min_codec_data_unit;
+ h_out_group = cinfo->max_h_samp_factor;
+ v_out_group = cinfo->max_v_samp_factor;
+ upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
+diff -cN ../jpeg-6b/jdscale.c ./jdscale.c
+*** ../jpeg-6b/jdscale.c
+--- ./jdscale.c Tue Apr 27 14:58:31 1999
+***************
+*** 0 ****
+--- 1,118 ----
++ /*
++ * jdscale.c
++ *
++ * Copyright (C) 1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains sample scaling for lossless JPEG. This is a
++ * combination of upscaling the undifferenced sample by 2^Pt and downscaling
++ * the sample to fit into JSAMPLE.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossls.h" /* Private declarations for lossless codec */
++
++
++ #ifdef D_LOSSLESS_SUPPORTED
++
++ /*
++ * Private scaler object for lossless decoding.
++ */
++
++ typedef struct {
++ int scale_factor;
++ } scaler;
++
++ typedef scaler * scaler_ptr;
++
++
++ /*
++ * Scalers for packing sample differences into JSAMPLEs.
++ */
++
++ METHODDEF(void)
++ simple_upscale(j_decompress_ptr cinfo,
++ JDIFFROW diff_buf, JSAMPROW output_buf,
++ JDIMENSION width)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ scaler_ptr scaler = (scaler_ptr) losslsd->scaler_private;
++ int scale_factor = scaler->scale_factor;
++ int xindex;
++
++ for (xindex = 0; xindex < width; xindex++)
++ output_buf[xindex] = (JSAMPLE) (diff_buf[xindex] << scale_factor);
++ }
++
++ METHODDEF(void)
++ simple_downscale(j_decompress_ptr cinfo,
++ JDIFFROW diff_buf, JSAMPROW output_buf,
++ JDIMENSION width)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ scaler_ptr scaler = (scaler_ptr) losslsd->scaler_private;
++ int scale_factor = scaler->scale_factor;
++ int xindex;
++
++ for (xindex = 0; xindex < width; xindex++)
++ output_buf[xindex] = (JSAMPLE) RIGHT_SHIFT(diff_buf[xindex], scale_factor);
++ }
++
++ METHODDEF(void)
++ noscale(j_decompress_ptr cinfo,
++ JDIFFROW diff_buf, JSAMPROW output_buf,
++ JDIMENSION width)
++ {
++ int xindex;
++
++ for (xindex = 0; xindex < width; xindex++)
++ output_buf[xindex] = (JSAMPLE) diff_buf[xindex];
++ }
++
++
++ METHODDEF(void)
++ scaler_start_pass (j_decompress_ptr cinfo)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ scaler_ptr scaler = (scaler_ptr) losslsd->scaler_private;
++ int downscale;
++
++ /*
++ * Downscale by the difference in the input vs. output precision. If the
++ * output precision >= input precision, then do not downscale.
++ */
++ downscale = BITS_IN_JSAMPLE < cinfo->data_precision ?
++ cinfo->data_precision - BITS_IN_JSAMPLE : 0;
++
++ scaler->scale_factor = cinfo->Al - downscale;
++
++ /* Set scaler functions based on scale_factor (positive = left shift) */
++ if (scaler->scale_factor > 0)
++ losslsd->scaler_scale = simple_upscale;
++ else if (scaler->scale_factor < 0) {
++ scaler->scale_factor = -scaler->scale_factor;
++ losslsd->scaler_scale = simple_downscale;
++ }
++ else
++ losslsd->scaler_scale = noscale;
++ }
++
++
++ GLOBAL(void)
++ jinit_d_scaler (j_decompress_ptr cinfo)
++ {
++ j_lossless_d_ptr losslsd = (j_lossless_d_ptr) cinfo->codec;
++ scaler_ptr scaler;
++
++ scaler = (scaler_ptr)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ SIZEOF(scaler));
++ losslsd->scaler_private = (void *) scaler;
++ losslsd->scaler_start_pass = scaler_start_pass;
++ }
++
++ #endif /* D_LOSSLESS_SUPPORTED */
++
+diff -cN ../jpeg-6b/jdshuff.c ./jdshuff.c
+*** ../jpeg-6b/jdshuff.c
+--- ./jdshuff.c Tue Apr 27 14:58:31 1999
+***************
+*** 0 ****
+--- 1,360 ----
++ /*
++ * jdshuff.c
++ *
++ * Copyright (C) 1991-1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This file contains Huffman entropy decoding routines for sequential JPEG.
++ *
++ * Much of the complexity here has to do with supporting input suspension.
++ * If the data source module demands suspension, we want to be able to back
++ * up to the start of the current MCU. To do this, we copy state variables
++ * into local working storage, and update them back to the permanent
++ * storage only upon successful completion of an MCU.
++ */
++
++ #define JPEG_INTERNALS
++ #include "jinclude.h"
++ #include "jpeglib.h"
++ #include "jlossy.h" /* Private declarations for lossy codec */
++ #include "jdhuff.h" /* Declarations shared with jd*huff.c */
++
++
++ /*
++ * Private entropy decoder object for Huffman decoding.
++ *
++ * The savable_state subrecord contains fields that change within an MCU,
++ * but must not be updated permanently until we complete the MCU.
++ */
++
++ typedef struct {
++ int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
++ } savable_state;
++
++ /* This macro is to work around compilers with missing or broken
++ * structure assignment. You'll need to fix this code if you have
++ * such a compiler and you change MAX_COMPS_IN_SCAN.
++ */
++
++ #ifndef NO_STRUCT_ASSIGN
++ #define ASSIGN_STATE(dest,src) ((dest) = (src))
++ #else
++ #if MAX_COMPS_IN_SCAN == 4
++ #define ASSIGN_STATE(dest,src) \
++ ((dest).last_dc_val[0] = (src).last_dc_val[0], \
++ (dest).last_dc_val[1] = (src).last_dc_val[1], \
++ (dest).last_dc_val[2] = (src).last_dc_val[2], \
++ (dest).last_dc_val[3] = (src).last_dc_val[3])
++ #endif
++ #endif
++
++
++ typedef struct {
++ huffd_common_fields; /* Fields shared with other entropy decoders */
++
++ /* These fields are loaded into local variables at start of each MCU.
++ * In case of suspension, we exit WITHOUT updating them.
++ */
++ savable_state saved; /* Other state at start of MCU */
++
++ /* These fields are NOT loaded into local working state. */
++ unsigned int restarts_to_go; /* MCUs left in this restart interval */
++
++ /* Pointers to derived tables (these workspaces have image lifespan) */
++ d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
++ d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
++
++ /* Precalculated info set up by start_pass for use in decode_mcu: */
++
++ /* Pointers to derived tables to be used for each block within an MCU */
++ d_derived_tbl * dc_cur_tbls[D_MAX_DATA_UNITS_IN_MCU];
++ d_derived_tbl * ac_cur_tbls[D_MAX_DATA_UNITS_IN_MCU];
++ /* Whether we care about the DC and AC coefficient values for each block */
++ boolean dc_needed[D_MAX_DATA_UNITS_IN_MCU];
++ boolean ac_needed[D_MAX_DATA_UNITS_IN_MCU];
++ } shuff_entropy_decoder;
++
++ typedef shuff_entropy_decoder * shuff_entropy_ptr;
++
++
++ /*
++ * Initialize for a Huffman-compressed scan.
++ */
++
++ METHODDEF(void)
++ start_pass_huff_decoder (j_decompress_ptr cinfo)
++ {
++ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
++ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyd->entropy_private;
++ int ci, blkn, dctbl, actbl;
++ jpeg_component_info * compptr;
++
++ /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
++ * This ought to be an error condition, but we make it a warning because
++ * there are some baseline files out there with all zeroes in these bytes.
++ */
++ if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
++ cinfo->Ah != 0 || cinfo->Al != 0)
++ WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
++
++ for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
++ compptr = cinfo->cur_comp_info[ci];
++ dctbl = compptr->dc_tbl_no;
++ actbl = compptr->ac_tbl_no;
++ /* Compute derived values for Huffman tables */
++ /* We may do this more than once for a table, but it's not expensive */
++ jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
++ & entropy->dc_derived_tbls[dctbl]);
++ jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
++ & entropy->ac_derived_tbls[actbl]);
++ /* Initialize DC predictions to 0 */
++ entropy->saved.last_dc_val[ci] = 0;
++ }
++
++ /* Precalculate decoding info for each block in an MCU of this scan */
++ for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
++ ci = cinfo->MCU_membership[blkn];
++ compptr = cinfo->cur_comp_info[ci];
++ /* Precalculate which table to use for each block */
++ entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
++ entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
++ /* Decide whether we really care about the coefficient values */
++ if (compptr->component_needed) {
++ entropy->dc_needed[blkn] = TRUE;
++ /* we don't need the ACs if producing a 1/8th-size image */
++ entropy->ac_needed[blkn] = (compptr->codec_data_unit > 1);
++ } else {
++ entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
++ }
++ }
++
++ /* Initialize bitread state variables */
++ entropy->bitstate.bits_left = 0;
++ entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
++ entropy->insufficient_data = FALSE;
++
++ /* Initialize restart counter */
++ entropy->restarts_to_go = cinfo->restart_interval;
++ }
++
++
++ /*
++ * Figure F.12: extend sign bit.
++ * On some machines, a shift and add will be faster than a table lookup.
++ */
++
++ #ifdef AVOID_TABLES
++
++ #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
++
++ #else
++
++ #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
++
++ static const int extend_test[16] = /* entry n is 2**(n-1) */
++ { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
++ 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
++
++ static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
++ { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
++ ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
++ ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
++ ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
++
++ #endif /* AVOID_TABLES */
++
++
++ /*
++ * Check for a restart marker & resynchronize decoder.
++ * Returns FALSE if must suspend.
++ */
++
++ LOCAL(boolean)
++ process_restart (j_decompress_ptr cinfo)
++ {
++ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
++ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyd->entropy_private;
++ int ci;
++
++ /* Throw away any unused bits remaining in bit buffer; */
++ /* include any full bytes in next_marker's count of discarded bytes */
++ cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
++ entropy->bitstate.bits_left = 0;
++
++ /* Advance past the RSTn marker */
++ if (! (*cinfo->marker->read_restart_marker) (cinfo))
++ return FALSE;
++
++ /* Re-initialize DC predictions to 0 */
++ for (ci = 0; ci < cinfo->comps_in_scan; ci++)
++ entropy->saved.last_dc_val[ci] = 0;
++
++ /* Reset restart counter */
++ entropy->restarts_to_go = cinfo->restart_interval;
++
++ /* Reset out-of-data flag, unless read_restart_marker left us smack up
++ * against a marker. In that case we will end up treating the next data
++ * segment as empty, and we can avoid producing bogus output pixels by
++ * leaving the flag set.
++ */
++ if (cinfo->unread_marker == 0)
++ entropy->insufficient_data = FALSE;
++
++ return TRUE;
++ }
++
++
++ /*
++ * Decode and return one MCU's worth of Huffman-compressed coefficients.
++ * The coefficients are reordered from zigzag order into natural array order,
++ * but are not dequantized.
++ *
++ * The i'th block of the MCU is stored into the block pointed to by
++ * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
++ * (Wholesale zeroing is usually a little faster than retail...)
++ *
++ * Returns FALSE if data source requested suspension. In that case no
++ * changes have been made to permanent state. (Exception: some output
++ * coefficients may already have been assigned. This is harmless for
++ * this module, since we'll just re-assign them on the next call.)
++ */
++
++ METHODDEF(boolean)
++ decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
++ {
++ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
++ shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyd->entropy_private;
++ int blkn;
++ BITREAD_STATE_VARS;
++ savable_state state;
++
++ /* Process restart marker if needed; may have to suspend */
++ if (cinfo->restart_interval) {
++ if (entropy->restarts_to_go == 0)
++ if (! process_restart(cinfo))
++ return FALSE;
++ }
++
++ /* If we've run out of data, just leave the MCU set to zeroes.
++ * This way, we return uniform gray for the remainder of the segment.
++ */
++ if (! entropy->insufficient_data) {
++
++ /* Load up working state */
++ BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
++ ASSIGN_STATE(state, entropy->saved);
++
++ /* Outer loop handles each block in the MCU */
++
++ for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
++ JBLOCKROW block = MCU_data[blkn];
++ d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
++ d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
++ register int s, k, r;
++
++ /* Decode a single block's worth of coefficients */
++
++ /* Section F.2.2.1: decode the DC coefficient difference */
++ HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
++ if (s) {
++ CHECK_BIT_BUFFER(br_state, s, return FALSE);
++ r = GET_BITS(s);
++ s = HUFF_EXTEND(r, s);
++ }
++
++ if (entropy->dc_needed[blkn]) {
++ /* Convert DC difference to actual value, update last_dc_val */
++ int ci = cinfo->MCU_membership[blkn];
++ s += state.last_dc_val[ci];
++ state.last_dc_val[ci] = s;
++ /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
++ (*block)[0] = (JCOEF) s;
++ }
++
++ if (entropy->ac_needed[blkn]) {
++
++ /* Section F.2.2.2: decode the AC coefficients */
++ /* Since zeroes are skipped, output area must be cleared beforehand */
++ for (k = 1; k < DCTSIZE2; k++) {
++ HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
++
++ r = s >> 4;
++ s &= 15;
++
++ if (s) {
++ k += r;
++ CHECK_BIT_BUFFER(br_state, s, return FALSE);
++ r = GET_BITS(s);
++ s = HUFF_EXTEND(r, s);
++ /* Output coefficient in natural (dezigzagged) order.
++ * Note: the extra entries in jpeg_natural_order[] will save us
++ * if k >= DCTSIZE2, which could happen if the data is corrupted.
++ */
++ (*block)[jpeg_natural_order[k]] = (JCOEF) s;
++ } else {
++ if (r != 15)
++ break;
++ k += 15;
++ }
++ }
++
++ } else {
++
++ /* Section F.2.2.2: decode the AC coefficients */
++ /* In this path we just discard the values */
++ for (k = 1; k < DCTSIZE2; k++) {
++ HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
++
++ r = s >> 4;
++ s &= 15;
++
++ if (s) {
++ k += r;
++ CHECK_BIT_BUFFER(br_state, s, return FALSE);
++ DROP_BITS(s);
++ } else {
++ if (r != 15)
++ break;
++ k += 15;
++ }
++ }
++
++ }
++ }
++
++ /* Completed MCU, so update state */
++ BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
++ ASSIGN_STATE(entropy->saved, state);
++ }
++
++ /* Account for restart interval (no-op if not using restarts) */
++ entropy->restarts_to_go--;
++
++ return TRUE;
++ }
++
++
++ /*
++ * Module initialization routine for Huffman entropy decoding.
++ */
++
++ GLOBAL(void)
++ jinit_shuff_decoder (j_decompress_ptr cinfo)
++ {
++ j_lossy_d_ptr lossyd = (j_lossy_d_ptr) cinfo->codec;
++ shuff_entropy_ptr entropy;
++ int i;
++
++ entropy = (shuff_entropy_ptr)
++ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
++ SIZEOF(shuff_entropy_decoder));
++ lossyd->entropy_private = (void *) entropy;
++ lossyd->entropy_start_pass = start_pass_huff_decoder;
++ lossyd->entropy_decode_mcu = decode_mcu;
++
++ /* Mark tables unallocated */
++ for (i = 0; i < NUM_HUFF_TBLS; i++) {
++ entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
++ }
++ }
+diff -cN ../jpeg-6b/jdtrans.c ./jdtrans.c
+*** ../jpeg-6b/jdtrans.c Sun Aug 3 17:47:58 1997
+--- ./jdtrans.c Tue Apr 27 14:58:31 1999
+***************
+*** 1,7 ****
+ /*
+ * jdtrans.c
+ *
+! * Copyright (C) 1995-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jdtrans.c
+ *
+! * Copyright (C) 1995-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 13,18 ****
+--- 13,19 ----
+ #define JPEG_INTERNALS
+ #include "jinclude.h"
+ #include "jpeglib.h"
++ #include "jlossy.h"
+
+
+ /* Forward declarations */
+***************
+*** 44,49 ****
+--- 45,58 ----
+ GLOBAL(jvirt_barray_ptr *)
+ jpeg_read_coefficients (j_decompress_ptr cinfo)
+ {
++ j_lossy_d_ptr decomp;
++
++ /* Can't read coefficients from lossless streams */
++ if (cinfo->process == JPROC_LOSSLESS) {
++ ERREXIT(cinfo, JERR_CANT_TRANSCODE);
++ return NULL;
++ }
++
+ if (cinfo->global_state == DSTATE_READY) {
+ /* First call: initialize active modules */
+ transdecode_master_selection(cinfo);
+***************
+*** 80,86 ****
+ */
+ if ((cinfo->global_state == DSTATE_STOPPING ||
+ cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
+! return cinfo->coef->coef_arrays;
+ }
+ /* Oops, improper usage */
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+--- 89,95 ----
+ */
+ if ((cinfo->global_state == DSTATE_STOPPING ||
+ cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
+! return ((j_lossy_d_ptr) cinfo->codec)->coef_arrays;
+ }
+ /* Oops, improper usage */
+ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+***************
+*** 99,120 ****
+ /* This is effectively a buffered-image operation. */
+ cinfo->buffered_image = TRUE;
+
+! /* Entropy decoding: either Huffman or arithmetic coding. */
+! if (cinfo->arith_code) {
+! ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
+! } else {
+! if (cinfo->progressive_mode) {
+! #ifdef D_PROGRESSIVE_SUPPORTED
+! jinit_phuff_decoder(cinfo);
+! #else
+! ERREXIT(cinfo, JERR_NOT_COMPILED);
+! #endif
+! } else
+! jinit_huff_decoder(cinfo);
+! }
+!
+! /* Always get a full-image coefficient buffer. */
+! jinit_d_coef_controller(cinfo, TRUE);
+
+ /* We can now tell the memory manager to allocate virtual arrays. */
+ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
+--- 108,115 ----
+ /* This is effectively a buffered-image operation. */
+ cinfo->buffered_image = TRUE;
+
+! /* Initialize decompression codec */
+! jinit_d_codec(cinfo);
+
+ /* We can now tell the memory manager to allocate virtual arrays. */
+ (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
+***************
+*** 126,132 ****
+ if (cinfo->progress != NULL) {
+ int nscans;
+ /* Estimate number of scans to set pass_limit. */
+! if (cinfo->progressive_mode) {
+ /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
+ nscans = 2 + 3 * cinfo->num_components;
+ } else if (cinfo->inputctl->has_multiple_scans) {
+--- 121,127 ----
+ if (cinfo->progress != NULL) {
+ int nscans;
+ /* Estimate number of scans to set pass_limit. */
+! if (cinfo->process == JPROC_PROGRESSIVE) {
+ /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
+ nscans = 2 + 3 * cinfo->num_components;
+ } else if (cinfo->inputctl->has_multiple_scans) {
+diff -cN ../jpeg-6b/jerror.h ./jerror.h
+*** ../jpeg-6b/jerror.h Sat Oct 18 14:59:10 1997
+--- ./jerror.h Tue Apr 27 14:58:32 1999
+***************
+*** 1,7 ****
+ /*
+ * jerror.h
+ *
+! * Copyright (C) 1994-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jerror.h
+ *
+! * Copyright (C) 1994-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 47,52 ****
+--- 47,53 ----
+ JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
+ JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
+ JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
++ JMESSAGE(JERR_BAD_DIFF, "spatial difference out of range")
+ JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
+ JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
+ JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
+***************
+*** 53,58 ****
+--- 54,63 ----
+ JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
+ JMESSAGE(JERR_BAD_LIB_VERSION,
+ "Wrong JPEG library version: library is %d, caller expects %d")
++ JMESSAGE(JERR_BAD_LOSSLESS,
++ "Invalid lossless parameters Ss=%d Se=%d Ah=%d Al=%d")
++ JMESSAGE(JERR_BAD_LOSSLESS_SCRIPT,
++ "Invalid lossless parameters at scan script entry %d")
+ JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
+ JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
+ JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
+***************
+*** 60,65 ****
+--- 65,71 ----
+ "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
+ JMESSAGE(JERR_BAD_PROG_SCRIPT,
+ "Invalid progressive parameters at scan script entry %d")
++ JMESSAGE(JERR_BAD_RESTART, "Invalid restart interval: %d, must be an integer multiple of the number of MCUs in an MCU_row (%d)")
+ JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
+ JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
+ JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
+***************
+*** 68,73 ****
+--- 74,81 ----
+ JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
+ JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
+ JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
++ JMESSAGE(JERR_CANT_TRANSCODE,
++ "Cannot transcode to/from lossless JPEG datastreams")
+ JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
+ JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
+ JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
+***************
+*** 96,101 ****
+--- 104,110 ----
+ JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
+ JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
+ JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
++ JMESSAGE(JERR_NO_LOSSLESS_SCRIPT, "Lossless encoding was requested but no scan script was supplied")
+ JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
+ JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
+ JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
+***************
+*** 165,171 ****
+ "JFIF extension marker: palette thumbnail image, length %u")
+ JMESSAGE(JTRC_THUMB_RGB,
+ "JFIF extension marker: RGB thumbnail image, length %u")
+! JMESSAGE(JTRC_UNKNOWN_IDS,
+ "Unrecognized component IDs %d %d %d, assuming YCbCr")
+ JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
+ JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
+--- 174,182 ----
+ "JFIF extension marker: palette thumbnail image, length %u")
+ JMESSAGE(JTRC_THUMB_RGB,
+ "JFIF extension marker: RGB thumbnail image, length %u")
+! JMESSAGE(JTRC_UNKNOWN_LOSSLESS_IDS,
+! "Unrecognized component IDs %d %d %d, assuming RGB")
+! JMESSAGE(JTRC_UNKNOWN_LOSSY_IDS,
+ "Unrecognized component IDs %d %d %d, assuming YCbCr")
+ JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
+ JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
+***************
+*** 178,183 ****
+--- 189,196 ----
+ JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
+ JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
+ JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
++ JMESSAGE(JWRN_MUST_DOWNSCALE,
++ "Must downscale data from %d bits to %d")
+ JMESSAGE(JWRN_MUST_RESYNC,
+ "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
+ JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
+diff -cN ../jpeg-6b/jlossls.h ./jlossls.h
+*** ../jpeg-6b/jlossls.h
+--- ./jlossls.h Tue Apr 27 14:58:32 1999
+***************
+*** 0 ****
+--- 1,149 ----
++ /*
++ * jlossls.h
++ *
++ * Copyright (C) 1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This include file contains common declarations for the lossless JPEG
++ * codec modules.
++ */
++
++ #ifndef JLOSSLS_H
++ #define JLOSSLS_H
++
++
++ /*
++ * Table H.1: Predictors for lossless coding.
++ */
++
++ #define PREDICTOR1 Ra
++ #define PREDICTOR2 Rb
++ #define PREDICTOR3 Rc
++ #define PREDICTOR4 (int) ((INT32) Ra + (INT32) Rb - (INT32) Rc)
++ #define PREDICTOR5 (int) ((INT32) Ra + RIGHT_SHIFT((INT32) Rb - (INT32) Rc, 1))
++ #define PREDICTOR6 (int) ((INT32) Rb + RIGHT_SHIFT((INT32) Ra - (INT32) Rc, 1))
++ #define PREDICTOR7 (int) RIGHT_SHIFT((INT32) Ra + (INT32) Rb, 1)
++
++
++ typedef JMETHOD(void, predict_difference_method_ptr,
++ (j_compress_ptr cinfo, int ci,
++ JSAMPROW input_buf, JSAMPROW prev_row,
++ JDIFFROW diff_buf, JDIMENSION width));
++
++ typedef JMETHOD(void, scaler_method_ptr,
++ (j_compress_ptr cinfo, int ci,
++ JSAMPROW input_buf, JSAMPROW output_buf,
++ JDIMENSION width));
++
++ /* Lossless-specific compression codec (compressor proper) */
++ typedef struct {
++ struct jpeg_c_codec pub; /* public fields */
++
++
++ /* Difference buffer control */
++ JMETHOD(void, diff_start_pass, (j_compress_ptr cinfo,
++ J_BUF_MODE pass_mode));
++
++ /* Pointer to data which is private to diff controller */
++ void *diff_private;
++
++
++ /* Entropy encoding */
++ JMETHOD(JDIMENSION, entropy_encode_mcus, (j_compress_ptr cinfo,
++ JDIFFIMAGE diff_buf,
++ JDIMENSION MCU_row_num,
++ JDIMENSION MCU_col_num,
++ JDIMENSION nMCU));
++
++ /* Pointer to data which is private to entropy module */
++ void *entropy_private;
++
++
++ /* Prediction, differencing */
++ JMETHOD(void, predict_start_pass, (j_compress_ptr cinfo));
++
++ /* It is useful to allow each component to have a separate diff method. */
++ predict_difference_method_ptr predict_difference[MAX_COMPONENTS];
++
++ /* Pointer to data which is private to predictor module */
++ void *pred_private;
++
++ /* Sample scaling */
++ JMETHOD(void, scaler_start_pass, (j_compress_ptr cinfo));
++ JMETHOD(void, scaler_scale, (j_compress_ptr cinfo,
++ JSAMPROW input_buf, JSAMPROW output_buf,
++ JDIMENSION width));
++
++ /* Pointer to data which is private to scaler module */
++ void *scaler_private;
++
++ } jpeg_lossless_c_codec;
++
++ typedef jpeg_lossless_c_codec * j_lossless_c_ptr;
++
++
++ typedef JMETHOD(void, predict_undifference_method_ptr,
++ (j_decompress_ptr cinfo, int comp_index,
++ JDIFFROW diff_buf, JDIFFROW prev_row,
++ JDIFFROW undiff_buf, JDIMENSION width));
++
++ /* Lossless-specific decompression codec (decompressor proper) */
++ typedef struct {
++ struct jpeg_d_codec pub; /* public fields */
++
++
++ /* Difference buffer control */
++ JMETHOD(void, diff_start_input_pass, (j_decompress_ptr cinfo));
++
++ /* Pointer to data which is private to diff controller */
++ void *diff_private;
++
++
++ /* Entropy decoding */
++ JMETHOD(void, entropy_start_pass, (j_decompress_ptr cinfo));
++ JMETHOD(boolean, entropy_process_restart, (j_decompress_ptr cinfo));
++ JMETHOD(JDIMENSION, entropy_decode_mcus, (j_decompress_ptr cinfo,
++ JDIFFIMAGE diff_buf,
++ JDIMENSION MCU_row_num,
++ JDIMENSION MCU_col_num,
++ JDIMENSION nMCU));
++
++ /* Pointer to data which is private to entropy module */
++ void *entropy_private;
++
++
++ /* Prediction, undifferencing */
++ JMETHOD(void, predict_start_pass, (j_decompress_ptr cinfo));
++ JMETHOD(void, predict_process_restart, (j_decompress_ptr cinfo));
++
++ /* It is useful to allow each component to have a separate undiff method. */
++ predict_undifference_method_ptr predict_undifference[MAX_COMPONENTS];
++
++ /* Pointer to data which is private to predictor module */
++ void *pred_private;
++
++ /* Sample scaling */
++ JMETHOD(void, scaler_start_pass, (j_decompress_ptr cinfo));
++ JMETHOD(void, scaler_scale, (j_decompress_ptr cinfo,
++ JDIFFROW diff_buf, JSAMPROW output_buf,
++ JDIMENSION width));
++
++ /* Pointer to data which is private to scaler module */
++ void *scaler_private;
++
++ } jpeg_lossless_d_codec;
++
++ typedef jpeg_lossless_d_codec * j_lossless_d_ptr;
++
++
++ /* Compression module initialization routines */
++ EXTERN(void) jinit_lhuff_encoder JPP((j_compress_ptr cinfo));
++ EXTERN(void) jinit_differencer JPP((j_compress_ptr cinfo));
++ EXTERN(void) jinit_c_scaler JPP((j_compress_ptr cinfo));
++ /* Decompression module initialization routines */
++ EXTERN(void) jinit_lhuff_decoder JPP((j_decompress_ptr cinfo));
++ EXTERN(void) jinit_undifferencer JPP((j_decompress_ptr cinfo));
++ EXTERN(void) jinit_d_scaler JPP((j_decompress_ptr cinfo));
++
++ #endif /* JLOSSLS_H */
+diff -cN ../jpeg-6b/jlossy.h ./jlossy.h
+*** ../jpeg-6b/jlossy.h
+--- ./jlossy.h Tue Apr 27 14:58:32 1999
+***************
+*** 0 ****
+--- 1,120 ----
++ /*
++ * jlossy.h
++ *
++ * Copyright (C) 1998, Thomas G. Lane.
++ * This file is part of the Independent JPEG Group's software.
++ * For conditions of distribution and use, see the accompanying README file.
++ *
++ * This include file contains common declarations for the lossy (DCT-based)
++ * JPEG codec modules.
++ */
++
++ #ifndef JLOSSY_H
++ #define JLOSSY_H
++
++
++ /* Lossy-specific compression codec (compressor proper) */
++ typedef struct {
++ struct jpeg_c_codec pub; /* public fields */
++
++
++ /* Coefficient buffer control */
++ JMETHOD(void, coef_start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
++ /* JMETHOD(boolean, coef_compress_data, (j_compress_ptr cinfo,
++ JSAMPIMAGE input_buf));*/
++
++ /* Pointer to data which is private to coef module */
++ void *coef_private;
++
++
++ /* Forward DCT (also controls coefficient quantization) */
++ JMETHOD(void, fdct_start_pass, (j_compress_ptr cinfo));
++ /* perhaps this should be an array??? */
++ JMETHOD(void, fdct_forward_DCT, (j_compress_ptr cinfo,
++ jpeg_component_info * compptr,
++ JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
++ JDIMENSION start_row, JDIMENSION start_col,
++ JDIMENSION num_blocks));
++
++ /* Pointer to data which is private to fdct module */
++ void *fdct_private;
++
++
++ /* Entropy encoding */
++ JMETHOD(boolean, entropy_encode_mcu, (j_compress_ptr cinfo,
++ JBLOCKROW *MCU_data));
++
++ /* Pointer to data which is private to entropy module */
++ void *entropy_private;
++
++ } jpeg_lossy_c_codec;
++
++ typedef jpeg_lossy_c_codec * j_lossy_c_ptr;
++
++
++
++ typedef JMETHOD(void, inverse_DCT_method_ptr,
++ (j_decompress_ptr cinfo, jpeg_component_info * compptr,
++ JCOEFPTR coef_block,
++ JSAMPARRAY output_buf, JDIMENSION output_col));
++
++ /* Lossy-specific decompression codec (decompressor proper) */
++ typedef struct {
++ struct jpeg_d_codec pub; /* public fields */
++
++
++ /* Coefficient buffer control */
++ JMETHOD(void, coef_start_input_pass, (j_decompress_ptr cinfo));
++ JMETHOD(void, coef_start_output_pass, (j_decompress_ptr cinfo));
++
++ /* Pointer to array of coefficient virtual arrays, or NULL if none */
++ jvirt_barray_ptr *coef_arrays;
++
++ /* Pointer to data which is private to coef module */
++ void *coef_private;
++
++
++ /* Entropy decoding */
++ JMETHOD(void, entropy_start_pass, (j_decompress_ptr cinfo));
++ JMETHOD(boolean, entropy_decode_mcu, (j_decompress_ptr cinfo,
++ JBLOCKROW *MCU_data));
++
++ /* This is here to share code between baseline and progressive decoders; */
++ /* other modules probably should not use it */
++ boolean entropy_insufficient_data; /* set TRUE after emitting warning */
++
++ /* Pointer to data which is private to entropy module */
++ void *entropy_private;
++
++
++ /* Inverse DCT (also performs dequantization) */
++ JMETHOD(void, idct_start_pass, (j_decompress_ptr cinfo));
++
++ /* It is useful to allow each component to have a separate IDCT method. */
++ inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
++
++ /* Pointer to data which is private to idct module */
++ void *idct_private;
++
++ } jpeg_lossy_d_codec;
++
++ typedef jpeg_lossy_d_codec * j_lossy_d_ptr;
++
++
++ /* Compression module initialization routines */
++ EXTERN(void) jinit_lossy_c_codec JPP((j_compress_ptr cinfo));
++ EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
++ boolean need_full_buffer));
++ EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
++ EXTERN(void) jinit_shuff_encoder JPP((j_compress_ptr cinfo));
++ EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
++
++ /* Decompression module initialization routines */
++ EXTERN(void) jinit_lossy_d_codec JPP((j_decompress_ptr cinfo));
++ EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
++ boolean need_full_buffer));
++ EXTERN(void) jinit_shuff_decoder JPP((j_decompress_ptr cinfo));
++ EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
++ EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
++
++ #endif /* JLOSSY_H */
+diff -cN ../jpeg-6b/jmemmgr.c ./jmemmgr.c
+*** ../jpeg-6b/jmemmgr.c Mon Apr 14 20:56:37 1997
+--- ./jmemmgr.c Tue Apr 27 14:58:33 1999
+***************
+*** 1,7 ****
+ /*
+ * jmemmgr.c
+ *
+! * Copyright (C) 1991-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jmemmgr.c
+ *
+! * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 42,52 ****
+ * The allocation routines provided here must never return NULL.
+ * They should exit to error_exit if unsuccessful.
+ *
+! * It's not a good idea to try to merge the sarray and barray routines,
+! * even though they are textually almost the same, because samples are
+! * usually stored as bytes while coefficients are shorts or ints. Thus,
+! * in machines where byte pointers have a different representation from
+! * word pointers, the resulting machine code could not be the same.
+ */
+
+
+--- 42,53 ----
+ * The allocation routines provided here must never return NULL.
+ * They should exit to error_exit if unsuccessful.
+ *
+! * It's not a good idea to try to merge the sarray, barray and darray
+! * routines, even though they are textually almost the same, because
+! * samples are usually stored as bytes while coefficients and differenced
+! * are shorts or ints. Thus, in machines where byte pointers have a
+! * different representation from word pointers, the resulting machine
+! * code could not be the same.
+ */
+
+
+***************
+*** 482,487 ****
+--- 483,540 ----
+ }
+
+
++ #ifdef NEED_DARRAY
++
++ /*
++ * Creation of 2-D difference arrays.
++ * This is essentially the same as the code for sample arrays, above.
++ */
++
++ METHODDEF(JDIFFARRAY)
++ alloc_darray (j_common_ptr cinfo, int pool_id,
++ JDIMENSION diffsperrow, JDIMENSION numrows)
++ /* Allocate a 2-D difference array */
++ {
++ my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
++ JDIFFARRAY result;
++ JDIFFROW workspace;
++ JDIMENSION rowsperchunk, currow, i;
++ long ltemp;
++
++ /* Calculate max # of rows allowed in one allocation chunk */
++ ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
++ ((long) diffsperrow * SIZEOF(JDIFF));
++ if (ltemp <= 0)
++ ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
++ if (ltemp < (long) numrows)
++ rowsperchunk = (JDIMENSION) ltemp;
++ else
++ rowsperchunk = numrows;
++ mem->last_rowsperchunk = rowsperchunk;
++
++ /* Get space for row pointers (small object) */
++ result = (JDIFFARRAY) alloc_small(cinfo, pool_id,
++ (size_t) (numrows * SIZEOF(JDIFFROW)));
++
++ /* Get the rows themselves (large objects) */
++ currow = 0;
++ while (currow < numrows) {
++ rowsperchunk = MIN(rowsperchunk, numrows - currow);
++ workspace = (JDIFFROW) alloc_large(cinfo, pool_id,
++ (size_t) ((size_t) rowsperchunk * (size_t) diffsperrow
++ * SIZEOF(JDIFF)));
++ for (i = rowsperchunk; i > 0; i--) {
++ result[currow++] = workspace;
++ workspace += diffsperrow;
++ }
++ }
++
++ return result;
++ }
++
++ #endif
++
++
+ /*
+ * About virtual array management:
+ *
+***************
+*** 1068,1073 ****
+--- 1121,1129 ----
+ mem->pub.alloc_large = alloc_large;
+ mem->pub.alloc_sarray = alloc_sarray;
+ mem->pub.alloc_barray = alloc_barray;
++ #ifdef NEED_DARRAY
++ mem->pub.alloc_darray = alloc_darray;
++ #endif
+ mem->pub.request_virt_sarray = request_virt_sarray;
+ mem->pub.request_virt_barray = request_virt_barray;
+ mem->pub.realize_virt_arrays = realize_virt_arrays;
+diff -cN ../jpeg-6b/jmorecfg.h ./jmorecfg.h
+*** ../jpeg-6b/jmorecfg.h Sat Aug 9 19:58:56 1997
+--- ./jmorecfg.h Tue Apr 27 14:58:33 1999
+***************
+*** 1,7 ****
+ /*
+ * jmorecfg.h
+ *
+! * Copyright (C) 1991-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jmorecfg.h
+ *
+! * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 90,95 ****
+--- 90,122 ----
+ #endif /* BITS_IN_JSAMPLE == 12 */
+
+
++ #if BITS_IN_JSAMPLE == 16
++ /* JSAMPLE should be the smallest type that will hold the values 0..65535.
++ * You can use a signed short by having GETJSAMPLE mask it with 0xFFFF.
++ */
++
++ #ifdef HAVE_UNSIGNED_SHORT
++
++ typedef unsigned short JSAMPLE;
++ #define GETJSAMPLE(value) ((int) (value))
++
++ #else /* not HAVE_UNSIGNED_SHORT */
++
++ typedef short JSAMPLE;
++ #ifdef SHORT_IS_UNSIGNED
++ #define GETJSAMPLE(value) ((int) (value))
++ #else
++ #define GETJSAMPLE(value) ((int) (value) & 0xFFFF)
++ #endif /* SHORT_IS_UNSIGNED */
++
++ #endif /* HAVE_UNSIGNED_SHORT */
++
++ #define MAXJSAMPLE 65535
++ #define CENTERJSAMPLE 32768
++
++ #endif /* BITS_IN_JSAMPLE == 16 */
++
++
+ /* Representation of a DCT frequency coefficient.
+ * This should be a signed value of at least 16 bits; "short" is usually OK.
+ * Again, we allocate large arrays of these, but you can change to int
+***************
+*** 99,104 ****
+--- 126,138 ----
+ typedef short JCOEF;
+
+
++ /* Representation of a spatial difference value.
++ * This should be a signed value of at least 16 bits; int is usually OK.
++ */
++
++ typedef int JDIFF;
++
++
+ /* Compressed datastreams are represented as arrays of JOCTET.
+ * These must be EXACTLY 8 bits wide, at least once they are written to
+ * external storage. Note that when using the stdio data source/destination
+***************
+*** 269,282 ****
+ #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
+ #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
+ #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
+ #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
+ /* Note: if you selected 12-bit data precision, it is dangerous to turn off
+ * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
+! * precision, so jchuff.c normally uses entropy optimization to compute
+ * usable tables for higher precision. If you don't want to do optimization,
+ * you'll have to supply different default Huffman tables.
+! * The exact same statements apply for progressive JPEG: the default tables
+! * don't work for progressive mode. (This may get fixed, however.)
+ */
+ #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
+
+--- 303,318 ----
+ #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
+ #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
+ #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
++ #define C_LOSSLESS_SUPPORTED /* Lossless JPEG? */
+ #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
+ /* Note: if you selected 12-bit data precision, it is dangerous to turn off
+ * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
+! * precision, so jcshuff.c normally uses entropy optimization to compute
+ * usable tables for higher precision. If you don't want to do optimization,
+ * you'll have to supply different default Huffman tables.
+! * The exact same statements apply for progressive and lossless JPEG:
+! * the default tables don't work for progressive mode or lossless mode.
+! * (This may get fixed, however.)
+ */
+ #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
+
+***************
+*** 285,290 ****
+--- 321,327 ----
+ #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
+ #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
+ #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
++ #define D_LOSSLESS_SUPPORTED /* Lossless JPEG? */
+ #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
+ #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
+ #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
+diff -cN ../jpeg-6b/jpegint.h ./jpegint.h
+*** ../jpeg-6b/jpegint.h Sat Apr 19 19:44:35 1997
+--- ./jpegint.h Tue Apr 27 14:58:33 1999
+***************
+*** 1,7 ****
+ /*
+ * jpegint.h
+ *
+! * Copyright (C) 1991-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * jpegint.h
+ *
+! * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 72,79 ****
+ JDIMENSION out_row_groups_avail));
+ };
+
+! /* Coefficient buffer control */
+! struct jpeg_c_coef_controller {
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
+ JSAMPIMAGE input_buf));
+--- 72,83 ----
+ JDIMENSION out_row_groups_avail));
+ };
+
+! /* Compression codec (compressor proper) */
+! struct jpeg_c_codec {
+! JMETHOD(void, entropy_start_pass, (j_compress_ptr cinfo,
+! boolean gather_statistics));
+! JMETHOD(void, entropy_finish_pass, (j_compress_ptr cinfo));
+! JMETHOD(boolean, need_optimization_pass, (j_compress_ptr cinfo));
+ JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
+ JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
+ JSAMPIMAGE input_buf));
+***************
+*** 98,121 ****
+ boolean need_context_rows; /* TRUE if need rows above & below */
+ };
+
+- /* Forward DCT (also controls coefficient quantization) */
+- struct jpeg_forward_dct {
+- JMETHOD(void, start_pass, (j_compress_ptr cinfo));
+- /* perhaps this should be an array??? */
+- JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
+- jpeg_component_info * compptr,
+- JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
+- JDIMENSION start_row, JDIMENSION start_col,
+- JDIMENSION num_blocks));
+- };
+-
+- /* Entropy encoding */
+- struct jpeg_entropy_encoder {
+- JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
+- JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
+- JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
+- };
+-
+ /* Marker writing */
+ struct jpeg_marker_writer {
+ JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
+--- 102,107 ----
+***************
+*** 162,176 ****
+ JDIMENSION out_rows_avail));
+ };
+
+! /* Coefficient buffer control */
+! struct jpeg_d_coef_controller {
+ JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
+ JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
+ JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
+ JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
+ JSAMPIMAGE output_buf));
+- /* Pointer to array of coefficient virtual arrays, or NULL if none */
+- jvirt_barray_ptr *coef_arrays;
+ };
+
+ /* Decompression postprocessing (color quantization buffer control) */
+--- 148,161 ----
+ JDIMENSION out_rows_avail));
+ };
+
+! /* Decompression codec (decompressor proper) */
+! struct jpeg_d_codec {
+! JMETHOD(void, calc_output_dimensions, (j_decompress_ptr cinfo));
+ JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
+ JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
+ JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
+ JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
+ JSAMPIMAGE output_buf));
+ };
+
+ /* Decompression postprocessing (color quantization buffer control) */
+***************
+*** 205,233 ****
+ unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
+ };
+
+- /* Entropy decoding */
+- struct jpeg_entropy_decoder {
+- JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+- JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
+- JBLOCKROW *MCU_data));
+-
+- /* This is here to share code between baseline and progressive decoders; */
+- /* other modules probably should not use it */
+- boolean insufficient_data; /* set TRUE after emitting warning */
+- };
+-
+- /* Inverse DCT (also performs dequantization) */
+- typedef JMETHOD(void, inverse_DCT_method_ptr,
+- (j_decompress_ptr cinfo, jpeg_component_info * compptr,
+- JCOEFPTR coef_block,
+- JSAMPARRAY output_buf, JDIMENSION output_col));
+-
+- struct jpeg_inverse_dct {
+- JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+- /* It is useful to allow each component to have a separate IDCT method. */
+- inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
+- };
+-
+ /* Upsampling (note that upsampler must also call color converter) */
+ struct jpeg_upsampler {
+ JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
+--- 190,195 ----
+***************
+*** 294,299 ****
+--- 256,263 ----
+ /* Short forms of external names for systems with brain-damaged linkers. */
+
+ #ifdef NEED_SHORT_EXTERNAL_NAMES
++ #define jinit_c_codec jICCodec
++ #define jinit_lossy_c_codec jILossyC
+ #define jinit_compress_master jICompress
+ #define jinit_c_master_control jICMaster
+ #define jinit_c_main_controller jICMainC
+***************
+*** 302,318 ****
+ #define jinit_color_converter jICColor
+ #define jinit_downsampler jIDownsampler
+ #define jinit_forward_dct jIFDCT
+! #define jinit_huff_encoder jIHEncoder
+ #define jinit_phuff_encoder jIPHEncoder
+ #define jinit_marker_writer jIMWriter
+ #define jinit_master_decompress jIDMaster
+ #define jinit_d_main_controller jIDMainC
+ #define jinit_d_coef_controller jIDCoefC
+ #define jinit_d_post_controller jIDPostC
+ #define jinit_input_controller jIInCtlr
+ #define jinit_marker_reader jIMReader
+! #define jinit_huff_decoder jIHDecoder
+ #define jinit_phuff_decoder jIPHDecoder
+ #define jinit_inverse_dct jIIDCT
+ #define jinit_upsampler jIUpsampler
+ #define jinit_color_deconverter jIDColor
+--- 266,289 ----
+ #define jinit_color_converter jICColor
+ #define jinit_downsampler jIDownsampler
+ #define jinit_forward_dct jIFDCT
+! #define jinit_shuff_encoder jISHEncoder
+ #define jinit_phuff_encoder jIPHEncoder
+ #define jinit_marker_writer jIMWriter
++ #define jinit_d_codec jIDCodec
++ #define jinit_lossy_d_codec jILossyD
++ #define jinit_lossless_d_codec jILosslsD
+ #define jinit_master_decompress jIDMaster
+ #define jinit_d_main_controller jIDMainC
+ #define jinit_d_coef_controller jIDCoefC
++ #define jinit_d_diff_controller jIDDiffC
+ #define jinit_d_post_controller jIDPostC
+ #define jinit_input_controller jIInCtlr
+ #define jinit_marker_reader jIMReader
+! #define jinit_shuff_decoder jISHDecoder
+ #define jinit_phuff_decoder jIPHDecoder
++ #define jinit_lhuff_decoder jILHDecoder
++ #define jinit_undifferencer jIUndiff
++ #define jinit_d_scaler jIDScaler
+ #define jinit_inverse_dct jIIDCT
+ #define jinit_upsampler jIUpsampler
+ #define jinit_color_deconverter jIDColor
+***************
+*** 338,364 ****
+ boolean need_full_buffer));
+ EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
+ boolean need_full_buffer));
+! EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
+! boolean need_full_buffer));
+ EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
+ EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
+- EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
+- EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
+- EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
+ EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
+ /* Decompression module initialization routines */
+ EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
+ EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
+ boolean need_full_buffer));
+! EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
+! boolean need_full_buffer));
+ EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
+ boolean need_full_buffer));
+ EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
+ EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
+- EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
+- EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
+- EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
+ EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
+ EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
+ EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
+--- 309,327 ----
+ boolean need_full_buffer));
+ EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
+ boolean need_full_buffer));
+! EXTERN(void) jinit_compressor JPP((j_compress_ptr cinfo));
+ EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
+ EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
+ EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
+ /* Decompression module initialization routines */
+ EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
+ EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
+ boolean need_full_buffer));
+! EXTERN(void) jinit_decompressor JPP((j_decompress_ptr cinfo));
+ EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
+ boolean need_full_buffer));
+ EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
+ EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
+ EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
+ EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
+ EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
+diff -cN ../jpeg-6b/jpeglib.h ./jpeglib.h
+*** ../jpeg-6b/jpeglib.h Sat Feb 21 14:48:14 1998
+--- ./jpeglib.h Tue Apr 27 14:58:34 1999
+***************
+*** 46,60 ****
+ #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
+ #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
+ /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
+! * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
+! * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
+ * to handle it. We even let you do this from the jconfig.h file. However,
+! * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
+ * sometimes emits noncompliant files doesn't mean you should too.
+ */
+! #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
+! #ifndef D_MAX_BLOCKS_IN_MCU
+! #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
+ #endif
+
+
+--- 46,61 ----
+ #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
+ #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
+ /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
+! * the PostScript DCT filter can emit files with many more than 10 data units
+! * per MCU.
+! * If you happen to run across such a file, you can up D_MAX_DATA_UNITS_IN_MCU
+ * to handle it. We even let you do this from the jconfig.h file. However,
+! * we strongly discourage changing C_MAX_DATA_UNITS_IN_MCU; just because Adobe
+ * sometimes emits noncompliant files doesn't mean you should too.
+ */
+! #define C_MAX_DATA_UNITS_IN_MCU 10 /* compressor's limit on data units/MCU */
+! #ifndef D_MAX_DATA_UNITS_IN_MCU
+! #define D_MAX_DATA_UNITS_IN_MCU 10 /* decompressor's limit on data units/MCU */
+ #endif
+
+
+***************
+*** 74,80 ****
+--- 75,85 ----
+
+ typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
+
++ typedef JDIFF FAR *JDIFFROW; /* pointer to one row of difference values */
++ typedef JDIFFROW *JDIFFARRAY; /* ptr to some rows (a 2-D diff array) */
++ typedef JDIFFARRAY *JDIFFIMAGE; /* a 3-D diff array: top index is color */
+
++
+ /* Types for JPEG compression parameters and working tables. */
+
+
+***************
+*** 132,155 ****
+ /* Remaining fields should be treated as private by applications. */
+
+ /* These values are computed during compression or decompression startup: */
+! /* Component's size in DCT blocks.
+! * Any dummy blocks added to complete an MCU are not counted; therefore
+ * these values do not depend on whether a scan is interleaved or not.
+ */
+! JDIMENSION width_in_blocks;
+! JDIMENSION height_in_blocks;
+! /* Size of a DCT block in samples. Always DCTSIZE for compression.
+! * For decompression this is the size of the output from one DCT block,
+! * reflecting any scaling we choose to apply during the IDCT step.
+! * Values of 1,2,4,8 are likely to be supported. Note that different
+! * components may receive different IDCT scalings.
+ */
+! int DCT_scaled_size;
+ /* The downsampled dimensions are the component's actual, unpadded number
+ * of samples at the main buffer (preprocessing/compression interface), thus
+ * downsampled_width = ceil(image_width * Hi/Hmax)
+! * and similarly for height. For decompression, IDCT scaling is included, so
+! * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
+ */
+ JDIMENSION downsampled_width; /* actual width in samples */
+ JDIMENSION downsampled_height; /* actual height in samples */
+--- 137,162 ----
+ /* Remaining fields should be treated as private by applications. */
+
+ /* These values are computed during compression or decompression startup: */
+! /* Component's size in data units.
+! * Any dummy data units added to complete an MCU are not counted; therefore
+ * these values do not depend on whether a scan is interleaved or not.
+ */
+! JDIMENSION width_in_data_units;
+! JDIMENSION height_in_data_units;
+! /* Size of a data unit in/output by the codec (in samples). Always
+! * data_unit for compression. For decompression this is the size of the
+! * output from one data_unit, reflecting any processing performed by the
+! * codec. For example, in the DCT-based codec, scaling may be applied
+! * during the IDCT step. Values of 1,2,4,8 are likely to be supported.
+! * Note that different components may have different codec_data_unit sizes.
+ */
+! int codec_data_unit;
+ /* The downsampled dimensions are the component's actual, unpadded number
+ * of samples at the main buffer (preprocessing/compression interface), thus
+ * downsampled_width = ceil(image_width * Hi/Hmax)
+! * and similarly for height. For decompression, codec-based processing is
+! * included (ie, IDCT scaling), so
+! * downsampled_width = ceil(image_width * Hi/Hmax * codec_data_unit/data_unit)
+ */
+ JDIMENSION downsampled_width; /* actual width in samples */
+ JDIMENSION downsampled_height; /* actual height in samples */
+***************
+*** 161,172 ****
+
+ /* These values are computed before starting a scan of the component. */
+ /* The decompressor output side may not use these variables. */
+! int MCU_width; /* number of blocks per MCU, horizontally */
+! int MCU_height; /* number of blocks per MCU, vertically */
+! int MCU_blocks; /* MCU_width * MCU_height */
+! int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
+! int last_col_width; /* # of non-dummy blocks across in last MCU */
+! int last_row_height; /* # of non-dummy blocks down in last MCU */
+
+ /* Saved quantization table for component; NULL if none yet saved.
+ * See jdinput.c comments about the need for this information.
+--- 168,179 ----
+
+ /* These values are computed before starting a scan of the component. */
+ /* The decompressor output side may not use these variables. */
+! int MCU_width; /* number of data units per MCU, horizontally */
+! int MCU_height; /* number of data units per MCU, vertically */
+! int MCU_data_units; /* MCU_width * MCU_height */
+! int MCU_sample_width; /* MCU width in samples, MCU_width*codec_data_unit */
+! int last_col_width; /* # of non-dummy data_units across in last MCU */
+! int last_row_height; /* # of non-dummy data_units down in last MCU */
+
+ /* Saved quantization table for component; NULL if none yet saved.
+ * See jdinput.c comments about the need for this information.
+***************
+*** 184,191 ****
+ typedef struct {
+ int comps_in_scan; /* number of components encoded in this scan */
+ int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
+! int Ss, Se; /* progressive JPEG spectral selection parms */
+! int Ah, Al; /* progressive JPEG successive approx. parms */
+ } jpeg_scan_info;
+
+ /* The decompressor can save APPn and COM markers in a list of these: */
+--- 191,200 ----
+ typedef struct {
+ int comps_in_scan; /* number of components encoded in this scan */
+ int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
+! int Ss, Se; /* progressive JPEG spectral selection parms
+! lossless JPEG predictor select parm (Ss) */
+! int Ah, Al; /* progressive JPEG successive approx. parms
+! lossless JPEG point transform parm (Al) */
+ } jpeg_scan_info;
+
+ /* The decompressor can save APPn and COM markers in a list of these: */
+***************
+*** 201,206 ****
+--- 210,223 ----
+ /* the marker length word is not counted in data_length or original_length */
+ };
+
++ /* Known codec processes. */
++
++ typedef enum {
++ JPROC_SEQUENTIAL, /* baseline/extended sequential DCT */
++ JPROC_PROGRESSIVE, /* progressive DCT */
++ JPROC_LOSSLESS /* lossless (sequential) */
++ } J_CODEC_PROCESS;
++
+ /* Known color spaces. */
+
+ typedef enum {
+***************
+*** 291,296 ****
+--- 308,315 ----
+ * helper routines to simplify changing parameters.
+ */
+
++ boolean lossless; /* TRUE=lossless encoding, FALSE=lossy */
++
+ int data_precision; /* bits of precision in image data */
+
+ int num_components; /* # of color components in JPEG image */
+***************
+*** 360,373 ****
+ /*
+ * These fields are computed during compression startup
+ */
+! boolean progressive_mode; /* TRUE if scan script uses progressive mode */
+ int max_h_samp_factor; /* largest h_samp_factor */
+ int max_v_samp_factor; /* largest v_samp_factor */
+
+! JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
+! /* The coefficient controller receives data in units of MCU rows as defined
+! * for fully interleaved scans (whether the JPEG file is interleaved or not).
+! * There are v_samp_factor * DCTSIZE sample rows of each component in an
+ * "iMCU" (interleaved MCU) row.
+ */
+
+--- 379,394 ----
+ /*
+ * These fields are computed during compression startup
+ */
+! int data_unit; /* size of data unit in samples */
+! J_CODEC_PROCESS process; /* encoding process of JPEG image */
+!
+ int max_h_samp_factor; /* largest h_samp_factor */
+ int max_v_samp_factor; /* largest v_samp_factor */
+
+! JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to codec */
+! /* The codec receives data in units of MCU rows as defined for fully
+! * interleaved scans (whether the JPEG file is interleaved or not).
+! * There are v_samp_factor * data_unit sample rows of each component in an
+ * "iMCU" (interleaved MCU) row.
+ */
+
+***************
+*** 382,393 ****
+ JDIMENSION MCUs_per_row; /* # of MCUs across the image */
+ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
+
+! int blocks_in_MCU; /* # of DCT blocks per MCU */
+! int MCU_membership[C_MAX_BLOCKS_IN_MCU];
+ /* MCU_membership[i] is index in cur_comp_info of component owning */
+ /* i'th block in an MCU */
+
+! int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
+
+ /*
+ * Links to compression subobjects (methods and private variables of modules)
+--- 403,414 ----
+ JDIMENSION MCUs_per_row; /* # of MCUs across the image */
+ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
+
+! int data_units_in_MCU; /* # of data units per MCU */
+! int MCU_membership[C_MAX_DATA_UNITS_IN_MCU];
+ /* MCU_membership[i] is index in cur_comp_info of component owning */
+ /* i'th block in an MCU */
+
+! int Ss, Se, Ah, Al; /* progressive/lossless JPEG parameters for scan */
+
+ /*
+ * Links to compression subobjects (methods and private variables of modules)
+***************
+*** 395,406 ****
+ struct jpeg_comp_master * master;
+ struct jpeg_c_main_controller * main;
+ struct jpeg_c_prep_controller * prep;
+! struct jpeg_c_coef_controller * coef;
+ struct jpeg_marker_writer * marker;
+ struct jpeg_color_converter * cconvert;
+ struct jpeg_downsampler * downsample;
+- struct jpeg_forward_dct * fdct;
+- struct jpeg_entropy_encoder * entropy;
+ jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
+ int script_space_size;
+ };
+--- 416,425 ----
+ struct jpeg_comp_master * master;
+ struct jpeg_c_main_controller * main;
+ struct jpeg_c_prep_controller * prep;
+! struct jpeg_c_codec * codec;
+ struct jpeg_marker_writer * marker;
+ struct jpeg_color_converter * cconvert;
+ struct jpeg_downsampler * downsample;
+ jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
+ int script_space_size;
+ };
+***************
+*** 535,541 ****
+ jpeg_component_info * comp_info;
+ /* comp_info[i] describes component that appears i'th in SOF */
+
+- boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
+ boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
+
+ UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
+--- 554,559 ----
+***************
+*** 572,589 ****
+ /*
+ * These fields are computed during decompression startup
+ */
+ int max_h_samp_factor; /* largest h_samp_factor */
+ int max_v_samp_factor; /* largest v_samp_factor */
+
+! int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
+
+ JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
+! /* The coefficient controller's input and output progress is measured in
+! * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
+! * in fully interleaved JPEG scans, but are used whether the scan is
+! * interleaved or not. We define an iMCU row as v_samp_factor DCT block
+! * rows of each component. Therefore, the IDCT output contains
+! * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
+ */
+
+ JSAMPLE * sample_range_limit; /* table for fast range-limiting */
+--- 590,610 ----
+ /*
+ * These fields are computed during decompression startup
+ */
++ int data_unit; /* size of data unit in samples */
++ J_CODEC_PROCESS process; /* decoding process of JPEG image */
++
+ int max_h_samp_factor; /* largest h_samp_factor */
+ int max_v_samp_factor; /* largest v_samp_factor */
+
+! int min_codec_data_unit; /* smallest codec_data_unit of any component */
+
+ JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
+! /* The codec's input and output progress is measured in units of "iMCU"
+! * (interleaved MCU) rows. These are the same as MCU rows in fully
+! * interleaved JPEG scans, but are used whether the scan is interleaved
+! * or not. We define an iMCU row as v_samp_factor data_unit rows of each
+! * component. Therefore, the codec output contains
+! * v_samp_factor*codec_data_unit sample rows of a component per iMCU row.
+ */
+
+ JSAMPLE * sample_range_limit; /* table for fast range-limiting */
+***************
+*** 600,611 ****
+ JDIMENSION MCUs_per_row; /* # of MCUs across the image */
+ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
+
+! int blocks_in_MCU; /* # of DCT blocks per MCU */
+! int MCU_membership[D_MAX_BLOCKS_IN_MCU];
+ /* MCU_membership[i] is index in cur_comp_info of component owning */
+! /* i'th block in an MCU */
+
+! int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
+
+ /* This field is shared between entropy decoder and marker parser.
+ * It is either zero or the code of a JPEG marker that has been
+--- 621,632 ----
+ JDIMENSION MCUs_per_row; /* # of MCUs across the image */
+ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
+
+! int data_units_in_MCU; /* # of data _units per MCU */
+! int MCU_membership[D_MAX_DATA_UNITS_IN_MCU];
+ /* MCU_membership[i] is index in cur_comp_info of component owning */
+! /* i'th data unit in an MCU */
+
+! int Ss, Se, Ah, Al; /* progressive/lossless JPEG parms for scan */
+
+ /* This field is shared between entropy decoder and marker parser.
+ * It is either zero or the code of a JPEG marker that has been
+***************
+*** 618,629 ****
+ */
+ struct jpeg_decomp_master * master;
+ struct jpeg_d_main_controller * main;
+! struct jpeg_d_coef_controller * coef;
+ struct jpeg_d_post_controller * post;
+ struct jpeg_input_controller * inputctl;
+ struct jpeg_marker_reader * marker;
+- struct jpeg_entropy_decoder * entropy;
+- struct jpeg_inverse_dct * idct;
+ struct jpeg_upsampler * upsample;
+ struct jpeg_color_deconverter * cconvert;
+ struct jpeg_color_quantizer * cquantize;
+--- 639,648 ----
+ */
+ struct jpeg_decomp_master * master;
+ struct jpeg_d_main_controller * main;
+! struct jpeg_d_codec * codec;
+ struct jpeg_d_post_controller * post;
+ struct jpeg_input_controller * inputctl;
+ struct jpeg_marker_reader * marker;
+ struct jpeg_upsampler * upsample;
+ struct jpeg_color_deconverter * cconvert;
+ struct jpeg_color_quantizer * cquantize;
+***************
+*** 753,758 ****
+--- 772,785 ----
+ typedef struct jvirt_barray_control * jvirt_barray_ptr;
+
+
++ #ifdef C_LOSSLESS_SUPPORTED
++ #define NEED_DARRAY
++ #else
++ #ifdef D_LOSSLESS_SUPPORTED
++ #define NEED_DARRAY
++ #endif
++ #endif
++
+ struct jpeg_memory_mgr {
+ /* Method pointers */
+ JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
+***************
+*** 765,770 ****
+--- 792,802 ----
+ JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
+ JDIMENSION blocksperrow,
+ JDIMENSION numrows));
++ #ifdef NEED_DARRAY
++ JMETHOD(JDIFFARRAY, alloc_darray, (j_common_ptr cinfo, int pool_id,
++ JDIMENSION diffsperrow,
++ JDIMENSION numrows));
++ #endif
+ JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
+ int pool_id,
+ boolean pre_zero,
+***************
+*** 843,848 ****
+--- 875,881 ----
+ #define jpeg_set_linear_quality jSetLQuality
+ #define jpeg_add_quant_table jAddQuantTable
+ #define jpeg_quality_scaling jQualityScaling
++ #define jpeg_simple_lossless jSimLossless
+ #define jpeg_simple_progression jSimProgress
+ #define jpeg_suppress_tables jSuppressTables
+ #define jpeg_alloc_quant_table jAlcQTable
+***************
+*** 926,931 ****
+--- 959,966 ----
+ int scale_factor,
+ boolean force_baseline));
+ EXTERN(int) jpeg_quality_scaling JPP((int quality));
++ EXTERN(void) jpeg_simple_lossless JPP((j_compress_ptr cinfo,
++ int predictor, int point_transform));
+ EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
+ EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
+ boolean suppress));
+diff -cN ../jpeg-6b/libjpeg.doc ./libjpeg.doc
+*** ../jpeg-6b/libjpeg.doc Sat Feb 21 16:08:54 1998
+--- ./libjpeg.doc Tue Apr 27 14:58:34 1999
+***************
+*** 92,98 ****
+ JPEG processes are supported. (Our subset includes all features now in common
+ use.) Unsupported ISO options include:
+ * Hierarchical storage
+- * Lossless JPEG
+ * Arithmetic entropy coding (unsupported for legal reasons)
+ * DNL marker
+ * Nonintegral subsampling ratios
+--- 92,97 ----
+***************
+*** 867,872 ****
+--- 866,877 ----
+ jpeg_simple_progression (j_compress_ptr cinfo)
+ Generates a default scan script for writing a progressive-JPEG file.
+ This is the recommended method of creating a progressive file,
++ unless you want to make a custom scan sequence. You must ensure that
++ the JPEG color space is set correctly before calling this routine.
++
++ jpeg_simple_lossless (j_compress_ptr cinfo, int predictor, int point_transform)
++ Generates a default scan script for writing a lossless-JPEG file.
++ This is the recommended method of creating a lossless file,
+ unless you want to make a custom scan sequence. You must ensure that
+ the JPEG color space is set correctly before calling this routine.
+
+diff -cN ../jpeg-6b/makefile.cfg ./makefile.cfg
+*** ../jpeg-6b/makefile.cfg Sat Mar 21 14:08:57 1998
+--- ./makefile.cfg Tue Apr 27 14:58:34 1999
+***************
+*** 73,86 ****
+
+
+ # source files: JPEG library proper
+! LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jchuff.c \
+! jcinit.c jcmainct.c jcmarker.c jcmaster.c jcomapi.c jcparam.c \
+! jcphuff.c jcprepct.c jcsample.c jctrans.c jdapimin.c jdapistd.c \
+! jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c jdhuff.c \
+! jdinput.c jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c \
+! jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c jfdctfst.c \
+! jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c jquant1.c \
+! jquant2.c jutils.c jmemmgr.c
+ # memmgr back ends: compile only one of these into a working library
+ SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+ # source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+--- 73,88 ----
+
+
+ # source files: JPEG library proper
+! LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jcdiffct.c \
+! jchuff.c jcinit.c jclhuff.c jclossls.c jclossy.c jcmainct.c \
+! jcmarker.c jcmaster.c jcodec.c jcomapi.c jcparam.c jcphuff.c jcpred.c \
+! jcprepct.c jcsample.c jcscale.c jcshuff.c jctrans.c jdapimin.c \
+! jdapistd.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c \
+! jddiffct.c jdhuff.c jdinput.c jdlhuff.c jdlossls.c jdlossy.c \
+! jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c jdpostct.c \
+! jdpred.c jdsample.c jdscale.c jdshuff.c jdtrans.c jerror.c jfdctflt.c \
+! jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c \
+! jquant1.c jquant2.c jutils.c jmemmgr.c
+ # memmgr back ends: compile only one of these into a working library
+ SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+ # source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+***************
+*** 89,96 ****
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+ SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+ # files included by source files
+! INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h \
+! jpegint.h jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
+ # documentation, test, and support files
+ DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
+--- 91,99 ----
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+ SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+ # files included by source files
+! INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jlossls.h jlossy.h \
+! jmemsys.h jmorecfg.h jpegint.h jpeglib.h jversion.h cdjpeg.h \
+! cderror.h transupp.h
+ # documentation, test, and support files
+ DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
+***************
+*** 110,127 ****
+ DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+ # library object files common to compression and decompression
+! COMOBJECTS= jcomapi.$(O) jutils.$(O) jerror.$(O) jmemmgr.$(O) $(SYSDEPMEM)
+ # compression library object files
+ CLIBOBJECTS= jcapimin.$(O) jcapistd.$(O) jctrans.$(O) jcparam.$(O) \
+ jdatadst.$(O) jcinit.$(O) jcmaster.$(O) jcmarker.$(O) jcmainct.$(O) \
+! jcprepct.$(O) jccoefct.$(O) jccolor.$(O) jcsample.$(O) jchuff.$(O) \
+! jcphuff.$(O) jcdctmgr.$(O) jfdctfst.$(O) jfdctflt.$(O) \
+! jfdctint.$(O)
+ # decompression library object files
+ DLIBOBJECTS= jdapimin.$(O) jdapistd.$(O) jdtrans.$(O) jdatasrc.$(O) \
+! jdmaster.$(O) jdinput.$(O) jdmarker.$(O) jdhuff.$(O) jdphuff.$(O) \
+! jdmainct.$(O) jdcoefct.$(O) jdpostct.$(O) jddctmgr.$(O) \
+! jidctfst.$(O) jidctflt.$(O) jidctint.$(O) jidctred.$(O) \
+ jdsample.$(O) jdcolor.$(O) jquant1.$(O) jquant2.$(O) jdmerge.$(O)
+ # These objectfiles are included in libjpeg.a
+ LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+--- 113,133 ----
+ DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+ # library object files common to compression and decompression
+! COMOBJECTS= jcomapi.$(O) jcodec.$(O) jutils.$(O) jerror.$(O) jmemmgr.$(O) \
+! $(SYSDEPMEM)
+ # compression library object files
+ CLIBOBJECTS= jcapimin.$(O) jcapistd.$(O) jctrans.$(O) jcparam.$(O) \
+ jdatadst.$(O) jcinit.$(O) jcmaster.$(O) jcmarker.$(O) jcmainct.$(O) \
+! jcprepct.$(O) jclossls.$(O) jclossy.o jccoefct.$(O) jccolor.$(O) \
+! jcsample.$(O) jchuff.$(O) jcphuff.$(O) jcshuff.$(O) jclhuff.$(O) \
+! jcpred.$(O) jcscale.$(O) jcdiffct.$(O) jcdctmgr.$(O) jfdctfst.$(O) \
+! jfdctflt.$(O) jfdctint.$(O)
+ # decompression library object files
+ DLIBOBJECTS= jdapimin.$(O) jdapistd.$(O) jdtrans.$(O) jdatasrc.$(O) \
+! jdmaster.$(O) jdinput.$(O) jdmarker.$(O) jdlossls.$(O) jdlossy.$(O) \
+! jdhuff.$(O) jdlhuff.$(O) jdphuff.$(O) jdshuff.$(O) jdpred.$(O) \
+! jdscale.$(O) jddiffct.$(O) jdmainct.$(O) jdcoefct.$(O) jdpostct.$(O) \
+! jddctmgr.$(O) jidctfst.$(O) jidctflt.$(O) jidctint.$(O) jidctred.$(O) \
+ jdsample.$(O) jdcolor.$(O) jquant1.$(O) jquant2.$(O) jdmerge.$(O)
+ # These objectfiles are included in libjpeg.a
+ LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+***************
+*** 228,233 ****
+--- 234,241 ----
+ ./djpeg -dct int -ppm -outfile testoutp.ppm $(srcdir)/testprog.jpg
+ ./cjpeg -dct int -progressive -opt -outfile testoutp.jpg $(srcdir)/testimg.ppm
+ ./jpegtran -outfile testoutt.jpg $(srcdir)/testprog.jpg
++ ./djpeg -ppm -outfile testoutl.ppm $(srcdir)/testimgl.jpg
++ ./cjpeg -lossless 4,1 -outfile testoutl.jpg $(srcdir)/testimg.ppm
+ cmp $(srcdir)/testimg.ppm testout.ppm
+ cmp $(srcdir)/testimg.bmp testout.bmp
+ cmp $(srcdir)/testimg.jpg testout.jpg
+***************
+*** 234,239 ****
+--- 242,249 ----
+ cmp $(srcdir)/testimg.ppm testoutp.ppm
+ cmp $(srcdir)/testimgp.jpg testoutp.jpg
+ cmp $(srcdir)/testorig.jpg testoutt.jpg
++ cmp $(srcdir)/testimgl.ppm testoutl.ppm
++ cmp $(srcdir)/testimgl.jpg testoutl.jpg
+
+ check: test
+
+***************
+*** 250,286 ****
+
+ jcapimin.$(O): jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jcapistd.$(O): jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jccoefct.$(O): jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jccolor.$(O): jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jcdctmgr.$(O): jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+! jchuff.$(O): jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+ jcinit.$(O): jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jcmainct.$(O): jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jcmarker.$(O): jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jcmaster.$(O): jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jcomapi.$(O): jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jcparam.$(O): jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jcphuff.$(O): jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+ jcprepct.$(O): jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jcsample.$(O): jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jctrans.$(O): jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdapimin.$(O): jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdapistd.$(O): jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdatadst.$(O): jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+ jdatasrc.$(O): jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+! jdcoefct.$(O): jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdcolor.$(O): jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jddctmgr.$(O): jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+! jdhuff.$(O): jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+ jdinput.$(O): jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdmainct.$(O): jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdmarker.$(O): jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdmaster.$(O): jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdmerge.$(O): jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jdphuff.$(O): jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+ jdpostct.$(O): jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdsample.$(O): jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jdtrans.$(O): jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jerror.$(O): jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+ jfdctflt.$(O): jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+ jfdctfst.$(O): jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+--- 260,311 ----
+
+ jcapimin.$(O): jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jcapistd.$(O): jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jccoefct.$(O): jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+! jcodec.$(O): jcodec.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jlossls.h
+ jccolor.$(O): jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jcdctmgr.$(O): jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jdct.h
+! jcdiffct.$(O): jcdiffct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+! jchuff.$(O): jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jlossls.h jchuff.h
+ jcinit.$(O): jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
++ jclhuff.$(O): jclhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h jchuff.h
++ jclossls.$(O): jclossls.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
++ jclossy.$(O): jclossy.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+ jcmainct.$(O): jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jcmarker.$(O): jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jcmaster.$(O): jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jcomapi.$(O): jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jcparam.$(O): jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jcphuff.$(O): jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jchuff.h
+! jcpred.$(O): jcpred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+ jcprepct.$(O): jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jcsample.$(O): jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jcscale.$(O): jcscale.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+! jcshuff.$(O): jcshuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jlossls.h jchuff.h
+! jctrans.$(O): jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+ jdapimin.$(O): jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdapistd.$(O): jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdatadst.$(O): jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+ jdatasrc.$(O): jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+! jdcoefct.$(O): jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+ jdcolor.$(O): jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jddctmgr.$(O): jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jdct.h
+! jddiffct.$(O): jddiffct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+! jdhuff.$(O): jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jlossls.h jdhuff.h
+ jdinput.$(O): jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
++ jdlhuff.$(O): jdlhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h jdhuff.h
++ jdlossls.$(O): jdlossls.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
++ jdlossy.$(O): jdlossy.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+ jdmainct.$(O): jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdmarker.$(O): jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdmaster.$(O): jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+ jdmerge.$(O): jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jdphuff.$(O): jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jdhuff.h
+ jdpostct.$(O): jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
++ jdpred.$(O): jdpred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+ jdsample.$(O): jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+! jdscale.$(O): jdscale.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+! jdshuff.$(O): jdshuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jdhuff.h
+! jdtrans.$(O): jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+ jerror.$(O): jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+ jfdctflt.$(O): jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+ jfdctfst.$(O): jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+diff -cN ../jpeg-6b/rdswitch.c ./rdswitch.c
+*** ../jpeg-6b/rdswitch.c Sat Jan 13 14:42:45 1996
+--- ./rdswitch.c Tue Apr 27 14:58:35 1999
+***************
+*** 330,332 ****
+--- 330,358 ----
+ }
+ return TRUE;
+ }
++
++
++ #ifdef C_LOSSLESS_SUPPORTED
++
++ GLOBAL(boolean)
++ set_simple_lossless (j_compress_ptr cinfo, char *arg)
++ {
++ int pred, pt = 0;
++ char ch;
++
++ ch = ','; /* if not set by sscanf, will be ',' */
++ if (sscanf(arg, "%d%c", &pred, &ch) < 1)
++ return FALSE;
++ if (ch != ',') /* syntax check */
++ return FALSE;
++ while (*arg && *arg++ != ',') /* advance to next segment of arg string */
++ ;
++ if (*arg) {
++ if (sscanf(arg, "%d", &pt) != 1)
++ pt = 0;
++ }
++ jpeg_simple_lossless(cinfo, pred, pt);
++ return TRUE;
++ }
++
++ #endif /* C_LOSSLESS_SUPPORTED */
+diff -cN ../jpeg-6b/structure.doc ./structure.doc
+*** ../jpeg-6b/structure.doc Tue Nov 21 12:00:39 1995
+--- ./structure.doc Tue Apr 27 14:58:35 1999
+***************
+*** 21,28 ****
+ A "sample" is a single component value (i.e., one number in the image data).
+ A "coefficient" is a frequency coefficient (a DCT transform output number).
+ A "block" is an 8x8 group of samples or coefficients.
+! An "MCU" (minimum coded unit) is an interleaved set of blocks of size
+! determined by the sampling factors, or a single block in a
+ noninterleaved scan.
+ We do not use the terms "pixel" and "sample" interchangeably. When we say
+ pixel, we mean an element of the full-size image, while a sample is an element
+--- 21,30 ----
+ A "sample" is a single component value (i.e., one number in the image data).
+ A "coefficient" is a frequency coefficient (a DCT transform output number).
+ A "block" is an 8x8 group of samples or coefficients.
+! A "data unit" is an abstract data type which is either a block for lossy
+! (DCT-based) codecs or a sample for lossless (predictive) codecs.
+! An "MCU" (minimum coded unit) is an interleaved set of data units of size
+! determined by the sampling factors, or a single data unit in a
+ noninterleaved scan.
+ We do not use the terms "pixel" and "sample" interchangeably. When we say
+ pixel, we mean an element of the full-size image, while a sample is an element
+***************
+*** 43,56 ****
+ formats. This document concentrates on the library itself.
+
+ We desire the library to be capable of supporting all JPEG baseline, extended
+! sequential, and progressive DCT processes. Hierarchical processes are not
+! supported.
+
+- The library does not support the lossless (spatial) JPEG process. Lossless
+- JPEG shares little or no code with lossy JPEG, and would normally be used
+- without the extensive pre- and post-processing provided by this library.
+- We feel that lossless JPEG is better handled by a separate library.
+-
+ Within these limits, any set of compression parameters allowed by the JPEG
+ spec should be readable for decompression. (We can be more restrictive about
+ what formats we can generate.) Although the system design allows for all
+--- 45,53 ----
+ formats. This document concentrates on the library itself.
+
+ We desire the library to be capable of supporting all JPEG baseline, extended
+! sequential, and progressive DCT processes, as well as the lossless (spatial)
+! process. Hierarchical processes are not supported.
+
+ Within these limits, any set of compression parameters allowed by the JPEG
+ spec should be readable for decompression. (We can be more restrictive about
+ what formats we can generate.) Although the system design allows for all
+***************
+*** 134,142 ****
+ * Color space conversion (e.g., RGB to YCbCr).
+ * Edge expansion and downsampling. Optionally, this step can do simple
+ smoothing --- this is often helpful for low-quality source data.
+! JPEG proper:
+ * MCU assembly, DCT, quantization.
+ * Entropy coding (sequential or progressive, Huffman or arithmetic).
+
+ In addition to these modules we need overall control, marker generation,
+ and support code (memory management & error handling). There is also a
+--- 131,143 ----
+ * Color space conversion (e.g., RGB to YCbCr).
+ * Edge expansion and downsampling. Optionally, this step can do simple
+ smoothing --- this is often helpful for low-quality source data.
+! Lossy JPEG proper:
+ * MCU assembly, DCT, quantization.
+ * Entropy coding (sequential or progressive, Huffman or arithmetic).
++ Lossless JPEG proper:
++ * Point transform.
++ * Prediction, differencing.
++ * Entropy coding (Huffman or arithmetic)
+
+ In addition to these modules we need overall control, marker generation,
+ and support code (memory management & error handling). There is also a
+***************
+*** 146,154 ****
+
+ The decompressor library contains the following main elements:
+
+! JPEG proper:
+ * Entropy decoding (sequential or progressive, Huffman or arithmetic).
+ * Dequantization, inverse DCT, MCU disassembly.
+ Postprocessing:
+ * Upsampling. Optionally, this step may be able to do more general
+ rescaling of the image.
+--- 147,159 ----
+
+ The decompressor library contains the following main elements:
+
+! Lossy JPEG proper:
+ * Entropy decoding (sequential or progressive, Huffman or arithmetic).
+ * Dequantization, inverse DCT, MCU disassembly.
++ Lossless JPEG proper:
++ * Entropy decoding (Huffman or arithmetic).
++ * Prediction, undifferencing.
++ * Point transform, sample size scaling.
+ Postprocessing:
+ * Upsampling. Optionally, this step may be able to do more general
+ rescaling of the image.
+***************
+*** 312,317 ****
+--- 317,337 ----
+ task performed by any one controller.
+
+
++ *** Codec object structure ***
++
++ As noted above, this library supports both the lossy (DCT-based) and lossless
++ JPEG processes. Because these processes have little in common with one another
++ (and their implementations share very little code), we need to provide a way to
++ isloate the underlying JPEG process from the rest of the library. This is
++ accomplished by introducing an abstract "codec object" which acts a generic
++ interface to the JPEG (de)compressor proper.
++
++ Using the power of the object-oriented scheme described above, we build the
++ lossy and lossless modules as two separate implementations of the codec object.
++ Switching between lossy and lossless processes then becomes as trivial as
++ assigning the appropriate method pointers during initialization of the library.
++
++
+ *** Compression object structure ***
+
+ Here is a sketch of the logical structure of the JPEG compression library:
+***************
+*** 319,329 ****
+ |-- Colorspace conversion
+ |-- Preprocessing controller --|
+ | |-- Downsampling
+ Main controller --|
+! | |-- Forward DCT, quantize
+! |-- Coefficient controller --|
+! |-- Entropy encoding
+
+ This sketch also describes the flow of control (subroutine calls) during
+ typical image data processing. Each of the components shown in the diagram is
+ an "object" which may have several different implementations available. One
+--- 339,369 ----
+ |-- Colorspace conversion
+ |-- Preprocessing controller --|
+ | |-- Downsampling
++ |
+ Main controller --|
+! | /--> Lossy codec
+! | /
+! |-- Compression codec < *OR*
+! \
+! \--> Lossless codec
+!
+!
+! where the lossy codec looks like:
+
++ |-- Forward DCT, quantize
++ <-- Coefficient controller --|
++ |-- Entropy encoding
++
++
++ and the lossless codec looks like:
++
++ |-- Point transformation
++ |
++ <-- Difference controller --|-- Prediction, differencing
++ |
++ |-- Lossless entropy encoding
++
++
+ This sketch also describes the flow of control (subroutine calls) during
+ typical image data processing. Each of the components shown in the diagram is
+ an "object" which may have several different implementations available. One
+***************
+*** 377,382 ****
+--- 417,439 ----
+ during each pass, and the coder must emit the appropriate subset of
+ coefficients.
+
++ * Difference controller: buffer controller for the spatial difference data.
++ When emitting a multiscan JPEG file, this controller is responsible for
++ buffering the full image. The equivalent of one fully interleaved MCU row
++ of subsampled data is processed per call, even when the JPEG file is
++ noninterleaved.
++
++ * Point transformation: Scale the data down by the point transformation
++ parameter.
++
++ * Prediction and differencing: Calculate the predictor and subtract it
++ from the input. Works on one scanline per call. The difference
++ controller supplies the prior scanline which is used for prediction.
++
++ * Lossless entropy encoding: Perform Huffman or arithmetic entropy coding and
++ emit the coded data to the data destination module. This module handles MCU
++ assembly. Works on one MCU-row per call.
++
+ In addition to the above objects, the compression library includes these
+ objects:
+
+***************
+*** 418,432 ****
+
+ Here is a sketch of the logical structure of the JPEG decompression library:
+
+! |-- Entropy decoding
+! |-- Coefficient controller --|
+! | |-- Dequantize, Inverse DCT
+ Main controller --|
+ | |-- Upsampling
+ |-- Postprocessing controller --| |-- Colorspace conversion
+ |-- Color quantization
+ |-- Color precision reduction
+
+ As before, this diagram also represents typical control flow. The objects
+ shown are:
+
+--- 475,509 ----
+
+ Here is a sketch of the logical structure of the JPEG decompression library:
+
+! /--> Lossy codec
+! /
+! |-- Decompression codec < *OR*
+! | \
+! | \--> Lossless codec
+ Main controller --|
++ |
+ | |-- Upsampling
+ |-- Postprocessing controller --| |-- Colorspace conversion
+ |-- Color quantization
+ |-- Color precision reduction
+
++
++ where the lossy codec looks like:
++
++ |-- Entropy decoding
++ <-- Coefficient controller --|
++ |-- Dequantize, Inverse DCT
++
++
++ and the lossless codec looks like:
++
++ |-- Lossless entropy decoding
++ |
++ <-- Difference controller --|-- Prediction, undifferencing
++ |
++ |-- Point transformation, sample size scaling
++
++
+ As before, this diagram also represents typical control flow. The objects
+ shown are:
+
+***************
+*** 459,464 ****
+--- 536,558 ----
+ When scaled-down output is asked for, simplified DCT algorithms may be used
+ that emit only 1x1, 2x2, or 4x4 samples per DCT block, not the full 8x8.
+ Works on one DCT block at a time.
++
++ * Difference controller: buffer controller for the spatial difference data.
++ When reading a multiscan JPEG file, this controller is responsible for
++ buffering the full image. The equivalent of one fully interleaved MCU row
++ is processed per call, even when the source JPEG file is noninterleaved.
++
++ * Lossless entropy decoding: Read coded data from the data source module and
++ perform Huffman or arithmetic entropy decoding. Works on one MCU-row per
++ call.
++
++ * Prediction and undifferencing: Calculate the predictor and add it to the
++ decoded difference. Works on one scanline per call. The difference
++ controller supplies the prior scanline which is used for prediction.
++
++ * Point transform and sample size scaling: Scale the data up by the point
++ transformation parameter and scale it down to fit into the compiled-in
++ sample size.
+
+ * Postprocessing controller: buffer controller for the color quantization
+ input buffer, when quantization is in use. (Without quantization, this
+diff -cN ../jpeg-6b/transupp.c ./transupp.c
+*** ../jpeg-6b/transupp.c Sat Aug 9 20:15:26 1997
+--- ./transupp.c Tue Apr 27 15:08:05 1999
+***************
+*** 1,7 ****
+ /*
+ * transupp.c
+ *
+! * Copyright (C) 1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+--- 1,7 ----
+ /*
+ * transupp.c
+ *
+! * Copyright (C) 1997-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+***************
+*** 84,90 ****
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+! for (blk_y = 0; blk_y < compptr->height_in_blocks;
+ blk_y += compptr->v_samp_factor) {
+ buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
+--- 84,90 ----
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+! for (blk_y = 0; blk_y < compptr->height_in_data_units;
+ blk_y += compptr->v_samp_factor) {
+ buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
+***************
+*** 136,142 ****
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_height = MCU_rows * compptr->v_samp_factor;
+! for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+--- 136,142 ----
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_height = MCU_rows * compptr->v_samp_factor;
+! for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+***************
+*** 158,164 ****
+ /* Row is within the mirrorable area. */
+ dst_row_ptr = dst_buffer[offset_y];
+ src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
+! for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
+ dst_blk_x++) {
+ dst_ptr = dst_row_ptr[dst_blk_x];
+ src_ptr = src_row_ptr[dst_blk_x];
+--- 158,164 ----
+ /* Row is within the mirrorable area. */
+ dst_row_ptr = dst_buffer[offset_y];
+ src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
+! for (dst_blk_x = 0; dst_blk_x < compptr->width_in_data_units;
+ dst_blk_x++) {
+ dst_ptr = dst_row_ptr[dst_blk_x];
+ src_ptr = src_row_ptr[dst_blk_x];
+***************
+*** 174,180 ****
+ } else {
+ /* Just copy row verbatim. */
+ jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
+! compptr->width_in_blocks);
+ }
+ }
+ }
+--- 174,180 ----
+ } else {
+ /* Just copy row verbatim. */
+ jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
+! compptr->width_in_data_units);
+ }
+ }
+ }
+***************
+*** 201,213 ****
+ */
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+! for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+! for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
+ dst_blk_x += compptr->h_samp_factor) {
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
+--- 201,213 ----
+ */
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+! for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+! for (dst_blk_x = 0; dst_blk_x < compptr->width_in_data_units;
+ dst_blk_x += compptr->h_samp_factor) {
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
+***************
+*** 251,263 ****
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+! for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+! for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
+ dst_blk_x += compptr->h_samp_factor) {
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
+--- 251,263 ----
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+! for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+! for (dst_blk_x = 0; dst_blk_x < compptr->width_in_data_units;
+ dst_blk_x += compptr->h_samp_factor) {
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
+***************
+*** 315,327 ****
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_height = MCU_rows * compptr->v_samp_factor;
+! for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+! for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
+ dst_blk_x += compptr->h_samp_factor) {
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
+--- 315,327 ----
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_height = MCU_rows * compptr->v_samp_factor;
+! for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+! for (dst_blk_x = 0; dst_blk_x < compptr->width_in_data_units;
+ dst_blk_x += compptr->h_samp_factor) {
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
+***************
+*** 378,384 ****
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+ comp_height = MCU_rows * compptr->v_samp_factor;
+! for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+--- 378,384 ----
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+ comp_height = MCU_rows * compptr->v_samp_factor;
+! for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+***************
+*** 418,424 ****
+ }
+ }
+ /* Any remaining right-edge blocks are only mirrored vertically. */
+! for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
+ dst_ptr = dst_row_ptr[dst_blk_x];
+ src_ptr = src_row_ptr[dst_blk_x];
+ for (i = 0; i < DCTSIZE; i += 2) {
+--- 418,424 ----
+ }
+ }
+ /* Any remaining right-edge blocks are only mirrored vertically. */
+! for (; dst_blk_x < compptr->width_in_data_units; dst_blk_x++) {
+ dst_ptr = dst_row_ptr[dst_blk_x];
+ src_ptr = src_row_ptr[dst_blk_x];
+ for (i = 0; i < DCTSIZE; i += 2) {
+***************
+*** 442,448 ****
+ }
+ }
+ /* Any remaining right-edge blocks are only copied. */
+! for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
+ dst_ptr = dst_row_ptr[dst_blk_x];
+ src_ptr = src_row_ptr[dst_blk_x];
+ for (i = 0; i < DCTSIZE2; i++)
+--- 442,448 ----
+ }
+ }
+ /* Any remaining right-edge blocks are only copied. */
+! for (; dst_blk_x < compptr->width_in_data_units; dst_blk_x++) {
+ dst_ptr = dst_row_ptr[dst_blk_x];
+ src_ptr = src_row_ptr[dst_blk_x];
+ for (i = 0; i < DCTSIZE2; i++)
+***************
+*** 482,494 ****
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+ comp_height = MCU_rows * compptr->v_samp_factor;
+! for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+! for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
+ dst_blk_x += compptr->h_samp_factor) {
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
+--- 482,494 ----
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+ comp_height = MCU_rows * compptr->v_samp_factor;
+! for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+! for (dst_blk_x = 0; dst_blk_x < compptr->width_in_data_units;
+ dst_blk_x += compptr->h_samp_factor) {
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
+***************
+*** 600,608 ****
+ compptr = srcinfo->comp_info + ci;
+ coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
+ ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
+! (JDIMENSION) jround_up((long) compptr->width_in_blocks,
+ (long) compptr->h_samp_factor),
+! (JDIMENSION) jround_up((long) compptr->height_in_blocks,
+ (long) compptr->v_samp_factor),
+ (JDIMENSION) compptr->v_samp_factor);
+ }
+--- 600,608 ----
+ compptr = srcinfo->comp_info + ci;
+ coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
+ ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
+! (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor),
+! (JDIMENSION) jround_up((long) compptr->height_in_data_units,
+ (long) compptr->v_samp_factor),
+ (JDIMENSION) compptr->v_samp_factor);
+ }
+***************
+*** 622,630 ****
+ compptr = srcinfo->comp_info + ci;
+ coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
+ ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
+! (JDIMENSION) jround_up((long) compptr->height_in_blocks,
+ (long) compptr->v_samp_factor),
+! (JDIMENSION) jround_up((long) compptr->width_in_blocks,
+ (long) compptr->h_samp_factor),
+ (JDIMENSION) compptr->h_samp_factor);
+ }
+--- 622,630 ----
+ compptr = srcinfo->comp_info + ci;
+ coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
+ ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
+! (JDIMENSION) jround_up((long) compptr->height_in_data_units,
+ (long) compptr->v_samp_factor),
+! (JDIMENSION) jround_up((long) compptr->width_in_data_units,
+ (long) compptr->h_samp_factor),
+ (JDIMENSION) compptr->h_samp_factor);
+ }
diff --git a/jpeg-6c/ltconfig b/jpeg-6c/ltconfig
new file mode 100644
index 0000000..2347e69
--- /dev/null
+++ b/jpeg-6c/ltconfig
@@ -0,0 +1,1512 @@
+#! /bin/sh
+
+# ltconfig - Create a system-specific libtool.
+# Copyright (C) 1996-1998 Free Software Foundation, Inc.
+# Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
+#
+# This file 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 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, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# A lot of this script is taken from autoconf-2.10.
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+if test "${CDPATH+set}" = set; then CDPATH=; export CDPATH; fi
+
+echo=echo
+if test "X`($echo '\t') 2>/dev/null`" = 'X\t'; then :
+else
+ # The Solaris and AIX default echo program unquotes backslashes.
+ # This makes it impossible to quote backslashes using
+ # echo "$something" | sed 's/\\/\\\\/g'
+ # So, we emulate echo with printf '%s\n'
+ echo="printf %s\\n"
+ if test "X`($echo '\t') 2>/dev/null`" = 'X\t'; then :
+ else
+ # Oops. We have no working printf. Try to find a not-so-buggy echo.
+ echo=echo
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS="${IFS}:"
+ for dir in $PATH /usr/ucb; do
+ if test -f $dir/echo && test "X`$dir/echo '\t'`" = 'X\t'; then
+ echo="$dir/echo"
+ break
+ fi
+ done
+ IFS="$save_ifs"
+ fi
+fi
+
+# Sed substitution that helps us do robust quoting. It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed='sed -e s/^X//'
+sed_quote_subst='s/\([\\"\\`$\\\\]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst='s/\([\\"\\`\\\\]\)/\\\1/g'
+
+# The name of this program.
+progname=`$echo "X$0" | $Xsed -e 's%^.*/%%'`
+
+# Constants:
+PROGRAM=ltconfig
+PACKAGE=libtool
+VERSION=1.2
+ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.c 1>&5'
+ac_link='${CC-cc} -o conftest $CFLAGS $CPPFLAGS $LDFLAGS conftest.c $LIBS 1>&5'
+rm="rm -f"
+
+help="Try \`$progname --help' for more information."
+
+# Global variables:
+can_build_shared=yes
+enable_shared=yes
+# All known linkers require a `.a' archive for static linking.
+enable_static=yes
+ltmain=
+silent=
+srcdir=
+ac_config_guess=
+ac_config_sub=
+host=
+nonopt=
+verify_host=yes
+with_gcc=no
+with_gnu_ld=no
+
+old_AR="$AR"
+old_CC="$CC"
+old_CFLAGS="$CFLAGS"
+old_CPPFLAGS="$CPPFLAGS"
+old_LD="$LD"
+old_LN_S="$LN_S"
+old_NM="$NM"
+old_RANLIB="$RANLIB"
+
+# Parse the command line options.
+args=
+prev=
+for option
+do
+ case "$option" in
+ -*=*) optarg=`echo "$option" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
+ *) optarg= ;;
+ esac
+
+ # If the previous option needs an argument, assign it.
+ if test -n "$prev"; then
+ eval "$prev=\$option"
+ prev=
+ continue
+ fi
+
+ case "$option" in
+ --help) cat <<EOM
+Usage: $progname [OPTION]... LTMAIN [HOST]
+
+Generate a system-specific libtool script.
+
+ --disable-shared do not build shared libraries
+ --disable-static do not build static libraries
+ --help display this help and exit
+ --no-verify do not verify that HOST is a valid host type
+ --quiet same as \`--silent'
+ --silent do not print informational messages
+ --srcdir=DIR find \`config.guess' in DIR
+ --version output version information and exit
+ --with-gcc assume that the GNU C compiler will be used
+ --with-gnu-ld assume that the C compiler uses the GNU linker
+
+LTMAIN is the \`ltmain.sh' shell script fragment that provides basic libtool
+functionality.
+
+HOST is the canonical host system name [default=guessed].
+EOM
+ exit 0
+ ;;
+
+ --disable-shared) enable_shared=no ;;
+
+ --disable-static) enable_static=no ;;
+
+ --quiet | --silent) silent=yes ;;
+
+ --srcdir) prev=srcdir ;;
+ --srcdir=*) srcdir="$optarg" ;;
+
+ --no-verify) verify_host=no ;;
+
+ --version) echo "$PROGRAM (GNU $PACKAGE) $VERSION"; exit 0 ;;
+
+ --with-gcc) with_gcc=yes ;;
+ --with-gnu-ld) with_gnu_ld=yes ;;
+
+ -*)
+ echo "$progname: unrecognized option \`$option'" 1>&2
+ echo "$help" 1>&2
+ exit 1
+ ;;
+
+ *)
+ if test -z "$ltmain"; then
+ ltmain="$option"
+ elif test -z "$host"; then
+# This generates an unnecessary warning for sparc-sun-solaris4.1.3_U1
+# if test -n "`echo $option| sed 's/[-a-z0-9.]//g'`"; then
+# echo "$progname: warning \`$option' is not a valid host type" 1>&2
+# fi
+ host="$option"
+ else
+ echo "$progname: too many arguments" 1>&2
+ echo "$help" 1>&2
+ exit 1
+ fi ;;
+ esac
+done
+
+if test -z "$ltmain"; then
+ echo "$progname: you must specify a LTMAIN file" 1>&2
+ echo "$help" 1>&2
+ exit 1
+fi
+
+if test -f "$ltmain"; then :
+else
+ echo "$progname: \`$ltmain' does not exist" 1>&2
+ echo "$help" 1>&2
+ exit 1
+fi
+
+# Quote any args containing shell metacharacters.
+ltconfig_args=
+for arg
+do
+ case "$arg" in
+ *" "*|*" "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?]*)
+ ltconfig_args="$ltconfig_args '$arg'" ;;
+ *) ltconfig_args="$ltconfig_args $arg" ;;
+ esac
+done
+
+# A relevant subset of AC_INIT.
+
+# File descriptor usage:
+# 0 standard input
+# 1 file creation
+# 2 errors and warnings
+# 3 some systems may open it to /dev/tty
+# 4 used on the Kubota Titan
+# 5 compiler messages saved in config.log
+# 6 checking for... messages and results
+if test "$silent" = yes; then
+ exec 6>/dev/null
+else
+ exec 6>&1
+fi
+exec 5>>./config.log
+
+# NLS nuisances.
+# Only set LANG and LC_ALL to C if already set.
+# These must not be set unconditionally because not all systems understand
+# e.g. LANG=C (notably SCO).
+if test "${LC_ALL+set}" = set; then LC_ALL=C; export LC_ALL; fi
+if test "${LANG+set}" = set; then LANG=C; export LANG; fi
+
+if (echo "testing\c"; echo 1,2,3) | grep c >/dev/null; then
+ # Stardent Vistra SVR4 grep lacks -e, says ghazi at caip.rutgers.edu.
+ if (echo -n testing; echo 1,2,3) | sed s/-n/xn/ | grep xn >/dev/null; then
+ ac_n= ac_c='
+' ac_t=' '
+ else
+ ac_n=-n ac_c= ac_t=
+ fi
+else
+ ac_n= ac_c='\c' ac_t=
+fi
+
+if test -z "$srcdir"; then
+ # Assume the source directory is the same one as the path to ltmain.sh.
+ srcdir=`$echo "$ltmain" | $Xsed -e 's%/[^/]*$%%'`
+ test "$srcdir" = "$ltmain" && srcdir=.
+fi
+
+trap "$rm conftest*; exit 1" 1 2 15
+if test "$verify_host" = yes; then
+ # Check for config.guess and config.sub.
+ ac_aux_dir=
+ for ac_dir in $srcdir $srcdir/.. $srcdir/../..; do
+ if test -f $ac_dir/config.guess; then
+ ac_aux_dir=$ac_dir
+ break
+ fi
+ done
+ if test -z "$ac_aux_dir"; then
+ echo "$progname: cannot find config.guess in $srcdir $srcdir/.. $srcdir/../.." 1>&2
+ echo "$help" 1>&2
+ exit 1
+ fi
+ ac_config_guess=$ac_aux_dir/config.guess
+ ac_config_sub=$ac_aux_dir/config.sub
+
+ # Make sure we can run config.sub.
+ if $ac_config_sub sun4 >/dev/null 2>&1; then :
+ else
+ echo "$progname: cannot run $ac_config_sub" 1>&2
+ echo "$help" 1>&2
+ exit 1
+ fi
+
+ echo $ac_n "checking host system type""... $ac_c" 1>&6
+
+ host_alias=$host
+ case "$host_alias" in
+ "")
+ if host_alias=`$ac_config_guess`; then :
+ else
+ echo "$progname: cannot guess host type; you must specify one" 1>&2
+ echo "$help" 1>&2
+ exit 1
+ fi ;;
+ esac
+ host=`$ac_config_sub $host_alias`
+ echo "$ac_t$host" 1>&6
+
+ # Make sure the host verified.
+ test -z "$host" && exit 1
+
+elif test -z "$host"; then
+ echo "$progname: you must specify a host type if you use \`--no-verify'" 1>&2
+ echo "$help" 1>&2
+ exit 1
+else
+ host_alias=$host
+fi
+
+# Transform linux* to *-*-linux-gnu*, to support old configure scripts.
+case "$host_os" in
+linux-gnu*) ;;
+linux*) host=`echo $host | sed 's/^\(.*-.*-linux\)\(.*\)$/\1-gnu\2/'`
+esac
+
+host_cpu=`echo $host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'`
+host_vendor=`echo $host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'`
+host_os=`echo $host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'`
+
+case "$host_os" in
+aix3*)
+ # AIX sometimes has problems with the GCC collect2 program. For some
+ # reason, if we set the COLLECT_NAMES environment variable, the problems
+ # vanish in a puff of smoke.
+ if test "${COLLECT_NAMES+set}" != set; then
+ COLLECT_NAMES=
+ export COLLECT_NAMES
+ fi
+ ;;
+esac
+
+# Determine commands to create old-style static archives.
+old_archive_cmds='$AR cru $oldlib$oldobjs'
+old_postinstall_cmds='chmod 644 $oldlib'
+old_postuninstall_cmds=
+
+# Set a sane default for `AR'.
+test -z "$AR" && AR=ar
+
+# If RANLIB is not set, then run the test.
+if test "${RANLIB+set}" != "set"; then
+ result=no
+
+ echo $ac_n "checking for ranlib... $ac_c" 1>&6
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS="${IFS}:"
+ for dir in $PATH; do
+ test -z "$dir" && dir=.
+ if test -f $dir/ranlib; then
+ RANLIB="ranlib"
+ result="ranlib"
+ break
+ fi
+ done
+ IFS="$save_ifs"
+
+ echo "$ac_t$result" 1>&6
+fi
+
+if test -n "$RANLIB"; then
+ old_archive_cmds="$old_archive_cmds;\$RANLIB \$oldlib"
+ old_postinstall_cmds="\$RANLIB \$oldlib;$old_postinstall_cmds"
+fi
+
+# Check to see if we are using GCC.
+if test "$with_gcc" != yes || test -z "$CC"; then
+ # If CC is not set, then try to find GCC or a usable CC.
+ if test -z "$CC"; then
+ echo $ac_n "checking for gcc... $ac_c" 1>&6
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS="${IFS}:"
+ for dir in $PATH; do
+ IFS="$save_ifs"
+ test -z "$dir" && dir=.
+ if test -f $dir/gcc; then
+ CC="gcc"
+ break
+ fi
+ done
+ IFS="$save_ifs"
+
+ if test -n "$CC"; then
+ echo "$ac_t$CC" 1>&6
+ else
+ echo "$ac_t"no 1>&6
+ fi
+ fi
+
+ # Not "gcc", so try "cc", rejecting "/usr/ucb/cc".
+ if test -z "$CC"; then
+ echo $ac_n "checking for cc... $ac_c" 1>&6
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS="${IFS}:"
+ cc_rejected=no
+ for dir in $PATH; do
+ test -z "$dir" && dir=.
+ if test -f $dir/cc; then
+ if test "$dir/cc" = "/usr/ucb/cc"; then
+ cc_rejected=yes
+ continue
+ fi
+ CC="cc"
+ break
+ fi
+ done
+ IFS="$save_ifs"
+ if test $cc_rejected = yes; then
+ # We found a bogon in the path, so make sure we never use it.
+ set dummy $CC
+ shift
+ if test $# -gt 0; then
+ # We chose a different compiler from the bogus one.
+ # However, it has the same name, so the bogon will be chosen
+ # first if we set CC to just the name; use the full file name.
+ shift
+ set dummy "$dir/cc" "$@"
+ shift
+ CC="$@"
+ fi
+ fi
+
+ if test -n "$CC"; then
+ echo "$ac_t$CC" 1>&6
+ else
+ echo "$ac_t"no 1>&6
+ fi
+
+ if test -z "$CC"; then
+ echo "$progname: error: no acceptable cc found in \$PATH" 1>&2
+ exit 1
+ fi
+ fi
+
+ # Now see if the compiler is really GCC.
+ with_gcc=no
+ echo $ac_n "checking whether we are using GNU C... $ac_c" 1>&6
+ echo "$progname:424: checking whether we are using GNU C" >&5
+
+ $rm conftest.c
+ cat > conftest.c <<EOF
+#ifdef __GNUC__
+ yes;
+#endif
+EOF
+ if { ac_try='${CC-cc} -E conftest.c'; { (eval echo $progname:432: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }; } | egrep yes >/dev/null 2>&1; then
+ with_gcc=yes
+ fi
+ $rm conftest.c
+ echo "$ac_t$with_gcc" 1>&6
+fi
+
+# Allow CC to be a program name with arguments.
+set dummy $CC
+compiler="$2"
+
+echo $ac_n "checking for $compiler option to produce PIC... $ac_c" 1>&6
+pic_flag=
+special_shlib_compile_flags=
+wl=
+link_static_flag=
+no_builtin_flag=
+
+if test "$with_gcc" = yes; then
+ wl='-Wl,'
+ link_static_flag='-static'
+ no_builtin_flag=' -fno-builtin'
+
+ case "$host_os" in
+ aix3* | aix4* | irix5* | irix6* | osf3* | osf4*)
+ # PIC is the default for these OSes.
+ ;;
+ os2*)
+ # We can build DLLs from non-PIC.
+ ;;
+ amigaos*)
+ # FIXME: we need at least 68020 code to build shared libraries, but
+ # adding the `-m68020' flag to GCC prevents building anything better,
+ # like `-m68040'.
+ pic_flag='-m68020 -resident32 -malways-restore-a4'
+ ;;
+ *)
+ pic_flag='-fPIC'
+ ;;
+ esac
+else
+ # PORTME Check for PIC flags for the system compiler.
+ case "$host_os" in
+ aix3* | aix4*)
+ # All AIX code is PIC.
+ link_static_flag='-bnso -bI:/lib/syscalls.exp'
+ ;;
+
+ hpux9* | hpux10*)
+ # Is there a better link_static_flag that works with the bundled CC?
+ wl='-Wl,'
+ link_static_flag="${wl}-a ${wl}archive"
+ pic_flag='+Z'
+ ;;
+
+ irix5* | irix6*)
+ wl='-Wl,'
+ link_static_flag='-non_shared'
+ # PIC (with -KPIC) is the default.
+ ;;
+
+ os2*)
+ # We can build DLLs from non-PIC.
+ ;;
+
+ osf3* | osf4*)
+ # All OSF/1 code is PIC.
+ wl='-Wl,'
+ link_static_flag='-non_shared'
+ ;;
+
+ sco3.2v5*)
+ pic_flag='-Kpic'
+ link_static_flag='-dn'
+ special_shlib_compile_flags='-belf'
+ ;;
+
+ solaris2*)
+ pic_flag='-KPIC'
+ link_static_flag='-Bstatic'
+ wl='-Wl,'
+ ;;
+
+ sunos4*)
+ pic_flag='-PIC'
+ link_static_flag='-Bstatic'
+ wl='-Qoption ld '
+ ;;
+
+ sysv4.2uw2*)
+ pic_flag='-KPIC'
+ link_static_flag='-Bstatic'
+ wl='-Wl,'
+ ;;
+
+ uts4*)
+ pic_flag='-pic'
+ link_static_flag='-Bstatic'
+ ;;
+
+ *)
+ can_build_shared=no
+ ;;
+ esac
+fi
+
+if test -n "$pic_flag"; then
+ echo "$ac_t$pic_flag" 1>&6
+
+ # Check to make sure the pic_flag actually works.
+ echo $ac_n "checking if $compiler PIC flag $pic_flag works... $ac_c" 1>&6
+ $rm conftest*
+ echo > conftest.c
+ save_CFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS $pic_flag -DPIC"
+ echo "$progname:547: checking if $compiler PIC flag $pic_flag works" >&5
+ if { (eval echo $progname:548: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>conftest.err; } && test -s conftest.o; then
+ # Append any warnings to the config.log.
+ cat conftest.err 1>&5
+
+ # On HP-UX, both CC and GCC only warn that PIC is supported... then they
+ # create non-PIC objects. So, if there were any warnings, we assume that
+ # PIC is not supported.
+ if test -s conftest.err; then
+ echo "$ac_t"no 1>&6
+ can_build_shared=no
+ pic_flag=
+ else
+ echo "$ac_t"yes 1>&6
+ pic_flag=" $pic_flag"
+ fi
+ else
+ # Append any errors to the config.log.
+ cat conftest.err 1>&5
+ can_build_shared=no
+ pic_flag=
+ echo "$ac_t"no 1>&6
+ fi
+ CFLAGS="$save_CFLAGS"
+ $rm conftest*
+else
+ echo "$ac_t"none 1>&6
+fi
+
+# Check for any special shared library compilation flags.
+if test -n "$special_shlib_compile_flags"; then
+ echo "$progname: warning: \`$CC' requires \`$special_shlib_compile_flags' to build shared libraries" 1>&2
+ if echo "$old_CC $old_CFLAGS " | egrep -e "[ ]$special_shlib_compile_flags[ ]" >/dev/null; then :
+ else
+ echo "$progname: add \`$special_shlib_compile_flags' to the CC or CFLAGS env variable and reconfigure" 1>&2
+ can_build_shared=no
+ fi
+fi
+
+echo $ac_n "checking if $compiler static flag $link_static_flag works... $ac_c" 1>&6
+$rm conftest*
+echo 'main(){return(0);}' > conftest.c
+save_LDFLAGS="$LDFLAGS"
+LDFLAGS="$LDFLAGS $link_static_flag"
+echo "$progname:591: checking if $compiler static flag $link_static_flag works" >&5
+if { (eval echo $progname:592: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest; then
+ echo "$ac_t$link_static_flag" 1>&6
+else
+ echo "$ac_t"none 1>&6
+ link_static_flag=
+fi
+LDFLAGS="$save_LDFLAGS"
+$rm conftest*
+
+if test -z "$LN_S"; then
+ # Check to see if we can use ln -s, or we need hard links.
+ echo $ac_n "checking whether ln -s works... $ac_c" 1>&6
+ $rm conftestdata
+ if ln -s X conftestdata 2>/dev/null; then
+ $rm conftestdata
+ LN_S="ln -s"
+ else
+ LN_S=ln
+ fi
+ if test "$LN_S" = "ln -s"; then
+ echo "$ac_t"yes 1>&6
+ else
+ echo "$ac_t"no 1>&6
+ fi
+fi
+
+# Make sure LD is an absolute path.
+if test -z "$LD"; then
+ ac_prog=ld
+ if test "$with_gcc" = yes; then
+ # Check if gcc -print-prog-name=ld gives a path.
+ echo $ac_n "checking for ld used by GCC... $ac_c" 1>&6
+ echo "$progname:624: checking for ld used by GCC" >&5
+ ac_prog=`($CC -print-prog-name=ld) 2>&5`
+ case "$ac_prog" in
+ # Accept absolute paths.
+ /* | [A-Za-z]:\\*)
+ test -z "$LD" && LD="$ac_prog"
+ ;;
+ "")
+ # If it fails, then pretend we are not using GCC.
+ ac_prog=ld
+ ;;
+ *)
+ # If it is relative, then search for the first ld in PATH.
+ with_gnu_ld=unknown
+ ;;
+ esac
+ elif test "$with_gnu_ld" = yes; then
+ echo $ac_n "checking for GNU ld... $ac_c" 1>&6
+ echo "$progname:642: checking for GNU ld" >&5
+ else
+ echo $ac_n "checking for non-GNU ld""... $ac_c" 1>&6
+ echo "$progname:645: checking for non-GNU ld" >&5
+ fi
+
+ if test -z "$LD"; then
+ IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS="${IFS}:"
+ for ac_dir in $PATH; do
+ test -z "$ac_dir" && ac_dir=.
+ if test -f "$ac_dir/$ac_prog"; then
+ LD="$ac_dir/$ac_prog"
+ # Check to see if the program is GNU ld. I'd rather use --version,
+ # but apparently some GNU ld's only accept -v.
+ # Break only if it was the GNU/non-GNU ld that we prefer.
+ if "$LD" -v 2>&1 < /dev/null | egrep '(GNU|with BFD)' > /dev/null; then
+ test "$with_gnu_ld" != no && break
+ else
+ test "$with_gnu_ld" != yes && break
+ fi
+ fi
+ done
+ IFS="$ac_save_ifs"
+ fi
+
+ if test -n "$LD"; then
+ echo "$ac_t$LD" 1>&6
+ else
+ echo "$ac_t"no 1>&6
+ fi
+
+ if test -z "$LD"; then
+ echo "$progname: error: no acceptable ld found in \$PATH" 1>&2
+ exit 1
+ fi
+fi
+
+# Check to see if it really is or is not GNU ld.
+echo $ac_n "checking if the linker ($LD) is GNU ld... $ac_c" 1>&6
+# I'd rather use --version here, but apparently some GNU ld's only accept -v.
+if $LD -v 2>&1 </dev/null | egrep '(GNU|with BFD)' 1>&5; then
+ with_gnu_ld=yes
+else
+ with_gnu_ld=no
+fi
+echo "$ac_t$with_gnu_ld" 1>&6
+
+# See if the linker supports building shared libraries.
+echo $ac_n "checking whether the linker ($LD) supports shared libraries... $ac_c" 1>&6
+
+allow_undefined_flag=
+no_undefined_flag=
+archive_cmds=
+old_archive_from_new_cmds=
+export_dynamic_flag_spec=
+hardcode_libdir_flag_spec=
+hardcode_libdir_separator=
+hardcode_direct=no
+hardcode_minus_L=no
+hardcode_shlibpath_var=unsupported
+runpath_var=
+
+case "$host_os" in
+amigaos* | sunos4*)
+ # On these operating systems, we should treat GNU ld like the system ld.
+ gnu_ld_acts_native=yes
+ ;;
+*)
+ gnu_ld_acts_native=no
+ ;;
+esac
+
+ld_shlibs=yes
+if test "$with_gnu_ld" = yes && test "$gnu_ld_acts_native" != yes; then
+
+ # See if GNU ld supports shared libraries.
+ if $LD --help 2>&1 | egrep ': supported targets:.* elf' > /dev/null; then
+ archive_cmds='$CC -shared ${wl}-soname $wl$soname -o $lib$libobjs'
+ runpath_var=LD_RUN_PATH
+ ld_shlibs=yes
+ else
+ ld_shlibs=no
+ fi
+
+ if test "$ld_shlibs" = yes; then
+ hardcode_libdir_flag_spec='${wl}--rpath ${wl}$libdir'
+ export_dynamic_flag_spec='${wl}--export-dynamic'
+ fi
+else
+ # PORTME fill in a description of your system's linker (not GNU ld)
+ case "$host_os" in
+ aix3*)
+ allow_undefined_flag=unsupported
+ archive_cmds='$NM$libobjs | $global_symbol_pipe | sed '\''s/.* //'\'' > $lib.exp;$LD -o $objdir/$soname$libobjs -bE:$lib.exp -T512 -H512 -bM:SRE;$AR cru $lib $objdir/$soname'
+ # Note: this linker hardcodes the directories in LIBPATH if there
+ # are no directories specified by -L.
+ hardcode_minus_L=yes
+ if test "$with_gcc" = yes && test -z "$link_static_flag"; then
+ # Neither direct hardcoding nor static linking is supported with a
+ # broken collect2.
+ hardcode_direct=unsupported
+ fi
+ ;;
+
+ aix4*)
+ allow_undefined_flag=unsupported
+ archive_cmds='$NM$libobjs | $global_symbol_pipe | sed '\''s/.* //'\'' > $lib.exp;$CC -o $objdir/$soname$libobjs ${wl}-bE:$lib.exp ${wl}-bM:SRE ${wl}-bnoentry;$AR cru $lib $objdir/$soname'
+ hardcode_direct=yes
+ hardcode_minus_L=yes
+ ;;
+
+ amigaos*)
+ archive_cmds='$rm $objdir/a2ixlibrary.data;$echo "#define NAME $libname" > $objdir/a2ixlibrary.data;$echo "#define LIBRARY_ID 1" >> $objdir/a2ixlibrary.data;$echo "#define VERSION $major" >> $objdir/a2ixlibrary.data;$echo "#define REVISION $revision" >> $objdir/a2ixlibrary.data;$AR cru $lib$libobjs;$RANLIB $lib;(cd $objdir && a2ixlibrary -32)'
+ hardcode_libdir_flag_spec='-L$libdir'
+ hardcode_minus_L=yes
+ ;;
+
+ # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
+ # support. Future versions do this automatically, but an explicit c++rt0.o
+ # does not break anything, and helps significantly (at the cost of a little
+ # extra space).
+ freebsd2.2*)
+ archive_cmds='$LD -Bshareable -o $lib$libobjs /usr/lib/c++rt0.o'
+ hardcode_libdir_flag_spec='-R$libdir'
+ hardcode_direct=yes
+ hardcode_minus_L=yes
+ hardcode_shlibpath_var=no
+ ;;
+
+ # Unfortunately, older versions of FreeBSD 2 do not have this feature.
+ freebsd2*)
+ archive_cmds='$LD -Bshareable -o $lib$libobjs'
+ hardcode_direct=yes
+ hardcode_minus_L=yes
+ hardcode_shlibpath_var=no
+ ;;
+
+ # FreeBSD 3, at last, uses gcc -shared to do shared libraries.
+ freebsd3*)
+ archive_cmds='$CC -shared -o $lib$libobjs'
+ hardcode_libdir_flag_spec='-R$libdir'
+ hardcode_direct=yes
+ hardcode_minus_L=yes
+ hardcode_shlibpath_var=no
+ ;;
+
+ hpux9*)
+ archive_cmds='$rm $objdir/$soname;$LD -b +s +b $install_libdir -o $objdir/$soname$libobjs;mv $objdir/$soname $lib'
+ hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+ hardcode_direct=yes
+ hardcode_minus_L=yes
+ export_dynamic_flag_spec='${wl}-E'
+ ;;
+
+ hpux10*)
+ archive_cmds='$LD -b +h $soname +s +b $install_libdir -o $lib$libobjs'
+ hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+ hardcode_direct=yes
+ hardcode_minus_L=yes
+ export_dynamic_flag_spec='${wl}-E'
+ ;;
+
+ irix5* | irix6*)
+ archive_cmds='$LD -shared -o $lib -soname $soname -set_version $verstring$libobjs'
+ hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+ ;;
+
+ netbsd*)
+ # Tested with NetBSD 1.2 ld
+ archive_cmds='$LD -Bshareable -o $lib$libobjs'
+ hardcode_libdir_flag_spec='-R$libdir'
+ hardcode_direct=yes
+ hardcode_shlibpath_var=no
+ ;;
+
+ openbsd*)
+ archive_cmds='$LD -Bshareable -o $lib$libobjs'
+ hardcode_libdir_flag_spec='-R$libdir'
+ hardcode_direct=yes
+ hardcode_shlibpath_var=no
+ ;;
+
+ os2*)
+ hardcode_libdir_flag_spec='-L$libdir'
+ hardcode_minus_L=yes
+ allow_undefined_flag=unsupported
+ archive_cmds='$echo "LIBRARY $libname INITINSTANCE" > $objdir/$libname.def;$echo "DESCRIPTION \"$libname\"" >> $objdir/$libname.def;$echo DATA >> $objdir/$libname.def;$echo " SINGLE NONSHARED" >> $objdir/$libname.def;$echo EXPORTS >> $objdir/$libname.def;emxexp$libobjs >> $objdir/$libname.def;$CC -Zdll -Zcrtdll -o $lib$libobjs $objdir/$libname.def'
+ old_archive_from_new_cmds='emximp -o $objdir/$libname.a $objdir/$libname.def'
+ ;;
+
+ osf3* | osf4*)
+ allow_undefined_flag=' -expect_unresolved \*'
+ archive_cmds='$LD -shared${allow_undefined_flag} -o $lib -soname $soname -set_version $verstring$libobjs$deplibs'
+ hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+ hardcode_libdir_separator=:
+ ;;
+
+ sco3.2v5*)
+ archive_cmds='$LD -G -o $lib$libobjs'
+ hardcode_direct=yes
+ ;;
+
+ solaris2*)
+ no_undefined_flag=' -z text'
+ archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib$libobjs'
+ hardcode_libdir_flag_spec='-R$libdir'
+ hardcode_shlibpath_var=no
+
+ # Solaris 2 before 2.5 hardcodes -L paths.
+ case "$host_os" in
+ solaris2.[0-4]*)
+ hardcode_minus_L=yes
+ ;;
+ esac
+ ;;
+
+ sunos4*)
+ if test "$with_gcc" = yes; then
+ archive_cmds='$CC -shared -o $lib$libobjs'
+ else
+ archive_cmds='$LD -assert pure-text -Bstatic -o $lib$libobjs'
+ fi
+
+ if test "$with_gnu_ld" = yes; then
+ export_dynamic_flag_spec='${wl}-export-dynamic'
+ fi
+ hardcode_libdir_flag_spec='-L$libdir'
+ hardcode_direct=yes
+ hardcode_minus_L=yes
+ hardcode_shlibpath_var=no
+ ;;
+
+ uts4*)
+ archive_cmds='$LD -G -h $soname -o $lib$libobjs'
+ hardcode_libdir_flag_spec='-L$libdir'
+ hardcode_direct=no
+ hardcode_minus_L=no
+ hardcode_shlibpath_var=no
+ ;;
+
+ *)
+ ld_shlibs=no
+ can_build_shared=no
+ ;;
+ esac
+fi
+echo "$ac_t$ld_shlibs" 1>&6
+
+if test -z "$NM"; then
+ echo $ac_n "checking for BSD-compatible nm... $ac_c" 1>&6
+ case "$NM" in
+ /* | [A-Za-z]:\\*) ;; # Let the user override the test with a path.
+ *)
+ IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS="${IFS}:"
+ for ac_dir in /usr/ucb /usr/ccs/bin $PATH /bin; do
+ test -z "$ac_dir" && ac_dir=.
+ if test -f $ac_dir/nm; then
+ # Check to see if the nm accepts a BSD-compat flag.
+ # Adding the `sed 1q' prevents false positives on HP-UX, which says:
+ # nm: unknown option "B" ignored
+ if ($ac_dir/nm -B /dev/null 2>&1 | sed '1q'; exit 0) | egrep /dev/null >/dev/null; then
+ NM="$ac_dir/nm -B"
+ elif ($ac_dir/nm -p /dev/null 2>&1 | sed '1q'; exit 0) | egrep /dev/null >/dev/null; then
+ NM="$ac_dir/nm -p"
+ else
+ NM="$ac_dir/nm"
+ fi
+ break
+ fi
+ done
+ IFS="$ac_save_ifs"
+ test -z "$NM" && NM=nm
+ ;;
+ esac
+ echo "$ac_t$NM" 1>&6
+fi
+
+# Check for command to grab the raw symbol name followed by C symbol from nm.
+echo $ac_n "checking command to parse $NM output... $ac_c" 1>&6
+
+# These are sane defaults that work on at least a few old systems.
+# [They come from Ultrix. What could be older than Ultrix?!! ;)]
+
+# Character class describing NM global symbol codes.
+symcode='[BCDEGRSTU]'
+
+# Regexp to match symbols that can be accessed directly from C.
+sympat='\([_A-Za-z][_A-Za-z0-9]*\)'
+
+# Transform the above into a raw symbol and a C symbol.
+symxfrm='\1 \1'
+
+# Define system-specific variables.
+case "$host_os" in
+aix*)
+ symcode='[BCDTU]'
+ ;;
+irix*)
+ # Cannot use undefined symbols on IRIX because inlined functions mess us up.
+ symcode='[BCDEGRST]'
+ ;;
+solaris2*)
+ symcode='[BDTU]'
+ ;;
+esac
+
+# If we're using GNU nm, then use its standard symbol codes.
+if $NM -V 2>&1 | egrep '(GNU|with BFD)' > /dev/null; then
+ symcode='[ABCDGISTUW]'
+fi
+
+# Write the raw and C identifiers.
+global_symbol_pipe="sed -n -e 's/^.* $symcode $sympat$/$symxfrm/p'"
+
+# Check to see that the pipe works correctly.
+pipe_works=no
+$rm conftest*
+cat > conftest.c <<EOF
+#ifdef __cplusplus
+extern "C" {
+#endif
+char nm_test_var;
+void nm_test_func(){}
+#ifdef __cplusplus
+}
+#endif
+main(){nm_test_var='a';nm_test_func();return(0);}
+EOF
+
+echo "$progname:971: checking if global_symbol_pipe works" >&5
+if { (eval echo $progname:972: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; } && test -s conftest.o; then
+ # Now try to grab the symbols.
+ nlist=conftest.nm
+ if { echo "$progname:975: eval \"$NM conftest.o | $global_symbol_pipe > $nlist\"" >&5; eval "$NM conftest.o | $global_symbol_pipe > $nlist 2>&5"; } && test -s "$nlist"; then
+
+ # Try sorting and uniquifying the output.
+ if sort "$nlist" | uniq > "$nlist"T; then
+ mv -f "$nlist"T "$nlist"
+ wcout=`wc "$nlist" 2>/dev/null`
+ count=`$echo "X$wcout" | $Xsed -e 's/^[ ]*\([0-9][0-9]*\).*$/\1/'`
+ (test "$count" -ge 0) 2>/dev/null || count=-1
+ else
+ rm -f "$nlist"T
+ count=-1
+ fi
+
+ # Make sure that we snagged all the symbols we need.
+ if egrep ' nm_test_var$' "$nlist" >/dev/null; then
+ if egrep ' nm_test_func$' "$nlist" >/dev/null; then
+ cat <<EOF > conftest.c
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+EOF
+ # Now generate the symbol file.
+ sed 's/^.* \(.*\)$/extern char \1;/' < "$nlist" >> conftest.c
+
+ cat <<EOF >> conftest.c
+#if defined (__STDC__) && __STDC__
+# define __ptr_t void *
+#else
+# define __ptr_t char *
+#endif
+
+/* The number of symbols in dld_preloaded_symbols, -1 if unsorted. */
+int dld_preloaded_symbol_count = $count;
+
+/* The mapping between symbol names and symbols. */
+struct {
+ char *name;
+ __ptr_t address;
+}
+dld_preloaded_symbols[] =
+{
+EOF
+ sed 's/^\(.*\) \(.*\)$/ {"\1", (__ptr_t) \&\2},/' < "$nlist" >> conftest.c
+ cat <<\EOF >> conftest.c
+ {0, (__ptr_t) 0}
+};
+
+#ifdef __cplusplus
+}
+#endif
+EOF
+ # Now try linking the two files.
+ mv conftest.o conftestm.o
+ save_LIBS="$LIBS"
+ save_CFLAGS="$CFLAGS"
+ LIBS='conftestm.o'
+ CFLAGS="$CFLAGS$no_builtin_flag"
+ if { (eval echo $progname:1033: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest; then
+ pipe_works=yes
+ else
+ echo "$progname: failed program was:" >&5
+ cat conftest.c >&5
+ fi
+ LIBS="$save_LIBS"
+ else
+ echo "cannot find nm_test_func in $nlist" >&5
+ fi
+ else
+ echo "cannot find nm_test_var in $nlist" >&5
+ fi
+ else
+ echo "cannot run $global_symbol_pipe" >&5
+ fi
+else
+ echo "$progname: failed program was:" >&5
+ cat conftest.c >&5
+fi
+$rm conftest*
+
+# Do not use the global_symbol_pipe unless it works.
+echo "$ac_t$pipe_works" 1>&6
+test "$pipe_works" = yes || global_symbol_pipe=
+
+# Check hardcoding attributes.
+echo $ac_n "checking how to hardcode library paths into programs... $ac_c" 1>&6
+hardcode_action=
+if test -n "$hardcode_libdir_flag_spec" || \
+ test -n "$runpath_var"; then
+
+ # We can hardcode non-existant directories.
+ if test "$hardcode_direct" != no && \
+ test "$hardcode_minus_L" != no && \
+ test "$hardcode_shlibpath_var" != no; then
+
+ # Linking always hardcodes the temporary library directory.
+ hardcode_action=relink
+ else
+ # We can link without hardcoding, and we can hardcode nonexisting dirs.
+ hardcode_action=immediate
+ fi
+elif test "$hardcode_direct" != yes && \
+ test "$hardcode_minus_L" != yes && \
+ test "$hardcode_shlibpath_var" != yes; then
+ # We cannot hardcode anything.
+ hardcode_action=unsupported
+else
+ # We can only hardcode existing directories.
+ hardcode_action=relink
+fi
+echo "$ac_t$hardcode_action" 1>&6
+test "$hardcode_action" = unsupported && can_build_shared=no
+
+
+reload_flag=
+reload_cmds='$LD$reload_flag -o $output$reload_objs'
+echo $ac_n "checking for $LD option to reload object files... $ac_c" 1>&6
+# PORTME Some linker may need a different reload flag.
+reload_flag='-r'
+echo "$ac_t$reload_flag"
+test -n "$reload_flag" && reload_flag=" $reload_flag"
+
+# PORTME Fill in your ld.so characteristics
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+version_type=none
+dynamic_linker="$host_os ld.so"
+
+echo $ac_n "checking dynamic linker characteristics... $ac_c" 1>&6
+case "$host_os" in
+aix3* | aix4*)
+ version_type=linux
+ library_names_spec='${libname}${release}.so.$versuffix $libname.a'
+ shlibpath_var=LIBPATH
+
+ # AIX has no versioning support, so we append a major version to the name.
+ soname_spec='${libname}${release}.so.$major'
+ ;;
+
+amigaos*)
+ library_names_spec='$libname.ixlibrary $libname.a'
+ # Create ${libname}_ixlibrary.a entries in /sys/libs.
+ finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "(cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a)"; (cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a) || exit 1; done'
+ ;;
+
+freebsd2* | freebsd3*)
+ version_type=sunos
+ library_names_spec='${libname}${release}.so.$versuffix $libname.so'
+ finish_cmds='PATH="$PATH:/sbin" ldconfig -m $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+gnu*)
+ version_type=sunos
+ library_names_spec='${libname}${release}.so.$versuffix'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+hpux9* | hpux10*)
+ # Give a soname corresponding to the major version so that dld.sl refuses to
+ # link against other versions.
+ dynamic_linker="$host_os dld.sl"
+ version_type=sunos
+ shlibpath_var=SHLIB_PATH
+ library_names_spec='${libname}${release}.sl.$versuffix ${libname}${release}.sl.$major $libname.sl'
+ soname_spec='${libname}${release}.sl.$major'
+ # HP-UX runs *really* slowly unless shared libraries are mode 555.
+ postinstall_cmds='chmod 555 $lib'
+ ;;
+
+irix5* | irix6*)
+ version_type=osf
+ soname_spec='${libname}${release}.so'
+ library_names_spec='${libname}${release}.so.$versuffix $libname.so'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux-gnuoldld* | linux-gnuaout* | linux-gnucoff*)
+ dynamic_linker=no
+ ;;
+
+# This must be Linux ELF.
+linux-gnu*)
+ version_type=linux
+ library_names_spec='${libname}${release}.so.$versuffix ${libname}${release}.so.$major $libname.so'
+ soname_spec='${libname}${release}.so.$major'
+ finish_cmds='PATH="$PATH:/sbin" ldconfig -n $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+
+ if test -f /lib/ld.so.1; then
+ dynamic_linker='GNU ld.so'
+ else
+ # Only the GNU ld.so supports shared libraries on MkLinux.
+ case "$host_cpu" in
+ powerpc*) dynamic_linker=no ;;
+ *) dynamic_linker='Linux ld.so' ;;
+ esac
+ fi
+ ;;
+
+netbsd* | openbsd*)
+ version_type=sunos
+ library_names_spec='${libname}${release}.so.$versuffix'
+ finish_cmds='PATH="$PATH:/sbin" ldconfig -m $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+os2*)
+ libname_spec='$name'
+ library_names_spec='$libname.dll $libname.a'
+ dynamic_linker='OS/2 ld.exe'
+ shlibpath_var=LIBPATH
+ ;;
+
+osf3* | osf4*)
+ version_type=osf
+ soname_spec='${libname}${release}.so'
+ library_names_spec='${libname}${release}.so.$versuffix $libname.so'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+sco3.2v5*)
+ version_type=osf
+ soname_spec='${libname}${release}.so.$major'
+ library_names_spec='${libname}${release}.so.$versuffix ${libname}${release}.so.$major $libname.so'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+solaris2*)
+ version_type=linux
+ library_names_spec='${libname}${release}.so.$versuffix ${libname}${release}.so.$major $libname.so'
+ soname_spec='${libname}${release}.so.$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+sunos4*)
+ version_type=sunos
+ library_names_spec='${libname}${release}.so.$versuffix'
+ finish_cmds='PATH="$PATH:/usr/etc" ldconfig $libdir'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+sysv4.2uw2*)
+ version_type=linux
+ library_names_spec='${libname}${release}.so.$versuffix ${libname}${release}.so.$major $libname.so'
+ soname_spec='${libname}${release}.so.$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+uts4*)
+ version_type=linux
+ library_names_spec='${libname}${release}.so.$versuffix ${libname}${release}.so.$major $libname.so'
+ soname_spec='${libname}${release}.so.$major'
+ shlibpath_var=LD_LIBRARY_PATH
+ ;;
+
+*)
+ dynamic_linker=no
+ ;;
+esac
+echo "$ac_t$dynamic_linker"
+test "$dynamic_linker" = no && can_build_shared=no
+
+# Report the final consequences.
+echo "checking if libtool supports shared libraries... $can_build_shared" 1>&6
+
+echo $ac_n "checking whether to build shared libraries... $ac_c" 1>&6
+test "$can_build_shared" = "no" && enable_shared=no
+
+# On AIX, shared libraries and static libraries use the same namespace, and
+# are all built from PIC.
+case "$host_os" in
+aix*)
+ test "$enable_shared" = yes && enable_static=no
+ if test -n "$RANLIB"; then
+ archive_cmds="$archive_cmds;\$RANLIB \$lib"
+ postinstall_cmds='$RANLIB $lib'
+ fi
+ ;;
+esac
+
+echo "$ac_t$enable_shared" 1>&6
+
+# Make sure either enable_shared or enable_static is yes.
+test "$enable_shared" = yes || enable_static=yes
+
+echo "checking whether to build static libraries... $enable_static" 1>&6
+
+echo $ac_n "checking for objdir... $ac_c" 1>&6
+rm -f .libs 2>/dev/null
+mkdir .libs 2>/dev/null
+if test -d .libs; then
+ objdir=.libs
+else
+ # MS-DOS does not allow filenames that begin with a dot.
+ objdir=_libs
+fi
+rmdir .libs 2>/dev/null
+echo "$ac_t$objdir" 1>&6
+
+# Copy echo and quote the copy, instead of the original, because it is
+# used later.
+ltecho="$echo"
+
+# Now quote all the things that may contain metacharacters.
+for var in ltecho old_CC old_CFLAGS old_CPPFLAGS old_LD old_NM old_RANLIB \
+ old_LN_S AR CC LD LN_S NM reload_flag reload_cmds wl pic_flag \
+ link_static_flag no_builtin_flag export_dynamic_flag_spec \
+ libname_spec library_names_spec soname_spec RANLIB \
+ old_archive_cmds old_archive_from_new_cmds old_postinstall_cmds \
+ old_postuninstall_cmds archive_cmds postinstall_cmds postuninstall_cmds \
+ allow_undefined_flag no_undefined_flag \
+ finish_cmds finish_eval global_symbol_pipe \
+ hardcode_libdir_flag_spec hardcode_libdir_separator; do
+
+ case "$var" in
+ reload_cmds | old_archive_cmds | old_archive_from_new_cmds | \
+ old_postinstall_cmds | old_postuninstall_cmds | archive_cmds | \
+ postinstall_cmds | postuninstall_cmds | finish_cmds)
+ # Double-quote double-evaled strings.
+ eval "$var=\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\"\`"
+ ;;
+ *)
+ eval "$var=\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`"
+ ;;
+ esac
+done
+
+ofile=libtool
+trap "$rm $ofile; exit 1" 1 2 15
+echo creating $ofile
+$rm $ofile
+cat <<EOF > $ofile
+#! /bin/sh
+
+# libtool - Provide generalized library-building support services.
+# Generated automatically by $PROGRAM - GNU $PACKAGE $VERSION
+# NOTE: Changes made to this file will be lost: look at ltconfig or ltmain.sh.
+#
+# Copyright (C) 1996-1998 Free Software Foundation, Inc.
+# Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
+#
+# 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 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, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# This program was configured as follows,
+# on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+#
+# CC="$old_CC" CFLAGS="$old_CFLAGS" CPPFLAGS="$old_CPPFLAGS" \\
+# LD="$old_LD" NM="$old_NM" RANLIB="$old_RANLIB" LN_S="$old_LN_S" \\
+# $0$ltconfig_args
+#
+# Compiler and other test output produced by $progname, useful for
+# debugging $progname, is in ./config.log if it exists.
+
+# Sed that helps us avoid accidentally triggering echo(1) options like -n.
+Xsed="sed -e s/^X//"
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+if test "\${CDPATH+set}" = set; then CDPATH=; export CDPATH; fi
+
+# An echo program that does not interpret backslashes.
+echo="$ltecho"
+
+# The version of $progname that generated this script.
+LTCONFIG_VERSION="$VERSION"
+
+# Shell to use when invoking shell scripts.
+SHELL=${CONFIG_SHELL-/bin/sh}
+
+# Whether or not to build libtool libraries.
+build_libtool_libs=$enable_shared
+
+# Whether or not to build old-style libraries.
+build_old_libs=$enable_static
+
+# The host system.
+host_alias="$host_alias"
+host="$host"
+
+# The archiver.
+AR="$AR"
+
+# The default C compiler.
+CC="$CC"
+
+# The linker used to build libraries.
+LD="$LD"
+
+# Whether we need hard or soft links.
+LN_S="$LN_S"
+
+# A BSD-compatible nm program.
+NM="$NM"
+
+# The name of the directory that contains temporary libtool files.
+objdir="$objdir"
+
+# How to create reloadable object files.
+reload_flag="$reload_flag"
+reload_cmds="$reload_cmds"
+
+# How to pass a linker flag through the compiler.
+wl="$wl"
+
+# Additional compiler flags for building library objects.
+pic_flag="$pic_flag"
+
+# Compiler flag to prevent dynamic linking.
+link_static_flag="$link_static_flag"
+
+# Compiler flag to turn off builtin functions.
+no_builtin_flag="$no_builtin_flag"
+
+# Compiler flag to allow reflexive dlopens.
+export_dynamic_flag_spec="$export_dynamic_flag_spec"
+
+# Library versioning type.
+version_type=$version_type
+
+# Format of library name prefix.
+libname_spec="$libname_spec"
+
+# List of archive names. First name is the real one, the rest are links.
+# The last name is the one that the linker finds with -lNAME.
+library_names_spec="$library_names_spec"
+
+# The coded name of the library, if different from the real name.
+soname_spec="$soname_spec"
+
+# Commands used to build and install an old-style archive.
+RANLIB="$RANLIB"
+old_archive_cmds="$old_archive_cmds"
+old_postinstall_cmds="$old_postinstall_cmds"
+old_postuninstall_cmds="$old_postuninstall_cmds"
+
+# Create an old-style archive from a shared archive.
+old_archive_from_new_cmds="$old_archive_from_new_cmds"
+
+# Commands used to build and install a shared archive.
+archive_cmds="$archive_cmds"
+postinstall_cmds="$postinstall_cmds"
+postuninstall_cmds="$postuninstall_cmds"
+
+# Flag that allows shared libraries with undefined symbols to be built.
+allow_undefined_flag="$allow_undefined_flag"
+
+# Flag that forces no undefined symbols.
+no_undefined_flag="$no_undefined_flag"
+
+# Commands used to finish a libtool library installation in a directory.
+finish_cmds="$finish_cmds"
+
+# Same as above, but a single script fragment to be evaled but not shown.
+finish_eval="$finish_eval"
+
+# Take the output of nm and produce a listing of raw symbols and C names.
+global_symbol_pipe="$global_symbol_pipe"
+
+# This is the shared library runtime path variable.
+runpath_var=$runpath_var
+
+# This is the shared library path variable.
+shlibpath_var=$shlibpath_var
+
+# How to hardcode a shared library path into an executable.
+hardcode_action=$hardcode_action
+
+# Flag to hardcode \$libdir into a binary during linking.
+# This must work even if \$libdir does not exist.
+hardcode_libdir_flag_spec="$hardcode_libdir_flag_spec"
+
+# Whether we need a single -rpath flag with a separated argument.
+hardcode_libdir_separator="$hardcode_libdir_separator"
+
+# Set to yes if using DIR/libNAME.so during linking hardcodes DIR into the
+# resulting binary.
+hardcode_direct=$hardcode_direct
+
+# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
+# resulting binary.
+hardcode_minus_L=$hardcode_minus_L
+
+# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into
+# the resulting binary.
+hardcode_shlibpath_var=$hardcode_shlibpath_var
+
+EOF
+
+case "$host_os" in
+aix3*)
+ cat <<\EOF >> $ofile
+# AIX sometimes has problems with the GCC collect2 program. For some
+# reason, if we set the COLLECT_NAMES environment variable, the problems
+# vanish in a puff of smoke.
+if test "${COLLECT_NAMES+set}" != set; then
+ COLLECT_NAMES=
+ export COLLECT_NAMES
+fi
+
+EOF
+ ;;
+esac
+
+# Append the ltmain.sh script.
+cat "$ltmain" >> $ofile || (rm -f $ofile; exit 1)
+
+chmod +x $ofile
+exit 0
+
+# Local Variables:
+# mode:shell-script
+# sh-indentation:2
+# End:
diff --git a/jpeg-6c/ltmain.sh b/jpeg-6c/ltmain.sh
new file mode 100644
index 0000000..e9350b3
--- /dev/null
+++ b/jpeg-6c/ltmain.sh
@@ -0,0 +1,2453 @@
+# ltmain.sh - Provide generalized library-building support services.
+# NOTE: Changing this file will not affect anything until you rerun ltconfig.
+#
+# Copyright (C) 1996-1998 Free Software Foundation, Inc.
+# Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
+#
+# 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 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, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# The name of this program.
+progname=`$echo "$0" | sed 's%^.*/%%'`
+modename="$progname"
+
+# Constants.
+PROGRAM=ltmain.sh
+PACKAGE=libtool
+VERSION=1.2
+
+default_mode=
+help="Try \`$progname --help' for more information."
+magic="%%%MAGIC variable%%%"
+mkdir="mkdir"
+mv="mv -f"
+rm="rm -f"
+
+# Sed substitution that helps us do robust quoting. It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed='sed -e s/^X//'
+sed_quote_subst='s/\([\\`\\"$\\\\]\)/\\\1/g'
+
+# NLS nuisances.
+# Only set LANG and LC_ALL to C if already set.
+# These must not be set unconditionally because not all systems understand
+# e.g. LANG=C (notably SCO).
+if test "${LC_ALL+set}" = set; then LC_ALL=C; export LC_ALL; fi
+if test "${LANG+set}" = set; then LANG=C; export LANG; fi
+
+if test "$LTCONFIG_VERSION" != "$VERSION"; then
+ echo "$modename: ltconfig version \`$LTCONFIG_VERSION' does not match $PROGRAM version \`$VERSION'" 1>&2
+ echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2
+ exit 1
+fi
+
+if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
+ echo "$modename: not configured to build any kind of library" 1>&2
+ echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2
+ exit 1
+fi
+
+# Global variables.
+mode=$default_mode
+nonopt=
+prev=
+prevopt=
+run=
+show="$echo"
+show_help=
+execute_dlfiles=
+
+# Parse our command line options once, thoroughly.
+while test $# -gt 0
+do
+ arg="$1"
+ shift
+
+ case "$arg" in
+ -*=*) optarg=`$echo "X$arg" | $Xsed -e 's/[-_a-zA-Z0-9]*=//'` ;;
+ *) optarg= ;;
+ esac
+
+ # If the previous option needs an argument, assign it.
+ if test -n "$prev"; then
+ case "$prev" in
+ execute_dlfiles)
+ eval "$prev=\"\$$prev \$arg\""
+ ;;
+ *)
+ eval "$prev=\$arg"
+ ;;
+ esac
+
+ prev=
+ prevopt=
+ continue
+ fi
+
+ # Have we seen a non-optional argument yet?
+ case "$arg" in
+ --help)
+ show_help=yes
+ ;;
+
+ --version)
+ echo "$PROGRAM (GNU $PACKAGE) $VERSION"
+ exit 0
+ ;;
+
+ --dry-run | -n)
+ run=:
+ ;;
+
+ --features)
+ echo "host: $host"
+ if test "$build_libtool_libs" = yes; then
+ echo "enable shared libraries"
+ else
+ echo "disable shared libraries"
+ fi
+ if test "$build_old_libs" = yes; then
+ echo "enable static libraries"
+ else
+ echo "disable static libraries"
+ fi
+ exit 0
+ ;;
+
+ --finish) mode="finish" ;;
+
+ --mode) prevopt="--mode" prev=mode ;;
+ --mode=*) mode="$optarg" ;;
+
+ --quiet | --silent)
+ show=:
+ ;;
+
+ -dlopen)
+ prevopt="-dlopen"
+ prev=execute_dlfiles
+ ;;
+
+ -*)
+ $echo "$modename: unrecognized option \`$arg'" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ ;;
+
+ *)
+ nonopt="$arg"
+ break
+ ;;
+ esac
+done
+
+if test -n "$prevopt"; then
+ $echo "$modename: option \`$prevopt' requires an argument" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+fi
+
+if test -z "$show_help"; then
+
+ # Infer the operation mode.
+ if test -z "$mode"; then
+ case "$nonopt" in
+ *cc | *++ | gcc* | *-gcc*)
+ mode=link
+ for arg
+ do
+ case "$arg" in
+ -c)
+ mode=compile
+ break
+ ;;
+ esac
+ done
+ ;;
+ *db | *dbx)
+ mode=execute
+ ;;
+ *install*|cp|mv)
+ mode=install
+ ;;
+ *rm)
+ mode=uninstall
+ ;;
+ *)
+ # If we have no mode, but dlfiles were specified, then do execute mode.
+ test -n "$execute_dlfiles" && mode=execute
+
+ # Just use the default operation mode.
+ if test -z "$mode"; then
+ if test -n "$nonopt"; then
+ $echo "$modename: warning: cannot infer operation mode from \`$nonopt'" 1>&2
+ else
+ $echo "$modename: warning: cannot infer operation mode without MODE-ARGS" 1>&2
+ fi
+ fi
+ ;;
+ esac
+ fi
+
+ # Only execute mode is allowed to have -dlopen flags.
+ if test -n "$execute_dlfiles" && test "$mode" != execute; then
+ $echo "$modename: unrecognized option \`-dlopen'" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ fi
+
+ # Change the help message to a mode-specific one.
+ generic_help="$help"
+ help="Try \`$modename --help --mode=$mode' for more information."
+
+ # These modes are in order of execution frequency so that they run quickly.
+ case "$mode" in
+ # libtool compile mode
+ compile)
+ modename="$modename: compile"
+ # Get the compilation command and the source file.
+ base_compile=
+ lastarg=
+ srcfile="$nonopt"
+ suppress_output=
+
+ for arg
+ do
+ # Accept any command-line options.
+ case "$arg" in
+ -o)
+ $echo "$modename: you cannot specify the output filename with \`-o'" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ ;;
+
+ -static)
+ build_libtool_libs=no
+ build_old_libs=yes
+ continue
+ ;;
+ esac
+
+ # Accept the current argument as the source file.
+ lastarg="$srcfile"
+ srcfile="$arg"
+
+ # Aesthetically quote the previous argument.
+
+ # Backslashify any backslashes, double quotes, and dollar signs.
+ # These are the only characters that are still specially
+ # interpreted inside of double-quoted scrings.
+ lastarg=`$echo "X$lastarg" | $Xsed -e "$sed_quote_subst"`
+
+ # Double-quote args containing other shell metacharacters.
+ # Many Bourne shells cannot handle close brackets correctly in scan
+ # sets, so we specify it separately.
+ case "$lastarg" in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*)
+ lastarg="\"$lastarg\""
+ ;;
+ esac
+
+ # Add the previous argument to base_compile.
+ if test -z "$base_compile"; then
+ base_compile="$lastarg"
+ else
+ base_compile="$base_compile $lastarg"
+ fi
+ done
+
+ # Get the name of the library object.
+ libobj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%'`
+
+ # Recognize several different file suffixes.
+ xform='[cCFSfms]'
+ case "$libobj" in
+ *.ada) xform=ada ;;
+ *.adb) xform=adb ;;
+ *.ads) xform=ads ;;
+ *.asm) xform=asm ;;
+ *.c++) xform=c++ ;;
+ *.cc) xform=cc ;;
+ *.cpp) xform=cpp ;;
+ *.cxx) xform=cxx ;;
+ *.f90) xform=f90 ;;
+ *.for) xform=for ;;
+ esac
+
+ libobj=`$echo "X$libobj" | $Xsed -e "s/\.$xform$/.lo/"`
+
+ case "$libobj" in
+ *.lo) obj=`$echo "X$libobj" | $Xsed -e 's/\.lo$/.o/'` ;;
+ *)
+ $echo "$modename: cannot determine name of library object from \`$srcfile'" 1>&2
+ exit 1
+ ;;
+ esac
+
+ if test -z "$base_compile"; then
+ $echo "$modename: you must specify a compilation command" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ fi
+
+ # Delete any leftover library objects.
+ if test "$build_old_libs" = yes; then
+ $run $rm $obj $libobj
+ trap "$run $rm $obj $libobj; exit 1" 1 2 15
+ else
+ $run $rm $libobj
+ trap "$run $rm $libobj; exit 1" 1 2 15
+ fi
+
+ # Only build a PIC object if we are building libtool libraries.
+ if test "$build_libtool_libs" = yes; then
+ # Without this assignment, base_compile gets emptied.
+ fbsd_hideous_sh_bug=$base_compile
+
+ # All platforms use -DPIC, to notify preprocessed assembler code.
+ $show "$base_compile$pic_flag -DPIC $srcfile"
+ if $run eval "$base_compile\$pic_flag -DPIC \$srcfile"; then :
+ else
+ test -n "$obj" && $run $rm $obj
+ exit 1
+ fi
+
+ # If we have no pic_flag, then copy the object into place and finish.
+ if test -z "$pic_flag"; then
+ $show "$LN_S $obj $libobj"
+ $run $LN_S $obj $libobj
+ exit $?
+ fi
+
+ # Just move the object, then go on to compile the next one
+ $show "$mv $obj $libobj"
+ $run $mv $obj $libobj || exit 1
+
+ # Allow error messages only from the first compilation.
+ suppress_output=' >/dev/null 2>&1'
+ fi
+
+ # Only build a position-dependent object if we build old libraries.
+ if test "$build_old_libs" = yes; then
+ # Suppress compiler output if we already did a PIC compilation.
+ $show "$base_compile $srcfile$suppress_output"
+ if $run eval "$base_compile \$srcfile$suppress_output"; then :
+ else
+ $run $rm $obj $libobj
+ exit 1
+ fi
+ fi
+
+ # Create an invalid libtool object if no PIC, so that we do not
+ # accidentally link it into a program.
+ if test "$build_libtool_libs" != yes; then
+ $show "echo timestamp > $libobj"
+ $run eval "echo timestamp > \$libobj" || exit $?
+ fi
+
+ exit 0
+ ;;
+
+ # libtool link mode
+ link)
+ modename="$modename: link"
+ CC="$nonopt"
+ allow_undefined=yes
+ compile_command="$CC"
+ finalize_command="$CC"
+
+ compile_shlibpath=
+ finalize_shlibpath=
+ deplibs=
+ dlfiles=
+ dlprefiles=
+ export_dynamic=no
+ hardcode_libdirs=
+ libobjs=
+ link_against_libtool_libs=
+ ltlibs=
+ objs=
+ prev=
+ prevarg=
+ release=
+ rpath=
+ perm_rpath=
+ temp_rpath=
+ vinfo=
+
+ # We need to know -static, to get the right output filenames.
+ for arg
+ do
+ case "$arg" in
+ -all-static | -static)
+ if test "X$arg" = "X-all-static" && test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then
+ $echo "$modename: warning: complete static linking is impossible in this configuration" 1>&2
+ fi
+ build_libtool_libs=no
+ build_old_libs=yes
+ break
+ ;;
+ esac
+ done
+
+ # See if our shared archives depend on static archives.
+ test -n "$old_archive_from_new_cmds" && build_old_libs=yes
+
+ # Go through the arguments, transforming them on the way.
+ for arg
+ do
+ # If the previous option needs an argument, assign it.
+ if test -n "$prev"; then
+ case "$prev" in
+ output)
+ compile_command="$compile_command @OUTPUT@"
+ finalize_command="$finalize_command @OUTPUT@"
+ ;;
+ esac
+
+ case "$prev" in
+ dlfiles|dlprefiles)
+ case "$arg" in
+ *.la | *.lo) ;; # We handle these cases below.
+ *)
+ dlprefiles="$dlprefiles $arg"
+ test "$prev" = dlfiles && dlfiles="$dlfiles $arg"
+ prev=
+ ;;
+ esac
+ ;;
+ release)
+ release="-$arg"
+ prev=
+ continue
+ ;;
+ rpath)
+ rpath="$rpath $arg"
+ prev=
+ continue
+ ;;
+ *)
+ eval "$prev=\"\$arg\""
+ prev=
+ continue
+ ;;
+ esac
+ fi
+
+ prevarg="$arg"
+
+ case "$arg" in
+ -all-static)
+ if test -n "$link_static_flag"; then
+ compile_command="$compile_command $link_static_flag"
+ finalize_command="$finalize_command $link_static_flag"
+ fi
+ continue
+ ;;
+
+ -allow-undefined)
+ # FIXME: remove this flag sometime in the future.
+ $echo "$modename: \`-allow-undefined' is deprecated because it is the default" 1>&2
+ continue
+ ;;
+
+ -dlopen)
+ prev=dlfiles
+ continue
+ ;;
+
+ -dlpreopen)
+ prev=dlprefiles
+ continue
+ ;;
+
+ -export-dynamic)
+ if test "$export_dynamic" != yes; then
+ export_dynamic=yes
+ if test -n "$export_dynamic_flag_spec"; then
+ eval arg=\"$export_dynamic_flag_spec\"
+ else
+ arg=
+ fi
+
+ # Add the symbol object into the linking commands.
+ compile_command="$compile_command @SYMFILE@"
+ finalize_command="$finalize_command @SYMFILE@"
+ fi
+ ;;
+
+ -L*)
+ dir=`$echo "X$arg" | $Xsed -e 's%^-L\(.*\)$%\1%'`
+ case "$dir" in
+ /* | [A-Za-z]:\\*)
+ # Add the corresponding hardcode_libdir_flag, if it is not identical.
+ ;;
+ *)
+ $echo "$modename: \`-L$dir' cannot specify a relative directory" 1>&2
+ exit 1
+ ;;
+ esac
+ deplibs="$deplibs $arg"
+ ;;
+
+ -l*) deplibs="$deplibs $arg" ;;
+
+ -no-undefined)
+ allow_undefined=no
+ continue
+ ;;
+
+ -o) prev=output ;;
+
+ -release)
+ prev=release
+ continue
+ ;;
+
+ -rpath)
+ prev=rpath
+ continue
+ ;;
+
+ -static)
+ # If we have no pic_flag, then this is the same as -all-static.
+ if test -z "$pic_flag" && test -n "$link_static_flag"; then
+ compile_command="$compile_command $link_static_flag"
+ finalize_command="$finalize_command $link_static_flag"
+ fi
+ continue
+ ;;
+
+ -version-info)
+ prev=vinfo
+ continue
+ ;;
+
+ # Some other compiler flag.
+ -* | +*)
+ # Unknown arguments in both finalize_command and compile_command need
+ # to be aesthetically quoted because they are evaled later.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case "$arg" in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*)
+ arg="\"$arg\""
+ ;;
+ esac
+ ;;
+
+ *.o | *.a)
+ # A standard object.
+ objs="$objs $arg"
+ ;;
+
+ *.lo)
+ # A library object.
+ if test "$prev" = dlfiles; then
+ dlfiles="$dlfiles $arg"
+ if test "$build_libtool_libs" = yes; then
+ prev=
+ continue
+ else
+ # If libtool objects are unsupported, then we need to preload.
+ prev=dlprefiles
+ fi
+ fi
+
+ if test "$prev" = dlprefiles; then
+ # Preload the old-style object.
+ dlprefiles="$dlprefiles "`$echo "X$arg" | $Xsed -e 's/\.lo$/\.o/'`
+ prev=
+ fi
+ libobjs="$libobjs $arg"
+ ;;
+
+ *.la)
+ # A libtool-controlled library.
+
+ dlname=
+ libdir=
+ library_names=
+ old_library=
+
+ # Check to see that this really is a libtool archive.
+ if (sed -e '2q' $arg | egrep '^# Generated by ltmain\.sh') >/dev/null 2>&1; then :
+ else
+ $echo "$modename: \`$arg' is not a valid libtool archive" 1>&2
+ exit 1
+ fi
+
+ # If there is no directory component, then add one.
+ case "$arg" in
+ */* | *\\*) . $arg ;;
+ *) . ./$arg ;;
+ esac
+
+ if test -z "$libdir"; then
+ $echo "$modename: \`$arg' contains no -rpath information" 1>&2
+ exit 1
+ fi
+
+ # Get the name of the library we link against.
+ linklib=
+ for l in $old_library $library_names; do
+ linklib="$l"
+ done
+
+ if test -z "$linklib"; then
+ $echo "$modename: cannot find name of link library for \`$arg'" 1>&2
+ exit 1
+ fi
+
+ # Find the relevant object directory and library name.
+ name=`$echo "X$arg" | $Xsed -e 's%^.*/%%' -e 's/\.la$//' -e 's/^lib//'`
+ dir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
+ if test "X$dir" = "X$arg"; then
+ dir="$objdir"
+ else
+ dir="$dir/$objdir"
+ fi
+
+ # This library was specified with -dlopen.
+ if test "$prev" = dlfiles; then
+ dlfiles="$dlfiles $arg"
+ if test -z "$dlname"; then
+ # If there is no dlname, we need to preload.
+ prev=dlprefiles
+ else
+ # We should not create a dependency on this library, but we
+ # may need any libraries it requires.
+ compile_command="$compile_command$dependency_libs"
+ finalize_command="$finalize_command$dependency_libs"
+ prev=
+ continue
+ fi
+ fi
+
+ # The library was specified with -dlpreopen.
+ if test "$prev" = dlprefiles; then
+ # Prefer using a static library (so that no silly _DYNAMIC symbols
+ # are required to link).
+ if test -n "$old_library"; then
+ dlprefiles="$dlprefiles $dir/$old_library"
+ else
+ dlprefiles="$dlprefiles $dir/$linklib"
+ fi
+ prev=
+ fi
+
+ if test "$build_libtool_libs" = yes && test -n "$library_names"; then
+ link_against_libtool_libs="$link_against_libtool_libs $arg"
+ if test -n "$shlibpath_var"; then
+ # Make sure the rpath contains only unique directories.
+ case "$temp_rpath " in
+ *" $dir "*) ;;
+ *) temp_rpath="$temp_rpath $dir" ;;
+ esac
+ fi
+
+ # This is the magic to use -rpath.
+ if test -n "$hardcode_libdir_flag_spec"; then
+ if test -n "$hardcode_libdir_separator"; then
+ if test -z "$hardcode_libdirs"; then
+ # Put the magic libdir with the hardcode flag.
+ hardcode_libdirs="$libdir"
+ libdir="@HARDCODE_LIBDIRS@"
+ else
+ # Just accumulate the unique libdirs.
+ case "$hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator" in
+ *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+ ;;
+ *)
+ hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+ ;;
+ esac
+ libdir=
+ fi
+ fi
+
+ if test -n "$libdir"; then
+ eval flag=\"$hardcode_libdir_flag_spec\"
+
+ compile_command="$compile_command $flag"
+ finalize_command="$finalize_command $flag"
+ fi
+ elif test -n "$runpath_var"; then
+ # Do the same for the permanent run path.
+ case "$perm_rpath " in
+ *" $libdir "*) ;;
+ *) perm_rpath="$perm_rpath $libdir" ;;
+ esac
+ fi
+
+
+ case "$hardcode_action" in
+ immediate)
+ if test "$hardcode_direct" = no; then
+ compile_command="$compile_command $dir/$linklib"
+ elif test "$hardcode_minus_L" = no; then
+ compile_command="$compile_command -L$dir -l$name"
+ elif test "$hardcode_shlibpath_var" = no; then
+ compile_shlibpath="$compile_shlibpath$dir:"
+ compile_command="$compile_command -l$name"
+ fi
+ ;;
+
+ relink)
+ # We need an absolute path.
+ case "$dir" in
+ /* | [A-Za-z]:\\*) ;;
+ *)
+ absdir=`cd "$dir" && pwd`
+ if test -z "$absdir"; then
+ $echo "$modename: cannot determine absolute directory name of \`$dir'" 1>&2
+ exit 1
+ fi
+ dir="$absdir"
+ ;;
+ esac
+
+ if test "$hardcode_direct" = yes; then
+ compile_command="$compile_command $dir/$linklib"
+ elif test "$hardcode_minus_L" = yes; then
+ compile_command="$compile_command -L$dir -l$name"
+ elif test "$hardcode_shlibpath_var" = yes; then
+ compile_shlibpath="$compile_shlibpath$dir:"
+ compile_command="$compile_command -l$name"
+ fi
+ ;;
+
+ *)
+ $echo "$modename: \`$hardcode_action' is an unknown hardcode action" 1>&2
+ exit 1
+ ;;
+ esac
+
+ # Finalize command for both is simple: just hardcode it.
+ if test "$hardcode_direct" = yes; then
+ finalize_command="$finalize_command $libdir/$linklib"
+ elif test "$hardcode_minus_L" = yes; then
+ finalize_command="$finalize_command -L$libdir -l$name"
+ elif test "$hardcode_shlibpath_var" = yes; then
+ finalize_shlibpath="$finalize_shlibpath$libdir:"
+ finalize_command="$finalize_command -l$name"
+ else
+ # We cannot seem to hardcode it, guess we'll fake it.
+ finalize_command="$finalize_command -L$libdir -l$name"
+ fi
+ else
+ # Transform directly to old archives if we don't build new libraries.
+ if test -n "$pic_flag" && test -z "$old_library"; then
+ $echo "$modename: cannot find static library for \`$arg'" 1>&2
+ exit 1
+ fi
+
+ # Here we assume that one of hardcode_direct or hardcode_minus_L
+ # is not unsupported. This is valid on all known static and
+ # shared platforms.
+ if test "$hardcode_direct" != unsupported; then
+ test -n "$old_library" && linklib="$old_library"
+ compile_command="$compile_command $dir/$linklib"
+ finalize_command="$finalize_command $dir/$linklib"
+ else
+ compile_command="$compile_command -L$dir -l$name"
+ finalize_command="$finalize_command -L$dir -l$name"
+ fi
+ fi
+
+ # Add in any libraries that this one depends upon.
+ compile_command="$compile_command$dependency_libs"
+ finalize_command="$finalize_command$dependency_libs"
+ continue
+ ;;
+
+ # Some other compiler argument.
+ *)
+ # Unknown arguments in both finalize_command and compile_command need
+ # to be aesthetically quoted because they are evaled later.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case "$arg" in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*)
+ arg="\"$arg\""
+ ;;
+ esac
+ ;;
+ esac
+
+ # Now actually substitute the argument into the commands.
+ if test -n "$arg"; then
+ compile_command="$compile_command $arg"
+ finalize_command="$finalize_command $arg"
+ fi
+ done
+
+ if test -n "$prev"; then
+ $echo "$modename: the \`$prevarg' option requires an argument" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ fi
+
+ if test -n "$vinfo" && test -n "$release"; then
+ $echo "$modename: you cannot specify both \`-version-info' and \`-release'" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ fi
+
+ oldlib=
+ oldobjs=
+ case "$output" in
+ "")
+ $echo "$modename: you must specify an output file" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ ;;
+
+ */* | *\\*)
+ $echo "$modename: output file \`$output' must have no directory components" 1>&2
+ exit 1
+ ;;
+
+ *.a)
+ # Now set the variables for building old libraries.
+ build_libtool_libs=no
+ build_old_libs=yes
+ oldlib="$output"
+ $show "$rm $oldlib"
+ $run $rm $oldlib
+ ;;
+
+ *.la)
+ # Make sure we only generate libraries of the form `libNAME.la'.
+ case "$output" in
+ lib*) ;;
+ *)
+ $echo "$modename: libtool library \`$arg' must begin with \`lib'" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ ;;
+ esac
+
+ name=`$echo "X$output" | $Xsed -e 's/\.la$//' -e 's/^lib//'`
+ eval libname=\"$libname_spec\"
+
+ # All the library-specific variables (install_libdir is set above).
+ library_names=
+ old_library=
+ dlname=
+ current=0
+ revision=0
+ age=0
+
+ if test -n "$objs"; then
+ $echo "$modename: cannot build libtool library \`$output' from non-libtool objects:$objs" 2>&1
+ exit 1
+ fi
+
+ # How the heck are we supposed to write a wrapper for a shared library?
+ if test -n "$link_against_libtool_libs"; then
+ $echo "$modename: libtool library \`$output' may not depend on uninstalled libraries:$link_against_libtool_libs" 1>&2
+ exit 1
+ fi
+
+ if test -n "$dlfiles$dlprefiles"; then
+ $echo "$modename: warning: \`-dlopen' is ignored while creating libtool libraries" 1>&2
+ # Nullify the symbol file.
+ compile_command=`$echo "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"`
+ finalize_command=`$echo "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"`
+ fi
+
+ if test -z "$rpath"; then
+ $echo "$modename: you must specify an installation directory with \`-rpath'" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ fi
+
+ set dummy $rpath
+ if test $# -gt 2; then
+ $echo "$modename: warning: ignoring multiple \`-rpath's for a libtool library" 1>&2
+ fi
+ install_libdir="$2"
+
+ # Parse the version information argument.
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS=':'
+ set dummy $vinfo
+ IFS="$save_ifs"
+
+ if test -n "$5"; then
+ $echo "$modename: too many parameters to \`-version-info'" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ fi
+
+ test -n "$2" && current="$2"
+ test -n "$3" && revision="$3"
+ test -n "$4" && age="$4"
+
+ # Check that each of the things are valid numbers.
+ case "$current" in
+ 0 | [1-9] | [1-9][0-9]*) ;;
+ *)
+ $echo "$modename: CURRENT \`$current' is not a nonnegative integer" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit 1
+ ;;
+ esac
+
+ case "$revision" in
+ 0 | [1-9] | [1-9][0-9]*) ;;
+ *)
+ $echo "$modename: REVISION \`$revision' is not a nonnegative integer" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit 1
+ ;;
+ esac
+
+ case "$age" in
+ 0 | [1-9] | [1-9][0-9]*) ;;
+ *)
+ $echo "$modename: AGE \`$age' is not a nonnegative integer" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit 1
+ ;;
+ esac
+
+ if test $age -gt $current; then
+ $echo "$modename: AGE \`$age' is greater than the current interface number \`$current'" 1>&2
+ $echo "$modename: \`$vinfo' is not valid version information" 1>&2
+ exit 1
+ fi
+
+ # Calculate the version variables.
+ version_vars="version_type current age revision"
+ case "$version_type" in
+ none) ;;
+
+ linux)
+ version_vars="$version_vars major versuffix"
+ major=`expr $current - $age`
+ versuffix="$major.$age.$revision"
+ ;;
+
+ osf)
+ version_vars="$version_vars versuffix verstring"
+ major=`expr $current - $age`
+ versuffix="$current.$age.$revision"
+ verstring="$versuffix"
+
+ # Add in all the interfaces that we are compatible with.
+ loop=$age
+ while test $loop != 0; do
+ iface=`expr $current - $loop`
+ loop=`expr $loop - 1`
+ verstring="$verstring:${iface}.0"
+ done
+
+ # Make executables depend on our current version.
+ verstring="$verstring:${current}.0"
+ ;;
+
+ sunos)
+ version_vars="$version_vars major versuffix"
+ major="$current"
+ versuffix="$current.$revision"
+ ;;
+
+ *)
+ $echo "$modename: unknown library version type \`$version_type'" 1>&2
+ echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2
+ exit 1
+ ;;
+ esac
+
+ # Create the output directory, or remove our outputs if we need to.
+ if test -d $objdir; then
+ $show "$rm $objdir/$output $objdir/$libname.* $objdir/${libname}${release}.*"
+ $run $rm $objdir/$output $objdir/$libname.* $objdir/${libname}${release}.*
+ else
+ $show "$mkdir $objdir"
+ $run $mkdir $objdir
+ status=$?
+ if test $status -eq 0 || test -d $objdir; then :
+ else
+ exit $status
+ fi
+ fi
+
+ # Check to see if the archive will have undefined symbols.
+ if test "$allow_undefined" = yes; then
+ if test "$allow_undefined_flag" = unsupported; then
+ $echo "$modename: warning: undefined symbols not allowed in $host shared libraries" 1>&2
+ build_libtool_libs=no
+ build_old_libs=yes
+ fi
+ else
+ # Don't allow undefined symbols.
+ allow_undefined_flag="$no_undefined_flag"
+ fi
+
+ # Add libc to deplibs on all systems.
+ dependency_libs="$deplibs"
+ deplibs="$deplibs -lc"
+
+ if test "$build_libtool_libs" = yes; then
+ # Get the real and link names of the library.
+ eval library_names=\"$library_names_spec\"
+ set dummy $library_names
+ realname="$2"
+ shift; shift
+
+ if test -n "$soname_spec"; then
+ eval soname=\"$soname_spec\"
+ else
+ soname="$realname"
+ fi
+
+ lib="$objdir/$realname"
+ for link
+ do
+ linknames="$linknames $link"
+ done
+
+ # Use standard objects if they are PIC.
+ test -z "$pic_flag" && libobjs=`$echo "X$libobjs " | $Xsed -e 's/\.lo /.o /g' -e 's/ $//g'`
+
+ # Do each of the archive commands.
+ eval cmds=\"$archive_cmds\"
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS=';'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+
+ # Create links to the real library.
+ for linkname in $linknames; do
+ $show "(cd $objdir && $LN_S $realname $linkname)"
+ $run eval '(cd $objdir && $LN_S $realname $linkname)' || exit $?
+ done
+
+ # If -export-dynamic was specified, set the dlname.
+ if test "$export_dynamic" = yes; then
+ # On all known operating systems, these are identical.
+ dlname="$soname"
+ fi
+ fi
+
+ # Now set the variables for building old libraries.
+ oldlib="$objdir/$libname.a"
+ ;;
+
+ *.lo | *.o)
+ if test -n "$link_against_libtool_libs"; then
+ $echo "$modename: error: cannot link libtool libraries into reloadable objects" 1>&2
+ exit 1
+ fi
+
+ if test -n "$deplibs"; then
+ $echo "$modename: warning: \`-l' and \`-L' are ignored while creating objects" 1>&2
+ fi
+
+ if test -n "$dlfiles$dlprefiles"; then
+ $echo "$modename: warning: \`-dlopen' is ignored while creating objects" 1>&2
+ # Nullify the symbol file.
+ compile_command=`$echo "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"`
+ finalize_command=`$echo "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"`
+ fi
+
+ if test -n "$rpath"; then
+ $echo "$modename: warning: \`-rpath' is ignored while creating objects" 1>&2
+ fi
+
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info' is ignored while creating objects" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored while creating objects" 1>&2
+ fi
+
+ case "$output" in
+ *.lo)
+ if test -n "$objs"; then
+ $echo "$modename: cannot build library object \`$output' from non-libtool objects" 1>&2
+ exit 1
+ fi
+ libobj="$output"
+ obj=`$echo "X$output" | $Xsed -e 's/\.lo$/.o/'`
+ ;;
+ *)
+ libobj=
+ obj="$output"
+ ;;
+ esac
+
+ # Delete the old objects.
+ $run $rm $obj $libobj
+
+ # Create the old-style object.
+ reload_objs="$objs"`$echo "X$libobjs " | $Xsed -e 's/[^ ]*\.a //g' -e 's/\.lo /.o /g' -e 's/ $//g'`
+
+ output="$obj"
+ eval cmds=\"$reload_cmds\"
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS=';'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+
+ # Exit if we aren't doing a library object file.
+ test -z "$libobj" && exit 0
+
+ if test "$build_libtool_libs" != yes; then
+ # Create an invalid libtool object if no PIC, so that we don't
+ # accidentally link it into a program.
+ $show "echo timestamp > $libobj"
+ $run eval "echo timestamp > $libobj" || exit $?
+ exit 0
+ fi
+
+ if test -n "$pic_flag"; then
+ # Only do commands if we really have different PIC objects.
+ reload_objs="$libobjs"
+ output="$libobj"
+ eval cmds=\"$reload_cmds\"
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS=';'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ else
+ # Just create a symlink.
+ $show "$LN_S $obj $libobj"
+ $run $LN_S $obj $libobj || exit 1
+ fi
+
+ exit 0
+ ;;
+
+ *)
+ if test -n "$vinfo"; then
+ $echo "$modename: warning: \`-version-info' is ignored while linking programs" 1>&2
+ fi
+
+ if test -n "$release"; then
+ $echo "$modename: warning: \`-release' is ignored while creating objects" 1>&2
+ fi
+
+ if test -n "$rpath"; then
+ # If the user specified any rpath flags, then add them.
+ for libdir in $rpath; do
+ if test -n "$hardcode_libdir_flag_spec"; then
+ if test -n "$hardcode_libdir_separator"; then
+ if test -z "$hardcode_libdirs"; then
+ # Put the magic libdir with the hardcode flag.
+ hardcode_libdirs="$libdir"
+ libdir="@HARDCODE_LIBDIRS@"
+ else
+ # Just accumulate the unique libdirs.
+ case "$hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator" in
+ *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
+ ;;
+ *)
+ hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir"
+ ;;
+ esac
+ libdir=
+ fi
+ fi
+
+ if test -n "$libdir"; then
+ eval flag=\"$hardcode_libdir_flag_spec\"
+
+ compile_command="$compile_command $flag"
+ finalize_command="$finalize_command $flag"
+ fi
+ elif test -n "$runpath_var"; then
+ case "$perm_rpath " in
+ *" $libdir "*) ;;
+ *) perm_rpath="$perm_rpath $libdir" ;;
+ esac
+ fi
+ done
+ fi
+
+ # Substitute the hardcoded libdirs into the compile commands.
+ if test -n "$hardcode_libdir_separator"; then
+ compile_command=`$echo "X$compile_command" | $Xsed -e "s%@HARDCODE_LIBDIRS@%$hardcode_libdirs%g"`
+ finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@HARDCODE_LIBDIRS@%$hardcode_libdirs%g"`
+ fi
+
+ if test -n "$libobjs" && test "$build_old_libs" = yes; then
+ # Transform all the library objects into standard objects.
+ compile_command=`$echo "X$compile_command " | $Xsed -e 's/\.lo /.o /g' -e 's/ $//'`
+ finalize_command=`$echo "X$finalize_command " | $Xsed -e 's/\.lo /.o /g' -e 's/ $//'`
+ fi
+
+ if test "$export_dynamic" = yes && test -n "$NM" && test -n "$global_symbol_pipe"; then
+ dlsyms="${output}S.c"
+ else
+ dlsyms=
+ fi
+
+ if test -n "$dlsyms"; then
+ # Add our own program objects to the preloaded list.
+ dlprefiles=`$echo "X$objs$dlprefiles " | $Xsed -e 's/\.lo /.o /g' -e 's/ $//'`
+
+ # Discover the nlist of each of the dlfiles.
+ nlist="$objdir/${output}.nm"
+
+ if test -d $objdir; then
+ $show "$rm $nlist ${nlist}T"
+ $run $rm "$nlist" "${nlist}T"
+ else
+ $show "$mkdir $objdir"
+ $run $mkdir $objdir
+ status=$?
+ if test $status -eq 0 || test -d $objdir; then :
+ else
+ exit $status
+ fi
+ fi
+
+ for arg in $dlprefiles; do
+ $show "extracting global C symbols from \`$arg'"
+ $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'"
+ done
+
+ # Parse the name list into a source file.
+ $show "creating $objdir/$dlsyms"
+ if test -z "$run"; then
+ # Make sure we at least have an empty file.
+ test -f "$nlist" || : > "$nlist"
+
+ # Try sorting and uniquifying the output.
+ if sort "$nlist" | uniq > "$nlist"T; then
+ mv -f "$nlist"T "$nlist"
+ wcout=`wc "$nlist" 2>/dev/null`
+ count=`echo "X$wcout" | $Xsed -e 's/^[ ]*\([0-9][0-9]*\).*$/\1/'`
+ (test "$count" -ge 0) 2>/dev/null || count=-1
+ else
+ $rm "$nlist"T
+ count=-1
+ fi
+
+ case "$dlsyms" in
+ "") ;;
+ *.c)
+ $echo > "$objdir/$dlsyms" "\
+/* $dlsyms - symbol resolution table for \`$output' dlsym emulation. */
+/* Generated by $PROGRAM - GNU $PACKAGE $VERSION */
+
+#ifdef __cplusplus
+extern \"C\" {
+#endif
+
+/* Prevent the only kind of declaration conflicts we can make. */
+#define dld_preloaded_symbol_count some_other_symbol
+#define dld_preloaded_symbols some_other_symbol
+
+/* External symbol declarations for the compiler. */\
+"
+
+ if test -f "$nlist"; then
+ sed -e 's/^.* \(.*\)$/extern char \1;/' < "$nlist" >> "$objdir/$dlsyms"
+ else
+ echo '/* NONE */' >> "$objdir/$dlsyms"
+ fi
+
+ $echo >> "$objdir/$dlsyms" "\
+
+#undef dld_preloaded_symbol_count
+#undef dld_preloaded_symbols
+
+#if defined (__STDC__) && __STDC__
+# define __ptr_t void *
+#else
+# define __ptr_t char *
+#endif
+
+/* The number of symbols in dld_preloaded_symbols, -1 if unsorted. */
+int dld_preloaded_symbol_count = $count;
+
+/* The mapping between symbol names and symbols. */
+struct {
+ char *name;
+ __ptr_t address;
+}
+dld_preloaded_symbols[] =
+{\
+"
+
+ if test -f "$nlist"; then
+ sed 's/^\(.*\) \(.*\)$/ {"\1", (__ptr_t) \&\2},/' < "$nlist" >> "$objdir/$dlsyms"
+ fi
+
+ $echo >> "$objdir/$dlsyms" "\
+ {0, (__ptr_t) 0}
+};
+
+#ifdef __cplusplus
+}
+#endif\
+"
+ ;;
+
+ *)
+ $echo "$modename: unknown suffix for \`$dlsyms'" 1>&2
+ exit 1
+ ;;
+ esac
+ fi
+
+ # Now compile the dynamic symbol file.
+ $show "(cd $objdir && $CC -c$no_builtin_flag \"$dlsyms\")"
+ $run eval '(cd $objdir && $CC -c$no_builtin_flag "$dlsyms")' || exit $?
+
+ # Transform the symbol file into the correct name.
+ compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$objdir/${output}S.o%"`
+ finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$objdir/${output}S.o%"`
+ elif test "$export_dynamic" != yes; then
+ test -n "$dlfiles$dlprefiles" && $echo "$modename: warning: \`-dlopen' and \`-dlpreopen' are ignored without \`-export-dynamic'" 1>&2
+ else
+ # We keep going just in case the user didn't refer to
+ # dld_preloaded_symbols. The linker will fail if global_symbol_pipe
+ # really was required.
+ $echo "$modename: not configured to extract global symbols from dlpreopened files" 1>&2
+
+ # Nullify the symbol file.
+ compile_command=`$echo "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"`
+ finalize_command=`$echo "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"`
+ fi
+
+ if test -z "$link_against_libtool_libs" || test "$build_libtool_libs" != yes; then
+ # Replace the output file specification.
+ compile_command=`$echo "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'`
+ finalize_command=`$echo "X$finalize_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'`
+
+ # We have no uninstalled library dependencies, so finalize right now.
+ $show "$compile_command"
+ $run eval "$compile_command"
+ exit $?
+ fi
+
+ # Replace the output file specification.
+ compile_command=`$echo "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$objdir/$output"'%g'`
+ finalize_command=`$echo "X$finalize_command" | $Xsed -e 's%@OUTPUT@%'"$objdir/$output"'T%g'`
+
+ # Create the binary in the object directory, then wrap it.
+ if test -d $objdir; then :
+ else
+ $show "$mkdir $objdir"
+ $run $mkdir $objdir
+ status=$?
+ if test $status -eq 0 || test -d $objdir; then :
+ else
+ exit $status
+ fi
+ fi
+
+ if test -n "$shlibpath_var"; then
+ # We should set the shlibpath_var
+ rpath=
+ for dir in $temp_rpath; do
+ case "$dir" in
+ /* | [A-Za-z]:\\*)
+ # Absolute path.
+ rpath="$rpath$dir:"
+ ;;
+ *)
+ # Relative path: add a thisdir entry.
+ rpath="$rpath\$thisdir/$dir:"
+ ;;
+ esac
+ done
+ temp_rpath="$rpath"
+ fi
+
+ # Delete the old output file.
+ $run $rm $output
+
+ if test -n "$compile_shlibpath"; then
+ compile_command="$shlibpath_var=\"$compile_shlibpath\$$shlibpath_var\" $compile_command"
+ fi
+ if test -n "$finalize_shlibpath"; then
+ finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command"
+ fi
+
+ if test -n "$runpath_var" && test -n "$perm_rpath"; then
+ # We should set the runpath_var.
+ rpath=
+ for dir in $perm_rpath; do
+ rpath="$rpath$dir:"
+ done
+ compile_command="$runpath_var=\"$rpath\$$runpath_var\" $compile_command"
+ finalize_command="$runpath_var=\"$rpath\$$runpath_var\" $finalize_command"
+ fi
+
+ case "$hardcode_action" in
+ relink)
+ # AGH! Flame the AIX and HP-UX people for me, will ya?
+ $echo "$modename: warning: using a buggy system linker" 1>&2
+ $echo "$modename: relinking will be required before \`$output' can be installed" 1>&2
+ ;;
+ esac
+
+ $show "$compile_command"
+ $run eval "$compile_command" || exit $?
+
+ # Now create the wrapper script.
+ $show "creating $output"
+
+ # Quote the finalize command for shipping.
+ finalize_command=`$echo "X$finalize_command" | $Xsed -e "$sed_quote_subst"`
+
+ # Quote $echo for shipping.
+ qecho=`$echo "X$echo" | $Xsed -e "$sed_quote_subst"`
+
+ # Only actually do things if our run command is non-null.
+ if test -z "$run"; then
+ $rm $output
+ trap "$rm $output; exit 1" 1 2 15
+
+ $echo > $output "\
+#! /bin/sh
+
+# $output - temporary wrapper script for $objdir/$output
+# Generated by ltmain.sh - GNU $PACKAGE $VERSION
+#
+# The $output program cannot be directly executed until all the libtool
+# libraries that it depends on are installed.
+#
+# This wrapper script should never be moved out of \``pwd`'.
+# If it is, it will not operate correctly.
+
+# Sed substitution that helps us do robust quoting. It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed='sed -e s/^X//'
+sed_quote_subst='$sed_quote_subst'
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+if test \"\${CDPATH+set}\" = set; then CDPATH=; export CDPATH; fi
+
+# This environment variable determines our operation mode.
+if test \"\$libtool_install_magic\" = \"$magic\"; then
+ # install mode needs the following variables:
+ link_against_libtool_libs='$link_against_libtool_libs'
+ finalize_command=\"$finalize_command\"
+else
+ # When we are sourced in execute mode, \$file and \$echo are already set.
+ if test \"\$libtool_execute_magic\" = \"$magic\"; then :
+ else
+ echo=\"$qecho\"
+ file=\"\$0\"
+ fi\
+"
+ $echo >> $output "\
+
+ # Find the directory that this script lives in.
+ thisdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\`
+ test \"x\$thisdir\" = \"x\$file\" && thisdir=.
+
+ # Follow symbolic links until we get to the real thisdir.
+ file=\`ls -ld \"\$file\" | sed -n 's/.*-> //p'\`
+ while test -n \"\$file\"; do
+ destdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\`
+
+ # If there was a directory component, then change thisdir.
+ if test \"x\$destdir\" != \"x\$file\"; then
+ case \"\$destdir\" in
+ /* | [A-Za-z]:\\*) thisdir=\"\$destdir\" ;;
+ *) thisdir=\"\$thisdir/\$destdir\" ;;
+ esac
+ fi
+
+ file=\`\$echo \"X\$file\" | \$Xsed -e 's%^.*/%%'\`
+ file=\`ls -ld \"\$thisdir/\$file\" | sed -n 's/.*-> //p'\`
+ done
+
+ # Try to get the absolute directory name.
+ absdir=\`cd \"\$thisdir\" && pwd\`
+ test -n \"\$absdir\" && thisdir=\"\$absdir\"
+
+ progdir=\"\$thisdir/$objdir\"
+ program='$output'
+
+ if test -f \"\$progdir/\$program\"; then"
+
+ # Export our shlibpath_var if we have one.
+ if test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+ $echo >> $output "\
+ # Add our own library path to $shlibpath_var
+ $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
+
+ # Some systems cannot cope with colon-terminated $shlibpath_var
+ $shlibpath_var=\`\$echo \"X\$$shlibpath_var\" | \$Xsed -e 's/:*\$//'\`
+
+ export $shlibpath_var
+"
+ fi
+
+ $echo >> $output "\
+ if test \"\$libtool_execute_magic\" != \"$magic\"; then
+ # Run the actual program with our arguments.
+
+ # Export the path to the program.
+ PATH=\"\$progdir:\$PATH\"
+ export PATH
+
+ exec \$program \${1+\"\$@\"}
+
+ \$echo \"\$0: cannot exec \$program \${1+\"\$@\"}\"
+ exit 1
+ fi
+ else
+ # The program doesn't exist.
+ \$echo \"\$0: error: \$progdir/\$program does not exist\" 1>&2
+ \$echo \"This script is just a wrapper for \$program.\" 1>&2
+ echo \"See the $PACKAGE documentation for more information.\" 1>&2
+ exit 1
+ fi
+fi\
+"
+ chmod +x $output
+ fi
+ exit 0
+ ;;
+ esac
+
+ # See if we need to build an old-fashioned archive.
+ if test "$build_old_libs" = "yes"; then
+ # Transform .lo files to .o files.
+ oldobjs="$objs"`$echo "X$libobjs " | $Xsed -e 's/[^ ]*\.a //g' -e 's/\.lo /.o /g' -e 's/ $//g'`
+
+ # Do each command in the archive commands.
+ if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then
+ eval cmds=\"$old_archive_from_new_cmds\"
+ else
+ eval cmds=\"$old_archive_cmds\"
+ fi
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS=';'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ fi
+
+ # Now create the libtool archive.
+ case "$output" in
+ *.la)
+ old_library=
+ test "$build_old_libs" = yes && old_library="$libname.a"
+
+ $show "creating $output"
+
+ # Only create the output if not a dry run.
+ if test -z "$run"; then
+ $echo > $output "\
+# $output - a libtool library file
+# Generated by ltmain.sh - GNU $PACKAGE $VERSION
+
+# The name that we can dlopen(3).
+dlname='$dlname'
+
+# Names of this library.
+library_names='$library_names'
+
+# The name of the static archive.
+old_library='$old_library'
+
+# Libraries that this one depends upon.
+dependency_libs='$dependency_libs'
+
+# Version information for $libname.
+current=$current
+age=$age
+revision=$revision
+
+# Directory that this library needs to be installed in:
+libdir='$install_libdir'\
+"
+ fi
+
+ # Do a symbolic link so that the libtool archive can be found in
+ # LD_LIBRARY_PATH before the program is installed.
+ $show "(cd $objdir && $LN_S ../$output $output)"
+ $run eval "(cd $objdir && $LN_S ../$output $output)" || exit 1
+ ;;
+ esac
+ exit 0
+ ;;
+
+ # libtool install mode
+ install)
+ modename="$modename: install"
+
+ # There may be an optional /bin/sh argument at the beginning of
+ # install_prog (especially on Windows NT).
+ if test "$nonopt" = "$SHELL"; then
+ # Aesthetically quote it.
+ arg=`$echo "X$nonopt" | $Xsed -e "$sed_quote_subst"`
+ case "$arg" in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*)
+ arg="\"$arg\""
+ ;;
+ esac
+ install_prog="$arg "
+ arg="$1"
+ shift
+ else
+ install_prog=
+ arg="$nonopt"
+ fi
+
+ # The real first argument should be the name of the installation program.
+ # Aesthetically quote it.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case "$arg" in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*)
+ arg="\"$arg\""
+ ;;
+ esac
+ install_prog="$install_prog$arg"
+
+ # We need to accept at least all the BSD install flags.
+ dest=
+ files=
+ opts=
+ prev=
+ install_type=
+ isdir=
+ stripme=
+ for arg
+ do
+ if test -n "$dest"; then
+ files="$files $dest"
+ dest="$arg"
+ continue
+ fi
+
+ case "$arg" in
+ -d) isdir=yes ;;
+ -f) prev="-f" ;;
+ -g) prev="-g" ;;
+ -m) prev="-m" ;;
+ -o) prev="-o" ;;
+ -s)
+ stripme=" -s"
+ continue
+ ;;
+ -*) ;;
+
+ *)
+ # If the previous option needed an argument, then skip it.
+ if test -n "$prev"; then
+ prev=
+ else
+ dest="$arg"
+ continue
+ fi
+ ;;
+ esac
+
+ # Aesthetically quote the argument.
+ arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
+ case "$arg" in
+ *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*)
+ arg="\"$arg\""
+ ;;
+ esac
+ install_prog="$install_prog $arg"
+ done
+
+ if test -z "$install_prog"; then
+ $echo "$modename: you must specify an install program" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ fi
+
+ if test -n "$prev"; then
+ $echo "$modename: the \`$prev' option requires an argument" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ fi
+
+ if test -z "$files"; then
+ if test -z "$dest"; then
+ $echo "$modename: no file or destination specified" 1>&2
+ else
+ $echo "$modename: you must specify a destination" 1>&2
+ fi
+ $echo "$help" 1>&2
+ exit 1
+ fi
+
+ # Strip any trailing slash from the destination.
+ dest=`$echo "X$dest" | $Xsed -e 's%/$%%'`
+
+ # Check to see that the destination is a directory.
+ test -d "$dest" && isdir=yes
+ if test -n "$isdir"; then
+ destdir="$dest"
+ destname=
+ else
+ destdir=`$echo "X$dest" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$destdir" = "X$dest" && destdir=.
+ destname=`$echo "X$dest" | $Xsed -e 's%^.*/%%'`
+
+ # Not a directory, so check to see that there is only one file specified.
+ set dummy $files
+ if test $# -gt 2; then
+ $echo "$modename: \`$dest' is not a directory" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ fi
+ fi
+ case "$destdir" in
+ /* | [A-Za-z]:\\*) ;;
+ *)
+ for file in $files; do
+ case "$file" in
+ *.lo) ;;
+ *)
+ $echo "$modename: \`$destdir' must be an absolute directory name" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ ;;
+ esac
+ done
+ ;;
+ esac
+
+ # This variable tells wrapper scripts just to set variables rather
+ # than running their programs.
+ libtool_install_magic="$magic"
+
+ staticlibs=
+ future_libdirs=
+ current_libdirs=
+ for file in $files; do
+
+ # Do each installation.
+ case "$file" in
+ *.a)
+ # Do the static libraries later.
+ staticlibs="$staticlibs $file"
+ ;;
+
+ *.la)
+ # Check to see that this really is a libtool archive.
+ if (sed -e '2q' $file | egrep '^# Generated by ltmain\.sh') >/dev/null 2>&1; then :
+ else
+ $echo "$modename: \`$file' is not a valid libtool archive" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ fi
+
+ library_names=
+ old_library=
+ # If there is no directory component, then add one.
+ case "$file" in
+ */* | *\\*) . $file ;;
+ *) . ./$file ;;
+ esac
+
+ # Add the libdir to current_libdirs if it is the destination.
+ if test "X$destdir" = "X$libdir"; then
+ case "$current_libdirs " in
+ *" $libdir "*) ;;
+ *) current_libdirs="$current_libdirs $libdir" ;;
+ esac
+ else
+ # Note the libdir as a future libdir.
+ case "$future_libdirs " in
+ *" $libdir "*) ;;
+ *) future_libdirs="$future_libdirs $libdir" ;;
+ esac
+ fi
+
+ dir="`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`/"
+ test "X$dir" = "X$file/" && dir=
+ dir="$dir$objdir"
+
+ # See the names of the shared library.
+ set dummy $library_names
+ if test -n "$2"; then
+ realname="$2"
+ shift
+ shift
+
+ # Install the shared library and build the symlinks.
+ $show "$install_prog $dir/$realname $destdir/$realname"
+ $run eval "$install_prog $dir/$realname $destdir/$realname" || exit $?
+ test "X$dlname" = "X$realname" && dlname=
+
+ if test $# -gt 0; then
+ # Delete the old symlinks.
+ rmcmd="$rm"
+ for linkname
+ do
+ rmcmd="$rmcmd $destdir/$linkname"
+ done
+ $show "$rmcmd"
+ $run $rmcmd
+
+ # ... and create new ones.
+ for linkname
+ do
+ test "X$dlname" = "X$linkname" && dlname=
+ $show "(cd $destdir && $LN_S $realname $linkname)"
+ $run eval "(cd $destdir && $LN_S $realname $linkname)"
+ done
+ fi
+
+ if test -n "$dlname"; then
+ # Install the dynamically-loadable library.
+ $show "$install_prog $dir/$dlname $destdir/$dlname"
+ $run eval "$install_prog $dir/$dlname $destdir/$dlname" || exit $?
+ fi
+
+ # Do each command in the postinstall commands.
+ lib="$destdir/$realname"
+ eval cmds=\"$postinstall_cmds\"
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS=';'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ fi
+
+ # Install the pseudo-library for information purposes.
+ name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ $show "$install_prog $file $destdir/$name"
+ $run eval "$install_prog $file $destdir/$name" || exit $?
+
+ # Maybe install the static library, too.
+ test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library"
+ ;;
+
+ *.lo)
+ # Install (i.e. copy) a libtool object.
+
+ # Figure out destination file name, if it wasn't already specified.
+ if test -n "$destname"; then
+ destfile="$destdir/$destname"
+ else
+ destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+ destfile="$destdir/$destfile"
+ fi
+
+ # Deduce the name of the destination old-style object file.
+ case "$destfile" in
+ *.lo)
+ staticdest=`$echo "X$destfile" | $Xsed -e 's/\.lo$/\.o/'`
+ ;;
+ *.o)
+ staticdest="$destfile"
+ destfile=
+ ;;
+ *)
+ $echo "$modename: cannot copy a libtool object to \`$destfile'" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ ;;
+ esac
+
+ # Install the libtool object if requested.
+ if test -n "$destfile"; then
+ $show "$install_prog $file $destfile"
+ $run eval "$install_prog $file $destfile" || exit $?
+ fi
+
+ # Install the old object if enabled.
+ if test "$build_old_libs" = yes; then
+ # Deduce the name of the old-style object file.
+ staticobj=`$echo "X$file" | $Xsed -e 's/\.lo$/\.o/'`
+
+ $show "$install_prog $staticobj $staticdest"
+ $run eval "$install_prog \$staticobj \$staticdest" || exit $?
+ fi
+ exit 0
+ ;;
+
+ *)
+ # Do a test to see if this is really a libtool program.
+ if (sed -e '4q' $file | egrep '^# Generated by ltmain\.sh') >/dev/null 2>&1; then
+ link_against_libtool_libs=
+ finalize_command=
+
+ # If there is no directory component, then add one.
+ case "$file" in
+ */* | *\\*) . $file ;;
+ *) . ./$file ;;
+ esac
+
+ # Check the variables that should have been set.
+ if test -z "$link_against_libtool_libs" || test -z "$finalize_command"; then
+ $echo "$modename: invalid libtool wrapper script \`$file'" 1>&2
+ exit 1
+ fi
+
+ finalize=yes
+ for lib in $link_against_libtool_libs; do
+ # Check to see that each library is installed.
+ libdir=
+ if test -f "$lib"; then
+ # If there is no directory component, then add one.
+ case "$lib" in
+ */* | *\\*) . $lib ;;
+ *) . ./$lib ;;
+ esac
+ fi
+ libfile="$libdir/`$echo "X$lib" | $Xsed -e 's%^.*/%%g'`"
+ if test -z "$libdir"; then
+ $echo "$modename: warning: \`$lib' contains no -rpath information" 1>&2
+ elif test -f "$libfile"; then :
+ else
+ $echo "$modename: warning: \`$lib' has not been installed in \`$libdir'" 1>&2
+ finalize=no
+ fi
+ done
+
+ if test "$hardcode_action" = relink; then
+ if test "$finalize" = yes; then
+ $echo "$modename: warning: relinking \`$file' on behalf of your buggy system linker" 1>&2
+ $show "$finalize_command"
+ if $run eval "$finalize_command"; then :
+ else
+ $echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2
+ continue
+ fi
+ file="$objdir/$file"T
+ else
+ $echo "$modename: warning: cannot relink \`$file' on behalf of your buggy system linker" 1>&2
+ fi
+ else
+ # Install the binary that we compiled earlier.
+ file=`$echo "X$file" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"`
+ fi
+ fi
+
+ $show "$install_prog$stripme $file $dest"
+ $run eval "$install_prog\$stripme \$file \$dest" || exit $?
+ ;;
+ esac
+ done
+
+ for file in $staticlibs; do
+ name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+
+ # Set up the ranlib parameters.
+ oldlib="$destdir/$name"
+
+ $show "$install_prog $file $oldlib"
+ $run eval "$install_prog \$file \$oldlib" || exit $?
+
+ # Do each command in the postinstall commands.
+ eval cmds=\"$old_postinstall_cmds\"
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS=';'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd" || exit $?
+ done
+ IFS="$save_ifs"
+ done
+
+ if test -n "$future_libdirs"; then
+ $echo "$modename: warning: remember to run \`$progname --finish$future_libdirs'" 1>&2
+ fi
+
+ if test -n "$current_libdirs"; then
+ # Maybe just do a dry run.
+ test -n "$run" && current_libdirs=" -n$current_libdirs"
+ exec $SHELL $0 --finish$current_libdirs
+ exit 1
+ fi
+
+ exit 0
+ ;;
+
+ # libtool finish mode
+ finish)
+ modename="$modename: finish"
+ libdirs="$nonopt"
+
+ if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+ for dir
+ do
+ libdirs="$libdirs $dir"
+ done
+
+ for libdir in $libdirs; do
+ if test -n "$finish_cmds"; then
+ # Do each command in the finish commands.
+ eval cmds=\"$finish_cmds\"
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS=';'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd"
+ done
+ IFS="$save_ifs"
+ fi
+ if test -n "$finish_eval"; then
+ # Do the single finish_eval.
+ eval cmds=\"$finish_eval\"
+ $run eval "$cmds"
+ fi
+ done
+ fi
+
+ echo "------------------------------------------------------------------------------"
+ echo "Libraries have been installed in:"
+ for libdir in $libdirs; do
+ echo " $libdir"
+ done
+ echo
+ echo "To link against installed libraries in a given directory, LIBDIR,"
+ echo "you must use the \`-LLIBDIR' flag during linking."
+ echo
+ echo " You will also need to do one of the following:"
+ if test -n "$shlibpath_var"; then
+ echo " - add LIBDIR to the \`$shlibpath_var' environment variable"
+ echo " during execution"
+ fi
+ if test -n "$runpath_var"; then
+ echo " - add LIBDIR to the \`$runpath_var' environment variable"
+ echo " during linking"
+ fi
+ if test -n "$hardcode_libdir_flag_spec"; then
+ libdir=LIBDIR
+ eval flag=\"$hardcode_libdir_flag_spec\"
+
+ echo " - use the \`$flag' linker flag"
+ fi
+ if test -f /etc/ld.so.conf; then
+ echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
+ fi
+ echo
+ echo "See any operating system documentation about shared libraries for"
+ echo "more information, such as the ld(1) and ld.so(8) manual pages."
+ echo "------------------------------------------------------------------------------"
+ exit 0
+ ;;
+
+ # libtool execute mode
+ execute)
+ modename="$modename: execute"
+
+ # The first argument is the command name.
+ cmd="$nonopt"
+ if test -z "$cmd"; then
+ $echo "$modename: you must specify a COMMAND" 1>&2
+ $echo "$help"
+ exit 1
+ fi
+
+ # Handle -dlopen flags immediately.
+ for file in $execute_dlfiles; do
+ if test -f "$file"; then :
+ else
+ $echo "$modename: \`$file' is not a file" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ fi
+
+ dir=
+ case "$file" in
+ *.la)
+ # Check to see that this really is a libtool archive.
+ if (sed -e '2q' $file | egrep '^# Generated by ltmain\.sh') >/dev/null 2>&1; then :
+ else
+ $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ fi
+
+ # Read the libtool library.
+ dlname=
+ library_names=
+
+ # If there is no directory component, then add one.
+ case "$file" in
+ */* | *\\*) . $file ;;
+ *) . ./$file ;;
+ esac
+
+ # Skip this library if it cannot be dlopened.
+ if test -z "$dlname"; then
+ # Warn if it was a shared library.
+ test -n "$library_names" && $echo "$modename: warning: \`$file' was not linked with \`-export-dynamic'"
+ continue
+ fi
+
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$dir" = "X$file" && dir=.
+
+ if test -f "$dir/$objdir/$dlname"; then
+ dir="$dir/$objdir"
+ else
+ $echo "$modename: cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" 1>&2
+ exit 1
+ fi
+ ;;
+
+ *.lo)
+ # Just add the directory containing the .lo file.
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$dir" = "X$file" && dir=.
+ ;;
+
+ *)
+ $echo "$modename: warning \`-dlopen' is ignored for non-libtool libraries and objects" 1>&2
+ continue
+ ;;
+ esac
+
+ # Get the absolute pathname.
+ absdir=`cd "$dir" && pwd`
+ test -n "$absdir" && dir="$absdir"
+
+ # Now add the directory to shlibpath_var.
+ if eval "test -z \"\$$shlibpath_var\""; then
+ eval "$shlibpath_var=\"\$dir\""
+ else
+ eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\""
+ fi
+ done
+
+ # This variable tells wrapper scripts just to set shlibpath_var
+ # rather than running their programs.
+ libtool_execute_magic="$magic"
+
+ # Check if any of the arguments is a wrapper script.
+ args=
+ for file
+ do
+ case "$file" in
+ -*) ;;
+ *)
+ # Do a test to see if this is really a libtool program.
+ if (sed -e '4q' $file | egrep '^# Generated by ltmain\.sh') >/dev/null 2>&1; then
+ # If there is no directory component, then add one.
+ case "$file" in
+ */* | *\\*) . $file ;;
+ *) . ./$file ;;
+ esac
+
+ # Transform arg to wrapped name.
+ file="$progdir/$program"
+ fi
+ ;;
+ esac
+ # Quote arguments (to preserve shell metacharacters).
+ file=`$echo "X$file" | $Xsed -e "$sed_quote_subst"`
+ args="$args \"$file\""
+ done
+
+ if test -z "$run"; then
+ # Export the shlibpath_var.
+ eval "export $shlibpath_var"
+
+ # Now actually exec the command.
+ eval "exec \$cmd$args"
+
+ $echo "$modename: cannot exec \$cmd$args"
+ exit 1
+ else
+ # Display what would be done.
+ eval "\$echo \"\$shlibpath_var=\$$shlibpath_var\""
+ $echo "export $shlibpath_var"
+ $echo "$cmd$args"
+ exit 0
+ fi
+ ;;
+
+ # libtool uninstall mode
+ uninstall)
+ modename="$modename: uninstall"
+ rm="$nonopt"
+ files=
+
+ for arg
+ do
+ case "$arg" in
+ -*) rm="$rm $arg" ;;
+ *) files="$files $arg" ;;
+ esac
+ done
+
+ if test -z "$rm"; then
+ $echo "$modename: you must specify an RM program" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ fi
+
+ for file in $files; do
+ dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
+ test "X$dir" = "X$file" && dir=.
+ name=`$echo "X$file" | $Xsed -e 's%^.*/%%'`
+
+ rmfiles="$file"
+
+ case "$name" in
+ *.la)
+ # Possibly a libtool archive, so verify it.
+ if (sed -e '2q' $file | egrep '^# Generated by ltmain\.sh') >/dev/null 2>&1; then
+ . $dir/$name
+
+ # Delete the libtool libraries and symlinks.
+ for n in $library_names; do
+ rmfiles="$rmfiles $dir/$n"
+ test "X$n" = "X$dlname" && dlname=
+ done
+ test -n "$dlname" && rmfiles="$rmfiles $dir/$dlname"
+ test -n "$old_library" && rmfiles="$rmfiles $dir/$old_library"
+
+ $show "$rm $rmfiles"
+ $run $rm $rmfiles
+
+ if test -n "$library_names"; then
+ # Do each command in the postuninstall commands.
+ eval cmds=\"$postuninstall_cmds\"
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS=';'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd"
+ done
+ IFS="$save_ifs"
+ fi
+
+ if test -n "$old_library"; then
+ # Do each command in the old_postuninstall commands.
+ eval cmds=\"$old_postuninstall_cmds\"
+ IFS="${IFS= }"; save_ifs="$IFS"; IFS=';'
+ for cmd in $cmds; do
+ IFS="$save_ifs"
+ $show "$cmd"
+ $run eval "$cmd"
+ done
+ IFS="$save_ifs"
+ fi
+
+ # FIXME: should reinstall the best remaining shared library.
+ fi
+ ;;
+
+ *.lo)
+ if test "$build_old_libs" = yes; then
+ oldobj=`$echo "X$name" | $Xsed -e 's/\.lo$/\.o/'`
+ rmfiles="$rmfiles $dir/$oldobj"
+ fi
+ $show "$rm $rmfiles"
+ $run $rm $rmfiles
+ ;;
+
+ *)
+ $show "$rm $rmfiles"
+ $run $rm $rmfiles
+ ;;
+ esac
+ done
+ exit 0
+ ;;
+
+ "")
+ $echo "$modename: you must specify a MODE" 1>&2
+ $echo "$generic_help" 1>&2
+ exit 1
+ ;;
+ esac
+
+ $echo "$modename: invalid operation mode \`$mode'" 1>&2
+ $echo "$generic_help" 1>&2
+ exit 1
+fi # test -z "$show_help"
+
+# We need to display help for each of the modes.
+case "$mode" in
+"") $echo \
+"Usage: $modename [OPTION]... [MODE-ARG]...
+
+Provide generalized library-building support services.
+
+-n, --dry-run display commands without modifying any files
+ --features display configuration information and exit
+ --finish same as \`--mode=finish'
+ --help display this help message and exit
+ --mode=MODE use operation mode MODE [default=inferred from MODE-ARGS]
+ --quiet same as \`--silent'
+ --silent don't print informational messages
+ --version print version information
+
+MODE must be one of the following:
+
+ compile compile a source file into a libtool object
+ execute automatically set library path, then run a program
+ finish complete the installation of libtool libraries
+ install install libraries or executables
+ link create a library or an executable
+ uninstall remove libraries from an installed directory
+
+MODE-ARGS vary depending on the MODE. Try \`$modename --help --mode=MODE' for
+a more detailed description of MODE."
+ exit 0
+ ;;
+
+compile)
+ $echo \
+"Usage: $modename [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE
+
+Compile a source file into a libtool library object.
+
+COMPILE-COMMAND is a command to be used in creating a \`standard' object file
+from the given SOURCEFILE.
+
+The output file name is determined by removing the directory component from
+SOURCEFILE, then substituting the C source code suffix \`.c' with the
+library object suffix, \`.lo'."
+ ;;
+
+execute)
+ $echo \
+"Usage: $modename [OPTION]... --mode=execute COMMAND [ARGS]...
+
+Automatically set library path, then run a program.
+
+This mode accepts the following additional options:
+
+ -dlopen FILE add the directory containing FILE to the library path
+
+This mode sets the library path environment variable according to \`-dlopen'
+flags.
+
+If any of the ARGS are libtool executable wrappers, then they are translated
+into their corresponding uninstalled binary, and any of their required library
+directories are added to the library path.
+
+Then, COMMAND is executed, with ARGS as arguments."
+ ;;
+
+finish)
+ $echo \
+"Usage: $modename [OPTION]... --mode=finish [LIBDIR]...
+
+Complete the installation of libtool libraries.
+
+Each LIBDIR is a directory that contains libtool libraries.
+
+The commands that this mode executes may require superuser privileges. Use
+the \`--dry-run' option if you just want to see what would be executed."
+ ;;
+
+install)
+ $echo \
+"Usage: $modename [OPTION]... --mode=install INSTALL-COMMAND...
+
+Install executables or libraries.
+
+INSTALL-COMMAND is the installation command. The first component should be
+either the \`install' or \`cp' program.
+
+The rest of the components are interpreted as arguments to that command (only
+BSD-compatible install options are recognized)."
+ ;;
+
+link)
+ $echo \
+"Usage: $modename [OPTION]... --mode=link LINK-COMMAND...
+
+Link object files or libraries together to form another library, or to
+create an executable program.
+
+LINK-COMMAND is a command using the C compiler that you would use to create
+a program from several object files.
+
+The following components of LINK-COMMAND are treated specially:
+
+ -all-static do not do any dynamic linking at all
+ -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime
+ -dlpreopen FILE link in FILE and add its symbols to dld_preloaded_symbols
+ -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3)
+ -LLIBDIR search LIBDIR for required installed libraries
+ -lNAME OUTPUT-FILE requires the installed library libNAME
+ -no-undefined declare that a library does not refer to external symbols
+ -o OUTPUT-FILE create OUTPUT-FILE from the specified objects
+ -release RELEASE specify package release information
+ -rpath LIBDIR the created library will eventually be installed in LIBDIR
+ -static do not do any dynamic linking of libtool libraries
+ -version-info CURRENT[:REVISION[:AGE]]
+ specify library version info [each variable defaults to 0]
+
+All other options (arguments beginning with \`-') are ignored.
+
+Every other argument is treated as a filename. Files ending in \`.la' are
+treated as uninstalled libtool libraries, other files are standard or library
+object files.
+
+If the OUTPUT-FILE ends in \`.la', then a libtool library is created, only
+library objects (\`.lo' files) may be specified, and \`-rpath' is required.
+
+If OUTPUT-FILE ends in \`.a', then a standard library is created using \`ar'
+and \`ranlib'.
+
+If OUTPUT-FILE ends in \`.lo' or \`.o', then a reloadable object file is
+created, otherwise an executable program is created."
+ ;;
+
+uninstall)
+ $echo
+"Usage: $modename [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...
+
+Remove libraries from an installation directory.
+
+RM is the name of the program to use to delete files associated with each FILE
+(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed
+to RM.
+
+If FILE is a libtool library, all the files associated with it are deleted.
+Otherwise, only FILE itself is deleted using RM."
+ ;;
+
+*)
+ $echo "$modename: invalid operation mode \`$mode'" 1>&2
+ $echo "$help" 1>&2
+ exit 1
+ ;;
+esac
+
+echo
+$echo "Try \`$modename --help' for more information about other modes."
+
+exit 0
+
+# Local Variables:
+# mode:shell-script
+# sh-indentation:2
+# End:
diff --git a/jpeg-6c/makcjpeg.st b/jpeg-6c/makcjpeg.st
new file mode 100644
index 0000000..fc72c89
--- /dev/null
+++ b/jpeg-6c/makcjpeg.st
@@ -0,0 +1,38 @@
+; Project file for Independent JPEG Group's software
+;
+; This project file is for Atari ST/STE/TT systems using Pure C or Turbo C.
+; Thanks to Frank Moehle (Frank.Moehle at arbi.informatik.uni-oldenburg.de),
+; Dr. B. Setzepfandt (bernd at gina.uni-muenster.de),
+; and Guido Vollbeding (guivol at esc.de).
+;
+; To use this file, rename it to cjpeg.prj.
+; If you are using Turbo C, change filenames beginning with "pc..." to "tc..."
+; Read installation instructions before trying to make the program!
+;
+;
+; * * * Output file * * *
+cjpeg.ttp
+;
+; * * * COMPILER OPTIONS * * *
+.C[-P] ; absolute calls
+.C[-M] ; and no string merging, folks
+.C[-w-cln] ; no "constant is long" warnings
+.C[-w-par] ; no "parameter xxxx unused"
+.C[-w-rch] ; no "unreachable code"
+.C[-wsig] ; warn if significant digits may be lost
+=
+; * * * * List of modules * * * *
+pcstart.o
+cjpeg.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h,jversion.h)
+cdjpeg.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+rdswitch.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+rdppm.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+rdgif.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+rdtarga.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+rdbmp.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+rdrle.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+libjpeg.lib ; built by libjpeg.prj
+pcfltlib.lib ; floating point library
+; the float library can be omitted if you've turned off DCT_FLOAT_SUPPORTED
+pcstdlib.lib ; standard library
+pcextlib.lib ; extended library
diff --git a/jpeg-6c/makdjpeg.st b/jpeg-6c/makdjpeg.st
new file mode 100644
index 0000000..3226726
--- /dev/null
+++ b/jpeg-6c/makdjpeg.st
@@ -0,0 +1,38 @@
+; Project file for Independent JPEG Group's software
+;
+; This project file is for Atari ST/STE/TT systems using Pure C or Turbo C.
+; Thanks to Frank Moehle (Frank.Moehle at arbi.informatik.uni-oldenburg.de),
+; Dr. B. Setzepfandt (bernd at gina.uni-muenster.de),
+; and Guido Vollbeding (guivol at esc.de).
+;
+; To use this file, rename it to djpeg.prj.
+; If you are using Turbo C, change filenames beginning with "pc..." to "tc..."
+; Read installation instructions before trying to make the program!
+;
+;
+; * * * Output file * * *
+djpeg.ttp
+;
+; * * * COMPILER OPTIONS * * *
+.C[-P] ; absolute calls
+.C[-M] ; and no string merging, folks
+.C[-w-cln] ; no "constant is long" warnings
+.C[-w-par] ; no "parameter xxxx unused"
+.C[-w-rch] ; no "unreachable code"
+.C[-wsig] ; warn if significant digits may be lost
+=
+; * * * * List of modules * * * *
+pcstart.o
+djpeg.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h,jversion.h)
+cdjpeg.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+rdcolmap.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+wrppm.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+wrgif.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+wrtarga.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+wrbmp.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+wrrle.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+libjpeg.lib ; built by libjpeg.prj
+pcfltlib.lib ; floating point library
+; the float library can be omitted if you've turned off DCT_FLOAT_SUPPORTED
+pcstdlib.lib ; standard library
+pcextlib.lib ; extended library
diff --git a/jpeg-6c/makeapps.ds b/jpeg-6c/makeapps.ds
new file mode 100644
index 0000000..bedd038
--- /dev/null
+++ b/jpeg-6c/makeapps.ds
@@ -0,0 +1,828 @@
+# Microsoft Developer Studio Generated NMAKE File, Format Version 4.20
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Console Application" 0x0103
+
+!IF "$(CFG)" == ""
+CFG=cjpeg - Win32
+!MESSAGE No configuration specified. Defaulting to cjpeg - Win32.
+!ENDIF
+
+!IF "$(CFG)" != "cjpeg - Win32" && "$(CFG)" != "djpeg - Win32" &&\
+ "$(CFG)" != "jpegtran - Win32" && "$(CFG)" != "rdjpgcom - Win32" &&\
+ "$(CFG)" != "wrjpgcom - Win32"
+!MESSAGE Invalid configuration "$(CFG)" specified.
+!MESSAGE You can specify a configuration when running NMAKE on this makefile
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "apps.mak" CFG="cjpeg - Win32"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "cjpeg - Win32" (based on "Win32 (x86) Console Application")
+!MESSAGE "djpeg - Win32" (based on "Win32 (x86) Console Application")
+!MESSAGE "jpegtran - Win32" (based on "Win32 (x86) Console Application")
+!MESSAGE "rdjpgcom - Win32" (based on "Win32 (x86) Console Application")
+!MESSAGE "wrjpgcom - Win32" (based on "Win32 (x86) Console Application")
+!MESSAGE
+!ERROR An invalid configuration is specified.
+!ENDIF
+
+!IF "$(OS)" == "Windows_NT"
+NULL=
+!ELSE
+NULL=nul
+!ENDIF
+################################################################################
+# Begin Project
+# PROP Target_Last_Scanned "cjpeg - Win32"
+CPP=cl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "cjpeg - Win32"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "cjpeg\Release"
+# PROP BASE Intermediate_Dir "cjpeg\Release"
+# PROP BASE Target_Dir "cjpeg"
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "cjpeg\Release"
+# PROP Intermediate_Dir "cjpeg\Release"
+# PROP Target_Dir "cjpeg"
+OUTDIR=.\cjpeg\Release
+INTDIR=.\cjpeg\Release
+
+ALL : "$(OUTDIR)\cjpeg.exe"
+
+CLEAN :
+ - at erase "$(INTDIR)\cjpeg.obj"
+ - at erase "$(INTDIR)\rdppm.obj"
+ - at erase "$(INTDIR)\rdgif.obj"
+ - at erase "$(INTDIR)\rdtarga.obj"
+ - at erase "$(INTDIR)\rdrle.obj"
+ - at erase "$(INTDIR)\rdbmp.obj"
+ - at erase "$(INTDIR)\rdswitch.obj"
+ - at erase "$(INTDIR)\cdjpeg.obj"
+ - at erase "$(OUTDIR)\cjpeg.exe"
+
+"$(OUTDIR)" :
+ if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
+
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c
+# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c
+CPP_PROJ=/nologo /ML /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE"\
+ /Fp"$(INTDIR)/cjpeg.pch" /YX /Fo"$(INTDIR)/" /c
+CPP_OBJS=.\cjpeg\Release/
+CPP_SBRS=.\.
+# ADD BASE RSC /l 0x409 /d "NDEBUG"
+# ADD RSC /l 0x409 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+BSC32_FLAGS=/nologo /o"$(OUTDIR)/cjpeg.bsc"
+BSC32_SBRS= \
+
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+# ADD LINK32 Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+LINK32_FLAGS=Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib\
+ comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib\
+ odbc32.lib odbccp32.lib /nologo /subsystem:console /incremental:no\
+ /pdb:"$(OUTDIR)/cjpeg.pdb" /machine:I386 /out:"$(OUTDIR)/cjpeg.exe"
+LINK32_OBJS= \
+ "$(INTDIR)\cjpeg.obj" \
+ "$(INTDIR)\rdppm.obj" \
+ "$(INTDIR)\rdgif.obj" \
+ "$(INTDIR)\rdtarga.obj" \
+ "$(INTDIR)\rdrle.obj" \
+ "$(INTDIR)\rdbmp.obj" \
+ "$(INTDIR)\rdswitch.obj" \
+ "$(INTDIR)\cdjpeg.obj" \
+
+
+"$(OUTDIR)\cjpeg.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
+ $(LINK32) @<<
+ $(LINK32_FLAGS) $(LINK32_OBJS)
+<<
+
+!ELSEIF "$(CFG)" == "djpeg - Win32"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "djpeg\Release"
+# PROP BASE Intermediate_Dir "djpeg\Release"
+# PROP BASE Target_Dir "djpeg"
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "djpeg\Release"
+# PROP Intermediate_Dir "djpeg\Release"
+# PROP Target_Dir "djpeg"
+OUTDIR=.\djpeg\Release
+INTDIR=.\djpeg\Release
+
+ALL : "$(OUTDIR)\djpeg.exe"
+
+CLEAN :
+ - at erase "$(INTDIR)\djpeg.obj"
+ - at erase "$(INTDIR)\wrppm.obj"
+ - at erase "$(INTDIR)\wrgif.obj"
+ - at erase "$(INTDIR)\wrtarga.obj"
+ - at erase "$(INTDIR)\wrrle.obj"
+ - at erase "$(INTDIR)\wrbmp.obj"
+ - at erase "$(INTDIR)\rdcolmap.obj"
+ - at erase "$(INTDIR)\cdjpeg.obj"
+ - at erase "$(OUTDIR)\djpeg.exe"
+
+"$(OUTDIR)" :
+ if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
+
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c
+# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c
+CPP_PROJ=/nologo /ML /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE"\
+ /Fp"$(INTDIR)/djpeg.pch" /YX /Fo"$(INTDIR)/" /c
+CPP_OBJS=.\djpeg\Release/
+CPP_SBRS=.\.
+# ADD BASE RSC /l 0x409 /d "NDEBUG"
+# ADD RSC /l 0x409 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+BSC32_FLAGS=/nologo /o"$(OUTDIR)/djpeg.bsc"
+BSC32_SBRS= \
+
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+# ADD LINK32 Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+LINK32_FLAGS=Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib\
+ comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib\
+ odbc32.lib odbccp32.lib /nologo /subsystem:console /incremental:no\
+ /pdb:"$(OUTDIR)/djpeg.pdb" /machine:I386 /out:"$(OUTDIR)/djpeg.exe"
+LINK32_OBJS= \
+ "$(INTDIR)\djpeg.obj" \
+ "$(INTDIR)\wrppm.obj" \
+ "$(INTDIR)\wrgif.obj" \
+ "$(INTDIR)\wrtarga.obj" \
+ "$(INTDIR)\wrrle.obj" \
+ "$(INTDIR)\wrbmp.obj" \
+ "$(INTDIR)\rdcolmap.obj" \
+ "$(INTDIR)\cdjpeg.obj" \
+
+
+"$(OUTDIR)\djpeg.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
+ $(LINK32) @<<
+ $(LINK32_FLAGS) $(LINK32_OBJS)
+<<
+
+!ELSEIF "$(CFG)" == "jpegtran - Win32"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "jpegtran\Release"
+# PROP BASE Intermediate_Dir "jpegtran\Release"
+# PROP BASE Target_Dir "jpegtran"
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "jpegtran\Release"
+# PROP Intermediate_Dir "jpegtran\Release"
+# PROP Target_Dir "jpegtran"
+OUTDIR=.\jpegtran\Release
+INTDIR=.\jpegtran\Release
+
+ALL : "$(OUTDIR)\jpegtran.exe"
+
+CLEAN :
+ - at erase "$(INTDIR)\jpegtran.obj"
+ - at erase "$(INTDIR)\rdswitch.obj"
+ - at erase "$(INTDIR)\cdjpeg.obj"
+ - at erase "$(INTDIR)\transupp.obj"
+ - at erase "$(OUTDIR)\jpegtran.exe"
+
+"$(OUTDIR)" :
+ if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
+
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c
+# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c
+CPP_PROJ=/nologo /ML /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE"\
+ /Fp"$(INTDIR)/jpegtran.pch" /YX /Fo"$(INTDIR)/" /c
+CPP_OBJS=.\jpegtran\Release/
+CPP_SBRS=.\.
+# ADD BASE RSC /l 0x409 /d "NDEBUG"
+# ADD RSC /l 0x409 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+BSC32_FLAGS=/nologo /o"$(OUTDIR)/jpegtran.bsc"
+BSC32_SBRS= \
+
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+# ADD LINK32 Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+LINK32_FLAGS=Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib\
+ comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib\
+ odbc32.lib odbccp32.lib /nologo /subsystem:console /incremental:no\
+ /pdb:"$(OUTDIR)/jpegtran.pdb" /machine:I386 /out:"$(OUTDIR)/jpegtran.exe"
+LINK32_OBJS= \
+ "$(INTDIR)\jpegtran.obj" \
+ "$(INTDIR)\rdswitch.obj" \
+ "$(INTDIR)\cdjpeg.obj" \
+ "$(INTDIR)\transupp.obj" \
+
+
+"$(OUTDIR)\jpegtran.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
+ $(LINK32) @<<
+ $(LINK32_FLAGS) $(LINK32_OBJS)
+<<
+
+!ELSEIF "$(CFG)" == "rdjpgcom - Win32"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "rdjpgcom\Release"
+# PROP BASE Intermediate_Dir "rdjpgcom\Release"
+# PROP BASE Target_Dir "rdjpgcom"
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "rdjpgcom\Release"
+# PROP Intermediate_Dir "rdjpgcom\Release"
+# PROP Target_Dir "rdjpgcom"
+OUTDIR=.\rdjpgcom\Release
+INTDIR=.\rdjpgcom\Release
+
+ALL : "$(OUTDIR)\rdjpgcom.exe"
+
+CLEAN :
+ - at erase "$(INTDIR)\rdjpgcom.obj"
+ - at erase "$(OUTDIR)\rdjpgcom.exe"
+
+"$(OUTDIR)" :
+ if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
+
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c
+# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c
+CPP_PROJ=/nologo /ML /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE"\
+ /Fp"$(INTDIR)/rdjpgcom.pch" /YX /Fo"$(INTDIR)/" /c
+CPP_OBJS=.\rdjpgcom\Release/
+CPP_SBRS=.\.
+# ADD BASE RSC /l 0x409 /d "NDEBUG"
+# ADD RSC /l 0x409 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+BSC32_FLAGS=/nologo /o"$(OUTDIR)/rdjpgcom.bsc"
+BSC32_SBRS= \
+
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+# ADD LINK32 Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+LINK32_FLAGS=Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib\
+ comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib\
+ odbc32.lib odbccp32.lib /nologo /subsystem:console /incremental:no\
+ /pdb:"$(OUTDIR)/rdjpgcom.pdb" /machine:I386 /out:"$(OUTDIR)/rdjpgcom.exe"
+LINK32_OBJS= \
+ "$(INTDIR)\rdjpgcom.obj"
+
+"$(OUTDIR)\rdjpgcom.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
+ $(LINK32) @<<
+ $(LINK32_FLAGS) $(LINK32_OBJS)
+<<
+
+!ELSEIF "$(CFG)" == "wrjpgcom - Win32"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "wrjpgcom\Release"
+# PROP BASE Intermediate_Dir "wrjpgcom\Release"
+# PROP BASE Target_Dir "wrjpgcom"
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "wrjpgcom\Release"
+# PROP Intermediate_Dir "wrjpgcom\Release"
+# PROP Target_Dir "wrjpgcom"
+OUTDIR=.\wrjpgcom\Release
+INTDIR=.\wrjpgcom\Release
+
+ALL : "$(OUTDIR)\wrjpgcom.exe"
+
+CLEAN :
+ - at erase "$(INTDIR)\wrjpgcom.obj"
+ - at erase "$(OUTDIR)\wrjpgcom.exe"
+
+"$(OUTDIR)" :
+ if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
+
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c
+# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /YX /c
+CPP_PROJ=/nologo /ML /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE"\
+ /Fp"$(INTDIR)/wrjpgcom.pch" /YX /Fo"$(INTDIR)/" /c
+CPP_OBJS=.\wrjpgcom\Release/
+CPP_SBRS=.\.
+# ADD BASE RSC /l 0x409 /d "NDEBUG"
+# ADD RSC /l 0x409 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+BSC32_FLAGS=/nologo /o"$(OUTDIR)/wrjpgcom.bsc"
+BSC32_SBRS= \
+
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+# ADD LINK32 Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
+LINK32_FLAGS=Release\jpeg.lib kernel32.lib user32.lib gdi32.lib winspool.lib\
+ comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib\
+ odbc32.lib odbccp32.lib /nologo /subsystem:console /incremental:no\
+ /pdb:"$(OUTDIR)/wrjpgcom.pdb" /machine:I386 /out:"$(OUTDIR)/wrjpgcom.exe"
+LINK32_OBJS= \
+ "$(INTDIR)\wrjpgcom.obj"
+
+"$(OUTDIR)\wrjpgcom.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
+ $(LINK32) @<<
+ $(LINK32_FLAGS) $(LINK32_OBJS)
+<<
+
+!ENDIF
+
+.c{$(CPP_OBJS)}.obj:
+ $(CPP) $(CPP_PROJ) $<
+
+.cpp{$(CPP_OBJS)}.obj:
+ $(CPP) $(CPP_PROJ) $<
+
+.cxx{$(CPP_OBJS)}.obj:
+ $(CPP) $(CPP_PROJ) $<
+
+.c{$(CPP_SBRS)}.sbr:
+ $(CPP) $(CPP_PROJ) $<
+
+.cpp{$(CPP_SBRS)}.sbr:
+ $(CPP) $(CPP_PROJ) $<
+
+.cxx{$(CPP_SBRS)}.sbr:
+ $(CPP) $(CPP_PROJ) $<
+
+################################################################################
+# Begin Target
+
+# Name "cjpeg - Win32"
+
+!IF "$(CFG)" == "cjpeg - Win32"
+
+!ENDIF
+
+################################################################################
+# Begin Source File
+
+SOURCE="cjpeg.c"
+DEP_CPP_CJPEG=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+ "jversion.h"\
+
+
+"$(INTDIR)\cjpeg.obj" : $(SOURCE) $(DEP_CPP_CJPEG) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="cdjpeg.c"
+DEP_CPP_CDJPE=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\cdjpeg.obj" : $(SOURCE) $(DEP_CPP_CDJPE) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="rdswitch.c"
+DEP_CPP_RDSWI=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\rdswitch.obj" : $(SOURCE) $(DEP_CPP_RDSWI) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="rdppm.c"
+DEP_CPP_RDPPM=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\rdppm.obj" : $(SOURCE) $(DEP_CPP_RDPPM) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="rdgif.c"
+DEP_CPP_RDGIF=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\rdgif.obj" : $(SOURCE) $(DEP_CPP_RDGIF) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="rdtarga.c"
+DEP_CPP_RDTAR=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\rdtarga.obj" : $(SOURCE) $(DEP_CPP_RDTAR) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="rdbmp.c"
+DEP_CPP_RDBMP=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\rdbmp.obj" : $(SOURCE) $(DEP_CPP_RDBMP) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="rdrle.c"
+DEP_CPP_RDRLE=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\rdrle.obj" : $(SOURCE) $(DEP_CPP_RDRLE) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+# End Target
+################################################################################
+# Begin Target
+
+# Name "djpeg - Win32"
+
+!IF "$(CFG)" == "djpeg - Win32"
+
+!ENDIF
+
+################################################################################
+# Begin Source File
+
+SOURCE="djpeg.c"
+DEP_CPP_DJPEG=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+ "jversion.h"\
+
+
+"$(INTDIR)\djpeg.obj" : $(SOURCE) $(DEP_CPP_DJPEG) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="cdjpeg.c"
+DEP_CPP_CDJPE=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\cdjpeg.obj" : $(SOURCE) $(DEP_CPP_CDJPE) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="rdcolmap.c"
+DEP_CPP_RDCOL=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\rdcolmap.obj" : $(SOURCE) $(DEP_CPP_RDCOL) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="wrppm.c"
+DEP_CPP_WRPPM=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\wrppm.obj" : $(SOURCE) $(DEP_CPP_WRPPM) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="wrgif.c"
+DEP_CPP_WRGIF=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\wrgif.obj" : $(SOURCE) $(DEP_CPP_WRGIF) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="wrtarga.c"
+DEP_CPP_WRTAR=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\wrtarga.obj" : $(SOURCE) $(DEP_CPP_WRTAR) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="wrbmp.c"
+DEP_CPP_WRBMP=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\wrbmp.obj" : $(SOURCE) $(DEP_CPP_WRBMP) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="wrrle.c"
+DEP_CPP_WRRLE=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\wrrle.obj" : $(SOURCE) $(DEP_CPP_WRRLE) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+# End Target
+################################################################################
+# Begin Target
+
+# Name "jpegtran - Win32"
+
+!IF "$(CFG)" == "jpegtran - Win32"
+
+!ENDIF
+
+################################################################################
+# Begin Source File
+
+SOURCE="jpegtran.c"
+DEP_CPP_JPEGT=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+ "transupp.h"\
+ "jversion.h"\
+
+
+"$(INTDIR)\jpegtran.obj" : $(SOURCE) $(DEP_CPP_JPEGT) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="cdjpeg.c"
+DEP_CPP_CDJPE=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\cdjpeg.obj" : $(SOURCE) $(DEP_CPP_CDJPE) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="rdswitch.c"
+DEP_CPP_RDSWI=\
+ "cdjpeg.h"\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+ "cderror.h"\
+
+
+"$(INTDIR)\rdswitch.obj" : $(SOURCE) $(DEP_CPP_RDSWI) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="transupp.c"
+DEP_CPP_TRANS=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "transupp.h"\
+
+
+"$(INTDIR)\transupp.obj" : $(SOURCE) $(DEP_CPP_TRANS) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+# End Target
+################################################################################
+# Begin Target
+
+# Name "rdjpgcom - Win32"
+
+!IF "$(CFG)" == "rdjpgcom - Win32"
+
+!ENDIF
+
+################################################################################
+# Begin Source File
+
+SOURCE="rdjpgcom.c"
+DEP_CPP_RDJPG=\
+ "jinclude.h"\
+ "jconfig.h"\
+
+
+"$(INTDIR)\rdjpgcom.obj" : $(SOURCE) $(DEP_CPP_RDJPG) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+# End Target
+################################################################################
+# Begin Target
+
+# Name "wrjpgcom - Win32"
+
+!IF "$(CFG)" == "wrjpgcom - Win32"
+
+!ENDIF
+
+################################################################################
+# Begin Source File
+
+SOURCE="wrjpgcom.c"
+DEP_CPP_WRJPG=\
+ "jinclude.h"\
+ "jconfig.h"\
+
+
+"$(INTDIR)\wrjpgcom.obj" : $(SOURCE) $(DEP_CPP_WRJPG) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+# End Target
+# End Project
+################################################################################
+
diff --git a/jpeg-6c/makefile.ansi b/jpeg-6c/makefile.ansi
new file mode 100644
index 0000000..8291913
--- /dev/null
+++ b/jpeg-6c/makefile.ansi
@@ -0,0 +1,214 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is suitable for Unix-like systems with ANSI-capable compilers.
+# If you have a non-ANSI compiler, makefile.unix is a better starting point.
+
+# Read installation instructions before saying "make" !!
+
+# The name of your C compiler:
+CC= cc
+
+# You may need to adjust these cc options:
+CFLAGS= -O
+# Generally, we recommend defining any configuration symbols in jconfig.h,
+# NOT via -D switches here.
+
+# Link-time cc options:
+LDFLAGS=
+
+# To link any special libraries, add the necessary -l commands here.
+LDLIBS=
+
+# Put here the object file name for the correct system-dependent memory
+# manager file. For Unix this is usually jmemnobs.o, but you may want
+# to use jmemansi.o or jmemname.o if you have limited swap space.
+SYSDEPMEM= jmemnobs.o
+
+# miscellaneous OS-dependent stuff
+# linker
+LN= $(CC)
+# file deletion command
+RM= rm -f
+# library (.a) file creation command
+AR= ar rc
+# second step in .a creation (use "touch" if not needed)
+AR2= ranlib
+
+# End of configurable options.
+
+
+# source files: JPEG library proper
+LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jchuff.c \
+ jcinit.c jcmainct.c jcmarker.c jcmaster.c jcomapi.c jcparam.c \
+ jcphuff.c jcprepct.c jcsample.c jctrans.c jdapimin.c jdapistd.c \
+ jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c jdhuff.c \
+ jdinput.c jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c \
+ jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c jfdctfst.c \
+ jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c jquant1.c \
+ jquant2.c jutils.c jmemmgr.c
+# memmgr back ends: compile only one of these into a working library
+SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \
+ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+# files included by source files
+INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h \
+ jpegint.h jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
+# documentation, test, and support files
+DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
+ coderules.doc filelist.doc change.log
+MKFILES= configure makefile.cfg makefile.ansi makefile.unix makefile.bcc \
+ makefile.mc6 makefile.dj makefile.wat makefile.vc makelib.ds \
+ makeapps.ds makeproj.mac makcjpeg.st makdjpeg.st makljpeg.st \
+ maktjpeg.st makefile.manx makefile.sas makefile.mms makefile.vms \
+ makvms.opt
+CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \
+ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \
+ jconfig.vms
+CONFIGUREFILES= config.guess config.sub install-sh ltconfig ltmain.sh
+OTHERFILES= jconfig.doc ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm
+TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \
+ testimgp.jpg
+DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+# library object files common to compression and decompression
+COMOBJECTS= jcomapi.o jutils.o jerror.o jmemmgr.o $(SYSDEPMEM)
+# compression library object files
+CLIBOBJECTS= jcapimin.o jcapistd.o jctrans.o jcparam.o jdatadst.o jcinit.o \
+ jcmaster.o jcmarker.o jcmainct.o jcprepct.o jccoefct.o jccolor.o \
+ jcsample.o jchuff.o jcphuff.o jcdctmgr.o jfdctfst.o jfdctflt.o \
+ jfdctint.o
+# decompression library object files
+DLIBOBJECTS= jdapimin.o jdapistd.o jdtrans.o jdatasrc.o jdmaster.o \
+ jdinput.o jdmarker.o jdhuff.o jdphuff.o jdmainct.o jdcoefct.o \
+ jdpostct.o jddctmgr.o jidctfst.o jidctflt.o jidctint.o jidctred.o \
+ jdsample.o jdcolor.o jquant1.o jquant2.o jdmerge.o
+# These objectfiles are included in libjpeg.a
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+# object files for sample applications (excluding library files)
+COBJECTS= cjpeg.o rdppm.o rdgif.o rdtarga.o rdrle.o rdbmp.o rdswitch.o \
+ cdjpeg.o
+DOBJECTS= djpeg.o wrppm.o wrgif.o wrtarga.o wrrle.o wrbmp.o rdcolmap.o \
+ cdjpeg.o
+TROBJECTS= jpegtran.o rdswitch.o cdjpeg.o transupp.o
+
+
+all: libjpeg.a cjpeg djpeg jpegtran rdjpgcom wrjpgcom
+
+libjpeg.a: $(LIBOBJECTS)
+ $(RM) libjpeg.a
+ $(AR) libjpeg.a $(LIBOBJECTS)
+ $(AR2) libjpeg.a
+
+cjpeg: $(COBJECTS) libjpeg.a
+ $(LN) $(LDFLAGS) -o cjpeg $(COBJECTS) libjpeg.a $(LDLIBS)
+
+djpeg: $(DOBJECTS) libjpeg.a
+ $(LN) $(LDFLAGS) -o djpeg $(DOBJECTS) libjpeg.a $(LDLIBS)
+
+jpegtran: $(TROBJECTS) libjpeg.a
+ $(LN) $(LDFLAGS) -o jpegtran $(TROBJECTS) libjpeg.a $(LDLIBS)
+
+rdjpgcom: rdjpgcom.o
+ $(LN) $(LDFLAGS) -o rdjpgcom rdjpgcom.o $(LDLIBS)
+
+wrjpgcom: wrjpgcom.o
+ $(LN) $(LDFLAGS) -o wrjpgcom wrjpgcom.o $(LDLIBS)
+
+jconfig.h: jconfig.doc
+ echo You must prepare a system-dependent jconfig.h file.
+ echo Please read the installation directions in install.doc.
+ exit 1
+
+clean:
+ $(RM) *.o cjpeg djpeg jpegtran libjpeg.a rdjpgcom wrjpgcom
+ $(RM) core testout*
+
+test: cjpeg djpeg jpegtran
+ $(RM) testout*
+ ./djpeg -dct int -ppm -outfile testout.ppm testorig.jpg
+ ./djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg
+ ./cjpeg -dct int -outfile testout.jpg testimg.ppm
+ ./djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
+ ./cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
+ ./jpegtran -outfile testoutt.jpg testprog.jpg
+ cmp testimg.ppm testout.ppm
+ cmp testimg.bmp testout.bmp
+ cmp testimg.jpg testout.jpg
+ cmp testimg.ppm testoutp.ppm
+ cmp testimgp.jpg testoutp.jpg
+ cmp testorig.jpg testoutt.jpg
+
+
+jcapimin.o: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcapistd.o: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccoefct.o: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccolor.o: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcdctmgr.o: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jchuff.o: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcinit.o: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmainct.o: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmarker.o: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmaster.o: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcomapi.o: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcparam.o: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcphuff.o: jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcprepct.o: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcsample.o: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jctrans.o: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapimin.o: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapistd.o: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdatadst.o: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdatasrc.o: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdcoefct.o: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdcolor.o: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jddctmgr.o: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jdhuff.o: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdinput.o: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmainct.o: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmarker.o: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmaster.o: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmerge.o: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdphuff.o: jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdpostct.o: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdsample.o: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdtrans.o: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jerror.o: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+jfdctflt.o: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctfst.o: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctint.o: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctflt.o: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctfst.o: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctint.o: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctred.o: jidctred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jquant1.o: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jquant2.o: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jutils.o: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jmemmgr.o: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemansi.o: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemname.o: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemnobs.o: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemdos.o: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemmac.o: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+cjpeg.o: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+djpeg.o: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+jpegtran.o: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
+rdjpgcom.o: rdjpgcom.c jinclude.h jconfig.h
+wrjpgcom.o: wrjpgcom.c jinclude.h jconfig.h
+cdjpeg.o: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdcolmap.o: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdswitch.o: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+transupp.o: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
+rdppm.o: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrppm.o: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdgif.o: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrgif.o: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdtarga.o: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrtarga.o: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdbmp.o: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrbmp.o: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdrle.o: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrrle.o: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
diff --git a/jpeg-6c/makefile.bcc b/jpeg-6c/makefile.bcc
new file mode 100644
index 0000000..a1cfcde
--- /dev/null
+++ b/jpeg-6c/makefile.bcc
@@ -0,0 +1,285 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is suitable for Borland C on MS-DOS or OS/2.
+# It works with Borland C++ for DOS, revision 3.0 or later,
+# and has been tested with Borland C++ for OS/2.
+# Watch out for optimization bugs in the OS/2 compilers --- see notes below!
+# Thanks to Tom Wright and Ge' Weijers (original DOS) and
+# Ken Porter (OS/2) for this file.
+
+# Read installation instructions before saying "make" !!
+
+# Are we under DOS or OS/2?
+!if !$d(DOS) && !$d(OS2)
+!if $d(__OS2__)
+OS2=1
+!else
+DOS=1
+!endif
+!endif
+
+# The name of your C compiler:
+CC= bcc
+
+# You may need to adjust these cc options:
+!if $d(DOS)
+CFLAGS= -O2 -mm -w-par -w-stu -w-ccc -w-rch
+!else
+CFLAGS= -O1 -w-par -w-stu -w-ccc -w-rch
+!endif
+# -O2 enables full code optimization (for pre-3.0 Borland C++, use -O -G -Z).
+# -O2 is buggy in Borland OS/2 C++ revision 2.0, so use -O1 there for now.
+# If you have Borland OS/2 C++ revision 1.0, use -O or no optimization at all.
+# -mm selects medium memory model (near data, far code pointers; DOS only!)
+# -w-par suppresses warnings about unused function parameters
+# -w-stu suppresses warnings about incomplete structures
+# -w-ccc suppresses warnings about compile-time-constant conditions
+# -w-rch suppresses warnings about unreachable code
+# Generally, we recommend defining any configuration symbols in jconfig.h,
+# NOT via -D switches here.
+
+# Link-time cc options:
+!if $d(DOS)
+LDFLAGS= -mm
+# memory model option here must match CFLAGS!
+!else
+LDFLAGS=
+# -lai full-screen app
+# -lc case-significant link
+!endif
+
+# Put here the object file name for the correct system-dependent memory
+# manager file.
+# For DOS, we recommend jmemdos.c and jmemdosa.asm.
+# For OS/2, we recommend jmemnobs.c (flat memory!)
+# SYSDEPMEMLIB must list the same files with "+" signs for the librarian.
+!if $d(DOS)
+SYSDEPMEM= jmemdos.obj jmemdosa.obj
+SYSDEPMEMLIB= +jmemdos.obj +jmemdosa.obj
+!else
+SYSDEPMEM= jmemnobs.obj
+SYSDEPMEMLIB= +jmemnobs.obj
+!endif
+
+# End of configurable options.
+
+
+# source files: JPEG library proper
+LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jchuff.c \
+ jcinit.c jcmainct.c jcmarker.c jcmaster.c jcomapi.c jcparam.c \
+ jcphuff.c jcprepct.c jcsample.c jctrans.c jdapimin.c jdapistd.c \
+ jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c jdhuff.c \
+ jdinput.c jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c \
+ jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c jfdctfst.c \
+ jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c jquant1.c \
+ jquant2.c jutils.c jmemmgr.c
+# memmgr back ends: compile only one of these into a working library
+SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \
+ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+# files included by source files
+INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h \
+ jpegint.h jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
+# documentation, test, and support files
+DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
+ coderules.doc filelist.doc change.log
+MKFILES= configure makefile.cfg makefile.ansi makefile.unix makefile.bcc \
+ makefile.mc6 makefile.dj makefile.wat makefile.vc makelib.ds \
+ makeapps.ds makeproj.mac makcjpeg.st makdjpeg.st makljpeg.st \
+ maktjpeg.st makefile.manx makefile.sas makefile.mms makefile.vms \
+ makvms.opt
+CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \
+ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \
+ jconfig.vms
+CONFIGUREFILES= config.guess config.sub install-sh ltconfig ltmain.sh
+OTHERFILES= jconfig.doc ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm
+TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \
+ testimgp.jpg
+DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+# library object files common to compression and decompression
+COMOBJECTS= jcomapi.obj jutils.obj jerror.obj jmemmgr.obj $(SYSDEPMEM)
+# compression library object files
+CLIBOBJECTS= jcapimin.obj jcapistd.obj jctrans.obj jcparam.obj jdatadst.obj \
+ jcinit.obj jcmaster.obj jcmarker.obj jcmainct.obj jcprepct.obj \
+ jccoefct.obj jccolor.obj jcsample.obj jchuff.obj jcphuff.obj \
+ jcdctmgr.obj jfdctfst.obj jfdctflt.obj jfdctint.obj
+# decompression library object files
+DLIBOBJECTS= jdapimin.obj jdapistd.obj jdtrans.obj jdatasrc.obj \
+ jdmaster.obj jdinput.obj jdmarker.obj jdhuff.obj jdphuff.obj \
+ jdmainct.obj jdcoefct.obj jdpostct.obj jddctmgr.obj jidctfst.obj \
+ jidctflt.obj jidctint.obj jidctred.obj jdsample.obj jdcolor.obj \
+ jquant1.obj jquant2.obj jdmerge.obj
+# These objectfiles are included in libjpeg.lib
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+# object files for sample applications (excluding library files)
+COBJECTS= cjpeg.obj rdppm.obj rdgif.obj rdtarga.obj rdrle.obj rdbmp.obj \
+ rdswitch.obj cdjpeg.obj
+DOBJECTS= djpeg.obj wrppm.obj wrgif.obj wrtarga.obj wrrle.obj wrbmp.obj \
+ rdcolmap.obj cdjpeg.obj
+TROBJECTS= jpegtran.obj rdswitch.obj cdjpeg.obj transupp.obj
+
+
+all: libjpeg.lib cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe
+
+libjpeg.lib: $(LIBOBJECTS)
+ - del libjpeg.lib
+ tlib libjpeg.lib /E /C @&&|
++jcapimin.obj +jcapistd.obj +jctrans.obj +jcparam.obj +jdatadst.obj &
++jcinit.obj +jcmaster.obj +jcmarker.obj +jcmainct.obj +jcprepct.obj &
++jccoefct.obj +jccolor.obj +jcsample.obj +jchuff.obj +jcphuff.obj &
++jcdctmgr.obj +jfdctfst.obj +jfdctflt.obj +jfdctint.obj +jdapimin.obj &
++jdapistd.obj +jdtrans.obj +jdatasrc.obj +jdmaster.obj +jdinput.obj &
++jdmarker.obj +jdhuff.obj +jdphuff.obj +jdmainct.obj +jdcoefct.obj &
++jdpostct.obj +jddctmgr.obj +jidctfst.obj +jidctflt.obj +jidctint.obj &
++jidctred.obj +jdsample.obj +jdcolor.obj +jquant1.obj +jquant2.obj &
++jdmerge.obj +jcomapi.obj +jutils.obj +jerror.obj +jmemmgr.obj &
+$(SYSDEPMEMLIB)
+|
+
+cjpeg.exe: $(COBJECTS) libjpeg.lib
+ $(CC) $(LDFLAGS) -ecjpeg.exe $(COBJECTS) libjpeg.lib
+
+djpeg.exe: $(DOBJECTS) libjpeg.lib
+ $(CC) $(LDFLAGS) -edjpeg.exe $(DOBJECTS) libjpeg.lib
+
+jpegtran.exe: $(TROBJECTS) libjpeg.lib
+ $(CC) $(LDFLAGS) -ejpegtran.exe $(TROBJECTS) libjpeg.lib
+
+rdjpgcom.exe: rdjpgcom.c
+!if $d(DOS)
+ $(CC) -ms -O rdjpgcom.c
+!else
+ $(CC) $(CFLAGS) rdjpgcom.c
+!endif
+
+# On DOS, wrjpgcom needs large model so it can malloc a 64K chunk
+wrjpgcom.exe: wrjpgcom.c
+!if $d(DOS)
+ $(CC) -ml -O wrjpgcom.c
+!else
+ $(CC) $(CFLAGS) wrjpgcom.c
+!endif
+
+# This "{}" syntax allows Borland Make to "batch" source files.
+# In this way, each run of the compiler can build many modules.
+.c.obj:
+ $(CC) $(CFLAGS) -c{ $<}
+
+jconfig.h: jconfig.doc
+ echo You must prepare a system-dependent jconfig.h file.
+ echo Please read the installation directions in install.doc.
+ exit 1
+
+clean:
+ - del *.obj
+ - del libjpeg.lib
+ - del cjpeg.exe
+ - del djpeg.exe
+ - del jpegtran.exe
+ - del rdjpgcom.exe
+ - del wrjpgcom.exe
+ - del testout*.*
+
+test: cjpeg.exe djpeg.exe jpegtran.exe
+ - del testout*.*
+ djpeg -dct int -ppm -outfile testout.ppm testorig.jpg
+ djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg
+ cjpeg -dct int -outfile testout.jpg testimg.ppm
+ djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
+ cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
+ jpegtran -outfile testoutt.jpg testprog.jpg
+!if $d(DOS)
+ fc /b testimg.ppm testout.ppm
+ fc /b testimg.bmp testout.bmp
+ fc /b testimg.jpg testout.jpg
+ fc /b testimg.ppm testoutp.ppm
+ fc /b testimgp.jpg testoutp.jpg
+ fc /b testorig.jpg testoutt.jpg
+!else
+ echo n > n.tmp
+ comp testimg.ppm testout.ppm < n.tmp
+ comp testimg.bmp testout.bmp < n.tmp
+ comp testimg.jpg testout.jpg < n.tmp
+ comp testimg.ppm testoutp.ppm < n.tmp
+ comp testimgp.jpg testoutp.jpg < n.tmp
+ comp testorig.jpg testoutt.jpg < n.tmp
+ del n.tmp
+!endif
+
+
+jcapimin.obj: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcapistd.obj: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccoefct.obj: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccolor.obj: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcdctmgr.obj: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jchuff.obj: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcinit.obj: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmainct.obj: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmarker.obj: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmaster.obj: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcomapi.obj: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcparam.obj: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcphuff.obj: jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcprepct.obj: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcsample.obj: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jctrans.obj: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapimin.obj: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapistd.obj: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdatadst.obj: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdatasrc.obj: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdcoefct.obj: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdcolor.obj: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jddctmgr.obj: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jdhuff.obj: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdinput.obj: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmainct.obj: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmarker.obj: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmaster.obj: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmerge.obj: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdphuff.obj: jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdpostct.obj: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdsample.obj: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdtrans.obj: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jerror.obj: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+jfdctflt.obj: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctfst.obj: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctint.obj: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctflt.obj: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctfst.obj: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctint.obj: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctred.obj: jidctred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jquant1.obj: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jquant2.obj: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jutils.obj: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jmemmgr.obj: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemansi.obj: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemname.obj: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemnobs.obj: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemdos.obj: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemmac.obj: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+cjpeg.obj: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+djpeg.obj: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+jpegtran.obj: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
+rdjpgcom.obj: rdjpgcom.c jinclude.h jconfig.h
+wrjpgcom.obj: wrjpgcom.c jinclude.h jconfig.h
+cdjpeg.obj: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdcolmap.obj: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdswitch.obj: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+transupp.obj: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
+rdppm.obj: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrppm.obj: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdgif.obj: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrgif.obj: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdtarga.obj: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrtarga.obj: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdbmp.obj: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrbmp.obj: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdrle.obj: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrrle.obj: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+jmemdosa.obj: jmemdosa.asm
+ tasm /mx jmemdosa.asm
diff --git a/jpeg-6c/makefile.cfg b/jpeg-6c/makefile.cfg
new file mode 100644
index 0000000..4e323f1
--- /dev/null
+++ b/jpeg-6c/makefile.cfg
@@ -0,0 +1,344 @@
+# Makefile for Independent JPEG Group's software
+
+# makefile.cfg is edited by configure to produce a custom Makefile.
+
+# Read installation instructions before saying "make" !!
+
+# For compiling with source and object files in different directories.
+srcdir = @srcdir@
+VPATH = @srcdir@
+
+# Where to install the programs and man pages.
+prefix = @prefix@
+exec_prefix = @exec_prefix@
+bindir = $(exec_prefix)/bin
+libdir = $(exec_prefix)/lib
+includedir = $(prefix)/include
+binprefix =
+manprefix =
+manext = 1
+mandir = $(prefix)/man/man$(manext)
+
+# The name of your C compiler:
+CC= @CC@
+
+# You may need to adjust these cc options:
+CFLAGS= @CFLAGS@ @CPPFLAGS@ @INCLUDEFLAGS@
+# Generally, we recommend defining any configuration symbols in jconfig.h,
+# NOT via -D switches here.
+# However, any special defines for ansi2knr.c may be included here:
+ANSI2KNRFLAGS= @ANSI2KNRFLAGS@
+
+# Link-time cc options:
+LDFLAGS= @LDFLAGS@
+
+# To link any special libraries, add the necessary -l commands here.
+LDLIBS= @LIBS@
+
+# If using GNU libtool, LIBTOOL references it; if not, LIBTOOL is empty.
+LIBTOOL = @LIBTOOL@
+# $(O) expands to "lo" if using libtool, plain "o" if not.
+# Similarly, $(A) expands to "la" or "a".
+O = @O@
+A = @A@
+
+# Library version ID; libtool uses this for the shared library version number.
+# Note: we suggest this match the macro of the same name in jpeglib.h.
+JPEG_LIB_VERSION = @JPEG_LIB_VERSION@
+
+# Put here the object file name for the correct system-dependent memory
+# manager file. For Unix this is usually jmemnobs.o, but you may want
+# to use jmemansi.o or jmemname.o if you have limited swap space.
+SYSDEPMEM= @MEMORYMGR@
+
+# miscellaneous OS-dependent stuff
+SHELL= /bin/sh
+# linker
+LN= @LN@
+# file deletion command
+RM= rm -f
+# directory creation command
+MKDIR= mkdir
+# library (.a) file creation command
+AR= ar rc
+# second step in .a creation (use "touch" if not needed)
+AR2= @RANLIB@
+# installation program
+INSTALL= @INSTALL@
+INSTALL_PROGRAM= @INSTALL_PROGRAM@
+INSTALL_LIB= @INSTALL_LIB@
+INSTALL_DATA= @INSTALL_DATA@
+
+# End of configurable options.
+
+
+# source files: JPEG library proper
+LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jcdiffct.c \
+ jchuff.c jcinit.c jclhuff.c jclossls.c jclossy.c jcmainct.c \
+ jcmarker.c jcmaster.c jcodec.c jcomapi.c jcparam.c jcphuff.c jcpred.c \
+ jcprepct.c jcsample.c jcscale.c jcshuff.c jctrans.c jdapimin.c \
+ jdapistd.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c \
+ jddiffct.c jdhuff.c jdinput.c jdlhuff.c jdlossls.c jdlossy.c \
+ jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c jdpostct.c \
+ jdpred.c jdsample.c jdscale.c jdshuff.c jdtrans.c jerror.c jfdctflt.c \
+ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c \
+ jquant1.c jquant2.c jutils.c jmemmgr.c
+# memmgr back ends: compile only one of these into a working library
+SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \
+ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+# files included by source files
+INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jlossls.h jlossy.h \
+ jmemsys.h jmorecfg.h jpegint.h jpeglib.h jversion.h cdjpeg.h \
+ cderror.h transupp.h
+# documentation, test, and support files
+DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
+ coderules.doc filelist.doc change.log
+MKFILES= configure makefile.cfg makefile.ansi makefile.unix makefile.bcc \
+ makefile.mc6 makefile.dj makefile.wat makefile.vc makelib.ds \
+ makeapps.ds makeproj.mac makcjpeg.st makdjpeg.st makljpeg.st \
+ maktjpeg.st makefile.manx makefile.sas makefile.mms makefile.vms \
+ makvms.opt
+CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \
+ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \
+ jconfig.vms
+CONFIGUREFILES= config.guess config.sub install-sh ltconfig ltmain.sh
+OTHERFILES= jconfig.doc ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm
+TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \
+ testimgp.jpg
+DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+# library object files common to compression and decompression
+COMOBJECTS= jcomapi.$(O) jcodec.$(O) jutils.$(O) jerror.$(O) jmemmgr.$(O) \
+ $(SYSDEPMEM)
+# compression library object files
+CLIBOBJECTS= jcapimin.$(O) jcapistd.$(O) jctrans.$(O) jcparam.$(O) \
+ jdatadst.$(O) jcinit.$(O) jcmaster.$(O) jcmarker.$(O) jcmainct.$(O) \
+ jcprepct.$(O) jclossls.$(O) jclossy.$(O) jccoefct.$(O) jccolor.$(O) \
+ jcsample.$(O) jchuff.$(O) jcphuff.$(O) jcshuff.$(O) jclhuff.$(O) \
+ jcpred.$(O) jcscale.$(O) jcdiffct.$(O) jcdctmgr.$(O) jfdctfst.$(O) \
+ jfdctflt.$(O) jfdctint.$(O)
+# decompression library object files
+DLIBOBJECTS= jdapimin.$(O) jdapistd.$(O) jdtrans.$(O) jdatasrc.$(O) \
+ jdmaster.$(O) jdinput.$(O) jdmarker.$(O) jdlossls.$(O) jdlossy.$(O) \
+ jdhuff.$(O) jdlhuff.$(O) jdphuff.$(O) jdshuff.$(O) jdpred.$(O) \
+ jdscale.$(O) jddiffct.$(O) jdmainct.$(O) jdcoefct.$(O) jdpostct.$(O) \
+ jddctmgr.$(O) jidctfst.$(O) jidctflt.$(O) jidctint.$(O) jidctred.$(O) \
+ jdsample.$(O) jdcolor.$(O) jquant1.$(O) jquant2.$(O) jdmerge.$(O)
+# These objectfiles are included in libjpeg.a
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+# object files for sample applications (excluding library files)
+COBJECTS= cjpeg.$(O) rdppm.$(O) rdgif.$(O) rdtarga.$(O) rdrle.$(O) \
+ rdbmp.$(O) rdswitch.$(O) cdjpeg.$(O)
+DOBJECTS= djpeg.$(O) wrppm.$(O) wrgif.$(O) wrtarga.$(O) wrrle.$(O) \
+ wrbmp.$(O) rdcolmap.$(O) cdjpeg.$(O)
+TROBJECTS= jpegtran.$(O) rdswitch.$(O) cdjpeg.$(O) transupp.$(O)
+
+
+all: @A2K_DEPS@ libjpeg.$(A) cjpeg djpeg jpegtran rdjpgcom wrjpgcom
+
+# Special compilation rules to support ansi2knr and libtool.
+.SUFFIXES: .lo .la
+
+# How to compile with libtool.
+ at COM_LT@.c.lo:
+ at COM_LT@ $(LIBTOOL) --mode=compile $(CC) $(CFLAGS) -c $(srcdir)/$*.c
+
+# How to use ansi2knr, when not using libtool.
+ at COM_A2K@.c.o:
+ at COM_A2K@ ./ansi2knr $(srcdir)/$*.c knr/$*.c
+ at COM_A2K@ $(CC) $(CFLAGS) -c knr/$*.c
+ at COM_A2K@ $(RM) knr/$*.c
+
+# How to use ansi2knr AND libtool.
+ at COM_A2K@.c.lo:
+ at COM_A2K@ ./ansi2knr $(srcdir)/$*.c knr/$*.c
+ at COM_A2K@ $(LIBTOOL) --mode=compile $(CC) $(CFLAGS) -c knr/$*.c
+ at COM_A2K@ $(RM) knr/$*.c
+
+ansi2knr: ansi2knr.c
+ $(CC) $(CFLAGS) $(ANSI2KNRFLAGS) -o ansi2knr $(srcdir)/ansi2knr.c
+ $(MKDIR) knr
+
+# the library:
+
+# without libtool:
+libjpeg.a: @A2K_DEPS@ $(LIBOBJECTS)
+ $(RM) libjpeg.a
+ $(AR) libjpeg.a $(LIBOBJECTS)
+ $(AR2) libjpeg.a
+
+# with libtool:
+libjpeg.la: @A2K_DEPS@ $(LIBOBJECTS)
+ $(LIBTOOL) --mode=link $(CC) -o libjpeg.la $(LIBOBJECTS) \
+ -rpath $(libdir) -version-info $(JPEG_LIB_VERSION)
+
+# sample programs:
+
+cjpeg: $(COBJECTS) libjpeg.$(A)
+ $(LN) $(LDFLAGS) -o cjpeg $(COBJECTS) libjpeg.$(A) $(LDLIBS)
+
+djpeg: $(DOBJECTS) libjpeg.$(A)
+ $(LN) $(LDFLAGS) -o djpeg $(DOBJECTS) libjpeg.$(A) $(LDLIBS)
+
+jpegtran: $(TROBJECTS) libjpeg.$(A)
+ $(LN) $(LDFLAGS) -o jpegtran $(TROBJECTS) libjpeg.$(A) $(LDLIBS)
+
+rdjpgcom: rdjpgcom.$(O)
+ $(LN) $(LDFLAGS) -o rdjpgcom rdjpgcom.$(O) $(LDLIBS)
+
+wrjpgcom: wrjpgcom.$(O)
+ $(LN) $(LDFLAGS) -o wrjpgcom wrjpgcom.$(O) $(LDLIBS)
+
+# Installation rules:
+
+install: cjpeg djpeg jpegtran rdjpgcom wrjpgcom @FORCE_INSTALL_LIB@
+ $(INSTALL_PROGRAM) cjpeg $(bindir)/$(binprefix)cjpeg
+ $(INSTALL_PROGRAM) djpeg $(bindir)/$(binprefix)djpeg
+ $(INSTALL_PROGRAM) jpegtran $(bindir)/$(binprefix)jpegtran
+ $(INSTALL_PROGRAM) rdjpgcom $(bindir)/$(binprefix)rdjpgcom
+ $(INSTALL_PROGRAM) wrjpgcom $(bindir)/$(binprefix)wrjpgcom
+ $(INSTALL_DATA) $(srcdir)/cjpeg.1 $(mandir)/$(manprefix)cjpeg.$(manext)
+ $(INSTALL_DATA) $(srcdir)/djpeg.1 $(mandir)/$(manprefix)djpeg.$(manext)
+ $(INSTALL_DATA) $(srcdir)/jpegtran.1 $(mandir)/$(manprefix)jpegtran.$(manext)
+ $(INSTALL_DATA) $(srcdir)/rdjpgcom.1 $(mandir)/$(manprefix)rdjpgcom.$(manext)
+ $(INSTALL_DATA) $(srcdir)/wrjpgcom.1 $(mandir)/$(manprefix)wrjpgcom.$(manext)
+
+install-lib: libjpeg.$(A) install-headers
+ $(INSTALL_LIB) libjpeg.$(A) $(libdir)/$(binprefix)libjpeg.$(A)
+
+install-headers: jconfig.h
+ $(INSTALL_DATA) jconfig.h $(includedir)/jconfig.h
+ $(INSTALL_DATA) $(srcdir)/jpeglib.h $(includedir)/jpeglib.h
+ $(INSTALL_DATA) $(srcdir)/jmorecfg.h $(includedir)/jmorecfg.h
+ $(INSTALL_DATA) $(srcdir)/jerror.h $(includedir)/jerror.h
+
+clean:
+ $(RM) *.o *.lo libjpeg.a libjpeg.la
+ $(RM) cjpeg djpeg jpegtran rdjpgcom wrjpgcom
+ $(RM) ansi2knr core testout* config.log config.status
+ $(RM) -r knr .libs _libs
+
+distclean: clean
+ $(RM) Makefile jconfig.h libtool config.cache
+
+test: cjpeg djpeg jpegtran
+ $(RM) testout*
+ ./djpeg -dct int -ppm -outfile testout.ppm $(srcdir)/testorig.jpg
+ ./djpeg -dct int -bmp -colors 256 -outfile testout.bmp $(srcdir)/testorig.jpg
+ ./cjpeg -dct int -outfile testout.jpg $(srcdir)/testimg.ppm
+ ./djpeg -dct int -ppm -outfile testoutp.ppm $(srcdir)/testprog.jpg
+ ./cjpeg -dct int -progressive -opt -outfile testoutp.jpg $(srcdir)/testimg.ppm
+ ./jpegtran -outfile testoutt.jpg $(srcdir)/testprog.jpg
+ ./djpeg -ppm -outfile testoutl.ppm $(srcdir)/testimgl.jpg
+ ./cjpeg -lossless 4,1 -outfile testoutl.jpg $(srcdir)/testimg.ppm
+ cmp $(srcdir)/testimg.ppm testout.ppm
+ cmp $(srcdir)/testimg.bmp testout.bmp
+ cmp $(srcdir)/testimg.jpg testout.jpg
+ cmp $(srcdir)/testimg.ppm testoutp.ppm
+ cmp $(srcdir)/testimgp.jpg testoutp.jpg
+ cmp $(srcdir)/testorig.jpg testoutt.jpg
+ cmp $(srcdir)/testimgl.ppm testoutl.ppm
+ cmp $(srcdir)/testimgl.jpg testoutl.jpg
+
+check: test
+
+# Mistake catcher:
+
+jconfig.h: jconfig.doc
+ echo You must prepare a system-dependent jconfig.h file.
+ echo Please read the installation directions in install.doc.
+ exit 1
+
+# GNU Make likes to know which target names are not really files to be made:
+.PHONY: all install install-lib install-headers clean distclean test check
+
+
+jcapimin.$(O): jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcapistd.$(O): jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccoefct.$(O): jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+jcodec.$(O): jcodec.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jlossls.h
+jccolor.$(O): jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcdctmgr.$(O): jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jdct.h
+jcdiffct.$(O): jcdiffct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jchuff.$(O): jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jlossls.h jchuff.h
+jcinit.$(O): jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jclhuff.$(O): jclhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h jchuff.h
+jclossls.$(O): jclossls.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jclossy.$(O): jclossy.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+jcmainct.$(O): jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmarker.$(O): jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmaster.$(O): jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcomapi.$(O): jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcparam.$(O): jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcphuff.$(O): jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jchuff.h
+jcpred.$(O): jcpred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jcprepct.$(O): jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcsample.$(O): jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcscale.$(O): jcscale.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jcshuff.$(O): jcshuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jlossls.h jchuff.h
+jctrans.$(O): jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+jdapimin.$(O): jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapistd.$(O): jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdatadst.$(O): jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdatasrc.$(O): jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdcoefct.$(O): jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+jdcolor.$(O): jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jddctmgr.$(O): jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jdct.h
+jddiffct.$(O): jddiffct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jdhuff.$(O): jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jlossls.h jdhuff.h
+jdinput.$(O): jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdlhuff.$(O): jdlhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h jdhuff.h
+jdlossls.$(O): jdlossls.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jdlossy.$(O): jdlossy.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+jdmainct.$(O): jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmarker.$(O): jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmaster.$(O): jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmerge.$(O): jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdphuff.$(O): jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jdhuff.h
+jdpostct.$(O): jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdpred.$(O): jdpred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jdsample.$(O): jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdscale.$(O): jdscale.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossls.h
+jdshuff.$(O): jdshuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h jdhuff.h
+jdtrans.$(O): jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jlossy.h
+jerror.$(O): jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+jfdctflt.$(O): jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctfst.$(O): jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctint.$(O): jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctflt.$(O): jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctfst.$(O): jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctint.$(O): jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctred.$(O): jidctred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jquant1.$(O): jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jquant2.$(O): jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jutils.$(O): jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jmemmgr.$(O): jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemansi.$(O): jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemname.$(O): jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemnobs.$(O): jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemdos.$(O): jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemmac.$(O): jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+cjpeg.$(O): cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+djpeg.$(O): djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+jpegtran.$(O): jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
+rdjpgcom.$(O): rdjpgcom.c jinclude.h jconfig.h
+wrjpgcom.$(O): wrjpgcom.c jinclude.h jconfig.h
+cdjpeg.$(O): cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdcolmap.$(O): rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdswitch.$(O): rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+transupp.$(O): transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
+rdppm.$(O): rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrppm.$(O): wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdgif.$(O): rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrgif.$(O): wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdtarga.$(O): rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrtarga.$(O): wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdbmp.$(O): rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrbmp.$(O): wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdrle.$(O): rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrrle.$(O): wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
diff --git a/jpeg-6c/makefile.dj b/jpeg-6c/makefile.dj
new file mode 100644
index 0000000..f766d25
--- /dev/null
+++ b/jpeg-6c/makefile.dj
@@ -0,0 +1,220 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is for DJGPP (Delorie's GNU C port on MS-DOS), v2.0 or later.
+# Thanks to Frank J. Donahoe for this version.
+
+# Read installation instructions before saying "make" !!
+
+# The name of your C compiler:
+CC= gcc
+
+# You may need to adjust these cc options:
+CFLAGS= -O2 -Wall -I.
+# Generally, we recommend defining any configuration symbols in jconfig.h,
+# NOT via -D switches here.
+
+# Link-time cc options:
+LDFLAGS= -s
+
+# To link any special libraries, add the necessary -l commands here.
+LDLIBS=
+
+# Put here the object file name for the correct system-dependent memory
+# manager file. For DJGPP this is usually jmemnobs.o, but you could
+# use jmemname.o if you want to use named temp files instead of swap space.
+SYSDEPMEM= jmemnobs.o
+
+# miscellaneous OS-dependent stuff
+# linker
+LN= $(CC)
+# file deletion command
+RM= del
+# library (.a) file creation command
+AR= ar rc
+# second step in .a creation (use "touch" if not needed)
+AR2= ranlib
+
+# End of configurable options.
+
+
+# source files: JPEG library proper
+LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jchuff.c \
+ jcinit.c jcmainct.c jcmarker.c jcmaster.c jcomapi.c jcparam.c \
+ jcphuff.c jcprepct.c jcsample.c jctrans.c jdapimin.c jdapistd.c \
+ jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c jdhuff.c \
+ jdinput.c jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c \
+ jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c jfdctfst.c \
+ jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c jquant1.c \
+ jquant2.c jutils.c jmemmgr.c
+# memmgr back ends: compile only one of these into a working library
+SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \
+ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+# files included by source files
+INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h \
+ jpegint.h jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
+# documentation, test, and support files
+DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
+ coderules.doc filelist.doc change.log
+MKFILES= configure makefile.cfg makefile.ansi makefile.unix makefile.bcc \
+ makefile.mc6 makefile.dj makefile.wat makefile.vc makelib.ds \
+ makeapps.ds makeproj.mac makcjpeg.st makdjpeg.st makljpeg.st \
+ maktjpeg.st makefile.manx makefile.sas makefile.mms makefile.vms \
+ makvms.opt
+CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \
+ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \
+ jconfig.vms
+CONFIGUREFILES= config.guess config.sub install-sh ltconfig ltmain.sh
+OTHERFILES= jconfig.doc ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm
+TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \
+ testimgp.jpg
+DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+# library object files common to compression and decompression
+COMOBJECTS= jcomapi.o jutils.o jerror.o jmemmgr.o $(SYSDEPMEM)
+# compression library object files
+CLIBOBJECTS= jcapimin.o jcapistd.o jctrans.o jcparam.o jdatadst.o jcinit.o \
+ jcmaster.o jcmarker.o jcmainct.o jcprepct.o jccoefct.o jccolor.o \
+ jcsample.o jchuff.o jcphuff.o jcdctmgr.o jfdctfst.o jfdctflt.o \
+ jfdctint.o
+# decompression library object files
+DLIBOBJECTS= jdapimin.o jdapistd.o jdtrans.o jdatasrc.o jdmaster.o \
+ jdinput.o jdmarker.o jdhuff.o jdphuff.o jdmainct.o jdcoefct.o \
+ jdpostct.o jddctmgr.o jidctfst.o jidctflt.o jidctint.o jidctred.o \
+ jdsample.o jdcolor.o jquant1.o jquant2.o jdmerge.o
+# These objectfiles are included in libjpeg.a
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+# object files for sample applications (excluding library files)
+COBJECTS= cjpeg.o rdppm.o rdgif.o rdtarga.o rdrle.o rdbmp.o rdswitch.o \
+ cdjpeg.o
+DOBJECTS= djpeg.o wrppm.o wrgif.o wrtarga.o wrrle.o wrbmp.o rdcolmap.o \
+ cdjpeg.o
+TROBJECTS= jpegtran.o rdswitch.o cdjpeg.o transupp.o
+
+
+all: libjpeg.a cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe
+
+libjpeg.a: $(LIBOBJECTS)
+ $(RM) libjpeg.a
+ $(AR) libjpeg.a $(LIBOBJECTS)
+ $(AR2) libjpeg.a
+
+cjpeg.exe: $(COBJECTS) libjpeg.a
+ $(LN) $(LDFLAGS) -o cjpeg.exe $(COBJECTS) libjpeg.a $(LDLIBS)
+
+djpeg.exe: $(DOBJECTS) libjpeg.a
+ $(LN) $(LDFLAGS) -o djpeg.exe $(DOBJECTS) libjpeg.a $(LDLIBS)
+
+jpegtran.exe: $(TROBJECTS) libjpeg.a
+ $(LN) $(LDFLAGS) -o jpegtran.exe $(TROBJECTS) libjpeg.a $(LDLIBS)
+
+rdjpgcom.exe: rdjpgcom.o
+ $(LN) $(LDFLAGS) -o rdjpgcom.exe rdjpgcom.o $(LDLIBS)
+
+wrjpgcom.exe: wrjpgcom.o
+ $(LN) $(LDFLAGS) -o wrjpgcom.exe wrjpgcom.o $(LDLIBS)
+
+jconfig.h: jconfig.doc
+ echo You must prepare a system-dependent jconfig.h file.
+ echo Please read the installation directions in install.doc.
+ exit 1
+
+clean:
+ $(RM) *.o
+ $(RM) cjpeg.exe
+ $(RM) djpeg.exe
+ $(RM) jpegtran.exe
+ $(RM) rdjpgcom.exe
+ $(RM) wrjpgcom.exe
+ $(RM) libjpeg.a
+ $(RM) testout*.*
+
+test: cjpeg.exe djpeg.exe jpegtran.exe
+ $(RM) testout*.*
+ ./djpeg -dct int -ppm -outfile testout.ppm testorig.jpg
+ ./djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg
+ ./cjpeg -dct int -outfile testout.jpg testimg.ppm
+ ./djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
+ ./cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
+ ./jpegtran -outfile testoutt.jpg testprog.jpg
+ fc /b testimg.ppm testout.ppm
+ fc /b testimg.bmp testout.bmp
+ fc /b testimg.jpg testout.jpg
+ fc /b testimg.ppm testoutp.ppm
+ fc /b testimgp.jpg testoutp.jpg
+ fc /b testorig.jpg testoutt.jpg
+
+
+jcapimin.o: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcapistd.o: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccoefct.o: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccolor.o: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcdctmgr.o: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jchuff.o: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcinit.o: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmainct.o: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmarker.o: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmaster.o: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcomapi.o: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcparam.o: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcphuff.o: jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcprepct.o: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcsample.o: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jctrans.o: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapimin.o: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapistd.o: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdatadst.o: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdatasrc.o: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdcoefct.o: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdcolor.o: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jddctmgr.o: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jdhuff.o: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdinput.o: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmainct.o: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmarker.o: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmaster.o: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmerge.o: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdphuff.o: jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdpostct.o: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdsample.o: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdtrans.o: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jerror.o: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+jfdctflt.o: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctfst.o: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctint.o: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctflt.o: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctfst.o: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctint.o: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctred.o: jidctred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jquant1.o: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jquant2.o: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jutils.o: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jmemmgr.o: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemansi.o: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemname.o: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemnobs.o: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemdos.o: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemmac.o: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+cjpeg.o: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+djpeg.o: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+jpegtran.o: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
+rdjpgcom.o: rdjpgcom.c jinclude.h jconfig.h
+wrjpgcom.o: wrjpgcom.c jinclude.h jconfig.h
+cdjpeg.o: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdcolmap.o: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdswitch.o: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+transupp.o: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
+rdppm.o: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrppm.o: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdgif.o: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrgif.o: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdtarga.o: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrtarga.o: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdbmp.o: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrbmp.o: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdrle.o: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrrle.o: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
diff --git a/jpeg-6c/makefile.manx b/jpeg-6c/makefile.manx
new file mode 100644
index 0000000..4cb42d1
--- /dev/null
+++ b/jpeg-6c/makefile.manx
@@ -0,0 +1,214 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is for Amiga systems using Manx Aztec C ver 5.x.
+# Thanks to D.J. James (djjames at cup.portal.com) for this version.
+
+# Read installation instructions before saying "make" !!
+
+# The name of your C compiler:
+CC= cc
+
+# You may need to adjust these cc options:
+# Uncomment for generic 68000 code (will work on any Amiga)
+ARCHFLAGS= -sn
+
+# Uncomment for 68020/68030 code (faster, but won't run on 68000 CPU)
+#ARCHFLAGS= -c2
+
+CFLAGS= -MC -MD $(ARCHFLAGS) -spfam -r4
+
+# Link-time cc options:
+LDFLAGS= -g
+
+# To link any special libraries, add the necessary -l commands here.
+LDLIBS= -lml -lcl
+
+# Put here the object file name for the correct system-dependent memory
+# manager file. For Amiga we recommend jmemname.o.
+SYSDEPMEM= jmemname.o
+
+# miscellaneous OS-dependent stuff
+# linker
+LN= ln
+# file deletion command
+RM= delete quiet
+# library (.lib) file creation command
+AR= lb
+
+# End of configurable options.
+
+
+# source files: JPEG library proper
+LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jchuff.c \
+ jcinit.c jcmainct.c jcmarker.c jcmaster.c jcomapi.c jcparam.c \
+ jcphuff.c jcprepct.c jcsample.c jctrans.c jdapimin.c jdapistd.c \
+ jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c jdhuff.c \
+ jdinput.c jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c \
+ jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c jfdctfst.c \
+ jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c jquant1.c \
+ jquant2.c jutils.c jmemmgr.c
+# memmgr back ends: compile only one of these into a working library
+SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \
+ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+# files included by source files
+INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h \
+ jpegint.h jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
+# documentation, test, and support files
+DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
+ coderules.doc filelist.doc change.log
+MKFILES= configure makefile.cfg makefile.ansi makefile.unix makefile.bcc \
+ makefile.mc6 makefile.dj makefile.wat makefile.vc makelib.ds \
+ makeapps.ds makeproj.mac makcjpeg.st makdjpeg.st makljpeg.st \
+ maktjpeg.st makefile.manx makefile.sas makefile.mms makefile.vms \
+ makvms.opt
+CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \
+ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \
+ jconfig.vms
+CONFIGUREFILES= config.guess config.sub install-sh ltconfig ltmain.sh
+OTHERFILES= jconfig.doc ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm
+TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \
+ testimgp.jpg
+DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+# library object files common to compression and decompression
+COMOBJECTS= jcomapi.o jutils.o jerror.o jmemmgr.o $(SYSDEPMEM)
+# compression library object files
+CLIBOBJECTS= jcapimin.o jcapistd.o jctrans.o jcparam.o jdatadst.o jcinit.o \
+ jcmaster.o jcmarker.o jcmainct.o jcprepct.o jccoefct.o jccolor.o \
+ jcsample.o jchuff.o jcphuff.o jcdctmgr.o jfdctfst.o jfdctflt.o \
+ jfdctint.o
+# decompression library object files
+DLIBOBJECTS= jdapimin.o jdapistd.o jdtrans.o jdatasrc.o jdmaster.o \
+ jdinput.o jdmarker.o jdhuff.o jdphuff.o jdmainct.o jdcoefct.o \
+ jdpostct.o jddctmgr.o jidctfst.o jidctflt.o jidctint.o jidctred.o \
+ jdsample.o jdcolor.o jquant1.o jquant2.o jdmerge.o
+# These objectfiles are included in libjpeg.lib
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+# object files for sample applications (excluding library files)
+COBJECTS= cjpeg.o rdppm.o rdgif.o rdtarga.o rdrle.o rdbmp.o rdswitch.o \
+ cdjpeg.o
+DOBJECTS= djpeg.o wrppm.o wrgif.o wrtarga.o wrrle.o wrbmp.o rdcolmap.o \
+ cdjpeg.o
+TROBJECTS= jpegtran.o rdswitch.o cdjpeg.o transupp.o
+
+
+all: libjpeg.lib cjpeg djpeg jpegtran rdjpgcom wrjpgcom
+
+libjpeg.lib: $(LIBOBJECTS)
+ -$(RM) libjpeg.lib
+ $(AR) libjpeg.lib $(LIBOBJECTS)
+
+cjpeg: $(COBJECTS) libjpeg.lib
+ $(LN) $(LDFLAGS) -o cjpeg $(COBJECTS) libjpeg.lib $(LDLIBS)
+
+djpeg: $(DOBJECTS) libjpeg.lib
+ $(LN) $(LDFLAGS) -o djpeg $(DOBJECTS) libjpeg.lib $(LDLIBS)
+
+jpegtran: $(TROBJECTS) libjpeg.lib
+ $(LN) $(LDFLAGS) -o jpegtran $(TROBJECTS) libjpeg.lib $(LDLIBS)
+
+rdjpgcom: rdjpgcom.o
+ $(LN) $(LDFLAGS) -o rdjpgcom rdjpgcom.o $(LDLIBS)
+
+wrjpgcom: wrjpgcom.o
+ $(LN) $(LDFLAGS) -o wrjpgcom wrjpgcom.o $(LDLIBS)
+
+jconfig.h: jconfig.doc
+ echo You must prepare a system-dependent jconfig.h file.
+ echo Please read the installation directions in install.doc.
+ exit 1
+
+clean:
+ -$(RM) *.o cjpeg djpeg jpegtran libjpeg.lib rdjpgcom wrjpgcom
+ -$(RM) core testout*.*
+
+test: cjpeg djpeg jpegtran
+ -$(RM) testout*.*
+ djpeg -dct int -ppm -outfile testout.ppm testorig.jpg
+ djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg
+ cjpeg -dct int -outfile testout.jpg testimg.ppm
+ djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
+ cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
+ jpegtran -outfile testoutt.jpg testprog.jpg
+ cmp testimg.ppm testout.ppm
+ cmp testimg.bmp testout.bmp
+ cmp testimg.jpg testout.jpg
+ cmp testimg.ppm testoutp.ppm
+ cmp testimgp.jpg testoutp.jpg
+ cmp testorig.jpg testoutt.jpg
+
+
+jcapimin.o: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcapistd.o: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccoefct.o: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccolor.o: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcdctmgr.o: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jchuff.o: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcinit.o: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmainct.o: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmarker.o: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmaster.o: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcomapi.o: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcparam.o: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcphuff.o: jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcprepct.o: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcsample.o: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jctrans.o: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapimin.o: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapistd.o: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdatadst.o: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdatasrc.o: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdcoefct.o: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdcolor.o: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jddctmgr.o: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jdhuff.o: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdinput.o: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmainct.o: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmarker.o: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmaster.o: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmerge.o: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdphuff.o: jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdpostct.o: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdsample.o: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdtrans.o: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jerror.o: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+jfdctflt.o: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctfst.o: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctint.o: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctflt.o: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctfst.o: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctint.o: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctred.o: jidctred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jquant1.o: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jquant2.o: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jutils.o: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jmemmgr.o: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemansi.o: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemname.o: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemnobs.o: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemdos.o: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemmac.o: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+cjpeg.o: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+djpeg.o: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+jpegtran.o: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
+rdjpgcom.o: rdjpgcom.c jinclude.h jconfig.h
+wrjpgcom.o: wrjpgcom.c jinclude.h jconfig.h
+cdjpeg.o: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdcolmap.o: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdswitch.o: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+transupp.o: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
+rdppm.o: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrppm.o: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdgif.o: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrgif.o: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdtarga.o: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrtarga.o: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdbmp.o: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrbmp.o: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdrle.o: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrrle.o: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
diff --git a/jpeg-6c/makefile.mc6 b/jpeg-6c/makefile.mc6
new file mode 100644
index 0000000..6aff054
--- /dev/null
+++ b/jpeg-6c/makefile.mc6
@@ -0,0 +1,249 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is for Microsoft C for MS-DOS, version 6.00A and up.
+# Use NMAKE, not Microsoft's brain-damaged MAKE.
+# Thanks to Alan Wright and Chris Turner of Olivetti Research Ltd.
+
+# Read installation instructions before saying "nmake" !!
+
+# You may need to adjust these compiler options:
+CFLAGS = -AM -Oecigt -Gs -W3
+# -AM medium memory model (or use -AS for small model, if you remove features)
+# -Oecigt -Gs maximum safe optimisation (-Ol has bugs in MSC 6.00A)
+# -W3 warning level 3
+# You might also want to add -G2 if you have an 80286, etc.
+# Generally, we recommend defining any configuration symbols in jconfig.h,
+# NOT via -D switches here.
+
+# Jan-Herman Buining suggests the following switches for MS C 8.0 and a 486:
+# CFLAGS = /AM /f- /FPi87 /G3 /Gs /Gy /Ob1 /Oc /Oe /Og /Oi /Ol /On /Oo /Ot \
+# /OV4 /W3
+# except for jquant1.c, which must be compiled with /Oo- to avoid a compiler
+# crash.
+
+# Ingar Steinsland suggests the following switches when building
+# a 16-bit Windows DLL:
+# CFLAGS = -ALw -Gsw -Zpe -W3 -O2 -Zi -Zd
+
+# Put here the object file name for the correct system-dependent memory
+# manager file. For DOS, we recommend jmemdos.c and jmemdosa.asm.
+# (But not for Windows; see install.doc if you use this makefile for Windows.)
+SYSDEPMEM= jmemdos.obj jmemdosa.obj
+# SYSDEPMEMLIB must list the same files with "+" signs for the librarian.
+SYSDEPMEMLIB= +jmemdos.obj +jmemdosa.obj
+
+# End of configurable options.
+
+
+# source files: JPEG library proper
+LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jchuff.c \
+ jcinit.c jcmainct.c jcmarker.c jcmaster.c jcomapi.c jcparam.c \
+ jcphuff.c jcprepct.c jcsample.c jctrans.c jdapimin.c jdapistd.c \
+ jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c jdhuff.c \
+ jdinput.c jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c \
+ jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c jfdctfst.c \
+ jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c jquant1.c \
+ jquant2.c jutils.c jmemmgr.c
+# memmgr back ends: compile only one of these into a working library
+SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \
+ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+# files included by source files
+INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h \
+ jpegint.h jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
+# documentation, test, and support files
+DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
+ coderules.doc filelist.doc change.log
+MKFILES= configure makefile.cfg makefile.ansi makefile.unix makefile.bcc \
+ makefile.mc6 makefile.dj makefile.wat makefile.vc makelib.ds \
+ makeapps.ds makeproj.mac makcjpeg.st makdjpeg.st makljpeg.st \
+ maktjpeg.st makefile.manx makefile.sas makefile.mms makefile.vms \
+ makvms.opt
+CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \
+ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \
+ jconfig.vms
+CONFIGUREFILES= config.guess config.sub install-sh ltconfig ltmain.sh
+OTHERFILES= jconfig.doc ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm
+TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \
+ testimgp.jpg
+DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+# library object files common to compression and decompression
+COMOBJECTS= jcomapi.obj jutils.obj jerror.obj jmemmgr.obj $(SYSDEPMEM)
+# compression library object files
+CLIBOBJECTS= jcapimin.obj jcapistd.obj jctrans.obj jcparam.obj jdatadst.obj \
+ jcinit.obj jcmaster.obj jcmarker.obj jcmainct.obj jcprepct.obj \
+ jccoefct.obj jccolor.obj jcsample.obj jchuff.obj jcphuff.obj \
+ jcdctmgr.obj jfdctfst.obj jfdctflt.obj jfdctint.obj
+# decompression library object files
+DLIBOBJECTS= jdapimin.obj jdapistd.obj jdtrans.obj jdatasrc.obj \
+ jdmaster.obj jdinput.obj jdmarker.obj jdhuff.obj jdphuff.obj \
+ jdmainct.obj jdcoefct.obj jdpostct.obj jddctmgr.obj jidctfst.obj \
+ jidctflt.obj jidctint.obj jidctred.obj jdsample.obj jdcolor.obj \
+ jquant1.obj jquant2.obj jdmerge.obj
+# These objectfiles are included in libjpeg.lib
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+# object files for sample applications (excluding library files)
+COBJECTS= cjpeg.obj rdppm.obj rdgif.obj rdtarga.obj rdrle.obj rdbmp.obj \
+ rdswitch.obj cdjpeg.obj
+DOBJECTS= djpeg.obj wrppm.obj wrgif.obj wrtarga.obj wrrle.obj wrbmp.obj \
+ rdcolmap.obj cdjpeg.obj
+TROBJECTS= jpegtran.obj rdswitch.obj cdjpeg.obj transupp.obj
+
+# need linker response file because file list > 128 chars
+RFILE = libjpeg.ans
+
+
+all: libjpeg.lib cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe
+
+libjpeg.lib: $(LIBOBJECTS) $(RFILE)
+ del libjpeg.lib
+ lib @$(RFILE)
+
+# linker response file for building libjpeg.lib
+$(RFILE) : makefile
+ del $(RFILE)
+ echo libjpeg.lib >$(RFILE)
+# silly want-to-create-it prompt:
+ echo y >>$(RFILE)
+ echo +jcapimin.obj +jcapistd.obj +jctrans.obj +jcparam.obj & >>$(RFILE)
+ echo +jdatadst.obj +jcinit.obj +jcmaster.obj +jcmarker.obj & >>$(RFILE)
+ echo +jcmainct.obj +jcprepct.obj +jccoefct.obj & >>$(RFILE)
+ echo +jccolor.obj +jcsample.obj +jchuff.obj +jcphuff.obj & >>$(RFILE)
+ echo +jcdctmgr.obj +jfdctfst.obj +jfdctflt.obj & >>$(RFILE)
+ echo +jfdctint.obj +jdapimin.obj +jdapistd.obj & >>$(RFILE)
+ echo +jdtrans.obj +jdatasrc.obj +jdmaster.obj +jdinput.obj & >>$(RFILE)
+ echo +jdmarker.obj +jdhuff.obj +jdphuff.obj +jdmainct.obj & >>$(RFILE)
+ echo +jdcoefct.obj +jdpostct.obj +jddctmgr.obj & >>$(RFILE)
+ echo +jidctfst.obj +jidctflt.obj +jidctint.obj & >>$(RFILE)
+ echo +jidctred.obj +jdsample.obj +jdcolor.obj +jquant1.obj & >>$(RFILE)
+ echo +jquant2.obj +jdmerge.obj +jcomapi.obj +jutils.obj & >>$(RFILE)
+ echo +jerror.obj +jmemmgr.obj & >>$(RFILE)
+ echo $(SYSDEPMEMLIB) ; >>$(RFILE)
+
+cjpeg.exe: $(COBJECTS) libjpeg.lib
+ echo $(COBJECTS) >cjpeg.lst
+ link /STACK:4096 /EXEPACK @cjpeg.lst, cjpeg.exe, , libjpeg.lib, ;
+ del cjpeg.lst
+
+djpeg.exe: $(DOBJECTS) libjpeg.lib
+ echo $(DOBJECTS) >djpeg.lst
+ link /STACK:4096 /EXEPACK @djpeg.lst, djpeg.exe, , libjpeg.lib, ;
+ del djpeg.lst
+
+jpegtran.exe: $(TROBJECTS) libjpeg.lib
+ link /STACK:4096 /EXEPACK $(TROBJECTS), jpegtran.exe, , libjpeg.lib, ;
+
+rdjpgcom.exe: rdjpgcom.c
+ $(CC) -AS -O -W3 rdjpgcom.c
+
+# wrjpgcom needs large model so it can malloc a 64K chunk
+wrjpgcom.exe: wrjpgcom.c
+ $(CC) -AL -O -W3 wrjpgcom.c
+
+jconfig.h: jconfig.doc
+ echo You must prepare a system-dependent jconfig.h file.
+ echo Please read the installation directions in install.doc.
+ exit 1
+
+clean:
+ del *.obj
+ del libjpeg.lib
+ del cjpeg.exe
+ del djpeg.exe
+ del jpegtran.exe
+ del rdjpgcom.exe
+ del wrjpgcom.exe
+ del testout*.*
+
+test: cjpeg.exe djpeg.exe jpegtran.exe
+ del testout*.*
+ djpeg -dct int -ppm -outfile testout.ppm testorig.jpg
+ djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg
+ cjpeg -dct int -outfile testout.jpg testimg.ppm
+ djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
+ cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
+ jpegtran -outfile testoutt.jpg testprog.jpg
+ fc /b testimg.ppm testout.ppm
+ fc /b testimg.bmp testout.bmp
+ fc /b testimg.jpg testout.jpg
+ fc /b testimg.ppm testoutp.ppm
+ fc /b testimgp.jpg testoutp.jpg
+ fc /b testorig.jpg testoutt.jpg
+
+
+jcapimin.obj: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcapistd.obj: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccoefct.obj: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccolor.obj: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcdctmgr.obj: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jchuff.obj: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcinit.obj: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmainct.obj: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmarker.obj: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmaster.obj: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcomapi.obj: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcparam.obj: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcphuff.obj: jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcprepct.obj: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcsample.obj: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jctrans.obj: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapimin.obj: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapistd.obj: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdatadst.obj: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdatasrc.obj: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdcoefct.obj: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdcolor.obj: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jddctmgr.obj: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jdhuff.obj: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdinput.obj: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmainct.obj: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmarker.obj: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmaster.obj: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmerge.obj: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdphuff.obj: jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdpostct.obj: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdsample.obj: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdtrans.obj: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jerror.obj: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+jfdctflt.obj: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctfst.obj: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctint.obj: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctflt.obj: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctfst.obj: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctint.obj: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctred.obj: jidctred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jquant1.obj: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jquant2.obj: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jutils.obj: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jmemmgr.obj: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemansi.obj: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemname.obj: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemnobs.obj: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemdos.obj: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemmac.obj: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+cjpeg.obj: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+djpeg.obj: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+jpegtran.obj: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
+rdjpgcom.obj: rdjpgcom.c jinclude.h jconfig.h
+wrjpgcom.obj: wrjpgcom.c jinclude.h jconfig.h
+cdjpeg.obj: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdcolmap.obj: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdswitch.obj: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+transupp.obj: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
+rdppm.obj: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrppm.obj: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdgif.obj: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrgif.obj: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdtarga.obj: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrtarga.obj: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdbmp.obj: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrbmp.obj: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdrle.obj: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrrle.obj: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+jmemdosa.obj : jmemdosa.asm
+ masm /mx $*;
diff --git a/jpeg-6c/makefile.mms b/jpeg-6c/makefile.mms
new file mode 100644
index 0000000..cf130e5
--- /dev/null
+++ b/jpeg-6c/makefile.mms
@@ -0,0 +1,218 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is for use with MMS on Digital VMS systems.
+# Thanks to Rick Dyson (dyson at iowasp.physics.uiowa.edu)
+# and Tim Bell (tbell at netcom.com) for their help.
+
+# Read installation instructions before saying "MMS" !!
+
+# You may need to adjust these cc options:
+CFLAGS= $(CFLAGS) /NoDebug /Optimize
+# Generally, we recommend defining any configuration symbols in jconfig.h,
+# NOT via /Define switches here.
+.ifdef ALPHA
+OPT=
+.else
+OPT= ,Sys$Disk:[]MAKVMS.OPT/Option
+.endif
+
+# Put here the object file name for the correct system-dependent memory
+# manager file. For Unix this is usually jmemnobs.o, but you may want
+# to use jmemansi.o or jmemname.o if you have limited swap space.
+SYSDEPMEM= jmemnobs.obj
+
+# End of configurable options.
+
+
+# source files: JPEG library proper
+LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jchuff.c \
+ jcinit.c jcmainct.c jcmarker.c jcmaster.c jcomapi.c jcparam.c \
+ jcphuff.c jcprepct.c jcsample.c jctrans.c jdapimin.c jdapistd.c \
+ jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c jdhuff.c \
+ jdinput.c jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c \
+ jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c jfdctfst.c \
+ jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c jquant1.c \
+ jquant2.c jutils.c jmemmgr.c
+# memmgr back ends: compile only one of these into a working library
+SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \
+ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+# files included by source files
+INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h \
+ jpegint.h jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
+# documentation, test, and support files
+DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
+ coderules.doc filelist.doc change.log
+MKFILES= configure makefile.cfg makefile.ansi makefile.unix makefile.bcc \
+ makefile.mc6 makefile.dj makefile.wat makefile.vc makelib.ds \
+ makeapps.ds makeproj.mac makcjpeg.st makdjpeg.st makljpeg.st \
+ maktjpeg.st makefile.manx makefile.sas makefile.mms makefile.vms \
+ makvms.opt
+CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \
+ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \
+ jconfig.vms
+CONFIGUREFILES= config.guess config.sub install-sh ltconfig ltmain.sh
+OTHERFILES= jconfig.doc ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm
+TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \
+ testimgp.jpg
+DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+# library object files common to compression and decompression
+COMOBJECTS= jcomapi.obj jutils.obj jerror.obj jmemmgr.obj $(SYSDEPMEM)
+# compression library object files
+CLIBOBJECTS= jcapimin.obj jcapistd.obj jctrans.obj jcparam.obj jdatadst.obj \
+ jcinit.obj jcmaster.obj jcmarker.obj jcmainct.obj jcprepct.obj \
+ jccoefct.obj jccolor.obj jcsample.obj jchuff.obj jcphuff.obj \
+ jcdctmgr.obj jfdctfst.obj jfdctflt.obj jfdctint.obj
+# decompression library object files
+DLIBOBJECTS= jdapimin.obj jdapistd.obj jdtrans.obj jdatasrc.obj \
+ jdmaster.obj jdinput.obj jdmarker.obj jdhuff.obj jdphuff.obj \
+ jdmainct.obj jdcoefct.obj jdpostct.obj jddctmgr.obj jidctfst.obj \
+ jidctflt.obj jidctint.obj jidctred.obj jdsample.obj jdcolor.obj \
+ jquant1.obj jquant2.obj jdmerge.obj
+# These objectfiles are included in libjpeg.olb
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+# object files for sample applications (excluding library files)
+COBJECTS= cjpeg.obj rdppm.obj rdgif.obj rdtarga.obj rdrle.obj rdbmp.obj \
+ rdswitch.obj cdjpeg.obj
+DOBJECTS= djpeg.obj wrppm.obj wrgif.obj wrtarga.obj wrrle.obj wrbmp.obj \
+ rdcolmap.obj cdjpeg.obj
+TROBJECTS= jpegtran.obj rdswitch.obj cdjpeg.obj transupp.obj
+# objectfile lists with commas --- what a crock
+COBJLIST= cjpeg.obj,rdppm.obj,rdgif.obj,rdtarga.obj,rdrle.obj,rdbmp.obj,\
+ rdswitch.obj,cdjpeg.obj
+DOBJLIST= djpeg.obj,wrppm.obj,wrgif.obj,wrtarga.obj,wrrle.obj,wrbmp.obj,\
+ rdcolmap.obj,cdjpeg.obj
+TROBJLIST= jpegtran.obj,rdswitch.obj,cdjpeg.obj,transupp.obj
+LIBOBJLIST= jcapimin.obj,jcapistd.obj,jctrans.obj,jcparam.obj,jdatadst.obj,\
+ jcinit.obj,jcmaster.obj,jcmarker.obj,jcmainct.obj,jcprepct.obj,\
+ jccoefct.obj,jccolor.obj,jcsample.obj,jchuff.obj,jcphuff.obj,\
+ jcdctmgr.obj,jfdctfst.obj,jfdctflt.obj,jfdctint.obj,jdapimin.obj,\
+ jdapistd.obj,jdtrans.obj,jdatasrc.obj,jdmaster.obj,jdinput.obj,\
+ jdmarker.obj,jdhuff.obj,jdphuff.obj,jdmainct.obj,jdcoefct.obj,\
+ jdpostct.obj,jddctmgr.obj,jidctfst.obj,jidctflt.obj,jidctint.obj,\
+ jidctred.obj,jdsample.obj,jdcolor.obj,jquant1.obj,jquant2.obj,\
+ jdmerge.obj,jcomapi.obj,jutils.obj,jerror.obj,jmemmgr.obj,$(SYSDEPMEM)
+
+
+.first
+ @- Define /NoLog Sys Sys$Library
+
+ALL : libjpeg.olb cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe
+ @ Continue
+
+libjpeg.olb : $(LIBOBJECTS)
+ Library /Create libjpeg.olb $(LIBOBJLIST)
+
+cjpeg.exe : $(COBJECTS) libjpeg.olb
+ $(LINK) $(LFLAGS) /Executable = cjpeg.exe $(COBJLIST),libjpeg.olb/Library$(OPT)
+
+djpeg.exe : $(DOBJECTS) libjpeg.olb
+ $(LINK) $(LFLAGS) /Executable = djpeg.exe $(DOBJLIST),libjpeg.olb/Library$(OPT)
+
+jpegtran.exe : $(TROBJECTS) libjpeg.olb
+ $(LINK) $(LFLAGS) /Executable = jpegtran.exe $(TROBJLIST),libjpeg.olb/Library$(OPT)
+
+rdjpgcom.exe : rdjpgcom.obj
+ $(LINK) $(LFLAGS) /Executable = rdjpgcom.exe rdjpgcom.obj$(OPT)
+
+wrjpgcom.exe : wrjpgcom.obj
+ $(LINK) $(LFLAGS) /Executable = wrjpgcom.exe wrjpgcom.obj$(OPT)
+
+jconfig.h : jconfig.vms
+ @- Copy jconfig.vms jconfig.h
+
+clean :
+ @- Set Protection = Owner:RWED *.*;-1
+ @- Set Protection = Owner:RWED *.OBJ
+ - Purge /NoLog /NoConfirm *.*
+ - Delete /NoLog /NoConfirm *.OBJ;
+
+test : cjpeg.exe djpeg.exe jpegtran.exe
+ mcr sys$disk:[]djpeg -dct int -ppm -outfile testout.ppm testorig.jpg
+ mcr sys$disk:[]djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg
+ mcr sys$disk:[]cjpeg -dct int -outfile testout.jpg testimg.ppm
+ mcr sys$disk:[]djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
+ mcr sys$disk:[]cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
+ mcr sys$disk:[]jpegtran -outfile testoutt.jpg testprog.jpg
+ - Backup /Compare/Log testimg.ppm testout.ppm
+ - Backup /Compare/Log testimg.bmp testout.bmp
+ - Backup /Compare/Log testimg.jpg testout.jpg
+ - Backup /Compare/Log testimg.ppm testoutp.ppm
+ - Backup /Compare/Log testimgp.jpg testoutp.jpg
+ - Backup /Compare/Log testorig.jpg testoutt.jpg
+
+
+jcapimin.obj : jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcapistd.obj : jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccoefct.obj : jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccolor.obj : jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcdctmgr.obj : jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jchuff.obj : jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcinit.obj : jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmainct.obj : jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmarker.obj : jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmaster.obj : jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcomapi.obj : jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcparam.obj : jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcphuff.obj : jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcprepct.obj : jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcsample.obj : jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jctrans.obj : jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapimin.obj : jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapistd.obj : jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdatadst.obj : jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdatasrc.obj : jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdcoefct.obj : jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdcolor.obj : jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jddctmgr.obj : jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jdhuff.obj : jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdinput.obj : jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmainct.obj : jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmarker.obj : jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmaster.obj : jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmerge.obj : jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdphuff.obj : jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdpostct.obj : jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdsample.obj : jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdtrans.obj : jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jerror.obj : jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+jfdctflt.obj : jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctfst.obj : jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctint.obj : jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctflt.obj : jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctfst.obj : jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctint.obj : jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctred.obj : jidctred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jquant1.obj : jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jquant2.obj : jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jutils.obj : jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jmemmgr.obj : jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemansi.obj : jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemname.obj : jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemnobs.obj : jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemdos.obj : jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemmac.obj : jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+cjpeg.obj : cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+djpeg.obj : djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+jpegtran.obj : jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
+rdjpgcom.obj : rdjpgcom.c jinclude.h jconfig.h
+wrjpgcom.obj : wrjpgcom.c jinclude.h jconfig.h
+cdjpeg.obj : cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdcolmap.obj : rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdswitch.obj : rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+transupp.obj : transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
+rdppm.obj : rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrppm.obj : wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdgif.obj : rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrgif.obj : wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdtarga.obj : rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrtarga.obj : wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdbmp.obj : rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrbmp.obj : wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdrle.obj : rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrrle.obj : wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
diff --git a/jpeg-6c/makefile.sas b/jpeg-6c/makefile.sas
new file mode 100644
index 0000000..f296faf
--- /dev/null
+++ b/jpeg-6c/makefile.sas
@@ -0,0 +1,252 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is for Amiga systems using SAS C 6.0 and up.
+# Thanks to Ed Hanway, Mark Rinfret, and Jim Zepeda.
+
+# Read installation instructions before saying "make" !!
+
+# The name of your C compiler:
+CC= sc
+
+# You may need to adjust these cc options:
+# Uncomment the following lines for generic 680x0 version
+ARCHFLAGS= cpu=any
+SUFFIX=
+
+# Uncomment the following lines for 68030-only version
+#ARCHFLAGS= cpu=68030
+#SUFFIX=.030
+
+CFLAGS= nostackcheck data=near parms=register optimize $(ARCHFLAGS) \
+ ignore=104 ignore=304 ignore=306
+# ignore=104 disables warnings for mismatched const qualifiers
+# ignore=304 disables warnings for variables being optimized out
+# ignore=306 disables warnings for the inlining of functions
+# Generally, we recommend defining any configuration symbols in jconfig.h,
+# NOT via define switches here.
+
+# Link-time cc options:
+LDFLAGS= SC SD ND BATCH
+
+# To link any special libraries, add the necessary commands here.
+LDLIBS= LIB:scm.lib LIB:sc.lib
+
+# Put here the object file name for the correct system-dependent memory
+# manager file. For Amiga we recommend jmemname.o.
+SYSDEPMEM= jmemname.o
+
+# miscellaneous OS-dependent stuff
+# linker
+LN= slink
+# file deletion command
+RM= delete quiet
+# library (.lib) file creation command
+AR= oml
+
+# End of configurable options.
+
+
+# source files: JPEG library proper
+LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jchuff.c \
+ jcinit.c jcmainct.c jcmarker.c jcmaster.c jcomapi.c jcparam.c \
+ jcphuff.c jcprepct.c jcsample.c jctrans.c jdapimin.c jdapistd.c \
+ jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c jdhuff.c \
+ jdinput.c jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c \
+ jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c jfdctfst.c \
+ jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c jquant1.c \
+ jquant2.c jutils.c jmemmgr.c
+# memmgr back ends: compile only one of these into a working library
+SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \
+ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+# files included by source files
+INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h \
+ jpegint.h jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
+# documentation, test, and support files
+DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
+ coderules.doc filelist.doc change.log
+MKFILES= configure makefile.cfg makefile.ansi makefile.unix makefile.bcc \
+ makefile.mc6 makefile.dj makefile.wat makefile.vc makelib.ds \
+ makeapps.ds makeproj.mac makcjpeg.st makdjpeg.st makljpeg.st \
+ maktjpeg.st makefile.manx makefile.sas makefile.mms makefile.vms \
+ makvms.opt
+CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \
+ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \
+ jconfig.vms
+CONFIGUREFILES= config.guess config.sub install-sh ltconfig ltmain.sh
+OTHERFILES= jconfig.doc ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm
+TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \
+ testimgp.jpg
+DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+# library object files common to compression and decompression
+COMOBJECTS= jcomapi.o jutils.o jerror.o jmemmgr.o $(SYSDEPMEM)
+# compression library object files
+CLIBOBJECTS= jcapimin.o jcapistd.o jctrans.o jcparam.o jdatadst.o jcinit.o \
+ jcmaster.o jcmarker.o jcmainct.o jcprepct.o jccoefct.o jccolor.o \
+ jcsample.o jchuff.o jcphuff.o jcdctmgr.o jfdctfst.o jfdctflt.o \
+ jfdctint.o
+# decompression library object files
+DLIBOBJECTS= jdapimin.o jdapistd.o jdtrans.o jdatasrc.o jdmaster.o \
+ jdinput.o jdmarker.o jdhuff.o jdphuff.o jdmainct.o jdcoefct.o \
+ jdpostct.o jddctmgr.o jidctfst.o jidctflt.o jidctint.o jidctred.o \
+ jdsample.o jdcolor.o jquant1.o jquant2.o jdmerge.o
+# These objectfiles are included in libjpeg.lib
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+# object files for sample applications (excluding library files)
+COBJECTS= cjpeg.o rdppm.o rdgif.o rdtarga.o rdrle.o rdbmp.o rdswitch.o \
+ cdjpeg.o
+DOBJECTS= djpeg.o wrppm.o wrgif.o wrtarga.o wrrle.o wrbmp.o rdcolmap.o \
+ cdjpeg.o
+TROBJECTS= jpegtran.o rdswitch.o cdjpeg.o transupp.o
+
+
+all: libjpeg.lib cjpeg$(SUFFIX) djpeg$(SUFFIX) jpegtran$(SUFFIX) rdjpgcom$(SUFFIX) wrjpgcom$(SUFFIX)
+
+# note: do several AR steps to avoid command line length limitations
+
+libjpeg.lib: $(LIBOBJECTS)
+ -$(RM) libjpeg.lib
+ $(AR) libjpeg.lib r $(CLIBOBJECTS)
+ $(AR) libjpeg.lib r $(DLIBOBJECTS)
+ $(AR) libjpeg.lib r $(COMOBJECTS)
+
+cjpeg$(SUFFIX): $(COBJECTS) libjpeg.lib
+ $(LN) <WITH <
+$(LDFLAGS)
+TO cjpeg$(SUFFIX)
+FROM LIB:c.o $(COBJECTS)
+LIB libjpeg.lib $(LDLIBS)
+<
+
+djpeg$(SUFFIX): $(DOBJECTS) libjpeg.lib
+ $(LN) <WITH <
+$(LDFLAGS)
+TO djpeg$(SUFFIX)
+FROM LIB:c.o $(DOBJECTS)
+LIB libjpeg.lib $(LDLIBS)
+<
+
+jpegtran$(SUFFIX): $(TROBJECTS) libjpeg.lib
+ $(LN) <WITH <
+$(LDFLAGS)
+TO jpegtran$(SUFFIX)
+FROM LIB:c.o $(TROBJECTS)
+LIB libjpeg.lib $(LDLIBS)
+<
+
+rdjpgcom$(SUFFIX): rdjpgcom.o
+ $(LN) <WITH <
+$(LDFLAGS)
+TO rdjpgcom$(SUFFIX)
+FROM LIB:c.o rdjpgcom.o
+LIB $(LDLIBS)
+<
+
+wrjpgcom$(SUFFIX): wrjpgcom.o
+ $(LN) <WITH <
+$(LDFLAGS)
+TO wrjpgcom$(SUFFIX)
+FROM LIB:c.o wrjpgcom.o
+LIB $(LDLIBS)
+<
+
+jconfig.h: jconfig.doc
+ echo You must prepare a system-dependent jconfig.h file.
+ echo Please read the installation directions in install.doc.
+ exit 1
+
+clean:
+ -$(RM) *.o cjpeg djpeg jpegtran cjpeg.030 djpeg.030 jpegtran.030
+ -$(RM) rdjpgcom wrjpgcom rdjpgcom.030 wrjpgcom.030
+ -$(RM) libjpeg.lib core testout*.*
+
+test: cjpeg djpeg jpegtran
+ -$(RM) testout*.*
+ djpeg -dct int -ppm -outfile testout.ppm testorig.jpg
+ djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg
+ cjpeg -dct int -outfile testout.jpg testimg.ppm
+ djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
+ cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
+ jpegtran -outfile testoutt.jpg testprog.jpg
+ cmp testimg.ppm testout.ppm
+ cmp testimg.bmp testout.bmp
+ cmp testimg.jpg testout.jpg
+ cmp testimg.ppm testoutp.ppm
+ cmp testimgp.jpg testoutp.jpg
+ cmp testorig.jpg testoutt.jpg
+
+
+jcapimin.o: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcapistd.o: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccoefct.o: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccolor.o: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcdctmgr.o: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jchuff.o: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcinit.o: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmainct.o: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmarker.o: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmaster.o: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcomapi.o: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcparam.o: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcphuff.o: jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcprepct.o: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcsample.o: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jctrans.o: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapimin.o: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapistd.o: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdatadst.o: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdatasrc.o: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdcoefct.o: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdcolor.o: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jddctmgr.o: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jdhuff.o: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdinput.o: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmainct.o: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmarker.o: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmaster.o: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmerge.o: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdphuff.o: jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdpostct.o: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdsample.o: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdtrans.o: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jerror.o: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+jfdctflt.o: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctfst.o: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctint.o: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctflt.o: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctfst.o: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctint.o: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctred.o: jidctred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jquant1.o: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jquant2.o: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jutils.o: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jmemmgr.o: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemansi.o: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemname.o: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemnobs.o: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemdos.o: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemmac.o: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+cjpeg.o: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+djpeg.o: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+jpegtran.o: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
+rdjpgcom.o: rdjpgcom.c jinclude.h jconfig.h
+wrjpgcom.o: wrjpgcom.c jinclude.h jconfig.h
+cdjpeg.o: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdcolmap.o: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdswitch.o: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+transupp.o: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
+rdppm.o: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrppm.o: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdgif.o: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrgif.o: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdtarga.o: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrtarga.o: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdbmp.o: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrbmp.o: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdrle.o: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrrle.o: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
diff --git a/jpeg-6c/makefile.unix b/jpeg-6c/makefile.unix
new file mode 100644
index 0000000..00455ab
--- /dev/null
+++ b/jpeg-6c/makefile.unix
@@ -0,0 +1,228 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is suitable for Unix-like systems with non-ANSI compilers.
+# If you have an ANSI compiler, makefile.ansi is a better starting point.
+
+# Read installation instructions before saying "make" !!
+
+# The name of your C compiler:
+CC= cc
+
+# You may need to adjust these cc options:
+CFLAGS= -O
+# Generally, we recommend defining any configuration symbols in jconfig.h,
+# NOT via -D switches here.
+# However, any special defines for ansi2knr.c may be included here:
+ANSI2KNRFLAGS=
+
+# Link-time cc options:
+LDFLAGS=
+
+# To link any special libraries, add the necessary -l commands here.
+LDLIBS=
+
+# Put here the object file name for the correct system-dependent memory
+# manager file. For Unix this is usually jmemnobs.o, but you may want
+# to use jmemansi.o or jmemname.o if you have limited swap space.
+SYSDEPMEM= jmemnobs.o
+
+# miscellaneous OS-dependent stuff
+# linker
+LN= $(CC)
+# file deletion command
+RM= rm -f
+# file rename command
+MV= mv
+# library (.a) file creation command
+AR= ar rc
+# second step in .a creation (use "touch" if not needed)
+AR2= ranlib
+
+# End of configurable options.
+
+
+# source files: JPEG library proper
+LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jchuff.c \
+ jcinit.c jcmainct.c jcmarker.c jcmaster.c jcomapi.c jcparam.c \
+ jcphuff.c jcprepct.c jcsample.c jctrans.c jdapimin.c jdapistd.c \
+ jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c jdhuff.c \
+ jdinput.c jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c \
+ jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c jfdctfst.c \
+ jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c jquant1.c \
+ jquant2.c jutils.c jmemmgr.c
+# memmgr back ends: compile only one of these into a working library
+SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \
+ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+# files included by source files
+INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h \
+ jpegint.h jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
+# documentation, test, and support files
+DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
+ coderules.doc filelist.doc change.log
+MKFILES= configure makefile.cfg makefile.ansi makefile.unix makefile.bcc \
+ makefile.mc6 makefile.dj makefile.wat makefile.vc makelib.ds \
+ makeapps.ds makeproj.mac makcjpeg.st makdjpeg.st makljpeg.st \
+ maktjpeg.st makefile.manx makefile.sas makefile.mms makefile.vms \
+ makvms.opt
+CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \
+ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \
+ jconfig.vms
+CONFIGUREFILES= config.guess config.sub install-sh ltconfig ltmain.sh
+OTHERFILES= jconfig.doc ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm
+TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \
+ testimgp.jpg
+DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+# library object files common to compression and decompression
+COMOBJECTS= jcomapi.o jutils.o jerror.o jmemmgr.o $(SYSDEPMEM)
+# compression library object files
+CLIBOBJECTS= jcapimin.o jcapistd.o jctrans.o jcparam.o jdatadst.o jcinit.o \
+ jcmaster.o jcmarker.o jcmainct.o jcprepct.o jccoefct.o jccolor.o \
+ jcsample.o jchuff.o jcphuff.o jcdctmgr.o jfdctfst.o jfdctflt.o \
+ jfdctint.o
+# decompression library object files
+DLIBOBJECTS= jdapimin.o jdapistd.o jdtrans.o jdatasrc.o jdmaster.o \
+ jdinput.o jdmarker.o jdhuff.o jdphuff.o jdmainct.o jdcoefct.o \
+ jdpostct.o jddctmgr.o jidctfst.o jidctflt.o jidctint.o jidctred.o \
+ jdsample.o jdcolor.o jquant1.o jquant2.o jdmerge.o
+# These objectfiles are included in libjpeg.a
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+# object files for sample applications (excluding library files)
+COBJECTS= cjpeg.o rdppm.o rdgif.o rdtarga.o rdrle.o rdbmp.o rdswitch.o \
+ cdjpeg.o
+DOBJECTS= djpeg.o wrppm.o wrgif.o wrtarga.o wrrle.o wrbmp.o rdcolmap.o \
+ cdjpeg.o
+TROBJECTS= jpegtran.o rdswitch.o cdjpeg.o transupp.o
+
+
+all: ansi2knr libjpeg.a cjpeg djpeg jpegtran rdjpgcom wrjpgcom
+
+# This rule causes ansi2knr to be invoked.
+.c.o:
+ ./ansi2knr $*.c T$*.c
+ $(CC) $(CFLAGS) -c T$*.c
+ $(RM) T$*.c $*.o
+ $(MV) T$*.o $*.o
+
+ansi2knr: ansi2knr.c
+ $(CC) $(CFLAGS) $(ANSI2KNRFLAGS) -o ansi2knr ansi2knr.c
+
+libjpeg.a: ansi2knr $(LIBOBJECTS)
+ $(RM) libjpeg.a
+ $(AR) libjpeg.a $(LIBOBJECTS)
+ $(AR2) libjpeg.a
+
+cjpeg: ansi2knr $(COBJECTS) libjpeg.a
+ $(LN) $(LDFLAGS) -o cjpeg $(COBJECTS) libjpeg.a $(LDLIBS)
+
+djpeg: ansi2knr $(DOBJECTS) libjpeg.a
+ $(LN) $(LDFLAGS) -o djpeg $(DOBJECTS) libjpeg.a $(LDLIBS)
+
+jpegtran: ansi2knr $(TROBJECTS) libjpeg.a
+ $(LN) $(LDFLAGS) -o jpegtran $(TROBJECTS) libjpeg.a $(LDLIBS)
+
+rdjpgcom: rdjpgcom.o
+ $(LN) $(LDFLAGS) -o rdjpgcom rdjpgcom.o $(LDLIBS)
+
+wrjpgcom: wrjpgcom.o
+ $(LN) $(LDFLAGS) -o wrjpgcom wrjpgcom.o $(LDLIBS)
+
+jconfig.h: jconfig.doc
+ echo You must prepare a system-dependent jconfig.h file.
+ echo Please read the installation directions in install.doc.
+ exit 1
+
+clean:
+ $(RM) *.o cjpeg djpeg jpegtran libjpeg.a rdjpgcom wrjpgcom
+ $(RM) ansi2knr core testout*
+
+test: cjpeg djpeg jpegtran
+ $(RM) testout*
+ ./djpeg -dct int -ppm -outfile testout.ppm testorig.jpg
+ ./djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg
+ ./cjpeg -dct int -outfile testout.jpg testimg.ppm
+ ./djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
+ ./cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
+ ./jpegtran -outfile testoutt.jpg testprog.jpg
+ cmp testimg.ppm testout.ppm
+ cmp testimg.bmp testout.bmp
+ cmp testimg.jpg testout.jpg
+ cmp testimg.ppm testoutp.ppm
+ cmp testimgp.jpg testoutp.jpg
+ cmp testorig.jpg testoutt.jpg
+
+
+jcapimin.o: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcapistd.o: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccoefct.o: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccolor.o: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcdctmgr.o: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jchuff.o: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcinit.o: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmainct.o: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmarker.o: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmaster.o: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcomapi.o: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcparam.o: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcphuff.o: jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcprepct.o: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcsample.o: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jctrans.o: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapimin.o: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapistd.o: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdatadst.o: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdatasrc.o: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdcoefct.o: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdcolor.o: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jddctmgr.o: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jdhuff.o: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdinput.o: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmainct.o: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmarker.o: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmaster.o: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmerge.o: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdphuff.o: jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdpostct.o: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdsample.o: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdtrans.o: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jerror.o: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+jfdctflt.o: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctfst.o: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctint.o: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctflt.o: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctfst.o: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctint.o: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctred.o: jidctred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jquant1.o: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jquant2.o: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jutils.o: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jmemmgr.o: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemansi.o: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemname.o: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemnobs.o: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemdos.o: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemmac.o: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+cjpeg.o: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+djpeg.o: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+jpegtran.o: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
+rdjpgcom.o: rdjpgcom.c jinclude.h jconfig.h
+wrjpgcom.o: wrjpgcom.c jinclude.h jconfig.h
+cdjpeg.o: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdcolmap.o: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdswitch.o: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+transupp.o: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
+rdppm.o: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrppm.o: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdgif.o: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrgif.o: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdtarga.o: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrtarga.o: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdbmp.o: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrbmp.o: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdrle.o: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrrle.o: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
diff --git a/jpeg-6c/makefile.vc b/jpeg-6c/makefile.vc
new file mode 100644
index 0000000..3603c38
--- /dev/null
+++ b/jpeg-6c/makefile.vc
@@ -0,0 +1,227 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is for Microsoft Visual C++ on Windows NT (and 95?).
+# It builds the IJG library as a statically linkable library (.LIB),
+# and builds the sample applications as console-mode apps.
+# Thanks to Xingong Chang, Raymond Everly and others.
+
+# Read installation instructions before saying "nmake" !!
+# To build an optimized library without debug info, say "nmake nodebug=1".
+
+# Pull in standard variable definitions
+#!include <win32.mak>
+
+# You may want to adjust these compiler options:
+CFLAGS= $(cflags) $(cdebug) $(cvars) /Zi /MT /O2 -c
+# Generally, we recommend defining any configuration symbols in jconfig.h,
+# NOT via -D switches here.
+
+# Link-time options:
+LDFLAGS= $(ldebug) $(conlflags)
+
+# To link any special libraries, add the necessary commands here.
+LDLIBS= $(conlibs)
+
+# Put here the object file name for the correct system-dependent memory
+# manager file. For NT we suggest jmemnobs.obj, which expects the OS to
+# provide adequate virtual memory.
+SYSDEPMEM= jmemnobs.obj
+
+# miscellaneous OS-dependent stuff
+# file deletion command
+RM= del
+
+# mvh 20100116
+cc = cl
+link = link
+O = obj
+
+# End of configurable options.
+
+
+# source files: JPEG library proper
+# mvh 20100116
+LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jcdiffct.c \
+ jchuff.c jcinit.c jclhuff.c jclossls.c jclossy.c jcmainct.c \
+ jcmarker.c jcmaster.c jcodec.c jcomapi.c jcparam.c jcphuff.c jcpred.c \
+ jcprepct.c jcsample.c jcscale.c jcshuff.c jctrans.c jdapimin.c \
+ jdapistd.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c \
+ jddiffct.c jdhuff.c jdinput.c jdlhuff.c jdlossls.c jdlossy.c \
+ jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c jdpostct.c \
+ jdpred.c jdsample.c jdscale.c jdshuff.c jdtrans.c jerror.c jfdctflt.c \
+ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c \
+ jquant1.c jquant2.c jutils.c jmemmgr.c
+# memmgr back ends: compile only one of these into a working library
+SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \
+ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+# files included by source files
+INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h \
+ jpegint.h jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
+# documentation, test, and support files
+DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
+ coderules.doc filelist.doc change.log
+MKFILES= configure makefile.cfg makefile.ansi makefile.unix makefile.bcc \
+ makefile.mc6 makefile.dj makefile.wat makefile.vc makelib.ds \
+ makeapps.ds makeproj.mac makcjpeg.st makdjpeg.st makljpeg.st \
+ maktjpeg.st makefile.manx makefile.sas makefile.mms makefile.vms \
+ makvms.opt
+CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \
+ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \
+ jconfig.vms
+CONFIGUREFILES= config.guess config.sub install-sh ltconfig ltmain.sh
+OTHERFILES= jconfig.doc ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm
+TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \
+ testimgp.jpg
+DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+# library object files common to compression and decompression
+# mvh 20100116
+COMOBJECTS= jcomapi.$(O) jcodec.$(O) jutils.$(O) jerror.$(O) jmemmgr.$(O) \
+ $(SYSDEPMEM)
+# compression library object files
+# mvh 20100116
+CLIBOBJECTS= jcapimin.$(O) jcapistd.$(O) jctrans.$(O) jcparam.$(O) \
+ jdatadst.$(O) jcinit.$(O) jcmaster.$(O) jcmarker.$(O) jcmainct.$(O) \
+ jcprepct.$(O) jclossls.$(O) jclossy.$(O) jccoefct.$(O) jccolor.$(O) \
+ jcsample.$(O) jchuff.$(O) jcphuff.$(O) jcshuff.$(O) jclhuff.$(O) \
+ jcpred.$(O) jcscale.$(O) jcdiffct.$(O) jcdctmgr.$(O) jfdctfst.$(O) \
+ jfdctflt.$(O) jfdctint.$(O)
+# decompression library object files
+# mvh 20100116
+DLIBOBJECTS= jdapimin.$(O) jdapistd.$(O) jdtrans.$(O) jdatasrc.$(O) \
+ jdmaster.$(O) jdinput.$(O) jdmarker.$(O) jdlossls.$(O) jdlossy.$(O) \
+ jdhuff.$(O) jdlhuff.$(O) jdphuff.$(O) jdshuff.$(O) jdpred.$(O) \
+ jdscale.$(O) jddiffct.$(O) jdmainct.$(O) jdcoefct.$(O) jdpostct.$(O) \
+ jddctmgr.$(O) jidctfst.$(O) jidctflt.$(O) jidctint.$(O) jidctred.$(O) \
+ jdsample.$(O) jdcolor.$(O) jquant1.$(O) jquant2.$(O) jdmerge.$(O)
+# These objectfiles are included in libjpeg.lib
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+# object files for sample applications (excluding library files)
+COBJECTS= cjpeg.obj rdppm.obj rdgif.obj rdtarga.obj rdrle.obj rdbmp.obj \
+ rdswitch.obj cdjpeg.obj
+DOBJECTS= djpeg.obj wrppm.obj wrgif.obj wrtarga.obj wrrle.obj wrbmp.obj \
+ rdcolmap.obj cdjpeg.obj
+TROBJECTS= jpegtran.obj rdswitch.obj cdjpeg.obj transupp.obj
+
+
+# Template command for compiling .c to .obj
+.c.obj:
+ $(cc) $(CFLAGS) $*.c
+
+
+all: libjpeg.lib cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe
+
+libjpeg.lib: $(LIBOBJECTS)
+ $(RM) libjpeg.lib
+ lib -out:libjpeg.lib $(LIBOBJECTS)
+
+cjpeg.exe: $(COBJECTS) libjpeg.lib
+ $(link) $(LDFLAGS) -out:cjpeg.exe $(COBJECTS) libjpeg.lib $(LDLIBS)
+
+djpeg.exe: $(DOBJECTS) libjpeg.lib
+ $(link) $(LDFLAGS) -out:djpeg.exe $(DOBJECTS) libjpeg.lib $(LDLIBS)
+
+jpegtran.exe: $(TROBJECTS) libjpeg.lib
+ $(link) $(LDFLAGS) -out:jpegtran.exe $(TROBJECTS) libjpeg.lib $(LDLIBS)
+
+rdjpgcom.exe: rdjpgcom.obj
+ $(link) $(LDFLAGS) -out:rdjpgcom.exe rdjpgcom.obj $(LDLIBS)
+
+wrjpgcom.exe: wrjpgcom.obj
+ $(link) $(LDFLAGS) -out:wrjpgcom.exe wrjpgcom.obj $(LDLIBS)
+
+
+clean:
+ $(RM) *.obj *.exe libjpeg.lib
+ $(RM) testout*
+
+test: cjpeg.exe djpeg.exe jpegtran.exe
+ $(RM) testout*
+ .\djpeg -dct int -ppm -outfile testout.ppm testorig.jpg
+ .\djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg
+ .\cjpeg -dct int -outfile testout.jpg testimg.ppm
+ .\djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
+ .\cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
+ .\jpegtran -outfile testoutt.jpg testprog.jpg
+ fc /b testimg.ppm testout.ppm
+ fc /b testimg.bmp testout.bmp
+ fc /b testimg.jpg testout.jpg
+ fc /b testimg.ppm testoutp.ppm
+ fc /b testimgp.jpg testoutp.jpg
+ fc /b testorig.jpg testoutt.jpg
+
+
+jcapimin.obj: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcapistd.obj: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccoefct.obj: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccolor.obj: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcdctmgr.obj: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jchuff.obj: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcinit.obj: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmainct.obj: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmarker.obj: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmaster.obj: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcomapi.obj: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcparam.obj: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcphuff.obj: jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcprepct.obj: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcsample.obj: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jctrans.obj: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapimin.obj: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapistd.obj: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdatadst.obj: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdatasrc.obj: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdcoefct.obj: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdcolor.obj: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jddctmgr.obj: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jdhuff.obj: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdinput.obj: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmainct.obj: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmarker.obj: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmaster.obj: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmerge.obj: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdphuff.obj: jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdpostct.obj: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdsample.obj: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdtrans.obj: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jerror.obj: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+jfdctflt.obj: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctfst.obj: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctint.obj: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctflt.obj: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctfst.obj: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctint.obj: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctred.obj: jidctred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jquant1.obj: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jquant2.obj: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jutils.obj: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jmemmgr.obj: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemansi.obj: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemname.obj: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemnobs.obj: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemdos.obj: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemmac.obj: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+cjpeg.obj: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+djpeg.obj: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+jpegtran.obj: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
+rdjpgcom.obj: rdjpgcom.c jinclude.h jconfig.h
+wrjpgcom.obj: wrjpgcom.c jinclude.h jconfig.h
+cdjpeg.obj: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdcolmap.obj: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdswitch.obj: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+transupp.obj: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
+rdppm.obj: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrppm.obj: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdgif.obj: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrgif.obj: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdtarga.obj: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrtarga.obj: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdbmp.obj: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrbmp.obj: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdrle.obj: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrrle.obj: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
diff --git a/jpeg-6c/makefile.vms b/jpeg-6c/makefile.vms
new file mode 100644
index 0000000..a42358d
--- /dev/null
+++ b/jpeg-6c/makefile.vms
@@ -0,0 +1,142 @@
+$! Makefile for Independent JPEG Group's software
+$!
+$! This is a command procedure for Digital VMS systems that do not have MMS.
+$! It builds the JPEG software by brute force, recompiling everything whether
+$! or not it is necessary. It then runs the basic self-test.
+$! Thanks to Rick Dyson (dyson at iowasp.physics.uiowa.edu)
+$! and Tim Bell (tbell at netcom.com) for their help.
+$!
+$! Read installation instructions before running this!!
+$!
+$ If F$Mode () .eqs. "INTERACTIVE"
+$ Then
+$ VERIFY = F$Verify (0)
+$ Else
+$ VERIFY = F$Verify (1)
+$ EndIf
+$ On Control_Y Then GoTo End
+$ On Error Then GoTo End
+$
+$ If F$GetSyi ("HW_MODEL") .gt. 1023
+$ Then
+$ OPT = ""
+$ Else
+$ OPT = ",Sys$Disk:[]makvms.opt/Option"
+$ EndIf
+$
+$ DoCompile := CC /NoDebug /Optimize /NoList
+$!
+$ DoCompile jcapimin.c
+$ DoCompile jcapistd.c
+$ DoCompile jctrans.c
+$ DoCompile jcparam.c
+$ DoCompile jdatadst.c
+$ DoCompile jcinit.c
+$ DoCompile jcmaster.c
+$ DoCompile jcmarker.c
+$ DoCompile jcmainct.c
+$ DoCompile jcprepct.c
+$ DoCompile jccoefct.c
+$ DoCompile jccolor.c
+$ DoCompile jcsample.c
+$ DoCompile jchuff.c
+$ DoCompile jcphuff.c
+$ DoCompile jcdctmgr.c
+$ DoCompile jfdctfst.c
+$ DoCompile jfdctflt.c
+$ DoCompile jfdctint.c
+$ DoCompile jdapimin.c
+$ DoCompile jdapistd.c
+$ DoCompile jdtrans.c
+$ DoCompile jdatasrc.c
+$ DoCompile jdmaster.c
+$ DoCompile jdinput.c
+$ DoCompile jdmarker.c
+$ DoCompile jdhuff.c
+$ DoCompile jdphuff.c
+$ DoCompile jdmainct.c
+$ DoCompile jdcoefct.c
+$ DoCompile jdpostct.c
+$ DoCompile jddctmgr.c
+$ DoCompile jidctfst.c
+$ DoCompile jidctflt.c
+$ DoCompile jidctint.c
+$ DoCompile jidctred.c
+$ DoCompile jdsample.c
+$ DoCompile jdcolor.c
+$ DoCompile jquant1.c
+$ DoCompile jquant2.c
+$ DoCompile jdmerge.c
+$ DoCompile jcomapi.c
+$ DoCompile jutils.c
+$ DoCompile jerror.c
+$ DoCompile jmemmgr.c
+$ DoCompile jmemnobs.c
+$!
+$ Library /Create libjpeg.olb jcapimin.obj,jcapistd.obj,jctrans.obj, -
+ jcparam.obj,jdatadst.obj,jcinit.obj,jcmaster.obj,jcmarker.obj, -
+ jcmainct.obj,jcprepct.obj,jccoefct.obj,jccolor.obj,jcsample.obj, -
+ jchuff.obj,jcphuff.obj,jcdctmgr.obj,jfdctfst.obj,jfdctflt.obj, -
+ jfdctint.obj,jdapimin.obj,jdapistd.obj,jdtrans.obj,jdatasrc.obj, -
+ jdmaster.obj,jdinput.obj,jdmarker.obj,jdhuff.obj,jdphuff.obj, -
+ jdmainct.obj,jdcoefct.obj,jdpostct.obj,jddctmgr.obj,jidctfst.obj, -
+ jidctflt.obj,jidctint.obj,jidctred.obj,jdsample.obj,jdcolor.obj, -
+ jquant1.obj,jquant2.obj,jdmerge.obj,jcomapi.obj,jutils.obj, -
+ jerror.obj,jmemmgr.obj,jmemnobs.obj
+$!
+$ DoCompile cjpeg.c
+$ DoCompile rdppm.c
+$ DoCompile rdgif.c
+$ DoCompile rdtarga.c
+$ DoCompile rdrle.c
+$ DoCompile rdbmp.c
+$ DoCompile rdswitch.c
+$ DoCompile cdjpeg.c
+$!
+$ Link /NoMap /Executable = cjpeg.exe cjpeg.obj,rdppm.obj,rdgif.obj, -
+ rdtarga.obj,rdrle.obj,rdbmp.obj,rdswitch.obj,cdjpeg.obj,libjpeg.olb/Library'OPT'
+$!
+$ DoCompile djpeg.c
+$ DoCompile wrppm.c
+$ DoCompile wrgif.c
+$ DoCompile wrtarga.c
+$ DoCompile wrrle.c
+$ DoCompile wrbmp.c
+$ DoCompile rdcolmap.c
+$ DoCompile cdjpeg.c
+$!
+$ Link /NoMap /Executable = djpeg.exe djpeg.obj,wrppm.obj,wrgif.obj, -
+ wrtarga.obj,wrrle.obj,wrbmp.obj,rdcolmap.obj,cdjpeg.obj,libjpeg.olb/Library'OPT'
+$!
+$ DoCompile jpegtran.c
+$ DoCompile rdswitch.c
+$ DoCompile cdjpeg.c
+$ DoCompile transupp.c
+$!
+$ Link /NoMap /Executable = jpegtran.exe jpegtran.obj,rdswitch.obj, -
+ cdjpeg.obj,transupp.obj,libjpeg.olb/Library'OPT'
+$!
+$ DoCompile rdjpgcom.c
+$ Link /NoMap /Executable = rdjpgcom.exe rdjpgcom.obj'OPT'
+$!
+$ DoCompile wrjpgcom.c
+$ Link /NoMap /Executable = wrjpgcom.exe wrjpgcom.obj'OPT'
+$!
+$! Run the self-test
+$!
+$ mcr sys$disk:[]djpeg -dct int -ppm -outfile testout.ppm testorig.jpg
+$ mcr sys$disk:[]djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg
+$ mcr sys$disk:[]cjpeg -dct int -outfile testout.jpg testimg.ppm
+$ mcr sys$disk:[]djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
+$ mcr sys$disk:[]cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
+$ mcr sys$disk:[]jpegtran -outfile testoutt.jpg testprog.jpg
+$ Backup /Compare/Log testimg.ppm testout.ppm
+$ Backup /Compare/Log testimg.bmp testout.bmp
+$ Backup /Compare/Log testimg.jpg testout.jpg
+$ Backup /Compare/Log testimg.ppm testoutp.ppm
+$ Backup /Compare/Log testimgp.jpg testoutp.jpg
+$ Backup /Compare/Log testorig.jpg testoutt.jpg
+$!
+$End:
+$ If Verify Then Set Verify
+$ Exit
diff --git a/jpeg-6c/makefile.wat b/jpeg-6c/makefile.wat
new file mode 100644
index 0000000..d953e46
--- /dev/null
+++ b/jpeg-6c/makefile.wat
@@ -0,0 +1,233 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is suitable for Watcom C/C++ 10.0 on MS-DOS (using
+# dos4g extender), OS/2, and Windows NT console mode.
+# Thanks to Janos Haide, jhaide at btrvtech.com.
+
+# Read installation instructions before saying "wmake" !!
+
+# Uncomment line for desired system
+SYSTEM=DOS
+#SYSTEM=OS2
+#SYSTEM=NT
+
+# The name of your C compiler:
+CC= wcl386
+
+# You may need to adjust these cc options:
+CFLAGS= -4r -ort -wx -zq -bt=$(SYSTEM)
+# Caution: avoid -ol or -ox; these generate bad code with 10.0 or 10.0a.
+# Generally, we recommend defining any configuration symbols in jconfig.h,
+# NOT via -D switches here.
+
+# Link-time cc options:
+!ifeq SYSTEM DOS
+LDFLAGS= -zq -l=dos4g
+!else ifeq SYSTEM OS2
+LDFLAGS= -zq -l=os2v2
+!else ifeq SYSTEM NT
+LDFLAGS= -zq -l=nt
+!endif
+
+# Put here the object file name for the correct system-dependent memory
+# manager file. jmemnobs should work fine for dos4g or OS/2 environment.
+SYSDEPMEM= jmemnobs.obj
+
+# End of configurable options.
+
+
+# source files: JPEG library proper
+LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jchuff.c &
+ jcinit.c jcmainct.c jcmarker.c jcmaster.c jcomapi.c jcparam.c &
+ jcphuff.c jcprepct.c jcsample.c jctrans.c jdapimin.c jdapistd.c &
+ jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c jdhuff.c &
+ jdinput.c jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c &
+ jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c jfdctfst.c &
+ jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c jquant1.c &
+ jquant2.c jutils.c jmemmgr.c
+# memmgr back ends: compile only one of these into a working library
+SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
+# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
+APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c &
+ rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c &
+ rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
+SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES)
+# files included by source files
+INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h &
+ jpegint.h jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
+# documentation, test, and support files
+DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 &
+ wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc &
+ coderules.doc filelist.doc change.log
+MKFILES= configure makefile.cfg makefile.ansi makefile.unix makefile.bcc &
+ makefile.mc6 makefile.dj makefile.wat makefile.vc makelib.ds &
+ makeapps.ds makeproj.mac makcjpeg.st makdjpeg.st makljpeg.st &
+ maktjpeg.st makefile.manx makefile.sas makefile.mms makefile.vms &
+ makvms.opt
+CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat &
+ jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas &
+ jconfig.vms
+CONFIGUREFILES= config.guess config.sub install-sh ltconfig ltmain.sh
+OTHERFILES= jconfig.doc ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm
+TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg &
+ testimgp.jpg
+DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) &
+ $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
+# library object files common to compression and decompression
+COMOBJECTS= jcomapi.obj jutils.obj jerror.obj jmemmgr.obj $(SYSDEPMEM)
+# compression library object files
+CLIBOBJECTS= jcapimin.obj jcapistd.obj jctrans.obj jcparam.obj jdatadst.obj &
+ jcinit.obj jcmaster.obj jcmarker.obj jcmainct.obj jcprepct.obj &
+ jccoefct.obj jccolor.obj jcsample.obj jchuff.obj jcphuff.obj &
+ jcdctmgr.obj jfdctfst.obj jfdctflt.obj jfdctint.obj
+# decompression library object files
+DLIBOBJECTS= jdapimin.obj jdapistd.obj jdtrans.obj jdatasrc.obj &
+ jdmaster.obj jdinput.obj jdmarker.obj jdhuff.obj jdphuff.obj &
+ jdmainct.obj jdcoefct.obj jdpostct.obj jddctmgr.obj jidctfst.obj &
+ jidctflt.obj jidctint.obj jidctred.obj jdsample.obj jdcolor.obj &
+ jquant1.obj jquant2.obj jdmerge.obj
+# These objectfiles are included in libjpeg.lib
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+# object files for sample applications (excluding library files)
+COBJECTS= cjpeg.obj rdppm.obj rdgif.obj rdtarga.obj rdrle.obj rdbmp.obj &
+ rdswitch.obj cdjpeg.obj
+DOBJECTS= djpeg.obj wrppm.obj wrgif.obj wrtarga.obj wrrle.obj wrbmp.obj &
+ rdcolmap.obj cdjpeg.obj
+TROBJECTS= jpegtran.obj rdswitch.obj cdjpeg.obj transupp.obj
+
+
+all: libjpeg.lib cjpeg.exe djpeg.exe jpegtran.exe rdjpgcom.exe wrjpgcom.exe
+
+libjpeg.lib: $(LIBOBJECTS)
+ - del libjpeg.lib
+ * wlib -n libjpeg.lib $(LIBOBJECTS)
+
+cjpeg.exe: $(COBJECTS) libjpeg.lib
+ $(CC) $(LDFLAGS) $(COBJECTS) libjpeg.lib
+
+djpeg.exe: $(DOBJECTS) libjpeg.lib
+ $(CC) $(LDFLAGS) $(DOBJECTS) libjpeg.lib
+
+jpegtran.exe: $(TROBJECTS) libjpeg.lib
+ $(CC) $(LDFLAGS) $(TROBJECTS) libjpeg.lib
+
+rdjpgcom.exe: rdjpgcom.c
+ $(CC) $(CFLAGS) $(LDFLAGS) rdjpgcom.c
+
+wrjpgcom.exe: wrjpgcom.c
+ $(CC) $(CFLAGS) $(LDFLAGS) wrjpgcom.c
+
+.c.obj:
+ $(CC) $(CFLAGS) -c $<
+
+jconfig.h: jconfig.doc
+ echo You must prepare a system-dependent jconfig.h file.
+ echo Please read the installation directions in install.doc.
+ exit 1
+
+clean: .SYMBOLIC
+ - del *.obj
+ - del libjpeg.lib
+ - del cjpeg.exe
+ - del djpeg.exe
+ - del jpegtran.exe
+ - del rdjpgcom.exe
+ - del wrjpgcom.exe
+ - del testout*.*
+
+test: cjpeg.exe djpeg.exe jpegtran.exe .SYMBOLIC
+ - del testout*.*
+ djpeg -dct int -ppm -outfile testout.ppm testorig.jpg
+ djpeg -dct int -bmp -colors 256 -outfile testout.bmp testorig.jpg
+ cjpeg -dct int -outfile testout.jpg testimg.ppm
+ djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
+ cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
+ jpegtran -outfile testoutt.jpg testprog.jpg
+!ifeq SYSTEM DOS
+ fc /b testimg.ppm testout.ppm
+ fc /b testimg.bmp testout.bmp
+ fc /b testimg.jpg testout.jpg
+ fc /b testimg.ppm testoutp.ppm
+ fc /b testimgp.jpg testoutp.jpg
+ fc /b testorig.jpg testoutt.jpg
+!else
+ echo n > n.tmp
+ comp testimg.ppm testout.ppm < n.tmp
+ comp testimg.bmp testout.bmp < n.tmp
+ comp testimg.jpg testout.jpg < n.tmp
+ comp testimg.ppm testoutp.ppm < n.tmp
+ comp testimgp.jpg testoutp.jpg < n.tmp
+ comp testorig.jpg testoutt.jpg < n.tmp
+ del n.tmp
+!endif
+
+
+jcapimin.obj: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcapistd.obj: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccoefct.obj: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jccolor.obj: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcdctmgr.obj: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jchuff.obj: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcinit.obj: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmainct.obj: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmarker.obj: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcmaster.obj: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcomapi.obj: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcparam.obj: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcphuff.obj: jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
+jcprepct.obj: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jcsample.obj: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jctrans.obj: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapimin.obj: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdapistd.obj: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdatadst.obj: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdatasrc.obj: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
+jdcoefct.obj: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdcolor.obj: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jddctmgr.obj: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jdhuff.obj: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdinput.obj: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmainct.obj: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmarker.obj: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmaster.obj: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdmerge.obj: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdphuff.obj: jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
+jdpostct.obj: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdsample.obj: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jdtrans.obj: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jerror.obj: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
+jfdctflt.obj: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctfst.obj: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jfdctint.obj: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctflt.obj: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctfst.obj: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctint.obj: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jidctred.obj: jidctred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
+jquant1.obj: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jquant2.obj: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jutils.obj: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
+jmemmgr.obj: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemansi.obj: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemname.obj: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemnobs.obj: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemdos.obj: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+jmemmac.obj: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
+cjpeg.obj: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+djpeg.obj: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h jversion.h
+jpegtran.obj: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h transupp.h jversion.h
+rdjpgcom.obj: rdjpgcom.c jinclude.h jconfig.h
+wrjpgcom.obj: wrjpgcom.c jinclude.h jconfig.h
+cdjpeg.obj: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdcolmap.obj: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdswitch.obj: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+transupp.obj: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h transupp.h
+rdppm.obj: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrppm.obj: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdgif.obj: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrgif.obj: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdtarga.obj: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrtarga.obj: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdbmp.obj: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrbmp.obj: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+rdrle.obj: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
+wrrle.obj: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
diff --git a/jpeg-6c/makelib.ds b/jpeg-6c/makelib.ds
new file mode 100644
index 0000000..c7ad36d
--- /dev/null
+++ b/jpeg-6c/makelib.ds
@@ -0,0 +1,1046 @@
+# Microsoft Developer Studio Generated NMAKE File, Format Version 4.20
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Static Library" 0x0104
+
+!IF "$(CFG)" == ""
+CFG=jpeg - Win32
+!MESSAGE No configuration specified. Defaulting to jpeg - Win32.
+!ENDIF
+
+!IF "$(CFG)" != "jpeg - Win32"
+!MESSAGE Invalid configuration "$(CFG)" specified.
+!MESSAGE You can specify a configuration when running NMAKE on this makefile
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE
+!MESSAGE NMAKE /f "jpeg.mak" CFG="jpeg - Win32"
+!MESSAGE
+!MESSAGE Possible choices for configuration are:
+!MESSAGE
+!MESSAGE "jpeg - Win32" (based on "Win32 (x86) Static Library")
+!MESSAGE
+!ERROR An invalid configuration is specified.
+!ENDIF
+
+!IF "$(OS)" == "Windows_NT"
+NULL=
+!ELSE
+NULL=nul
+!ENDIF
+################################################################################
+# Begin Project
+# PROP Target_Last_Scanned "jpeg - Win32"
+CPP=cl.exe
+
+!IF "$(CFG)" == "jpeg - Win32"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "Release"
+# PROP BASE Intermediate_Dir "Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "Release"
+# PROP Intermediate_Dir "Release"
+# PROP Target_Dir ""
+OUTDIR=.\Release
+INTDIR=.\Release
+
+ALL : "$(OUTDIR)\jpeg.lib"
+
+CLEAN :
+ - at erase "$(INTDIR)\jcapimin.obj"
+ - at erase "$(INTDIR)\jcapistd.obj"
+ - at erase "$(INTDIR)\jctrans.obj"
+ - at erase "$(INTDIR)\jcparam.obj"
+ - at erase "$(INTDIR)\jdatadst.obj"
+ - at erase "$(INTDIR)\jcinit.obj"
+ - at erase "$(INTDIR)\jcmaster.obj"
+ - at erase "$(INTDIR)\jcmarker.obj"
+ - at erase "$(INTDIR)\jcmainct.obj"
+ - at erase "$(INTDIR)\jcprepct.obj"
+ - at erase "$(INTDIR)\jccoefct.obj"
+ - at erase "$(INTDIR)\jccolor.obj"
+ - at erase "$(INTDIR)\jcsample.obj"
+ - at erase "$(INTDIR)\jchuff.obj"
+ - at erase "$(INTDIR)\jcphuff.obj"
+ - at erase "$(INTDIR)\jcdctmgr.obj"
+ - at erase "$(INTDIR)\jfdctfst.obj"
+ - at erase "$(INTDIR)\jfdctflt.obj"
+ - at erase "$(INTDIR)\jfdctint.obj"
+ - at erase "$(INTDIR)\jdapimin.obj"
+ - at erase "$(INTDIR)\jdapistd.obj"
+ - at erase "$(INTDIR)\jdtrans.obj"
+ - at erase "$(INTDIR)\jdatasrc.obj"
+ - at erase "$(INTDIR)\jdmaster.obj"
+ - at erase "$(INTDIR)\jdinput.obj"
+ - at erase "$(INTDIR)\jdmarker.obj"
+ - at erase "$(INTDIR)\jdhuff.obj"
+ - at erase "$(INTDIR)\jdphuff.obj"
+ - at erase "$(INTDIR)\jdmainct.obj"
+ - at erase "$(INTDIR)\jdcoefct.obj"
+ - at erase "$(INTDIR)\jdpostct.obj"
+ - at erase "$(INTDIR)\jddctmgr.obj"
+ - at erase "$(INTDIR)\jidctfst.obj"
+ - at erase "$(INTDIR)\jidctflt.obj"
+ - at erase "$(INTDIR)\jidctint.obj"
+ - at erase "$(INTDIR)\jidctred.obj"
+ - at erase "$(INTDIR)\jdsample.obj"
+ - at erase "$(INTDIR)\jdcolor.obj"
+ - at erase "$(INTDIR)\jquant1.obj"
+ - at erase "$(INTDIR)\jquant2.obj"
+ - at erase "$(INTDIR)\jdmerge.obj"
+ - at erase "$(INTDIR)\jcomapi.obj"
+ - at erase "$(INTDIR)\jutils.obj"
+ - at erase "$(INTDIR)\jerror.obj"
+ - at erase "$(INTDIR)\jmemmgr.obj"
+ - at erase "$(INTDIR)\jmemnobs.obj"
+ - at erase "$(OUTDIR)\jpeg.lib"
+
+"$(OUTDIR)" :
+ if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
+
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
+# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
+CPP_PROJ=/nologo /ML /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS"\
+ /Fp"$(INTDIR)/jpeg.pch" /YX /Fo"$(INTDIR)/" /c
+CPP_OBJS=.\Release/
+CPP_SBRS=.\.
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+BSC32_FLAGS=/nologo /o"$(OUTDIR)/jpeg.bsc"
+BSC32_SBRS= \
+
+LIB32=link.exe -lib
+# ADD BASE LIB32 /nologo
+# ADD LIB32 /nologo
+LIB32_FLAGS=/nologo /out:"$(OUTDIR)/jpeg.lib"
+LIB32_OBJS= \
+ "$(INTDIR)\jcapimin.obj" \
+ "$(INTDIR)\jcapistd.obj" \
+ "$(INTDIR)\jctrans.obj" \
+ "$(INTDIR)\jcparam.obj" \
+ "$(INTDIR)\jdatadst.obj" \
+ "$(INTDIR)\jcinit.obj" \
+ "$(INTDIR)\jcmaster.obj" \
+ "$(INTDIR)\jcmarker.obj" \
+ "$(INTDIR)\jcmainct.obj" \
+ "$(INTDIR)\jcprepct.obj" \
+ "$(INTDIR)\jccoefct.obj" \
+ "$(INTDIR)\jccolor.obj" \
+ "$(INTDIR)\jcsample.obj" \
+ "$(INTDIR)\jchuff.obj" \
+ "$(INTDIR)\jcphuff.obj" \
+ "$(INTDIR)\jcdctmgr.obj" \
+ "$(INTDIR)\jfdctfst.obj" \
+ "$(INTDIR)\jfdctflt.obj" \
+ "$(INTDIR)\jfdctint.obj" \
+ "$(INTDIR)\jdapimin.obj" \
+ "$(INTDIR)\jdapistd.obj" \
+ "$(INTDIR)\jdtrans.obj" \
+ "$(INTDIR)\jdatasrc.obj" \
+ "$(INTDIR)\jdmaster.obj" \
+ "$(INTDIR)\jdinput.obj" \
+ "$(INTDIR)\jdmarker.obj" \
+ "$(INTDIR)\jdhuff.obj" \
+ "$(INTDIR)\jdphuff.obj" \
+ "$(INTDIR)\jdmainct.obj" \
+ "$(INTDIR)\jdcoefct.obj" \
+ "$(INTDIR)\jdpostct.obj" \
+ "$(INTDIR)\jddctmgr.obj" \
+ "$(INTDIR)\jidctfst.obj" \
+ "$(INTDIR)\jidctflt.obj" \
+ "$(INTDIR)\jidctint.obj" \
+ "$(INTDIR)\jidctred.obj" \
+ "$(INTDIR)\jdsample.obj" \
+ "$(INTDIR)\jdcolor.obj" \
+ "$(INTDIR)\jquant1.obj" \
+ "$(INTDIR)\jquant2.obj" \
+ "$(INTDIR)\jdmerge.obj" \
+ "$(INTDIR)\jcomapi.obj" \
+ "$(INTDIR)\jutils.obj" \
+ "$(INTDIR)\jerror.obj" \
+ "$(INTDIR)\jmemmgr.obj" \
+ "$(INTDIR)\jmemnobs.obj"
+
+"$(OUTDIR)\jpeg.lib" : "$(OUTDIR)" $(DEF_FILE) $(LIB32_OBJS)
+ $(LIB32) @<<
+ $(LIB32_FLAGS) $(DEF_FLAGS) $(LIB32_OBJS)
+<<
+
+!ENDIF
+
+.c{$(CPP_OBJS)}.obj:
+ $(CPP) $(CPP_PROJ) $<
+
+.cpp{$(CPP_OBJS)}.obj:
+ $(CPP) $(CPP_PROJ) $<
+
+.cxx{$(CPP_OBJS)}.obj:
+ $(CPP) $(CPP_PROJ) $<
+
+.c{$(CPP_SBRS)}.sbr:
+ $(CPP) $(CPP_PROJ) $<
+
+.cpp{$(CPP_SBRS)}.sbr:
+ $(CPP) $(CPP_PROJ) $<
+
+.cxx{$(CPP_SBRS)}.sbr:
+ $(CPP) $(CPP_PROJ) $<
+
+################################################################################
+# Begin Target
+
+# Name "jpeg - Win32"
+
+!IF "$(CFG)" == "jpeg - Win32"
+
+!ENDIF
+
+################################################################################
+# Begin Source File
+
+SOURCE="jcapimin.c"
+DEP_CPP_JCAPI=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jcapimin.obj" : $(SOURCE) $(DEP_CPP_JCAPI) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jcapistd.c"
+DEP_CPP_JCAPIS=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jcapistd.obj" : $(SOURCE) $(DEP_CPP_JCAPIS) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jccoefct.c"
+DEP_CPP_JCCOE=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jccoefct.obj" : $(SOURCE) $(DEP_CPP_JCCOE) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jccolor.c"
+DEP_CPP_JCCOL=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jccolor.obj" : $(SOURCE) $(DEP_CPP_JCCOL) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jcdctmgr.c"
+DEP_CPP_JCDCT=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jdct.h"\
+
+
+"$(INTDIR)\jcdctmgr.obj" : $(SOURCE) $(DEP_CPP_JCDCT) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jchuff.c"
+DEP_CPP_JCHUF=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jchuff.h"\
+
+
+"$(INTDIR)\jchuff.obj" : $(SOURCE) $(DEP_CPP_JCHUF) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jcinit.c"
+DEP_CPP_JCINI=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jcinit.obj" : $(SOURCE) $(DEP_CPP_JCINI) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jcmainct.c"
+DEP_CPP_JCMAI=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jcmainct.obj" : $(SOURCE) $(DEP_CPP_JCMAI) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jcmarker.c"
+DEP_CPP_JCMAR=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jcmarker.obj" : $(SOURCE) $(DEP_CPP_JCMAR) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jcmaster.c"
+DEP_CPP_JCMAS=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jcmaster.obj" : $(SOURCE) $(DEP_CPP_JCMAS) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jcomapi.c"
+DEP_CPP_JCOMA=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jcomapi.obj" : $(SOURCE) $(DEP_CPP_JCOMA) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jcparam.c"
+DEP_CPP_JCPAR=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jcparam.obj" : $(SOURCE) $(DEP_CPP_JCPAR) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jcphuff.c"
+DEP_CPP_JCPHU=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jchuff.h"\
+
+
+"$(INTDIR)\jcphuff.obj" : $(SOURCE) $(DEP_CPP_JCPHU) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jcprepct.c"
+DEP_CPP_JCPRE=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jcprepct.obj" : $(SOURCE) $(DEP_CPP_JCPRE) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jcsample.c"
+DEP_CPP_JCSAM=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jcsample.obj" : $(SOURCE) $(DEP_CPP_JCSAM) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jctrans.c"
+DEP_CPP_JCTRA=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jctrans.obj" : $(SOURCE) $(DEP_CPP_JCTRA) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdapimin.c"
+DEP_CPP_JDAPI=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdapimin.obj" : $(SOURCE) $(DEP_CPP_JDAPI) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdapistd.c"
+DEP_CPP_JDAPIS=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdapistd.obj" : $(SOURCE) $(DEP_CPP_JDAPIS) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdatadst.c"
+DEP_CPP_JDATA=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdatadst.obj" : $(SOURCE) $(DEP_CPP_JDATA) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdatasrc.c"
+DEP_CPP_JDATAS=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdatasrc.obj" : $(SOURCE) $(DEP_CPP_JDATAS) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdcoefct.c"
+DEP_CPP_JDCOE=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdcoefct.obj" : $(SOURCE) $(DEP_CPP_JDCOE) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdcolor.c"
+DEP_CPP_JDCOL=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdcolor.obj" : $(SOURCE) $(DEP_CPP_JDCOL) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jddctmgr.c"
+DEP_CPP_JDDCT=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jdct.h"\
+
+
+"$(INTDIR)\jddctmgr.obj" : $(SOURCE) $(DEP_CPP_JDDCT) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdhuff.c"
+DEP_CPP_JDHUF=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jdhuff.h"\
+
+
+"$(INTDIR)\jdhuff.obj" : $(SOURCE) $(DEP_CPP_JDHUF) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdinput.c"
+DEP_CPP_JDINP=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdinput.obj" : $(SOURCE) $(DEP_CPP_JDINP) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdmainct.c"
+DEP_CPP_JDMAI=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdmainct.obj" : $(SOURCE) $(DEP_CPP_JDMAI) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdmarker.c"
+DEP_CPP_JDMAR=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdmarker.obj" : $(SOURCE) $(DEP_CPP_JDMAR) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdmaster.c"
+DEP_CPP_JDMAS=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdmaster.obj" : $(SOURCE) $(DEP_CPP_JDMAS) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdmerge.c"
+DEP_CPP_JDMER=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdmerge.obj" : $(SOURCE) $(DEP_CPP_JDMER) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdphuff.c"
+DEP_CPP_JDPHU=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jdhuff.h"\
+
+
+"$(INTDIR)\jdphuff.obj" : $(SOURCE) $(DEP_CPP_JDPHU) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdpostct.c"
+DEP_CPP_JDPOS=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdpostct.obj" : $(SOURCE) $(DEP_CPP_JDPOS) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdsample.c"
+DEP_CPP_JDSAM=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdsample.obj" : $(SOURCE) $(DEP_CPP_JDSAM) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jdtrans.c"
+DEP_CPP_JDTRA=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jdtrans.obj" : $(SOURCE) $(DEP_CPP_JDTRA) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jerror.c"
+DEP_CPP_JERRO=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jversion.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jerror.obj" : $(SOURCE) $(DEP_CPP_JERRO) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jfdctflt.c"
+DEP_CPP_JFDCT=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jdct.h"\
+
+
+"$(INTDIR)\jfdctflt.obj" : $(SOURCE) $(DEP_CPP_JFDCT) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jfdctfst.c"
+DEP_CPP_JFDCTF=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jdct.h"\
+
+
+"$(INTDIR)\jfdctfst.obj" : $(SOURCE) $(DEP_CPP_JFDCTF) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jfdctint.c"
+DEP_CPP_JFDCTI=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jdct.h"\
+
+
+"$(INTDIR)\jfdctint.obj" : $(SOURCE) $(DEP_CPP_JFDCTI) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jidctflt.c"
+DEP_CPP_JIDCT=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jdct.h"\
+
+
+"$(INTDIR)\jidctflt.obj" : $(SOURCE) $(DEP_CPP_JIDCT) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jidctfst.c"
+DEP_CPP_JIDCTF=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jdct.h"\
+
+
+"$(INTDIR)\jidctfst.obj" : $(SOURCE) $(DEP_CPP_JIDCTF) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jidctint.c"
+DEP_CPP_JIDCTI=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jdct.h"\
+
+
+"$(INTDIR)\jidctint.obj" : $(SOURCE) $(DEP_CPP_JIDCTI) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jidctred.c"
+DEP_CPP_JIDCTR=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jdct.h"\
+
+
+"$(INTDIR)\jidctred.obj" : $(SOURCE) $(DEP_CPP_JIDCTR) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jquant1.c"
+DEP_CPP_JQUAN=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jquant1.obj" : $(SOURCE) $(DEP_CPP_JQUAN) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jquant2.c"
+DEP_CPP_JQUANT=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jquant2.obj" : $(SOURCE) $(DEP_CPP_JQUANT) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jutils.c"
+DEP_CPP_JUTIL=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+
+
+"$(INTDIR)\jutils.obj" : $(SOURCE) $(DEP_CPP_JUTIL) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jmemmgr.c"
+DEP_CPP_JMEMM=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jmemsys.h"\
+
+
+"$(INTDIR)\jmemmgr.obj" : $(SOURCE) $(DEP_CPP_JMEMM) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+################################################################################
+# Begin Source File
+
+SOURCE="jmemnobs.c"
+DEP_CPP_JMEMN=\
+ "jinclude.h"\
+ "jconfig.h"\
+ "jpeglib.h"\
+ "jmorecfg.h"\
+ "jpegint.h"\
+ "jerror.h"\
+ "jmemsys.h"\
+
+
+"$(INTDIR)\jmemnobs.obj" : $(SOURCE) $(DEP_CPP_JMEMN) "$(INTDIR)"
+ $(CPP) $(CPP_PROJ) $(SOURCE)
+
+
+# End Source File
+# End Target
+# End Project
+################################################################################
+
diff --git a/jpeg-6c/makeproj.mac b/jpeg-6c/makeproj.mac
new file mode 100644
index 0000000..ed277c8
--- /dev/null
+++ b/jpeg-6c/makeproj.mac
@@ -0,0 +1,213 @@
+--
+-- makeproj.mac
+--
+-- This AppleScript builds Code Warrior PRO Release 2 project files for the
+-- libjpeg library as well as the test programs 'cjpeg', 'djpeg', 'jpegtran'.
+-- (We'd distribute real project files, except they're not text
+-- and would create maintenance headaches.)
+--
+-- The script then compiles and links the library and the test programs.
+-- NOTE: if you haven't already created a 'jconfig.h' file, the script
+-- automatically copies 'jconfig.mac' to 'jconfig.h'.
+--
+-- To use this script, you must have AppleScript 1.1 or later installed
+-- and a suitable AppleScript editor like Script Editor or Script Debugger
+-- (http://www.latenightsw.com). Open this file with your AppleScript
+-- editor and execute the "run" command to build the projects.
+--
+-- Thanks to Dan Sears and Don Agro for this script.
+-- Questions about this script can be addressed to dogpark at interlog.com
+--
+
+on run
+
+ choose folder with prompt ">>> Select IJG source folder <<<"
+ set ijg_folder to result
+
+ choose folder with prompt ">>> Select MetroWerks folder <<<"
+ set cw_folder to result
+
+ -- if jconfig.h doesn't already exist, copy jconfig.mac
+
+ tell application "Finder"
+ if not (exists file "jconfig.h" of ijg_folder) then
+ duplicate {file "jconfig.mac" of folder ijg_folder}
+ select file "jconfig.mac copy" of folder ijg_folder
+ set name of selection to "jconfig.h"
+ end if
+ end tell
+
+ tell application "CodeWarrior IDE 2.1"
+ with timeout of 10000 seconds
+
+ -- create libjpeg project
+
+ activate
+ Create Project (ijg_folder as string) & "libjpeg.proj"
+ Set Preferences of panel "Target Settings" to {Target Name:"libjpeg"}
+ Set Preferences of panel "PPC Project" to {File Name:"libjpeg"}
+ Set Preferences of panel "Target Settings" to {Linker:"MacOS PPC Linker"}
+ Set Preferences of panel "PPC Project" to {Project Type:library}
+ Set Preferences of panel "C/C++ Compiler" to {ANSI Strict:true}
+ Set Preferences of panel "C/C++ Compiler" to {Enums Always Ints:true}
+ Set Preferences of panel "PPC Codegen" to {Struct Alignment:PowerPC}
+ Set Preferences of panel "PPC Linker" to {Generate SYM File:false}
+
+ Add Files (ijg_folder as string) & "jcapimin.c" To Segment 1
+ Add Files (ijg_folder as string) & "jcapistd.c" To Segment 1
+ Add Files (ijg_folder as string) & "jctrans.c" To Segment 1
+ Add Files (ijg_folder as string) & "jcparam.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdatadst.c" To Segment 1
+ Add Files (ijg_folder as string) & "jcinit.c" To Segment 1
+ Add Files (ijg_folder as string) & "jcmaster.c" To Segment 1
+ Add Files (ijg_folder as string) & "jcmarker.c" To Segment 1
+ Add Files (ijg_folder as string) & "jcmainct.c" To Segment 1
+ Add Files (ijg_folder as string) & "jcprepct.c" To Segment 1
+ Add Files (ijg_folder as string) & "jccoefct.c" To Segment 1
+ Add Files (ijg_folder as string) & "jccolor.c" To Segment 1
+ Add Files (ijg_folder as string) & "jcsample.c" To Segment 1
+ Add Files (ijg_folder as string) & "jchuff.c" To Segment 1
+ Add Files (ijg_folder as string) & "jcphuff.c" To Segment 1
+ Add Files (ijg_folder as string) & "jcdctmgr.c" To Segment 1
+ Add Files (ijg_folder as string) & "jfdctfst.c" To Segment 1
+ Add Files (ijg_folder as string) & "jfdctflt.c" To Segment 1
+ Add Files (ijg_folder as string) & "jfdctint.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdapimin.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdapistd.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdtrans.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdatasrc.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdmaster.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdinput.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdmarker.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdhuff.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdphuff.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdmainct.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdcoefct.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdpostct.c" To Segment 1
+ Add Files (ijg_folder as string) & "jddctmgr.c" To Segment 1
+ Add Files (ijg_folder as string) & "jidctfst.c" To Segment 1
+ Add Files (ijg_folder as string) & "jidctflt.c" To Segment 1
+ Add Files (ijg_folder as string) & "jidctint.c" To Segment 1
+ Add Files (ijg_folder as string) & "jidctred.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdsample.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdcolor.c" To Segment 1
+ Add Files (ijg_folder as string) & "jquant1.c" To Segment 1
+ Add Files (ijg_folder as string) & "jquant2.c" To Segment 1
+ Add Files (ijg_folder as string) & "jdmerge.c" To Segment 1
+ Add Files (ijg_folder as string) & "jcomapi.c" To Segment 1
+ Add Files (ijg_folder as string) & "jutils.c" To Segment 1
+ Add Files (ijg_folder as string) & "jerror.c" To Segment 1
+ Add Files (ijg_folder as string) & "jmemmgr.c" To Segment 1
+ Add Files (ijg_folder as string) & "jmemmac.c" To Segment 1
+
+ -- compile and link the library
+
+ Make Project
+ Close Project
+
+ -- create cjpeg project
+
+ activate
+ Create Project (ijg_folder as string) & "cjpeg.proj"
+ Set Preferences of panel "Target Settings" to {Target Name:"cjpeg"}
+ Set Preferences of panel "PPC Project" to {File Name:"cjpeg"}
+ Set Preferences of panel "Target Settings" to {Linker:"MacOS PPC Linker"}
+ Set Preferences of panel "C/C++ Compiler" to {ANSI Strict:true}
+ Set Preferences of panel "C/C++ Compiler" to {Enums Always Ints:true}
+ Set Preferences of panel "PPC Codegen" to {Struct Alignment:PowerPC}
+ Set Preferences of panel "PPC Linker" to {Generate SYM File:false}
+
+ Add Files (ijg_folder as string) & "cjpeg.c" To Segment 1
+ Add Files (ijg_folder as string) & "rdppm.c" To Segment 1
+ Add Files (ijg_folder as string) & "rdgif.c" To Segment 1
+ Add Files (ijg_folder as string) & "rdtarga.c" To Segment 1
+ Add Files (ijg_folder as string) & "rdrle.c" To Segment 1
+ Add Files (ijg_folder as string) & "rdbmp.c" To Segment 1
+ Add Files (ijg_folder as string) & "rdswitch.c" To Segment 1
+ Add Files (ijg_folder as string) & "cdjpeg.c" To Segment 1
+
+ Add Files (ijg_folder as string) & "libjpeg" To Segment 2
+
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:Metrowerks Standard Library:MSL C:Bin:MSL C.PPC.Lib" To Segment 3
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:Metrowerks Standard Library:MSL C:Bin:MSL SIOUX.PPC.Lib" To Segment 3
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:Runtime:Runtime PPC:MSL RuntimePPC.Lib" To Segment 3
+
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:MacOS Common:InterfaceLib" To Segment 4
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:MacOS Common:MathLib" To Segment 4
+
+ -- compile and link cjpeg
+
+ Make Project
+ Close Project
+
+ -- create djpeg project
+
+ activate
+ Create Project (ijg_folder as string) & "djpeg.proj"
+ Set Preferences of panel "Target Settings" to {Target Name:"djpeg"}
+ Set Preferences of panel "PPC Project" to {File Name:"djpeg"}
+ Set Preferences of panel "Target Settings" to {Linker:"MacOS PPC Linker"}
+ Set Preferences of panel "C/C++ Compiler" to {ANSI Strict:true}
+ Set Preferences of panel "C/C++ Compiler" to {Enums Always Ints:true}
+ Set Preferences of panel "PPC Codegen" to {Struct Alignment:PowerPC}
+ Set Preferences of panel "PPC Linker" to {Generate SYM File:false}
+
+ Add Files (ijg_folder as string) & "djpeg.c" To Segment 1
+ Add Files (ijg_folder as string) & "wrppm.c" To Segment 1
+ Add Files (ijg_folder as string) & "wrgif.c" To Segment 1
+ Add Files (ijg_folder as string) & "wrtarga.c" To Segment 1
+ Add Files (ijg_folder as string) & "wrrle.c" To Segment 1
+ Add Files (ijg_folder as string) & "wrbmp.c" To Segment 1
+ Add Files (ijg_folder as string) & "rdcolmap.c" To Segment 1
+ Add Files (ijg_folder as string) & "cdjpeg.c" To Segment 1
+
+ Add Files (ijg_folder as string) & "libjpeg" To Segment 2
+
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:Metrowerks Standard Library:MSL C:Bin:MSL C.PPC.Lib" To Segment 3
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:Metrowerks Standard Library:MSL C:Bin:MSL SIOUX.PPC.Lib" To Segment 3
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:Runtime:Runtime PPC:MSL RuntimePPC.Lib" To Segment 3
+
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:MacOS Common:InterfaceLib" To Segment 4
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:MacOS Common:MathLib" To Segment 4
+
+ -- compile and link djpeg
+
+ Make Project
+ Close Project
+
+ -- create jpegtran project
+
+ activate
+ Create Project (ijg_folder as string) & "jpegtran.proj"
+ Set Preferences of panel "Target Settings" to {Target Name:"jpegtran"}
+ Set Preferences of panel "PPC Project" to {File Name:"jpegtran"}
+ Set Preferences of panel "Target Settings" to {Linker:"MacOS PPC Linker"}
+ Set Preferences of panel "C/C++ Compiler" to {ANSI Strict:true}
+ Set Preferences of panel "C/C++ Compiler" to {Enums Always Ints:true}
+ Set Preferences of panel "PPC Codegen" to {Struct Alignment:PowerPC}
+ Set Preferences of panel "PPC Linker" to {Generate SYM File:false}
+
+ Add Files (ijg_folder as string) & "jpegtran.c" To Segment 1
+ Add Files (ijg_folder as string) & "rdswitch.c" To Segment 1
+ Add Files (ijg_folder as string) & "cdjpeg.c" To Segment 1
+ Add Files (ijg_folder as string) & "transupp.c" To Segment 1
+
+ Add Files (ijg_folder as string) & "libjpeg" To Segment 2
+
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:Metrowerks Standard Library:MSL C:Bin:MSL C.PPC.Lib" To Segment 3
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:Metrowerks Standard Library:MSL C:Bin:MSL SIOUX.PPC.Lib" To Segment 3
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:Runtime:Runtime PPC:MSL RuntimePPC.Lib" To Segment 3
+
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:MacOS Common:InterfaceLib" To Segment 4
+ Add Files (cw_folder as string) & "Metrowerks CodeWarrior:MacOS Support:Libraries:MacOS Common:MathLib" To Segment 4
+
+ -- compile and link jpegtran
+
+ Make Project
+ Close Project
+
+ quit
+
+ end timeout
+ end tell
+end run
diff --git a/jpeg-6c/makljpeg.st b/jpeg-6c/makljpeg.st
new file mode 100644
index 0000000..813493e
--- /dev/null
+++ b/jpeg-6c/makljpeg.st
@@ -0,0 +1,70 @@
+; Project file for Independent JPEG Group's software
+;
+; This project file is for Atari ST/STE/TT systems using Pure C or Turbo C.
+; Thanks to Frank Moehle (Frank.Moehle at arbi.informatik.uni-oldenburg.de),
+; Dr. B. Setzepfandt (bernd at gina.uni-muenster.de),
+; and Guido Vollbeding (guivol at esc.de).
+;
+; To use this file, rename it to libjpeg.prj.
+; Read installation instructions before trying to make the program!
+;
+;
+; * * * Output file * * *
+libjpeg.lib
+;
+; * * * COMPILER OPTIONS * * *
+.C[-P] ; absolute calls
+.C[-M] ; and no string merging, folks
+.C[-w-cln] ; no "constant is long" warnings
+.C[-w-par] ; no "parameter xxxx unused"
+.C[-w-rch] ; no "unreachable code"
+.C[-wsig] ; warn if significant digits may be lost
+.L[-J] ; link new Obj-format (so we get a library)
+=
+; * * * * List of modules * * * *
+jcapimin.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jcapistd.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jccoefct.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jccolor.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jcdctmgr.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h)
+jchuff.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jchuff.h)
+jcinit.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jcmainct.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jcmarker.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jcmaster.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jcomapi.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jcparam.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jcphuff.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jchuff.h)
+jcprepct.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jcsample.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jctrans.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jdapimin.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jdapistd.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jdatadst.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h)
+jdatasrc.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h)
+jdcoefct.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jdcolor.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jddctmgr.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h)
+jdhuff.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdhuff.h)
+jdinput.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jdmainct.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jdmarker.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jdmaster.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jdmerge.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jdphuff.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdhuff.h)
+jdpostct.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jdsample.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jdtrans.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jerror.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jversion.h,jerror.h)
+jfdctflt.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h)
+jfdctfst.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h)
+jfdctint.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h)
+jidctflt.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h)
+jidctfst.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h)
+jidctint.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h)
+jidctred.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jdct.h)
+jquant1.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jquant2.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jutils.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h)
+jmemmgr.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jmemsys.h)
+jmemansi.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,jmemsys.h)
diff --git a/jpeg-6c/maktjpeg.st b/jpeg-6c/maktjpeg.st
new file mode 100644
index 0000000..31f4d16
--- /dev/null
+++ b/jpeg-6c/maktjpeg.st
@@ -0,0 +1,32 @@
+; Project file for Independent JPEG Group's software
+;
+; This project file is for Atari ST/STE/TT systems using Pure C or Turbo C.
+; Thanks to Frank Moehle (Frank.Moehle at arbi.informatik.uni-oldenburg.de),
+; Dr. B. Setzepfandt (bernd at gina.uni-muenster.de),
+; and Guido Vollbeding (guivol at esc.de).
+;
+; To use this file, rename it to jpegtran.prj.
+; If you are using Turbo C, change filenames beginning with "pc..." to "tc..."
+; Read installation instructions before trying to make the program!
+;
+;
+; * * * Output file * * *
+jpegtran.ttp
+;
+; * * * COMPILER OPTIONS * * *
+.C[-P] ; absolute calls
+.C[-M] ; and no string merging, folks
+.C[-w-cln] ; no "constant is long" warnings
+.C[-w-par] ; no "parameter xxxx unused"
+.C[-w-rch] ; no "unreachable code"
+.C[-wsig] ; warn if significant digits may be lost
+=
+; * * * * List of modules * * * *
+pcstart.o
+jpegtran.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h,transupp.h,jversion.h)
+cdjpeg.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+rdswitch.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h)
+transupp.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,transupp.h)
+libjpeg.lib ; built by libjpeg.prj
+pcstdlib.lib ; standard library
+pcextlib.lib ; extended library
diff --git a/jpeg-6c/makvms.opt b/jpeg-6c/makvms.opt
new file mode 100644
index 0000000..675e8fe
--- /dev/null
+++ b/jpeg-6c/makvms.opt
@@ -0,0 +1,4 @@
+! A pointer to the VAX/VMS C Run-Time Shareable Library.
+! This file is needed by makefile.mms and makefile.vms,
+! but only for the older VAX C compiler. DEC C does not need it.
+Sys$Library:VAXCRTL.EXE /Share
diff --git a/jpeg-6c/rdbmp.c b/jpeg-6c/rdbmp.c
new file mode 100644
index 0000000..b05fe2a
--- /dev/null
+++ b/jpeg-6c/rdbmp.c
@@ -0,0 +1,439 @@
+/*
+ * rdbmp.c
+ *
+ * Copyright (C) 1994-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to read input images in Microsoft "BMP"
+ * format (MS Windows 3.x, OS/2 1.x, and OS/2 2.x flavors).
+ * Currently, only 8-bit and 24-bit images are supported, not 1-bit or
+ * 4-bit (feeding such low-depth images into JPEG would be silly anyway).
+ * Also, we don't support RLE-compressed files.
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications. As they stand, they assume input from
+ * an ordinary stdio stream. They further assume that reading begins
+ * at the start of the file; start_input may need work if the
+ * user interface has already read some data (e.g., to determine that
+ * the file is indeed BMP format).
+ *
+ * This code contributed by James Arthur Boucher.
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+
+#ifdef BMP_SUPPORTED
+
+
+/* Macros to deal with unsigned chars as efficiently as compiler allows */
+
+#ifdef HAVE_UNSIGNED_CHAR
+typedef unsigned char U_CHAR;
+#define UCH(x) ((int) (x))
+#else /* !HAVE_UNSIGNED_CHAR */
+#ifdef CHAR_IS_UNSIGNED
+typedef char U_CHAR;
+#define UCH(x) ((int) (x))
+#else
+typedef char U_CHAR;
+#define UCH(x) ((int) (x) & 0xFF)
+#endif
+#endif /* HAVE_UNSIGNED_CHAR */
+
+
+#define ReadOK(file,buffer,len) (JFREAD(file,buffer,len) == ((size_t) (len)))
+
+
+/* Private version of data source object */
+
+typedef struct _bmp_source_struct * bmp_source_ptr;
+
+typedef struct _bmp_source_struct {
+ struct cjpeg_source_struct pub; /* public fields */
+
+ j_compress_ptr cinfo; /* back link saves passing separate parm */
+
+ JSAMPARRAY colormap; /* BMP colormap (converted to my format) */
+
+ jvirt_sarray_ptr whole_image; /* Needed to reverse row order */
+ JDIMENSION source_row; /* Current source row number */
+ JDIMENSION row_width; /* Physical width of scanlines in file */
+
+ int bits_per_pixel; /* remembers 8- or 24-bit format */
+} bmp_source_struct;
+
+
+LOCAL(int)
+read_byte (bmp_source_ptr sinfo)
+/* Read next byte from BMP file */
+{
+ register FILE *infile = sinfo->pub.input_file;
+ register int c;
+
+ if ((c = getc(infile)) == EOF)
+ ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
+ return c;
+}
+
+
+LOCAL(void)
+read_colormap (bmp_source_ptr sinfo, int cmaplen, int mapentrysize)
+/* Read the colormap from a BMP file */
+{
+ int i;
+
+ switch (mapentrysize) {
+ case 3:
+ /* BGR format (occurs in OS/2 files) */
+ for (i = 0; i < cmaplen; i++) {
+ sinfo->colormap[2][i] = (JSAMPLE) read_byte(sinfo);
+ sinfo->colormap[1][i] = (JSAMPLE) read_byte(sinfo);
+ sinfo->colormap[0][i] = (JSAMPLE) read_byte(sinfo);
+ }
+ break;
+ case 4:
+ /* BGR0 format (occurs in MS Windows files) */
+ for (i = 0; i < cmaplen; i++) {
+ sinfo->colormap[2][i] = (JSAMPLE) read_byte(sinfo);
+ sinfo->colormap[1][i] = (JSAMPLE) read_byte(sinfo);
+ sinfo->colormap[0][i] = (JSAMPLE) read_byte(sinfo);
+ (void) read_byte(sinfo);
+ }
+ break;
+ default:
+ ERREXIT(sinfo->cinfo, JERR_BMP_BADCMAP);
+ break;
+ }
+}
+
+
+/*
+ * Read one row of pixels.
+ * The image has been read into the whole_image array, but is otherwise
+ * unprocessed. We must read it out in top-to-bottom row order, and if
+ * it is an 8-bit image, we must expand colormapped pixels to 24bit format.
+ */
+
+METHODDEF(JDIMENSION)
+get_8bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading 8-bit colormap indexes */
+{
+ bmp_source_ptr source = (bmp_source_ptr) sinfo;
+ register JSAMPARRAY colormap = source->colormap;
+ JSAMPARRAY image_ptr;
+ register int t;
+ register JSAMPROW inptr, outptr;
+ register JDIMENSION col;
+
+ /* Fetch next row from virtual array */
+ source->source_row--;
+ image_ptr = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, source->whole_image,
+ source->source_row, (JDIMENSION) 1, FALSE);
+
+ /* Expand the colormap indexes to real data */
+ inptr = image_ptr[0];
+ outptr = source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ t = GETJSAMPLE(*inptr++);
+ *outptr++ = colormap[0][t]; /* can omit GETJSAMPLE() safely */
+ *outptr++ = colormap[1][t];
+ *outptr++ = colormap[2][t];
+ }
+
+ return 1;
+}
+
+
+METHODDEF(JDIMENSION)
+get_24bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading 24-bit pixels */
+{
+ bmp_source_ptr source = (bmp_source_ptr) sinfo;
+ JSAMPARRAY image_ptr;
+ register JSAMPROW inptr, outptr;
+ register JDIMENSION col;
+
+ /* Fetch next row from virtual array */
+ source->source_row--;
+ image_ptr = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, source->whole_image,
+ source->source_row, (JDIMENSION) 1, FALSE);
+
+ /* Transfer data. Note source values are in BGR order
+ * (even though Microsoft's own documents say the opposite).
+ */
+ inptr = image_ptr[0];
+ outptr = source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ outptr[2] = *inptr++; /* can omit GETJSAMPLE() safely */
+ outptr[1] = *inptr++;
+ outptr[0] = *inptr++;
+ outptr += 3;
+ }
+
+ return 1;
+}
+
+
+/*
+ * This method loads the image into whole_image during the first call on
+ * get_pixel_rows. The get_pixel_rows pointer is then adjusted to call
+ * get_8bit_row or get_24bit_row on subsequent calls.
+ */
+
+METHODDEF(JDIMENSION)
+preload_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ bmp_source_ptr source = (bmp_source_ptr) sinfo;
+ register FILE *infile = source->pub.input_file;
+ register int c;
+ register JSAMPROW out_ptr;
+ JSAMPARRAY image_ptr;
+ JDIMENSION row, col;
+ cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
+
+ /* Read the data into a virtual array in input-file row order. */
+ for (row = 0; row < cinfo->image_height; row++) {
+ if (progress != NULL) {
+ progress->pub.pass_counter = (long) row;
+ progress->pub.pass_limit = (long) cinfo->image_height;
+ (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
+ }
+ image_ptr = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, source->whole_image,
+ row, (JDIMENSION) 1, TRUE);
+ out_ptr = image_ptr[0];
+ for (col = source->row_width; col > 0; col--) {
+ /* inline copy of read_byte() for speed */
+ if ((c = getc(infile)) == EOF)
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ *out_ptr++ = (JSAMPLE) c;
+ }
+ }
+ if (progress != NULL)
+ progress->completed_extra_passes++;
+
+ /* Set up to read from the virtual array in top-to-bottom order */
+ switch (source->bits_per_pixel) {
+ case 8:
+ source->pub.get_pixel_rows = get_8bit_row;
+ break;
+ case 24:
+ source->pub.get_pixel_rows = get_24bit_row;
+ break;
+ default:
+ ERREXIT(cinfo, JERR_BMP_BADDEPTH);
+ }
+ source->source_row = cinfo->image_height;
+
+ /* And read the first row */
+ return (*source->pub.get_pixel_rows) (cinfo, sinfo);
+}
+
+
+/*
+ * Read the file header; return image size and component count.
+ */
+
+METHODDEF(void)
+start_input_bmp (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ bmp_source_ptr source = (bmp_source_ptr) sinfo;
+ U_CHAR bmpfileheader[14];
+ U_CHAR bmpinfoheader[64];
+#define GET_2B(array,offset) ((unsigned int) UCH(array[offset]) + \
+ (((unsigned int) UCH(array[offset+1])) << 8))
+#define GET_4B(array,offset) ((INT32) UCH(array[offset]) + \
+ (((INT32) UCH(array[offset+1])) << 8) + \
+ (((INT32) UCH(array[offset+2])) << 16) + \
+ (((INT32) UCH(array[offset+3])) << 24))
+ INT32 bfOffBits;
+ INT32 headerSize;
+ INT32 biWidth = 0; /* initialize to avoid compiler warning */
+ INT32 biHeight = 0;
+ unsigned int biPlanes;
+ INT32 biCompression;
+ INT32 biXPelsPerMeter,biYPelsPerMeter;
+ INT32 biClrUsed = 0;
+ int mapentrysize = 0; /* 0 indicates no colormap */
+ INT32 bPad;
+ JDIMENSION row_width;
+
+ /* Read and verify the bitmap file header */
+ if (! ReadOK(source->pub.input_file, bmpfileheader, 14))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ if (GET_2B(bmpfileheader,0) != 0x4D42) /* 'BM' */
+ ERREXIT(cinfo, JERR_BMP_NOT);
+ bfOffBits = (INT32) GET_4B(bmpfileheader,10);
+ /* We ignore the remaining fileheader fields */
+
+ /* The infoheader might be 12 bytes (OS/2 1.x), 40 bytes (Windows),
+ * or 64 bytes (OS/2 2.x). Check the first 4 bytes to find out which.
+ */
+ if (! ReadOK(source->pub.input_file, bmpinfoheader, 4))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ headerSize = (INT32) GET_4B(bmpinfoheader,0);
+ if (headerSize < 12 || headerSize > 64)
+ ERREXIT(cinfo, JERR_BMP_BADHEADER);
+ if (! ReadOK(source->pub.input_file, bmpinfoheader+4, headerSize-4))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+
+ switch ((int) headerSize) {
+ case 12:
+ /* Decode OS/2 1.x header (Microsoft calls this a BITMAPCOREHEADER) */
+ biWidth = (INT32) GET_2B(bmpinfoheader,4);
+ biHeight = (INT32) GET_2B(bmpinfoheader,6);
+ biPlanes = GET_2B(bmpinfoheader,8);
+ source->bits_per_pixel = (int) GET_2B(bmpinfoheader,10);
+
+ switch (source->bits_per_pixel) {
+ case 8: /* colormapped image */
+ mapentrysize = 3; /* OS/2 uses RGBTRIPLE colormap */
+ TRACEMS2(cinfo, 1, JTRC_BMP_OS2_MAPPED, (int) biWidth, (int) biHeight);
+ break;
+ case 24: /* RGB image */
+ TRACEMS2(cinfo, 1, JTRC_BMP_OS2, (int) biWidth, (int) biHeight);
+ break;
+ default:
+ ERREXIT(cinfo, JERR_BMP_BADDEPTH);
+ break;
+ }
+ if (biPlanes != 1)
+ ERREXIT(cinfo, JERR_BMP_BADPLANES);
+ break;
+ case 40:
+ case 64:
+ /* Decode Windows 3.x header (Microsoft calls this a BITMAPINFOHEADER) */
+ /* or OS/2 2.x header, which has additional fields that we ignore */
+ biWidth = GET_4B(bmpinfoheader,4);
+ biHeight = GET_4B(bmpinfoheader,8);
+ biPlanes = GET_2B(bmpinfoheader,12);
+ source->bits_per_pixel = (int) GET_2B(bmpinfoheader,14);
+ biCompression = GET_4B(bmpinfoheader,16);
+ biXPelsPerMeter = GET_4B(bmpinfoheader,24);
+ biYPelsPerMeter = GET_4B(bmpinfoheader,28);
+ biClrUsed = GET_4B(bmpinfoheader,32);
+ /* biSizeImage, biClrImportant fields are ignored */
+
+ switch (source->bits_per_pixel) {
+ case 8: /* colormapped image */
+ mapentrysize = 4; /* Windows uses RGBQUAD colormap */
+ TRACEMS2(cinfo, 1, JTRC_BMP_MAPPED, (int) biWidth, (int) biHeight);
+ break;
+ case 24: /* RGB image */
+ TRACEMS2(cinfo, 1, JTRC_BMP, (int) biWidth, (int) biHeight);
+ break;
+ default:
+ ERREXIT(cinfo, JERR_BMP_BADDEPTH);
+ break;
+ }
+ if (biPlanes != 1)
+ ERREXIT(cinfo, JERR_BMP_BADPLANES);
+ if (biCompression != 0)
+ ERREXIT(cinfo, JERR_BMP_COMPRESSED);
+
+ if (biXPelsPerMeter > 0 && biYPelsPerMeter > 0) {
+ /* Set JFIF density parameters from the BMP data */
+ cinfo->X_density = (UINT16) (biXPelsPerMeter/100); /* 100 cm per meter */
+ cinfo->Y_density = (UINT16) (biYPelsPerMeter/100);
+ cinfo->density_unit = 2; /* dots/cm */
+ }
+ break;
+ default:
+ ERREXIT(cinfo, JERR_BMP_BADHEADER);
+ break;
+ }
+
+ /* Compute distance to bitmap data --- will adjust for colormap below */
+ bPad = bfOffBits - (headerSize + 14);
+
+ /* Read the colormap, if any */
+ if (mapentrysize > 0) {
+ if (biClrUsed <= 0)
+ biClrUsed = 256; /* assume it's 256 */
+ else if (biClrUsed > 256)
+ ERREXIT(cinfo, JERR_BMP_BADCMAP);
+ /* Allocate space to store the colormap */
+ source->colormap = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) biClrUsed, (JDIMENSION) 3);
+ /* and read it from the file */
+ read_colormap(source, (int) biClrUsed, mapentrysize);
+ /* account for size of colormap */
+ bPad -= biClrUsed * mapentrysize;
+ }
+
+ /* Skip any remaining pad bytes */
+ if (bPad < 0) /* incorrect bfOffBits value? */
+ ERREXIT(cinfo, JERR_BMP_BADHEADER);
+ while (--bPad >= 0) {
+ (void) read_byte(source);
+ }
+
+ /* Compute row width in file, including padding to 4-byte boundary */
+ if (source->bits_per_pixel == 24)
+ row_width = (JDIMENSION) (biWidth * 3);
+ else
+ row_width = (JDIMENSION) biWidth;
+ while ((row_width & 3) != 0) row_width++;
+ source->row_width = row_width;
+
+ /* Allocate space for inversion array, prepare for preload pass */
+ source->whole_image = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ row_width, (JDIMENSION) biHeight, (JDIMENSION) 1);
+ source->pub.get_pixel_rows = preload_image;
+ if (cinfo->progress != NULL) {
+ cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
+ progress->total_extra_passes++; /* count file input as separate pass */
+ }
+
+ /* Allocate one-row buffer for returned data */
+ source->pub.buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) (biWidth * 3), (JDIMENSION) 1);
+ source->pub.buffer_height = 1;
+
+ cinfo->in_color_space = JCS_RGB;
+ cinfo->input_components = 3;
+ cinfo->data_precision = 8;
+ cinfo->image_width = (JDIMENSION) biWidth;
+ cinfo->image_height = (JDIMENSION) biHeight;
+}
+
+
+/*
+ * Finish up at the end of the file.
+ */
+
+METHODDEF(void)
+finish_input_bmp (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ /* no work */
+}
+
+
+/*
+ * The module selection routine for BMP format input.
+ */
+
+GLOBAL(cjpeg_source_ptr)
+jinit_read_bmp (j_compress_ptr cinfo)
+{
+ bmp_source_ptr source;
+
+ /* Create module interface object */
+ source = (bmp_source_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(bmp_source_struct));
+ source->cinfo = cinfo; /* make back link for subroutines */
+ /* Fill in method ptrs, except get_pixel_rows which start_input sets */
+ source->pub.start_input = start_input_bmp;
+ source->pub.finish_input = finish_input_bmp;
+
+ return (cjpeg_source_ptr) source;
+}
+
+#endif /* BMP_SUPPORTED */
diff --git a/jpeg-6c/rdcolmap.c b/jpeg-6c/rdcolmap.c
new file mode 100644
index 0000000..48a61f7
--- /dev/null
+++ b/jpeg-6c/rdcolmap.c
@@ -0,0 +1,260 @@
+/*
+ * rdcolmap.c
+ *
+ * Copyright (C) 1994-1996, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file implements djpeg's "-map file" switch. It reads a source image
+ * and constructs a colormap to be supplied to the JPEG decompressor.
+ *
+ * Currently, these file formats are supported for the map file:
+ * GIF: the contents of the GIF's global colormap are used.
+ * PPM (either text or raw flavor): the entire file is read and
+ * each unique pixel value is entered in the map.
+ * Note that reading a large PPM file will be horrendously slow.
+ * Typically, a PPM-format map file should contain just one pixel
+ * of each desired color. Such a file can be extracted from an
+ * ordinary image PPM file with ppmtomap(1).
+ *
+ * Rescaling a PPM that has a maxval unequal to cinfo->maxjsample is not
+ * currently implemented.
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+
+#ifdef QUANT_2PASS_SUPPORTED /* otherwise can't quantize to supplied map */
+
+/* Portions of this code are based on the PBMPLUS library, which is:
+**
+** Copyright (C) 1988 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.
+*/
+
+
+/*
+ * Add a (potentially) new color to the color map.
+ */
+
+LOCAL(void)
+add_map_entry (j_decompress_ptr cinfo, int R, int G, int B)
+{
+ JSAMPROW16 colormap0 = cinfo->colormap16[0];
+ JSAMPROW16 colormap1 = cinfo->colormap16[1];
+ JSAMPROW16 colormap2 = cinfo->colormap16[2];
+ JSAMPROW colormap8_0 = cinfo->colormap[0];
+ JSAMPROW colormap8_1 = cinfo->colormap[1];
+ JSAMPROW colormap8_2 = cinfo->colormap[2];
+ int ncolors = cinfo->actual_number_of_colors;
+ int index;
+
+ /* Check for duplicate color. */
+ for (index = 0; index < ncolors; index++) {
+ if (GETJSAMPLE(colormap0[index]) == R &&
+ GETJSAMPLE(colormap1[index]) == G &&
+ GETJSAMPLE(colormap2[index]) == B)
+ return; /* color is already in map */
+ }
+
+ /* Check for map overflow. */
+ if (ncolors >= (cinfo->maxjsample+1))
+ ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, (cinfo->maxjsample+1));
+
+ /* OK, add color to maps. */
+ colormap0[ncolors] = (JSAMPLE16) R;
+ colormap1[ncolors] = (JSAMPLE16) G;
+ colormap2[ncolors] = (JSAMPLE16) B;
+ colormap8_0[ncolors] = (JSAMPLE)(R & 0xFF);
+ colormap8_1[ncolors] = (JSAMPLE)(G & 0xFF);
+ colormap8_2[ncolors] = (JSAMPLE)(B & 0xFF);
+ cinfo->actual_number_of_colors++;
+}
+
+
+/*
+ * Extract color map from a GIF file.
+ */
+
+LOCAL(void)
+read_gif_map (j_decompress_ptr cinfo, FILE * infile)
+{
+ int header[13];
+ int i, colormaplen;
+ int R, G, B;
+
+ /* Initial 'G' has already been read by read_color_map */
+ /* Read the rest of the GIF header and logical screen descriptor */
+ for (i = 1; i < 13; i++) {
+ if ((header[i] = getc(infile)) == EOF)
+ ERREXIT(cinfo, JERR_BAD_CMAP_FILE);
+ }
+
+ /* Verify GIF Header */
+ if (header[1] != 'I' || header[2] != 'F')
+ ERREXIT(cinfo, JERR_BAD_CMAP_FILE);
+
+ /* There must be a global color map. */
+ if ((header[10] & 0x80) == 0)
+ ERREXIT(cinfo, JERR_BAD_CMAP_FILE);
+
+ /* OK, fetch it. */
+ colormaplen = 2 << (header[10] & 0x07);
+
+ for (i = 0; i < colormaplen; i++) {
+ R = getc(infile);
+ G = getc(infile);
+ B = getc(infile);
+ if (R == EOF || G == EOF || B == EOF)
+ ERREXIT(cinfo, JERR_BAD_CMAP_FILE);
+ add_map_entry(cinfo,
+ R << (cinfo->data_precision -8),
+ G << (cinfo->data_precision -8),
+ B << (cinfo->data_precision -8));
+ }
+}
+
+
+/* Support routines for reading PPM */
+
+
+LOCAL(int)
+pbm_getc (FILE * infile)
+/* Read next char, skipping over any comments */
+/* A comment/newline sequence is returned as a newline */
+{
+ register int ch;
+
+ ch = getc(infile);
+ if (ch == '#') {
+ do {
+ ch = getc(infile);
+ } while (ch != '\n' && ch != EOF);
+ }
+ return ch;
+}
+
+
+LOCAL(unsigned int)
+read_pbm_integer (j_decompress_ptr cinfo, FILE * infile)
+/* Read an unsigned decimal integer from the PPM file */
+/* Swallows one trailing character after the integer */
+/* Note that on a 16-bit-int machine, only values up to 64k can be read. */
+/* This should not be a problem in practice. */
+{
+ register int ch;
+ register unsigned int val;
+
+ /* Skip any leading whitespace */
+ do {
+ ch = pbm_getc(infile);
+ if (ch == EOF)
+ ERREXIT(cinfo, JERR_BAD_CMAP_FILE);
+ } while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
+
+ if (ch < '0' || ch > '9')
+ ERREXIT(cinfo, JERR_BAD_CMAP_FILE);
+
+ val = ch - '0';
+ while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') {
+ val *= 10;
+ val += ch - '0';
+ }
+ return val;
+}
+
+
+/*
+ * Extract color map from a PPM file.
+ */
+
+LOCAL(void)
+read_ppm_map (j_decompress_ptr cinfo, FILE * infile)
+{
+ int c;
+ unsigned int w, h, maxval, row, col;
+ int R, G, B;
+
+ /* Initial 'P' has already been read by read_color_map */
+ c = getc(infile); /* save format discriminator for a sec */
+
+ /* while we fetch the remaining header info */
+ w = read_pbm_integer(cinfo, infile);
+ h = read_pbm_integer(cinfo, infile);
+ maxval = read_pbm_integer(cinfo, infile);
+
+ if (w <= 0 || h <= 0 || maxval <= 0) /* error check */
+ ERREXIT(cinfo, JERR_BAD_CMAP_FILE);
+
+ /* For now, we don't support rescaling from an unusual maxval. */
+ if (maxval != (unsigned int) cinfo->maxjsample)
+ ERREXIT(cinfo, JERR_BAD_CMAP_FILE);
+
+ switch (c) {
+ case '3': /* it's a text-format PPM file */
+ for (row = 0; row < h; row++) {
+ for (col = 0; col < w; col++) {
+ R = read_pbm_integer(cinfo, infile);
+ G = read_pbm_integer(cinfo, infile);
+ B = read_pbm_integer(cinfo, infile);
+ add_map_entry(cinfo, R, G, B);
+ }
+ }
+ break;
+
+ case '6': /* it's a raw-format PPM file */
+ for (row = 0; row < h; row++) {
+ for (col = 0; col < w; col++) {
+ R = getc(infile);
+ G = getc(infile);
+ B = getc(infile);
+ if (R == EOF || G == EOF || B == EOF)
+ ERREXIT(cinfo, JERR_BAD_CMAP_FILE);
+ add_map_entry(cinfo, R, G, B);
+ }
+ }
+ break;
+
+ default:
+ ERREXIT(cinfo, JERR_BAD_CMAP_FILE);
+ break;
+ }
+}
+
+
+/*
+ * Main entry point from djpeg.c.
+ * Input: opened input file (from file name argument on command line).
+ * Output: colormap and actual_number_of_colors fields are set in cinfo.
+ */
+
+GLOBAL(void)
+read_color_map (j_decompress_ptr cinfo, FILE * infile)
+{
+ /* Allocate space for a color map of maximum supported size. */
+ cinfo->colormap16 = (JSAMPARRAY16)(*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) ((cinfo->maxjsample + 1) * SIZEOF(JSAMPLE16)), (JDIMENSION) 3);
+ cinfo->actual_number_of_colors = 0; /* initialize map to empty */
+
+ /* Read first byte to determine file format */
+ switch (getc(infile)) {
+ case 'G':
+ read_gif_map(cinfo, infile);
+ break;
+ case 'P':
+ read_ppm_map(cinfo, infile);
+ break;
+ default:
+ ERREXIT(cinfo, JERR_BAD_CMAP_FILE);
+ break;
+ }
+}
+
+#endif /* QUANT_2PASS_SUPPORTED */
diff --git a/jpeg-6c/rdgif.c b/jpeg-6c/rdgif.c
new file mode 100644
index 0000000..0da2515
--- /dev/null
+++ b/jpeg-6c/rdgif.c
@@ -0,0 +1,683 @@
+/*
+ * rdgif.c
+ *
+ * Copyright (C) 1991-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ **************************************************************************
+ * WARNING: You will need an LZW patent license from Unisys in order to *
+ * use this file legally in any commercial or shareware application. *
+ **************************************************************************
+ *
+ * This file contains routines to read input images in GIF format.
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications. As they stand, they assume input from
+ * an ordinary stdio stream. They further assume that reading begins
+ * at the start of the file; input_init may need work if the
+ * user interface has already read some data (e.g., to determine that
+ * the file is indeed GIF format).
+ */
+
+/*
+ * This code is loosely based on giftoppm from the PBMPLUS distribution
+ * of Feb. 1991. That file contains the following copyright notice:
+ * +-------------------------------------------------------------------+
+ * | Copyright 1990, David Koblas. |
+ * | 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. |
+ * +-------------------------------------------------------------------+
+ *
+ * We are also required to state that
+ * "The Graphics Interchange Format(c) is the Copyright property of
+ * CompuServe Incorporated. GIF(sm) is a Service Mark property of
+ * CompuServe Incorporated."
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+
+#ifdef GIF_SUPPORTED
+
+
+#define MAXCOLORMAPSIZE 256 /* max # of colors in a GIF colormap */
+#define NUMCOLORS 3 /* # of colors */
+#define CM_RED 0 /* color component numbers */
+#define CM_GREEN 1
+#define CM_BLUE 2
+
+#define MAX_LZW_BITS 12 /* maximum LZW code size */
+#define LZW_TABLE_SIZE (1<<MAX_LZW_BITS) /* # of possible LZW symbols */
+
+/* Macros for extracting header data --- note we assume chars may be signed */
+
+#define LM_to_uint(a,b) ((((b)&0xFF) << 8) | ((a)&0xFF))
+
+#define BitSet(byte, bit) ((byte) & (bit))
+#define INTERLACE 0x40 /* mask for bit signifying interlaced image */
+#define COLORMAPFLAG 0x80 /* mask for bit signifying colormap presence */
+
+#define ReadOK(file,buffer,len) (JFREAD(file,buffer,len) == ((size_t) (len)))
+
+/* LZW decompression tables look like this:
+ * symbol_head[K] = prefix symbol of any LZW symbol K (0..LZW_TABLE_SIZE-1)
+ * symbol_tail[K] = suffix byte of any LZW symbol K (0..LZW_TABLE_SIZE-1)
+ * Note that entries 0..end_code of the above tables are not used,
+ * since those symbols represent raw bytes or special codes.
+ *
+ * The stack represents the not-yet-used expansion of the last LZW symbol.
+ * In the worst case, a symbol could expand to as many bytes as there are
+ * LZW symbols, so we allocate LZW_TABLE_SIZE bytes for the stack.
+ * (This is conservative since that number includes the raw-byte symbols.)
+ *
+ * The tables are allocated from FAR heap space since they would use up
+ * rather a lot of the near data space in a PC.
+ */
+
+
+/* Private version of data source object */
+
+typedef struct {
+ struct cjpeg_source_struct pub; /* public fields */
+
+ j_compress_ptr cinfo; /* back link saves passing separate parm */
+
+ JSAMPARRAY colormap; /* GIF colormap (converted to my format) */
+
+ /* State for GetCode and LZWReadByte */
+ char code_buf[256+4]; /* current input data block */
+ int last_byte; /* # of bytes in code_buf */
+ int last_bit; /* # of bits in code_buf */
+ int cur_bit; /* next bit index to read */
+ boolean out_of_blocks; /* TRUE if hit terminator data block */
+
+ int input_code_size; /* codesize given in GIF file */
+ int clear_code,end_code; /* values for Clear and End codes */
+
+ int code_size; /* current actual code size */
+ int limit_code; /* 2^code_size */
+ int max_code; /* first unused code value */
+ boolean first_time; /* flags first call to LZWReadByte */
+
+ /* Private state for LZWReadByte */
+ int oldcode; /* previous LZW symbol */
+ int firstcode; /* first byte of oldcode's expansion */
+
+ /* LZW symbol table and expansion stack */
+ UINT16 FAR *symbol_head; /* => table of prefix symbols */
+ UINT8 FAR *symbol_tail; /* => table of suffix bytes */
+ UINT8 FAR *symbol_stack; /* => stack for symbol expansions */
+ UINT8 FAR *sp; /* stack pointer */
+
+ /* State for interlaced image processing */
+ boolean is_interlaced; /* TRUE if have interlaced image */
+ jvirt_sarray_ptr interlaced_image; /* full image in interlaced order */
+ JDIMENSION cur_row_number; /* need to know actual row number */
+ JDIMENSION pass2_offset; /* # of pixel rows in pass 1 */
+ JDIMENSION pass3_offset; /* # of pixel rows in passes 1&2 */
+ JDIMENSION pass4_offset; /* # of pixel rows in passes 1,2,3 */
+} gif_source_struct;
+
+typedef gif_source_struct * gif_source_ptr;
+
+
+/* Forward declarations */
+METHODDEF(JDIMENSION) get_pixel_rows
+ JPP((j_compress_ptr cinfo, cjpeg_source_ptr sinfo));
+METHODDEF(JDIMENSION) load_interlaced_image
+ JPP((j_compress_ptr cinfo, cjpeg_source_ptr sinfo));
+METHODDEF(JDIMENSION) get_interlaced_row
+ JPP((j_compress_ptr cinfo, cjpeg_source_ptr sinfo));
+
+
+LOCAL(int)
+ReadByte (gif_source_ptr sinfo)
+/* Read next byte from GIF file */
+{
+ register FILE * infile = sinfo->pub.input_file;
+ int c;
+
+ if ((c = getc(infile)) == EOF)
+ ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
+ return c;
+}
+
+
+LOCAL(int)
+GetDataBlock (gif_source_ptr sinfo, char *buf)
+/* Read a GIF data block, which has a leading count byte */
+/* A zero-length block marks the end of a data block sequence */
+{
+ int count;
+
+ count = ReadByte(sinfo);
+ if (count > 0) {
+ if (! ReadOK(sinfo->pub.input_file, buf, count))
+ ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
+ }
+ return count;
+}
+
+
+LOCAL(void)
+SkipDataBlocks (gif_source_ptr sinfo)
+/* Skip a series of data blocks, until a block terminator is found */
+{
+ char buf[256];
+
+ while (GetDataBlock(sinfo, buf) > 0)
+ /* skip */;
+}
+
+
+LOCAL(void)
+ReInitLZW (gif_source_ptr sinfo)
+/* (Re)initialize LZW state; shared code for startup and Clear processing */
+{
+ sinfo->code_size = sinfo->input_code_size + 1;
+ sinfo->limit_code = sinfo->clear_code << 1; /* 2^code_size */
+ sinfo->max_code = sinfo->clear_code + 2; /* first unused code value */
+ sinfo->sp = sinfo->symbol_stack; /* init stack to empty */
+}
+
+
+LOCAL(void)
+InitLZWCode (gif_source_ptr sinfo)
+/* Initialize for a series of LZWReadByte (and hence GetCode) calls */
+{
+ /* GetCode initialization */
+ sinfo->last_byte = 2; /* make safe to "recopy last two bytes" */
+ sinfo->last_bit = 0; /* nothing in the buffer */
+ sinfo->cur_bit = 0; /* force buffer load on first call */
+ sinfo->out_of_blocks = FALSE;
+
+ /* LZWReadByte initialization: */
+ /* compute special code values (note that these do not change later) */
+ sinfo->clear_code = 1 << sinfo->input_code_size;
+ sinfo->end_code = sinfo->clear_code + 1;
+ sinfo->first_time = TRUE;
+ ReInitLZW(sinfo);
+}
+
+
+LOCAL(int)
+GetCode (gif_source_ptr sinfo)
+/* Fetch the next code_size bits from the GIF data */
+/* We assume code_size is less than 16 */
+{
+ register INT32 accum;
+ int offs, ret, count;
+
+ while ( (sinfo->cur_bit + sinfo->code_size) > sinfo->last_bit) {
+ /* Time to reload the buffer */
+ if (sinfo->out_of_blocks) {
+ WARNMS(sinfo->cinfo, JWRN_GIF_NOMOREDATA);
+ return sinfo->end_code; /* fake something useful */
+ }
+ /* preserve last two bytes of what we have -- assume code_size <= 16 */
+ sinfo->code_buf[0] = sinfo->code_buf[sinfo->last_byte-2];
+ sinfo->code_buf[1] = sinfo->code_buf[sinfo->last_byte-1];
+ /* Load more bytes; set flag if we reach the terminator block */
+ if ((count = GetDataBlock(sinfo, &sinfo->code_buf[2])) == 0) {
+ sinfo->out_of_blocks = TRUE;
+ WARNMS(sinfo->cinfo, JWRN_GIF_NOMOREDATA);
+ return sinfo->end_code; /* fake something useful */
+ }
+ /* Reset counters */
+ sinfo->cur_bit = (sinfo->cur_bit - sinfo->last_bit) + 16;
+ sinfo->last_byte = 2 + count;
+ sinfo->last_bit = sinfo->last_byte * 8;
+ }
+
+ /* Form up next 24 bits in accum */
+ offs = sinfo->cur_bit >> 3; /* byte containing cur_bit */
+#ifdef CHAR_IS_UNSIGNED
+ accum = sinfo->code_buf[offs+2];
+ accum <<= 8;
+ accum |= sinfo->code_buf[offs+1];
+ accum <<= 8;
+ accum |= sinfo->code_buf[offs];
+#else
+ accum = sinfo->code_buf[offs+2] & 0xFF;
+ accum <<= 8;
+ accum |= sinfo->code_buf[offs+1] & 0xFF;
+ accum <<= 8;
+ accum |= sinfo->code_buf[offs] & 0xFF;
+#endif
+
+ /* Right-align cur_bit in accum, then mask off desired number of bits */
+ accum >>= (sinfo->cur_bit & 7);
+ ret = ((int) accum) & ((1 << sinfo->code_size) - 1);
+
+ sinfo->cur_bit += sinfo->code_size;
+ return ret;
+}
+
+
+LOCAL(int)
+LZWReadByte (gif_source_ptr sinfo)
+/* Read an LZW-compressed byte */
+{
+ register int code; /* current working code */
+ int incode; /* saves actual input code */
+
+ /* First time, just eat the expected Clear code(s) and return next code, */
+ /* which is expected to be a raw byte. */
+ if (sinfo->first_time) {
+ sinfo->first_time = FALSE;
+ code = sinfo->clear_code; /* enables sharing code with Clear case */
+ } else {
+
+ /* If any codes are stacked from a previously read symbol, return them */
+ if (sinfo->sp > sinfo->symbol_stack)
+ return (int) *(-- sinfo->sp);
+
+ /* Time to read a new symbol */
+ code = GetCode(sinfo);
+
+ }
+
+ if (code == sinfo->clear_code) {
+ /* Reinit state, swallow any extra Clear codes, and */
+ /* return next code, which is expected to be a raw byte. */
+ ReInitLZW(sinfo);
+ do {
+ code = GetCode(sinfo);
+ } while (code == sinfo->clear_code);
+ if (code > sinfo->clear_code) { /* make sure it is a raw byte */
+ WARNMS(sinfo->cinfo, JWRN_GIF_BADDATA);
+ code = 0; /* use something valid */
+ }
+ /* make firstcode, oldcode valid! */
+ sinfo->firstcode = sinfo->oldcode = code;
+ return code;
+ }
+
+ if (code == sinfo->end_code) {
+ /* Skip the rest of the image, unless GetCode already read terminator */
+ if (! sinfo->out_of_blocks) {
+ SkipDataBlocks(sinfo);
+ sinfo->out_of_blocks = TRUE;
+ }
+ /* Complain that there's not enough data */
+ WARNMS(sinfo->cinfo, JWRN_GIF_ENDCODE);
+ /* Pad data with 0's */
+ return 0; /* fake something usable */
+ }
+
+ /* Got normal raw byte or LZW symbol */
+ incode = code; /* save for a moment */
+
+ if (code >= sinfo->max_code) { /* special case for not-yet-defined symbol */
+ /* code == max_code is OK; anything bigger is bad data */
+ if (code > sinfo->max_code) {
+ WARNMS(sinfo->cinfo, JWRN_GIF_BADDATA);
+ incode = 0; /* prevent creation of loops in symbol table */
+ }
+ /* this symbol will be defined as oldcode/firstcode */
+ *(sinfo->sp++) = (UINT8) sinfo->firstcode;
+ code = sinfo->oldcode;
+ }
+
+ /* If it's a symbol, expand it into the stack */
+ while (code >= sinfo->clear_code) {
+ *(sinfo->sp++) = sinfo->symbol_tail[code]; /* tail is a byte value */
+ code = sinfo->symbol_head[code]; /* head is another LZW symbol */
+ }
+ /* At this point code just represents a raw byte */
+ sinfo->firstcode = code; /* save for possible future use */
+
+ /* If there's room in table, */
+ if ((code = sinfo->max_code) < LZW_TABLE_SIZE) {
+ /* Define a new symbol = prev sym + head of this sym's expansion */
+ sinfo->symbol_head[code] = sinfo->oldcode;
+ sinfo->symbol_tail[code] = (UINT8) sinfo->firstcode;
+ sinfo->max_code++;
+ /* Is it time to increase code_size? */
+ if ((sinfo->max_code >= sinfo->limit_code) &&
+ (sinfo->code_size < MAX_LZW_BITS)) {
+ sinfo->code_size++;
+ sinfo->limit_code <<= 1; /* keep equal to 2^code_size */
+ }
+ }
+
+ sinfo->oldcode = incode; /* save last input symbol for future use */
+ return sinfo->firstcode; /* return first byte of symbol's expansion */
+}
+
+
+LOCAL(void)
+ReadColorMap (gif_source_ptr sinfo, int cmaplen, JSAMPARRAY cmap)
+/* Read a GIF colormap */
+{
+ int i;
+
+ for (i = 0; i < cmaplen; i++) {
+#if BITS_IN_JSAMPLE == 8
+#define UPSCALE(x) (x)
+#else
+#define UPSCALE(x) ((x) << (BITS_IN_JSAMPLE-8))
+#endif
+ cmap[CM_RED][i] = (JSAMPLE) UPSCALE(ReadByte(sinfo));
+ cmap[CM_GREEN][i] = (JSAMPLE) UPSCALE(ReadByte(sinfo));
+ cmap[CM_BLUE][i] = (JSAMPLE) UPSCALE(ReadByte(sinfo));
+ }
+}
+
+
+LOCAL(void)
+DoExtension (gif_source_ptr sinfo)
+/* Process an extension block */
+/* Currently we ignore 'em all */
+{
+ int extlabel;
+
+ /* Read extension label byte */
+ extlabel = ReadByte(sinfo);
+ TRACEMS1(sinfo->cinfo, 1, JTRC_GIF_EXTENSION, extlabel);
+ /* Skip the data block(s) associated with the extension */
+ SkipDataBlocks(sinfo);
+}
+
+
+/*
+ * Read the file header; return image size and component count.
+ */
+
+METHODDEF(void)
+start_input_gif (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ gif_source_ptr source = (gif_source_ptr) sinfo;
+ char hdrbuf[10]; /* workspace for reading control blocks */
+ unsigned int width, height; /* image dimensions */
+ int colormaplen, aspectRatio;
+ int c;
+
+ /* Allocate space to store the colormap */
+ source->colormap = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) MAXCOLORMAPSIZE, (JDIMENSION) NUMCOLORS);
+
+ /* Read and verify GIF Header */
+ if (! ReadOK(source->pub.input_file, hdrbuf, 6))
+ ERREXIT(cinfo, JERR_GIF_NOT);
+ if (hdrbuf[0] != 'G' || hdrbuf[1] != 'I' || hdrbuf[2] != 'F')
+ ERREXIT(cinfo, JERR_GIF_NOT);
+ /* Check for expected version numbers.
+ * If unknown version, give warning and try to process anyway;
+ * this is per recommendation in GIF89a standard.
+ */
+ if ((hdrbuf[3] != '8' || hdrbuf[4] != '7' || hdrbuf[5] != 'a') &&
+ (hdrbuf[3] != '8' || hdrbuf[4] != '9' || hdrbuf[5] != 'a'))
+ TRACEMS3(cinfo, 1, JTRC_GIF_BADVERSION, hdrbuf[3], hdrbuf[4], hdrbuf[5]);
+
+ /* Read and decipher Logical Screen Descriptor */
+ if (! ReadOK(source->pub.input_file, hdrbuf, 7))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ width = LM_to_uint(hdrbuf[0],hdrbuf[1]);
+ height = LM_to_uint(hdrbuf[2],hdrbuf[3]);
+ colormaplen = 2 << (hdrbuf[4] & 0x07);
+ /* we ignore the color resolution, sort flag, and background color index */
+ aspectRatio = hdrbuf[6] & 0xFF;
+ if (aspectRatio != 0 && aspectRatio != 49)
+ TRACEMS(cinfo, 1, JTRC_GIF_NONSQUARE);
+
+ /* Read global colormap if header indicates it is present */
+ if (BitSet(hdrbuf[4], COLORMAPFLAG))
+ ReadColorMap(source, colormaplen, source->colormap);
+
+ /* Scan until we reach start of desired image.
+ * We don't currently support skipping images, but could add it easily.
+ */
+ for (;;) {
+ c = ReadByte(source);
+
+ if (c == ';') /* GIF terminator?? */
+ ERREXIT(cinfo, JERR_GIF_IMAGENOTFOUND);
+
+ if (c == '!') { /* Extension */
+ DoExtension(source);
+ continue;
+ }
+
+ if (c != ',') { /* Not an image separator? */
+ WARNMS1(cinfo, JWRN_GIF_CHAR, c);
+ continue;
+ }
+
+ /* Read and decipher Local Image Descriptor */
+ if (! ReadOK(source->pub.input_file, hdrbuf, 9))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ /* we ignore top/left position info, also sort flag */
+ width = LM_to_uint(hdrbuf[4],hdrbuf[5]);
+ height = LM_to_uint(hdrbuf[6],hdrbuf[7]);
+ source->is_interlaced = BitSet(hdrbuf[8], INTERLACE);
+
+ /* Read local colormap if header indicates it is present */
+ /* Note: if we wanted to support skipping images, */
+ /* we'd need to skip rather than read colormap for ignored images */
+ if (BitSet(hdrbuf[8], COLORMAPFLAG)) {
+ colormaplen = 2 << (hdrbuf[8] & 0x07);
+ ReadColorMap(source, colormaplen, source->colormap);
+ }
+
+ source->input_code_size = ReadByte(source); /* get min-code-size byte */
+ if (source->input_code_size < 2 || source->input_code_size >= MAX_LZW_BITS)
+ ERREXIT1(cinfo, JERR_GIF_CODESIZE, source->input_code_size);
+
+ /* Reached desired image, so break out of loop */
+ /* If we wanted to skip this image, */
+ /* we'd call SkipDataBlocks and then continue the loop */
+ break;
+ }
+
+ /* Prepare to read selected image: first initialize LZW decompressor */
+ source->symbol_head = (UINT16 FAR *)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ LZW_TABLE_SIZE * SIZEOF(UINT16));
+ source->symbol_tail = (UINT8 FAR *)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ LZW_TABLE_SIZE * SIZEOF(UINT8));
+ source->symbol_stack = (UINT8 FAR *)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ LZW_TABLE_SIZE * SIZEOF(UINT8));
+ InitLZWCode(source);
+
+ /*
+ * If image is interlaced, we read it into a full-size sample array,
+ * decompressing as we go; then get_interlaced_row selects rows from the
+ * sample array in the proper order.
+ */
+ if (source->is_interlaced) {
+ /* We request the virtual array now, but can't access it until virtual
+ * arrays have been allocated. Hence, the actual work of reading the
+ * image is postponed until the first call to get_pixel_rows.
+ */
+ source->interlaced_image = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ (JDIMENSION) width, (JDIMENSION) height, (JDIMENSION) 1);
+ if (cinfo->progress != NULL) {
+ cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
+ progress->total_extra_passes++; /* count file input as separate pass */
+ }
+ source->pub.get_pixel_rows = load_interlaced_image;
+ } else {
+ source->pub.get_pixel_rows = get_pixel_rows;
+ }
+
+ /* Create compressor input buffer. */
+ source->pub.buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) width * NUMCOLORS, (JDIMENSION) 1);
+ source->pub.buffer_height = 1;
+
+ /* Return info about the image. */
+ cinfo->in_color_space = JCS_RGB;
+ cinfo->input_components = NUMCOLORS;
+ cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */
+ cinfo->image_width = width;
+ cinfo->image_height = height;
+
+ TRACEMS3(cinfo, 1, JTRC_GIF, width, height, colormaplen);
+}
+
+
+/*
+ * Read one row of pixels.
+ * This version is used for noninterlaced GIF images:
+ * we read directly from the GIF file.
+ */
+
+METHODDEF(JDIMENSION)
+get_pixel_rows (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ gif_source_ptr source = (gif_source_ptr) sinfo;
+ register int c;
+ register JSAMPROW ptr;
+ register JDIMENSION col;
+ register JSAMPARRAY colormap = source->colormap;
+
+ ptr = source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ c = LZWReadByte(source);
+ *ptr++ = colormap[CM_RED][c];
+ *ptr++ = colormap[CM_GREEN][c];
+ *ptr++ = colormap[CM_BLUE][c];
+ }
+ return 1;
+}
+
+
+/*
+ * Read one row of pixels.
+ * This version is used for the first call on get_pixel_rows when
+ * reading an interlaced GIF file: we read the whole image into memory.
+ */
+
+METHODDEF(JDIMENSION)
+load_interlaced_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ gif_source_ptr source = (gif_source_ptr) sinfo;
+ JSAMPARRAY image_ptr;
+ register JSAMPROW sptr;
+ register JDIMENSION col;
+ JDIMENSION row;
+ cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
+
+ /* Read the interlaced image into the virtual array we've created. */
+ for (row = 0; row < cinfo->image_height; row++) {
+ if (progress != NULL) {
+ progress->pub.pass_counter = (long) row;
+ progress->pub.pass_limit = (long) cinfo->image_height;
+ (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
+ }
+ image_ptr = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, source->interlaced_image,
+ row, (JDIMENSION) 1, TRUE);
+ sptr = image_ptr[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ *sptr++ = (JSAMPLE) LZWReadByte(source);
+ }
+ }
+ if (progress != NULL)
+ progress->completed_extra_passes++;
+
+ /* Replace method pointer so subsequent calls don't come here. */
+ source->pub.get_pixel_rows = get_interlaced_row;
+ /* Initialize for get_interlaced_row, and perform first call on it. */
+ source->cur_row_number = 0;
+ source->pass2_offset = (cinfo->image_height + 7) / 8;
+ source->pass3_offset = source->pass2_offset + (cinfo->image_height + 3) / 8;
+ source->pass4_offset = source->pass3_offset + (cinfo->image_height + 1) / 4;
+
+ return get_interlaced_row(cinfo, sinfo);
+}
+
+
+/*
+ * Read one row of pixels.
+ * This version is used for interlaced GIF images:
+ * we read from the virtual array.
+ */
+
+METHODDEF(JDIMENSION)
+get_interlaced_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ gif_source_ptr source = (gif_source_ptr) sinfo;
+ JSAMPARRAY image_ptr;
+ register int c;
+ register JSAMPROW sptr, ptr;
+ register JDIMENSION col;
+ register JSAMPARRAY colormap = source->colormap;
+ JDIMENSION irow;
+
+ /* Figure out which row of interlaced image is needed, and access it. */
+ switch ((int) (source->cur_row_number & 7)) {
+ case 0: /* first-pass row */
+ irow = source->cur_row_number >> 3;
+ break;
+ case 4: /* second-pass row */
+ irow = (source->cur_row_number >> 3) + source->pass2_offset;
+ break;
+ case 2: /* third-pass row */
+ case 6:
+ irow = (source->cur_row_number >> 2) + source->pass3_offset;
+ break;
+ default: /* fourth-pass row */
+ irow = (source->cur_row_number >> 1) + source->pass4_offset;
+ break;
+ }
+ image_ptr = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, source->interlaced_image,
+ irow, (JDIMENSION) 1, FALSE);
+ /* Scan the row, expand colormap, and output */
+ sptr = image_ptr[0];
+ ptr = source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ c = GETJSAMPLE(*sptr++);
+ *ptr++ = colormap[CM_RED][c];
+ *ptr++ = colormap[CM_GREEN][c];
+ *ptr++ = colormap[CM_BLUE][c];
+ }
+ source->cur_row_number++; /* for next time */
+ return 1;
+}
+
+
+/*
+ * Finish up at the end of the file.
+ */
+
+METHODDEF(void)
+finish_input_gif (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ /* no work */
+}
+
+
+/*
+ * The module selection routine for GIF format input.
+ */
+
+GLOBAL(cjpeg_source_ptr)
+jinit_read_gif (j_compress_ptr cinfo)
+{
+ gif_source_ptr source;
+
+ /* Create module interface object */
+ source = (gif_source_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(gif_source_struct));
+ source->cinfo = cinfo; /* make back link for subroutines */
+ /* Fill in method ptrs, except get_pixel_rows which start_input sets */
+ source->pub.start_input = start_input_gif;
+ source->pub.finish_input = finish_input_gif;
+
+ return (cjpeg_source_ptr) source;
+}
+
+#endif /* GIF_SUPPORTED */
diff --git a/jpeg-6c/rdjpgcom.1 b/jpeg-6c/rdjpgcom.1
new file mode 100644
index 0000000..2bba04e
--- /dev/null
+++ b/jpeg-6c/rdjpgcom.1
@@ -0,0 +1,54 @@
+.TH RDJPGCOM 1 "11 October 1997"
+.SH NAME
+rdjpgcom \- display text comments from a JPEG file
+.SH SYNOPSIS
+.B rdjpgcom
+[
+.B \-verbose
+]
+[
+.I filename
+]
+.LP
+.SH DESCRIPTION
+.LP
+.B rdjpgcom
+reads the named JPEG/JFIF file, or the standard input if no file is named,
+and prints any text comments found in the file on the standard output.
+.PP
+The JPEG standard allows "comment" (COM) blocks to occur within a JPEG file.
+Although the standard doesn't actually define what COM blocks are for, they
+are widely used to hold user-supplied text strings. This lets you add
+annotations, titles, index terms, etc to your JPEG files, and later retrieve
+them as text. COM blocks do not interfere with the image stored in the JPEG
+file. The maximum size of a COM block is 64K, but you can have as many of
+them as you like in one JPEG file.
+.SH OPTIONS
+.TP
+.B \-verbose
+Causes
+.B rdjpgcom
+to also display the JPEG image dimensions.
+.PP
+Switch names may be abbreviated, and are not case sensitive.
+.SH HINTS
+.B rdjpgcom
+does not depend on the IJG JPEG library. Its source code is intended as an
+illustration of the minimum amount of code required to parse a JPEG file
+header correctly.
+.PP
+In
+.B \-verbose
+mode,
+.B rdjpgcom
+will also attempt to print the contents of any "APP12" markers as text.
+Some digital cameras produce APP12 markers containing useful textual
+information. If you like, you can modify the source code to print
+other APPn marker types as well.
+.SH SEE ALSO
+.BR cjpeg (1),
+.BR djpeg (1),
+.BR jpegtran (1),
+.BR wrjpgcom (1)
+.SH AUTHOR
+Independent JPEG Group
diff --git a/jpeg-6c/rdjpgcom.c b/jpeg-6c/rdjpgcom.c
new file mode 100644
index 0000000..ffe6fc6
--- /dev/null
+++ b/jpeg-6c/rdjpgcom.c
@@ -0,0 +1,496 @@
+/*
+ * rdjpgcom.c
+ *
+ * Copyright (C) 1994-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a very simple stand-alone application that displays
+ * the text in COM (comment) markers in a JFIF file.
+ * This may be useful as an example of the minimum logic needed to parse
+ * JPEG markers.
+ */
+
+#define JPEG_CJPEG_DJPEG /* to get the command-line config symbols */
+#include "jinclude.h" /* get auto-config symbols, <stdio.h> */
+
+#include <ctype.h> /* to declare isupper(), tolower() */
+#ifdef USE_SETMODE
+#include <fcntl.h> /* to declare setmode()'s parameter macros */
+/* If you have setmode() but not <io.h>, just delete this line: */
+#include <io.h> /* to declare setmode() */
+#endif
+
+#ifdef USE_CCOMMAND /* command-line reader for Macintosh */
+#ifdef __MWERKS__
+#include <SIOUX.h> /* Metrowerks needs this */
+#include <console.h> /* ... and this */
+#endif
+#ifdef THINK_C
+#include <console.h> /* Think declares it here */
+#endif
+#endif
+
+#ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
+#define READ_BINARY "r"
+#else
+#ifdef VMS /* VMS is very nonstandard */
+#define READ_BINARY "rb", "ctx=stm"
+#else /* standard ANSI-compliant case */
+#define READ_BINARY "rb"
+#endif
+#endif
+
+#ifndef EXIT_FAILURE /* define exit() codes if not provided */
+#define EXIT_FAILURE 1
+#endif
+#ifndef EXIT_SUCCESS
+#ifdef VMS
+#define EXIT_SUCCESS 1 /* VMS is very nonstandard */
+#else
+#define EXIT_SUCCESS 0
+#endif
+#endif
+
+
+/*
+ * These macros are used to read the input file.
+ * To reuse this code in another application, you might need to change these.
+ */
+
+static FILE * infile; /* input JPEG file */
+
+/* Return next input byte, or EOF if no more */
+#define NEXTBYTE() getc(infile)
+
+
+/* Error exit handler */
+#define ERREXIT(msg) (fprintf(stderr, "%s\n", msg), exit(EXIT_FAILURE))
+
+
+/* Read one byte, testing for EOF */
+static int
+read_1_byte (void)
+{
+ int c;
+
+ c = NEXTBYTE();
+ if (c == EOF)
+ ERREXIT("Premature EOF in JPEG file");
+ return c;
+}
+
+/* Read 2 bytes, convert to unsigned int */
+/* All 2-byte quantities in JPEG markers are MSB first */
+static unsigned int
+read_2_bytes (void)
+{
+ int c1, c2;
+
+ c1 = NEXTBYTE();
+ if (c1 == EOF)
+ ERREXIT("Premature EOF in JPEG file");
+ c2 = NEXTBYTE();
+ if (c2 == EOF)
+ ERREXIT("Premature EOF in JPEG file");
+ return (((unsigned int) c1) << 8) + ((unsigned int) c2);
+}
+
+
+/*
+ * JPEG markers consist of one or more 0xFF bytes, followed by a marker
+ * code byte (which is not an FF). Here are the marker codes of interest
+ * in this program. (See jdmarker.c for a more complete list.)
+ */
+
+#define M_SOF0 0xC0 /* Start Of Frame N */
+#define M_SOF1 0xC1 /* N indicates which compression process */
+#define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */
+#define M_SOF3 0xC3
+#define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */
+#define M_SOF6 0xC6
+#define M_SOF7 0xC7
+#define M_SOF9 0xC9
+#define M_SOF10 0xCA
+#define M_SOF11 0xCB
+#define M_SOF13 0xCD
+#define M_SOF14 0xCE
+#define M_SOF15 0xCF
+#define M_SOI 0xD8 /* Start Of Image (beginning of datastream) */
+#define M_EOI 0xD9 /* End Of Image (end of datastream) */
+#define M_SOS 0xDA /* Start Of Scan (begins compressed data) */
+#define M_APP0 0xE0 /* Application-specific marker, type N */
+#define M_APP12 0xEC /* (we don't bother to list all 16 APPn's) */
+#define M_COM 0xFE /* COMment */
+
+
+/*
+ * Find the next JPEG marker and return its marker code.
+ * We expect at least one FF byte, possibly more if the compressor used FFs
+ * to pad the file.
+ * There could also be non-FF garbage between markers. The treatment of such
+ * garbage is unspecified; we choose to skip over it but emit a warning msg.
+ * NB: this routine must not be used after seeing SOS marker, since it will
+ * not deal correctly with FF/00 sequences in the compressed image data...
+ */
+
+static int
+next_marker (void)
+{
+ int c;
+ int discarded_bytes = 0;
+
+ /* Find 0xFF byte; count and skip any non-FFs. */
+ c = read_1_byte();
+ while (c != 0xFF) {
+ discarded_bytes++;
+ c = read_1_byte();
+ }
+ /* Get marker code byte, swallowing any duplicate FF bytes. Extra FFs
+ * are legal as pad bytes, so don't count them in discarded_bytes.
+ */
+ do {
+ c = read_1_byte();
+ } while (c == 0xFF);
+
+ if (discarded_bytes != 0) {
+ fprintf(stderr, "Warning: garbage data found in JPEG file\n");
+ }
+
+ return c;
+}
+
+
+/*
+ * Read the initial marker, which should be SOI.
+ * For a JFIF file, the first two bytes of the file should be literally
+ * 0xFF M_SOI. To be more general, we could use next_marker, but if the
+ * input file weren't actually JPEG at all, next_marker might read the whole
+ * file and then return a misleading error message...
+ */
+
+static int
+first_marker (void)
+{
+ int c1, c2;
+
+ c1 = NEXTBYTE();
+ c2 = NEXTBYTE();
+ if (c1 != 0xFF || c2 != M_SOI)
+ ERREXIT("Not a JPEG file");
+ return c2;
+}
+
+
+/*
+ * Most types of marker are followed by a variable-length parameter segment.
+ * This routine skips over the parameters for any marker we don't otherwise
+ * want to process.
+ * Note that we MUST skip the parameter segment explicitly in order not to
+ * be fooled by 0xFF bytes that might appear within the parameter segment;
+ * such bytes do NOT introduce new markers.
+ */
+
+static void
+skip_variable (void)
+/* Skip over an unknown or uninteresting variable-length marker */
+{
+ unsigned int length;
+
+ /* Get the marker parameter length count */
+ length = read_2_bytes();
+ /* Length includes itself, so must be at least 2 */
+ if (length < 2)
+ ERREXIT("Erroneous JPEG marker length");
+ length -= 2;
+ /* Skip over the remaining bytes */
+ while (length > 0) {
+ (void) read_1_byte();
+ length--;
+ }
+}
+
+
+/*
+ * Process a COM marker.
+ * We want to print out the marker contents as legible text;
+ * we must guard against non-text junk and varying newline representations.
+ */
+
+static void
+process_COM (void)
+{
+ unsigned int length;
+ int ch;
+ int lastch = 0;
+
+ /* Get the marker parameter length count */
+ length = read_2_bytes();
+ /* Length includes itself, so must be at least 2 */
+ if (length < 2)
+ ERREXIT("Erroneous JPEG marker length");
+ length -= 2;
+
+ while (length > 0) {
+ ch = read_1_byte();
+ /* 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 newline.
+ */
+ if (ch == '\r') {
+ printf("\n");
+ } else if (ch == '\n') {
+ if (lastch != '\r')
+ printf("\n");
+ } else if (ch == '\\') {
+ printf("\\\\");
+ } else if (isprint(ch)) {
+ putc(ch, stdout);
+ } else {
+ printf("\\%03o", ch);
+ }
+ lastch = ch;
+ length--;
+ }
+ printf("\n");
+}
+
+
+/*
+ * Process a SOFn marker.
+ * This code is only needed if you want to know the image dimensions...
+ */
+
+static void
+process_SOFn (int marker)
+{
+ unsigned int length;
+ unsigned int image_height, image_width;
+ int data_precision, num_components;
+ const char * process;
+ int ci;
+
+ length = read_2_bytes(); /* usual parameter length count */
+
+ data_precision = read_1_byte();
+ image_height = read_2_bytes();
+ image_width = read_2_bytes();
+ num_components = read_1_byte();
+
+ switch (marker) {
+ case M_SOF0: process = "Baseline"; break;
+ case M_SOF1: process = "Extended sequential"; break;
+ case M_SOF2: process = "Progressive"; break;
+ case M_SOF3: process = "Lossless"; break;
+ case M_SOF5: process = "Differential sequential"; break;
+ case M_SOF6: process = "Differential progressive"; break;
+ case M_SOF7: process = "Differential lossless"; break;
+ case M_SOF9: process = "Extended sequential, arithmetic coding"; break;
+ case M_SOF10: process = "Progressive, arithmetic coding"; break;
+ case M_SOF11: process = "Lossless, arithmetic coding"; break;
+ case M_SOF13: process = "Differential sequential, arithmetic coding"; break;
+ case M_SOF14: process = "Differential progressive, arithmetic coding"; break;
+ case M_SOF15: process = "Differential lossless, arithmetic coding"; break;
+ default: process = "Unknown"; break;
+ }
+
+ printf("JPEG image is %uw * %uh, %d color components, %d bits per sample\n",
+ image_width, image_height, num_components, data_precision);
+ printf("JPEG process: %s\n", process);
+
+ if (length != (unsigned int) (8 + num_components * 3))
+ ERREXIT("Bogus SOF marker length");
+
+ for (ci = 0; ci < num_components; ci++) {
+ (void) read_1_byte(); /* Component ID code */
+ (void) read_1_byte(); /* H, V sampling factors */
+ (void) read_1_byte(); /* Quantization table number */
+ }
+}
+
+
+/*
+ * Parse the marker stream until SOS or EOI is seen;
+ * display any COM markers.
+ * While the companion program wrjpgcom will always insert COM markers before
+ * SOFn, other implementations might not, so we scan to SOS before stopping.
+ * If we were only interested in the image dimensions, we would stop at SOFn.
+ * (Conversely, if we only cared about COM markers, there would be no need
+ * for special code to handle SOFn; we could treat it like other markers.)
+ */
+
+static int
+scan_JPEG_header (int verbose)
+{
+ int marker;
+
+ /* Expect SOI at start of file */
+ if (first_marker() != M_SOI)
+ ERREXIT("Expected SOI marker first");
+
+ /* Scan miscellaneous markers until we reach SOS. */
+ for (;;) {
+ marker = next_marker();
+ switch (marker) {
+ /* Note that marker codes 0xC4, 0xC8, 0xCC are not, and must not be,
+ * treated as SOFn. C4 in particular is actually DHT.
+ */
+ case M_SOF0: /* Baseline */
+ case M_SOF1: /* Extended sequential, Huffman */
+ case M_SOF2: /* Progressive, Huffman */
+ case M_SOF3: /* Lossless, Huffman */
+ case M_SOF5: /* Differential sequential, Huffman */
+ case M_SOF6: /* Differential progressive, Huffman */
+ case M_SOF7: /* Differential lossless, Huffman */
+ case M_SOF9: /* Extended sequential, arithmetic */
+ case M_SOF10: /* Progressive, arithmetic */
+ case M_SOF11: /* Lossless, arithmetic */
+ case M_SOF13: /* Differential sequential, arithmetic */
+ case M_SOF14: /* Differential progressive, arithmetic */
+ case M_SOF15: /* Differential lossless, arithmetic */
+ if (verbose)
+ process_SOFn(marker);
+ else
+ skip_variable();
+ break;
+
+ case M_SOS: /* stop before hitting compressed data */
+ return marker;
+
+ case M_EOI: /* in case it's a tables-only JPEG stream */
+ return marker;
+
+ case M_COM:
+ process_COM();
+ break;
+
+ case M_APP12:
+ /* Some digital camera makers put useful textual information into
+ * APP12 markers, so we print those out too when in -verbose mode.
+ */
+ if (verbose) {
+ printf("APP12 contains:\n");
+ process_COM();
+ } else
+ skip_variable();
+ break;
+
+ default: /* Anything else just gets skipped */
+ skip_variable(); /* we assume it has a parameter count... */
+ break;
+ }
+ } /* end loop */
+}
+
+
+/* Command line parsing code */
+
+static const char * progname; /* program name for error messages */
+
+
+static void
+usage (void)
+/* complain about bad command line */
+{
+ fprintf(stderr, "rdjpgcom displays any textual comments in a JPEG file.\n");
+
+ fprintf(stderr, "Usage: %s [switches] [inputfile]\n", progname);
+
+ fprintf(stderr, "Switches (names may be abbreviated):\n");
+ fprintf(stderr, " -verbose Also display dimensions of JPEG image\n");
+
+ exit(EXIT_FAILURE);
+}
+
+
+static int
+keymatch (char * arg, const char * keyword, int minchars)
+/* Case-insensitive matching of (possibly abbreviated) keyword switches. */
+/* keyword is the constant keyword (must be lower case already), */
+/* minchars is length of minimum legal abbreviation. */
+{
+ register int ca, ck;
+ register int nmatched = 0;
+
+ while ((ca = *arg++) != '\0') {
+ if ((ck = *keyword++) == '\0')
+ return 0; /* arg longer than keyword, no good */
+ if (isupper(ca)) /* force arg to lcase (assume ck is already) */
+ ca = tolower(ca);
+ if (ca != ck)
+ return 0; /* no good */
+ nmatched++; /* count matched characters */
+ }
+ /* reached end of argument; fail if it's too short for unique abbrev */
+ if (nmatched < minchars)
+ return 0;
+ return 1; /* A-OK */
+}
+
+
+/*
+ * The main program.
+ */
+
+int
+main (int argc, char **argv)
+{
+ int argn;
+ char * arg;
+ int verbose = 0;
+
+ /* On Mac, fetch a command line. */
+#ifdef USE_CCOMMAND
+ argc = ccommand(&argv);
+#endif
+
+ progname = argv[0];
+ if (progname == NULL || progname[0] == 0)
+ progname = "rdjpgcom"; /* in case C library doesn't provide it */
+
+ /* Parse switches, if any */
+ for (argn = 1; argn < argc; argn++) {
+ arg = argv[argn];
+ if (arg[0] != '-')
+ break; /* not switch, must be file name */
+ arg++; /* advance over '-' */
+ if (keymatch(arg, "verbose", 1)) {
+ verbose++;
+ } else
+ usage();
+ }
+
+ /* Open the input file. */
+ /* Unix style: expect zero or one file name */
+ if (argn < argc-1) {
+ fprintf(stderr, "%s: only one input file\n", progname);
+ usage();
+ }
+ if (argn < argc) {
+ if ((infile = fopen(argv[argn], READ_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ /* default input file is stdin */
+#ifdef USE_SETMODE /* need to hack file mode? */
+ setmode(fileno(stdin), O_BINARY);
+#endif
+#ifdef USE_FDOPEN /* need to re-open in binary mode? */
+ if ((infile = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open stdin\n", progname);
+ exit(EXIT_FAILURE);
+ }
+#else
+ infile = stdin;
+#endif
+ }
+
+ /* Scan the JPEG headers. */
+ (void) scan_JPEG_header(verbose);
+
+ /* All done. */
+ exit(EXIT_SUCCESS);
+ return 0; /* suppress no-return-value warnings */
+}
diff --git a/jpeg-6c/rdppm.c b/jpeg-6c/rdppm.c
new file mode 100644
index 0000000..27e053a
--- /dev/null
+++ b/jpeg-6c/rdppm.c
@@ -0,0 +1,654 @@
+/*
+ * rdppm.c
+ *
+ * Copyright (C) 1991-1997, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to read input images in PPM/PGM format.
+ * The extended 2-byte-per-sample raw PPM/PGM formats are supported.
+ * The PBMPLUS library is NOT required to compile this software
+ * (but it is highly useful as a set of PPM image manipulation programs).
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications. As they stand, they assume input from
+ * an ordinary stdio stream. They further assume that reading begins
+ * at the start of the file; start_input may need work if the
+ * user interface has already read some data (e.g., to determine that
+ * the file is indeed PPM format).
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+
+#ifdef PPM_SUPPORTED
+
+
+/* Portions of this code are based on the PBMPLUS library, which is:
+**
+** Copyright (C) 1988 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.
+*/
+
+
+/* Macros to deal with unsigned chars as efficiently as compiler allows */
+
+#ifdef HAVE_UNSIGNED_CHAR
+typedef unsigned char U_CHAR;
+#define UCH(x) ((int) (x))
+#else /* !HAVE_UNSIGNED_CHAR */
+#ifdef CHAR_IS_UNSIGNED
+typedef char U_CHAR;
+#define UCH(x) ((int) (x))
+#else
+typedef char U_CHAR;
+#define UCH(x) ((int) (x) & 0xFF)
+#endif
+#endif /* HAVE_UNSIGNED_CHAR */
+
+
+#define ReadOK(file,buffer,len) (JFREAD(file,buffer,len) == ((size_t) (len)))
+
+
+/*
+ * On most systems, reading individual bytes with getc() is drastically less
+ * efficient than buffering a row at a time with fread(). On PCs, we must
+ * allocate the buffer in near data space, because we are assuming small-data
+ * memory model, wherein fread() can't reach far memory. If you need to
+ * process very wide images on a PC, you might have to compile in large-memory
+ * model, or else replace fread() with a getc() loop --- which will be much
+ * slower.
+ */
+
+
+/* Private version of data source object */
+
+typedef struct {
+ struct cjpeg_source_struct pub; /* public fields */
+
+ U_CHAR *iobuffer; /* non-FAR pointer to I/O buffer */
+ JSAMPROW pixrow; /* FAR pointer to same */
+ size_t buffer_width; /* width of I/O buffer */
+ JSAMPLE *rescale; /* => maxval-remapping array, or NULL */
+} ppm_source_struct;
+
+typedef ppm_source_struct * ppm_source_ptr;
+
+
+LOCAL(int)
+pbm_getc (FILE * infile)
+/* Read next char, skipping over any comments */
+/* A comment/newline sequence is returned as a newline */
+{
+ register int ch;
+
+ ch = getc(infile);
+ if (ch == '#') {
+ do {
+ ch = getc(infile);
+ } while (ch != '\n' && ch != EOF);
+ }
+ return ch;
+}
+
+
+LOCAL(unsigned int)
+read_pbm_integer (j_compress_ptr cinfo, FILE * infile)
+/* Read an unsigned decimal integer from the PPM file */
+/* Swallows one trailing character after the integer */
+/* Note that on a 16-bit-int machine, only values up to 64k can be read. */
+/* This should not be a problem in practice. */
+{
+ register int ch;
+ register unsigned int val;
+
+ /* Skip any leading whitespace */
+ do {
+ ch = pbm_getc(infile);
+ if (ch == EOF)
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ } while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
+
+ if (ch < '0' || ch > '9')
+ ERREXIT(cinfo, JERR_PPM_NONNUMERIC);
+
+ val = ch - '0';
+ while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') {
+ val *= 10;
+ val += ch - '0';
+ }
+ return val;
+}
+
+
+/*
+ * Read one row of pixels.
+ *
+ * We provide several different versions depending on input file format.
+ * In all cases, input is scaled to the size of JSAMPLE.
+ *
+ * A really fast path is provided for reading byte/sample raw files with
+ * maxval = MAXJSAMPLE, which is the normal case for 8-bit data.
+ */
+
+
+METHODDEF(JDIMENSION)
+get_text_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading text-format PGM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ FILE * infile = source->pub.input_file;
+ register JSAMPROW ptr;
+ register JSAMPLE *rescale = source->rescale;
+ JDIMENSION col;
+
+ ptr = source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_text_gray_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading text-format PGM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ FILE * infile = source->pub.input_file;
+ register JSAMPROW16 ptr;
+ register JSAMPLE16 *rescale = (JSAMPROW16)source->rescale;
+ JDIMENSION col;
+
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_text_rgb_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading text-format PPM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ FILE * infile = source->pub.input_file;
+ register JSAMPROW ptr;
+ register JSAMPLE *rescale = source->rescale;
+ JDIMENSION col;
+
+ ptr = source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
+ *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
+ *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_text_rgb_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading text-format PPM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ FILE * infile = source->pub.input_file;
+ register JSAMPROW16 ptr;
+ register JSAMPLE16 *rescale = (JSAMPROW16)source->rescale;
+ JDIMENSION col;
+
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
+ *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
+ *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_scaled_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-byte-format PGM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW ptr;
+ register U_CHAR * bufferptr;
+ register JSAMPLE *rescale = source->rescale;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr++ = rescale[UCH(*bufferptr++)];
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_scaled_gray_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-byte-format PGM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW16 ptr;
+ register U_CHAR * bufferptr;
+ register JSAMPLE16 *rescale = (JSAMPROW16)source->rescale;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr++ = rescale[UCH(*bufferptr++)];
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_scaled_rgb_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-byte-format PPM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW ptr;
+ register U_CHAR * bufferptr;
+ register JSAMPLE *rescale = source->rescale;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr++ = rescale[UCH(*bufferptr++)];
+ *ptr++ = rescale[UCH(*bufferptr++)];
+ *ptr++ = rescale[UCH(*bufferptr++)];
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_scaled_rgb_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-byte-format PPM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW16 ptr;
+ register U_CHAR * bufferptr;
+ register JSAMPLE16 *rescale = (JSAMPROW16)source->rescale;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr++ = rescale[UCH(*bufferptr++)];
+ *ptr++ = rescale[UCH(*bufferptr++)];
+ *ptr++ = rescale[UCH(*bufferptr++)];
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_raw_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-byte-format files with maxval = MAXJSAMPLE.
+ * In this case we just read right into the JSAMPLE buffer!
+ * Note that same code works for PPM and PGM files.
+ */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_corr_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-word-format maxval = MAXJSAMPLE, any endian */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW16 ptr;
+ register U_CHAR * bufferptr;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ *ptr = UCH(*bufferptr++) << 8;
+ *ptr++ |= UCH(*bufferptr++);
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_word_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-word-format PGM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW ptr;
+ register U_CHAR * bufferptr;
+ register JSAMPLE *rescale = source->rescale;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ register int temp;
+ temp = UCH(*bufferptr++) << 8;
+ temp |= UCH(*bufferptr++);
+ *ptr++ = rescale[temp];
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_word_gray_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-word-format PGM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW16 ptr;
+ register U_CHAR * bufferptr;
+ register JSAMPLE16 *rescale = (JSAMPROW16)source->rescale;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ register int temp;
+ temp = UCH(*bufferptr++) << 8;
+ temp |= UCH(*bufferptr++);
+ *ptr++ = rescale[temp];
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_word_rgb_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-word-format PPM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW ptr;
+ register U_CHAR * bufferptr;
+ register JSAMPLE *rescale = source->rescale;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ register int temp;
+ temp = UCH(*bufferptr++) << 8;
+ temp |= UCH(*bufferptr++);
+ *ptr++ = rescale[temp];
+ temp = UCH(*bufferptr++) << 8;
+ temp |= UCH(*bufferptr++);
+ *ptr++ = rescale[temp];
+ temp = UCH(*bufferptr++) << 8;
+ temp |= UCH(*bufferptr++);
+ *ptr++ = rescale[temp];
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_word_rgb_row16 (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading raw-word-format PPM files with any maxval */
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ register JSAMPROW16 ptr;
+ register U_CHAR * bufferptr;
+ register JSAMPLE16 *rescale = (JSAMPROW16)source->rescale;
+ JDIMENSION col;
+
+ if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ ptr = (JSAMPROW16)source->pub.buffer[0];
+ bufferptr = source->iobuffer;
+ for (col = cinfo->image_width; col > 0; col--) {
+ register int temp;
+ temp = UCH(*bufferptr++);
+ temp |= UCH(*bufferptr++) << 8;
+ *ptr++ = rescale[temp];
+ temp = UCH(*bufferptr++);
+ temp |= UCH(*bufferptr++) << 8;
+ *ptr++ = rescale[temp];
+ temp = UCH(*bufferptr++);
+ temp |= UCH(*bufferptr++) << 8;
+ *ptr++ = rescale[temp];
+ }
+ return 1;
+}
+
+/*
+ * Read the file header; return image size and component count.
+ */
+
+METHODDEF(void)
+start_input_ppm (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ ppm_source_ptr source = (ppm_source_ptr) sinfo;
+ int c, bit_width;
+ unsigned int w, h, maxval;
+/* On 16-bit-int machines we have to be careful of maxval = 65535 + 1 */
+ long maxval_shift;
+ boolean need_iobuffer, use_raw_buffer, need_rescale;
+
+ if (getc(source->pub.input_file) != 'P')
+ ERREXIT(cinfo, JERR_PPM_NOT);
+
+ c = getc(source->pub.input_file); /* subformat discriminator character */
+
+ /* detect unsupported variants (ie, PBM) before trying to read header */
+ switch (c) {
+ case '2': /* it's a text-format PGM file */
+ case '3': /* it's a text-format PPM file */
+ case '5': /* it's a raw-format PGM file */
+ case '6': /* it's a raw-format PPM file */
+ break;
+ default:
+ ERREXIT(cinfo, JERR_PPM_NOT);
+ break;
+ }
+
+ /* fetch the remaining header info */
+ w = read_pbm_integer(cinfo, source->pub.input_file);
+ h = read_pbm_integer(cinfo, source->pub.input_file);
+ maxval = read_pbm_integer(cinfo, source->pub.input_file);
+
+ if (w <= 0 || h <= 0 || maxval <= 0) /* error check */
+ ERREXIT(cinfo, JERR_PPM_NOT);
+
+/* cinfo->data_precision = BITS_IN_JSAMPLE;*/ /* we always rescale data to this */
+/* Find the # of bits for maxval. */
+ cinfo->data_precision_other = 0;
+ for (maxval_shift = (long)maxval + 1L ; maxval_shift > 1; maxval_shift >>= 1)
+ cinfo->data_precision_other++;
+/* Set to 0 for: use input value from file */
+ if (cinfo->data_precision == 0)
+ cinfo->data_precision = cinfo->data_precision_other;
+
+ cinfo->image_width = (JDIMENSION) w;
+ cinfo->image_height = (JDIMENSION) h;
+
+ /* initialize flags to most common settings */
+ need_iobuffer = TRUE; /* do we need an I/O buffer? */
+ use_raw_buffer = FALSE; /* do we map input buffer onto I/O buffer? */
+ need_rescale = TRUE; /* do we need a rescale array? */
+
+ switch (c) {
+ case '2': /* it's a text-format PGM file */
+ cinfo->input_components = 1;
+ cinfo->in_color_space = JCS_GRAYSCALE;
+ TRACEMS2(cinfo, 1, JTRC_PGM_TEXT, w, h);
+ if (cinfo->data_precision <= 8)
+ source->pub.get_pixel_rows = get_text_gray_row;
+ else source->pub.get_pixel_rows = get_text_gray_row16;
+ need_iobuffer = FALSE;
+ break;
+
+ case '3': /* it's a text-format PPM file */
+ cinfo->input_components = 3;
+ cinfo->in_color_space = JCS_RGB;
+ TRACEMS2(cinfo, 1, JTRC_PPM_TEXT, w, h);
+ if (cinfo->data_precision <= 8)
+ source->pub.get_pixel_rows = get_text_rgb_row;
+ else source->pub.get_pixel_rows = get_text_rgb_row16;
+ need_iobuffer = FALSE;
+ break;
+
+ case '5': /* it's a raw-format PGM file */
+ cinfo->input_components = 1;
+ cinfo->in_color_space = JCS_GRAYSCALE;
+ TRACEMS2(cinfo, 1, JTRC_PGM, w, h);
+ if (cinfo->data_precision == cinfo->data_precision_other) {
+ need_rescale = FALSE;
+ if (cinfo->data_precision > 8) {
+ source->pub.get_pixel_rows = get_corr_row16;
+ use_raw_buffer = FALSE;
+ } else { /* 8 bit*/
+ source->pub.get_pixel_rows = get_raw_row;
+ use_raw_buffer = TRUE;
+ }
+ } else if (cinfo->data_precision > 8) {
+ if (cinfo->data_precision_other > 8)
+ source->pub.get_pixel_rows = get_word_gray_row16;
+ else source->pub.get_pixel_rows = get_word_gray_row;
+ } else {
+ if (cinfo->data_precision_other > 8)
+ source->pub.get_pixel_rows = get_scaled_gray_row16;
+ else source->pub.get_pixel_rows = get_scaled_gray_row;
+ }
+ break;
+
+ case '6': /* it's a raw-format PPM file */
+ cinfo->input_components = 3;
+ cinfo->in_color_space = JCS_RGB;
+ TRACEMS2(cinfo, 1, JTRC_PPM, w, h);
+ if (cinfo->data_precision == cinfo->data_precision_other) {
+ need_rescale = FALSE;
+ if (cinfo->data_precision > 8) {
+ source->pub.get_pixel_rows = get_corr_row16;
+ use_raw_buffer = FALSE;
+ } else { /* 8 bit*/
+ source->pub.get_pixel_rows = get_raw_row;
+ use_raw_buffer = TRUE;
+ }
+ } else if (cinfo->data_precision > 8) {
+ if (cinfo->data_precision_other > 8)
+ source->pub.get_pixel_rows = get_word_rgb_row16;
+ else source->pub.get_pixel_rows = get_word_rgb_row;
+ } else {
+ if (cinfo->data_precision_other > 8)
+ source->pub.get_pixel_rows = get_scaled_rgb_row16;
+ else source->pub.get_pixel_rows = get_scaled_rgb_row;
+ }
+ break;
+ }
+
+ /* Allocate space for I/O buffer: 1 or 3 bytes or words/pixel. */
+ if (need_iobuffer) {
+ source->buffer_width = (size_t) w * cinfo->input_components *
+ ((maxval<=255) ? SIZEOF(U_CHAR) : (2*SIZEOF(U_CHAR)));
+ source->iobuffer = (U_CHAR *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ source->buffer_width);
+ }
+
+ /* Create compressor input buffer. */
+ bit_width = ((cinfo->data_precision<=8) ? SIZEOF(JSAMPLE) : SIZEOF(JSAMPLE16));
+ if (use_raw_buffer) {
+ /* For unscaled raw-input case, we can just map it onto the I/O buffer. */
+ /* Synthesize a JSAMPARRAY pointer structure */
+ /* Cast here implies near->far pointer conversion on PCs */
+ source->pixrow = (JSAMPROW) source->iobuffer;
+ source->pub.buffer = & source->pixrow;
+ source->pub.buffer_height = 1;
+ } else {
+ /* Need to translate anyway, so make a separate sample buffer. */
+ source->pub.buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) w * cinfo->input_components *
+ bit_width, (JDIMENSION) 1);
+ source->pub.buffer_height = 1;
+ }
+
+ /* Compute the rescaling array if required. */
+ cinfo->lossless_scaling = FALSE;
+ if (need_rescale) {
+ INT32 val, half_maxval, maxjsample;
+
+ /* On 16-bit-int machines we have to be careful of maxval = 65535 */
+ source->rescale = (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (size_t) (((long) maxval + 1L) * (long)bit_width));
+ half_maxval = maxval / 2;
+ maxjsample = (1 << cinfo->data_precision) - 1;
+ if (bit_width == 1) {
+ if (maxjsample == maxval) {
+ for (val = 0; val <= (INT32) maxval; val++) source->rescale[val] = val;
+ } else {
+ for (val = 0; val <= (INT32) maxval; val++) {
+ /* The multiplication here must be done in 32 bits to avoid overflow */
+ source->rescale[val] = (JSAMPLE) ((val*maxjsample + half_maxval)/maxval);
+ }
+ }
+ } else {
+ JSAMPLE16 *rescale16;
+ rescale16 = (JSAMPLE16 *)source->rescale;
+ if (maxjsample == maxval) {
+ for (val = 0; val <= (INT32) maxval; val++) rescale16[val] = val;
+ } else {
+ for (val = 0; val <= (INT32) maxval; val++) {
+ /* The multiplication here must be done in 32 bits to avoid overflow */
+ rescale16[val] = (JSAMPLE16) ((val*maxjsample + half_maxval)/maxval);
+ }
+ }
+ }
+ }
+}
+
+
+/*
+ * Finish up at the end of the file.
+ */
+
+METHODDEF(void)
+finish_input_ppm (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ /* no work */
+}
+
+
+/*
+ * The module selection routine for PPM format input.
+ */
+
+GLOBAL(cjpeg_source_ptr)
+jinit_read_ppm (j_compress_ptr cinfo)
+{
+ ppm_source_ptr source;
+
+ /* Create module interface object */
+ source = (ppm_source_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(ppm_source_struct));
+ /* Fill in method ptrs, except get_pixel_rows which start_input sets */
+ source->pub.start_input = start_input_ppm;
+ source->pub.finish_input = finish_input_ppm;
+
+ return (cjpeg_source_ptr) source;
+}
+
+#endif /* PPM_SUPPORTED */
diff --git a/jpeg-6c/rdrle.c b/jpeg-6c/rdrle.c
new file mode 100644
index 0000000..542bc37
--- /dev/null
+++ b/jpeg-6c/rdrle.c
@@ -0,0 +1,387 @@
+/*
+ * rdrle.c
+ *
+ * Copyright (C) 1991-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to read input images in Utah RLE format.
+ * The Utah Raster Toolkit library is required (version 3.1 or later).
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications. As they stand, they assume input from
+ * an ordinary stdio stream. They further assume that reading begins
+ * at the start of the file; start_input may need work if the
+ * user interface has already read some data (e.g., to determine that
+ * the file is indeed RLE format).
+ *
+ * Based on code contributed by Mike Lijewski,
+ * with updates from Robert Hutchinson.
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+
+#ifdef RLE_SUPPORTED
+
+/* rle.h is provided by the Utah Raster Toolkit. */
+
+#include <rle.h>
+
+/*
+ * We assume that JSAMPLE has the same representation as rle_pixel,
+ * to wit, "unsigned char". Hence we can't cope with 12- or 16-bit samples.
+ */
+
+#if BITS_IN_JSAMPLE != 8
+ Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
+#endif
+
+/*
+ * We support the following types of RLE files:
+ *
+ * GRAYSCALE - 8 bits, no colormap
+ * MAPPEDGRAY - 8 bits, 1 channel colomap
+ * PSEUDOCOLOR - 8 bits, 3 channel colormap
+ * TRUECOLOR - 24 bits, 3 channel colormap
+ * DIRECTCOLOR - 24 bits, no colormap
+ *
+ * For now, we ignore any alpha channel in the image.
+ */
+
+typedef enum
+ { GRAYSCALE, MAPPEDGRAY, PSEUDOCOLOR, TRUECOLOR, DIRECTCOLOR } rle_kind;
+
+
+/*
+ * Since RLE stores scanlines bottom-to-top, we have to invert the image
+ * to conform to JPEG's top-to-bottom order. To do this, we read the
+ * incoming image into a virtual array on the first get_pixel_rows call,
+ * then fetch the required row from the virtual array on subsequent calls.
+ */
+
+typedef struct _rle_source_struct * rle_source_ptr;
+
+typedef struct _rle_source_struct {
+ struct cjpeg_source_struct pub; /* public fields */
+
+ rle_kind visual; /* actual type of input file */
+ jvirt_sarray_ptr image; /* virtual array to hold the image */
+ JDIMENSION row; /* current row # in the virtual array */
+ rle_hdr header; /* Input file information */
+ rle_pixel** rle_row; /* holds a row returned by rle_getrow() */
+
+} rle_source_struct;
+
+
+/*
+ * Read the file header; return image size and component count.
+ */
+
+METHODDEF(void)
+start_input_rle (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ rle_source_ptr source = (rle_source_ptr) sinfo;
+ JDIMENSION width, height;
+#ifdef PROGRESS_REPORT
+ cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
+#endif
+
+ /* Use RLE library routine to get the header info */
+ source->header = *rle_hdr_init(NULL);
+ source->header.rle_file = source->pub.input_file;
+ switch (rle_get_setup(&(source->header))) {
+ case RLE_SUCCESS:
+ /* A-OK */
+ break;
+ case RLE_NOT_RLE:
+ ERREXIT(cinfo, JERR_RLE_NOT);
+ break;
+ case RLE_NO_SPACE:
+ ERREXIT(cinfo, JERR_RLE_MEM);
+ break;
+ case RLE_EMPTY:
+ ERREXIT(cinfo, JERR_RLE_EMPTY);
+ break;
+ case RLE_EOF:
+ ERREXIT(cinfo, JERR_RLE_EOF);
+ break;
+ default:
+ ERREXIT(cinfo, JERR_RLE_BADERROR);
+ break;
+ }
+
+ /* Figure out what we have, set private vars and return values accordingly */
+
+ width = source->header.xmax - source->header.xmin + 1;
+ height = source->header.ymax - source->header.ymin + 1;
+ source->header.xmin = 0; /* realign horizontally */
+ source->header.xmax = width-1;
+
+ cinfo->image_width = width;
+ cinfo->image_height = height;
+ cinfo->data_precision = 8; /* we can only handle 8 bit data */
+
+ if (source->header.ncolors == 1 && source->header.ncmap == 0) {
+ source->visual = GRAYSCALE;
+ TRACEMS2(cinfo, 1, JTRC_RLE_GRAY, width, height);
+ } else if (source->header.ncolors == 1 && source->header.ncmap == 1) {
+ source->visual = MAPPEDGRAY;
+ TRACEMS3(cinfo, 1, JTRC_RLE_MAPGRAY, width, height,
+ 1 << source->header.cmaplen);
+ } else if (source->header.ncolors == 1 && source->header.ncmap == 3) {
+ source->visual = PSEUDOCOLOR;
+ TRACEMS3(cinfo, 1, JTRC_RLE_MAPPED, width, height,
+ 1 << source->header.cmaplen);
+ } else if (source->header.ncolors == 3 && source->header.ncmap == 3) {
+ source->visual = TRUECOLOR;
+ TRACEMS3(cinfo, 1, JTRC_RLE_FULLMAP, width, height,
+ 1 << source->header.cmaplen);
+ } else if (source->header.ncolors == 3 && source->header.ncmap == 0) {
+ source->visual = DIRECTCOLOR;
+ TRACEMS2(cinfo, 1, JTRC_RLE, width, height);
+ } else
+ ERREXIT(cinfo, JERR_RLE_UNSUPPORTED);
+
+ if (source->visual == GRAYSCALE || source->visual == MAPPEDGRAY) {
+ cinfo->in_color_space = JCS_GRAYSCALE;
+ cinfo->input_components = 1;
+ } else {
+ cinfo->in_color_space = JCS_RGB;
+ cinfo->input_components = 3;
+ }
+
+ /*
+ * A place to hold each scanline while it's converted.
+ * (GRAYSCALE scanlines don't need converting)
+ */
+ if (source->visual != GRAYSCALE) {
+ source->rle_row = (rle_pixel**) (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) width, (JDIMENSION) cinfo->input_components);
+ }
+
+ /* request a virtual array to hold the image */
+ source->image = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ (JDIMENSION) (width * source->header.ncolors),
+ (JDIMENSION) height, (JDIMENSION) 1);
+
+#ifdef PROGRESS_REPORT
+ if (progress != NULL) {
+ /* count file input as separate pass */
+ progress->total_extra_passes++;
+ }
+#endif
+
+ source->pub.buffer_height = 1;
+}
+
+
+/*
+ * Read one row of pixels.
+ * Called only after load_image has read the image into the virtual array.
+ * Used for GRAYSCALE, MAPPEDGRAY, TRUECOLOR, and DIRECTCOLOR images.
+ */
+
+METHODDEF(JDIMENSION)
+get_rle_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ rle_source_ptr source = (rle_source_ptr) sinfo;
+
+ source->row--;
+ source->pub.buffer = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, source->image, source->row, (JDIMENSION) 1, FALSE);
+
+ return 1;
+}
+
+/*
+ * Read one row of pixels.
+ * Called only after load_image has read the image into the virtual array.
+ * Used for PSEUDOCOLOR images.
+ */
+
+METHODDEF(JDIMENSION)
+get_pseudocolor_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ rle_source_ptr source = (rle_source_ptr) sinfo;
+ JSAMPROW src_row, dest_row;
+ JDIMENSION col;
+ rle_map *colormap;
+ int val;
+
+ colormap = source->header.cmap;
+ dest_row = source->pub.buffer[0];
+ source->row--;
+ src_row = * (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, source->image, source->row, (JDIMENSION) 1, FALSE);
+
+ for (col = cinfo->image_width; col > 0; col--) {
+ val = GETJSAMPLE(*src_row++);
+ *dest_row++ = (JSAMPLE) (colormap[val ] >> 8);
+ *dest_row++ = (JSAMPLE) (colormap[val + 256] >> 8);
+ *dest_row++ = (JSAMPLE) (colormap[val + 512] >> 8);
+ }
+
+ return 1;
+}
+
+
+/*
+ * Load the image into a virtual array. We have to do this because RLE
+ * files start at the lower left while the JPEG standard has them starting
+ * in the upper left. This is called the first time we want to get a row
+ * of input. What we do is load the RLE data into the array and then call
+ * the appropriate routine to read one row from the array. Before returning,
+ * we set source->pub.get_pixel_rows so that subsequent calls go straight to
+ * the appropriate row-reading routine.
+ */
+
+METHODDEF(JDIMENSION)
+load_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ rle_source_ptr source = (rle_source_ptr) sinfo;
+ JDIMENSION row, col;
+ JSAMPROW scanline, red_ptr, green_ptr, blue_ptr;
+ rle_pixel **rle_row;
+ rle_map *colormap;
+ char channel;
+#ifdef PROGRESS_REPORT
+ cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
+#endif
+
+ colormap = source->header.cmap;
+ rle_row = source->rle_row;
+
+ /* Read the RLE data into our virtual array.
+ * We assume here that (a) rle_pixel is represented the same as JSAMPLE,
+ * and (b) we are not on a machine where FAR pointers differ from regular.
+ */
+ RLE_CLR_BIT(source->header, RLE_ALPHA); /* don't read the alpha channel */
+
+#ifdef PROGRESS_REPORT
+ if (progress != NULL) {
+ progress->pub.pass_limit = cinfo->image_height;
+ progress->pub.pass_counter = 0;
+ (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
+ }
+#endif
+
+ switch (source->visual) {
+
+ case GRAYSCALE:
+ case PSEUDOCOLOR:
+ for (row = 0; row < cinfo->image_height; row++) {
+ rle_row = (rle_pixel **) (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, source->image, row, (JDIMENSION) 1, TRUE);
+ rle_getrow(&source->header, rle_row);
+#ifdef PROGRESS_REPORT
+ if (progress != NULL) {
+ progress->pub.pass_counter++;
+ (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
+ }
+#endif
+ }
+ break;
+
+ case MAPPEDGRAY:
+ case TRUECOLOR:
+ for (row = 0; row < cinfo->image_height; row++) {
+ scanline = * (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, source->image, row, (JDIMENSION) 1, TRUE);
+ rle_row = source->rle_row;
+ rle_getrow(&source->header, rle_row);
+
+ for (col = 0; col < cinfo->image_width; col++) {
+ for (channel = 0; channel < source->header.ncolors; channel++) {
+ *scanline++ = (JSAMPLE)
+ (colormap[GETJSAMPLE(rle_row[channel][col]) + 256 * channel] >> 8);
+ }
+ }
+
+#ifdef PROGRESS_REPORT
+ if (progress != NULL) {
+ progress->pub.pass_counter++;
+ (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
+ }
+#endif
+ }
+ break;
+
+ case DIRECTCOLOR:
+ for (row = 0; row < cinfo->image_height; row++) {
+ scanline = * (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, source->image, row, (JDIMENSION) 1, TRUE);
+ rle_getrow(&source->header, rle_row);
+
+ red_ptr = rle_row[0];
+ green_ptr = rle_row[1];
+ blue_ptr = rle_row[2];
+
+ for (col = cinfo->image_width; col > 0; col--) {
+ *scanline++ = *red_ptr++;
+ *scanline++ = *green_ptr++;
+ *scanline++ = *blue_ptr++;
+ }
+
+#ifdef PROGRESS_REPORT
+ if (progress != NULL) {
+ progress->pub.pass_counter++;
+ (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
+ }
+#endif
+ }
+ }
+
+#ifdef PROGRESS_REPORT
+ if (progress != NULL)
+ progress->completed_extra_passes++;
+#endif
+
+ /* Set up to call proper row-extraction routine in future */
+ if (source->visual == PSEUDOCOLOR) {
+ source->pub.buffer = source->rle_row;
+ source->pub.get_pixel_rows = get_pseudocolor_row;
+ } else {
+ source->pub.get_pixel_rows = get_rle_row;
+ }
+ source->row = cinfo->image_height;
+
+ /* And fetch the topmost (bottommost) row */
+ return (*source->pub.get_pixel_rows) (cinfo, sinfo);
+}
+
+
+/*
+ * Finish up at the end of the file.
+ */
+
+METHODDEF(void)
+finish_input_rle (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ /* no work */
+}
+
+
+/*
+ * The module selection routine for RLE format input.
+ */
+
+GLOBAL(cjpeg_source_ptr)
+jinit_read_rle (j_compress_ptr cinfo)
+{
+ rle_source_ptr source;
+
+ /* Create module interface object */
+ source = (rle_source_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(rle_source_struct));
+ /* Fill in method ptrs */
+ source->pub.start_input = start_input_rle;
+ source->pub.finish_input = finish_input_rle;
+ source->pub.get_pixel_rows = load_image;
+
+ return (cjpeg_source_ptr) source;
+}
+
+#endif /* RLE_SUPPORTED */
diff --git a/jpeg-6c/rdswitch.c b/jpeg-6c/rdswitch.c
new file mode 100644
index 0000000..fae66b1
--- /dev/null
+++ b/jpeg-6c/rdswitch.c
@@ -0,0 +1,358 @@
+/*
+ * rdswitch.c
+ *
+ * Copyright (C) 1991-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to process some of cjpeg's more complicated
+ * command-line switches. Switches processed here are:
+ * -qtables file Read quantization tables from text file
+ * -scans file Read scan script from text file
+ * -qslots N[,N,...] Set component quantization table selectors
+ * -sample HxV[,HxV,...] Set component sampling factors
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+#include <ctype.h> /* to declare isdigit(), isspace() */
+
+
+LOCAL(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;
+
+ ch = getc(file);
+ if (ch == '#') {
+ do {
+ ch = getc(file);
+ } while (ch != '\n' && ch != EOF);
+ }
+ return ch;
+}
+
+
+LOCAL(boolean)
+read_text_integer (FILE * file, long * result, int * termchar)
+/* Read an unsigned decimal integer from a file, store it in result */
+/* Reads one trailing character after the integer; returns it in termchar */
+{
+ register int ch;
+ register long val;
+
+ /* Skip any leading whitespace, detect EOF */
+ do {
+ ch = text_getc(file);
+ if (ch == EOF) {
+ *termchar = ch;
+ return FALSE;
+ }
+ } while (isspace(ch));
+
+ if (! isdigit(ch)) {
+ *termchar = ch;
+ return FALSE;
+ }
+
+ val = ch - '0';
+ while ((ch = text_getc(file)) != EOF) {
+ if (! isdigit(ch))
+ break;
+ val *= 10;
+ val += ch - '0';
+ }
+ *result = val;
+ *termchar = ch;
+ return TRUE;
+}
+
+
+GLOBAL(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.
+ */
+{
+ FILE * fp;
+ int tblno, i, termchar;
+ long val;
+ unsigned int table[DCTSIZE2];
+
+ if ((fp = fopen(filename, "r")) == NULL) {
+ fprintf(stderr, "Can't open table file %s\n", filename);
+ return FALSE;
+ }
+ tblno = 0;
+
+ while (read_text_integer(fp, &val, &termchar)) { /* read 1st element of table */
+ if (tblno >= NUM_QUANT_TBLS) {
+ fprintf(stderr, "Too many tables in file %s\n", filename);
+ fclose(fp);
+ return FALSE;
+ }
+ table[0] = (unsigned int) val;
+ for (i = 1; i < DCTSIZE2; i++) {
+ if (! read_text_integer(fp, &val, &termchar)) {
+ fprintf(stderr, "Invalid table data in file %s\n", filename);
+ fclose(fp);
+ return FALSE;
+ }
+ table[i] = (unsigned int) val;
+ }
+ jpeg_add_quant_table(cinfo, tblno, table, scale_factor, force_baseline);
+ tblno++;
+ }
+
+ if (termchar != EOF) {
+ fprintf(stderr, "Non-numeric data in file %s\n", filename);
+ fclose(fp);
+ return FALSE;
+ }
+
+ fclose(fp);
+ return TRUE;
+}
+
+
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+
+LOCAL(boolean)
+read_scan_integer (FILE * file, long * result, int * termchar)
+/* Variant of read_text_integer that always looks for a non-space termchar;
+ * this simplifies parsing of punctuation in scan scripts.
+ */
+{
+ register int ch;
+
+ if (! read_text_integer(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 != ':')
+ ch = ' ';
+ }
+ *termchar = ch;
+ return TRUE;
+}
+
+
+GLOBAL(boolean)
+read_scan_script (j_compress_ptr cinfo, char * filename)
+/* 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.
+ * 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.
+ * Comments preceded by '#' may be included in the file.
+ * Note: we do very little validity checking here;
+ * jcmaster.c will validate the script parameters.
+ */
+{
+ FILE * fp;
+ int scanno, ncomps, termchar;
+ long val;
+ jpeg_scan_info * scanptr;
+#define MAX_SCANS 100 /* quite arbitrary limit */
+ jpeg_scan_info scans[MAX_SCANS];
+
+ if ((fp = fopen(filename, "r")) == NULL) {
+ fprintf(stderr, "Can't open scan definition file %s\n", filename);
+ return FALSE;
+ }
+ scanptr = scans;
+ scanno = 0;
+
+ while (read_scan_integer(fp, &val, &termchar)) {
+ if (scanno >= MAX_SCANS) {
+ fprintf(stderr, "Too many scans defined in file %s\n", filename);
+ fclose(fp);
+ return FALSE;
+ }
+ scanptr->component_index[0] = (int) val;
+ ncomps = 1;
+ while (termchar == ' ') {
+ if (ncomps >= MAX_COMPS_IN_SCAN) {
+ fprintf(stderr, "Too many components in one scan in file %s\n",
+ filename);
+ fclose(fp);
+ return FALSE;
+ }
+ if (! read_scan_integer(fp, &val, &termchar))
+ goto bogus;
+ scanptr->component_index[ncomps] = (int) val;
+ ncomps++;
+ }
+ scanptr->comps_in_scan = ncomps;
+ if (termchar == ':') {
+ if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ')
+ goto bogus;
+ scanptr->Ss = (int) val;
+ if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ')
+ goto bogus;
+ scanptr->Se = (int) val;
+ if (! read_scan_integer(fp, &val, &termchar) || termchar != ' ')
+ goto bogus;
+ scanptr->Ah = (int) val;
+ if (! read_scan_integer(fp, &val, &termchar))
+ goto bogus;
+ scanptr->Al = (int) val;
+ } else {
+ /* set non-progressive parameters */
+ scanptr->Ss = 0;
+ scanptr->Se = DCTSIZE2-1;
+ scanptr->Ah = 0;
+ scanptr->Al = 0;
+ }
+ if (termchar != ';' && termchar != EOF) {
+bogus:
+ fprintf(stderr, "Invalid scan entry format in file %s\n", filename);
+ fclose(fp);
+ return FALSE;
+ }
+ scanptr++, scanno++;
+ }
+
+ if (termchar != EOF) {
+ fprintf(stderr, "Non-numeric data in file %s\n", filename);
+ fclose(fp);
+ return FALSE;
+ }
+
+ if (scanno > 0) {
+ /* Stash completed scan list in cinfo structure.
+ * NOTE: for cjpeg's use, JPOOL_IMAGE is the right lifetime for this data,
+ * but if you want to compress multiple images you'd want JPOOL_PERMANENT.
+ */
+ scanptr = (jpeg_scan_info *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ scanno * SIZEOF(jpeg_scan_info));
+ MEMCOPY(scanptr, scans, scanno * SIZEOF(jpeg_scan_info));
+ cinfo->scan_info = scanptr;
+ cinfo->num_scans = scanno;
+ }
+
+ fclose(fp);
+ return TRUE;
+}
+
+#endif /* C_MULTISCAN_FILES_SUPPORTED */
+
+
+GLOBAL(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 # */
+ int ci;
+ char ch;
+
+ 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;
+ if (val < 0 || val >= NUM_QUANT_TBLS) {
+ fprintf(stderr, "JPEG quantization tables are numbered 0..%d\n",
+ NUM_QUANT_TBLS-1);
+ return FALSE;
+ }
+ cinfo->comp_info[ci].quant_tbl_no = val;
+ while (*arg && *arg++ != ',') /* advance to next segment of arg string */
+ ;
+ } else {
+ /* reached end of parameter, set remaining components to last table */
+ cinfo->comp_info[ci].quant_tbl_no = val;
+ }
+ }
+ return TRUE;
+}
+
+
+GLOBAL(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;
+ if ((ch1 != 'x' && ch1 != 'X') || ch2 != ',') /* syntax check */
+ return FALSE;
+ if (val1 <= 0 || val1 > 4 || val2 <= 0 || val2 > 4) {
+ fprintf(stderr, "JPEG sampling factors must be 1..4\n");
+ return FALSE;
+ }
+ cinfo->comp_info[ci].h_samp_factor = val1;
+ cinfo->comp_info[ci].v_samp_factor = val2;
+ while (*arg && *arg++ != ',') /* advance to next segment of arg string */
+ ;
+ } else {
+ /* reached end of parameter, set remaining components to 1x1 sampling */
+ cinfo->comp_info[ci].h_samp_factor = 1;
+ cinfo->comp_info[ci].v_samp_factor = 1;
+ }
+ }
+ return TRUE;
+}
+
+
+#ifdef C_LOSSLESS_SUPPORTED
+
+GLOBAL(boolean)
+set_simple_lossless (j_compress_ptr cinfo, char *arg)
+{
+ int pred, pt = 0;
+ char ch;
+
+ ch = ','; /* if not set by sscanf, will be ',' */
+ if (sscanf(arg, "%d%c", &pred, &ch) < 1)
+ return FALSE;
+ if (ch != ',') /* syntax check */
+ return FALSE;
+ while (*arg && *arg++ != ',') /* advance to next segment of arg string */
+ ;
+ if (*arg) {
+ if (sscanf(arg, "%d", &pt) != 1)
+ pt = 0;
+ }
+ jpeg_simple_lossless(cinfo, pred, pt);
+ return TRUE;
+}
+
+#endif /* C_LOSSLESS_SUPPORTED */
diff --git a/jpeg-6c/rdtarga.c b/jpeg-6c/rdtarga.c
new file mode 100644
index 0000000..4c2cd26
--- /dev/null
+++ b/jpeg-6c/rdtarga.c
@@ -0,0 +1,500 @@
+/*
+ * rdtarga.c
+ *
+ * Copyright (C) 1991-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to read input images in Targa format.
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications. As they stand, they assume input from
+ * an ordinary stdio stream. They further assume that reading begins
+ * at the start of the file; start_input may need work if the
+ * user interface has already read some data (e.g., to determine that
+ * the file is indeed Targa format).
+ *
+ * Based on code contributed by Lee Daniel Crocker.
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+
+#ifdef TARGA_SUPPORTED
+
+
+/* Macros to deal with unsigned chars as efficiently as compiler allows */
+
+#ifdef HAVE_UNSIGNED_CHAR
+typedef unsigned char U_CHAR;
+#define UCH(x) ((int) (x))
+#else /* !HAVE_UNSIGNED_CHAR */
+#ifdef CHAR_IS_UNSIGNED
+typedef char U_CHAR;
+#define UCH(x) ((int) (x))
+#else
+typedef char U_CHAR;
+#define UCH(x) ((int) (x) & 0xFF)
+#endif
+#endif /* HAVE_UNSIGNED_CHAR */
+
+
+#define ReadOK(file,buffer,len) (JFREAD(file,buffer,len) == ((size_t) (len)))
+
+
+/* Private version of data source object */
+
+typedef struct _tga_source_struct * tga_source_ptr;
+
+typedef struct _tga_source_struct {
+ struct cjpeg_source_struct pub; /* public fields */
+
+ j_compress_ptr cinfo; /* back link saves passing separate parm */
+
+ JSAMPARRAY colormap; /* Targa colormap (converted to my format) */
+
+ jvirt_sarray_ptr whole_image; /* Needed if funny input row order */
+ JDIMENSION current_row; /* Current logical row number to read */
+
+ /* Pointer to routine to extract next Targa pixel from input file */
+ JMETHOD(void, read_pixel, (tga_source_ptr sinfo));
+
+ /* Result of read_pixel is delivered here: */
+ U_CHAR tga_pixel[4];
+
+ int pixel_size; /* Bytes per Targa pixel (1 to 4) */
+
+ /* State info for reading RLE-coded pixels; both counts must be init to 0 */
+ int block_count; /* # of pixels remaining in RLE block */
+ int dup_pixel_count; /* # of times to duplicate previous pixel */
+
+ /* This saves the correct pixel-row-expansion method for preload_image */
+ JMETHOD(JDIMENSION, get_pixel_rows, (j_compress_ptr cinfo,
+ cjpeg_source_ptr sinfo));
+} tga_source_struct;
+
+
+/* For expanding 5-bit pixel values to 8-bit with best rounding */
+
+static const UINT8 c5to8bits[32] = {
+ 0, 8, 16, 25, 33, 41, 49, 58,
+ 66, 74, 82, 90, 99, 107, 115, 123,
+ 132, 140, 148, 156, 165, 173, 181, 189,
+ 197, 206, 214, 222, 230, 239, 247, 255
+};
+
+
+
+LOCAL(int)
+read_byte (tga_source_ptr sinfo)
+/* Read next byte from Targa file */
+{
+ register FILE *infile = sinfo->pub.input_file;
+ register int c;
+
+ if ((c = getc(infile)) == EOF)
+ ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
+ return c;
+}
+
+
+LOCAL(void)
+read_colormap (tga_source_ptr sinfo, int cmaplen, int mapentrysize)
+/* Read the colormap from a Targa file */
+{
+ int i;
+
+ /* Presently only handles 24-bit BGR format */
+ if (mapentrysize != 24)
+ ERREXIT(sinfo->cinfo, JERR_TGA_BADCMAP);
+
+ for (i = 0; i < cmaplen; i++) {
+ sinfo->colormap[2][i] = (JSAMPLE) read_byte(sinfo);
+ sinfo->colormap[1][i] = (JSAMPLE) read_byte(sinfo);
+ sinfo->colormap[0][i] = (JSAMPLE) read_byte(sinfo);
+ }
+}
+
+
+/*
+ * read_pixel methods: get a single pixel from Targa file into tga_pixel[]
+ */
+
+METHODDEF(void)
+read_non_rle_pixel (tga_source_ptr sinfo)
+/* Read one Targa pixel from the input file; no RLE expansion */
+{
+ register FILE *infile = sinfo->pub.input_file;
+ register int i;
+
+ for (i = 0; i < sinfo->pixel_size; i++) {
+ sinfo->tga_pixel[i] = (U_CHAR) getc(infile);
+ }
+}
+
+
+METHODDEF(void)
+read_rle_pixel (tga_source_ptr sinfo)
+/* Read one Targa pixel from the input file, expanding RLE data as needed */
+{
+ register FILE *infile = sinfo->pub.input_file;
+ register int i;
+
+ /* Duplicate previously read pixel? */
+ if (sinfo->dup_pixel_count > 0) {
+ sinfo->dup_pixel_count--;
+ return;
+ }
+
+ /* Time to read RLE block header? */
+ if (--sinfo->block_count < 0) { /* decrement pixels remaining in block */
+ i = read_byte(sinfo);
+ if (i & 0x80) { /* Start of duplicate-pixel block? */
+ sinfo->dup_pixel_count = i & 0x7F; /* number of dups after this one */
+ sinfo->block_count = 0; /* then read new block header */
+ } else {
+ sinfo->block_count = i & 0x7F; /* number of pixels after this one */
+ }
+ }
+
+ /* Read next pixel */
+ for (i = 0; i < sinfo->pixel_size; i++) {
+ sinfo->tga_pixel[i] = (U_CHAR) getc(infile);
+ }
+}
+
+
+/*
+ * Read one row of pixels.
+ *
+ * We provide several different versions depending on input file format.
+ */
+
+
+METHODDEF(JDIMENSION)
+get_8bit_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading 8-bit grayscale pixels */
+{
+ tga_source_ptr source = (tga_source_ptr) sinfo;
+ register JSAMPROW ptr;
+ register JDIMENSION col;
+
+ ptr = source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ (*source->read_pixel) (source); /* Load next pixel into tga_pixel */
+ *ptr++ = (JSAMPLE) UCH(source->tga_pixel[0]);
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_8bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading 8-bit colormap indexes */
+{
+ tga_source_ptr source = (tga_source_ptr) sinfo;
+ register int t;
+ register JSAMPROW ptr;
+ register JDIMENSION col;
+ register JSAMPARRAY colormap = source->colormap;
+
+ ptr = source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ (*source->read_pixel) (source); /* Load next pixel into tga_pixel */
+ t = UCH(source->tga_pixel[0]);
+ *ptr++ = colormap[0][t];
+ *ptr++ = colormap[1][t];
+ *ptr++ = colormap[2][t];
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_16bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading 16-bit pixels */
+{
+ tga_source_ptr source = (tga_source_ptr) sinfo;
+ register int t;
+ register JSAMPROW ptr;
+ register JDIMENSION col;
+
+ ptr = source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ (*source->read_pixel) (source); /* Load next pixel into tga_pixel */
+ t = UCH(source->tga_pixel[0]);
+ t += UCH(source->tga_pixel[1]) << 8;
+ /* We expand 5 bit data to 8 bit sample width.
+ * The format of the 16-bit (LSB first) input word is
+ * xRRRRRGGGGGBBBBB
+ */
+ ptr[2] = (JSAMPLE) c5to8bits[t & 0x1F];
+ t >>= 5;
+ ptr[1] = (JSAMPLE) c5to8bits[t & 0x1F];
+ t >>= 5;
+ ptr[0] = (JSAMPLE) c5to8bits[t & 0x1F];
+ ptr += 3;
+ }
+ return 1;
+}
+
+METHODDEF(JDIMENSION)
+get_24bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+/* This version is for reading 24-bit pixels */
+{
+ tga_source_ptr source = (tga_source_ptr) sinfo;
+ register JSAMPROW ptr;
+ register JDIMENSION col;
+
+ ptr = source->pub.buffer[0];
+ for (col = cinfo->image_width; col > 0; col--) {
+ (*source->read_pixel) (source); /* Load next pixel into tga_pixel */
+ *ptr++ = (JSAMPLE) UCH(source->tga_pixel[2]); /* change BGR to RGB order */
+ *ptr++ = (JSAMPLE) UCH(source->tga_pixel[1]);
+ *ptr++ = (JSAMPLE) UCH(source->tga_pixel[0]);
+ }
+ return 1;
+}
+
+/*
+ * Targa also defines a 32-bit pixel format with order B,G,R,A.
+ * We presently ignore the attribute byte, so the code for reading
+ * these pixels is identical to the 24-bit routine above.
+ * This works because the actual pixel length is only known to read_pixel.
+ */
+
+#define get_32bit_row get_24bit_row
+
+
+/*
+ * This method is for re-reading the input data in standard top-down
+ * row order. The entire image has already been read into whole_image
+ * with proper conversion of pixel format, but it's in a funny row order.
+ */
+
+METHODDEF(JDIMENSION)
+get_memory_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ tga_source_ptr source = (tga_source_ptr) sinfo;
+ JDIMENSION source_row;
+
+ /* Compute row of source that maps to current_row of normal order */
+ /* For now, assume image is bottom-up and not interlaced. */
+ /* NEEDS WORK to support interlaced images! */
+ source_row = cinfo->image_height - source->current_row - 1;
+
+ /* Fetch that row from virtual array */
+ source->pub.buffer = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, source->whole_image,
+ source_row, (JDIMENSION) 1, FALSE);
+
+ source->current_row++;
+ return 1;
+}
+
+
+/*
+ * This method loads the image into whole_image during the first call on
+ * get_pixel_rows. The get_pixel_rows pointer is then adjusted to call
+ * get_memory_row on subsequent calls.
+ */
+
+METHODDEF(JDIMENSION)
+preload_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ tga_source_ptr source = (tga_source_ptr) sinfo;
+ JDIMENSION row;
+ cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
+
+ /* Read the data into a virtual array in input-file row order. */
+ for (row = 0; row < cinfo->image_height; row++) {
+ if (progress != NULL) {
+ progress->pub.pass_counter = (long) row;
+ progress->pub.pass_limit = (long) cinfo->image_height;
+ (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
+ }
+ source->pub.buffer = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, source->whole_image, row, (JDIMENSION) 1, TRUE);
+ (*source->get_pixel_rows) (cinfo, sinfo);
+ }
+ if (progress != NULL)
+ progress->completed_extra_passes++;
+
+ /* Set up to read from the virtual array in unscrambled order */
+ source->pub.get_pixel_rows = get_memory_row;
+ source->current_row = 0;
+ /* And read the first row */
+ return get_memory_row(cinfo, sinfo);
+}
+
+
+/*
+ * Read the file header; return image size and component count.
+ */
+
+METHODDEF(void)
+start_input_tga (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ tga_source_ptr source = (tga_source_ptr) sinfo;
+ U_CHAR targaheader[18];
+ int idlen, cmaptype, subtype, flags, interlace_type, components;
+ unsigned int width, height, maplen;
+ boolean is_bottom_up;
+
+#define GET_2B(offset) ((unsigned int) UCH(targaheader[offset]) + \
+ (((unsigned int) UCH(targaheader[offset+1])) << 8))
+
+ if (! ReadOK(source->pub.input_file, targaheader, 18))
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+
+ /* Pretend "15-bit" pixels are 16-bit --- we ignore attribute bit anyway */
+ if (targaheader[16] == 15)
+ targaheader[16] = 16;
+
+ idlen = UCH(targaheader[0]);
+ cmaptype = UCH(targaheader[1]);
+ subtype = UCH(targaheader[2]);
+ maplen = GET_2B(5);
+ width = GET_2B(12);
+ height = GET_2B(14);
+ source->pixel_size = UCH(targaheader[16]) >> 3;
+ flags = UCH(targaheader[17]); /* Image Descriptor byte */
+
+ is_bottom_up = ((flags & 0x20) == 0); /* bit 5 set => top-down */
+ interlace_type = flags >> 6; /* bits 6/7 are interlace code */
+
+ if (cmaptype > 1 || /* cmaptype must be 0 or 1 */
+ source->pixel_size < 1 || source->pixel_size > 4 ||
+ (UCH(targaheader[16]) & 7) != 0 || /* bits/pixel must be multiple of 8 */
+ interlace_type != 0) /* currently don't allow interlaced image */
+ ERREXIT(cinfo, JERR_TGA_BADPARMS);
+
+ if (subtype > 8) {
+ /* It's an RLE-coded file */
+ source->read_pixel = read_rle_pixel;
+ source->block_count = source->dup_pixel_count = 0;
+ subtype -= 8;
+ } else {
+ /* Non-RLE file */
+ source->read_pixel = read_non_rle_pixel;
+ }
+
+ /* Now should have subtype 1, 2, or 3 */
+ components = 3; /* until proven different */
+ cinfo->in_color_space = JCS_RGB;
+
+ switch (subtype) {
+ case 1: /* Colormapped image */
+ if (source->pixel_size == 1 && cmaptype == 1)
+ source->get_pixel_rows = get_8bit_row;
+ else
+ ERREXIT(cinfo, JERR_TGA_BADPARMS);
+ TRACEMS2(cinfo, 1, JTRC_TGA_MAPPED, width, height);
+ break;
+ case 2: /* RGB image */
+ switch (source->pixel_size) {
+ case 2:
+ source->get_pixel_rows = get_16bit_row;
+ break;
+ case 3:
+ source->get_pixel_rows = get_24bit_row;
+ break;
+ case 4:
+ source->get_pixel_rows = get_32bit_row;
+ break;
+ default:
+ ERREXIT(cinfo, JERR_TGA_BADPARMS);
+ break;
+ }
+ TRACEMS2(cinfo, 1, JTRC_TGA, width, height);
+ break;
+ case 3: /* Grayscale image */
+ components = 1;
+ cinfo->in_color_space = JCS_GRAYSCALE;
+ if (source->pixel_size == 1)
+ source->get_pixel_rows = get_8bit_gray_row;
+ else
+ ERREXIT(cinfo, JERR_TGA_BADPARMS);
+ TRACEMS2(cinfo, 1, JTRC_TGA_GRAY, width, height);
+ break;
+ default:
+ ERREXIT(cinfo, JERR_TGA_BADPARMS);
+ break;
+ }
+
+ if (is_bottom_up) {
+ /* Create a virtual array to buffer the upside-down image. */
+ source->whole_image = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ (JDIMENSION) width * components, (JDIMENSION) height, (JDIMENSION) 1);
+ if (cinfo->progress != NULL) {
+ cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
+ progress->total_extra_passes++; /* count file input as separate pass */
+ }
+ /* source->pub.buffer will point to the virtual array. */
+ source->pub.buffer_height = 1; /* in case anyone looks at it */
+ source->pub.get_pixel_rows = preload_image;
+ } else {
+ /* Don't need a virtual array, but do need a one-row input buffer. */
+ source->whole_image = NULL;
+ source->pub.buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) width * components, (JDIMENSION) 1);
+ source->pub.buffer_height = 1;
+ source->pub.get_pixel_rows = source->get_pixel_rows;
+ }
+
+ while (idlen--) /* Throw away ID field */
+ (void) read_byte(source);
+
+ if (maplen > 0) {
+ if (maplen > 256 || GET_2B(3) != 0)
+ ERREXIT(cinfo, JERR_TGA_BADCMAP);
+ /* Allocate space to store the colormap */
+ source->colormap = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) maplen, (JDIMENSION) 3);
+ /* and read it from the file */
+ read_colormap(source, (int) maplen, UCH(targaheader[7]));
+ } else {
+ if (cmaptype) /* but you promised a cmap! */
+ ERREXIT(cinfo, JERR_TGA_BADPARMS);
+ source->colormap = NULL;
+ }
+
+ cinfo->input_components = components;
+ cinfo->data_precision = 8;
+ cinfo->image_width = width;
+ cinfo->image_height = height;
+}
+
+
+/*
+ * Finish up at the end of the file.
+ */
+
+METHODDEF(void)
+finish_input_tga (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
+{
+ /* no work */
+}
+
+
+/*
+ * The module selection routine for Targa format input.
+ */
+
+GLOBAL(cjpeg_source_ptr)
+jinit_read_targa (j_compress_ptr cinfo)
+{
+ tga_source_ptr source;
+
+ /* Create module interface object */
+ source = (tga_source_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(tga_source_struct));
+ source->cinfo = cinfo; /* make back link for subroutines */
+ /* Fill in method ptrs, except get_pixel_rows which start_input sets */
+ source->pub.start_input = start_input_tga;
+ source->pub.finish_input = finish_input_tga;
+
+ return (cjpeg_source_ptr) source;
+}
+
+#endif /* TARGA_SUPPORTED */
diff --git a/jpeg-6c/structure.doc b/jpeg-6c/structure.doc
new file mode 100644
index 0000000..3d62acc
--- /dev/null
+++ b/jpeg-6c/structure.doc
@@ -0,0 +1,1042 @@
+IJG JPEG LIBRARY: SYSTEM ARCHITECTURE
+
+Copyright (C) 1991-1995, Thomas G. Lane.
+This file is part of the Independent JPEG Group's software.
+For conditions of distribution and use, see the accompanying README file.
+
+
+This file provides an overview of the architecture of the IJG JPEG software;
+that is, the functions of the various modules in the system and the interfaces
+between modules. For more precise details about any data structure or calling
+convention, see the include files and comments in the source code.
+
+We assume that the reader is already somewhat familiar with the JPEG standard.
+The README file includes references for learning about JPEG. The file
+libjpeg.doc describes the library from the viewpoint of an application
+programmer using the library; it's best to read that file before this one.
+Also, the file coderules.doc describes the coding style conventions we use.
+
+In this document, JPEG-specific terminology follows the JPEG standard:
+ A "component" means a color channel, e.g., Red or Luminance.
+ A "sample" is a single component value (i.e., one number in the image data).
+ A "coefficient" is a frequency coefficient (a DCT transform output number).
+ A "block" is an 8x8 group of samples or coefficients.
+ A "data unit" is an abstract data type which is either a block for lossy
+ (DCT-based) codecs or a sample for lossless (predictive) codecs.
+ An "MCU" (minimum coded unit) is an interleaved set of data units of size
+ determined by the sampling factors, or a single data unit in a
+ noninterleaved scan.
+We do not use the terms "pixel" and "sample" interchangeably. When we say
+pixel, we mean an element of the full-size image, while a sample is an element
+of the downsampled image. Thus the number of samples may vary across
+components while the number of pixels does not. (This terminology is not used
+rigorously throughout the code, but it is used in places where confusion would
+otherwise result.)
+
+
+*** System features ***
+
+The IJG distribution contains two parts:
+ * A subroutine library for JPEG compression and decompression.
+ * cjpeg/djpeg, two sample applications that use the library to transform
+ JFIF JPEG files to and from several other image formats.
+cjpeg/djpeg are of no great intellectual complexity: they merely add a simple
+command-line user interface and I/O routines for several uncompressed image
+formats. This document concentrates on the library itself.
+
+We desire the library to be capable of supporting all JPEG baseline, extended
+sequential, and progressive DCT processes, as well as the lossless (spatial)
+process. Hierarchical processes are not supported.
+
+Within these limits, any set of compression parameters allowed by the JPEG
+spec should be readable for decompression. (We can be more restrictive about
+what formats we can generate.) Although the system design allows for all
+parameter values, some uncommon settings are not yet implemented and may
+never be; nonintegral sampling ratios are the prime example. Furthermore,
+we treat 8-bit vs. 12-bit data precision as a compile-time switch, not a
+run-time option, because most machines can store 8-bit pixels much more
+compactly than 12-bit.
+
+For legal reasons, JPEG arithmetic coding is not currently supported, but
+extending the library to include it would be straightforward.
+
+By itself, the library handles only interchange JPEG datastreams --- in
+particular the widely used JFIF file format. The library can be used by
+surrounding code to process interchange or abbreviated JPEG datastreams that
+are embedded in more complex file formats. (For example, libtiff uses this
+library to implement JPEG compression within the TIFF file format.)
+
+The library includes a substantial amount of code that is not covered by the
+JPEG standard but is necessary for typical applications of JPEG. These
+functions preprocess the image before JPEG compression or postprocess it after
+decompression. They include colorspace conversion, downsampling/upsampling,
+and color quantization. This code can be omitted if not needed.
+
+A wide range of quality vs. speed tradeoffs are possible in JPEG processing,
+and even more so in decompression postprocessing. The decompression library
+provides multiple implementations that cover most of the useful tradeoffs,
+ranging from very-high-quality down to fast-preview operation. On the
+compression side we have generally not provided low-quality choices, since
+compression is normally less time-critical. It should be understood that the
+low-quality modes may not meet the JPEG standard's accuracy requirements;
+nonetheless, they are useful for viewers.
+
+
+*** Portability issues ***
+
+Portability is an essential requirement for the library. The key portability
+issues that show up at the level of system architecture are:
+
+1. Memory usage. We want the code to be able to run on PC-class machines
+with limited memory. Images should therefore be processed sequentially (in
+strips), to avoid holding the whole image in memory at once. Where a
+full-image buffer is necessary, we should be able to use either virtual memory
+or temporary files.
+
+2. Near/far pointer distinction. To run efficiently on 80x86 machines, the
+code should distinguish "small" objects (kept in near data space) from
+"large" ones (kept in far data space). This is an annoying restriction, but
+fortunately it does not impact code quality for less brain-damaged machines,
+and the source code clutter turns out to be minimal with sufficient use of
+pointer typedefs.
+
+3. Data precision. We assume that "char" is at least 8 bits, "short" and
+"int" at least 16, "long" at least 32. The code will work fine with larger
+data sizes, although memory may be used inefficiently in some cases. However,
+the JPEG compressed datastream must ultimately appear on external storage as a
+sequence of 8-bit bytes if it is to conform to the standard. This may pose a
+problem on machines where char is wider than 8 bits. The library represents
+compressed data as an array of values of typedef JOCTET. If no data type
+exactly 8 bits wide is available, custom data source and data destination
+modules must be written to unpack and pack the chosen JOCTET datatype into
+8-bit external representation.
+
+
+*** System overview ***
+
+The compressor and decompressor are each divided into two main sections:
+the JPEG compressor or decompressor proper, and the preprocessing or
+postprocessing functions. The interface between these two sections is the
+image data that the official JPEG spec regards as its input or output: this
+data is in the colorspace to be used for compression, and it is downsampled
+to the sampling factors to be used. The preprocessing and postprocessing
+steps are responsible for converting a normal image representation to or from
+this form. (Those few applications that want to deal with YCbCr downsampled
+data can skip the preprocessing or postprocessing step.)
+
+Looking more closely, the compressor library contains the following main
+elements:
+
+ Preprocessing:
+ * Color space conversion (e.g., RGB to YCbCr).
+ * Edge expansion and downsampling. Optionally, this step can do simple
+ smoothing --- this is often helpful for low-quality source data.
+ Lossy JPEG proper:
+ * MCU assembly, DCT, quantization.
+ * Entropy coding (sequential or progressive, Huffman or arithmetic).
+ Lossless JPEG proper:
+ * Point transform.
+ * Prediction, differencing.
+ * Entropy coding (Huffman or arithmetic)
+
+In addition to these modules we need overall control, marker generation,
+and support code (memory management & error handling). There is also a
+module responsible for physically writing the output data --- typically
+this is just an interface to fwrite(), but some applications may need to
+do something else with the data.
+
+The decompressor library contains the following main elements:
+
+ Lossy JPEG proper:
+ * Entropy decoding (sequential or progressive, Huffman or arithmetic).
+ * Dequantization, inverse DCT, MCU disassembly.
+ Lossless JPEG proper:
+ * Entropy decoding (Huffman or arithmetic).
+ * Prediction, undifferencing.
+ * Point transform, sample size scaling.
+ Postprocessing:
+ * Upsampling. Optionally, this step may be able to do more general
+ rescaling of the image.
+ * Color space conversion (e.g., YCbCr to RGB). This step may also
+ provide gamma adjustment [ currently it does not ].
+ * Optional color quantization (e.g., reduction to 256 colors).
+ * Optional color precision reduction (e.g., 24-bit to 15-bit color).
+ [This feature is not currently implemented.]
+
+We also need overall control, marker parsing, and a data source module.
+The support code (memory management & error handling) can be shared with
+the compression half of the library.
+
+There may be several implementations of each of these elements, particularly
+in the decompressor, where a wide range of speed/quality tradeoffs is very
+useful. It must be understood that some of the best speedups involve
+merging adjacent steps in the pipeline. For example, upsampling, color space
+conversion, and color quantization might all be done at once when using a
+low-quality ordered-dither technique. The system architecture is designed to
+allow such merging where appropriate.
+
+
+Note: it is convenient to regard edge expansion (padding to block boundaries)
+as a preprocessing/postprocessing function, even though the JPEG spec includes
+it in compression/decompression. We do this because downsampling/upsampling
+can be simplified a little if they work on padded data: it's not necessary to
+have special cases at the right and bottom edges. Therefore the interface
+buffer is always an integral number of blocks wide and high, and we expect
+compression preprocessing to pad the source data properly. Padding will occur
+only to the next block (8-sample) boundary. In an interleaved-scan situation,
+additional dummy blocks may be used to fill out MCUs, but the MCU assembly and
+disassembly logic will create or discard these blocks internally. (This is
+advantageous for speed reasons, since we avoid DCTing the dummy blocks.
+It also permits a small reduction in file size, because the compressor can
+choose dummy block contents so as to minimize their size in compressed form.
+Finally, it makes the interface buffer specification independent of whether
+the file is actually interleaved or not.) Applications that wish to deal
+directly with the downsampled data must provide similar buffering and padding
+for odd-sized images.
+
+
+*** Poor man's object-oriented programming ***
+
+It should be clear by now that we have a lot of quasi-independent processing
+steps, many of which have several possible behaviors. To avoid cluttering the
+code with lots of switch statements, we use a simple form of object-style
+programming to separate out the different possibilities.
+
+For example, two different color quantization algorithms could be implemented
+as two separate modules that present the same external interface; at runtime,
+the calling code will access the proper module indirectly through an "object".
+
+We can get the limited features we need while staying within portable C.
+The basic tool is a function pointer. An "object" is just a struct
+containing one or more function pointer fields, each of which corresponds to
+a method name in real object-oriented languages. During initialization we
+fill in the function pointers with references to whichever module we have
+determined we need to use in this run. Then invocation of the module is done
+by indirecting through a function pointer; on most machines this is no more
+expensive than a switch statement, which would be the only other way of
+making the required run-time choice. The really significant benefit, of
+course, is keeping the source code clean and well structured.
+
+We can also arrange to have private storage that varies between different
+implementations of the same kind of object. We do this by making all the
+module-specific object structs be separately allocated entities, which will
+be accessed via pointers in the master compression or decompression struct.
+The "public" fields or methods for a given kind of object are specified by
+a commonly known struct. But a module's initialization code can allocate
+a larger struct that contains the common struct as its first member, plus
+additional private fields. With appropriate pointer casting, the module's
+internal functions can access these private fields. (For a simple example,
+see jdatadst.c, which implements the external interface specified by struct
+jpeg_destination_mgr, but adds extra fields.)
+
+(Of course this would all be a lot easier if we were using C++, but we are
+not yet prepared to assume that everyone has a C++ compiler.)
+
+An important benefit of this scheme is that it is easy to provide multiple
+versions of any method, each tuned to a particular case. While a lot of
+precalculation might be done to select an optimal implementation of a method,
+the cost per invocation is constant. For example, the upsampling step might
+have a "generic" method, plus one or more "hardwired" methods for the most
+popular sampling factors; the hardwired methods would be faster because they'd
+use straight-line code instead of for-loops. The cost to determine which
+method to use is paid only once, at startup, and the selection criteria are
+hidden from the callers of the method.
+
+This plan differs a little bit from usual object-oriented structures, in that
+only one instance of each object class will exist during execution. The
+reason for having the class structure is that on different runs we may create
+different instances (choose to execute different modules). You can think of
+the term "method" as denoting the common interface presented by a particular
+set of interchangeable functions, and "object" as denoting a group of related
+methods, or the total shared interface behavior of a group of modules.
+
+
+*** Overall control structure ***
+
+We previously mentioned the need for overall control logic in the compression
+and decompression libraries. In IJG implementations prior to v5, overall
+control was mostly provided by "pipeline control" modules, which proved to be
+large, unwieldy, and hard to understand. To improve the situation, the
+control logic has been subdivided into multiple modules. The control modules
+consist of:
+
+1. Master control for module selection and initialization. This has two
+responsibilities:
+
+ 1A. Startup initialization at the beginning of image processing.
+ The individual processing modules to be used in this run are selected
+ and given initialization calls.
+
+ 1B. Per-pass control. This determines how many passes will be performed
+ and calls each active processing module to configure itself
+ appropriately at the beginning of each pass. End-of-pass processing,
+ where necessary, is also invoked from the master control module.
+
+ Method selection is partially distributed, in that a particular processing
+ module may contain several possible implementations of a particular method,
+ which it will select among when given its initialization call. The master
+ control code need only be concerned with decisions that affect more than
+ one module.
+
+2. Data buffering control. A separate control module exists for each
+ inter-processing-step data buffer. This module is responsible for
+ invoking the processing steps that write or read that data buffer.
+
+Each buffer controller sees the world as follows:
+
+input data => processing step A => buffer => processing step B => output data
+ | | |
+ ------------------ controller ------------------
+
+The controller knows the dataflow requirements of steps A and B: how much data
+they want to accept in one chunk and how much they output in one chunk. Its
+function is to manage its buffer and call A and B at the proper times.
+
+A data buffer control module may itself be viewed as a processing step by a
+higher-level control module; thus the control modules form a binary tree with
+elementary processing steps at the leaves of the tree.
+
+The control modules are objects. A considerable amount of flexibility can
+be had by replacing implementations of a control module. For example:
+* Merging of adjacent steps in the pipeline is done by replacing a control
+ module and its pair of processing-step modules with a single processing-
+ step module. (Hence the possible merges are determined by the tree of
+ control modules.)
+* In some processing modes, a given interstep buffer need only be a "strip"
+ buffer large enough to accommodate the desired data chunk sizes. In other
+ modes, a full-image buffer is needed and several passes are required.
+ The control module determines which kind of buffer is used and manipulates
+ virtual array buffers as needed. One or both processing steps may be
+ unaware of the multi-pass behavior.
+
+In theory, we might be able to make all of the data buffer controllers
+interchangeable and provide just one set of implementations for all. In
+practice, each one contains considerable special-case processing for its
+particular job. The buffer controller concept should be regarded as an
+overall system structuring principle, not as a complete description of the
+task performed by any one controller.
+
+
+*** Codec object structure ***
+
+As noted above, this library supports both the lossy (DCT-based) and lossless
+JPEG processes. Because these processes have little in common with one another
+(and their implementations share very little code), we need to provide a way to
+isloate the underlying JPEG process from the rest of the library. This is
+accomplished by introducing an abstract "codec object" which acts a generic
+interface to the JPEG (de)compressor proper.
+
+Using the power of the object-oriented scheme described above, we build the
+lossy and lossless modules as two separate implementations of the codec object.
+Switching between lossy and lossless processes then becomes as trivial as
+assigning the appropriate method pointers during initialization of the library.
+
+
+*** Compression object structure ***
+
+Here is a sketch of the logical structure of the JPEG compression library:
+
+ |-- Colorspace conversion
+ |-- Preprocessing controller --|
+ | |-- Downsampling
+ |
+Main controller --|
+ | /--> Lossy codec
+ | /
+ |-- Compression codec < *OR*
+ \
+ \--> Lossless codec
+
+
+where the lossy codec looks like:
+
+ |-- Forward DCT, quantize
+<-- Coefficient controller --|
+ |-- Entropy encoding
+
+
+and the lossless codec looks like:
+
+ |-- Point transformation
+ |
+<-- Difference controller --|-- Prediction, differencing
+ |
+ |-- Lossless entropy encoding
+
+
+This sketch also describes the flow of control (subroutine calls) during
+typical image data processing. Each of the components shown in the diagram is
+an "object" which may have several different implementations available. One
+or more source code files contain the actual implementation(s) of each object.
+
+The objects shown above are:
+
+* Main controller: buffer controller for the subsampled-data buffer, which
+ holds the preprocessed input data. This controller invokes preprocessing to
+ fill the subsampled-data buffer, and JPEG compression to empty it. There is
+ usually no need for a full-image buffer here; a strip buffer is adequate.
+
+* Preprocessing controller: buffer controller for the downsampling input data
+ buffer, which lies between colorspace conversion and downsampling. Note
+ that a unified conversion/downsampling module would probably replace this
+ controller entirely.
+
+* Colorspace conversion: converts application image data into the desired
+ JPEG color space; also changes the data from pixel-interleaved layout to
+ separate component planes. Processes one pixel row at a time.
+
+* Downsampling: performs reduction of chroma components as required.
+ Optionally may perform pixel-level smoothing as well. Processes a "row
+ group" at a time, where a row group is defined as Vmax pixel rows of each
+ component before downsampling, and Vk sample rows afterwards (remember Vk
+ differs across components). Some downsampling or smoothing algorithms may
+ require context rows above and below the current row group; the
+ preprocessing controller is responsible for supplying these rows via proper
+ buffering. The downsampler is responsible for edge expansion at the right
+ edge (i.e., extending each sample row to a multiple of 8 samples); but the
+ preprocessing controller is responsible for vertical edge expansion (i.e.,
+ duplicating the bottom sample row as needed to make a multiple of 8 rows).
+
+* Coefficient controller: buffer controller for the DCT-coefficient data.
+ This controller handles MCU assembly, including insertion of dummy DCT
+ blocks when needed at the right or bottom edge. When performing
+ Huffman-code optimization or emitting a multiscan JPEG file, this
+ controller is responsible for buffering the full image. The equivalent of
+ one fully interleaved MCU row of subsampled data is processed per call,
+ even when the JPEG file is noninterleaved.
+
+* Forward DCT and quantization: Perform DCT, quantize, and emit coefficients.
+ Works on one or more DCT blocks at a time. (Note: the coefficients are now
+ emitted in normal array order, which the entropy encoder is expected to
+ convert to zigzag order as necessary. Prior versions of the IJG code did
+ the conversion to zigzag order within the quantization step.)
+
+* Entropy encoding: Perform Huffman or arithmetic entropy coding and emit the
+ coded data to the data destination module. Works on one MCU per call.
+ For progressive JPEG, the same DCT blocks are fed to the entropy coder
+ during each pass, and the coder must emit the appropriate subset of
+ coefficients.
+
+* Difference controller: buffer controller for the spatial difference data.
+ When emitting a multiscan JPEG file, this controller is responsible for
+ buffering the full image. The equivalent of one fully interleaved MCU row
+ of subsampled data is processed per call, even when the JPEG file is
+ noninterleaved.
+
+* Point transformation: Scale the data down by the point transformation
+ parameter.
+
+* Prediction and differencing: Calculate the predictor and subtract it
+ from the input. Works on one scanline per call. The difference
+ controller supplies the prior scanline which is used for prediction.
+
+* Lossless entropy encoding: Perform Huffman or arithmetic entropy coding and
+ emit the coded data to the data destination module. This module handles MCU
+ assembly. Works on one MCU-row per call.
+
+In addition to the above objects, the compression library includes these
+objects:
+
+* Master control: determines the number of passes required, controls overall
+ and per-pass initialization of the other modules.
+
+* Marker writing: generates JPEG markers (except for RSTn, which is emitted
+ by the entropy encoder when needed).
+
+* Data destination manager: writes the output JPEG datastream to its final
+ destination (e.g., a file). The destination manager supplied with the
+ library knows how to write to a stdio stream; for other behaviors, the
+ surrounding application may provide its own destination manager.
+
+* Memory manager: allocates and releases memory, controls virtual arrays
+ (with backing store management, where required).
+
+* Error handler: performs formatting and output of error and trace messages;
+ determines handling of nonfatal errors. The surrounding application may
+ override some or all of this object's methods to change error handling.
+
+* Progress monitor: supports output of "percent-done" progress reports.
+ This object represents an optional callback to the surrounding application:
+ if wanted, it must be supplied by the application.
+
+The error handler, destination manager, and progress monitor objects are
+defined as separate objects in order to simplify application-specific
+customization of the JPEG library. A surrounding application may override
+individual methods or supply its own all-new implementation of one of these
+objects. The object interfaces for these objects are therefore treated as
+part of the application interface of the library, whereas the other objects
+are internal to the library.
+
+The error handler and memory manager are shared by JPEG compression and
+decompression; the progress monitor, if used, may be shared as well.
+
+
+*** Decompression object structure ***
+
+Here is a sketch of the logical structure of the JPEG decompression library:
+
+ /--> Lossy codec
+ /
+ |-- Decompression codec < *OR*
+ | \
+ | \--> Lossless codec
+Main controller --|
+ |
+ | |-- Upsampling
+ |-- Postprocessing controller --| |-- Colorspace conversion
+ |-- Color quantization
+ |-- Color precision reduction
+
+
+where the lossy codec looks like:
+
+ |-- Entropy decoding
+<-- Coefficient controller --|
+ |-- Dequantize, Inverse DCT
+
+
+and the lossless codec looks like:
+
+ |-- Lossless entropy decoding
+ |
+<-- Difference controller --|-- Prediction, undifferencing
+ |
+ |-- Point transformation, sample size scaling
+
+
+As before, this diagram also represents typical control flow. The objects
+shown are:
+
+* Main controller: buffer controller for the subsampled-data buffer, which
+ holds the output of JPEG decompression proper. This controller's primary
+ task is to feed the postprocessing procedure. Some upsampling algorithms
+ may require context rows above and below the current row group; when this
+ is true, the main controller is responsible for managing its buffer so as
+ to make context rows available. In the current design, the main buffer is
+ always a strip buffer; a full-image buffer is never required.
+
+* Coefficient controller: buffer controller for the DCT-coefficient data.
+ This controller handles MCU disassembly, including deletion of any dummy
+ DCT blocks at the right or bottom edge. When reading a multiscan JPEG
+ file, this controller is responsible for buffering the full image.
+ (Buffering DCT coefficients, rather than samples, is necessary to support
+ progressive JPEG.) The equivalent of one fully interleaved MCU row of
+ subsampled data is processed per call, even when the source JPEG file is
+ noninterleaved.
+
+* Entropy decoding: Read coded data from the data source module and perform
+ Huffman or arithmetic entropy decoding. Works on one MCU per call.
+ For progressive JPEG decoding, the coefficient controller supplies the prior
+ coefficients of each MCU (initially all zeroes), which the entropy decoder
+ modifies in each scan.
+
+* Dequantization and inverse DCT: like it says. Note that the coefficients
+ buffered by the coefficient controller have NOT been dequantized; we
+ merge dequantization and inverse DCT into a single step for speed reasons.
+ When scaled-down output is asked for, simplified DCT algorithms may be used
+ that emit only 1x1, 2x2, or 4x4 samples per DCT block, not the full 8x8.
+ Works on one DCT block at a time.
+
+* Difference controller: buffer controller for the spatial difference data.
+ When reading a multiscan JPEG file, this controller is responsible for
+ buffering the full image. The equivalent of one fully interleaved MCU row
+ is processed per call, even when the source JPEG file is noninterleaved.
+
+* Lossless entropy decoding: Read coded data from the data source module and
+ perform Huffman or arithmetic entropy decoding. Works on one MCU-row per
+ call.
+
+* Prediction and undifferencing: Calculate the predictor and add it to the
+ decoded difference. Works on one scanline per call. The difference
+ controller supplies the prior scanline which is used for prediction.
+
+* Point transform and sample size scaling: Scale the data up by the point
+ transformation parameter and scale it down to fit into the compiled-in
+ sample size.
+
+* Postprocessing controller: buffer controller for the color quantization
+ input buffer, when quantization is in use. (Without quantization, this
+ controller just calls the upsampler.) For two-pass quantization, this
+ controller is responsible for buffering the full-image data.
+
+* Upsampling: restores chroma components to full size. (May support more
+ general output rescaling, too. Note that if undersized DCT outputs have
+ been emitted by the DCT module, this module must adjust so that properly
+ sized outputs are created.) Works on one row group at a time. This module
+ also calls the color conversion module, so its top level is effectively a
+ buffer controller for the upsampling->color conversion buffer. However, in
+ all but the highest-quality operating modes, upsampling and color
+ conversion are likely to be merged into a single step.
+
+* Colorspace conversion: convert from JPEG color space to output color space,
+ and change data layout from separate component planes to pixel-interleaved.
+ Works on one pixel row at a time.
+
+* Color quantization: reduce the data to colormapped form, using either an
+ externally specified colormap or an internally generated one. This module
+ is not used for full-color output. Works on one pixel row at a time; may
+ require two passes to generate a color map. Note that the output will
+ always be a single component representing colormap indexes. In the current
+ design, the output values are JSAMPLEs, so an 8-bit compilation cannot
+ quantize to more than 256 colors. This is unlikely to be a problem in
+ practice.
+
+* Color reduction: this module handles color precision reduction, e.g.,
+ generating 15-bit color (5 bits/primary) from JPEG's 24-bit output.
+ Not quite clear yet how this should be handled... should we merge it with
+ colorspace conversion???
+
+Note that some high-speed operating modes might condense the entire
+postprocessing sequence to a single module (upsample, color convert, and
+quantize in one step).
+
+In addition to the above objects, the decompression library includes these
+objects:
+
+* Master control: determines the number of passes required, controls overall
+ and per-pass initialization of the other modules. This is subdivided into
+ input and output control: jdinput.c controls only input-side processing,
+ while jdmaster.c handles overall initialization and output-side control.
+
+* Marker reading: decodes JPEG markers (except for RSTn).
+
+* Data source manager: supplies the input JPEG datastream. The source
+ manager supplied with the library knows how to read from a stdio stream;
+ for other behaviors, the surrounding application may provide its own source
+ manager.
+
+* Memory manager: same as for compression library.
+
+* Error handler: same as for compression library.
+
+* Progress monitor: same as for compression library.
+
+As with compression, the data source manager, error handler, and progress
+monitor are candidates for replacement by a surrounding application.
+
+
+*** Decompression input and output separation ***
+
+To support efficient incremental display of progressive JPEG files, the
+decompressor is divided into two sections that can run independently:
+
+1. Data input includes marker parsing, entropy decoding, and input into the
+ coefficient controller's DCT coefficient buffer. Note that this
+ processing is relatively cheap and fast.
+
+2. Data output reads from the DCT coefficient buffer and performs the IDCT
+ and all postprocessing steps.
+
+For a progressive JPEG file, the data input processing is allowed to get
+arbitrarily far ahead of the data output processing. (This occurs only
+if the application calls jpeg_consume_input(); otherwise input and output
+run in lockstep, since the input section is called only when the output
+section needs more data.) In this way the application can avoid making
+extra display passes when data is arriving faster than the display pass
+can run. Furthermore, it is possible to abort an output pass without
+losing anything, since the coefficient buffer is read-only as far as the
+output section is concerned. See libjpeg.doc for more detail.
+
+A full-image coefficient array is only created if the JPEG file has multiple
+scans (or if the application specifies buffered-image mode anyway). When
+reading a single-scan file, the coefficient controller normally creates only
+a one-MCU buffer, so input and output processing must run in lockstep in this
+case. jpeg_consume_input() is effectively a no-op in this situation.
+
+The main impact of dividing the decompressor in this fashion is that we must
+be very careful with shared variables in the cinfo data structure. Each
+variable that can change during the course of decompression must be
+classified as belonging to data input or data output, and each section must
+look only at its own variables. For example, the data output section may not
+depend on any of the variables that describe the current scan in the JPEG
+file, because these may change as the data input section advances into a new
+scan.
+
+The progress monitor is (somewhat arbitrarily) defined to treat input of the
+file as one pass when buffered-image mode is not used, and to ignore data
+input work completely when buffered-image mode is used. Note that the
+library has no reliable way to predict the number of passes when dealing
+with a progressive JPEG file, nor can it predict the number of output passes
+in buffered-image mode. So the work estimate is inherently bogus anyway.
+
+No comparable division is currently made in the compression library, because
+there isn't any real need for it.
+
+
+*** Data formats ***
+
+Arrays of pixel sample values use the following data structure:
+
+ typedef something JSAMPLE; a pixel component value, 0..MAXJSAMPLE
+ typedef JSAMPLE *JSAMPROW; ptr to a row of samples
+ typedef JSAMPROW *JSAMPARRAY; ptr to a list of rows
+ typedef JSAMPARRAY *JSAMPIMAGE; ptr to a list of color-component arrays
+
+The basic element type JSAMPLE will typically be one of unsigned char,
+(signed) char, or short. Short will be used if samples wider than 8 bits are
+to be supported (this is a compile-time option). Otherwise, unsigned char is
+used if possible. If the compiler only supports signed chars, then it is
+necessary to mask off the value when reading. Thus, all reads of JSAMPLE
+values must be coded as "GETJSAMPLE(value)", where the macro will be defined
+as "((value) & 0xFF)" on signed-char machines and "((int) (value))" elsewhere.
+
+With these conventions, JSAMPLE values can be assumed to be >= 0. This helps
+simplify correct rounding during downsampling, etc. The JPEG standard's
+specification that sample values run from -128..127 is accommodated by
+subtracting 128 just as the sample value is copied into the source array for
+the DCT step (this will be an array of signed ints). Similarly, during
+decompression the output of the IDCT step will be immediately shifted back to
+0..255. (NB: different values are required when 12-bit samples are in use.
+The code is written in terms of MAXJSAMPLE and CENTERJSAMPLE, which will be
+defined as 255 and 128 respectively in an 8-bit implementation, and as 4095
+and 2048 in a 12-bit implementation.)
+
+We use a pointer per row, rather than a two-dimensional JSAMPLE array. This
+choice costs only a small amount of memory and has several benefits:
+* Code using the data structure doesn't need to know the allocated width of
+ the rows. This simplifies edge expansion/compression, since we can work
+ in an array that's wider than the logical picture width.
+* Indexing doesn't require multiplication; this is a performance win on many
+ machines.
+* Arrays with more than 64K total elements can be supported even on machines
+ where malloc() cannot allocate chunks larger than 64K.
+* The rows forming a component array may be allocated at different times
+ without extra copying. This trick allows some speedups in smoothing steps
+ that need access to the previous and next rows.
+
+Note that each color component is stored in a separate array; we don't use the
+traditional layout in which the components of a pixel are stored together.
+This simplifies coding of modules that work on each component independently,
+because they don't need to know how many components there are. Furthermore,
+we can read or write each component to a temporary file independently, which
+is helpful when dealing with noninterleaved JPEG files.
+
+In general, a specific sample value is accessed by code such as
+ GETJSAMPLE(image[colorcomponent][row][col])
+where col is measured from the image left edge, but row is measured from the
+first sample row currently in memory. Either of the first two indexings can
+be precomputed by copying the relevant pointer.
+
+
+Since most image-processing applications prefer to work on images in which
+the components of a pixel are stored together, the data passed to or from the
+surrounding application uses the traditional convention: a single pixel is
+represented by N consecutive JSAMPLE values, and an image row is an array of
+(# of color components)*(image width) JSAMPLEs. One or more rows of data can
+be represented by a pointer of type JSAMPARRAY in this scheme. This scheme is
+converted to component-wise storage inside the JPEG library. (Applications
+that want to skip JPEG preprocessing or postprocessing will have to contend
+with component-wise storage.)
+
+
+Arrays of DCT-coefficient values use the following data structure:
+
+ typedef short JCOEF; a 16-bit signed integer
+ typedef JCOEF JBLOCK[DCTSIZE2]; an 8x8 block of coefficients
+ typedef JBLOCK *JBLOCKROW; ptr to one horizontal row of 8x8 blocks
+ typedef JBLOCKROW *JBLOCKARRAY; ptr to a list of such rows
+ typedef JBLOCKARRAY *JBLOCKIMAGE; ptr to a list of color component arrays
+
+The underlying type is at least a 16-bit signed integer; while "short" is big
+enough on all machines of interest, on some machines it is preferable to use
+"int" for speed reasons, despite the storage cost. Coefficients are grouped
+into 8x8 blocks (but we always use #defines DCTSIZE and DCTSIZE2 rather than
+"8" and "64").
+
+The contents of a coefficient block may be in either "natural" or zigzagged
+order, and may be true values or divided by the quantization coefficients,
+depending on where the block is in the processing pipeline. In the current
+library, coefficient blocks are kept in natural order everywhere; the entropy
+codecs zigzag or dezigzag the data as it is written or read. The blocks
+contain quantized coefficients everywhere outside the DCT/IDCT subsystems.
+(This latter decision may need to be revisited to support variable
+quantization a la JPEG Part 3.)
+
+Notice that the allocation unit is now a row of 8x8 blocks, corresponding to
+eight rows of samples. Otherwise the structure is much the same as for
+samples, and for the same reasons.
+
+On machines where malloc() can't handle a request bigger than 64Kb, this data
+structure limits us to rows of less than 512 JBLOCKs, or a picture width of
+4000+ pixels. This seems an acceptable restriction.
+
+
+On 80x86 machines, the bottom-level pointer types (JSAMPROW and JBLOCKROW)
+must be declared as "far" pointers, but the upper levels can be "near"
+(implying that the pointer lists are allocated in the DS segment).
+We use a #define symbol FAR, which expands to the "far" keyword when
+compiling on 80x86 machines and to nothing elsewhere.
+
+
+*** Suspendable processing ***
+
+In some applications it is desirable to use the JPEG library as an
+incremental, memory-to-memory filter. In this situation the data source or
+destination may be a limited-size buffer, and we can't rely on being able to
+empty or refill the buffer at arbitrary times. Instead the application would
+like to have control return from the library at buffer overflow/underrun, and
+then resume compression or decompression at a later time.
+
+This scenario is supported for simple cases. (For anything more complex, we
+recommend that the application "bite the bullet" and develop real multitasking
+capability.) The libjpeg.doc file goes into more detail about the usage and
+limitations of this capability; here we address the implications for library
+structure.
+
+The essence of the problem is that the entropy codec (coder or decoder) must
+be prepared to stop at arbitrary times. In turn, the controllers that call
+the entropy codec must be able to stop before having produced or consumed all
+the data that they normally would handle in one call. That part is reasonably
+straightforward: we make the controller call interfaces include "progress
+counters" which indicate the number of data chunks successfully processed, and
+we require callers to test the counter rather than just assume all of the data
+was processed.
+
+Rather than trying to restart at an arbitrary point, the current Huffman
+codecs are designed to restart at the beginning of the current MCU after a
+suspension due to buffer overflow/underrun. At the start of each call, the
+codec's internal state is loaded from permanent storage (in the JPEG object
+structures) into local variables. On successful completion of the MCU, the
+permanent state is updated. (This copying is not very expensive, and may even
+lead to *improved* performance if the local variables can be registerized.)
+If a suspension occurs, the codec simply returns without updating the state,
+thus effectively reverting to the start of the MCU. Note that this implies
+leaving some data unprocessed in the source/destination buffer (ie, the
+compressed partial MCU). The data source/destination module interfaces are
+specified so as to make this possible. This also implies that the data buffer
+must be large enough to hold a worst-case compressed MCU; a couple thousand
+bytes should be enough.
+
+In a successive-approximation AC refinement scan, the progressive Huffman
+decoder has to be able to undo assignments of newly nonzero coefficients if it
+suspends before the MCU is complete, since decoding requires distinguishing
+previously-zero and previously-nonzero coefficients. This is a bit tedious
+but probably won't have much effect on performance. Other variants of Huffman
+decoding need not worry about this, since they will just store the same values
+again if forced to repeat the MCU.
+
+This approach would probably not work for an arithmetic codec, since its
+modifiable state is quite large and couldn't be copied cheaply. Instead it
+would have to suspend and resume exactly at the point of the buffer end.
+
+The JPEG marker reader is designed to cope with suspension at an arbitrary
+point. It does so by backing up to the start of the marker parameter segment,
+so the data buffer must be big enough to hold the largest marker of interest.
+Again, a couple KB should be adequate. (A special "skip" convention is used
+to bypass COM and APPn markers, so these can be larger than the buffer size
+without causing problems; otherwise a 64K buffer would be needed in the worst
+case.)
+
+The JPEG marker writer currently does *not* cope with suspension. I feel that
+this is not necessary; it is much easier simply to require the application to
+ensure there is enough buffer space before starting. (An empty 2K buffer is
+more than sufficient for the header markers; and ensuring there are a dozen or
+two bytes available before calling jpeg_finish_compress() will suffice for the
+trailer.) This would not work for writing multi-scan JPEG files, but
+we simply do not intend to support that capability with suspension.
+
+
+*** Memory manager services ***
+
+The JPEG library's memory manager controls allocation and deallocation of
+memory, and it manages large "virtual" data arrays on machines where the
+operating system does not provide virtual memory. Note that the same
+memory manager serves both compression and decompression operations.
+
+In all cases, allocated objects are tied to a particular compression or
+decompression master record, and they will be released when that master
+record is destroyed.
+
+The memory manager does not provide explicit deallocation of objects.
+Instead, objects are created in "pools" of free storage, and a whole pool
+can be freed at once. This approach helps prevent storage-leak bugs, and
+it speeds up operations whenever malloc/free are slow (as they often are).
+The pools can be regarded as lifetime identifiers for objects. Two
+pools/lifetimes are defined:
+ * JPOOL_PERMANENT lasts until master record is destroyed
+ * JPOOL_IMAGE lasts until done with image (JPEG datastream)
+Permanent lifetime is used for parameters and tables that should be carried
+across from one datastream to another; this includes all application-visible
+parameters. Image lifetime is used for everything else. (A third lifetime,
+JPOOL_PASS = one processing pass, was originally planned. However it was
+dropped as not being worthwhile. The actual usage patterns are such that the
+peak memory usage would be about the same anyway; and having per-pass storage
+substantially complicates the virtual memory allocation rules --- see below.)
+
+The memory manager deals with three kinds of object:
+1. "Small" objects. Typically these require no more than 10K-20K total.
+2. "Large" objects. These may require tens to hundreds of K depending on
+ image size. Semantically they behave the same as small objects, but we
+ distinguish them for two reasons:
+ * On MS-DOS machines, large objects are referenced by FAR pointers,
+ small objects by NEAR pointers.
+ * Pool allocation heuristics may differ for large and small objects.
+ Note that individual "large" objects cannot exceed the size allowed by
+ type size_t, which may be 64K or less on some machines.
+3. "Virtual" objects. These are large 2-D arrays of JSAMPLEs or JBLOCKs
+ (typically large enough for the entire image being processed). The
+ memory manager provides stripwise access to these arrays. On machines
+ without virtual memory, the rest of the array may be swapped out to a
+ temporary file.
+
+(Note: JSAMPARRAY and JBLOCKARRAY data structures are a combination of large
+objects for the data proper and small objects for the row pointers. For
+convenience and speed, the memory manager provides single routines to create
+these structures. Similarly, virtual arrays include a small control block
+and a JSAMPARRAY or JBLOCKARRAY working buffer, all created with one call.)
+
+In the present implementation, virtual arrays are only permitted to have image
+lifespan. (Permanent lifespan would not be reasonable, and pass lifespan is
+not very useful since a virtual array's raison d'etre is to store data for
+multiple passes through the image.) We also expect that only "small" objects
+will be given permanent lifespan, though this restriction is not required by
+the memory manager.
+
+In a non-virtual-memory machine, some performance benefit can be gained by
+making the in-memory buffers for virtual arrays be as large as possible.
+(For small images, the buffers might fit entirely in memory, so blind
+swapping would be very wasteful.) The memory manager will adjust the height
+of the buffers to fit within a prespecified maximum memory usage. In order
+to do this in a reasonably optimal fashion, the manager needs to allocate all
+of the virtual arrays at once. Therefore, there isn't a one-step allocation
+routine for virtual arrays; instead, there is a "request" routine that simply
+allocates the control block, and a "realize" routine (called just once) that
+determines space allocation and creates all of the actual buffers. The
+realize routine must allow for space occupied by non-virtual large objects.
+(We don't bother to factor in the space needed for small objects, on the
+grounds that it isn't worth the trouble.)
+
+To support all this, we establish the following protocol for doing business
+with the memory manager:
+ 1. Modules must request virtual arrays (which may have only image lifespan)
+ during the initial setup phase, i.e., in their jinit_xxx routines.
+ 2. All "large" objects (including JSAMPARRAYs and JBLOCKARRAYs) must also be
+ allocated during initial setup.
+ 3. realize_virt_arrays will be called at the completion of initial setup.
+ The above conventions ensure that sufficient information is available
+ for it to choose a good size for virtual array buffers.
+Small objects of any lifespan may be allocated at any time. We expect that
+the total space used for small objects will be small enough to be negligible
+in the realize_virt_arrays computation.
+
+In a virtual-memory machine, we simply pretend that the available space is
+infinite, thus causing realize_virt_arrays to decide that it can allocate all
+the virtual arrays as full-size in-memory buffers. The overhead of the
+virtual-array access protocol is very small when no swapping occurs.
+
+A virtual array can be specified to be "pre-zeroed"; when this flag is set,
+never-yet-written sections of the array are set to zero before being made
+available to the caller. If this flag is not set, never-written sections
+of the array contain garbage. (This feature exists primarily because the
+equivalent logic would otherwise be needed in jdcoefct.c for progressive
+JPEG mode; we may as well make it available for possible other uses.)
+
+The first write pass on a virtual array is required to occur in top-to-bottom
+order; read passes, as well as any write passes after the first one, may
+access the array in any order. This restriction exists partly to simplify
+the virtual array control logic, and partly because some file systems may not
+support seeking beyond the current end-of-file in a temporary file. The main
+implication of this restriction is that rearrangement of rows (such as
+converting top-to-bottom data order to bottom-to-top) must be handled while
+reading data out of the virtual array, not while putting it in.
+
+
+*** Memory manager internal structure ***
+
+To isolate system dependencies as much as possible, we have broken the
+memory manager into two parts. There is a reasonably system-independent
+"front end" (jmemmgr.c) and a "back end" that contains only the code
+likely to change across systems. All of the memory management methods
+outlined above are implemented by the front end. The back end provides
+the following routines for use by the front end (none of these routines
+are known to the rest of the JPEG code):
+
+jpeg_mem_init, jpeg_mem_term system-dependent initialization/shutdown
+
+jpeg_get_small, jpeg_free_small interface to malloc and free library routines
+ (or their equivalents)
+
+jpeg_get_large, jpeg_free_large interface to FAR malloc/free in MSDOS machines;
+ else usually the same as
+ jpeg_get_small/jpeg_free_small
+
+jpeg_mem_available estimate available memory
+
+jpeg_open_backing_store create a backing-store object
+
+read_backing_store, manipulate a backing-store object
+write_backing_store,
+close_backing_store
+
+On some systems there will be more than one type of backing-store object
+(specifically, in MS-DOS a backing store file might be an area of extended
+memory as well as a disk file). jpeg_open_backing_store is responsible for
+choosing how to implement a given object. The read/write/close routines
+are method pointers in the structure that describes a given object; this
+lets them be different for different object types.
+
+It may be necessary to ensure that backing store objects are explicitly
+released upon abnormal program termination. For example, MS-DOS won't free
+extended memory by itself. To support this, we will expect the main program
+or surrounding application to arrange to call self_destruct (typically via
+jpeg_destroy) upon abnormal termination. This may require a SIGINT signal
+handler or equivalent. We don't want to have the back end module install its
+own signal handler, because that would pre-empt the surrounding application's
+ability to control signal handling.
+
+The IJG distribution includes several memory manager back end implementations.
+Usually the same back end should be suitable for all applications on a given
+system, but it is possible for an application to supply its own back end at
+need.
+
+
+*** Implications of DNL marker ***
+
+Some JPEG files may use a DNL marker to postpone definition of the image
+height (this would be useful for a fax-like scanner's output, for instance).
+In these files the SOF marker claims the image height is 0, and you only
+find out the true image height at the end of the first scan.
+
+We could read these files as follows:
+1. Upon seeing zero image height, replace it by 65535 (the maximum allowed).
+2. When the DNL is found, update the image height in the global image
+ descriptor.
+This implies that control modules must avoid making copies of the image
+height, and must re-test for termination after each MCU row. This would
+be easy enough to do.
+
+In cases where image-size data structures are allocated, this approach will
+result in very inefficient use of virtual memory or much-larger-than-necessary
+temporary files. This seems acceptable for something that probably won't be a
+mainstream usage. People might have to forgo use of memory-hogging options
+(such as two-pass color quantization or noninterleaved JPEG files) if they
+want efficient conversion of such files. (One could improve efficiency by
+demanding a user-supplied upper bound for the height, less than 65536; in most
+cases it could be much less.)
+
+The standard also permits the SOF marker to overestimate the image height,
+with a DNL to give the true, smaller height at the end of the first scan.
+This would solve the space problems if the overestimate wasn't too great.
+However, it implies that you don't even know whether DNL will be used.
+
+This leads to a couple of very serious objections:
+1. Testing for a DNL marker must occur in the inner loop of the decompressor's
+ Huffman decoder; this implies a speed penalty whether the feature is used
+ or not.
+2. There is no way to hide the last-minute change in image height from an
+ application using the decoder. Thus *every* application using the IJG
+ library would suffer a complexity penalty whether it cared about DNL or
+ not.
+We currently do not support DNL because of these problems.
+
+A different approach is to insist that DNL-using files be preprocessed by a
+separate program that reads ahead to the DNL, then goes back and fixes the SOF
+marker. This is a much simpler solution and is probably far more efficient.
+Even if one wants piped input, buffering the first scan of the JPEG file needs
+a lot smaller temp file than is implied by the maximum-height method. For
+this approach we'd simply treat DNL as a no-op in the decompressor (at most,
+check that it matches the SOF image height).
+
+We will not worry about making the compressor capable of outputting DNL.
+Something similar to the first scheme above could be applied if anyone ever
+wants to make that work.
diff --git a/jpeg-6c/testimg.bmp b/jpeg-6c/testimg.bmp
new file mode 100644
index 0000000..8603d15
Binary files /dev/null and b/jpeg-6c/testimg.bmp differ
diff --git a/jpeg-6c/testimg.jpg b/jpeg-6c/testimg.jpg
new file mode 100644
index 0000000..b34ca5d
Binary files /dev/null and b/jpeg-6c/testimg.jpg differ
diff --git a/jpeg-6c/testimg.ppm b/jpeg-6c/testimg.ppm
new file mode 100644
index 0000000..9d81ce2
--- /dev/null
+++ b/jpeg-6c/testimg.ppm
@@ -0,0 +1,4 @@
+P6
+227 149
+255
+0/-0/-10.21/51.51.62/62/83/83/:3-:3-:3-:3-:3-:3-:2/91.91.80-80-91.91.:2/80-80-80-80-80-80-80-80-6.+6.+6.+5-*5-*4,)4,)4,)4,)4,)4,)4,)4,)4,)4,)2-)/*$/,%/,%0-&1.'2/(30)30)63,63,74-85.85.96/:70:7.A:0B<0D>2F at 4IA4JB5KC6KC6MD5MD5OC3NB2OC3OC3PD4RE5R?1Y?2b at 4nB5}E6�H8�G9�F7�G:�G9�E:�G;�G>�G?�H@�E@�FL�CL�DK�EI�CI�BD�>B�=A�;A�:@�:?�<?�?@�@>�?<�A7�=/�@.�@.�?-�?-�@-�?-�@-�@,�A,�A-�B,�@*�A)�@*�A,�>-�?/�?/�>.�>,�=+�<+�<+�?+�?+�=*�=*�=*�>+�?,�@/�?6�>5�=2�?1�B3�D3�D4�D4�?0�A2�F8�H;�H9oA2T8*C3&=52954954732 [...]
\ No newline at end of file
diff --git a/jpeg-6c/testimgl.jpg b/jpeg-6c/testimgl.jpg
new file mode 100644
index 0000000..82b6b03
Binary files /dev/null and b/jpeg-6c/testimgl.jpg differ
diff --git a/jpeg-6c/testimgl.ppm b/jpeg-6c/testimgl.ppm
new file mode 100644
index 0000000..3130769
--- /dev/null
+++ b/jpeg-6c/testimgl.ppm
@@ -0,0 +1,4 @@
+P6
+227 149
+255
+0.,0.,00.20.40.40.62.62.82.82.:2,:2,:2,:2,:2,:2,:2.80.80.80,80,80.80.:2.80,80,80,80,80,80,80,80,6.*6.*6.*4,*4,*4,(4,(4,(4,(4,(4,(4,(4,(4,(4,(2,(.*$.,$.,$0,&0.&2.(20(20(62,62,64,84.84.86.:60:6.@:0B<0D>2F at 4H@4JB4JB6JB6LD4LD4NB2NB2NB2NB2PD4RD4R>0X>2b at 4nB4|D6�H8�F8�F6�F:�F8�D:�F:�F>�F>�H@�D@�FL�BL�DJ�DH�BH�BD�>B�<@�:@�:@�:>�<>�>@�@>�><�@6�<.�@.�@.�>,�>,�@,�>,�@,�@,�@,�@,�B,�@*�@(�@*�@,�>,�>.�>.�>.�>,�<*�<*�<*�>*�>*�<*�<*�<*�>*�>,�@.�>6�>4�<2�>0�B2�D2�D4�D4�>0�@2�F8�H:�H8n at 2T8*B2&<42844844622 [...]
\ No newline at end of file
diff --git a/jpeg-6c/testimgp.jpg b/jpeg-6c/testimgp.jpg
new file mode 100644
index 0000000..8cbb658
Binary files /dev/null and b/jpeg-6c/testimgp.jpg differ
diff --git a/jpeg-6c/testorig.jpg b/jpeg-6c/testorig.jpg
new file mode 100644
index 0000000..9816a0c
Binary files /dev/null and b/jpeg-6c/testorig.jpg differ
diff --git a/jpeg-6c/testprog.jpg b/jpeg-6c/testprog.jpg
new file mode 100644
index 0000000..920fee2
Binary files /dev/null and b/jpeg-6c/testprog.jpg differ
diff --git a/jpeg-6c/transupp.c b/jpeg-6c/transupp.c
new file mode 100644
index 0000000..5e98fd7
--- /dev/null
+++ b/jpeg-6c/transupp.c
@@ -0,0 +1,1931 @@
+/*
+ * transupp.c
+ *
+ * Copyright (C) 1997-2001, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains image transformation routines and other utility code
+ * used by the jpegtran sample application. These are NOT part of the core
+ * JPEG library. But we keep these routines separate from jpegtran.c toheight_in_data_units
+ * ease the task of maintaining jpegtran-like programs that have other user
+ * interfaces.
+ */
+
+/* Although this file really shouldn't have access to the library internals,
+ * it's helpful to let it call jround_up() and jcopy_block_row().
+ */
+#define JPEG_INTERNALS
+
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "transupp.h" /* My own external interface */
+#include <ctype.h> /* to declare isdigit() */
+
+
+#if TRANSFORMS_SUPPORTED
+
+/*
+ * Lossless image transformation routines. These routines work on DCT
+ * coefficient arrays and thus do not require any lossy decompression
+ * or recompression of the image.
+ * Thanks to Guido Vollbeding for the initial design and code of this feature,
+ * and to Ben Jackson for introducing the cropping feature.
+ *
+ * Horizontal flipping is done in-place, using a single top-to-bottom
+ * pass through the virtual source array. It will thus be much the
+ * fastest option for images larger than main memory.
+ *
+ * The other routines require a set of destination virtual arrays, so they
+ * need twice as much memory as jpegtran normally does. The destination
+ * arrays are always written in normal scan order (top to bottom) because
+ * the virtual array manager expects this. The source arrays will be scanned
+ * in the corresponding order, which means multiple passes through the source
+ * arrays for most of the transforms. That could result in much thrashing
+ * if the image is larger than main memory.
+ *
+ * If cropping or trimming is involved, the destination arrays may be smaller
+ * than the source arrays. Note it is not possible to do horizontal flip
+ * in-place when a nonzero Y crop offset is specified, since we'd have to move
+ * data from one block row to another but the virtual array manager doesn't
+ * guarantee we can touch more than one row at a time. So in that case,
+ * we have to use a separate destination array.
+ *
+ * Some notes about the operating environment of the individual transform
+ * routines:
+ * 1. Both the source and destination virtual arrays are allocated from the
+ * source JPEG object, and therefore should be manipulated by calling the
+ * source's memory manager.
+ * 2. The destination's component count should be used. It may be smaller
+ * than the source's when forcing to grayscale.
+ * 3. Likewise the destination's sampling factors should be used. When
+ * forcing to grayscale the destination's sampling factors will be all 1,
+ * and we may as well take that as the effective iMCU size.
+ * 4. When "trim" is in effect, the destination's dimensions will be the
+ * trimmed values but the source's will be untrimmed.
+ * 5. When "crop" is in effect, the destination's dimensions will be the
+ * cropped values but the source's will be uncropped. Each transform
+ * routine is responsible for picking up source data starting at the
+ * correct X and Y offset for the crop region. (The X and Y offsets
+ * passed to the transform routines are measured in iMCU blocks of the
+ * destination.)
+ * 6. All the routines assume that the source and destination buffers are
+ * padded out to a full iMCU boundary. This is true, although for the
+ * source buffer it is an undocumented property of jdcoefct.c.
+ */
+
+
+/* Drop code may be used with or without virtual memory adaptation code.
+ * This code has some dependencies on internal library behavior, so you
+ * may choose to disable it. For example, it doesn't make a difference
+ * if you only use jmemnobs anyway.
+ */
+#ifndef DROP_REQUEST_FROM_SRC
+#define DROP_REQUEST_FROM_SRC 1 /* 0 disables adaptation */
+#endif
+
+
+#if DROP_REQUEST_FROM_SRC
+/* Force jpeg_read_coefficients to request
+ * the virtual coefficient arrays from
+ * the source decompression object.
+ */
+METHODDEF(jvirt_barray_ptr)
+drop_request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
+ JDIMENSION blocksperrow, JDIMENSION numrows,
+ JDIMENSION maxaccess)
+{
+ j_decompress_ptr srcinfo = (j_decompress_ptr) cinfo->client_data;
+
+ return (*srcinfo->mem->request_virt_barray)
+ ((j_common_ptr) srcinfo, pool_id, pre_zero,
+ blocksperrow, numrows, maxaccess);
+}
+
+
+/* Force jpeg_read_coefficients to return
+ * after requesting and before accessing
+ * the virtual coefficient arrays.
+ */
+METHODDEF(int)
+drop_consume_input (j_decompress_ptr cinfo)
+{
+ return JPEG_SUSPENDED;
+}
+
+
+METHODDEF(void)
+drop_start_input_pass (j_decompress_ptr cinfo)
+{
+ cinfo->inputctl->consume_input = drop_consume_input;
+}
+
+
+LOCAL(void)
+drop_request_from_src (j_decompress_ptr dropinfo, j_decompress_ptr srcinfo)
+{
+ void *save_client_data;
+ JMETHOD(jvirt_barray_ptr, save_request_virt_barray,
+ (j_common_ptr cinfo, int pool_id, boolean pre_zero,
+ JDIMENSION blocksperrow, JDIMENSION numrows, JDIMENSION maxaccess));
+ JMETHOD(void, save_start_input_pass, (j_decompress_ptr cinfo));
+
+ /* Set custom method pointers, save original pointers */
+ save_client_data = dropinfo->client_data;
+ dropinfo->client_data = (void *) srcinfo;
+ save_request_virt_barray = dropinfo->mem->request_virt_barray;
+ dropinfo->mem->request_virt_barray = drop_request_virt_barray;
+ save_start_input_pass = dropinfo->inputctl->start_input_pass;
+ dropinfo->inputctl->start_input_pass = drop_start_input_pass;
+
+ /* Execute only initialization part.
+ * Requested coefficient arrays will be realized later by the srcinfo object.
+ * Next call to the same function will then do the actual data reading.
+ * NB: since we request the coefficient arrays from another object,
+ * the inherent realization call is effectively a no-op.
+ */
+ (void) jpeg_read_coefficients(dropinfo);
+
+ /* Reset method pointers */
+ dropinfo->client_data = save_client_data;
+ dropinfo->mem->request_virt_barray = save_request_virt_barray;
+ dropinfo->inputctl->start_input_pass = save_start_input_pass;
+ /* Do input initialization for first scan now,
+ * which also resets the consume_input method.
+ */
+ (*save_start_input_pass)(dropinfo);
+}
+#endif /* DROP_REQUEST_FROM_SRC */
+
+
+LOCAL(void)
+dequant_comp (j_decompress_ptr cinfo, jpeg_component_info *compptr,
+ jvirt_barray_ptr coef_array, JQUANT_TBL *qtblptr1)
+{
+ JDIMENSION blk_x, blk_y;
+ int offset_y, k;
+ JQUANT_TBL *qtblptr;
+ JBLOCKARRAY buffer;
+ JBLOCKROW block;
+ JCOEFPTR ptr;
+
+ qtblptr = compptr->quant_table;
+ for (blk_y = 0; blk_y < compptr->height_in_data_units;
+ blk_y += compptr->v_samp_factor) {
+ buffer = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef_array, blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ block = buffer[offset_y];
+ for (blk_x = 0; blk_x < compptr->width_in_data_units; blk_x++) {
+ ptr = block[blk_x];
+ for (k = 0; k < DCTSIZE2; k++)
+ if (qtblptr->quantval[k] != qtblptr1->quantval[k])
+ ptr[k] *= qtblptr->quantval[k] / qtblptr1->quantval[k];
+ }
+ }
+ }
+}
+
+
+LOCAL(void)
+requant_comp (j_decompress_ptr cinfo, jpeg_component_info *compptr,
+ jvirt_barray_ptr coef_array, JQUANT_TBL *qtblptr1)
+{
+ JDIMENSION blk_x, blk_y;
+ int offset_y, k;
+ JQUANT_TBL *qtblptr;
+ JBLOCKARRAY buffer;
+ JBLOCKROW block;
+ JCOEFPTR ptr;
+ JCOEF temp, qval;
+
+ qtblptr = compptr->quant_table;
+ for (blk_y = 0; blk_y < compptr->height_in_data_units;
+ blk_y += compptr->v_samp_factor) {
+ buffer = (*cinfo->mem->access_virt_barray)
+ ((j_common_ptr) cinfo, coef_array, blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ block = buffer[offset_y];
+ for (blk_x = 0; blk_x < compptr->width_in_data_units; blk_x++) {
+ ptr = block[blk_x];
+ for (k = 0; k < DCTSIZE2; k++) {
+ temp = qtblptr->quantval[k];
+ qval = qtblptr1->quantval[k];
+ if (temp != qval) {
+ temp *= ptr[k];
+ /* The following quantization code is a copy from jcdctmgr.c */
+#ifdef FAST_DIVIDE
+#define DIVIDE_BY(a,b) a /= b
+#else
+#define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
+#endif
+ if (temp < 0) {
+ temp = -temp;
+ temp += qval>>1; /* for rounding */
+ DIVIDE_BY(temp, qval);
+ temp = -temp;
+ } else {
+ temp += qval>>1; /* for rounding */
+ DIVIDE_BY(temp, qval);
+ }
+ ptr[k] = temp;
+ }
+ }
+ }
+ }
+ }
+}
+
+
+/* Calculate largest common denominator with Euklid's algorithm.
+ */
+LOCAL(JCOEF)
+largest_common_denominator(JCOEF a, JCOEF b)
+{
+ JCOEF c;
+
+ do {
+ c = a % b;
+ a = b;
+ b = c;
+ } while (c);
+
+ return a;
+}
+
+
+LOCAL(void)
+adjust_quant(j_decompress_ptr srcinfo, jvirt_barray_ptr *src_coef_arrays,
+ j_decompress_ptr dropinfo, jvirt_barray_ptr *drop_coef_arrays,
+ boolean trim, j_compress_ptr dstinfo)
+{
+ jpeg_component_info *compptr1, *compptr2;
+ JQUANT_TBL *qtblptr1, *qtblptr2, *qtblptr3;
+ int ci, k;
+
+ for (ci = 0; ci < dstinfo->num_components &&
+ ci < dropinfo->num_components; ci++) {
+ compptr1 = srcinfo->comp_info + ci;
+ compptr2 = dropinfo->comp_info + ci;
+ qtblptr1 = compptr1->quant_table;
+ qtblptr2 = compptr2->quant_table;
+ for (k = 0; k < DCTSIZE2; k++) {
+ if (qtblptr1->quantval[k] != qtblptr2->quantval[k]) {
+ if (trim)
+ requant_comp(dropinfo, compptr2, drop_coef_arrays[ci], qtblptr1);
+ else {
+ qtblptr3 = dstinfo->quant_tbl_ptrs[compptr1->quant_tbl_no];
+ for (k = 0; k < DCTSIZE2; k++)
+ if (qtblptr1->quantval[k] != qtblptr2->quantval[k])
+ qtblptr3->quantval[k] = largest_common_denominator
+ (qtblptr1->quantval[k], qtblptr2->quantval[k]);
+ dequant_comp(srcinfo, compptr1, src_coef_arrays[ci], qtblptr3);
+ dequant_comp(dropinfo, compptr2, drop_coef_arrays[ci], qtblptr3);
+ }
+ break;
+ }
+ }
+ }
+}
+
+
+LOCAL(void)
+do_drop (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ JDIMENSION x_crop_offset, JDIMENSION y_crop_offset,
+ jvirt_barray_ptr *src_coef_arrays,
+ j_decompress_ptr dropinfo, jvirt_barray_ptr *drop_coef_arrays,
+ JDIMENSION drop_width, JDIMENSION drop_height)
+/* Drop. If the dropinfo component number is smaller than the destination's,
+ * we fill in the remaining components with zero. This provides the feature
+ * of dropping grayscale into (arbitrarily sampled) color images.
+ */
+{
+ JDIMENSION comp_width, comp_height;
+ JDIMENSION blk_y, x_drop_blocks, y_drop_blocks;
+ int ci, offset_y;
+ JBLOCKARRAY src_buffer, dst_buffer;
+ jpeg_component_info *compptr;
+
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_width = drop_width * compptr->h_samp_factor;
+ comp_height = drop_height * compptr->v_samp_factor;
+ x_drop_blocks = x_crop_offset * compptr->h_samp_factor;
+ y_drop_blocks = y_crop_offset * compptr->v_samp_factor;
+ for (blk_y = 0; blk_y < comp_height; blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y + y_drop_blocks,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ if (ci < dropinfo->num_components) {
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, drop_coef_arrays[ci], blk_y,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ jcopy_block_row(src_buffer[offset_y],
+ dst_buffer[offset_y] + x_drop_blocks,
+ comp_width);
+ }
+ } else {
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ jzero_far(dst_buffer[offset_y] + x_drop_blocks,
+ comp_width * SIZEOF(JBLOCK));
+ }
+ }
+ }
+ }
+}
+
+
+LOCAL(void)
+do_crop (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ JDIMENSION x_crop_offset, JDIMENSION y_crop_offset,
+ jvirt_barray_ptr *src_coef_arrays,
+ jvirt_barray_ptr *dst_coef_arrays)
+/* Crop. This is only used when no rotate/flip is requested with the crop.
+ * Extension: If the destination size is larger than the source, we fill in
+ * the extra area with zero (neutral gray). Note we also have to zero partial
+ * iMCUs at the right and bottom edge of the source image area in this case.
+ */
+{
+ JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height;
+ JDIMENSION dst_blk_y, x_crop_blocks, y_crop_blocks;
+ int ci, offset_y;
+ JBLOCKARRAY src_buffer, dst_buffer;
+ jpeg_component_info *compptr;
+
+ MCU_cols = srcinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
+ MCU_rows = srcinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
+
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+ comp_height = MCU_rows * compptr->v_samp_factor;
+ x_crop_blocks = x_crop_offset * compptr->h_samp_factor;
+ y_crop_blocks = y_crop_offset * compptr->v_samp_factor;
+ for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ if (dstinfo->image_height > srcinfo->image_height) {
+ if (dst_blk_y < y_crop_blocks ||
+ dst_blk_y >= comp_height + y_crop_blocks) {
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ jzero_far(dst_buffer[offset_y],
+ compptr->width_in_data_units * SIZEOF(JBLOCK));
+ }
+ continue;
+ }
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci],
+ dst_blk_y - y_crop_blocks,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ } else {
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci],
+ dst_blk_y + y_crop_blocks,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ }
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ if (dstinfo->image_width > srcinfo->image_width) {
+ if (x_crop_blocks > 0) {
+ jzero_far(dst_buffer[offset_y],
+ x_crop_blocks * SIZEOF(JBLOCK));
+ }
+ jcopy_block_row(src_buffer[offset_y],
+ dst_buffer[offset_y] + x_crop_blocks,
+ comp_width);
+ if (compptr->width_in_data_units > comp_width + x_crop_blocks) {
+ jzero_far(dst_buffer[offset_y] +
+ comp_width + x_crop_blocks,
+ (compptr->width_in_data_units -
+ comp_width - x_crop_blocks) * SIZEOF(JBLOCK));
+ }
+ } else {
+ jcopy_block_row(src_buffer[offset_y] + x_crop_blocks,
+ dst_buffer[offset_y],
+ compptr->width_in_data_units);
+ }
+ }
+ }
+ }
+}
+
+
+LOCAL(void)
+do_flip_h_no_crop (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ JDIMENSION x_crop_offset,
+ jvirt_barray_ptr *src_coef_arrays)
+/* Horizontal flip; done in-place, so no separate dest array is required.
+ * NB: this only works when y_crop_offset is zero.
+ */
+{
+ JDIMENSION MCU_cols, comp_width, blk_x, blk_y, x_crop_blocks;
+ int ci, k, offset_y;
+ JBLOCKARRAY buffer;
+ JCOEFPTR ptr1, ptr2;
+ JCOEF temp1, temp2;
+ jpeg_component_info *compptr;
+
+ /* Horizontal mirroring of DCT blocks is accomplished by swapping
+ * pairs of blocks in-place. Within a DCT block, we perform horizontal
+ * mirroring by changing the signs of odd-numbered columns.
+ * Partial iMCUs at the right edge are left untouched.
+ */
+ MCU_cols = srcinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
+
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+ x_crop_blocks = x_crop_offset * compptr->h_samp_factor;
+ for (blk_y = 0; blk_y < compptr->height_in_data_units;
+ blk_y += compptr->v_samp_factor) {
+ buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ /* Do the mirroring */
+ for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
+ ptr1 = buffer[offset_y][blk_x];
+ ptr2 = buffer[offset_y][comp_width - blk_x - 1];
+ /* this unrolled loop doesn't need to know which row it's on... */
+ for (k = 0; k < DCTSIZE2; k += 2) {
+ temp1 = *ptr1; /* swap even column */
+ temp2 = *ptr2;
+ *ptr1++ = temp2;
+ *ptr2++ = temp1;
+ temp1 = *ptr1; /* swap odd column with sign change */
+ temp2 = *ptr2;
+ *ptr1++ = -temp2;
+ *ptr2++ = -temp1;
+ }
+ }
+ if (x_crop_blocks > 0) {
+ /* Now left-justify the portion of the data to be kept.
+ * We can't use a single jcopy_block_row() call because that routine
+ * depends on memcpy(), whose behavior is unspecified for overlapping
+ * source and destination areas. Sigh.
+ */
+ for (blk_x = 0; blk_x < compptr->width_in_data_units; blk_x++) {
+ jcopy_block_row(buffer[offset_y] + blk_x + x_crop_blocks,
+ buffer[offset_y] + blk_x,
+ (JDIMENSION) 1);
+ }
+ }
+ }
+ }
+ }
+}
+
+
+LOCAL(void)
+do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ JDIMENSION x_crop_offset, JDIMENSION y_crop_offset,
+ jvirt_barray_ptr *src_coef_arrays,
+ jvirt_barray_ptr *dst_coef_arrays)
+/* Horizontal flip in general cropping case */
+{
+ JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
+ JDIMENSION x_crop_blocks, y_crop_blocks;
+ int ci, k, offset_y;
+ JBLOCKARRAY src_buffer, dst_buffer;
+ JBLOCKROW src_row_ptr, dst_row_ptr;
+ JCOEFPTR src_ptr, dst_ptr;
+ jpeg_component_info *compptr;
+
+ /* Here we must output into a separate array because we can't touch
+ * different rows of a single virtual array simultaneously. Otherwise,
+ * this is essentially the same as the routine above.
+ */
+ MCU_cols = srcinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
+
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+ x_crop_blocks = x_crop_offset * compptr->h_samp_factor;
+ y_crop_blocks = y_crop_offset * compptr->v_samp_factor;
+ for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci],
+ dst_blk_y + y_crop_blocks,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ dst_row_ptr = dst_buffer[offset_y];
+ src_row_ptr = src_buffer[offset_y];
+ for (dst_blk_x = 0; dst_blk_x < compptr->width_in_data_units; dst_blk_x++) {
+ if (x_crop_blocks + dst_blk_x < comp_width) {
+ /* Do the mirrorable blocks */
+ dst_ptr = dst_row_ptr[dst_blk_x];
+ src_ptr = src_row_ptr[comp_width - x_crop_blocks - dst_blk_x - 1];
+ /* this unrolled loop doesn't need to know which row it's on... */
+ for (k = 0; k < DCTSIZE2; k += 2) {
+ *dst_ptr++ = *src_ptr++; /* copy even column */
+ *dst_ptr++ = - *src_ptr++; /* copy odd column with sign change */
+ }
+ } else {
+ /* Copy last partial block(s) verbatim */
+ jcopy_block_row(src_row_ptr + dst_blk_x + x_crop_blocks,
+ dst_row_ptr + dst_blk_x,
+ (JDIMENSION) 1);
+ }
+ }
+ }
+ }
+ }
+}
+
+
+LOCAL(void)
+do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ JDIMENSION x_crop_offset, JDIMENSION y_crop_offset,
+ jvirt_barray_ptr *src_coef_arrays,
+ jvirt_barray_ptr *dst_coef_arrays)
+/* Vertical flip */
+{
+ JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
+ JDIMENSION x_crop_blocks, y_crop_blocks;
+ int ci, i, j, offset_y;
+ JBLOCKARRAY src_buffer, dst_buffer;
+ JBLOCKROW src_row_ptr, dst_row_ptr;
+ JCOEFPTR src_ptr, dst_ptr;
+ jpeg_component_info *compptr;
+
+ /* We output into a separate array because we can't touch different
+ * rows of the source virtual array simultaneously. Otherwise, this
+ * is a pretty straightforward analog of horizontal flip.
+ * Within a DCT block, vertical mirroring is done by changing the signs
+ * of odd-numbered rows.
+ * Partial iMCUs at the bottom edge are copied verbatim.
+ */
+ MCU_rows = srcinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
+
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_height = MCU_rows * compptr->v_samp_factor;
+ x_crop_blocks = x_crop_offset * compptr->h_samp_factor;
+ y_crop_blocks = y_crop_offset * compptr->v_samp_factor;
+ for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ if (y_crop_blocks + dst_blk_y < comp_height) {
+ /* Row is within the mirrorable area. */
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci],
+ comp_height - y_crop_blocks - dst_blk_y -
+ (JDIMENSION) compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ } else {
+ /* Bottom-edge blocks will be copied verbatim. */
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci],
+ dst_blk_y + y_crop_blocks,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ }
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ if (y_crop_blocks + dst_blk_y < comp_height) {
+ /* Row is within the mirrorable area. */
+ dst_row_ptr = dst_buffer[offset_y];
+ src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
+ src_row_ptr += x_crop_blocks;
+ for (dst_blk_x = 0; dst_blk_x < compptr->width_in_data_units;
+ dst_blk_x++) {
+ dst_ptr = dst_row_ptr[dst_blk_x];
+ src_ptr = src_row_ptr[dst_blk_x];
+ for (i = 0; i < DCTSIZE; i += 2) {
+ /* copy even row */
+ for (j = 0; j < DCTSIZE; j++)
+ *dst_ptr++ = *src_ptr++;
+ /* copy odd row with sign change */
+ for (j = 0; j < DCTSIZE; j++)
+ *dst_ptr++ = - *src_ptr++;
+ }
+ }
+ } else {
+ /* Just copy row verbatim. */
+ jcopy_block_row(src_buffer[offset_y] + x_crop_blocks,
+ dst_buffer[offset_y],
+ compptr->width_in_data_units);
+ }
+ }
+ }
+ }
+}
+
+
+LOCAL(void)
+do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ JDIMENSION x_crop_offset, JDIMENSION y_crop_offset,
+ jvirt_barray_ptr *src_coef_arrays,
+ jvirt_barray_ptr *dst_coef_arrays)
+/* Transpose source into destination */
+{
+ JDIMENSION dst_blk_x, dst_blk_y, x_crop_blocks, y_crop_blocks;
+ int ci, i, j, offset_x, offset_y;
+ JBLOCKARRAY src_buffer, dst_buffer;
+ JCOEFPTR src_ptr, dst_ptr;
+ jpeg_component_info *compptr;
+
+ /* Transposing pixels within a block just requires transposing the
+ * DCT coefficients.
+ * Partial iMCUs at the edges require no special treatment; we simply
+ * process all the available DCT blocks for every component.
+ */
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ x_crop_blocks = x_crop_offset * compptr->h_samp_factor;
+ y_crop_blocks = y_crop_offset * compptr->v_samp_factor;
+ for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ for (dst_blk_x = 0; dst_blk_x < compptr->width_in_data_units;
+ dst_blk_x += compptr->h_samp_factor) {
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci],
+ dst_blk_x + x_crop_blocks,
+ (JDIMENSION) compptr->h_samp_factor, FALSE);
+ for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
+ dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
+ src_ptr = src_buffer[offset_x][dst_blk_y + offset_y + y_crop_blocks];
+ for (i = 0; i < DCTSIZE; i++)
+ for (j = 0; j < DCTSIZE; j++)
+ dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
+ }
+ }
+ }
+ }
+ }
+}
+
+
+LOCAL(void)
+do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ JDIMENSION x_crop_offset, JDIMENSION y_crop_offset,
+ jvirt_barray_ptr *src_coef_arrays,
+ jvirt_barray_ptr *dst_coef_arrays)
+/* 90 degree rotation is equivalent to
+ * 1. Transposing the image;
+ * 2. Horizontal mirroring.
+ * These two steps are merged into a single processing routine.
+ */
+{
+ JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
+ JDIMENSION x_crop_blocks, y_crop_blocks;
+ int ci, i, j, offset_x, offset_y;
+ JBLOCKARRAY src_buffer, dst_buffer;
+ JCOEFPTR src_ptr, dst_ptr;
+ jpeg_component_info *compptr;
+
+ /* Because of the horizontal mirror step, we can't process partial iMCUs
+ * at the (output) right edge properly. They just get transposed and
+ * not mirrored.
+ */
+ MCU_cols = srcinfo->image_height / (dstinfo->max_h_samp_factor * DCTSIZE);
+
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+ x_crop_blocks = x_crop_offset * compptr->h_samp_factor;
+ y_crop_blocks = y_crop_offset * compptr->v_samp_factor;
+ for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ for (dst_blk_x = 0; dst_blk_x < compptr->width_in_data_units;
+ dst_blk_x += compptr->h_samp_factor) {
+ if (x_crop_blocks + dst_blk_x < comp_width) {
+ /* Block is within the mirrorable area. */
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci],
+ comp_width - x_crop_blocks - dst_blk_x -
+ (JDIMENSION) compptr->h_samp_factor,
+ (JDIMENSION) compptr->h_samp_factor, FALSE);
+ } else {
+ /* Edge blocks are transposed but not mirrored. */
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci],
+ dst_blk_x + x_crop_blocks,
+ (JDIMENSION) compptr->h_samp_factor, FALSE);
+ }
+ for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
+ dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
+ if (x_crop_blocks + dst_blk_x < comp_width) {
+ /* Block is within the mirrorable area. */
+ src_ptr = src_buffer[compptr->h_samp_factor - offset_x - 1]
+ [dst_blk_y + offset_y + y_crop_blocks];
+ for (i = 0; i < DCTSIZE; i++) {
+ for (j = 0; j < DCTSIZE; j++)
+ dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
+ i++;
+ for (j = 0; j < DCTSIZE; j++)
+ dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
+ }
+ } else {
+ /* Edge blocks are transposed but not mirrored. */
+ src_ptr = src_buffer[offset_x]
+ [dst_blk_y + offset_y + y_crop_blocks];
+ for (i = 0; i < DCTSIZE; i++)
+ for (j = 0; j < DCTSIZE; j++)
+ dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+LOCAL(void)
+do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ JDIMENSION x_crop_offset, JDIMENSION y_crop_offset,
+ jvirt_barray_ptr *src_coef_arrays,
+ jvirt_barray_ptr *dst_coef_arrays)
+/* 270 degree rotation is equivalent to
+ * 1. Horizontal mirroring;
+ * 2. Transposing the image.
+ * These two steps are merged into a single processing routine.
+ */
+{
+ JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
+ JDIMENSION x_crop_blocks, y_crop_blocks;
+ int ci, i, j, offset_x, offset_y;
+ JBLOCKARRAY src_buffer, dst_buffer;
+ JCOEFPTR src_ptr, dst_ptr;
+ jpeg_component_info *compptr;
+
+ /* Because of the horizontal mirror step, we can't process partial iMCUs
+ * at the (output) bottom edge properly. They just get transposed and
+ * not mirrored.
+ */
+ MCU_rows = srcinfo->image_width / (dstinfo->max_v_samp_factor * DCTSIZE);
+
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_height = MCU_rows * compptr->v_samp_factor;
+ x_crop_blocks = x_crop_offset * compptr->h_samp_factor;
+ y_crop_blocks = y_crop_offset * compptr->v_samp_factor;
+ for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ for (dst_blk_x = 0; dst_blk_x < compptr->width_in_data_units;
+ dst_blk_x += compptr->h_samp_factor) {
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci],
+ dst_blk_x + x_crop_blocks,
+ (JDIMENSION) compptr->h_samp_factor, FALSE);
+ for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
+ dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
+ if (y_crop_blocks + dst_blk_y < comp_height) {
+ /* Block is within the mirrorable area. */
+ src_ptr = src_buffer[offset_x]
+ [comp_height - y_crop_blocks - dst_blk_y - offset_y - 1];
+ for (i = 0; i < DCTSIZE; i++) {
+ for (j = 0; j < DCTSIZE; j++) {
+ dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
+ j++;
+ dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
+ }
+ }
+ } else {
+ /* Edge blocks are transposed but not mirrored. */
+ src_ptr = src_buffer[offset_x]
+ [dst_blk_y + offset_y + y_crop_blocks];
+ for (i = 0; i < DCTSIZE; i++)
+ for (j = 0; j < DCTSIZE; j++)
+ dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+LOCAL(void)
+do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ JDIMENSION x_crop_offset, JDIMENSION y_crop_offset,
+ jvirt_barray_ptr *src_coef_arrays,
+ jvirt_barray_ptr *dst_coef_arrays)
+/* 180 degree rotation is equivalent to
+ * 1. Vertical mirroring;
+ * 2. Horizontal mirroring.
+ * These two steps are merged into a single processing routine.
+ */
+{
+ JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
+ JDIMENSION x_crop_blocks, y_crop_blocks;
+ int ci, i, j, offset_y;
+ JBLOCKARRAY src_buffer, dst_buffer;
+ JBLOCKROW src_row_ptr, dst_row_ptr;
+ JCOEFPTR src_ptr, dst_ptr;
+ jpeg_component_info *compptr;
+
+ MCU_cols = srcinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
+ MCU_rows = srcinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
+
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+ comp_height = MCU_rows * compptr->v_samp_factor;
+ x_crop_blocks = x_crop_offset * compptr->h_samp_factor;
+ y_crop_blocks = y_crop_offset * compptr->v_samp_factor;
+ for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ if (y_crop_blocks + dst_blk_y < comp_height) {
+ /* Row is within the vertically mirrorable area. */
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci],
+ comp_height - y_crop_blocks - dst_blk_y -
+ (JDIMENSION) compptr->v_samp_factor,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ } else {
+ /* Bottom-edge rows are only mirrored horizontally. */
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci],
+ dst_blk_y + y_crop_blocks,
+ (JDIMENSION) compptr->v_samp_factor, FALSE);
+ }
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ dst_row_ptr = dst_buffer[offset_y];
+ if (y_crop_blocks + dst_blk_y < comp_height) {
+ /* Row is within the mirrorable area. */
+ src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
+ for (dst_blk_x = 0; dst_blk_x < compptr->width_in_data_units; dst_blk_x++) {
+ dst_ptr = dst_row_ptr[dst_blk_x];
+ if (x_crop_blocks + dst_blk_x < comp_width) {
+ /* Process the blocks that can be mirrored both ways. */
+ src_ptr = src_row_ptr[comp_width - x_crop_blocks - dst_blk_x - 1];
+ for (i = 0; i < DCTSIZE; i += 2) {
+ /* For even row, negate every odd column. */
+ for (j = 0; j < DCTSIZE; j += 2) {
+ *dst_ptr++ = *src_ptr++;
+ *dst_ptr++ = - *src_ptr++;
+ }
+ /* For odd row, negate every even column. */
+ for (j = 0; j < DCTSIZE; j += 2) {
+ *dst_ptr++ = - *src_ptr++;
+ *dst_ptr++ = *src_ptr++;
+ }
+ }
+ } else {
+ /* Any remaining right-edge blocks are only mirrored vertically. */
+ src_ptr = src_row_ptr[x_crop_blocks + dst_blk_x];
+ for (i = 0; i < DCTSIZE; i += 2) {
+ for (j = 0; j < DCTSIZE; j++)
+ *dst_ptr++ = *src_ptr++;
+ for (j = 0; j < DCTSIZE; j++)
+ *dst_ptr++ = - *src_ptr++;
+ }
+ }
+ }
+ } else {
+ /* Remaining rows are just mirrored horizontally. */
+ src_row_ptr = src_buffer[offset_y];
+ for (dst_blk_x = 0; dst_blk_x < compptr->width_in_data_units; dst_blk_x++) {
+ if (x_crop_blocks + dst_blk_x < comp_width) {
+ /* Process the blocks that can be mirrored. */
+ dst_ptr = dst_row_ptr[dst_blk_x];
+ src_ptr = src_row_ptr[comp_width - x_crop_blocks - dst_blk_x - 1];
+ for (i = 0; i < DCTSIZE2; i += 2) {
+ *dst_ptr++ = *src_ptr++;
+ *dst_ptr++ = - *src_ptr++;
+ }
+ } else {
+ /* Any remaining right-edge blocks are only copied. */
+ jcopy_block_row(src_row_ptr + dst_blk_x + x_crop_blocks,
+ dst_row_ptr + dst_blk_x,
+ (JDIMENSION) 1);
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+LOCAL(void)
+do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ JDIMENSION x_crop_offset, JDIMENSION y_crop_offset,
+ jvirt_barray_ptr *src_coef_arrays,
+ jvirt_barray_ptr *dst_coef_arrays)
+/* Transverse transpose is equivalent to
+ * 1. 180 degree rotation;
+ * 2. Transposition;
+ * or
+ * 1. Horizontal mirroring;
+ * 2. Transposition;
+ * 3. Horizontal mirroring.
+ * These steps are merged into a single processing routine.
+ */
+{
+ JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
+ JDIMENSION x_crop_blocks, y_crop_blocks;
+ int ci, i, j, offset_x, offset_y;
+ JBLOCKARRAY src_buffer, dst_buffer;
+ JCOEFPTR src_ptr, dst_ptr;
+ jpeg_component_info *compptr;
+
+ MCU_cols = srcinfo->image_height / (dstinfo->max_h_samp_factor * DCTSIZE);
+ MCU_rows = srcinfo->image_width / (dstinfo->max_v_samp_factor * DCTSIZE);
+
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ comp_width = MCU_cols * compptr->h_samp_factor;
+ comp_height = MCU_rows * compptr->v_samp_factor;
+ x_crop_blocks = x_crop_offset * compptr->h_samp_factor;
+ y_crop_blocks = y_crop_offset * compptr->v_samp_factor;
+ for (dst_blk_y = 0; dst_blk_y < compptr->height_in_data_units;
+ dst_blk_y += compptr->v_samp_factor) {
+ dst_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
+ (JDIMENSION) compptr->v_samp_factor, TRUE);
+ for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
+ for (dst_blk_x = 0; dst_blk_x < compptr->width_in_data_units;
+ dst_blk_x += compptr->h_samp_factor) {
+ if (x_crop_blocks + dst_blk_x < comp_width) {
+ /* Block is within the mirrorable area. */
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci],
+ comp_width - x_crop_blocks - dst_blk_x -
+ (JDIMENSION) compptr->h_samp_factor,
+ (JDIMENSION) compptr->h_samp_factor, FALSE);
+ } else {
+ src_buffer = (*srcinfo->mem->access_virt_barray)
+ ((j_common_ptr) srcinfo, src_coef_arrays[ci],
+ dst_blk_x + x_crop_blocks,
+ (JDIMENSION) compptr->h_samp_factor, FALSE);
+ }
+ for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
+ dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
+ if (y_crop_blocks + dst_blk_y < comp_height) {
+ if (x_crop_blocks + dst_blk_x < comp_width) {
+ /* Block is within the mirrorable area. */
+ src_ptr = src_buffer[compptr->h_samp_factor - offset_x - 1]
+ [comp_height - y_crop_blocks - dst_blk_y - offset_y - 1];
+ for (i = 0; i < DCTSIZE; i++) {
+ for (j = 0; j < DCTSIZE; j++) {
+ dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
+ j++;
+ dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
+ }
+ i++;
+ for (j = 0; j < DCTSIZE; j++) {
+ dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
+ j++;
+ dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
+ }
+ }
+ } else {
+ /* Right-edge blocks are mirrored in y only */
+ src_ptr = src_buffer[offset_x]
+ [comp_height - y_crop_blocks - dst_blk_y - offset_y - 1];
+ for (i = 0; i < DCTSIZE; i++) {
+ for (j = 0; j < DCTSIZE; j++) {
+ dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
+ j++;
+ dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
+ }
+ }
+ }
+ } else {
+ if (x_crop_blocks + dst_blk_x < comp_width) {
+ /* Bottom-edge blocks are mirrored in x only */
+ src_ptr = src_buffer[compptr->h_samp_factor - offset_x - 1]
+ [dst_blk_y + offset_y + y_crop_blocks];
+ for (i = 0; i < DCTSIZE; i++) {
+ for (j = 0; j < DCTSIZE; j++)
+ dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
+ i++;
+ for (j = 0; j < DCTSIZE; j++)
+ dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
+ }
+ } else {
+ /* At lower right corner, just transpose, no mirroring */
+ src_ptr = src_buffer[offset_x]
+ [dst_blk_y + offset_y + y_crop_blocks];
+ for (i = 0; i < DCTSIZE; i++)
+ for (j = 0; j < DCTSIZE; j++)
+ dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+/* Parse an unsigned integer: subroutine for jtransform_parse_crop_spec.
+ * Returns TRUE if valid integer found, FALSE if not.
+ * *strptr is advanced over the digit string, and *result is set to its value.
+ */
+
+LOCAL(boolean)
+jt_read_integer (const char ** strptr, JDIMENSION * result)
+{
+ const char * ptr = *strptr;
+ JDIMENSION val = 0;
+
+ for (; isdigit(*ptr); ptr++) {
+ val = val * 10 + (JDIMENSION) (*ptr - '0');
+ }
+ *result = val;
+ if (ptr == *strptr)
+ return FALSE; /* oops, no digits */
+ *strptr = ptr;
+ return TRUE;
+}
+
+
+/* Parse a crop specification (written in X11 geometry style).
+ * The routine returns TRUE if the spec string is valid, FALSE if not.
+ *
+ * The crop spec string should have the format
+ * <width>x<height>{+-}<xoffset>{+-}<yoffset>
+ * where width, height, xoffset, and yoffset are unsigned integers.
+ * Each of the elements can be omitted to indicate a default value.
+ * (A weakness of this style is that it is not possible to omit xoffset
+ * while specifying yoffset, since they look alike.)
+ *
+ * This code is loosely based on XParseGeometry from the X11 distribution.
+ */
+
+GLOBAL(boolean)
+jtransform_parse_crop_spec (jpeg_transform_info *info, const char *spec)
+{
+ info->crop = FALSE;
+ info->crop_width_set = JCROP_UNSET;
+ info->crop_height_set = JCROP_UNSET;
+ info->crop_xoffset_set = JCROP_UNSET;
+ info->crop_yoffset_set = JCROP_UNSET;
+
+ if (isdigit(*spec)) {
+ /* fetch width */
+ if (! jt_read_integer(&spec, &info->crop_width))
+ return FALSE;
+ info->crop_width_set = JCROP_POS;
+ }
+ if (*spec == 'x' || *spec == 'X') {
+ /* fetch height */
+ spec++;
+ if (! jt_read_integer(&spec, &info->crop_height))
+ return FALSE;
+ info->crop_height_set = JCROP_POS;
+ }
+ if (*spec == '+' || *spec == '-') {
+ /* fetch xoffset */
+ info->crop_xoffset_set = (*spec == '-') ? JCROP_NEG : JCROP_POS;
+ spec++;
+ if (! jt_read_integer(&spec, &info->crop_xoffset))
+ return FALSE;
+ }
+ if (*spec == '+' || *spec == '-') {
+ /* fetch yoffset */
+ info->crop_yoffset_set = (*spec == '-') ? JCROP_NEG : JCROP_POS;
+ spec++;
+ if (! jt_read_integer(&spec, &info->crop_yoffset))
+ return FALSE;
+ }
+ /* We had better have gotten to the end of the string. */
+ if (*spec != '\0')
+ return FALSE;
+ info->crop = TRUE;
+ return TRUE;
+}
+
+
+/* Trim off any partial iMCUs on the indicated destination edge */
+
+LOCAL(void)
+trim_right_edge (jpeg_transform_info *info, JDIMENSION full_width)
+{
+ JDIMENSION MCU_cols;
+
+ MCU_cols = info->output_width / (info->max_h_samp_factor * DCTSIZE);
+ if (MCU_cols > 0 && info->x_crop_offset + MCU_cols ==
+ full_width / (info->max_h_samp_factor * DCTSIZE))
+ info->output_width = MCU_cols * (info->max_h_samp_factor * DCTSIZE);
+}
+
+LOCAL(void)
+trim_bottom_edge (jpeg_transform_info *info, JDIMENSION full_height)
+{
+ JDIMENSION MCU_rows;
+
+ MCU_rows = info->output_height / (info->max_v_samp_factor * DCTSIZE);
+ if (MCU_rows > 0 && info->y_crop_offset + MCU_rows ==
+ full_height / (info->max_v_samp_factor * DCTSIZE))
+ info->output_height = MCU_rows * (info->max_v_samp_factor * DCTSIZE);
+}
+
+
+/* Request any required workspace.
+ *
+ * This routine figures out the size that the output image will be
+ * (which implies that all the transform parameters must be set before
+ * it is called).
+ *
+ * We allocate the workspace virtual arrays from the source decompression
+ * object, so that all the arrays (both the original data and the workspace)
+ * will be taken into account while making memory management decisions.
+ * Hence, this routine must be called after jpeg_read_header (which reads
+ * the image dimensions) and before jpeg_read_coefficients (which realizes
+ * the source's virtual arrays).
+ */
+
+GLOBAL(void)
+jtransform_request_workspace (j_decompress_ptr srcinfo,
+ jpeg_transform_info *info)
+{
+ jvirt_barray_ptr *coef_arrays = NULL;
+ boolean need_workspace, transpose_it;
+ jpeg_component_info *compptr;
+ JDIMENSION xoffset, yoffset, dtemp, width_in_iMCUs, height_in_iMCUs;
+ JDIMENSION width_in_data_units, height_in_data_units;
+ int itemp, ci, h_samp_factor, v_samp_factor;
+
+ /* Determine number of components in output image */
+ if (info->force_grayscale &&
+ srcinfo->jpeg_color_space == JCS_YCbCr &&
+ srcinfo->num_components == 3) {
+ /* We'll only process the first component */
+ info->num_components = 1;
+ } else {
+ /* Process all the components */
+ info->num_components = srcinfo->num_components;
+ }
+ /* If there is only one output component, force the iMCU size to be 1;
+ * else use the source iMCU size. (This allows us to do the right thing
+ * when reducing color to grayscale, and also provides a handy way of
+ * cleaning up "funny" grayscale images whose sampling factors are not 1x1.)
+ */
+
+ switch (info->transform) {
+ case JXFORM_TRANSPOSE:
+ case JXFORM_TRANSVERSE:
+ case JXFORM_ROT_90:
+ case JXFORM_ROT_270:
+ info->output_width = srcinfo->image_height;
+ info->output_height = srcinfo->image_width;
+ if (info->num_components == 1) {
+ info->max_h_samp_factor = 1;
+ info->max_v_samp_factor = 1;
+ } else {
+ info->max_h_samp_factor = srcinfo->max_v_samp_factor;
+ info->max_v_samp_factor = srcinfo->max_h_samp_factor;
+ }
+ break;
+ default:
+ info->output_width = srcinfo->image_width;
+ info->output_height = srcinfo->image_height;
+ if (info->num_components == 1) {
+ info->max_h_samp_factor = 1;
+ info->max_v_samp_factor = 1;
+ } else {
+ info->max_h_samp_factor = srcinfo->max_h_samp_factor;
+ info->max_v_samp_factor = srcinfo->max_v_samp_factor;
+ }
+ break;
+ }
+
+ /* If cropping has been requested, compute the crop area's position and
+ * dimensions, ensuring that its upper left corner falls at an iMCU boundary.
+ */
+ if (info->crop) {
+ /* Insert default values for unset crop parameters */
+ if (info->crop_xoffset_set == JCROP_UNSET)
+ info->crop_xoffset = 0; /* default to +0 */
+ if (info->crop_yoffset_set == JCROP_UNSET)
+ info->crop_yoffset = 0; /* default to +0 */
+ if (info->crop_width_set == JCROP_UNSET) {
+ if (info->crop_xoffset >= info->output_width)
+ ERREXIT(srcinfo, JERR_BAD_CROP_SPEC);
+ info->crop_width = info->output_width - info->crop_xoffset;
+ } else {
+ /* Check for crop extension */
+ if (info->crop_width > info->output_width) {
+ /* Crop extension does not work when transforming! */
+ if (info->transform != JXFORM_NONE ||
+ info->crop_xoffset >= info->crop_width ||
+ info->crop_xoffset > info->crop_width - info->output_width)
+ ERREXIT(srcinfo, JERR_BAD_CROP_SPEC);
+ } else {
+ if (info->crop_xoffset >= info->output_width ||
+ info->crop_width <= 0 ||
+ info->crop_xoffset > info->output_width - info->crop_width)
+ ERREXIT(srcinfo, JERR_BAD_CROP_SPEC);
+ }
+ }
+ if (info->crop_height_set == JCROP_UNSET) {
+ if (info->crop_yoffset >= info->output_height)
+ ERREXIT(srcinfo, JERR_BAD_CROP_SPEC);
+ info->crop_height = info->output_height - info->crop_yoffset;
+ } else {
+ /* Check for crop extension */
+ if (info->crop_height > info->output_height) {
+ /* Crop extension does not work when transforming! */
+ if (info->transform != JXFORM_NONE ||
+ info->crop_yoffset >= info->crop_height ||
+ info->crop_yoffset > info->crop_height - info->output_height)
+ ERREXIT(srcinfo, JERR_BAD_CROP_SPEC);
+ } else {
+ if (info->crop_yoffset >= info->output_height ||
+ info->crop_height <= 0 ||
+ info->crop_yoffset > info->output_height - info->crop_height)
+ ERREXIT(srcinfo, JERR_BAD_CROP_SPEC);
+ }
+ }
+ /* Convert negative crop offsets into regular offsets */
+ if (info->crop_xoffset_set == JCROP_NEG) {
+ if (info->crop_width > info->output_width)
+ xoffset = info->crop_width - info->output_width - info->crop_xoffset;
+ else
+ xoffset = info->output_width - info->crop_width - info->crop_xoffset;
+ } else
+ xoffset = info->crop_xoffset;
+ if (info->crop_yoffset_set == JCROP_NEG) {
+ if (info->crop_height > info->output_height)
+ yoffset = info->crop_height - info->output_height - info->crop_yoffset;
+ else
+ yoffset = info->output_height - info->crop_height - info->crop_yoffset;
+ } else
+ yoffset = info->crop_yoffset;
+ /* Now adjust so that upper left corner falls at an iMCU boundary */
+ if (info->transform == JXFORM_DROP) {
+ /* Ensure the effective drop region will not exceed the requested */
+ itemp = info->max_h_samp_factor * DCTSIZE;
+ dtemp = itemp - 1 - ((xoffset + itemp - 1) % itemp);
+ xoffset += dtemp;
+ if (info->crop_width > dtemp)
+ info->drop_width = (info->crop_width - dtemp) / itemp;
+ else
+ info->drop_width = 0;
+ itemp = info->max_v_samp_factor * DCTSIZE;
+ dtemp = itemp - 1 - ((yoffset + itemp - 1) % itemp);
+ yoffset += dtemp;
+ if (info->crop_height > dtemp)
+ info->drop_height = (info->crop_height - dtemp) / itemp;
+ else
+ info->drop_height = 0;
+ /* Check if sampling factors match for dropping */
+ if (info->drop_width != 0 && info->drop_height != 0)
+ for (ci = 0; ci < info->num_components &&
+ ci < info->drop_ptr->num_components; ci++) {
+ if (info->drop_ptr->comp_info[ci].h_samp_factor *
+ srcinfo->max_h_samp_factor !=
+ srcinfo->comp_info[ci].h_samp_factor *
+ info->drop_ptr->max_h_samp_factor)
+ ERREXIT6(srcinfo, JERR_BAD_DROP_SAMPLING, ci,
+ info->drop_ptr->comp_info[ci].h_samp_factor,
+ info->drop_ptr->max_h_samp_factor,
+ srcinfo->comp_info[ci].h_samp_factor,
+ srcinfo->max_h_samp_factor, 'h');
+ if (info->drop_ptr->comp_info[ci].v_samp_factor *
+ srcinfo->max_v_samp_factor !=
+ srcinfo->comp_info[ci].v_samp_factor *
+ info->drop_ptr->max_v_samp_factor)
+ ERREXIT6(srcinfo, JERR_BAD_DROP_SAMPLING, ci,
+ info->drop_ptr->comp_info[ci].v_samp_factor,
+ info->drop_ptr->max_v_samp_factor,
+ srcinfo->comp_info[ci].v_samp_factor,
+ srcinfo->max_v_samp_factor, 'v');
+ }
+ } else {
+ /* Ensure the effective crop region will cover the requested */
+ if (info->crop_width > info->output_width)
+ info->output_width = info->crop_width;
+ else
+ info->output_width =
+ info->crop_width + (xoffset % (info->max_h_samp_factor * DCTSIZE));
+ if (info->crop_height > info->output_height)
+ info->output_height = info->crop_height;
+ else
+ info->output_height =
+ info->crop_height + (yoffset % (info->max_v_samp_factor * DCTSIZE));
+ }
+ /* Save x/y offsets measured in iMCUs */
+ info->x_crop_offset = xoffset / (info->max_h_samp_factor * DCTSIZE);
+ info->y_crop_offset = yoffset / (info->max_v_samp_factor * DCTSIZE);
+ } else {
+ info->x_crop_offset = 0;
+ info->y_crop_offset = 0;
+ }
+
+ /* Figure out whether we need workspace arrays,
+ * and if so whether they are transposed relative to the source.
+ */
+ need_workspace = FALSE;
+ transpose_it = FALSE;
+ switch (info->transform) {
+ case JXFORM_NONE:
+ if (info->x_crop_offset != 0 || info->y_crop_offset != 0 ||
+ info->output_width > srcinfo->image_width ||
+ info->output_height > srcinfo->image_height)
+ need_workspace = TRUE;
+ /* No workspace needed if neither cropping nor transforming */
+ break;
+ case JXFORM_FLIP_H:
+ if (info->trim)
+ trim_right_edge(info, srcinfo->image_width);
+ if (info->y_crop_offset != 0)
+ need_workspace = TRUE;
+ /* do_flip_h_no_crop doesn't need a workspace array */
+ break;
+ case JXFORM_FLIP_V:
+ if (info->trim)
+ trim_bottom_edge(info, srcinfo->image_height);
+ /* Need workspace arrays having same dimensions as source image. */
+ need_workspace = TRUE;
+ break;
+ case JXFORM_TRANSPOSE:
+ /* transpose does NOT have to trim anything */
+ /* Need workspace arrays having transposed dimensions. */
+ need_workspace = TRUE;
+ transpose_it = TRUE;
+ break;
+ case JXFORM_TRANSVERSE:
+ if (info->trim) {
+ trim_right_edge(info, srcinfo->image_height);
+ trim_bottom_edge(info, srcinfo->image_width);
+ }
+ /* Need workspace arrays having transposed dimensions. */
+ need_workspace = TRUE;
+ transpose_it = TRUE;
+ break;
+ case JXFORM_ROT_90:
+ if (info->trim)
+ trim_right_edge(info, srcinfo->image_height);
+ /* Need workspace arrays having transposed dimensions. */
+ need_workspace = TRUE;
+ transpose_it = TRUE;
+ break;
+ case JXFORM_ROT_180:
+ if (info->trim) {
+ trim_right_edge(info, srcinfo->image_width);
+ trim_bottom_edge(info, srcinfo->image_height);
+ }
+ /* Need workspace arrays having same dimensions as source image. */
+ need_workspace = TRUE;
+ break;
+ case JXFORM_ROT_270:
+ if (info->trim)
+ trim_bottom_edge(info, srcinfo->image_width);
+ /* Need workspace arrays having transposed dimensions. */
+ need_workspace = TRUE;
+ transpose_it = TRUE;
+ break;
+ case JXFORM_DROP:
+#if DROP_REQUEST_FROM_SRC
+ drop_request_from_src(info->drop_ptr, srcinfo);
+#endif
+ break;
+ }
+
+ /* Allocate workspace if needed.
+ * Note that we allocate arrays padded out to the next iMCU boundary,
+ * so that transform routines need not worry about missing edge blocks.
+ */
+ if (need_workspace) {
+ coef_arrays = (jvirt_barray_ptr *)
+ (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
+ SIZEOF(jvirt_barray_ptr) * info->num_components);
+ width_in_iMCUs = (JDIMENSION)
+ jdiv_round_up((long) info->output_width,
+ (long) (info->max_h_samp_factor * DCTSIZE));
+ height_in_iMCUs = (JDIMENSION)
+ jdiv_round_up((long) info->output_height,
+ (long) (info->max_v_samp_factor * DCTSIZE));
+ for (ci = 0; ci < info->num_components; ci++) {
+ compptr = srcinfo->comp_info + ci;
+ if (info->num_components == 1) {
+ /* we're going to force samp factors to 1x1 in this case */
+ h_samp_factor = v_samp_factor = 1;
+ } else if (transpose_it) {
+ h_samp_factor = compptr->v_samp_factor;
+ v_samp_factor = compptr->h_samp_factor;
+ } else {
+ h_samp_factor = compptr->h_samp_factor;
+ v_samp_factor = compptr->v_samp_factor;
+ }
+ width_in_data_units = width_in_iMCUs * h_samp_factor;
+ height_in_data_units = height_in_iMCUs * v_samp_factor;
+ coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
+ ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
+ width_in_data_units * SIZEOF(JSAMPLE16), height_in_data_units, (JDIMENSION) v_samp_factor);
+ }
+ }
+
+ info->workspace_coef_arrays = coef_arrays;
+}
+
+
+/* Transpose destination image parameters */
+
+LOCAL(void)
+transpose_critical_parameters (j_compress_ptr dstinfo)
+{
+ int tblno, i, j, ci, itemp;
+ jpeg_component_info *compptr;
+ JQUANT_TBL *qtblptr;
+ UINT16 qtemp;
+
+ /* Transpose sampling factors */
+ for (ci = 0; ci < dstinfo->num_components; ci++) {
+ compptr = dstinfo->comp_info + ci;
+ itemp = compptr->h_samp_factor;
+ compptr->h_samp_factor = compptr->v_samp_factor;
+ compptr->v_samp_factor = itemp;
+ }
+
+ /* Transpose quantization tables */
+ for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
+ qtblptr = dstinfo->quant_tbl_ptrs[tblno];
+ if (qtblptr != NULL) {
+ for (i = 0; i < DCTSIZE; i++) {
+ for (j = 0; j < i; j++) {
+ qtemp = qtblptr->quantval[i*DCTSIZE+j];
+ qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
+ qtblptr->quantval[j*DCTSIZE+i] = qtemp;
+ }
+ }
+ }
+ }
+}
+
+
+/* Adjust Exif image parameters.
+ *
+ * We try to adjust the Tags ExifImageWidth and ExifImageHeight if possible.
+ */
+
+LOCAL(void)
+adjust_exif_parameters (JOCTET FAR * data, unsigned int length,
+ JDIMENSION new_width, JDIMENSION new_height)
+{
+ boolean is_motorola; /* Flag for byte order */
+ unsigned int number_of_tags, tagnum;
+ unsigned int firstoffset, offset;
+ JDIMENSION new_value;
+
+ if (length < 12) return; /* Length of an IFD entry */
+
+ /* Discover byte order */
+ if (GETJOCTET(data[0]) == 0x49 && GETJOCTET(data[1]) == 0x49)
+ is_motorola = FALSE;
+ else if (GETJOCTET(data[0]) == 0x4D && GETJOCTET(data[1]) == 0x4D)
+ is_motorola = TRUE;
+ else
+ return;
+
+ /* Check Tag Mark */
+ if (is_motorola) {
+ if (GETJOCTET(data[2]) != 0) return;
+ if (GETJOCTET(data[3]) != 0x2A) return;
+ } else {
+ if (GETJOCTET(data[3]) != 0) return;
+ if (GETJOCTET(data[2]) != 0x2A) return;
+ }
+
+ /* Get first IFD offset (offset to IFD0) */
+ if (is_motorola) {
+ if (GETJOCTET(data[4]) != 0) return;
+ if (GETJOCTET(data[5]) != 0) return;
+ firstoffset = GETJOCTET(data[6]);
+ firstoffset <<= 8;
+ firstoffset += GETJOCTET(data[7]);
+ } else {
+ if (GETJOCTET(data[7]) != 0) return;
+ if (GETJOCTET(data[6]) != 0) return;
+ firstoffset = GETJOCTET(data[5]);
+ firstoffset <<= 8;
+ firstoffset += GETJOCTET(data[4]);
+ }
+ if (firstoffset > length - 2) return; /* check end of data segment */
+
+ /* Get the number of directory entries contained in this IFD */
+ if (is_motorola) {
+ number_of_tags = GETJOCTET(data[firstoffset]);
+ number_of_tags <<= 8;
+ number_of_tags += GETJOCTET(data[firstoffset+1]);
+ } else {
+ number_of_tags = GETJOCTET(data[firstoffset+1]);
+ number_of_tags <<= 8;
+ number_of_tags += GETJOCTET(data[firstoffset]);
+ }
+ if (number_of_tags == 0) return;
+ firstoffset += 2;
+
+ /* Search for ExifSubIFD offset Tag in IFD0 */
+ for (;;) {
+ if (firstoffset > length - 12) return; /* check end of data segment */
+ /* Get Tag number */
+ if (is_motorola) {
+ tagnum = GETJOCTET(data[firstoffset]);
+ tagnum <<= 8;
+ tagnum += GETJOCTET(data[firstoffset+1]);
+ } else {
+ tagnum = GETJOCTET(data[firstoffset+1]);
+ tagnum <<= 8;
+ tagnum += GETJOCTET(data[firstoffset]);
+ }
+ if (tagnum == 0x8769) break; /* found ExifSubIFD offset Tag */
+ if (--number_of_tags == 0) return;
+ firstoffset += 12;
+ }
+
+ /* Get the ExifSubIFD offset */
+ if (is_motorola) {
+ if (GETJOCTET(data[firstoffset+8]) != 0) return;
+ if (GETJOCTET(data[firstoffset+9]) != 0) return;
+ offset = GETJOCTET(data[firstoffset+10]);
+ offset <<= 8;
+ offset += GETJOCTET(data[firstoffset+11]);
+ } else {
+ if (GETJOCTET(data[firstoffset+11]) != 0) return;
+ if (GETJOCTET(data[firstoffset+10]) != 0) return;
+ offset = GETJOCTET(data[firstoffset+9]);
+ offset <<= 8;
+ offset += GETJOCTET(data[firstoffset+8]);
+ }
+ if (offset > length - 2) return; /* check end of data segment */
+
+ /* Get the number of directory entries contained in this SubIFD */
+ if (is_motorola) {
+ number_of_tags = GETJOCTET(data[offset]);
+ number_of_tags <<= 8;
+ number_of_tags += GETJOCTET(data[offset+1]);
+ } else {
+ number_of_tags = GETJOCTET(data[offset+1]);
+ number_of_tags <<= 8;
+ number_of_tags += GETJOCTET(data[offset]);
+ }
+ if (number_of_tags < 2) return;
+ offset += 2;
+
+ /* Search for ExifImageWidth and ExifImageHeight Tags in this SubIFD */
+ do {
+ if (offset > length - 12) return; /* check end of data segment */
+ /* Get Tag number */
+ if (is_motorola) {
+ tagnum = GETJOCTET(data[offset]);
+ tagnum <<= 8;
+ tagnum += GETJOCTET(data[offset+1]);
+ } else {
+ tagnum = GETJOCTET(data[offset+1]);
+ tagnum <<= 8;
+ tagnum += GETJOCTET(data[offset]);
+ }
+ if (tagnum == 0xA002 || tagnum == 0xA003) {
+ if (tagnum == 0xA002)
+ new_value = new_width; /* ExifImageWidth Tag */
+ else
+ new_value = new_height; /* ExifImageHeight Tag */
+ if (is_motorola) {
+ data[offset+2] = 0; /* Format = unsigned long (4 octets) */
+ data[offset+3] = 4;
+ data[offset+4] = 0; /* Number Of Components = 1 */
+ data[offset+5] = 0;
+ data[offset+6] = 0;
+ data[offset+7] = 1;
+ data[offset+8] = 0;
+ data[offset+9] = 0;
+ data[offset+10] = (JOCTET)((new_value >> 8) & 0xFF);
+ data[offset+11] = (JOCTET)(new_value & 0xFF);
+ } else {
+ data[offset+2] = 4; /* Format = unsigned long (4 octets) */
+ data[offset+3] = 0;
+ data[offset+4] = 1; /* Number Of Components = 1 */
+ data[offset+5] = 0;
+ data[offset+6] = 0;
+ data[offset+7] = 0;
+ data[offset+8] = (JOCTET)(new_value & 0xFF);
+ data[offset+9] = (JOCTET)((new_value >> 8) & 0xFF);
+ data[offset+10] = 0;
+ data[offset+11] = 0;
+ }
+ }
+ offset += 12;
+ } while (--number_of_tags);
+}
+
+
+/* Adjust output image parameters as needed.
+ *
+ * This must be called after jpeg_copy_critical_parameters()
+ * and before jpeg_write_coefficients().
+ *
+ * The return value is the set of virtual coefficient arrays to be written
+ * (either the ones allocated by jtransform_request_workspace, or the
+ * original source data arrays). The caller will need to pass this value
+ * to jpeg_write_coefficients().
+ */
+
+GLOBAL(jvirt_barray_ptr *)
+jtransform_adjust_parameters (j_decompress_ptr srcinfo,
+ j_compress_ptr dstinfo,
+ jvirt_barray_ptr *src_coef_arrays,
+ jpeg_transform_info *info)
+{
+ /* If force-to-grayscale is requested, adjust destination parameters */
+ if (info->force_grayscale) {
+ /* First, ensure we have YCbCr or grayscale data, and that the source's
+ * Y channel is full resolution. (No reasonable person would make Y
+ * be less than full resolution, so actually coping with that case
+ * isn't worth extra code space. But we check it to avoid crashing.)
+ */
+ if (((dstinfo->jpeg_color_space == JCS_YCbCr &&
+ dstinfo->num_components == 3) ||
+ (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
+ dstinfo->num_components == 1)) &&
+ srcinfo->comp_info[0].h_samp_factor == srcinfo->max_h_samp_factor &&
+ srcinfo->comp_info[0].v_samp_factor == srcinfo->max_v_samp_factor) {
+ /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
+ * properly. Among other things, it sets the target h_samp_factor &
+ * v_samp_factor to 1, which typically won't match the source.
+ * We have to preserve the source's quantization table number, however.
+ */
+ int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
+ jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
+ dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
+ } else {
+ /* Sorry, can't do it */
+ ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
+ }
+ } else if (info->num_components == 1) {
+ /* For a single-component source, we force the destination sampling factors
+ * to 1x1, with or without force_grayscale. This is useful because some
+ * decoders choke on grayscale images with other sampling factors.
+ */
+ dstinfo->comp_info[0].h_samp_factor = 1;
+ dstinfo->comp_info[0].v_samp_factor = 1;
+ }
+
+ /* Correct the destination's image dimensions etc as necessary
+ * for crop and rotate/flip operations.
+ */
+ dstinfo->image_width = info->output_width;
+ dstinfo->image_height = info->output_height;
+ switch (info->transform) {
+ case JXFORM_TRANSPOSE:
+ case JXFORM_TRANSVERSE:
+ case JXFORM_ROT_90:
+ case JXFORM_ROT_270:
+ transpose_critical_parameters(dstinfo);
+ break;
+ case JXFORM_DROP:
+ if (info->drop_width != 0 && info->drop_height != 0)
+ adjust_quant(srcinfo, src_coef_arrays,
+ info->drop_ptr, info->drop_coef_arrays,
+ info->trim, dstinfo);
+ default :
+ break;
+ }
+
+ /* Adjust Exif properties */
+ if (srcinfo->marker_list != NULL &&
+ srcinfo->marker_list->marker == JPEG_APP0+1 &&
+ srcinfo->marker_list->data_length >= 6 &&
+ GETJOCTET(srcinfo->marker_list->data[0]) == 0x45 &&
+ GETJOCTET(srcinfo->marker_list->data[1]) == 0x78 &&
+ GETJOCTET(srcinfo->marker_list->data[2]) == 0x69 &&
+ GETJOCTET(srcinfo->marker_list->data[3]) == 0x66 &&
+ GETJOCTET(srcinfo->marker_list->data[4]) == 0 &&
+ GETJOCTET(srcinfo->marker_list->data[5]) == 0) {
+ /* Suppress output of JFIF marker */
+ dstinfo->write_JFIF_header = FALSE;
+ /* Adjust Exif image parameters */
+ if (dstinfo->image_width != srcinfo->image_width ||
+ dstinfo->image_height != srcinfo->image_height)
+ /* Align data segment to start of TIFF structure for parsing */
+ adjust_exif_parameters(srcinfo->marker_list->data + 6,
+ srcinfo->marker_list->data_length - 6,
+ dstinfo->image_width, dstinfo->image_height);
+ }
+
+ /* Return the appropriate output data set */
+ if (info->workspace_coef_arrays != NULL)
+ return info->workspace_coef_arrays;
+ return src_coef_arrays;
+}
+
+
+/* Execute the actual transformation, if any.
+ *
+ * This must be called *after* jpeg_write_coefficients, because it depends
+ * on jpeg_write_coefficients to have computed subsidiary values such as
+ * the per-component width and height fields in the destination object.
+ *
+ * Note that some transformations will modify the source data arrays!
+ */
+
+GLOBAL(void)
+jtransform_execute_transform (j_decompress_ptr srcinfo,
+ j_compress_ptr dstinfo,
+ jvirt_barray_ptr *src_coef_arrays,
+ jpeg_transform_info *info)
+{
+ jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
+
+ /* Note: conditions tested here should match those in switch statement
+ * in jtransform_request_workspace()
+ */
+ switch (info->transform) {
+ case JXFORM_NONE:
+ if (info->x_crop_offset != 0 || info->y_crop_offset != 0 ||
+ info->output_width > srcinfo->image_width ||
+ info->output_height > srcinfo->image_height)
+ do_crop(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset,
+ src_coef_arrays, dst_coef_arrays);
+ break;
+ case JXFORM_FLIP_H:
+ if (info->y_crop_offset != 0)
+ do_flip_h(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset,
+ src_coef_arrays, dst_coef_arrays);
+ else
+ do_flip_h_no_crop(srcinfo, dstinfo, info->x_crop_offset,
+ src_coef_arrays);
+ break;
+ case JXFORM_FLIP_V:
+ do_flip_v(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset,
+ src_coef_arrays, dst_coef_arrays);
+ break;
+ case JXFORM_TRANSPOSE:
+ do_transpose(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset,
+ src_coef_arrays, dst_coef_arrays);
+ break;
+ case JXFORM_TRANSVERSE:
+ do_transverse(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset,
+ src_coef_arrays, dst_coef_arrays);
+ break;
+ case JXFORM_ROT_90:
+ do_rot_90(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset,
+ src_coef_arrays, dst_coef_arrays);
+ break;
+ case JXFORM_ROT_180:
+ do_rot_180(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset,
+ src_coef_arrays, dst_coef_arrays);
+ break;
+ case JXFORM_ROT_270:
+ do_rot_270(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset,
+ src_coef_arrays, dst_coef_arrays);
+ break;
+ case JXFORM_DROP:
+ if (info->drop_width != 0 && info->drop_height != 0)
+ do_drop(srcinfo, dstinfo, info->x_crop_offset, info->y_crop_offset,
+ src_coef_arrays, info->drop_ptr, info->drop_coef_arrays,
+ info->drop_width, info->drop_height);
+ default :
+ break;
+ }
+}
+
+/* jtransform_perfect_transform
+ *
+ * Determine whether lossless transformation is perfectly
+ * possible for a specified image and transformation.
+ *
+ * Inputs:
+ * image_width, image_height: source image dimensions.
+ * MCU_width, MCU_height: pixel dimensions of MCU.
+ * transform: transformation identifier.
+ * Parameter sources from initialized jpeg_struct
+ * (after reading source header):
+ * image_width = cinfo.image_width
+ * image_height = cinfo.image_height
+ * MCU_width = cinfo.max_h_samp_factor * DCTSIZE
+ * MCU_height = cinfo.max_v_samp_factor * DCTSIZE
+ * Result:
+ * TRUE = perfect transformation possible
+ * FALSE = perfect transformation not possible
+ * (may use custom action then)
+ */
+
+GLOBAL(boolean)
+jtransform_perfect_transform(JDIMENSION image_width, JDIMENSION image_height,
+ int MCU_width, int MCU_height,
+ JXFORM_CODE transform)
+{
+ boolean result = TRUE; /* initialize TRUE */
+
+ switch (transform) {
+ case JXFORM_FLIP_H:
+ case JXFORM_ROT_270:
+ if (image_width % (JDIMENSION) MCU_width)
+ result = FALSE;
+ break;
+ case JXFORM_FLIP_V:
+ case JXFORM_ROT_90:
+ if (image_height % (JDIMENSION) MCU_height)
+ result = FALSE;
+ break;
+ case JXFORM_TRANSVERSE:
+ case JXFORM_ROT_180:
+ if (image_width % (JDIMENSION) MCU_width)
+ result = FALSE;
+ if (image_height % (JDIMENSION) MCU_height)
+ result = FALSE;
+ default :
+ break;
+ }
+
+ return result;
+}
+
+#endif /* TRANSFORMS_SUPPORTED */
+
+
+/* Setup decompression object to save desired markers in memory.
+ * This must be called before jpeg_read_header() to have the desired effect.
+ */
+
+GLOBAL(void)
+jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
+{
+#ifdef SAVE_MARKERS_SUPPORTED
+ int m;
+
+ /* Save comments except under NONE option */
+ if (option != JCOPYOPT_NONE) {
+ jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
+ }
+ /* Save all types of APPn markers iff ALL option */
+ if (option == JCOPYOPT_ALL) {
+ for (m = 0; m < 16; m++)
+ jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
+ }
+#endif /* SAVE_MARKERS_SUPPORTED */
+}
+
+/* Copy markers saved in the given source object to the destination object.
+ * This should be called just after jpeg_start_compress() or
+ * jpeg_write_coefficients().
+ * Note that those routines will have written the SOI, and also the
+ * JFIF APP0 or Adobe APP14 markers if selected.
+ */
+
+GLOBAL(void)
+jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ JCOPY_OPTION option)
+{
+ jpeg_saved_marker_ptr marker;
+
+ /* In the current implementation, we don't actually need to examine the
+ * option flag here; we just copy everything that got saved.
+ * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
+ * if the encoder library already wrote one.
+ */
+ for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
+ if (dstinfo->write_JFIF_header &&
+ marker->marker == JPEG_APP0 &&
+ marker->data_length >= 5 &&
+ GETJOCTET(marker->data[0]) == 0x4A &&
+ GETJOCTET(marker->data[1]) == 0x46 &&
+ GETJOCTET(marker->data[2]) == 0x49 &&
+ GETJOCTET(marker->data[3]) == 0x46 &&
+ GETJOCTET(marker->data[4]) == 0)
+ continue; /* reject duplicate JFIF */
+ if (dstinfo->write_Adobe_marker &&
+ marker->marker == JPEG_APP0+14 &&
+ marker->data_length >= 5 &&
+ GETJOCTET(marker->data[0]) == 0x41 &&
+ GETJOCTET(marker->data[1]) == 0x64 &&
+ GETJOCTET(marker->data[2]) == 0x6F &&
+ GETJOCTET(marker->data[3]) == 0x62 &&
+ GETJOCTET(marker->data[4]) == 0x65)
+ continue; /* reject duplicate Adobe */
+#ifdef NEED_FAR_POINTERS
+ /* We could use jpeg_write_marker if the data weren't FAR... */
+ {
+ unsigned int i;
+ jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
+ for (i = 0; i < marker->data_length; i++)
+ jpeg_write_m_byte(dstinfo, marker->data[i]);
+ }
+#else
+ jpeg_write_marker(dstinfo, marker->marker,
+ marker->data, marker->data_length);
+#endif
+ }
+}
diff --git a/jpeg-6c/transupp.h b/jpeg-6c/transupp.h
new file mode 100644
index 0000000..2ca033b
--- /dev/null
+++ b/jpeg-6c/transupp.h
@@ -0,0 +1,212 @@
+/*
+ * transupp.h
+ *
+ * Copyright (C) 1997-2001, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains declarations for image transformation routines and
+ * other utility code used by the jpegtran sample application. These are
+ * NOT part of the core JPEG library. But we keep these routines separate
+ * from jpegtran.c to ease the task of maintaining jpegtran-like programs
+ * that have other user interfaces.
+ *
+ * NOTE: all the routines declared here have very specific requirements
+ * about when they are to be executed during the reading and writing of the
+ * source and destination files. See the comments in transupp.c, or see
+ * jpegtran.c for an example of correct usage.
+ */
+
+/* If you happen not to want the image transform support, disable it here */
+#ifndef TRANSFORMS_SUPPORTED
+#define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
+#endif
+
+/*
+ * Although rotating and flipping data expressed as DCT coefficients is not
+ * hard, there is an asymmetry in the JPEG format specification for images
+ * whose dimensions aren't multiples of the iMCU size. The right and bottom
+ * image edges are padded out to the next iMCU boundary with junk data; but
+ * no padding is possible at the top and left edges. If we were to flip
+ * the whole image including the pad data, then pad garbage would become
+ * visible at the top and/or left, and real pixels would disappear into the
+ * pad margins --- perhaps permanently, since encoders & decoders may not
+ * bother to preserve DCT blocks that appear to be completely outside the
+ * nominal image area. So, we have to exclude any partial iMCUs from the
+ * basic transformation.
+ *
+ * Transpose is the only transformation that can handle partial iMCUs at the
+ * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
+ * at the bottom, but leaves any partial iMCUs at the right edge untouched.
+ * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
+ * The other transforms are defined as combinations of these basic transforms
+ * and process edge blocks in a way that preserves the equivalence.
+ *
+ * The "trim" option causes untransformable partial iMCUs to be dropped;
+ * this is not strictly lossless, but it usually gives the best-looking
+ * result for odd-size images. Note that when this option is active,
+ * the expected mathematical equivalences between the transforms may not hold.
+ * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
+ * followed by -rot 180 -trim trims both edges.)
+ *
+ * We also offer a lossless-crop option, which discards data outside a given
+ * image region but losslessly preserves what is inside. Like the rotate and
+ * flip transforms, lossless crop is restricted by the JPEG format: the upper
+ * left corner of the selected region must fall on an iMCU boundary. If this
+ * does not hold for the given crop parameters, we silently move the upper left
+ * corner up and/or left to make it so, simultaneously increasing the region
+ * dimensions to keep the lower right crop corner unchanged. (Thus, the
+ * output image covers at least the requested region, but may cover more.)
+ *
+ * If both crop and a rotate/flip transform are requested, the crop is applied
+ * last --- that is, the crop region is specified in terms of the destination
+ * image.
+ *
+ * We also offer a "force to grayscale" option, which simply discards the
+ * chrominance channels of a YCbCr image. This is lossless in the sense that
+ * the luminance channel is preserved exactly. It's not the same kind of
+ * thing as the rotate/flip transformations, but it's convenient to handle it
+ * as part of this package, mainly because the transformation routines have to
+ * be aware of the option to know how many components to work on.
+ */
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jtransform_parse_crop_spec jTrParCrop
+#define jtransform_request_workspace jTrRequest
+#define jtransform_adjust_parameters jTrAdjust
+#define jtransform_execute_transform jTrExec
+#define jtransform_perfect_transform jTrPerfect
+#define jcopy_markers_setup jCMrkSetup
+#define jcopy_markers_execute jCMrkExec
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/*
+ * Codes for supported types of image transformations.
+ */
+
+typedef enum {
+ JXFORM_NONE, /* no transformation, crop */
+ JXFORM_FLIP_H, /* horizontal flip */
+ JXFORM_FLIP_V, /* vertical flip */
+ JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
+ JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
+ JXFORM_ROT_90, /* 90-degree clockwise rotation */
+ JXFORM_ROT_180, /* 180-degree rotation */
+ JXFORM_ROT_270, /* 270-degree clockwise (or 90 ccw) */
+ JXFORM_DROP /* drop */
+} JXFORM_CODE;
+
+/*
+ * Codes for crop parameters, which can individually be unspecified,
+ * positive, or negative. (Negative width or height makes no sense, though.)
+ */
+
+typedef enum {
+ JCROP_UNSET,
+ JCROP_POS,
+ JCROP_NEG
+} JCROP_CODE;
+
+/*
+ * Transform parameters struct.
+ * NB: application must not change any elements of this struct after
+ * calling jtransform_request_workspace.
+ */
+
+typedef struct {
+ /* Options: set by caller */
+ JXFORM_CODE transform; /* image transform operator */
+ boolean perfect; /* if TRUE, fail if partial MCUs are requested */
+ boolean trim; /* if TRUE, trim partial MCUs as needed */
+ boolean force_grayscale; /* if TRUE, convert color image to grayscale */
+ boolean crop; /* if TRUE, crop source image */
+
+ /* Crop parameters: application need not set these unless crop is TRUE.
+ * These can be filled in by jtransform_parse_crop_spec().
+ */
+ JDIMENSION crop_width; /* Width of selected region */
+ JCROP_CODE crop_width_set;
+ JDIMENSION crop_height; /* Height of selected region */
+ JCROP_CODE crop_height_set;
+ JDIMENSION crop_xoffset; /* X offset of selected region */
+ JCROP_CODE crop_xoffset_set; /* (negative measures from right edge) */
+ JDIMENSION crop_yoffset; /* Y offset of selected region */
+ JCROP_CODE crop_yoffset_set; /* (negative measures from bottom edge) */
+
+ /* Drop parameters: set by caller for drop request */
+ j_decompress_ptr drop_ptr;
+ jvirt_barray_ptr * drop_coef_arrays;
+
+ /* Internal workspace: caller should not touch these */
+ int num_components; /* # of components in workspace */
+ jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
+ JDIMENSION output_width; /* cropped destination dimensions */
+ JDIMENSION output_height;
+ JDIMENSION x_crop_offset; /* destination crop offsets measured in iMCUs */
+ JDIMENSION y_crop_offset;
+ JDIMENSION drop_width; /* drop dimensions measured in iMCUs */
+ JDIMENSION drop_height;
+ int max_h_samp_factor; /* destination iMCU size */
+ int max_v_samp_factor;
+} jpeg_transform_info;
+
+
+#if TRANSFORMS_SUPPORTED
+
+/* Parse a crop specification (written in X11 geometry style) */
+EXTERN(boolean) jtransform_parse_crop_spec
+ JPP((jpeg_transform_info *info, const char *spec));
+/* Request any required workspace */
+EXTERN(void) jtransform_request_workspace
+ JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
+/* Adjust output image parameters and return output coefficient arrays */
+EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
+ JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ jvirt_barray_ptr *src_coef_arrays,
+ jpeg_transform_info *info));
+/* Execute the actual transformation, if any */
+EXTERN(void) jtransform_execute_transform
+ JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ jvirt_barray_ptr *src_coef_arrays,
+ jpeg_transform_info *info));
+/* Determine whether lossless transformation is perfectly
+ * possible for a specified image and transformation.
+ */
+EXTERN(boolean) jtransform_perfect_transform
+ JPP((JDIMENSION image_width, JDIMENSION image_height,
+ int MCU_width, int MCU_height,
+ JXFORM_CODE transform));
+
+/* jtransform_execute_transform used to be called
+ * jtransform_execute_transformation, but some compilers complain about
+ * routine names that long. This macro is here to avoid breaking any
+ * old source code that uses the original name...
+ */
+#define jtransform_execute_transformation jtransform_execute_transform
+
+#endif /* TRANSFORMS_SUPPORTED */
+
+
+/*
+ * Support for copying optional markers from source to destination file.
+ */
+
+typedef enum {
+ JCOPYOPT_NONE, /* copy no optional markers */
+ JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
+ JCOPYOPT_ALL /* copy all optional markers */
+} JCOPY_OPTION;
+
+#define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
+
+/* Setup decompression object to save desired markers in memory */
+EXTERN(void) jcopy_markers_setup
+ JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
+/* Copy markers saved in the given source object to the destination object */
+EXTERN(void) jcopy_markers_execute
+ JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
+ JCOPY_OPTION option));
diff --git a/jpeg-6c/usage.doc b/jpeg-6c/usage.doc
new file mode 100644
index 0000000..8c4970a
--- /dev/null
+++ b/jpeg-6c/usage.doc
@@ -0,0 +1,562 @@
+USAGE instructions for the Independent JPEG Group's JPEG software
+=================================================================
+
+This file describes usage of the JPEG conversion programs cjpeg and djpeg,
+as well as the utility programs jpegtran, rdjpgcom and wrjpgcom. (See
+the other documentation files if you wish to use the JPEG library within
+your own programs.)
+
+If you are on a Unix machine you may prefer to read the Unix-style manual
+pages in files cjpeg.1, djpeg.1, jpegtran.1, rdjpgcom.1, wrjpgcom.1.
+
+
+INTRODUCTION
+
+These programs implement JPEG image compression and decompression. JPEG
+(pronounced "jay-peg") is a standardized compression method for full-color
+and gray-scale images. JPEG is designed to handle "real-world" scenes,
+for example scanned photographs. Cartoons, line drawings, and other
+non-realistic images are not JPEG's strong suit; on that sort of material
+you may get poor image quality and/or little compression.
+
+JPEG is lossy, meaning that the output image is not necessarily identical to
+the input image. Hence you should not use JPEG if you have to have identical
+output bits. However, on typical real-world images, very good compression
+levels can be obtained with no visible change, and amazingly high compression
+is possible if you can tolerate a low-quality image. You can trade off image
+quality against file size by adjusting the compressor's "quality" setting.
+
+
+GENERAL USAGE
+
+We provide two programs, cjpeg to compress an image file into JPEG format,
+and djpeg to decompress a JPEG file back into a conventional image format.
+
+On Unix-like systems, you say:
+ cjpeg [switches] [imagefile] >jpegfile
+or
+ djpeg [switches] [jpegfile] >imagefile
+The programs read the specified input file, or standard input if none is
+named. They always write to standard output (with trace/error messages to
+standard error). These conventions are handy for piping images between
+programs.
+
+On most non-Unix systems, you say:
+ cjpeg [switches] imagefile jpegfile
+or
+ djpeg [switches] jpegfile imagefile
+i.e., both the input and output files are named on the command line. This
+style is a little more foolproof, and it loses no functionality if you don't
+have pipes. (You can get this style on Unix too, if you prefer, by defining
+TWO_FILE_COMMANDLINE when you compile the programs; see install.doc.)
+
+You can also say:
+ cjpeg [switches] -outfile jpegfile imagefile
+or
+ djpeg [switches] -outfile imagefile jpegfile
+This syntax works on all systems, so it is useful for scripts.
+
+The currently supported image file formats are: PPM (PBMPLUS color format),
+PGM (PBMPLUS gray-scale format), BMP, Targa, and RLE (Utah Raster Toolkit
+format). (RLE is supported only if the URT library is available.)
+cjpeg recognizes the input image format automatically, with the exception
+of some Targa-format files. You have to tell djpeg which format to generate.
+
+JPEG files are in the defacto standard JFIF file format. There are other,
+less widely used JPEG-based file formats, but we don't support them.
+
+All switch names may be abbreviated; for example, -grayscale may be written
+-gray or -gr. Most of the "basic" switches can be abbreviated to as little as
+one letter. Upper and lower case are equivalent (-BMP is the same as -bmp).
+British spellings are also accepted (e.g., -greyscale), though for brevity
+these are not mentioned below.
+
+
+CJPEG DETAILS
+
+The basic command line switches for cjpeg are:
+
+ -quality N Scale quantization tables to adjust image quality.
+ Quality is 0 (worst) to 100 (best); default is 75.
+ (See below for more info.)
+
+ -grayscale Create monochrome JPEG file from color input.
+ Be sure to use this switch when compressing a grayscale
+ BMP file, because cjpeg isn't bright enough to notice
+ whether a BMP file uses only shades of gray. By
+ saying -grayscale, you'll get a smaller JPEG file that
+ takes less time to process.
+
+ -optimize Perform optimization of entropy encoding parameters.
+ Without this, default encoding parameters are used.
+ -optimize usually makes the JPEG file a little smaller,
+ but cjpeg runs somewhat slower and needs much more
+ memory. Image quality and speed of decompression are
+ unaffected by -optimize.
+
+ -progressive Create progressive JPEG file (see below).
+
+ -targa Input file is Targa format. Targa files that contain
+ an "identification" field will not be automatically
+ recognized by cjpeg; for such files you must specify
+ -targa to make cjpeg treat the input as Targa format.
+ For most Targa files, you won't need this switch.
+
+The -quality switch lets you trade off compressed file size against quality of
+the reconstructed image: the higher the quality setting, the larger the JPEG
+file, and the closer the output image will be to the original input. Normally
+you want to use the lowest quality setting (smallest file) that decompresses
+into something visually indistinguishable from the original image. For this
+purpose the quality setting should be between 50 and 95; the default of 75 is
+often about right. If you see defects at -quality 75, then go up 5 or 10
+counts at a time until you are happy with the output image. (The optimal
+setting will vary from one image to another.)
+
+-quality 100 will generate a quantization table of all 1's, minimizing loss
+in the quantization step (but there is still information loss in subsampling,
+as well as roundoff error). This setting is mainly of interest for
+experimental purposes. Quality values above about 95 are NOT recommended for
+normal use; the compressed file size goes up dramatically for hardly any gain
+in output image quality.
+
+In the other direction, quality values below 50 will produce very small files
+of low image quality. Settings around 5 to 10 might be useful in preparing an
+index of a large image library, for example. Try -quality 2 (or so) for some
+amusing Cubist effects. (Note: quality values below about 25 generate 2-byte
+quantization tables, which are considered optional in the JPEG standard.
+cjpeg emits a warning message when you give such a quality value, because some
+other JPEG programs may be unable to decode the resulting file. Use -baseline
+if you need to ensure compatibility at low quality values.)
+
+The -progressive switch creates a "progressive JPEG" file. In this type of
+JPEG file, the data is stored in multiple scans of increasing quality. If the
+file is being transmitted over a slow communications link, the decoder can use
+the first scan to display a low-quality image very quickly, and can then
+improve the display with each subsequent scan. The final image is exactly
+equivalent to a standard JPEG file of the same quality setting, and the total
+file size is about the same --- often a little smaller. CAUTION: progressive
+JPEG is not yet widely implemented, so many decoders will be unable to view a
+progressive JPEG file at all.
+
+Switches for advanced users:
+
+ -dct int Use integer DCT method (default).
+ -dct fast Use fast integer DCT (less accurate).
+ -dct float Use floating-point DCT method.
+ The float method is very slightly more accurate than
+ the int method, but is much slower unless your machine
+ has very fast floating-point hardware. Also note that
+ results of the floating-point method may vary slightly
+ across machines, while the integer methods should give
+ the same results everywhere. The fast integer method
+ is much less accurate than the other two.
+
+ -restart N Emit a JPEG restart marker every N MCU rows, or every
+ N MCU blocks if "B" is attached to the number.
+ -restart 0 (the default) means no restart markers.
+
+ -smooth N Smooth the input image to eliminate dithering noise.
+ N, ranging from 1 to 100, indicates the strength of
+ smoothing. 0 (the default) means no smoothing.
+
+ -maxmemory N Set limit for amount of memory to use in processing
+ large images. Value is in thousands of bytes, or
+ millions of bytes if "M" is attached to the number.
+ For example, -max 4m selects 4000000 bytes. If more
+ space is needed, temporary files will be used.
+
+ -verbose Enable debug printout. More -v's give more printout.
+ or -debug Also, version information is printed at startup.
+
+The -restart option inserts extra markers that allow a JPEG decoder to
+resynchronize after a transmission error. Without restart markers, any damage
+to a compressed file will usually ruin the image from the point of the error
+to the end of the image; with restart markers, the damage is usually confined
+to the portion of the image up to the next restart marker. Of course, the
+restart markers occupy extra space. We recommend -restart 1 for images that
+will be transmitted across unreliable networks such as Usenet.
+
+The -smooth option filters the input to eliminate fine-scale noise. This is
+often useful when converting dithered images to JPEG: a moderate smoothing
+factor of 10 to 50 gets rid of dithering patterns in the input file, resulting
+in a smaller JPEG file and a better-looking image. Too large a smoothing
+factor will visibly blur the image, however.
+
+Switches for wizards:
+
+ -baseline Force baseline-compatible quantization tables to be
+ generated. This clamps quantization values to 8 bits
+ even at low quality settings. (This switch is poorly
+ named, since it does not ensure that the output is
+ actually baseline JPEG. For example, you can use
+ -baseline and -progressive together.)
+
+ -qtables file Use the quantization tables given in the specified
+ text file.
+
+ -qslots N[,...] Select which quantization table to use for each color
+ component.
+
+ -sample HxV[,...] Set JPEG sampling factors for each color component.
+
+ -scans file Use the scan script given in the specified text file.
+
+The "wizard" switches are intended for experimentation with JPEG. If you
+don't know what you are doing, DON'T USE THEM. These switches are documented
+further in the file wizard.doc.
+
+
+DJPEG DETAILS
+
+The basic command line switches for djpeg are:
+
+ -colors N Reduce image to at most N colors. This reduces the
+ or -quantize N number of colors used in the output image, so that it
+ can be displayed on a colormapped display or stored in
+ a colormapped file format. For example, if you have
+ an 8-bit display, you'd need to reduce to 256 or fewer
+ colors. (-colors is the recommended name, -quantize
+ is provided only for backwards compatibility.)
+
+ -fast Select recommended processing options for fast, low
+ quality output. (The default options are chosen for
+ highest quality output.) Currently, this is equivalent
+ to "-dct fast -nosmooth -onepass -dither ordered".
+
+ -grayscale Force gray-scale output even if JPEG file is color.
+ Useful for viewing on monochrome displays; also,
+ djpeg runs noticeably faster in this mode.
+
+ -scale M/N Scale the output image by a factor M/N. Currently
+ the scale factor must be 1/1, 1/2, 1/4, or 1/8.
+ Scaling is handy if the image is larger than your
+ screen; also, djpeg runs much faster when scaling
+ down the output.
+
+ -bmp Select BMP output format (Windows flavor). 8-bit
+ colormapped format is emitted if -colors or -grayscale
+ is specified, or if the JPEG file is gray-scale;
+ otherwise, 24-bit full-color format is emitted.
+
+ -gif Select GIF output format. Since GIF does not support
+ more than 256 colors, -colors 256 is assumed (unless
+ you specify a smaller number of colors). If you
+ specify -fast, the default number of colors is 216.
+
+ -os2 Select BMP output format (OS/2 1.x flavor). 8-bit
+ colormapped format is emitted if -colors or -grayscale
+ is specified, or if the JPEG file is gray-scale;
+ otherwise, 24-bit full-color format is emitted.
+
+ -pnm Select PBMPLUS (PPM/PGM) output format (this is the
+ default format). PGM is emitted if the JPEG file is
+ gray-scale or if -grayscale is specified; otherwise
+ PPM is emitted.
+
+ -rle Select RLE output format. (Requires URT library.)
+
+ -targa Select Targa output format. Gray-scale format is
+ emitted if the JPEG file is gray-scale or if
+ -grayscale is specified; otherwise, colormapped format
+ is emitted if -colors is specified; otherwise, 24-bit
+ full-color format is emitted.
+
+Switches for advanced users:
+
+ -dct int Use integer DCT method (default).
+ -dct fast Use fast integer DCT (less accurate).
+ -dct float Use floating-point DCT method.
+ The float method is very slightly more accurate than
+ the int method, but is much slower unless your machine
+ has very fast floating-point hardware. Also note that
+ results of the floating-point method may vary slightly
+ across machines, while the integer methods should give
+ the same results everywhere. The fast integer method
+ is much less accurate than the other two.
+
+ -dither fs Use Floyd-Steinberg dithering in color quantization.
+ -dither ordered Use ordered dithering in color quantization.
+ -dither none Do not use dithering in color quantization.
+ By default, Floyd-Steinberg dithering is applied when
+ quantizing colors; this is slow but usually produces
+ the best results. Ordered dither is a compromise
+ between speed and quality; no dithering is fast but
+ usually looks awful. Note that these switches have
+ no effect unless color quantization is being done.
+ Ordered dither is only available in -onepass mode.
+
+ -map FILE Quantize to the colors used in the specified image
+ file. This is useful for producing multiple files
+ with identical color maps, or for forcing a predefined
+ set of colors to be used. The FILE must be a GIF
+ or PPM file. This option overrides -colors and
+ -onepass.
+
+ -nosmooth Use a faster, lower-quality upsampling routine.
+
+ -onepass Use one-pass instead of two-pass color quantization.
+ The one-pass method is faster and needs less memory,
+ but it produces a lower-quality image. -onepass is
+ ignored unless you also say -colors N. Also,
+ the one-pass method is always used for gray-scale
+ output (the two-pass method is no improvement then).
+
+ -maxmemory N Set limit for amount of memory to use in processing
+ large images. Value is in thousands of bytes, or
+ millions of bytes if "M" is attached to the number.
+ For example, -max 4m selects 4000000 bytes. If more
+ space is needed, temporary files will be used.
+
+ -verbose Enable debug printout. More -v's give more printout.
+ or -debug Also, version information is printed at startup.
+
+
+HINTS FOR CJPEG
+
+Color GIF files are not the ideal input for JPEG; JPEG is really intended for
+compressing full-color (24-bit) images. In particular, don't try to convert
+cartoons, line drawings, and other images that have only a few distinct
+colors. GIF works great on these, JPEG does not. If you want to convert a
+GIF to JPEG, you should experiment with cjpeg's -quality and -smooth options
+to get a satisfactory conversion. -smooth 10 or so is often helpful.
+
+Avoid running an image through a series of JPEG compression/decompression
+cycles. Image quality loss will accumulate; after ten or so cycles the image
+may be noticeably worse than it was after one cycle. It's best to use a
+lossless format while manipulating an image, then convert to JPEG format when
+you are ready to file the image away.
+
+The -optimize option to cjpeg is worth using when you are making a "final"
+version for posting or archiving. It's also a win when you are using low
+quality settings to make very small JPEG files; the percentage improvement
+is often a lot more than it is on larger files. (At present, -optimize
+mode is always selected when generating progressive JPEG files.)
+
+GIF input files are no longer supported, to avoid the Unisys LZW patent.
+Use a Unisys-licensed program if you need to read a GIF file. (Conversion
+of GIF files to JPEG is usually a bad idea anyway.)
+
+
+HINTS FOR DJPEG
+
+To get a quick preview of an image, use the -grayscale and/or -scale switches.
+"-grayscale -scale 1/8" is the fastest case.
+
+Several options are available that trade off image quality to gain speed.
+"-fast" turns on the recommended settings.
+
+"-dct fast" and/or "-nosmooth" gain speed at a small sacrifice in quality.
+When producing a color-quantized image, "-onepass -dither ordered" is fast but
+much lower quality than the default behavior. "-dither none" may give
+acceptable results in two-pass mode, but is seldom tolerable in one-pass mode.
+
+If you are fortunate enough to have very fast floating point hardware,
+"-dct float" may be even faster than "-dct fast". But on most machines
+"-dct float" is slower than "-dct int"; in this case it is not worth using,
+because its theoretical accuracy advantage is too small to be significant
+in practice.
+
+Two-pass color quantization requires a good deal of memory; on MS-DOS machines
+it may run out of memory even with -maxmemory 0. In that case you can still
+decompress, with some loss of image quality, by specifying -onepass for
+one-pass quantization.
+
+To avoid the Unisys LZW patent, djpeg produces uncompressed GIF files. These
+are larger than they should be, but are readable by standard GIF decoders.
+
+
+HINTS FOR BOTH PROGRAMS
+
+If more space is needed than will fit in the available main memory (as
+determined by -maxmemory), temporary files will be used. (MS-DOS versions
+will try to get extended or expanded memory first.) The temporary files are
+often rather large: in typical cases they occupy three bytes per pixel, for
+example 3*800*600 = 1.44Mb for an 800x600 image. If you don't have enough
+free disk space, leave out -progressive and -optimize (for cjpeg) or specify
+-onepass (for djpeg).
+
+On MS-DOS, the temporary files are created in the directory named by the TMP
+or TEMP environment variable, or in the current directory if neither of those
+exist. Amiga implementations put the temp files in the directory named by
+JPEGTMP:, so be sure to assign JPEGTMP: to a disk partition with adequate free
+space.
+
+The default memory usage limit (-maxmemory) is set when the software is
+compiled. If you get an "insufficient memory" error, try specifying a smaller
+-maxmemory value, even -maxmemory 0 to use the absolute minimum space. You
+may want to recompile with a smaller default value if this happens often.
+
+On machines that have "environment" variables, you can define the environment
+variable JPEGMEM to set the default memory limit. The value is specified as
+described for the -maxmemory switch. JPEGMEM overrides the default value
+specified when the program was compiled, and itself is overridden by an
+explicit -maxmemory switch.
+
+On MS-DOS machines, -maxmemory is the amount of main (conventional) memory to
+use. (Extended or expanded memory is also used if available.) Most
+DOS-specific versions of this software do their own memory space estimation
+and do not need you to specify -maxmemory.
+
+
+JPEGTRAN
+
+jpegtran performs various useful transformations of JPEG files.
+It can translate the coded representation from one variant of JPEG to another,
+for example from baseline JPEG to progressive JPEG or vice versa. It can also
+perform some rearrangements of the image data, for example turning an image
+from landscape to portrait format by rotation.
+
+jpegtran works by rearranging the compressed data (DCT coefficients), without
+ever fully decoding the image. Therefore, its transformations are lossless:
+there is no image degradation at all, which would not be true if you used
+djpeg followed by cjpeg to accomplish the same conversion. But by the same
+token, jpegtran cannot perform lossy operations such as changing the image
+quality.
+
+jpegtran uses a command line syntax similar to cjpeg or djpeg.
+On Unix-like systems, you say:
+ jpegtran [switches] [inputfile] >outputfile
+On most non-Unix systems, you say:
+ jpegtran [switches] inputfile outputfile
+where both the input and output files are JPEG files.
+
+To specify the coded JPEG representation used in the output file,
+jpegtran accepts a subset of the switches recognized by cjpeg:
+ -optimize Perform optimization of entropy encoding parameters.
+ -progressive Create progressive JPEG file.
+ -restart N Emit a JPEG restart marker every N MCU rows, or every
+ N MCU blocks if "B" is attached to the number.
+ -scans file Use the scan script given in the specified text file.
+See the previous discussion of cjpeg for more details about these switches.
+If you specify none of these switches, you get a plain baseline-JPEG output
+file. The quality setting and so forth are determined by the input file.
+
+The image can be losslessly transformed by giving one of these switches:
+ -flip horizontal Mirror image horizontally (left-right).
+ -flip vertical Mirror image vertically (top-bottom).
+ -rotate 90 Rotate image 90 degrees clockwise.
+ -rotate 180 Rotate image 180 degrees.
+ -rotate 270 Rotate image 270 degrees clockwise (or 90 ccw).
+ -transpose Transpose image (across UL-to-LR axis).
+ -transverse Transverse transpose (across UR-to-LL axis).
+
+The transpose transformation has no restrictions regarding image dimensions.
+The other transformations operate rather oddly if the image dimensions are not
+a multiple of the iMCU size (usually 8 or 16 pixels), because they can only
+transform complete blocks of DCT coefficient data in the desired way.
+
+jpegtran's default behavior when transforming an odd-size image is designed
+to preserve exact reversibility and mathematical consistency of the
+transformation set. As stated, transpose is able to flip the entire image
+area. Horizontal mirroring leaves any partial iMCU column at the right edge
+untouched, but is able to flip all rows of the image. Similarly, vertical
+mirroring leaves any partial iMCU row at the bottom edge untouched, but is
+able to flip all columns. The other transforms can be built up as sequences
+of transpose and flip operations; for consistency, their actions on edge
+pixels are defined to be the same as the end result of the corresponding
+transpose-and-flip sequence.
+
+For practical use, you may prefer to discard any untransformable edge pixels
+rather than having a strange-looking strip along the right and/or bottom edges
+of a transformed image. To do this, add the -trim switch:
+ -trim Drop non-transformable edge blocks.
+Obviously, a transformation with -trim is not reversible, so strictly speaking
+jpegtran with this switch is not lossless. Also, the expected mathematical
+equivalences between the transformations no longer hold. For example,
+"-rot 270 -trim" trims only the bottom edge, but "-rot 90 -trim" followed by
+"-rot 180 -trim" trims both edges.
+
+Another not-strictly-lossless transformation switch is:
+ -grayscale Force grayscale output.
+This option discards the chrominance channels if the input image is YCbCr
+(ie, a standard color JPEG), resulting in a grayscale JPEG file. The
+luminance channel is preserved exactly, so this is a better method of reducing
+to grayscale than decompression, conversion, and recompression. This switch
+is particularly handy for fixing a monochrome picture that was mistakenly
+encoded as a color JPEG. (In such a case, the space savings from getting rid
+of the near-empty chroma channels won't be large; but the decoding time for
+a grayscale JPEG is substantially less than that for a color JPEG.)
+
+jpegtran also recognizes these switches that control what to do with "extra"
+markers, such as comment blocks:
+ -copy none Copy no extra markers from source file. This setting
+ suppresses all comments and other excess baggage
+ present in the source file.
+ -copy comments Copy only comment markers. This setting copies
+ comments from the source file, but discards
+ any other inessential data.
+ -copy all Copy all extra markers. This setting preserves
+ miscellaneous markers found in the source file, such
+ as JFIF thumbnails and Photoshop settings. In some
+ files these extra markers can be sizable.
+The default behavior is -copy comments. (Note: in IJG releases v6 and v6a,
+jpegtran always did the equivalent of -copy none.)
+
+Additional switches recognized by jpegtran are:
+ -outfile filename
+ -maxmemory N
+ -verbose
+ -debug
+These work the same as in cjpeg or djpeg.
+
+
+THE COMMENT UTILITIES
+
+The JPEG standard allows "comment" (COM) blocks to occur within a JPEG file.
+Although the standard doesn't actually define what COM blocks are for, they
+are widely used to hold user-supplied text strings. This lets you add
+annotations, titles, index terms, etc to your JPEG files, and later retrieve
+them as text. COM blocks do not interfere with the image stored in the JPEG
+file. The maximum size of a COM block is 64K, but you can have as many of
+them as you like in one JPEG file.
+
+We provide two utility programs to display COM block contents and add COM
+blocks to a JPEG file.
+
+rdjpgcom searches a JPEG file and prints the contents of any COM blocks on
+standard output. The command line syntax is
+ rdjpgcom [-verbose] [inputfilename]
+The switch "-verbose" (or just "-v") causes rdjpgcom to also display the JPEG
+image dimensions. If you omit the input file name from the command line,
+the JPEG file is read from standard input. (This may not work on some
+operating systems, if binary data can't be read from stdin.)
+
+wrjpgcom adds a COM block, containing text you provide, to a JPEG file.
+Ordinarily, the COM block is added after any existing COM blocks, but you
+can delete the old COM blocks if you wish. wrjpgcom produces a new JPEG
+file; it does not modify the input file. DO NOT try to overwrite the input
+file by directing wrjpgcom's output back into it; on most systems this will
+just destroy your file.
+
+The command line syntax for wrjpgcom is similar to cjpeg's. On Unix-like
+systems, it is
+ wrjpgcom [switches] [inputfilename]
+The output file is written to standard output. The input file comes from
+the named file, or from standard input if no input file is named.
+
+On most non-Unix systems, the syntax is
+ wrjpgcom [switches] inputfilename outputfilename
+where both input and output file names must be given explicitly.
+
+wrjpgcom understands three switches:
+ -replace Delete any existing COM blocks from the file.
+ -comment "Comment text" Supply new COM text on command line.
+ -cfile name Read text for new COM block from named file.
+(Switch names can be abbreviated.) If you have only one line of comment text
+to add, you can provide it on the command line with -comment. The comment
+text must be surrounded with quotes so that it is treated as a single
+argument. Longer comments can be read from a text file.
+
+If you give neither -comment nor -cfile, then wrjpgcom will read the comment
+text from standard input. (In this case an input image file name MUST be
+supplied, so that the source JPEG file comes from somewhere else.) You can
+enter multiple lines, up to 64KB worth. Type an end-of-file indicator
+(usually control-D or control-Z) to terminate the comment text entry.
+
+wrjpgcom will not add a COM block if the provided comment string is empty.
+Therefore -replace -comment "" can be used to delete all COM blocks from a
+file.
+
+These utility programs do not depend on the IJG JPEG library. In
+particular, the source code for rdjpgcom is intended as an illustration of
+the minimum amount of code required to parse a JPEG file header correctly.
diff --git a/jpeg-6c/wizard.doc b/jpeg-6c/wizard.doc
new file mode 100644
index 0000000..54170b2
--- /dev/null
+++ b/jpeg-6c/wizard.doc
@@ -0,0 +1,211 @@
+Advanced usage instructions for the Independent JPEG Group's JPEG software
+==========================================================================
+
+This file describes cjpeg's "switches for wizards".
+
+The "wizard" switches are intended for experimentation with JPEG by persons
+who are reasonably knowledgeable about the JPEG standard. If you don't know
+what you are doing, DON'T USE THESE SWITCHES. You'll likely produce files
+with worse image quality and/or poorer compression than you'd get from the
+default settings. Furthermore, these switches must be used with caution
+when making files intended for general use, because not all JPEG decoders
+will support unusual JPEG parameter settings.
+
+
+Quantization Table Adjustment
+-----------------------------
+
+Ordinarily, cjpeg starts with a default set of tables (the same ones given
+as examples in the JPEG standard) and scales them up or down according to
+the -quality setting. The details of the scaling algorithm can be found in
+jcparam.c. At very low quality settings, some quantization table entries
+can get scaled up to values exceeding 255. Although 2-byte quantization
+values are supported by the IJG software, this feature is not in baseline
+JPEG and is not supported by all implementations. If you need to ensure
+wide compatibility of low-quality files, you can constrain the scaled
+quantization values to no more than 255 by giving the -baseline switch.
+Note that use of -baseline will result in poorer quality for the same file
+size, since more bits than necessary are expended on higher AC coefficients.
+
+You can substitute a different set of quantization values by using the
+-qtables switch:
+
+ -qtables file Use the quantization tables given in the named file.
+
+The specified file should be a text file containing decimal quantization
+values. The file should contain one to four tables, each of 64 elements.
+The tables are implicitly numbered 0,1,etc. in order of appearance. Table
+entries appear in normal array order (NOT in the zigzag order in which they
+will be stored in the JPEG file).
+
+Quantization table files are free format, in that arbitrary whitespace can
+appear between numbers. Also, comments can be included: a comment starts
+with '#' and extends to the end of the line. Here is an example file that
+duplicates the default quantization tables:
+
+ # Quantization tables given in JPEG spec, section K.1
+
+ # This is table 0 (the luminance table):
+ 16 11 10 16 24 40 51 61
+ 12 12 14 19 26 58 60 55
+ 14 13 16 24 40 57 69 56
+ 14 17 22 29 51 87 80 62
+ 18 22 37 56 68 109 103 77
+ 24 35 55 64 81 104 113 92
+ 49 64 78 87 103 121 120 101
+ 72 92 95 98 112 100 103 99
+
+ # This is table 1 (the chrominance table):
+ 17 18 24 47 99 99 99 99
+ 18 21 26 66 99 99 99 99
+ 24 26 56 99 99 99 99 99
+ 47 66 99 99 99 99 99 99
+ 99 99 99 99 99 99 99 99
+ 99 99 99 99 99 99 99 99
+ 99 99 99 99 99 99 99 99
+ 99 99 99 99 99 99 99 99
+
+If the -qtables switch is used without -quality, then the specified tables
+are used exactly as-is. If both -qtables and -quality are used, then the
+tables taken from the file are scaled in the same fashion that the default
+tables would be scaled for that quality setting. If -baseline appears, then
+the quantization values are constrained to the range 1-255.
+
+By default, cjpeg will use quantization table 0 for luminance components and
+table 1 for chrominance components. To override this choice, use the -qslots
+switch:
+
+ -qslots N[,...] Select which quantization table to use for
+ each color component.
+
+The -qslots switch specifies a quantization table number for each color
+component, in the order in which the components appear in the JPEG SOF marker.
+For example, to create a separate table for each of Y,Cb,Cr, you could
+provide a -qtables file that defines three quantization tables and say
+"-qslots 0,1,2". If -qslots gives fewer table numbers than there are color
+components, then the last table number is repeated as necessary.
+
+
+Sampling Factor Adjustment
+--------------------------
+
+By default, cjpeg uses 2:1 horizontal and vertical downsampling when
+compressing YCbCr data, and no downsampling for all other color spaces.
+You can override this default with the -sample switch:
+
+ -sample HxV[,...] Set JPEG sampling factors for each color
+ component.
+
+The -sample switch specifies the JPEG sampling factors for each color
+component, in the order in which they appear in the JPEG SOF marker.
+If you specify fewer HxV pairs than there are components, the remaining
+components are set to 1x1 sampling. For example, the default YCbCr setting
+is equivalent to "-sample 2x2,1x1,1x1", which can be abbreviated to
+"-sample 2x2".
+
+There are still some JPEG decoders in existence that support only 2x1
+sampling (also called 4:2:2 sampling). Compatibility with such decoders can
+be achieved by specifying "-sample 2x1". This is not recommended unless
+really necessary, since it increases file size and encoding/decoding time
+with very little quality gain.
+
+
+Multiple Scan / Progression Control
+-----------------------------------
+
+By default, cjpeg emits a single-scan sequential JPEG file. The
+-progressive switch generates a progressive JPEG file using a default series
+of progression parameters. You can create multiple-scan sequential JPEG
+files or progressive JPEG files with custom progression parameters by using
+the -scans switch:
+
+ -scans file Use the scan sequence given in the named file.
+
+The specified file should be a text file containing a "scan script".
+The script specifies the contents and ordering of the scans to be emitted.
+Each entry in the script defines one scan. A scan definition specifies
+the components to be included in the scan, and for progressive JPEG it also
+specifies the progression parameters Ss,Se,Ah,Al for the scan. Scan
+definitions are separated by semicolons (';'). A semicolon after the last
+scan definition is optional.
+
+Each scan definition contains one to four component indexes, optionally
+followed by a colon (':') and the four progressive-JPEG parameters. The
+component indexes denote which color component(s) are to be transmitted in
+the scan. Components are numbered in the order in which they appear in the
+JPEG SOF marker, with the first component being numbered 0. (Note that these
+indexes are not the "component ID" codes assigned to the components, just
+positional indexes.)
+
+The progression parameters for each scan are:
+ Ss Zigzag index of first coefficient included in scan
+ Se Zigzag index of last coefficient included in scan
+ Ah Zero for first scan of a coefficient, else Al of prior scan
+ Al Successive approximation low bit position for scan
+If the progression parameters are omitted, the values 0,63,0,0 are used,
+producing a sequential JPEG file. cjpeg automatically determines whether
+the script represents a progressive or sequential file, by observing whether
+Ss and Se values other than 0 and 63 appear. (The -progressive switch is
+not needed to specify this; in fact, it is ignored when -scans appears.)
+The scan script must meet the JPEG restrictions on progression sequences.
+(cjpeg checks that the spec's requirements are obeyed.)
+
+Scan script files are free format, in that arbitrary whitespace can appear
+between numbers and around punctuation. Also, comments can be included: a
+comment starts with '#' and extends to the end of the line. For additional
+legibility, commas or dashes can be placed between values. (Actually, any
+single punctuation character other than ':' or ';' can be inserted.) For
+example, the following two scan definitions are equivalent:
+ 0 1 2: 0 63 0 0;
+ 0,1,2 : 0-63, 0,0 ;
+
+Here is an example of a scan script that generates a partially interleaved
+sequential JPEG file:
+
+ 0; # Y only in first scan
+ 1 2; # Cb and Cr in second scan
+
+Here is an example of a progressive scan script using only spectral selection
+(no successive approximation):
+
+ # Interleaved DC scan for Y,Cb,Cr:
+ 0,1,2: 0-0, 0, 0 ;
+ # AC scans:
+ 0: 1-2, 0, 0 ; # First two Y AC coefficients
+ 0: 3-5, 0, 0 ; # Three more
+ 1: 1-63, 0, 0 ; # All AC coefficients for Cb
+ 2: 1-63, 0, 0 ; # All AC coefficients for Cr
+ 0: 6-9, 0, 0 ; # More Y coefficients
+ 0: 10-63, 0, 0 ; # Remaining Y coefficients
+
+Here is an example of a successive-approximation script. This is equivalent
+to the default script used by "cjpeg -progressive" for YCbCr images:
+
+ # Initial DC scan for Y,Cb,Cr (lowest bit not sent)
+ 0,1,2: 0-0, 0, 1 ;
+ # First AC scan: send first 5 Y AC coefficients, minus 2 lowest bits:
+ 0: 1-5, 0, 2 ;
+ # Send all Cr,Cb AC coefficients, minus lowest bit:
+ # (chroma data is usually too small to be worth subdividing further;
+ # but note we send Cr first since eye is least sensitive to Cb)
+ 2: 1-63, 0, 1 ;
+ 1: 1-63, 0, 1 ;
+ # Send remaining Y AC coefficients, minus 2 lowest bits:
+ 0: 6-63, 0, 2 ;
+ # Send next-to-lowest bit of all Y AC coefficients:
+ 0: 1-63, 2, 1 ;
+ # At this point we've sent all but the lowest bit of all coefficients.
+ # Send lowest bit of DC coefficients
+ 0,1,2: 0-0, 1, 0 ;
+ # Send lowest bit of AC coefficients
+ 2: 1-63, 1, 0 ;
+ 1: 1-63, 1, 0 ;
+ # Y AC lowest bit scan is last; it's usually the largest scan
+ 0: 1-63, 1, 0 ;
+
+It may be worth pointing out that this script is tuned for quality settings
+of around 50 to 75. For lower quality settings, you'd probably want to use
+a script with fewer stages of successive approximation (otherwise the
+initial scans will be really bad). For higher quality settings, you might
+want to use more stages of successive approximation (so that the initial
+scans are not too large).
diff --git a/jpeg-6c/wrbmp.c b/jpeg-6c/wrbmp.c
new file mode 100644
index 0000000..3283b0f
--- /dev/null
+++ b/jpeg-6c/wrbmp.c
@@ -0,0 +1,442 @@
+/*
+ * wrbmp.c
+ *
+ * Copyright (C) 1994-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to write output images in Microsoft "BMP"
+ * format (MS Windows 3.x and OS/2 1.x flavors).
+ * Either 8-bit colormapped or 24-bit full-color format can be written.
+ * No compression is supported.
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications. As they stand, they assume output to
+ * an ordinary stdio stream.
+ *
+ * This code contributed by James Arthur Boucher.
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+
+#ifdef BMP_SUPPORTED
+
+
+/*
+ * To support 12-bit JPEG data, we'd have to scale output down to 8 bits.
+ * This is not yet implemented.
+ */
+
+#if BITS_IN_JSAMPLE != 8
+ Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
+#endif
+
+/*
+ * Since BMP stores scanlines bottom-to-top, we have to invert the image
+ * from JPEG's top-to-bottom order. To do this, we save the outgoing data
+ * in a virtual array during put_pixel_row calls, then actually emit the
+ * BMP file during finish_output. The virtual array contains one JSAMPLE per
+ * pixel if the output is grayscale or colormapped, three if it is full color.
+ */
+
+/* Private version of data destination object */
+
+typedef struct {
+ struct djpeg_dest_struct pub; /* public fields */
+
+ boolean is_os2; /* saves the OS2 format request flag */
+
+ jvirt_sarray_ptr whole_image; /* needed to reverse row order */
+ JDIMENSION data_width; /* JSAMPLEs per row */
+ JDIMENSION row_width; /* physical width of one row in the BMP file */
+ int pad_bytes; /* number of padding bytes needed per row */
+ JDIMENSION cur_output_row; /* next row# to write to virtual array */
+} bmp_dest_struct;
+
+typedef bmp_dest_struct * bmp_dest_ptr;
+
+
+/* Forward declarations */
+LOCAL(void) write_colormap
+ JPP((j_decompress_ptr cinfo, bmp_dest_ptr dest,
+ int map_colors, int map_entry_size));
+
+
+/*
+ * Write some pixel data.
+ * In this module rows_supplied will always be 1.
+ */
+
+METHODDEF(void)
+put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+/* This version is for writing 24-bit pixels */
+{
+ bmp_dest_ptr dest = (bmp_dest_ptr) dinfo;
+ JSAMPARRAY image_ptr;
+ register JSAMPROW inptr, outptr;
+ register JDIMENSION col;
+ int pad;
+
+ /* Access next row in virtual array */
+ image_ptr = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, dest->whole_image,
+ dest->cur_output_row, (JDIMENSION) 1, TRUE);
+ dest->cur_output_row++;
+
+ /* Transfer data. Note destination values must be in BGR order
+ * (even though Microsoft's own documents say the opposite).
+ */
+ inptr = dest->pub.buffer[0];
+ outptr = image_ptr[0];
+ for (col = cinfo->output_width; col > 0; col--) {
+ outptr[2] = *inptr++; /* can omit GETJSAMPLE() safely */
+ outptr[1] = *inptr++;
+ outptr[0] = *inptr++;
+ outptr += 3;
+ }
+
+ /* Zero out the pad bytes. */
+ pad = dest->pad_bytes;
+ while (--pad >= 0)
+ *outptr++ = 0;
+}
+
+METHODDEF(void)
+put_gray_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+/* This version is for grayscale OR quantized color output */
+{
+ bmp_dest_ptr dest = (bmp_dest_ptr) dinfo;
+ JSAMPARRAY image_ptr;
+ register JSAMPROW inptr, outptr;
+ register JDIMENSION col;
+ int pad;
+
+ /* Access next row in virtual array */
+ image_ptr = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, dest->whole_image,
+ dest->cur_output_row, (JDIMENSION) 1, TRUE);
+ dest->cur_output_row++;
+
+ /* Transfer data. */
+ inptr = dest->pub.buffer[0];
+ outptr = image_ptr[0];
+ for (col = cinfo->output_width; col > 0; col--) {
+ *outptr++ = *inptr++; /* can omit GETJSAMPLE() safely */
+ }
+
+ /* Zero out the pad bytes. */
+ pad = dest->pad_bytes;
+ while (--pad >= 0)
+ *outptr++ = 0;
+}
+
+
+/*
+ * Startup: normally writes the file header.
+ * In this module we may as well postpone everything until finish_output.
+ */
+
+METHODDEF(void)
+start_output_bmp (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
+{
+ /* no work here */
+}
+
+
+/*
+ * Finish up at the end of the file.
+ *
+ * Here is where we really output the BMP file.
+ *
+ * First, routines to write the Windows and OS/2 variants of the file header.
+ */
+
+LOCAL(void)
+write_bmp_header (j_decompress_ptr cinfo, bmp_dest_ptr dest)
+/* Write a Windows-style BMP file header, including colormap if needed */
+{
+ char bmpfileheader[14];
+ char bmpinfoheader[40];
+#define PUT_2B(array,offset,value) \
+ (array[offset] = (char) ((value) & 0xFF), \
+ array[offset+1] = (char) (((value) >> 8) & 0xFF))
+#define PUT_4B(array,offset,value) \
+ (array[offset] = (char) ((value) & 0xFF), \
+ array[offset+1] = (char) (((value) >> 8) & 0xFF), \
+ array[offset+2] = (char) (((value) >> 16) & 0xFF), \
+ array[offset+3] = (char) (((value) >> 24) & 0xFF))
+ INT32 headersize, bfSize;
+ int bits_per_pixel, cmap_entries;
+
+ /* Compute colormap size and total file size */
+ if (cinfo->out_color_space == JCS_RGB) {
+ if (cinfo->quantize_colors) {
+ /* Colormapped RGB */
+ bits_per_pixel = 8;
+ cmap_entries = 256;
+ } else {
+ /* Unquantized, full color RGB */
+ bits_per_pixel = 24;
+ cmap_entries = 0;
+ }
+ } else {
+ /* Grayscale output. We need to fake a 256-entry colormap. */
+ bits_per_pixel = 8;
+ cmap_entries = 256;
+ }
+ /* File size */
+ headersize = 14 + 40 + cmap_entries * 4; /* Header and colormap */
+ bfSize = headersize + (INT32) dest->row_width * (INT32) cinfo->output_height;
+
+ /* Set unused fields of header to 0 */
+ MEMZERO(bmpfileheader, SIZEOF(bmpfileheader));
+ MEMZERO(bmpinfoheader, SIZEOF(bmpinfoheader));
+
+ /* Fill the file header */
+ bmpfileheader[0] = 0x42; /* first 2 bytes are ASCII 'B', 'M' */
+ bmpfileheader[1] = 0x4D;
+ PUT_4B(bmpfileheader, 2, bfSize); /* bfSize */
+ /* we leave bfReserved1 & bfReserved2 = 0 */
+ PUT_4B(bmpfileheader, 10, headersize); /* bfOffBits */
+
+ /* Fill the info header (Microsoft calls this a BITMAPINFOHEADER) */
+ PUT_2B(bmpinfoheader, 0, 40); /* biSize */
+ PUT_4B(bmpinfoheader, 4, cinfo->output_width); /* biWidth */
+ PUT_4B(bmpinfoheader, 8, cinfo->output_height); /* biHeight */
+ PUT_2B(bmpinfoheader, 12, 1); /* biPlanes - must be 1 */
+ PUT_2B(bmpinfoheader, 14, bits_per_pixel); /* biBitCount */
+ /* we leave biCompression = 0, for none */
+ /* we leave biSizeImage = 0; this is correct for uncompressed data */
+ if (cinfo->density_unit == 2) { /* if have density in dots/cm, then */
+ PUT_4B(bmpinfoheader, 24, (INT32) (cinfo->X_density*100)); /* XPels/M */
+ PUT_4B(bmpinfoheader, 28, (INT32) (cinfo->Y_density*100)); /* XPels/M */
+ }
+ PUT_2B(bmpinfoheader, 32, cmap_entries); /* biClrUsed */
+ /* we leave biClrImportant = 0 */
+
+ if (JFWRITE(dest->pub.output_file, bmpfileheader, 14) != (size_t) 14)
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+ if (JFWRITE(dest->pub.output_file, bmpinfoheader, 40) != (size_t) 40)
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+
+ if (cmap_entries > 0)
+ write_colormap(cinfo, dest, cmap_entries, 4);
+}
+
+
+LOCAL(void)
+write_os2_header (j_decompress_ptr cinfo, bmp_dest_ptr dest)
+/* Write an OS2-style BMP file header, including colormap if needed */
+{
+ char bmpfileheader[14];
+ char bmpcoreheader[12];
+ INT32 headersize, bfSize;
+ int bits_per_pixel, cmap_entries;
+
+ /* Compute colormap size and total file size */
+ if (cinfo->out_color_space == JCS_RGB) {
+ if (cinfo->quantize_colors) {
+ /* Colormapped RGB */
+ bits_per_pixel = 8;
+ cmap_entries = 256;
+ } else {
+ /* Unquantized, full color RGB */
+ bits_per_pixel = 24;
+ cmap_entries = 0;
+ }
+ } else {
+ /* Grayscale output. We need to fake a 256-entry colormap. */
+ bits_per_pixel = 8;
+ cmap_entries = 256;
+ }
+ /* File size */
+ headersize = 14 + 12 + cmap_entries * 3; /* Header and colormap */
+ bfSize = headersize + (INT32) dest->row_width * (INT32) cinfo->output_height;
+
+ /* Set unused fields of header to 0 */
+ MEMZERO(bmpfileheader, SIZEOF(bmpfileheader));
+ MEMZERO(bmpcoreheader, SIZEOF(bmpcoreheader));
+
+ /* Fill the file header */
+ bmpfileheader[0] = 0x42; /* first 2 bytes are ASCII 'B', 'M' */
+ bmpfileheader[1] = 0x4D;
+ PUT_4B(bmpfileheader, 2, bfSize); /* bfSize */
+ /* we leave bfReserved1 & bfReserved2 = 0 */
+ PUT_4B(bmpfileheader, 10, headersize); /* bfOffBits */
+
+ /* Fill the info header (Microsoft calls this a BITMAPCOREHEADER) */
+ PUT_2B(bmpcoreheader, 0, 12); /* bcSize */
+ PUT_2B(bmpcoreheader, 4, cinfo->output_width); /* bcWidth */
+ PUT_2B(bmpcoreheader, 6, cinfo->output_height); /* bcHeight */
+ PUT_2B(bmpcoreheader, 8, 1); /* bcPlanes - must be 1 */
+ PUT_2B(bmpcoreheader, 10, bits_per_pixel); /* bcBitCount */
+
+ if (JFWRITE(dest->pub.output_file, bmpfileheader, 14) != (size_t) 14)
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+ if (JFWRITE(dest->pub.output_file, bmpcoreheader, 12) != (size_t) 12)
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+
+ if (cmap_entries > 0)
+ write_colormap(cinfo, dest, cmap_entries, 3);
+}
+
+
+/*
+ * Write the colormap.
+ * Windows uses BGR0 map entries; OS/2 uses BGR entries.
+ */
+
+LOCAL(void)
+write_colormap (j_decompress_ptr cinfo, bmp_dest_ptr dest,
+ int map_colors, int map_entry_size)
+{
+ JSAMPARRAY colormap = cinfo->colormap;
+ int num_colors = cinfo->actual_number_of_colors;
+ FILE * outfile = dest->pub.output_file;
+ int i;
+
+ if (colormap != NULL) {
+ if (cinfo->out_color_components == 3) {
+ /* Normal case with RGB colormap */
+ for (i = 0; i < num_colors; i++) {
+ putc(GETJSAMPLE(colormap[2][i]), outfile);
+ putc(GETJSAMPLE(colormap[1][i]), outfile);
+ putc(GETJSAMPLE(colormap[0][i]), outfile);
+ if (map_entry_size == 4)
+ putc(0, outfile);
+ }
+ } else {
+ /* Grayscale colormap (only happens with grayscale quantization) */
+ for (i = 0; i < num_colors; i++) {
+ putc(GETJSAMPLE(colormap[0][i]), outfile);
+ putc(GETJSAMPLE(colormap[0][i]), outfile);
+ putc(GETJSAMPLE(colormap[0][i]), outfile);
+ if (map_entry_size == 4)
+ putc(0, outfile);
+ }
+ }
+ } else {
+ /* If no colormap, must be grayscale data. Generate a linear "map". */
+ for (i = 0; i < 256; i++) {
+ putc(i, outfile);
+ putc(i, outfile);
+ putc(i, outfile);
+ if (map_entry_size == 4)
+ putc(0, outfile);
+ }
+ }
+ /* Pad colormap with zeros to ensure specified number of colormap entries */
+ if (i > map_colors)
+ ERREXIT1(cinfo, JERR_TOO_MANY_COLORS, i);
+ for (; i < map_colors; i++) {
+ putc(0, outfile);
+ putc(0, outfile);
+ putc(0, outfile);
+ if (map_entry_size == 4)
+ putc(0, outfile);
+ }
+}
+
+
+METHODDEF(void)
+finish_output_bmp (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
+{
+ bmp_dest_ptr dest = (bmp_dest_ptr) dinfo;
+ register FILE * outfile = dest->pub.output_file;
+ JSAMPARRAY image_ptr;
+ register JSAMPROW data_ptr;
+ JDIMENSION row;
+ register JDIMENSION col;
+ cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
+
+ /* Write the header and colormap */
+ if (dest->is_os2)
+ write_os2_header(cinfo, dest);
+ else
+ write_bmp_header(cinfo, dest);
+
+ /* Write the file body from our virtual array */
+ for (row = cinfo->output_height; row > 0; row--) {
+ if (progress != NULL) {
+ progress->pub.pass_counter = (long) (cinfo->output_height - row);
+ progress->pub.pass_limit = (long) cinfo->output_height;
+ (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
+ }
+ image_ptr = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, dest->whole_image, row-1, (JDIMENSION) 1, FALSE);
+ data_ptr = image_ptr[0];
+ for (col = dest->row_width; col > 0; col--) {
+ putc(GETJSAMPLE(*data_ptr), outfile);
+ data_ptr++;
+ }
+ }
+ if (progress != NULL)
+ progress->completed_extra_passes++;
+
+ /* Make sure we wrote the output file OK */
+ fflush(outfile);
+ if (ferror(outfile))
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+}
+
+
+/*
+ * The module selection routine for BMP format output.
+ */
+
+GLOBAL(djpeg_dest_ptr)
+jinit_write_bmp (j_decompress_ptr cinfo, boolean is_os2)
+{
+ bmp_dest_ptr dest;
+ JDIMENSION row_width;
+
+ /* Create module interface object, fill in method pointers */
+ dest = (bmp_dest_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(bmp_dest_struct));
+ dest->pub.start_output = start_output_bmp;
+ dest->pub.finish_output = finish_output_bmp;
+ dest->is_os2 = is_os2;
+
+ if (cinfo->out_color_space == JCS_GRAYSCALE) {
+ dest->pub.put_pixel_rows = put_gray_rows;
+ } else if (cinfo->out_color_space == JCS_RGB) {
+ if (cinfo->quantize_colors)
+ dest->pub.put_pixel_rows = put_gray_rows;
+ else
+ dest->pub.put_pixel_rows = put_pixel_rows;
+ } else {
+ ERREXIT(cinfo, JERR_BMP_COLORSPACE);
+ }
+
+ /* Calculate output image dimensions so we can allocate space */
+ jpeg_calc_output_dimensions(cinfo);
+
+ /* Determine width of rows in the BMP file (padded to 4-byte boundary). */
+ row_width = cinfo->output_width * cinfo->output_components;
+ dest->data_width = row_width;
+ while ((row_width & 3) != 0) row_width++;
+ dest->row_width = row_width;
+ dest->pad_bytes = (int) (row_width - dest->data_width);
+
+ /* Allocate space for inversion array, prepare for write pass */
+ dest->whole_image = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ row_width, cinfo->output_height, (JDIMENSION) 1);
+ dest->cur_output_row = 0;
+ if (cinfo->progress != NULL) {
+ cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
+ progress->total_extra_passes++; /* count file input as separate pass */
+ }
+
+ /* Create decompressor output buffer. */
+ dest->pub.buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, row_width, (JDIMENSION) 1);
+ dest->pub.buffer_height = 1;
+
+ return (djpeg_dest_ptr) dest;
+}
+
+#endif /* BMP_SUPPORTED */
diff --git a/jpeg-6c/wrgif.c b/jpeg-6c/wrgif.c
new file mode 100644
index 0000000..5faa7c7
--- /dev/null
+++ b/jpeg-6c/wrgif.c
@@ -0,0 +1,505 @@
+/*
+ * wrgif.c
+ *
+ * Copyright (C) 1991-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ **************************************************************************
+ * WARNING: You will need an LZW patent license from Unisys in order to *
+ * use this file legally in any commercial or shareware application. *
+ **************************************************************************
+ *
+ * This file contains routines to write output images in GIF format.
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications. As they stand, they assume output to
+ * an ordinary stdio stream.
+ */
+
+/*
+ * This code is loosely based on ppmtogif from the PBMPLUS distribution
+ * of Feb. 1991. That file contains the following copyright notice:
+ * Based on GIFENCODE by David Rowley <mgardi at watdscu.waterloo.edu>.
+ * Lempel-Ziv compression based on "compress" by Spencer W. Thomas et al.
+ * Copyright (C) 1989 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.
+ *
+ * We are also required to state that
+ * "The Graphics Interchange Format(c) is the Copyright property of
+ * CompuServe Incorporated. GIF(sm) is a Service Mark property of
+ * CompuServe Incorporated."
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+
+#ifdef GIF_SUPPORTED
+
+
+#define MAX_LZW_BITS 12 /* maximum LZW code size (4096 symbols) */
+
+typedef INT16 code_int; /* must hold -1 .. 2**MAX_LZW_BITS */
+
+#define LZW_TABLE_SIZE ((code_int) 1 << MAX_LZW_BITS)
+
+#define HSIZE 5003 /* hash table size for 80% occupancy */
+
+typedef int hash_int; /* must hold -2*HSIZE..2*HSIZE */
+
+#define MAXCODE(n_bits) (((code_int) 1 << (n_bits)) - 1)
+
+
+/*
+ * The LZW hash table consists of two parallel arrays:
+ * hash_code[i] code of symbol in slot i, or 0 if empty slot
+ * hash_value[i] symbol's value; undefined if empty slot
+ * where slot values (i) range from 0 to HSIZE-1. The symbol value is
+ * its prefix symbol's code concatenated with its suffix character.
+ *
+ * Algorithm: use open addressing double hashing (no chaining) on the
+ * prefix code / suffix character combination. We do a variant of Knuth's
+ * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
+ * secondary probe.
+ *
+ * The hash_value[] table is allocated from FAR heap space since it would
+ * use up rather a lot of the near data space in a PC.
+ */
+
+typedef INT32 hash_entry; /* must hold (code_int<<8) | byte */
+
+#define HASH_ENTRY(prefix,suffix) ((((hash_entry) (prefix)) << 8) | (suffix))
+
+
+/* Private version of data destination object */
+
+typedef struct {
+ struct djpeg_dest_struct pub; /* public fields */
+
+ j_decompress_ptr cinfo; /* back link saves passing separate parm */
+
+ /* State for packing variable-width codes into a bitstream */
+ int n_bits; /* current number of bits/code */
+ code_int maxcode; /* maximum code, given n_bits */
+ int init_bits; /* initial n_bits ... restored after clear */
+ INT32 cur_accum; /* holds bits not yet output */
+ int cur_bits; /* # of bits in cur_accum */
+
+ /* LZW string construction */
+ code_int waiting_code; /* symbol not yet output; may be extendable */
+ boolean first_byte; /* if TRUE, waiting_code is not valid */
+
+ /* State for LZW code assignment */
+ code_int ClearCode; /* clear code (doesn't change) */
+ code_int EOFCode; /* EOF code (ditto) */
+ code_int free_code; /* first not-yet-used symbol code */
+
+ /* LZW hash table */
+ code_int *hash_code; /* => hash table of symbol codes */
+ hash_entry FAR *hash_value; /* => hash table of symbol values */
+
+ /* GIF data packet construction buffer */
+ int bytesinpkt; /* # of bytes in current packet */
+ char packetbuf[256]; /* workspace for accumulating packet */
+
+} gif_dest_struct;
+
+typedef gif_dest_struct * gif_dest_ptr;
+
+
+/*
+ * Routines to package compressed data bytes into GIF data blocks.
+ * A data block consists of a count byte (1..255) and that many data bytes.
+ */
+
+LOCAL(void)
+flush_packet (gif_dest_ptr dinfo)
+/* flush any accumulated data */
+{
+ if (dinfo->bytesinpkt > 0) { /* never write zero-length packet */
+ dinfo->packetbuf[0] = (char) dinfo->bytesinpkt++;
+ if (JFWRITE(dinfo->pub.output_file, dinfo->packetbuf, dinfo->bytesinpkt)
+ != (size_t) dinfo->bytesinpkt)
+ ERREXIT(dinfo->cinfo, JERR_FILE_WRITE);
+ dinfo->bytesinpkt = 0;
+ }
+}
+
+
+/* Add a character to current packet; flush to disk if necessary */
+#define CHAR_OUT(dinfo,c) \
+ { (dinfo)->packetbuf[++(dinfo)->bytesinpkt] = (char) (c); \
+ if ((dinfo)->bytesinpkt >= 255) \
+ flush_packet(dinfo); \
+ }
+
+
+/* Routine to convert variable-width codes into a byte stream */
+
+LOCAL(void)
+output (gif_dest_ptr dinfo, code_int code)
+/* Emit a code of n_bits bits */
+/* Uses cur_accum and cur_bits to reblock into 8-bit bytes */
+{
+ dinfo->cur_accum |= ((INT32) code) << dinfo->cur_bits;
+ dinfo->cur_bits += dinfo->n_bits;
+
+ while (dinfo->cur_bits >= 8) {
+ CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF);
+ dinfo->cur_accum >>= 8;
+ dinfo->cur_bits -= 8;
+ }
+
+ /*
+ * If the next entry is going to be too big for the code size,
+ * then increase it, if possible. We do this here to ensure
+ * that it's done in sync with the decoder's codesize increases.
+ */
+ if (dinfo->free_code > dinfo->maxcode) {
+ dinfo->n_bits++;
+ if (dinfo->n_bits == MAX_LZW_BITS)
+ dinfo->maxcode = LZW_TABLE_SIZE; /* free_code will never exceed this */
+ else
+ dinfo->maxcode = MAXCODE(dinfo->n_bits);
+ }
+}
+
+
+/* The LZW algorithm proper */
+
+
+LOCAL(void)
+clear_hash (gif_dest_ptr dinfo)
+/* Fill the hash table with empty entries */
+{
+ /* It's sufficient to zero hash_code[] */
+ MEMZERO(dinfo->hash_code, HSIZE * SIZEOF(code_int));
+}
+
+
+LOCAL(void)
+clear_block (gif_dest_ptr dinfo)
+/* Reset compressor and issue a Clear code */
+{
+ clear_hash(dinfo); /* delete all the symbols */
+ dinfo->free_code = dinfo->ClearCode + 2;
+ output(dinfo, dinfo->ClearCode); /* inform decoder */
+ dinfo->n_bits = dinfo->init_bits; /* reset code size */
+ dinfo->maxcode = MAXCODE(dinfo->n_bits);
+}
+
+
+LOCAL(void)
+compress_init (gif_dest_ptr dinfo, int i_bits)
+/* Initialize LZW compressor */
+{
+ /* init all the state variables */
+ dinfo->n_bits = dinfo->init_bits = i_bits;
+ dinfo->maxcode = MAXCODE(dinfo->n_bits);
+ dinfo->ClearCode = ((code_int) 1 << (i_bits - 1));
+ dinfo->EOFCode = dinfo->ClearCode + 1;
+ dinfo->free_code = dinfo->ClearCode + 2;
+ dinfo->first_byte = TRUE; /* no waiting symbol yet */
+ /* init output buffering vars */
+ dinfo->bytesinpkt = 0;
+ dinfo->cur_accum = 0;
+ dinfo->cur_bits = 0;
+ /* clear hash table */
+ clear_hash(dinfo);
+ /* GIF specifies an initial Clear code */
+ output(dinfo, dinfo->ClearCode);
+}
+
+
+LOCAL(void)
+compress_byte (gif_dest_ptr dinfo, int c)
+/* Accept and compress one 8-bit byte */
+{
+ register hash_int i;
+ register hash_int disp;
+ register hash_entry probe_value;
+
+ if (dinfo->first_byte) { /* need to initialize waiting_code */
+ dinfo->waiting_code = c;
+ dinfo->first_byte = FALSE;
+ return;
+ }
+
+ /* Probe hash table to see if a symbol exists for
+ * waiting_code followed by c.
+ * If so, replace waiting_code by that symbol and return.
+ */
+ i = ((hash_int) c << (MAX_LZW_BITS-8)) + dinfo->waiting_code;
+ /* i is less than twice 2**MAX_LZW_BITS, therefore less than twice HSIZE */
+ if (i >= HSIZE)
+ i -= HSIZE;
+
+ probe_value = HASH_ENTRY(dinfo->waiting_code, c);
+
+ if (dinfo->hash_code[i] != 0) { /* is first probed slot empty? */
+ if (dinfo->hash_value[i] == probe_value) {
+ dinfo->waiting_code = dinfo->hash_code[i];
+ return;
+ }
+ if (i == 0) /* secondary hash (after G. Knott) */
+ disp = 1;
+ else
+ disp = HSIZE - i;
+ for (;;) {
+ i -= disp;
+ if (i < 0)
+ i += HSIZE;
+ if (dinfo->hash_code[i] == 0)
+ break; /* hit empty slot */
+ if (dinfo->hash_value[i] == probe_value) {
+ dinfo->waiting_code = dinfo->hash_code[i];
+ return;
+ }
+ }
+ }
+
+ /* here when hashtable[i] is an empty slot; desired symbol not in table */
+ output(dinfo, dinfo->waiting_code);
+ if (dinfo->free_code < LZW_TABLE_SIZE) {
+ dinfo->hash_code[i] = dinfo->free_code++; /* add symbol to hashtable */
+ dinfo->hash_value[i] = probe_value;
+ } else
+ clear_block(dinfo);
+ dinfo->waiting_code = c;
+}
+
+
+LOCAL(void)
+compress_term (gif_dest_ptr dinfo)
+/* Clean up at end */
+{
+ /* Flush out the buffered code */
+ if (! dinfo->first_byte)
+ output(dinfo, dinfo->waiting_code);
+ /* Send an EOF code */
+ output(dinfo, dinfo->EOFCode);
+ /* Flush the bit-packing buffer */
+ if (dinfo->cur_bits > 0) {
+ CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF);
+ }
+ /* Flush the packet buffer */
+ flush_packet(dinfo);
+}
+
+
+/* GIF header construction */
+
+
+LOCAL(void)
+put_word (gif_dest_ptr dinfo, unsigned int w)
+/* Emit a 16-bit word, LSB first */
+{
+ putc(w & 0xFF, dinfo->pub.output_file);
+ putc((w >> 8) & 0xFF, dinfo->pub.output_file);
+}
+
+
+LOCAL(void)
+put_3bytes (gif_dest_ptr dinfo, int val)
+/* Emit 3 copies of same byte value --- handy subr for colormap construction */
+{
+ putc(val, dinfo->pub.output_file);
+ putc(val, dinfo->pub.output_file);
+ putc(val, dinfo->pub.output_file);
+}
+
+
+LOCAL(void)
+emit_header (gif_dest_ptr dinfo, int num_colors, JSAMPARRAY colormap)
+/* Output the GIF file header, including color map */
+/* If colormap==NULL, synthesize a gray-scale colormap */
+{
+ int BitsPerPixel, ColorMapSize, InitCodeSize, FlagByte;
+ int cshift = dinfo->cinfo->data_precision - 8;
+ int i;
+
+ if (num_colors > 256)
+ ERREXIT1(dinfo->cinfo, JERR_TOO_MANY_COLORS, num_colors);
+ /* Compute bits/pixel and related values */
+ BitsPerPixel = 1;
+ while (num_colors > (1 << BitsPerPixel))
+ BitsPerPixel++;
+ ColorMapSize = 1 << BitsPerPixel;
+ if (BitsPerPixel <= 1)
+ InitCodeSize = 2;
+ else
+ InitCodeSize = BitsPerPixel;
+ /*
+ * Write the GIF header.
+ * Note that we generate a plain GIF87 header for maximum compatibility.
+ */
+ putc('G', dinfo->pub.output_file);
+ putc('I', dinfo->pub.output_file);
+ putc('F', dinfo->pub.output_file);
+ putc('8', dinfo->pub.output_file);
+ putc('7', dinfo->pub.output_file);
+ putc('a', dinfo->pub.output_file);
+ /* Write the Logical Screen Descriptor */
+ put_word(dinfo, (unsigned int) dinfo->cinfo->output_width);
+ put_word(dinfo, (unsigned int) dinfo->cinfo->output_height);
+ FlagByte = 0x80; /* Yes, there is a global color table */
+ FlagByte |= (BitsPerPixel-1) << 4; /* color resolution */
+ FlagByte |= (BitsPerPixel-1); /* size of global color table */
+ putc(FlagByte, dinfo->pub.output_file);
+ putc(0, dinfo->pub.output_file); /* Background color index */
+ putc(0, dinfo->pub.output_file); /* Reserved (aspect ratio in GIF89) */
+ /* Write the Global Color Map */
+ /* If the color map is more than 8 bits precision, */
+ /* we reduce it to 8 bits by shifting */
+ for (i=0; i < ColorMapSize; i++) {
+ if (i < num_colors) {
+ if (colormap != NULL) {
+ if (dinfo->cinfo->out_color_space == JCS_RGB) {
+ /* Normal case: RGB color map */
+ putc(GETJSAMPLE(colormap[0][i]) >> cshift, dinfo->pub.output_file);
+ putc(GETJSAMPLE(colormap[1][i]) >> cshift, dinfo->pub.output_file);
+ putc(GETJSAMPLE(colormap[2][i]) >> cshift, dinfo->pub.output_file);
+ } else {
+ /* Grayscale "color map": possible if quantizing grayscale image */
+ put_3bytes(dinfo, GETJSAMPLE(colormap[0][i]) >> cshift);
+ }
+ } else {
+ /* Create a gray-scale map of num_colors values, range 0..255 */
+ put_3bytes(dinfo, (i * 255 + (num_colors-1)/2) / (num_colors-1));
+ }
+ } else {
+ /* fill out the map to a power of 2 */
+ put_3bytes(dinfo, 0);
+ }
+ }
+ /* Write image separator and Image Descriptor */
+ putc(',', dinfo->pub.output_file); /* separator */
+ put_word(dinfo, 0); /* left/top offset */
+ put_word(dinfo, 0);
+ put_word(dinfo, (unsigned int) dinfo->cinfo->output_width); /* image size */
+ put_word(dinfo, (unsigned int) dinfo->cinfo->output_height);
+ /* flag byte: not interlaced, no local color map */
+ putc(0x00, dinfo->pub.output_file);
+ /* Write Initial Code Size byte */
+ putc(InitCodeSize, dinfo->pub.output_file);
+
+ /* Initialize for LZW compression of image data */
+ compress_init(dinfo, InitCodeSize+1);
+}
+
+
+/*
+ * Startup: write the file header.
+ */
+
+METHODDEF(void)
+start_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
+{
+ gif_dest_ptr dest = (gif_dest_ptr) dinfo;
+
+ if (cinfo->quantize_colors)
+ emit_header(dest, cinfo->actual_number_of_colors, cinfo->colormap);
+ else
+ emit_header(dest, 256, (JSAMPARRAY) NULL);
+}
+
+
+/*
+ * Write some pixel data.
+ * In this module rows_supplied will always be 1.
+ */
+
+METHODDEF(void)
+put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ gif_dest_ptr dest = (gif_dest_ptr) dinfo;
+ register JSAMPROW ptr;
+ register JDIMENSION col;
+
+ ptr = dest->pub.buffer[0];
+ for (col = cinfo->output_width; col > 0; col--) {
+ compress_byte(dest, GETJSAMPLE(*ptr++));
+ }
+}
+
+
+/*
+ * Finish up at the end of the file.
+ */
+
+METHODDEF(void)
+finish_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
+{
+ gif_dest_ptr dest = (gif_dest_ptr) dinfo;
+
+ /* Flush LZW mechanism */
+ compress_term(dest);
+ /* Write a zero-length data block to end the series */
+ putc(0, dest->pub.output_file);
+ /* Write the GIF terminator mark */
+ putc(';', dest->pub.output_file);
+ /* Make sure we wrote the output file OK */
+ fflush(dest->pub.output_file);
+ if (ferror(dest->pub.output_file))
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+}
+
+
+/*
+ * The module selection routine for GIF format output.
+ */
+
+GLOBAL(djpeg_dest_ptr)
+jinit_write_gif (j_decompress_ptr cinfo)
+{
+ gif_dest_ptr dest;
+
+ /* Create module interface object, fill in method pointers */
+ dest = (gif_dest_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(gif_dest_struct));
+ dest->cinfo = cinfo; /* make back link for subroutines */
+ dest->pub.start_output = start_output_gif;
+ dest->pub.put_pixel_rows = put_pixel_rows;
+ dest->pub.finish_output = finish_output_gif;
+
+ if (cinfo->out_color_space != JCS_GRAYSCALE &&
+ cinfo->out_color_space != JCS_RGB)
+ ERREXIT(cinfo, JERR_GIF_COLORSPACE);
+
+ /* Force quantization if color or if > 8 bits input */
+ if (cinfo->out_color_space != JCS_GRAYSCALE || cinfo->data_precision > 8) {
+ /* Force quantization to at most 256 colors */
+ cinfo->quantize_colors = TRUE;
+ if (cinfo->desired_number_of_colors > 256)
+ cinfo->desired_number_of_colors = 256;
+ }
+
+ /* Calculate output image dimensions so we can allocate space */
+ jpeg_calc_output_dimensions(cinfo);
+
+ if (cinfo->output_components != 1) /* safety check: just one component? */
+ ERREXIT(cinfo, JERR_GIF_BUG);
+
+ /* Create decompressor output buffer. */
+ dest->pub.buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->output_width, (JDIMENSION) 1);
+ dest->pub.buffer_height = 1;
+
+ /* Allocate space for hash table */
+ dest->hash_code = (code_int *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ HSIZE * SIZEOF(code_int));
+ dest->hash_value = (hash_entry FAR *)
+ (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ HSIZE * SIZEOF(hash_entry));
+
+ return (djpeg_dest_ptr) dest;
+}
+
+#endif /* GIF_SUPPORTED */
diff --git a/jpeg-6c/wrjpgcom.1 b/jpeg-6c/wrjpgcom.1
new file mode 100644
index 0000000..d419a99
--- /dev/null
+++ b/jpeg-6c/wrjpgcom.1
@@ -0,0 +1,103 @@
+.TH WRJPGCOM 1 "15 June 1995"
+.SH NAME
+wrjpgcom \- insert text comments into a JPEG file
+.SH SYNOPSIS
+.B wrjpgcom
+[
+.B \-replace
+]
+[
+.BI \-comment " text"
+]
+[
+.BI \-cfile " name"
+]
+[
+.I filename
+]
+.LP
+.SH DESCRIPTION
+.LP
+.B wrjpgcom
+reads the named JPEG/JFIF file, or the standard input if no file is named,
+and generates a new JPEG/JFIF file on standard output. A comment block is
+added to the file.
+.PP
+The JPEG standard allows "comment" (COM) blocks to occur within a JPEG file.
+Although the standard doesn't actually define what COM blocks are for, they
+are widely used to hold user-supplied text strings. This lets you add
+annotations, titles, index terms, etc to your JPEG files, and later retrieve
+them as text. COM blocks do not interfere with the image stored in the JPEG
+file. The maximum size of a COM block is 64K, but you can have as many of
+them as you like in one JPEG file.
+.PP
+.B wrjpgcom
+adds a COM block, containing text you provide, to a JPEG file.
+Ordinarily, the COM block is added after any existing COM blocks; but you
+can delete the old COM blocks if you wish.
+.SH OPTIONS
+Switch names may be abbreviated, and are not case sensitive.
+.TP
+.B \-replace
+Delete any existing COM blocks from the file.
+.TP
+.BI \-comment " text"
+Supply text for new COM block on command line.
+.TP
+.BI \-cfile " name"
+Read text for new COM block from named file.
+.PP
+If you have only one line of comment text to add, you can provide it on the
+command line with
+.BR \-comment .
+The comment text must be surrounded with quotes so that it is treated as a
+single argument. Longer comments can be read from a text file.
+.PP
+If you give neither
+.B \-comment
+nor
+.BR \-cfile ,
+then
+.B wrjpgcom
+will read the comment text from standard input. (In this case an input image
+file name MUST be supplied, so that the source JPEG file comes from somewhere
+else.) You can enter multiple lines, up to 64KB worth. Type an end-of-file
+indicator (usually control-D) to terminate the comment text entry.
+.PP
+.B wrjpgcom
+will not add a COM block if the provided comment string is empty. Therefore
+\fB\-replace \-comment ""\fR can be used to delete all COM blocks from a file.
+.SH EXAMPLES
+.LP
+Add a short comment to in.jpg, producing out.jpg:
+.IP
+.B wrjpgcom \-c
+\fI"View of my back yard" in.jpg
+.B >
+.I out.jpg
+.PP
+Attach a long comment previously stored in comment.txt:
+.IP
+.B wrjpgcom
+.I in.jpg
+.B <
+.I comment.txt
+.B >
+.I out.jpg
+.PP
+or equivalently
+.IP
+.B wrjpgcom
+.B -cfile
+.I comment.txt
+.B <
+.I in.jpg
+.B >
+.I out.jpg
+.SH SEE ALSO
+.BR cjpeg (1),
+.BR djpeg (1),
+.BR jpegtran (1),
+.BR rdjpgcom (1)
+.SH AUTHOR
+Independent JPEG Group
diff --git a/jpeg-6c/wrjpgcom.c b/jpeg-6c/wrjpgcom.c
new file mode 100644
index 0000000..8c04b05
--- /dev/null
+++ b/jpeg-6c/wrjpgcom.c
@@ -0,0 +1,583 @@
+/*
+ * wrjpgcom.c
+ *
+ * Copyright (C) 1994-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains a very simple stand-alone application that inserts
+ * user-supplied text as a COM (comment) marker in a JFIF file.
+ * This may be useful as an example of the minimum logic needed to parse
+ * JPEG markers.
+ */
+
+#define JPEG_CJPEG_DJPEG /* to get the command-line config symbols */
+#include "jinclude.h" /* get auto-config symbols, <stdio.h> */
+
+#ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc() */
+extern void * malloc ();
+#endif
+#include <ctype.h> /* to declare isupper(), tolower() */
+#ifdef USE_SETMODE
+#include <fcntl.h> /* to declare setmode()'s parameter macros */
+/* If you have setmode() but not <io.h>, just delete this line: */
+#include <io.h> /* to declare setmode() */
+#endif
+
+#ifdef USE_CCOMMAND /* command-line reader for Macintosh */
+#ifdef __MWERKS__
+#include <SIOUX.h> /* Metrowerks needs this */
+#include <console.h> /* ... and this */
+#endif
+#ifdef THINK_C
+#include <console.h> /* Think declares it here */
+#endif
+#endif
+
+#ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
+#define READ_BINARY "r"
+#define WRITE_BINARY "w"
+#else
+#ifdef VMS /* VMS is very nonstandard */
+#define READ_BINARY "rb", "ctx=stm"
+#define WRITE_BINARY "wb", "ctx=stm"
+#else /* standard ANSI-compliant case */
+#define READ_BINARY "rb"
+#define WRITE_BINARY "wb"
+#endif
+#endif
+
+#ifndef EXIT_FAILURE /* define exit() codes if not provided */
+#define EXIT_FAILURE 1
+#endif
+#ifndef EXIT_SUCCESS
+#ifdef VMS
+#define EXIT_SUCCESS 1 /* VMS is very nonstandard */
+#else
+#define EXIT_SUCCESS 0
+#endif
+#endif
+
+/* Reduce this value if your malloc() can't allocate blocks up to 64K.
+ * On DOS, compiling in large model is usually a better solution.
+ */
+
+#ifndef MAX_COM_LENGTH
+#define MAX_COM_LENGTH 65000L /* must be <= 65533 in any case */
+#endif
+
+
+/*
+ * These macros are used to read the input file and write the output file.
+ * To reuse this code in another application, you might need to change these.
+ */
+
+static FILE * infile; /* input JPEG file */
+
+/* Return next input byte, or EOF if no more */
+#define NEXTBYTE() getc(infile)
+
+static FILE * outfile; /* output JPEG file */
+
+/* Emit an output byte */
+#define PUTBYTE(x) putc((x), outfile)
+
+
+/* Error exit handler */
+#define ERREXIT(msg) (fprintf(stderr, "%s\n", msg), exit(EXIT_FAILURE))
+
+
+/* Read one byte, testing for EOF */
+static int
+read_1_byte (void)
+{
+ int c;
+
+ c = NEXTBYTE();
+ if (c == EOF)
+ ERREXIT("Premature EOF in JPEG file");
+ return c;
+}
+
+/* Read 2 bytes, convert to unsigned int */
+/* All 2-byte quantities in JPEG markers are MSB first */
+static unsigned int
+read_2_bytes (void)
+{
+ int c1, c2;
+
+ c1 = NEXTBYTE();
+ if (c1 == EOF)
+ ERREXIT("Premature EOF in JPEG file");
+ c2 = NEXTBYTE();
+ if (c2 == EOF)
+ ERREXIT("Premature EOF in JPEG file");
+ return (((unsigned int) c1) << 8) + ((unsigned int) c2);
+}
+
+
+/* Routines to write data to output file */
+
+static void
+write_1_byte (int c)
+{
+ PUTBYTE(c);
+}
+
+static void
+write_2_bytes (unsigned int val)
+{
+ PUTBYTE((val >> 8) & 0xFF);
+ PUTBYTE(val & 0xFF);
+}
+
+static void
+write_marker (int marker)
+{
+ PUTBYTE(0xFF);
+ PUTBYTE(marker);
+}
+
+static void
+copy_rest_of_file (void)
+{
+ int c;
+
+ while ((c = NEXTBYTE()) != EOF)
+ PUTBYTE(c);
+}
+
+
+/*
+ * JPEG markers consist of one or more 0xFF bytes, followed by a marker
+ * code byte (which is not an FF). Here are the marker codes of interest
+ * in this program. (See jdmarker.c for a more complete list.)
+ */
+
+#define M_SOF0 0xC0 /* Start Of Frame N */
+#define M_SOF1 0xC1 /* N indicates which compression process */
+#define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */
+#define M_SOF3 0xC3
+#define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */
+#define M_SOF6 0xC6
+#define M_SOF7 0xC7
+#define M_SOF9 0xC9
+#define M_SOF10 0xCA
+#define M_SOF11 0xCB
+#define M_SOF13 0xCD
+#define M_SOF14 0xCE
+#define M_SOF15 0xCF
+#define M_SOI 0xD8 /* Start Of Image (beginning of datastream) */
+#define M_EOI 0xD9 /* End Of Image (end of datastream) */
+#define M_SOS 0xDA /* Start Of Scan (begins compressed data) */
+#define M_COM 0xFE /* COMment */
+
+
+/*
+ * Find the next JPEG marker and return its marker code.
+ * We expect at least one FF byte, possibly more if the compressor used FFs
+ * to pad the file. (Padding FFs will NOT be replicated in the output file.)
+ * There could also be non-FF garbage between markers. The treatment of such
+ * garbage is unspecified; we choose to skip over it but emit a warning msg.
+ * NB: this routine must not be used after seeing SOS marker, since it will
+ * not deal correctly with FF/00 sequences in the compressed image data...
+ */
+
+static int
+next_marker (void)
+{
+ int c;
+ int discarded_bytes = 0;
+
+ /* Find 0xFF byte; count and skip any non-FFs. */
+ c = read_1_byte();
+ while (c != 0xFF) {
+ discarded_bytes++;
+ c = read_1_byte();
+ }
+ /* Get marker code byte, swallowing any duplicate FF bytes. Extra FFs
+ * are legal as pad bytes, so don't count them in discarded_bytes.
+ */
+ do {
+ c = read_1_byte();
+ } while (c == 0xFF);
+
+ if (discarded_bytes != 0) {
+ fprintf(stderr, "Warning: garbage data found in JPEG file\n");
+ }
+
+ return c;
+}
+
+
+/*
+ * Read the initial marker, which should be SOI.
+ * For a JFIF file, the first two bytes of the file should be literally
+ * 0xFF M_SOI. To be more general, we could use next_marker, but if the
+ * input file weren't actually JPEG at all, next_marker might read the whole
+ * file and then return a misleading error message...
+ */
+
+static int
+first_marker (void)
+{
+ int c1, c2;
+
+ c1 = NEXTBYTE();
+ c2 = NEXTBYTE();
+ if (c1 != 0xFF || c2 != M_SOI)
+ ERREXIT("Not a JPEG file");
+ return c2;
+}
+
+
+/*
+ * Most types of marker are followed by a variable-length parameter segment.
+ * This routine skips over the parameters for any marker we don't otherwise
+ * want to process.
+ * Note that we MUST skip the parameter segment explicitly in order not to
+ * be fooled by 0xFF bytes that might appear within the parameter segment;
+ * such bytes do NOT introduce new markers.
+ */
+
+static void
+copy_variable (void)
+/* Copy an unknown or uninteresting variable-length marker */
+{
+ unsigned int length;
+
+ /* Get the marker parameter length count */
+ length = read_2_bytes();
+ write_2_bytes(length);
+ /* Length includes itself, so must be at least 2 */
+ if (length < 2)
+ ERREXIT("Erroneous JPEG marker length");
+ length -= 2;
+ /* Skip over the remaining bytes */
+ while (length > 0) {
+ write_1_byte(read_1_byte());
+ length--;
+ }
+}
+
+static void
+skip_variable (void)
+/* Skip over an unknown or uninteresting variable-length marker */
+{
+ unsigned int length;
+
+ /* Get the marker parameter length count */
+ length = read_2_bytes();
+ /* Length includes itself, so must be at least 2 */
+ if (length < 2)
+ ERREXIT("Erroneous JPEG marker length");
+ length -= 2;
+ /* Skip over the remaining bytes */
+ while (length > 0) {
+ (void) read_1_byte();
+ length--;
+ }
+}
+
+
+/*
+ * Parse the marker stream until SOFn or EOI is seen;
+ * copy data to output, but discard COM markers unless keep_COM is true.
+ */
+
+static int
+scan_JPEG_header (int keep_COM)
+{
+ int marker;
+
+ /* Expect SOI at start of file */
+ if (first_marker() != M_SOI)
+ ERREXIT("Expected SOI marker first");
+ write_marker(M_SOI);
+
+ /* Scan miscellaneous markers until we reach SOFn. */
+ for (;;) {
+ marker = next_marker();
+ switch (marker) {
+ /* Note that marker codes 0xC4, 0xC8, 0xCC are not, and must not be,
+ * treated as SOFn. C4 in particular is actually DHT.
+ */
+ case M_SOF0: /* Baseline */
+ case M_SOF1: /* Extended sequential, Huffman */
+ case M_SOF2: /* Progressive, Huffman */
+ case M_SOF3: /* Lossless, Huffman */
+ case M_SOF5: /* Differential sequential, Huffman */
+ case M_SOF6: /* Differential progressive, Huffman */
+ case M_SOF7: /* Differential lossless, Huffman */
+ case M_SOF9: /* Extended sequential, arithmetic */
+ case M_SOF10: /* Progressive, arithmetic */
+ case M_SOF11: /* Lossless, arithmetic */
+ case M_SOF13: /* Differential sequential, arithmetic */
+ case M_SOF14: /* Differential progressive, arithmetic */
+ case M_SOF15: /* Differential lossless, arithmetic */
+ return marker;
+
+ case M_SOS: /* should not see compressed data before SOF */
+ ERREXIT("SOS without prior SOFn");
+ break;
+
+ case M_EOI: /* in case it's a tables-only JPEG stream */
+ return marker;
+
+ case M_COM: /* Existing COM: conditionally discard */
+ if (keep_COM) {
+ write_marker(marker);
+ copy_variable();
+ } else {
+ skip_variable();
+ }
+ break;
+
+ default: /* Anything else just gets copied */
+ write_marker(marker);
+ copy_variable(); /* we assume it has a parameter count... */
+ break;
+ }
+ } /* end loop */
+}
+
+
+/* Command line parsing code */
+
+static const char * progname; /* program name for error messages */
+
+
+static void
+usage (void)
+/* complain about bad command line */
+{
+ fprintf(stderr, "wrjpgcom inserts a textual comment in a JPEG file.\n");
+ fprintf(stderr, "You can add to or replace any existing comment(s).\n");
+
+ fprintf(stderr, "Usage: %s [switches] ", progname);
+#ifdef TWO_FILE_COMMANDLINE
+ fprintf(stderr, "inputfile outputfile\n");
+#else
+ fprintf(stderr, "[inputfile]\n");
+#endif
+
+ fprintf(stderr, "Switches (names may be abbreviated):\n");
+ fprintf(stderr, " -replace Delete any existing comments\n");
+ fprintf(stderr, " -comment \"text\" Insert comment with given text\n");
+ fprintf(stderr, " -cfile name Read comment from named file\n");
+ fprintf(stderr, "Notice that you must put quotes around the comment text\n");
+ fprintf(stderr, "when you use -comment.\n");
+ fprintf(stderr, "If you do not give either -comment or -cfile on the command line,\n");
+ fprintf(stderr, "then the comment text is read from standard input.\n");
+ fprintf(stderr, "It can be multiple lines, up to %u characters total.\n",
+ (unsigned int) MAX_COM_LENGTH);
+#ifndef TWO_FILE_COMMANDLINE
+ fprintf(stderr, "You must specify an input JPEG file name when supplying\n");
+ fprintf(stderr, "comment text from standard input.\n");
+#endif
+
+ exit(EXIT_FAILURE);
+}
+
+
+static int
+keymatch (char * arg, const char * keyword, int minchars)
+/* Case-insensitive matching of (possibly abbreviated) keyword switches. */
+/* keyword is the constant keyword (must be lower case already), */
+/* minchars is length of minimum legal abbreviation. */
+{
+ register int ca, ck;
+ register int nmatched = 0;
+
+ while ((ca = *arg++) != '\0') {
+ if ((ck = *keyword++) == '\0')
+ return 0; /* arg longer than keyword, no good */
+ if (isupper(ca)) /* force arg to lcase (assume ck is already) */
+ ca = tolower(ca);
+ if (ca != ck)
+ return 0; /* no good */
+ nmatched++; /* count matched characters */
+ }
+ /* reached end of argument; fail if it's too short for unique abbrev */
+ if (nmatched < minchars)
+ return 0;
+ return 1; /* A-OK */
+}
+
+
+/*
+ * The main program.
+ */
+
+int
+main (int argc, char **argv)
+{
+ int argn;
+ char * arg;
+ int keep_COM = 1;
+ char * comment_arg = NULL;
+ FILE * comment_file = NULL;
+ unsigned int comment_length = 0;
+ int marker;
+
+ /* On Mac, fetch a command line. */
+#ifdef USE_CCOMMAND
+ argc = ccommand(&argv);
+#endif
+
+ progname = argv[0];
+ if (progname == NULL || progname[0] == 0)
+ progname = "wrjpgcom"; /* in case C library doesn't provide it */
+
+ /* Parse switches, if any */
+ for (argn = 1; argn < argc; argn++) {
+ arg = argv[argn];
+ if (arg[0] != '-')
+ break; /* not switch, must be file name */
+ arg++; /* advance over '-' */
+ if (keymatch(arg, "replace", 1)) {
+ keep_COM = 0;
+ } else if (keymatch(arg, "cfile", 2)) {
+ if (++argn >= argc) usage();
+ if ((comment_file = fopen(argv[argn], "r")) == NULL) {
+ fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
+ exit(EXIT_FAILURE);
+ }
+ } else if (keymatch(arg, "comment", 1)) {
+ if (++argn >= argc) usage();
+ comment_arg = argv[argn];
+ /* If the comment text starts with '"', then we are probably running
+ * under MS-DOG and must parse out the quoted string ourselves. Sigh.
+ */
+ if (comment_arg[0] == '"') {
+ comment_arg = (char *) malloc((size_t) MAX_COM_LENGTH);
+ if (comment_arg == NULL)
+ ERREXIT("Insufficient memory");
+ strcpy(comment_arg, argv[argn]+1);
+ for (;;) {
+ comment_length = (unsigned int) strlen(comment_arg);
+ if (comment_length > 0 && comment_arg[comment_length-1] == '"') {
+ comment_arg[comment_length-1] = '\0'; /* zap terminating quote */
+ break;
+ }
+ if (++argn >= argc)
+ ERREXIT("Missing ending quote mark");
+ strcat(comment_arg, " ");
+ strcat(comment_arg, argv[argn]);
+ }
+ }
+ comment_length = (unsigned int) strlen(comment_arg);
+ } else
+ usage();
+ }
+
+ /* Cannot use both -comment and -cfile. */
+ if (comment_arg != NULL && comment_file != NULL)
+ usage();
+ /* If there is neither -comment nor -cfile, we will read the comment text
+ * from stdin; in this case there MUST be an input JPEG file name.
+ */
+ if (comment_arg == NULL && comment_file == NULL && argn >= argc)
+ usage();
+
+ /* Open the input file. */
+ if (argn < argc) {
+ if ((infile = fopen(argv[argn], READ_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ /* default input file is stdin */
+#ifdef USE_SETMODE /* need to hack file mode? */
+ setmode(fileno(stdin), O_BINARY);
+#endif
+#ifdef USE_FDOPEN /* need to re-open in binary mode? */
+ if ((infile = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open stdin\n", progname);
+ exit(EXIT_FAILURE);
+ }
+#else
+ infile = stdin;
+#endif
+ }
+
+ /* Open the output file. */
+#ifdef TWO_FILE_COMMANDLINE
+ /* Must have explicit output file name */
+ if (argn != argc-2) {
+ fprintf(stderr, "%s: must name one input and one output file\n",
+ progname);
+ usage();
+ }
+ if ((outfile = fopen(argv[argn+1], WRITE_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open %s\n", progname, argv[argn+1]);
+ exit(EXIT_FAILURE);
+ }
+#else
+ /* Unix style: expect zero or one file name */
+ if (argn < argc-1) {
+ fprintf(stderr, "%s: only one input file\n", progname);
+ usage();
+ }
+ /* default output file is stdout */
+#ifdef USE_SETMODE /* need to hack file mode? */
+ setmode(fileno(stdout), O_BINARY);
+#endif
+#ifdef USE_FDOPEN /* need to re-open in binary mode? */
+ if ((outfile = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) {
+ fprintf(stderr, "%s: can't open stdout\n", progname);
+ exit(EXIT_FAILURE);
+ }
+#else
+ outfile = stdout;
+#endif
+#endif /* TWO_FILE_COMMANDLINE */
+
+ /* Collect comment text from comment_file or stdin, if necessary */
+ if (comment_arg == NULL) {
+ FILE * src_file;
+ int c;
+
+ comment_arg = (char *) malloc((size_t) MAX_COM_LENGTH);
+ if (comment_arg == NULL)
+ ERREXIT("Insufficient memory");
+ comment_length = 0;
+ src_file = (comment_file != NULL ? comment_file : stdin);
+ while ((c = getc(src_file)) != EOF) {
+ if (comment_length >= (unsigned int) MAX_COM_LENGTH) {
+ fprintf(stderr, "Comment text may not exceed %u bytes\n",
+ (unsigned int) MAX_COM_LENGTH);
+ exit(EXIT_FAILURE);
+ }
+ comment_arg[comment_length++] = (char) c;
+ }
+ if (comment_file != NULL)
+ fclose(comment_file);
+ }
+
+ /* Copy JPEG headers until SOFn marker;
+ * we will insert the new comment marker just before SOFn.
+ * This (a) causes the new comment to appear after, rather than before,
+ * existing comments; and (b) ensures that comments come after any JFIF
+ * or JFXX markers, as required by the JFIF specification.
+ */
+ marker = scan_JPEG_header(keep_COM);
+ /* Insert the new COM marker, but only if nonempty text has been supplied */
+ if (comment_length > 0) {
+ write_marker(M_COM);
+ write_2_bytes(comment_length + 2);
+ while (comment_length > 0) {
+ write_1_byte(*comment_arg++);
+ comment_length--;
+ }
+ }
+ /* Duplicate the remainder of the source file.
+ * Note that any COM markers occuring after SOF will not be touched.
+ */
+ write_marker(marker);
+ copy_rest_of_file();
+
+ /* All done. */
+ exit(EXIT_SUCCESS);
+ return 0; /* suppress no-return-value warnings */
+}
diff --git a/jpeg-6c/wrppm.c b/jpeg-6c/wrppm.c
new file mode 100644
index 0000000..061a3f8
--- /dev/null
+++ b/jpeg-6c/wrppm.c
@@ -0,0 +1,343 @@
+/*
+ * wrppm.c
+ *
+ * Copyright (C) 1991-1996, Thomas G. Lane.
+ * Modifided for multibit by Bruce Barton of BITS Limited (shameless plug), 2009, (GPL).
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to write output images in PPM/PGM format.
+ * The extended 2-byte-per-sample raw PPM/PGM formats are supported.
+ * The PBMPLUS library is NOT required to compile this software
+ * (but it is highly useful as a set of PPM image manipulation programs).
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications. As they stand, they assume output to
+ * an ordinary stdio stream.
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+
+#ifdef PPM_SUPPORTED
+
+
+/*
+ * For 12-bit JPEG data, we either downscale the values to 8 bits
+ * (to write standard byte-per-sample PPM/PGM files), or output
+ * nonstandard word-per-sample PPM/PGM files. Downscaling is done
+ * if PPM_NORAWWORD is defined (this can be done in the Makefile
+ * or in jconfig.h).
+ * (When the core library supports data precision reduction, a cleaner
+ * implementation will be to ask for that instead.)
+ */
+
+/*#if BITS_IN_JSAMPLE == 8
+#define PUTPPMSAMPLE(ptr,v) *ptr++ = (char) (v)
+#define BYTESPERSAMPLE 1
+#define PPM_MAXVAL 255
+#else
+#ifdef PPM_NORAWWORD
+#define PUTPPMSAMPLE(ptr,v) *ptr++ = (char) ((v) >> (cinfo->data_precision-8))
+#define BYTESPERSAMPLE 1
+#define PPM_MAXVAL 255
+#else*/
+/* The word-per-sample format always puts the LSB first. */
+/*#define PUTPPMSAMPLE(ptr,v) \
+ { register int val_ = v; \
+ *ptr++ = (char) (val_ & 0xFF); \
+ *ptr++ = (char) ((val_ >> 8) & 0xFF); \
+ }
+#define BYTESPERSAMPLE 2
+#define PPM_MAXVAL ((1<<cinfo->data_precision)-1)
+#endif
+#endif*/
+
+
+/*
+ * When JSAMPLE is the same size as char, we can just fwrite() the
+ * decompressed data to the PPM or PGM file. On PCs, in order to make this
+ * work the output buffer must be allocated in near data space, because we are
+ * assuming small-data memory model wherein fwrite() can't reach far memory.
+ * If you need to process very wide images on a PC, you might have to compile
+ * in large-memory model, or else replace fwrite() with a putc() loop ---
+ * which will be much slower.
+ */
+
+
+/* Private version of data destination object */
+
+typedef struct {
+ struct djpeg_dest_struct pub; /* public fields */
+
+ /* Usually these two pointers point to the same place: */
+ char *iobuffer; /* fwrite's I/O buffer */
+/* JSAMPROW16 pixrow;*/ /* decompressor output buffer */
+ size_t buffer_width; /* width of I/O buffer */
+ JDIMENSION samples_per_row; /* JSAMPLEs per output row */
+} ppm_dest_struct;
+
+typedef ppm_dest_struct * ppm_dest_ptr;
+
+
+/*
+ * Write some pixel data.
+ * In this module rows_supplied will always be 1.
+ *
+ * put_pixel_rows handles the "normal" 8-bit case where the decompressor
+ * output buffer is physically the same as the fwrite buffer.
+ */
+
+/*METHODDEF(void)
+put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}*/
+
+
+/*
+ * This code is used when we have to copy the data and apply a pixel
+ * format translation. Typically this only happens in 12-bit mode.
+ */
+
+METHODDEF(void)
+copy_pixel_rows8 (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register JSAMPROW16 ptr;
+ register JDIMENSION col;
+
+ ptr = (JSAMPROW16)dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = dest->samples_per_row; col > 0; col--) {
+ *bufferptr++ = (char)GETJSAMPLE(*ptr++);
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+METHODDEF(void)
+copy_pixel_rows16 (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register JSAMPROW16 ptr;
+ register JDIMENSION col;
+ register int val;
+
+ ptr = (JSAMPROW16)dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = dest->samples_per_row; col > 0; col--) {
+ val = GETJSAMPLE(*ptr++);
+ *bufferptr++ = (char)((val >> 8) & 0xFF);
+ *bufferptr++ = (char)(val & 0xFF);
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+/*
+ * Write some pixel data when color quantization is in effect.
+ * We have to demap the color index values to straight data.
+ */
+
+METHODDEF(void)
+put_demapped_rgb8 (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register int pixval;
+ register JSAMPROW16 ptr;
+ register JSAMPROW16 color_map0 = cinfo->colormap16[0];
+ register JSAMPROW16 color_map1 = cinfo->colormap16[1];
+ register JSAMPROW16 color_map2 = cinfo->colormap16[2];
+ register JDIMENSION col;
+
+ ptr = (JSAMPROW16)dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = cinfo->output_width; col > 0; col--) {
+ pixval = GETJSAMPLE(*ptr++);
+ *bufferptr++ = (char)GETJSAMPLE(color_map0[pixval]);
+ *bufferptr++ = (char)GETJSAMPLE(color_map1[pixval]);
+ *bufferptr++ = (char)GETJSAMPLE(color_map2[pixval]);
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+METHODDEF(void)
+put_demapped_rgb16 (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register int pixval, val;
+ register JSAMPROW16 ptr;
+ register JSAMPROW16 color_map0 = cinfo->colormap16[0];
+ register JSAMPROW16 color_map1 = cinfo->colormap16[1];
+ register JSAMPROW16 color_map2 = cinfo->colormap16[2];
+ register JDIMENSION col;
+
+ ptr = (JSAMPROW16)dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = cinfo->output_width; col > 0; col--) {
+ pixval = GETJSAMPLE(*ptr++);
+ val = GETJSAMPLE(color_map0[pixval]);
+ *bufferptr++ = (char)((val >> 8) & 0xFF);
+ *bufferptr++ = (char)(val & 0xFF);
+ val = GETJSAMPLE(color_map1[pixval]);
+ *bufferptr++ = (char)((val >> 8) & 0xFF);
+ *bufferptr++ = (char)(val & 0xFF);
+ val = GETJSAMPLE(color_map2[pixval]);
+ *bufferptr++ = (char)((val >> 8) & 0xFF);
+ *bufferptr++ = (char)(val & 0xFF);
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+METHODDEF(void)
+put_demapped_gray8 (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register JSAMPROW16 ptr;
+ register JSAMPROW16 color_map = cinfo->colormap16[0];
+ register JDIMENSION col;
+
+ ptr = (JSAMPROW16)dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = cinfo->output_width; col > 0; col--) {
+ *bufferptr++ = (char)GETJSAMPLE(color_map[GETJSAMPLE(*ptr++)]);
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+METHODDEF(void)
+put_demapped_gray16 (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ register char * bufferptr;
+ register JSAMPROW16 ptr;
+ register JSAMPROW16 color_map = cinfo->colormap16[0];
+ register JDIMENSION col;
+ register int val;
+
+ ptr = (JSAMPROW16)dest->pub.buffer[0];
+ bufferptr = dest->iobuffer;
+ for (col = cinfo->output_width; col > 0; col--) {
+ val = GETJSAMPLE(color_map[GETJSAMPLE(*ptr++)]);
+ *bufferptr++ = (char)((val >> 8) & 0xFF);
+ *bufferptr++ = (char)(val & 0xFF);
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+
+/*
+ * Startup: write the file header.
+ */
+
+METHODDEF(void)
+start_output_ppm (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
+{
+ ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
+ int ppm_maxval;
+
+ /* Create physical I/O buffer. Note we make this near on a PC. */
+ cinfo->buffer_size_char = FALSE; /* JSAMPLE16 buffer sent. */
+ if (cinfo->data_precision_other <= 8)
+ dest->buffer_width = dest->samples_per_row * SIZEOF(char);
+ else dest->buffer_width = dest->samples_per_row * SIZEOF(JSAMPLE16);
+ dest->iobuffer = (char *) (*cinfo->mem->alloc_small)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, dest->buffer_width);
+
+ ppm_maxval = (1<<cinfo->data_precision_other)-1;
+
+ /* Emit file header */
+ switch (cinfo->out_color_space) {
+ case JCS_GRAYSCALE:
+ /* emit header for raw PGM format */
+ fprintf(dest->pub.output_file, "P5\n%ld %ld\n%d\n",
+ (long) cinfo->output_width, (long) cinfo->output_height,
+ ppm_maxval);
+ break;
+ case JCS_RGB:
+ /* emit header for raw PPM format */
+ fprintf(dest->pub.output_file, "P6\n%ld %ld\n%d\n",
+ (long) cinfo->output_width, (long) cinfo->output_height,
+ ppm_maxval);
+ break;
+ default:
+ ERREXIT(cinfo, JERR_PPM_COLORSPACE);
+ }
+}
+
+
+/*
+ * Finish up at the end of the file.
+ */
+
+METHODDEF(void)
+finish_output_ppm (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
+{
+ /* Make sure we wrote the output file OK */
+ fflush(dinfo->output_file);
+ if (ferror(dinfo->output_file))
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+}
+
+
+/*
+ * The module selection routine for PPM format output.
+ */
+
+GLOBAL(djpeg_dest_ptr)
+jinit_write_ppm (j_decompress_ptr cinfo)
+{
+ ppm_dest_ptr dest;
+
+ /* Create module interface object, fill in method pointers */
+ dest = (ppm_dest_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(ppm_dest_struct));
+ dest->pub.start_output = start_output_ppm;
+ dest->pub.finish_output = finish_output_ppm;
+
+ /* Calculate output image dimensions so we can allocate space */
+ jpeg_calc_output_dimensions(cinfo);
+
+ /* Dimensions for the physical I/O buffer. */
+ dest->samples_per_row = cinfo->output_width * cinfo->out_color_components;
+
+ /* A JSAMPLE16 buffer for decompression now that jdapistd take it.
+ * Conversion to 8 bit if needed is done later with copy or put 8.
+ * Scaling is now done by the jpeg library. */
+ dest->pub.buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (JDIMENSION) cinfo->output_width * cinfo->output_components
+ * SIZEOF(JSAMPLE16),(JDIMENSION) 1);
+ dest->pub.buffer_height = 1;
+
+ if (cinfo->data_precision_other <= 8) {
+ if (cinfo->quantize_colors) {
+ if (cinfo->out_color_space == JCS_GRAYSCALE)
+ dest->pub.put_pixel_rows = put_demapped_gray8;
+ else dest->pub.put_pixel_rows = put_demapped_rgb8; /* Maped color */
+ } else dest->pub.put_pixel_rows = copy_pixel_rows8; /* Default 8 bit */
+ } else { /* > 8 bit output */
+ if (cinfo->quantize_colors) {
+ if (cinfo->out_color_space == JCS_GRAYSCALE)
+ dest->pub.put_pixel_rows = put_demapped_gray16;
+ else dest->pub.put_pixel_rows = put_demapped_rgb16;
+ } else dest->pub.put_pixel_rows = copy_pixel_rows16; /* No quanttize */
+ }
+
+ return (djpeg_dest_ptr) dest;
+}
+
+#endif /* PPM_SUPPORTED */
diff --git a/jpeg-6c/wrrle.c b/jpeg-6c/wrrle.c
new file mode 100644
index 0000000..a4e7337
--- /dev/null
+++ b/jpeg-6c/wrrle.c
@@ -0,0 +1,305 @@
+/*
+ * wrrle.c
+ *
+ * Copyright (C) 1991-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to write output images in RLE format.
+ * The Utah Raster Toolkit library is required (version 3.1 or later).
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications. As they stand, they assume output to
+ * an ordinary stdio stream.
+ *
+ * Based on code contributed by Mike Lijewski,
+ * with updates from Robert Hutchinson.
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+
+#ifdef RLE_SUPPORTED
+
+/* rle.h is provided by the Utah Raster Toolkit. */
+
+#include <rle.h>
+
+/*
+ * We assume that JSAMPLE has the same representation as rle_pixel,
+ * to wit, "unsigned char". Hence we can't cope with 12- or 16-bit samples.
+ */
+
+#if BITS_IN_JSAMPLE != 8
+ Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
+#endif
+
+
+/*
+ * Since RLE stores scanlines bottom-to-top, we have to invert the image
+ * from JPEG's top-to-bottom order. To do this, we save the outgoing data
+ * in a virtual array during put_pixel_row calls, then actually emit the
+ * RLE file during finish_output.
+ */
+
+
+/*
+ * For now, if we emit an RLE color map then it is always 256 entries long,
+ * though not all of the entries need be used.
+ */
+
+#define CMAPBITS 8
+#define CMAPLENGTH (1<<(CMAPBITS))
+
+typedef struct {
+ struct djpeg_dest_struct pub; /* public fields */
+
+ jvirt_sarray_ptr image; /* virtual array to store the output image */
+ rle_map *colormap; /* RLE-style color map, or NULL if none */
+ rle_pixel **rle_row; /* To pass rows to rle_putrow() */
+
+} rle_dest_struct;
+
+typedef rle_dest_struct * rle_dest_ptr;
+
+/* Forward declarations */
+METHODDEF(void) rle_put_pixel_rows
+ JPP((j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied));
+
+
+/*
+ * Write the file header.
+ *
+ * In this module it's easier to wait till finish_output to write anything.
+ */
+
+METHODDEF(void)
+start_output_rle (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
+{
+ rle_dest_ptr dest = (rle_dest_ptr) dinfo;
+ size_t cmapsize;
+ int i, ci;
+#ifdef PROGRESS_REPORT
+ cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
+#endif
+
+ /*
+ * Make sure the image can be stored in RLE format.
+ *
+ * - RLE stores image dimensions as *signed* 16 bit integers. JPEG
+ * uses unsigned, so we have to check the width.
+ *
+ * - Colorspace is expected to be grayscale or RGB.
+ *
+ * - The number of channels (components) is expected to be 1 (grayscale/
+ * pseudocolor) or 3 (truecolor/directcolor).
+ * (could be 2 or 4 if using an alpha channel, but we aren't)
+ */
+
+ if (cinfo->output_width > 32767 || cinfo->output_height > 32767)
+ ERREXIT2(cinfo, JERR_RLE_DIMENSIONS, cinfo->output_width,
+ cinfo->output_height);
+
+ if (cinfo->out_color_space != JCS_GRAYSCALE &&
+ cinfo->out_color_space != JCS_RGB)
+ ERREXIT(cinfo, JERR_RLE_COLORSPACE);
+
+ if (cinfo->output_components != 1 && cinfo->output_components != 3)
+ ERREXIT1(cinfo, JERR_RLE_TOOMANYCHANNELS, cinfo->num_components);
+
+ /* Convert colormap, if any, to RLE format. */
+
+ dest->colormap = NULL;
+
+ if (cinfo->quantize_colors) {
+ /* Allocate storage for RLE-style cmap, zero any extra entries */
+ cmapsize = cinfo->out_color_components * CMAPLENGTH * SIZEOF(rle_map);
+ dest->colormap = (rle_map *) (*cinfo->mem->alloc_small)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, cmapsize);
+ MEMZERO(dest->colormap, cmapsize);
+
+ /* Save away data in RLE format --- note 8-bit left shift! */
+ /* Shifting would need adjustment for JSAMPLEs wider than 8 bits. */
+ for (ci = 0; ci < cinfo->out_color_components; ci++) {
+ for (i = 0; i < cinfo->actual_number_of_colors; i++) {
+ dest->colormap[ci * CMAPLENGTH + i] =
+ GETJSAMPLE(cinfo->colormap[ci][i]) << 8;
+ }
+ }
+ }
+
+ /* Set the output buffer to the first row */
+ dest->pub.buffer = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, dest->image, (JDIMENSION) 0, (JDIMENSION) 1, TRUE);
+ dest->pub.buffer_height = 1;
+
+ dest->pub.put_pixel_rows = rle_put_pixel_rows;
+
+#ifdef PROGRESS_REPORT
+ if (progress != NULL) {
+ progress->total_extra_passes++; /* count file writing as separate pass */
+ }
+#endif
+}
+
+
+/*
+ * Write some pixel data.
+ *
+ * This routine just saves the data away in a virtual array.
+ */
+
+METHODDEF(void)
+rle_put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ rle_dest_ptr dest = (rle_dest_ptr) dinfo;
+
+ if (cinfo->output_scanline < cinfo->output_height) {
+ dest->pub.buffer = (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, dest->image,
+ cinfo->output_scanline, (JDIMENSION) 1, TRUE);
+ }
+}
+
+/*
+ * Finish up at the end of the file.
+ *
+ * Here is where we really output the RLE file.
+ */
+
+METHODDEF(void)
+finish_output_rle (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
+{
+ rle_dest_ptr dest = (rle_dest_ptr) dinfo;
+ rle_hdr header; /* Output file information */
+ rle_pixel **rle_row, *red, *green, *blue;
+ JSAMPROW output_row;
+ char cmapcomment[80];
+ int row, col;
+ int ci;
+#ifdef PROGRESS_REPORT
+ cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
+#endif
+
+ /* Initialize the header info */
+ header = *rle_hdr_init(NULL);
+ header.rle_file = dest->pub.output_file;
+ header.xmin = 0;
+ header.xmax = cinfo->output_width - 1;
+ header.ymin = 0;
+ header.ymax = cinfo->output_height - 1;
+ header.alpha = 0;
+ header.ncolors = cinfo->output_components;
+ for (ci = 0; ci < cinfo->output_components; ci++) {
+ RLE_SET_BIT(header, ci);
+ }
+ if (cinfo->quantize_colors) {
+ header.ncmap = cinfo->out_color_components;
+ header.cmaplen = CMAPBITS;
+ header.cmap = dest->colormap;
+ /* Add a comment to the output image with the true colormap length. */
+ sprintf(cmapcomment, "color_map_length=%d", cinfo->actual_number_of_colors);
+ rle_putcom(cmapcomment, &header);
+ }
+
+ /* Emit the RLE header and color map (if any) */
+ rle_put_setup(&header);
+
+ /* Now output the RLE data from our virtual array.
+ * We assume here that (a) rle_pixel is represented the same as JSAMPLE,
+ * and (b) we are not on a machine where FAR pointers differ from regular.
+ */
+
+#ifdef PROGRESS_REPORT
+ if (progress != NULL) {
+ progress->pub.pass_limit = cinfo->output_height;
+ progress->pub.pass_counter = 0;
+ (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
+ }
+#endif
+
+ if (cinfo->output_components == 1) {
+ for (row = cinfo->output_height-1; row >= 0; row--) {
+ rle_row = (rle_pixel **) (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, dest->image,
+ (JDIMENSION) row, (JDIMENSION) 1, FALSE);
+ rle_putrow(rle_row, (int) cinfo->output_width, &header);
+#ifdef PROGRESS_REPORT
+ if (progress != NULL) {
+ progress->pub.pass_counter++;
+ (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
+ }
+#endif
+ }
+ } else {
+ for (row = cinfo->output_height-1; row >= 0; row--) {
+ rle_row = (rle_pixel **) dest->rle_row;
+ output_row = * (*cinfo->mem->access_virt_sarray)
+ ((j_common_ptr) cinfo, dest->image,
+ (JDIMENSION) row, (JDIMENSION) 1, FALSE);
+ red = rle_row[0];
+ green = rle_row[1];
+ blue = rle_row[2];
+ for (col = cinfo->output_width; col > 0; col--) {
+ *red++ = GETJSAMPLE(*output_row++);
+ *green++ = GETJSAMPLE(*output_row++);
+ *blue++ = GETJSAMPLE(*output_row++);
+ }
+ rle_putrow(rle_row, (int) cinfo->output_width, &header);
+#ifdef PROGRESS_REPORT
+ if (progress != NULL) {
+ progress->pub.pass_counter++;
+ (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
+ }
+#endif
+ }
+ }
+
+#ifdef PROGRESS_REPORT
+ if (progress != NULL)
+ progress->completed_extra_passes++;
+#endif
+
+ /* Emit file trailer */
+ rle_puteof(&header);
+ fflush(dest->pub.output_file);
+ if (ferror(dest->pub.output_file))
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+}
+
+
+/*
+ * The module selection routine for RLE format output.
+ */
+
+GLOBAL(djpeg_dest_ptr)
+jinit_write_rle (j_decompress_ptr cinfo)
+{
+ rle_dest_ptr dest;
+
+ /* Create module interface object, fill in method pointers */
+ dest = (rle_dest_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(rle_dest_struct));
+ dest->pub.start_output = start_output_rle;
+ dest->pub.finish_output = finish_output_rle;
+
+ /* Calculate output image dimensions so we can allocate space */
+ jpeg_calc_output_dimensions(cinfo);
+
+ /* Allocate a work array for output to the RLE library. */
+ dest->rle_row = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ cinfo->output_width, (JDIMENSION) cinfo->output_components);
+
+ /* Allocate a virtual array to hold the image. */
+ dest->image = (*cinfo->mem->request_virt_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
+ (JDIMENSION) (cinfo->output_width * cinfo->output_components),
+ cinfo->output_height, (JDIMENSION) 1);
+
+ return (djpeg_dest_ptr) dest;
+}
+
+#endif /* RLE_SUPPORTED */
diff --git a/jpeg-6c/wrtarga.c b/jpeg-6c/wrtarga.c
new file mode 100644
index 0000000..cf104d2
--- /dev/null
+++ b/jpeg-6c/wrtarga.c
@@ -0,0 +1,253 @@
+/*
+ * wrtarga.c
+ *
+ * Copyright (C) 1991-1996, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains routines to write output images in Targa format.
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications. As they stand, they assume output to
+ * an ordinary stdio stream.
+ *
+ * Based on code contributed by Lee Daniel Crocker.
+ */
+
+#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
+
+#ifdef TARGA_SUPPORTED
+
+
+/*
+ * To support 12-bit JPEG data, we'd have to scale output down to 8 bits.
+ * This is not yet implemented.
+ */
+
+#if BITS_IN_JSAMPLE != 8
+ Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
+#endif
+
+/*
+ * The output buffer needs to be writable by fwrite(). On PCs, we must
+ * allocate the buffer in near data space, because we are assuming small-data
+ * memory model, wherein fwrite() can't reach far memory. If you need to
+ * process very wide images on a PC, you might have to compile in large-memory
+ * model, or else replace fwrite() with a putc() loop --- which will be much
+ * slower.
+ */
+
+
+/* Private version of data destination object */
+
+typedef struct {
+ struct djpeg_dest_struct pub; /* public fields */
+
+ char *iobuffer; /* physical I/O buffer */
+ JDIMENSION buffer_width; /* width of one row */
+} tga_dest_struct;
+
+typedef tga_dest_struct * tga_dest_ptr;
+
+
+LOCAL(void)
+write_header (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, int num_colors)
+/* Create and write a Targa header */
+{
+ char targaheader[18];
+
+ /* Set unused fields of header to 0 */
+ MEMZERO(targaheader, SIZEOF(targaheader));
+
+ if (num_colors > 0) {
+ targaheader[1] = 1; /* color map type 1 */
+ targaheader[5] = (char) (num_colors & 0xFF);
+ targaheader[6] = (char) (num_colors >> 8);
+ targaheader[7] = 24; /* 24 bits per cmap entry */
+ }
+
+ targaheader[12] = (char) (cinfo->output_width & 0xFF);
+ targaheader[13] = (char) (cinfo->output_width >> 8);
+ targaheader[14] = (char) (cinfo->output_height & 0xFF);
+ targaheader[15] = (char) (cinfo->output_height >> 8);
+ targaheader[17] = 0x20; /* Top-down, non-interlaced */
+
+ if (cinfo->out_color_space == JCS_GRAYSCALE) {
+ targaheader[2] = 3; /* image type = uncompressed gray-scale */
+ targaheader[16] = 8; /* bits per pixel */
+ } else { /* must be RGB */
+ if (num_colors > 0) {
+ targaheader[2] = 1; /* image type = colormapped RGB */
+ targaheader[16] = 8;
+ } else {
+ targaheader[2] = 2; /* image type = uncompressed RGB */
+ targaheader[16] = 24;
+ }
+ }
+
+ if (JFWRITE(dinfo->output_file, targaheader, 18) != (size_t) 18)
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+}
+
+
+/*
+ * Write some pixel data.
+ * In this module rows_supplied will always be 1.
+ */
+
+METHODDEF(void)
+put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+/* used for unquantized full-color output */
+{
+ tga_dest_ptr dest = (tga_dest_ptr) dinfo;
+ register JSAMPROW inptr;
+ register char * outptr;
+ register JDIMENSION col;
+
+ inptr = dest->pub.buffer[0];
+ outptr = dest->iobuffer;
+ for (col = cinfo->output_width; col > 0; col--) {
+ outptr[0] = (char) GETJSAMPLE(inptr[2]); /* RGB to BGR order */
+ outptr[1] = (char) GETJSAMPLE(inptr[1]);
+ outptr[2] = (char) GETJSAMPLE(inptr[0]);
+ inptr += 3, outptr += 3;
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+METHODDEF(void)
+put_gray_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+/* used for grayscale OR quantized color output */
+{
+ tga_dest_ptr dest = (tga_dest_ptr) dinfo;
+ register JSAMPROW inptr;
+ register char * outptr;
+ register JDIMENSION col;
+
+ inptr = dest->pub.buffer[0];
+ outptr = dest->iobuffer;
+ for (col = cinfo->output_width; col > 0; col--) {
+ *outptr++ = (char) GETJSAMPLE(*inptr++);
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+
+/*
+ * Write some demapped pixel data when color quantization is in effect.
+ * For Targa, this is only applied to grayscale data.
+ */
+
+METHODDEF(void)
+put_demapped_gray (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
+ JDIMENSION rows_supplied)
+{
+ tga_dest_ptr dest = (tga_dest_ptr) dinfo;
+ register JSAMPROW inptr;
+ register char * outptr;
+ register JSAMPROW color_map0 = cinfo->colormap[0];
+ register JDIMENSION col;
+
+ inptr = dest->pub.buffer[0];
+ outptr = dest->iobuffer;
+ for (col = cinfo->output_width; col > 0; col--) {
+ *outptr++ = (char) GETJSAMPLE(color_map0[GETJSAMPLE(*inptr++)]);
+ }
+ (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
+}
+
+
+/*
+ * Startup: write the file header.
+ */
+
+METHODDEF(void)
+start_output_tga (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
+{
+ tga_dest_ptr dest = (tga_dest_ptr) dinfo;
+ int num_colors, i;
+ FILE *outfile;
+
+ if (cinfo->out_color_space == JCS_GRAYSCALE) {
+ /* Targa doesn't have a mapped grayscale format, so we will */
+ /* demap quantized gray output. Never emit a colormap. */
+ write_header(cinfo, dinfo, 0);
+ if (cinfo->quantize_colors)
+ dest->pub.put_pixel_rows = put_demapped_gray;
+ else
+ dest->pub.put_pixel_rows = put_gray_rows;
+ } else if (cinfo->out_color_space == JCS_RGB) {
+ if (cinfo->quantize_colors) {
+ /* We only support 8-bit colormap indexes, so only 256 colors */
+ num_colors = cinfo->actual_number_of_colors;
+ if (num_colors > 256)
+ ERREXIT1(cinfo, JERR_TOO_MANY_COLORS, num_colors);
+ write_header(cinfo, dinfo, num_colors);
+ /* Write the colormap. Note Targa uses BGR byte order */
+ outfile = dest->pub.output_file;
+ for (i = 0; i < num_colors; i++) {
+ putc(GETJSAMPLE(cinfo->colormap[2][i]), outfile);
+ putc(GETJSAMPLE(cinfo->colormap[1][i]), outfile);
+ putc(GETJSAMPLE(cinfo->colormap[0][i]), outfile);
+ }
+ dest->pub.put_pixel_rows = put_gray_rows;
+ } else {
+ write_header(cinfo, dinfo, 0);
+ dest->pub.put_pixel_rows = put_pixel_rows;
+ }
+ } else {
+ ERREXIT(cinfo, JERR_TGA_COLORSPACE);
+ }
+}
+
+
+/*
+ * Finish up at the end of the file.
+ */
+
+METHODDEF(void)
+finish_output_tga (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
+{
+ /* Make sure we wrote the output file OK */
+ fflush(dinfo->output_file);
+ if (ferror(dinfo->output_file))
+ ERREXIT(cinfo, JERR_FILE_WRITE);
+}
+
+
+/*
+ * The module selection routine for Targa format output.
+ */
+
+GLOBAL(djpeg_dest_ptr)
+jinit_write_targa (j_decompress_ptr cinfo)
+{
+ tga_dest_ptr dest;
+
+ /* Create module interface object, fill in method pointers */
+ dest = (tga_dest_ptr)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ SIZEOF(tga_dest_struct));
+ dest->pub.start_output = start_output_tga;
+ dest->pub.finish_output = finish_output_tga;
+
+ /* Calculate output image dimensions so we can allocate space */
+ jpeg_calc_output_dimensions(cinfo);
+
+ /* Create I/O buffer. Note we make this near on a PC. */
+ dest->buffer_width = cinfo->output_width * cinfo->output_components;
+ dest->iobuffer = (char *)
+ (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+ (size_t) (dest->buffer_width * SIZEOF(char)));
+
+ /* Create decompressor output buffer. */
+ dest->pub.buffer = (*cinfo->mem->alloc_sarray)
+ ((j_common_ptr) cinfo, JPOOL_IMAGE, dest->buffer_width, (JDIMENSION) 1);
+ dest->pub.buffer_height = 1;
+
+ return (djpeg_dest_ptr) dest;
+}
+
+#endif /* TARGA_SUPPORTED */
diff --git a/jpeg_encoder.cpp b/jpeg_encoder.cpp
new file mode 100644
index 0000000..2071e74
--- /dev/null
+++ b/jpeg_encoder.cpp
@@ -0,0 +1,1901 @@
+///////////////////
+// amalgamation of YUV jpeg encoder by Nitin Gupta (er.nitingupta.tripod.com)
+// version 11/20/2001
+// with some fixes (C) 2005 Michel Xhaard
+// compiled to one source file by mvh, 20081201; made thread safe 20081203
+// fixed for RGB input
+///////////////////
+
+/*
+20090215 mvh Started on update history
+20090412 mvh Added BGRto444 (14): acceptd RGB instead instead of BGR (!)
+20100224 bcb Fix warning redifine INT32 with HAVE_LIBJPEG
+20100309 bcb Fixed Operation on 'x' may be undefined warnings (gcc4.2)
+20100703 mvh Merged except typedef INT32
+20100706 bcb Accepted INT32 change
+20100717 mvh Merged
+*/
+
+
+#include <stdio.h>
+#include <string.h>
+#ifndef DARWIN
+#include <malloc.h>
+#endif //DARWIN
+
+typedef unsigned char UINT8;
+
+typedef short INT16;
+typedef unsigned short UINT16;
+
+typedef int INT32;
+typedef unsigned int UINT32;
+
+// image format
+
+#define FOUR_ZERO_ZERO 0
+#define FOUR_TWO_ZERO 1
+#define FOUR_TWO_TWO 2
+#define FOUR_FOUR_FOUR 3
+
+/* transform RGB24 to YUV Packet*/
+#define RGBto444 4 //RGB24 to packet YUV444
+#define RGBto422 5 //RGB24 to packet YUV422
+#define RGBto420 6 //RGB24 to packet YUV420
+#define RGBto400 7 //RGB24 to packet YUV400
+/* transform RGBxxx to YUV Packet*/
+#define RGB565to420 11 //RGB565 to packet YUV420
+#define RGB32to420 12 //RGB32 to packet YUV420
+/* transform YUV planar to YUV packet */
+#define YUVto444 8 //YUV444Planar to Packet YUV444
+#define YUVto422 9 //YUV422Planar to Packet YUV422
+#define YUVto420 10 //YUV420Planar to Packet YUV420
+
+#define BGRto444 14 //RGB24 to packet YUV444
+
+/////////////////// prototype of encoder
+
+UINT32 encode_image (UINT8 *input_ptr, UINT8 *output_ptr, UINT32 quality_factor, UINT32 image_format, UINT32 image_width, UINT32 image_height);
+
+#define BLOCK_SIZE 64
+
+typedef struct _JPEG_ENCODER_STRUCTURE
+{
+ UINT16 mcu_width;
+ UINT16 mcu_height;
+ UINT16 horizontal_mcus;
+ UINT16 vertical_mcus;
+ UINT16 cols_in_right_mcus;
+ UINT16 rows_in_bottom_mcus;
+
+ UINT16 rows;
+ UINT16 cols;
+
+ UINT16 length_minus_mcu_width;
+ UINT16 length_minus_width;
+ UINT16 incr;
+ UINT16 mcu_width_size;
+ UINT16 offset;
+
+ INT16 ldc1;
+ INT16 ldc2;
+ INT16 ldc3;
+
+ UINT8 Lqt [BLOCK_SIZE];
+ UINT8 Cqt [BLOCK_SIZE];
+ UINT16 ILqt [BLOCK_SIZE];
+ UINT16 ICqt [BLOCK_SIZE];
+
+ INT16 Y1 [BLOCK_SIZE];
+ INT16 Y2 [BLOCK_SIZE];
+ INT16 Y3 [BLOCK_SIZE];
+ INT16 Y4 [BLOCK_SIZE];
+ INT16 CB [BLOCK_SIZE];
+ INT16 CR [BLOCK_SIZE];
+ INT16 Temp [BLOCK_SIZE];
+
+ UINT32 lcode;
+ UINT16 bitindex;
+
+ UINT32 read_format_choice;
+} JPEG_ENCODER_STRUCTURE;
+
+////////////////// DCT.C //////////////////
+
+/* DCT for One block(8x8) */
+static void DCT (INT16 *data)
+{
+ UINT16 i;
+ INT32 x0, x1, x2, x3, x4, x5, x6, x7, x8;
+
+/* All values are shifted left by 10
+ and rounded off to nearest integer */
+
+ static const UINT16 c1=1420; /* cos PI/16 * root(2) */
+ static const UINT16 c2=1338; /* cos PI/8 * root(2) */
+ static const UINT16 c3=1204; /* cos 3PI/16 * root(2) */
+ static const UINT16 c5=805; /* cos 5PI/16 * root(2) */
+ static const UINT16 c6=554; /* cos 3PI/8 * root(2) */
+ static const UINT16 c7=283; /* cos 7PI/16 * root(2) */
+
+ static const UINT16 s1=3;
+ static const UINT16 s2=10;
+ static const UINT16 s3=13;
+
+ for (i=8; i>0; i--)
+ {
+ x8 = data [0] + data [7];
+ x0 = data [0] - data [7];
+
+ x7 = data [1] + data [6];
+ x1 = data [1] - data [6];
+
+ x6 = data [2] + data [5];
+ x2 = data [2] - data [5];
+
+ x5 = data [3] + data [4];
+ x3 = data [3] - data [4];
+
+ x4 = x8 + x5;
+ x8 -= x5;
+
+ x5 = x7 + x6;
+ x7 -= x6;
+
+ data [0] = (INT16) (x4 + x5);
+ data [4] = (INT16) (x4 - x5);
+
+ data [2] = (INT16) ((x8*c2 + x7*c6) >> s2);
+ data [6] = (INT16) ((x8*c6 - x7*c2) >> s2);
+
+ data [7] = (INT16) ((x0*c7 - x1*c5 + x2*c3 - x3*c1) >> s2);
+ data [5] = (INT16) ((x0*c5 - x1*c1 + x2*c7 + x3*c3) >> s2);
+ data [3] = (INT16) ((x0*c3 - x1*c7 - x2*c1 - x3*c5) >> s2);
+ data [1] = (INT16) ((x0*c1 + x1*c3 + x2*c5 + x3*c7) >> s2);
+
+ data += 8;
+ }
+
+ data -= 64;
+
+ for (i=8; i>0; i--)
+ {
+ x8 = data [0] + data [56];
+ x0 = data [0] - data [56];
+
+ x7 = data [8] + data [48];
+ x1 = data [8] - data [48];
+
+ x6 = data [16] + data [40];
+ x2 = data [16] - data [40];
+
+ x5 = data [24] + data [32];
+ x3 = data [24] - data [32];
+
+ x4 = x8 + x5;
+ x8 -= x5;
+
+ x5 = x7 + x6;
+ x7 -= x6;
+
+ data [0] = (INT16) ((x4 + x5) >> s1);
+ data [32] = (INT16) ((x4 - x5) >> s1);
+
+ data [16] = (INT16) ((x8*c2 + x7*c6) >> s3);
+ data [48] = (INT16) ((x8*c6 - x7*c2) >> s3);
+
+ data [56] = (INT16) ((x0*c7 - x1*c5 + x2*c3 - x3*c1) >> s3);
+ data [40] = (INT16) ((x0*c5 - x1*c1 + x2*c7 + x3*c3) >> s3);
+ data [24] = (INT16) ((x0*c3 - x1*c7 - x2*c1 - x3*c5) >> s3);
+ data [8] = (INT16) ((x0*c1 + x1*c3 + x2*c5 + x3*c7) >> s3);
+
+ data++;
+ }
+}
+
+////////////////// HUFFMAN //////////////////
+
+
+static UINT16 luminance_dc_code_table [] =
+{
+ 0x0000, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006,
+ 0x000E, 0x001E, 0x003E, 0x007E, 0x00FE, 0x01FE
+};
+
+static UINT16 luminance_dc_size_table [] =
+{
+ 0x0002, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003,
+ 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009
+};
+
+static UINT16 chrominance_dc_code_table [] =
+{
+ 0x0000, 0x0001, 0x0002, 0x0006, 0x000E, 0x001E,
+ 0x003E, 0x007E, 0x00FE, 0x01FE, 0x03FE, 0x07FE
+};
+
+static UINT16 chrominance_dc_size_table [] =
+{
+ 0x0002, 0x0002, 0x0002, 0x0003, 0x0004, 0x0005,
+ 0x0006, 0x0007, 0x0008, 0x0009, 0x000A, 0x000B
+};
+
+static UINT16 luminance_ac_code_table [] =
+{
+ 0x000A,
+ 0x0000, 0x0001, 0x0004, 0x000B, 0x001A, 0x0078, 0x00F8, 0x03F6, 0xFF82, 0xFF83,
+ 0x000C, 0x001B, 0x0079, 0x01F6, 0x07F6, 0xFF84, 0xFF85, 0xFF86, 0xFF87, 0xFF88,
+ 0x001C, 0x00F9, 0x03F7, 0x0FF4, 0xFF89, 0xFF8A, 0xFF8b, 0xFF8C, 0xFF8D, 0xFF8E,
+ 0x003A, 0x01F7, 0x0FF5, 0xFF8F, 0xFF90, 0xFF91, 0xFF92, 0xFF93, 0xFF94, 0xFF95,
+ 0x003B, 0x03F8, 0xFF96, 0xFF97, 0xFF98, 0xFF99, 0xFF9A, 0xFF9B, 0xFF9C, 0xFF9D,
+ 0x007A, 0x07F7, 0xFF9E, 0xFF9F, 0xFFA0, 0xFFA1, 0xFFA2, 0xFFA3, 0xFFA4, 0xFFA5,
+ 0x007B, 0x0FF6, 0xFFA6, 0xFFA7, 0xFFA8, 0xFFA9, 0xFFAA, 0xFFAB, 0xFFAC, 0xFFAD,
+ 0x00FA, 0x0FF7, 0xFFAE, 0xFFAF, 0xFFB0, 0xFFB1, 0xFFB2, 0xFFB3, 0xFFB4, 0xFFB5,
+ 0x01F8, 0x7FC0, 0xFFB6, 0xFFB7, 0xFFB8, 0xFFB9, 0xFFBA, 0xFFBB, 0xFFBC, 0xFFBD,
+ 0x01F9, 0xFFBE, 0xFFBF, 0xFFC0, 0xFFC1, 0xFFC2, 0xFFC3, 0xFFC4, 0xFFC5, 0xFFC6,
+ 0x01FA, 0xFFC7, 0xFFC8, 0xFFC9, 0xFFCA, 0xFFCB, 0xFFCC, 0xFFCD, 0xFFCE, 0xFFCF,
+ 0x03F9, 0xFFD0, 0xFFD1, 0xFFD2, 0xFFD3, 0xFFD4, 0xFFD5, 0xFFD6, 0xFFD7, 0xFFD8,
+ 0x03FA, 0xFFD9, 0xFFDA, 0xFFDB, 0xFFDC, 0xFFDD, 0xFFDE, 0xFFDF, 0xFFE0, 0xFFE1,
+ 0x07F8, 0xFFE2, 0xFFE3, 0xFFE4, 0xFFE5, 0xFFE6, 0xFFE7, 0xFFE8, 0xFFE9, 0xFFEA,
+ 0xFFEB, 0xFFEC, 0xFFED, 0xFFEE, 0xFFEF, 0xFFF0, 0xFFF1, 0xFFF2, 0xFFF3, 0xFFF4,
+ 0xFFF5, 0xFFF6, 0xFFF7, 0xFFF8, 0xFFF9, 0xFFFA, 0xFFFB, 0xFFFC, 0xFFFD, 0xFFFE,
+ 0x07F9
+};
+
+static UINT16 luminance_ac_size_table [] =
+{
+ 0x0004,
+ 0x0002, 0x0002, 0x0003, 0x0004, 0x0005, 0x0007, 0x0008, 0x000A, 0x0010, 0x0010,
+ 0x0004, 0x0005, 0x0007, 0x0009, 0x000B, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0005, 0x0008, 0x000A, 0x000C, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0006, 0x0009, 0x000C, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0006, 0x000A, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0007, 0x000B, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0007, 0x000C, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0008, 0x000C, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0009, 0x000F, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0009, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0009, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x000A, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x000A, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x000B, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x000B
+};
+
+static UINT16 chrominance_ac_code_table [] =
+{
+ 0x0000,
+ 0x0001, 0x0004, 0x000A, 0x0018, 0x0019, 0x0038, 0x0078, 0x01F4, 0x03F6, 0x0FF4,
+ 0x000B, 0x0039, 0x00F6, 0x01F5, 0x07F6, 0x0FF5, 0xFF88, 0xFF89, 0xFF8A, 0xFF8B,
+ 0x001A, 0x00F7, 0x03F7, 0x0FF6, 0x7FC2, 0xFF8C, 0xFF8D, 0xFF8E, 0xFF8F, 0xFF90,
+ 0x001B, 0x00F8, 0x03F8, 0x0FF7, 0xFF91, 0xFF92, 0xFF93, 0xFF94, 0xFF95, 0xFF96,
+ 0x003A, 0x01F6, 0xFF97, 0xFF98, 0xFF99, 0xFF9A, 0xFF9B, 0xFF9C, 0xFF9D, 0xFF9E,
+ 0x003B, 0x03F9, 0xFF9F, 0xFFA0, 0xFFA1, 0xFFA2, 0xFFA3, 0xFFA4, 0xFFA5, 0xFFA6,
+ 0x0079, 0x07F7, 0xFFA7, 0xFFA8, 0xFFA9, 0xFFAA, 0xFFAB, 0xFFAC, 0xFFAD, 0xFFAE,
+ 0x007A, 0x07F8, 0xFFAF, 0xFFB0, 0xFFB1, 0xFFB2, 0xFFB3, 0xFFB4, 0xFFB5, 0xFFB6,
+ 0x00F9, 0xFFB7, 0xFFB8, 0xFFB9, 0xFFBA, 0xFFBB, 0xFFBC, 0xFFBD, 0xFFBE, 0xFFBF,
+ 0x01F7, 0xFFC0, 0xFFC1, 0xFFC2, 0xFFC3, 0xFFC4, 0xFFC5, 0xFFC6, 0xFFC7, 0xFFC8,
+ 0x01F8, 0xFFC9, 0xFFCA, 0xFFCB, 0xFFCC, 0xFFCD, 0xFFCE, 0xFFCF, 0xFFD0, 0xFFD1,
+ 0x01F9, 0xFFD2, 0xFFD3, 0xFFD4, 0xFFD5, 0xFFD6, 0xFFD7, 0xFFD8, 0xFFD9, 0xFFDA,
+ 0x01FA, 0xFFDB, 0xFFDC, 0xFFDD, 0xFFDE, 0xFFDF, 0xFFE0, 0xFFE1, 0xFFE2, 0xFFE3,
+ 0x07F9, 0xFFE4, 0xFFE5, 0xFFE6, 0xFFE7, 0xFFE8, 0xFFE9, 0xFFEA, 0xFFEb, 0xFFEC,
+ 0x3FE0, 0xFFED, 0xFFEE, 0xFFEF, 0xFFF0, 0xFFF1, 0xFFF2, 0xFFF3, 0xFFF4, 0xFFF5,
+ 0x7FC3, 0xFFF6, 0xFFF7, 0xFFF8, 0xFFF9, 0xFFFA, 0xFFFB, 0xFFFC, 0xFFFD, 0xFFFE,
+ 0x03FA
+};
+
+static UINT16 chrominance_ac_size_table [] =
+{
+ 0x0002,
+ 0x0002, 0x0003, 0x0004, 0x0005, 0x0005, 0x0006, 0x0007, 0x0009, 0x000A, 0x000C,
+ 0x0004, 0x0006, 0x0008, 0x0009, 0x000B, 0x000C, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0005, 0x0008, 0x000A, 0x000C, 0x000F, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0005, 0x0008, 0x000A, 0x000C, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0006, 0x0009, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0006, 0x000A, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0007, 0x000B, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0007, 0x000B, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0008, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0009, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0009, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0009, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x0009, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x000B, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x000E, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x000F, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010, 0x0010,
+ 0x000A
+};
+
+static UINT8 bitsize [] =
+{
+ 0, 1, 2, 2, 3, 3, 3, 3,
+ 4, 4, 4, 4, 4, 4, 4, 4,
+ 5, 5, 5, 5, 5, 5, 5, 5,
+ 5, 5, 5, 5, 5, 5, 5, 5,
+ 6, 6, 6, 6, 6, 6, 6, 6,
+ 6, 6, 6, 6, 6, 6, 6, 6,
+ 6, 6, 6, 6, 6, 6, 6, 6,
+ 6, 6, 6, 6, 6, 6, 6, 6,
+ 7, 7, 7, 7, 7, 7, 7, 7,
+ 7, 7, 7, 7, 7, 7, 7, 7,
+ 7, 7, 7, 7, 7, 7, 7, 7,
+ 7, 7, 7, 7, 7, 7, 7, 7,
+ 7, 7, 7, 7, 7, 7, 7, 7,
+ 7, 7, 7, 7, 7, 7, 7, 7,
+ 7, 7, 7, 7, 7, 7, 7, 7,
+ 7, 7, 7, 7, 7, 7, 7, 7,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8
+};
+
+#define PUTBITS \
+{ \
+ bits_in_next_word = (INT16) (jpeg_encoder_structure->bitindex + numbits - 32); \
+ if (bits_in_next_word < 0) \
+ { \
+ jpeg_encoder_structure->lcode = (jpeg_encoder_structure->lcode << numbits) | data; \
+ jpeg_encoder_structure->bitindex += numbits; \
+ } \
+ else \
+ { \
+ jpeg_encoder_structure->lcode = (jpeg_encoder_structure->lcode << (32 - jpeg_encoder_structure->bitindex)) | (data >> bits_in_next_word); \
+ if ((*output_ptr++ = (UINT8)(jpeg_encoder_structure->lcode >> 24)) == 0xff) \
+ *output_ptr++ = 0; \
+ if ((*output_ptr++ = (UINT8)(jpeg_encoder_structure->lcode >> 16)) == 0xff) \
+ *output_ptr++ = 0; \
+ if ((*output_ptr++ = (UINT8)(jpeg_encoder_structure->lcode >> 8)) == 0xff) \
+ *output_ptr++ = 0; \
+ if ((*output_ptr++ = (UINT8) jpeg_encoder_structure->lcode) == 0xff) \
+ *output_ptr++ = 0; \
+ jpeg_encoder_structure->lcode = data; \
+ jpeg_encoder_structure->bitindex = bits_in_next_word; \
+ } \
+}
+
+static UINT8* huffman (JPEG_ENCODER_STRUCTURE *jpeg_encoder_structure, UINT16 component, UINT8 *output_ptr)
+{
+ UINT16 i;
+ UINT16 *DcCodeTable, *DcSizeTable, *AcCodeTable, *AcSizeTable;
+
+ INT16 *Temp_Ptr, Coeff, LastDc;
+ UINT16 AbsCoeff, HuffCode, HuffSize, RunLength=0, DataSize=0, index;
+
+ INT16 bits_in_next_word;
+ UINT16 numbits;
+ UINT32 data;
+
+ Temp_Ptr = jpeg_encoder_structure->Temp;
+ Coeff = *Temp_Ptr++;
+
+ if (component == 1)
+ {
+ DcCodeTable = luminance_dc_code_table;
+ DcSizeTable = luminance_dc_size_table;
+ AcCodeTable = luminance_ac_code_table;
+ AcSizeTable = luminance_ac_size_table;
+
+ LastDc = jpeg_encoder_structure->ldc1;
+ jpeg_encoder_structure->ldc1 = Coeff;
+ }
+ else
+ {
+ DcCodeTable = chrominance_dc_code_table;
+ DcSizeTable = chrominance_dc_size_table;
+ AcCodeTable = chrominance_ac_code_table;
+ AcSizeTable = chrominance_ac_size_table;
+
+ if (component == 2)
+ {
+ LastDc = jpeg_encoder_structure->ldc2;
+ jpeg_encoder_structure->ldc2 = Coeff;
+ }
+ else
+ {
+ LastDc = jpeg_encoder_structure->ldc3;
+ jpeg_encoder_structure->ldc3 = Coeff;
+ }
+ }
+
+ Coeff -= LastDc;
+
+ AbsCoeff = (Coeff < 0) ? -Coeff-- : Coeff;
+
+ while (AbsCoeff != 0)
+ {
+ AbsCoeff >>= 1;
+ DataSize++;
+ }
+
+ HuffCode = DcCodeTable [DataSize];
+ HuffSize = DcSizeTable [DataSize];
+
+ Coeff &= (1 << DataSize) - 1;
+ data = (HuffCode << DataSize) | Coeff;
+ numbits = HuffSize + DataSize;
+
+ PUTBITS
+
+ for (i=63; i>0; i--)
+ {
+ if ((Coeff = *Temp_Ptr++) != 0)
+ {
+ while (RunLength > 15)
+ {
+ RunLength -= 16;
+ data = AcCodeTable [161];
+ numbits = AcSizeTable [161];
+ PUTBITS
+ }
+
+ AbsCoeff = (Coeff < 0) ? -Coeff-- : Coeff;
+
+ if (AbsCoeff >> 8 == 0)
+ DataSize = bitsize [AbsCoeff];
+ else
+ DataSize = bitsize [AbsCoeff >> 8] + 8;
+
+ index = RunLength * 10 + DataSize;
+ HuffCode = AcCodeTable [index];
+ HuffSize = AcSizeTable [index];
+
+ Coeff &= (1 << DataSize) - 1;
+ data = (HuffCode << DataSize) | Coeff;
+ numbits = HuffSize + DataSize;
+
+ PUTBITS
+ RunLength = 0;
+ }
+ else
+ RunLength++;
+ }
+
+ if (RunLength != 0)
+ {
+ data = AcCodeTable [0];
+ numbits = AcSizeTable [0];
+ PUTBITS
+ }
+ return output_ptr;
+}
+
+/* For bit Stuffing and EOI marker */
+static UINT8* close_bitstream (JPEG_ENCODER_STRUCTURE *jpeg_encoder_structure, UINT8 *output_ptr)
+{
+ UINT16 i, count;
+ UINT8 *ptr;
+
+ if (jpeg_encoder_structure->bitindex > 0)
+ {
+ jpeg_encoder_structure->lcode <<= (32 - jpeg_encoder_structure->bitindex);
+ count = (jpeg_encoder_structure->bitindex + 7) >> 3;
+
+ ptr = (UINT8 *) & jpeg_encoder_structure->lcode + 3;
+
+ for (i=count; i>0; i--)
+ {
+ if ((*output_ptr++ = *ptr--) == 0xff)
+ *output_ptr++ = 0;
+ }
+ }
+
+ // End of image marker
+ *output_ptr++ = 0xFF;
+ *output_ptr++ = 0xD9;
+ return output_ptr;
+}
+
+////////// MARKER /////////////
+
+static UINT16 markerdata [] =
+{
+ // dht
+ 0xFFC4, 0x1A2, 0x00,
+
+ // luminance dc (2 - 16) + 1
+ 0x0105, 0x0101, 0x00101, 0x0101, 0x0000, 0x00000, 00000, 00000,
+
+ // luminance dc (2 - 12) + 1
+ 0x0102, 0x0304, 0x0506, 0x0708, 0x090A, 0x0B01,
+
+ // chrominance dc (1 - 16)
+ 0x0003, 0x0101, 0x0101, 0x0101, 0x0101, 0x0100, 0x0000, 0x0000,
+
+ // chrominance dc (1 - 12)
+ 0x0001, 0x00203, 0x0405, 0x0607, 0x0809, 0x00A0B,
+
+ // luminance ac 1 + (1 - 15)
+ 0x1000, 0x0201, 0x0303, 0x0204, 0x0305, 0x0504, 0x0400, 0x0001,
+
+ // luminance ac 1 + (1 - 162) + 1
+ 0x7D01, 0x0203, 0x0004, 0x1105, 0x1221, 0x3141, 0x0613, 0x5161,
+ 0x0722, 0x7114, 0x3281, 0x91A1, 0x0823, 0x42B1, 0xC115, 0x52D1,
+ 0xF024, 0x3362, 0x7282, 0x090A, 0x1617, 0x1819, 0x1A25, 0x2627,
+ 0x2829, 0x2A34, 0x3536, 0x3738, 0x393A, 0x4344, 0x4546, 0x4748,
+ 0x494A, 0x5354, 0x5556, 0x5758, 0x595A, 0x6364, 0x6566, 0x6768,
+ 0x696A, 0x7374, 0x7576, 0x7778, 0x797A, 0x8384, 0x8586, 0x8788,
+ 0x898A, 0x9293, 0x9495, 0x9697, 0x9899, 0x9AA2, 0xA3A4, 0xA5A6,
+ 0xA7A8, 0xA9AA, 0xB2B3, 0xB4B5, 0xB6B7, 0xB8B9, 0xBAC2, 0xC3C4,
+ 0xC5C6, 0xC7C8, 0xC9CA, 0xD2D3, 0xD4D5, 0xD6D7, 0xD8D9, 0xDAE1,
+ 0xE2E3, 0xE4E5, 0xE6E7, 0xE8E9, 0xEAF1, 0xF2F3, 0xF4F5, 0xF6F7,
+ 0xF8F9, 0xFA11,
+
+ // chrominance ac (1 - 16)
+ 0x0002, 0x0102, 0x0404, 0x0304, 0x0705, 0x0404, 0x0001, 0x0277,
+
+ // chrominance ac (1 - 162)
+ 0x0001, 0x0203, 0x1104, 0x0521, 0x3106, 0x1241, 0x5107, 0x6171,
+ 0x1322, 0x3281, 0x0814, 0x4291, 0xA1B1, 0xC109, 0x2333, 0x52F0,
+ 0x1562, 0x72D1, 0x0A16, 0x2434, 0xE125, 0xF117, 0x1819, 0x1A26,
+ 0x2728, 0x292A, 0x3536, 0x3738, 0x393A, 0x4344, 0x4546, 0x4748,
+ 0x494A, 0x5354, 0x5556, 0x5758, 0x595A, 0x6364, 0x6566, 0x6768,
+ 0x696A, 0x7374, 0x7576, 0x7778, 0x797A, 0x8283, 0x8485, 0x8687,
+ 0x8889, 0x8A92, 0x9394, 0x9596, 0x9798, 0x999A, 0xA2A3, 0xA4A5,
+ 0xA6A7, 0xA8A9, 0xAAB2, 0xB3B4, 0xB5B6, 0xB7B8, 0xB9BA, 0xC2C3,
+ 0xC4C5, 0xC6C7, 0xC8C9, 0xCAD2, 0xD3D4, 0xD5D6, 0xD7D8, 0xD9DA,
+ 0xE2E3, 0xE4E5, 0xE6E7, 0xE8E9, 0xEAF2, 0xF3F4, 0xF5F6, 0xF7F8,
+ 0xF9FA
+};
+
+static UINT8 *write_markers (JPEG_ENCODER_STRUCTURE *jpeg_encoder_structure, UINT8 *output_ptr, UINT32 image_format, UINT32 image_width, UINT32 image_height)
+{
+ UINT16 i, header_length;
+ UINT8 number_of_components;
+
+ // Start of image marker
+ *output_ptr++ = 0xFF;
+ *output_ptr++ = 0xD8;
+
+ // Quantization table marker
+ *output_ptr++ = 0xFF;
+ *output_ptr++ = 0xDB;
+
+ // Quantization table length
+ *output_ptr++ = 0x00;
+ *output_ptr++ = 0x84;
+
+ // Pq, Tq
+ *output_ptr++ = 0x00;
+
+ // Lqt table
+ for (i=0; i<64; i++)
+ *output_ptr++ = jpeg_encoder_structure->Lqt [i];
+
+ // Pq, Tq
+ *output_ptr++ = 0x01;
+
+ // Cqt table
+ for (i=0; i<64; i++)
+ *output_ptr++ = jpeg_encoder_structure->Cqt [i];
+
+ // huffman table(DHT)
+ for (i=0; i<210; i++)
+ {
+ *output_ptr++ = (UINT8) (markerdata [i] >> 8);
+ *output_ptr++ = (UINT8) markerdata [i];
+ }
+
+ if (image_format == FOUR_ZERO_ZERO)
+ number_of_components = 1;
+ else
+ number_of_components = 3;
+
+ // Frame header(SOF)
+
+ // Start of frame marker
+ *output_ptr++ = 0xFF;
+ *output_ptr++ = 0xC0;
+
+ header_length = (UINT16) (8 + 3 * number_of_components);
+
+ // Frame header length
+ *output_ptr++ = (UINT8) (header_length >> 8);
+ *output_ptr++ = (UINT8) header_length;
+
+ // Precision (P)
+ *output_ptr++ = 0x08;
+
+ // image height
+ *output_ptr++ = (UINT8) (image_height >> 8);
+ *output_ptr++ = (UINT8) image_height;
+
+ // image width
+ *output_ptr++ = (UINT8) (image_width >> 8);
+ *output_ptr++ = (UINT8) image_width;
+
+ // Nf
+ *output_ptr++ = number_of_components;
+
+ if (image_format == FOUR_ZERO_ZERO)
+ {
+ *output_ptr++ = 0x01;
+ *output_ptr++ = 0x11;
+ *output_ptr++ = 0x00;
+ }
+ else
+ {
+ *output_ptr++ = 0x01;
+
+ if (image_format == FOUR_TWO_ZERO)
+ *output_ptr++ = 0x22;
+ else if (image_format == FOUR_TWO_TWO)
+ *output_ptr++ = 0x21;
+ else
+ *output_ptr++ = 0x11;
+
+ *output_ptr++ = 0x00;
+
+ *output_ptr++ = 0x02;
+ *output_ptr++ = 0x11;
+ *output_ptr++ = 0x01;
+
+ *output_ptr++ = 0x03;
+ *output_ptr++ = 0x11;
+ *output_ptr++ = 0x01;
+ }
+
+ // Scan header(SOF)
+
+ // Start of scan marker
+ *output_ptr++ = 0xFF;
+ *output_ptr++ = 0xDA;
+
+ header_length = (UINT16) (6 + (number_of_components << 1));
+
+ // Scan header length
+ *output_ptr++ = (UINT8) (header_length >> 8);
+ *output_ptr++ = (UINT8) header_length;
+
+ // Ns
+ *output_ptr++ = number_of_components;
+
+ if (image_format == FOUR_ZERO_ZERO)
+ {
+ *output_ptr++ = 0x01;
+ *output_ptr++ = 0x00;
+ }
+ else
+ {
+ *output_ptr++ = 0x01;
+ *output_ptr++ = 0x00;
+
+ *output_ptr++ = 0x02;
+ *output_ptr++ = 0x11;
+
+ *output_ptr++ = 0x03;
+ *output_ptr++ = 0x11;
+ }
+
+ *output_ptr++ = 0x00;
+ *output_ptr++ = 0x3F;
+ *output_ptr++ = 0x00;
+
+ return output_ptr;
+}
+
+////////// QUANT ////////////
+
+static UINT8 zigzag_table [] =
+{
+ 0, 1, 5, 6, 14, 15, 27, 28,
+ 2, 4, 7, 13, 16, 26, 29, 42,
+ 3, 8, 12, 17, 25, 30, 41, 43,
+ 9, 11, 18, 24, 31, 40, 44, 53,
+ 10, 19, 23, 32, 39, 45, 52, 54,
+ 20, 22, 33, 38, 46, 51, 55, 60,
+ 21, 34, 37, 47, 50, 56, 59, 61,
+ 35, 36, 48, 49, 57, 58, 62, 63
+};
+
+
+/* This function implements 16 Step division for Q.15 format data */
+static UINT16 DSP_Division (UINT32 numer, UINT32 denom)
+{
+ UINT16 i;
+
+ denom <<= 15;
+
+ for (i=16; i>0; i--)
+ {
+ if (numer > denom)
+ {
+ numer -= denom;
+ numer <<= 1;
+ numer++;
+ }
+ else
+ numer <<= 1;
+ }
+
+ return (UINT16) numer;
+}
+
+/* Multiply Quantization table with quality factor to get LQT and CQT */
+static void initialize_quantization_tables (JPEG_ENCODER_STRUCTURE *jpeg_encoder_structure, UINT32 quality_factor)
+{
+ UINT16 i, index;
+ UINT32 value;
+
+ UINT8 luminance_quant_table [] =
+ {
+ 16, 11, 10, 16, 24, 40, 51, 61,
+ 12, 12, 14, 19, 26, 58, 60, 55,
+ 14, 13, 16, 24, 40, 57, 69, 56,
+ 14, 17, 22, 29, 51, 87, 80, 62,
+ 18, 22, 37, 56, 68, 109, 103, 77,
+ 24, 35, 55, 64, 81, 104, 113, 92,
+ 49, 64, 78, 87, 103, 121, 120, 101,
+ 72, 92, 95, 98, 112, 100, 103, 99
+ };
+
+ UINT8 chrominance_quant_table [] =
+ {
+ 17, 18, 24, 47, 99, 99, 99, 99,
+ 18, 21, 26, 66, 99, 99, 99, 99,
+ 24, 26, 56, 99, 99, 99, 99, 99,
+ 47, 66, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99,
+ 99, 99, 99, 99, 99, 99, 99, 99
+ };
+
+ for (i=0; i<64; i++)
+ {
+ index = zigzag_table [i];
+
+ /* luminance quantization table * quality factor */
+ value = luminance_quant_table [i] * quality_factor;
+ value = (value + 0x200) >> 10;
+
+ if (value == 0)
+ value = 1;
+ else if (value > 255)
+ value = 255;
+
+ jpeg_encoder_structure->Lqt [index] = (UINT8) value;
+ jpeg_encoder_structure->ILqt [i] = DSP_Division (0x8000, value);
+
+ /* chrominance quantization table * quality factor */
+ value = chrominance_quant_table [i] * quality_factor;
+ value = (value + 0x200) >> 10;
+
+ if (value == 0)
+ value = 1;
+ else if (value > 255)
+ value = 255;
+
+ jpeg_encoder_structure->Cqt [index] = (UINT8) value;
+ jpeg_encoder_structure->ICqt [i] = DSP_Division (0x8000, value);
+ }
+}
+
+/* multiply DCT Coefficients with Quantization table and store in ZigZag location */
+static void quantization (JPEG_ENCODER_STRUCTURE *jpeg_encoder_structure, INT16* const data, UINT16* const quant_table_ptr)
+{
+ INT16 i;
+ INT32 value;
+
+ for (i=63; i>=0; i--)
+ {
+ value = data [i] * quant_table_ptr [i];
+ value = (value + 0x4000) >> 15;
+
+ jpeg_encoder_structure->Temp [zigzag_table [i]] = (INT16) value;
+ }
+}
+
+
+///////// READYUV ///////////////
+
+static void read_400_format (JPEG_ENCODER_STRUCTURE *jpeg_encoder_structure, UINT8 *input_ptr)
+{
+ INT32 i, j;
+ INT16 *Y1_Ptr = jpeg_encoder_structure->Y1;
+
+ UINT16 rows = jpeg_encoder_structure->rows;
+ UINT16 cols = jpeg_encoder_structure->cols;
+ UINT16 incr = jpeg_encoder_structure->incr;
+
+ for (i=rows; i>0; i--)
+ {
+ for (j=cols; j>0; j--)
+ *Y1_Ptr++ = *input_ptr++ - 128;
+
+ for (j=8-cols; j>0; j--)
+ {
+ *Y1_Ptr = *(Y1_Ptr-1);
+ Y1_Ptr++;
+ }
+
+ input_ptr += incr;
+ }
+
+ for (i=8-rows; i>0; i--)
+ {
+ for (j=8; j>0; j--)
+ {
+ *Y1_Ptr = *(Y1_Ptr - 8);
+ Y1_Ptr++;
+ }
+ }
+}
+
+static void read_420_format (JPEG_ENCODER_STRUCTURE *jpeg_encoder_structure, UINT8 *input_ptr)
+{
+ INT32 i, j;
+ UINT16 Y1_rows, Y3_rows, Y1_cols, Y2_cols;
+
+ INT16 *Y1_Ptr = jpeg_encoder_structure->Y1;
+ INT16 *Y2_Ptr = jpeg_encoder_structure->Y2;
+ INT16 *Y3_Ptr = jpeg_encoder_structure->Y3;
+ INT16 *Y4_Ptr = jpeg_encoder_structure->Y4;
+ INT16 *CB_Ptr = jpeg_encoder_structure->CB;
+ INT16 *CR_Ptr = jpeg_encoder_structure->CR;
+
+ INT16 *Y1Ptr = jpeg_encoder_structure->Y1 + 8;
+ INT16 *Y2Ptr = jpeg_encoder_structure->Y2 + 8;
+ INT16 *Y3Ptr = jpeg_encoder_structure->Y3 + 8;
+ INT16 *Y4Ptr = jpeg_encoder_structure->Y4 + 8;
+
+ UINT16 rows = jpeg_encoder_structure->rows;
+ UINT16 cols = jpeg_encoder_structure->cols;
+ UINT16 incr = jpeg_encoder_structure->incr;
+
+ if (rows <= 8)
+ {
+ Y1_rows = rows;
+ Y3_rows = 0;
+ }
+ else
+ {
+ Y1_rows = 8;
+ Y3_rows = (UINT16) (rows - 8);
+ }
+
+ if (cols <= 8)
+ {
+ Y1_cols = cols;
+ Y2_cols = 0;
+ }
+ else
+ {
+ Y1_cols = 8;
+ Y2_cols = (UINT16) (cols - 8);
+ }
+
+ for (i=Y1_rows>>1; i>0; i--)
+ {
+ for (j=Y1_cols>>1; j>0; j--)
+ {
+ *Y1_Ptr++ = *input_ptr++ - 128;
+ *Y1_Ptr++ = *input_ptr++ - 128;
+ *Y1Ptr++ = *input_ptr++ - 128;
+ *Y1Ptr++ = *input_ptr++ - 128;
+ *CB_Ptr++ = *input_ptr++ - 128;
+ *CR_Ptr++ = *input_ptr++ - 128;
+ }
+
+ for (j=Y2_cols>>1; j>0; j--)
+ {
+ *Y2_Ptr++ = *input_ptr++ - 128;
+ *Y2_Ptr++ = *input_ptr++ - 128;
+ *Y2Ptr++ = *input_ptr++ - 128;
+ *Y2Ptr++ = *input_ptr++ - 128;
+ *CB_Ptr++ = *input_ptr++ - 128;
+ *CR_Ptr++ = *input_ptr++ - 128;
+ }
+
+ if (cols <= 8)
+ {
+ for (j=8-Y1_cols; j>0; j--)
+ {
+ *Y1_Ptr = *(Y1_Ptr - 1);
+ Y1_Ptr++;
+ *Y1Ptr = *(Y1Ptr - 1);
+ Y1Ptr++;
+ }
+
+ for (j=8; j>0; j--)
+ {
+ *Y2_Ptr++ = *(Y1_Ptr - 1);
+ *Y2Ptr++ = *(Y1Ptr - 1);
+ }
+ }
+ else
+ {
+ for (j=8-Y2_cols; j>0; j--)
+ {
+ *Y2_Ptr = *(Y2_Ptr - 1);
+ Y2_Ptr++;
+ *Y2Ptr = *(Y2Ptr - 1);
+ Y2Ptr++;
+ }
+ }
+
+ for (j=(16-cols)>>1; j>0; j--)
+ {
+ *CB_Ptr = *(CB_Ptr-1);
+ CB_Ptr++;
+ *CR_Ptr = *(CR_Ptr-1);
+ CR_Ptr++;
+ }
+
+ Y1_Ptr += 8;
+ Y2_Ptr += 8;
+ Y1Ptr += 8;
+ Y2Ptr += 8;
+
+ input_ptr += incr;
+ }
+
+ for (i=Y3_rows>>1; i>0; i--)
+ {
+ for (j=Y1_cols>>1; j>0; j--)
+ {
+ *Y3_Ptr++ = *input_ptr++ - 128;
+ *Y3_Ptr++ = *input_ptr++ - 128;
+ *Y3Ptr++ = *input_ptr++ - 128;
+ *Y3Ptr++ = *input_ptr++ - 128;
+ *CB_Ptr++ = *input_ptr++ - 128;
+ *CR_Ptr++ = *input_ptr++ - 128;
+ }
+
+ for (j=Y2_cols>>1; j>0; j--)
+ {
+ *Y4_Ptr++ = *input_ptr++ - 128;
+ *Y4_Ptr++ = *input_ptr++ - 128;
+ *Y4Ptr++ = *input_ptr++ - 128;
+ *Y4Ptr++ = *input_ptr++ - 128;
+ *CB_Ptr++ = *input_ptr++ - 128;
+ *CR_Ptr++ = *input_ptr++ - 128;
+ }
+
+ if (cols <= 8)
+ {
+ for (j=8-Y1_cols; j>0; j--)
+ {
+ *Y3_Ptr = *(Y3_Ptr - 1);
+ Y3_Ptr++;
+ *Y3Ptr = *(Y3Ptr - 1);
+ Y3Ptr++;
+ }
+
+ for (j=8; j>0; j--)
+ {
+ *Y4_Ptr++ = *(Y3_Ptr - 1);
+ *Y4Ptr++ = *(Y3Ptr - 1);
+ }
+ }
+ else
+ {
+ for (j=8-Y2_cols; j>0; j--)
+ {
+ *Y4_Ptr = *(Y4_Ptr - 1);
+ Y4_Ptr++;
+ *Y4Ptr = *(Y4Ptr - 1);
+ Y4Ptr++;
+ }
+ }
+
+ for (j=(16-cols)>>1; j>0; j--)
+ {
+ *CB_Ptr = *(CB_Ptr-1);
+ CB_Ptr++;
+ *CR_Ptr = *(CR_Ptr-1);
+ CR_Ptr++;
+ }
+
+ Y3_Ptr += 8;
+ Y4_Ptr += 8;
+ Y3Ptr += 8;
+ Y4Ptr += 8;
+
+ input_ptr += incr;
+ }
+
+ if (rows <= 8)
+ {
+ for (i=8-rows; i>0; i--)
+ {
+ for (j=8; j>0; j--)
+ {
+ *Y1_Ptr = *(Y1_Ptr - 8);
+ Y1_Ptr++;
+ *Y2_Ptr = *(Y2_Ptr - 8);
+ Y2_Ptr++;
+ }
+ }
+
+ for (i=8; i>0; i--)
+ {
+ Y1_Ptr -= 8;
+ Y2_Ptr -= 8;
+
+ for (j=8; j>0; j--)
+ {
+ *Y3_Ptr++ = *Y1_Ptr++;
+ *Y4_Ptr++ = *Y2_Ptr++;
+ }
+ }
+ }
+ else
+ {
+ for (i=(16-rows); i>0; i--)
+ {
+ for (j=8; j>0; j--)
+ {
+ *Y3_Ptr = *(Y3_Ptr - 8);
+ Y3_Ptr++;
+ *Y4_Ptr = *(Y4_Ptr - 8);
+ Y4_Ptr++;
+ }
+ }
+ }
+
+ for (i=((16-rows)>>1); i>0; i--)
+ {
+ for (j=8; j>0; j--)
+ {
+ *CB_Ptr = *(CB_Ptr-8);
+ CB_Ptr++;
+ *CR_Ptr = *(CR_Ptr-8);
+ CR_Ptr++;
+ }
+ }
+}
+
+static void read_422_format (JPEG_ENCODER_STRUCTURE *jpeg_encoder_structure, UINT8 *input_ptr)
+{
+ INT32 i, j;
+ UINT16 Y1_cols, Y2_cols;
+
+ INT16 *Y1_Ptr = jpeg_encoder_structure->Y1;
+ INT16 *Y2_Ptr = jpeg_encoder_structure->Y2;
+ INT16 *CB_Ptr = jpeg_encoder_structure->CB;
+ INT16 *CR_Ptr = jpeg_encoder_structure->CR;
+
+ UINT16 rows = jpeg_encoder_structure->rows;
+ UINT16 cols = jpeg_encoder_structure->cols;
+ UINT16 incr = jpeg_encoder_structure->incr;
+
+ if (cols <= 8)
+ {
+ Y1_cols = cols;
+ Y2_cols = 0;
+ }
+ else
+ {
+ Y1_cols = 8;
+ Y2_cols = (UINT16) (cols - 8);
+ }
+
+ for (i=rows; i>0; i--)
+ {
+ for (j=Y1_cols>>1; j>0; j--)
+ {
+ *Y1_Ptr++ = *input_ptr++ - 128;
+ *CB_Ptr++ = *input_ptr++ - 128;
+ *Y1_Ptr++ = *input_ptr++ - 128;
+ *CR_Ptr++ = *input_ptr++ - 128;
+ }
+
+ for (j=Y2_cols>>1; j>0; j--)
+ {
+ *Y2_Ptr++ = *input_ptr++ - 128;
+ *CB_Ptr++ = *input_ptr++ - 128;
+ *Y2_Ptr++ = *input_ptr++ - 128;
+ *CR_Ptr++ = *input_ptr++ - 128;
+ }
+
+ if (cols <= 8)
+ {
+ for (j=8-Y1_cols; j>0; j--)
+ {
+ *Y1_Ptr = *(Y1_Ptr - 1);
+ Y1_Ptr++;
+ }
+
+ for (j=8-Y2_cols; j>0; j--)
+ *Y2_Ptr++ = *(Y1_Ptr - 1);
+ }
+ else
+ {
+ for (j=8-Y2_cols; j>0; j--)
+ {
+ *Y2_Ptr = *(Y2_Ptr - 1);
+ Y2_Ptr++;
+ }
+ }
+
+ for (j=(16-cols)>>1; j>0; j--)
+ {
+ *CB_Ptr = *(CB_Ptr-1);
+ CB_Ptr++;
+ *CR_Ptr = *(CR_Ptr-1);
+ CR_Ptr++;
+ }
+
+ input_ptr += incr;
+ }
+
+ for (i=8-rows; i>0; i--)
+ {
+ for (j=8; j>0; j--)
+ {
+ *Y1_Ptr = *(Y1_Ptr - 8);
+ Y1_Ptr++;
+ *Y2_Ptr = *(Y2_Ptr - 8);
+ Y2_Ptr++;
+ *CB_Ptr = *(CB_Ptr - 8);
+ CB_Ptr++;
+ *CR_Ptr = *(CR_Ptr - 8);
+ CR_Ptr++;
+ }
+ }
+}
+
+static void read_444_format (JPEG_ENCODER_STRUCTURE *jpeg_encoder_structure, UINT8 *input_ptr)
+{
+ INT32 i, j;
+ INT16 *Y1_Ptr = jpeg_encoder_structure->Y1;
+ INT16 *CB_Ptr = jpeg_encoder_structure->CB;
+ INT16 *CR_Ptr = jpeg_encoder_structure->CR;
+
+ UINT16 rows = jpeg_encoder_structure->rows;
+ UINT16 cols = jpeg_encoder_structure->cols;
+ UINT16 incr = jpeg_encoder_structure->incr;
+
+ for (i=rows; i>0; i--)
+ {
+ for (j=cols; j>0; j--)
+ {
+ *Y1_Ptr++ = *input_ptr++ - 128;
+ *CB_Ptr++ = *input_ptr++ - 128;
+ *CR_Ptr++ = *input_ptr++ - 128;
+ }
+
+ for (j=8-cols; j>0; j--)
+ {
+ *Y1_Ptr = *(Y1_Ptr-1);
+ Y1_Ptr++;
+ *CB_Ptr = *(CB_Ptr-1);
+ CB_Ptr++;
+ *CR_Ptr = *(CR_Ptr-1);
+ CR_Ptr++;
+ }
+
+ input_ptr += incr;
+ }
+
+ for (i=8-rows; i>0; i--)
+ {
+ for (j=8; j>0; j--)
+ {
+ *Y1_Ptr = *(Y1_Ptr - 8);
+ Y1_Ptr++;
+ *CB_Ptr = *(CB_Ptr - 8);
+ CB_Ptr++;
+ *CR_Ptr = *(CR_Ptr - 8);
+ CR_Ptr++;
+ }
+ }
+}
+
+static void RGB_2_444 (UINT8 *input_ptr, UINT32 image_width, UINT32 image_height)
+{
+ UINT32 i, size;
+ UINT8 R, G, B;
+ INT32 Y, Cb, Cr;
+ UINT8 *output_ptr = input_ptr;
+
+ size = image_width * image_height;
+
+ for (i=size; i>0; i--)
+ {
+ B = *input_ptr++;
+ G = *input_ptr++;
+ R = *input_ptr++;
+
+ Y = ((77 * R + 150 * G + 29 * B) >> 8);
+ Cb = ((-43 * R - 85 * G + 128 * B) >> 8) + 128;
+ Cr = ((128 * R - 107 * G - 21 * B) >> 8) + 128;
+
+ if (Y < 0)
+ Y = 0;
+ else if (Y > 255)
+ Y = 255;
+
+ if (Cb < 0)
+ Cb = 0;
+ else if (Cb > 255)
+ Cb = 255;
+
+ if (Cr < 0)
+ Cr = 0;
+ else if (Cr > 255)
+ Cr = 255;
+
+ *output_ptr++ = (UINT8) Y;
+ *output_ptr++ = (UINT8) Cb;
+ *output_ptr++ = (UINT8) Cr;
+ }
+}
+
+static void BGR_2_444 (UINT8 *input_ptr, UINT32 image_width, UINT32 image_height)
+{
+ UINT32 i, size;
+ UINT8 R, G, B;
+ INT32 Y, Cb, Cr;
+ UINT8 *output_ptr = input_ptr;
+
+ size = image_width * image_height;
+
+ for (i=size; i>0; i--)
+ {
+ R = *input_ptr++;
+ G = *input_ptr++;
+ B = *input_ptr++;
+
+ Y = ((77 * R + 150 * G + 29 * B) >> 8);
+ Cb = ((-43 * R - 85 * G + 128 * B) >> 8) + 128;
+ Cr = ((128 * R - 107 * G - 21 * B) >> 8) + 128;
+
+ if (Y < 0)
+ Y = 0;
+ else if (Y > 255)
+ Y = 255;
+
+ if (Cb < 0)
+ Cb = 0;
+ else if (Cb > 255)
+ Cb = 255;
+
+ if (Cr < 0)
+ Cr = 0;
+ else if (Cr > 255)
+ Cr = 255;
+
+ *output_ptr++ = (UINT8) Y;
+ *output_ptr++ = (UINT8) Cb;
+ *output_ptr++ = (UINT8) Cr;
+ }
+}
+
+#define CLIP(color) (unsigned char)(((color)>0xFF)?0xff:(((color)<0)?0:(color)))
+
+/* translate RGB24 to YUV422 in input */
+static void RGB_2_422 (UINT8 * input_ptr, UINT32 image_width, UINT32 image_height)
+{
+ UINT32 i, size;
+ UINT8 R, G, B, R1, G1, B1;
+ INT32 Y, Yp, Cb, Cr;
+ UINT8 * inbuf = input_ptr;
+ size = image_width * image_height;
+ for (i = size; i > 0; i--)
+
+ {
+ B = inbuf[0];
+ G = inbuf[1];
+ R = inbuf[2];
+ B1 = inbuf[3];
+ G1 = inbuf[4];
+ R1 = inbuf[5];
+ inbuf += 6;
+ Y = CLIP ((77 * R + 150 * G + 29 * B) >> 8);
+ Yp = CLIP ((77 * R1 + 150 * G1 + 29 * B1) >> 8);
+ Cb = CLIP (((-43 * R - 85 * G + 128 * B) >> 8) + 128);
+ Cr = CLIP (((128 * R - 107 * G - 21 * B) >> 8) + 128);
+ *input_ptr++ = (UINT8) Y;
+ *input_ptr++ = (UINT8) Cb;
+ *input_ptr++ = (UINT8) Yp;
+ *input_ptr++ = (UINT8) Cr;
+ }
+}
+
+
+/* translate RGB24 to YUV420 in input */
+static void RGB_2_420 (UINT8 * input_ptr, UINT32 image_width, UINT32 image_height)
+{
+ UINT32 i, j, size;
+ UINT8 R, G, B, R1, G1, B1, Rd, Gd, Bd, Rd1, Gd1, Bd1;
+ INT32 Y, Yd, Y11, Yd1, Cb, Cr;
+ UINT8 * inbuf = input_ptr;
+ UINT8 * inbuf1 = input_ptr + (image_width * 3);
+ size = image_width * image_height >> 2;
+ for (i = size, j = 0; i > 0; i--)
+
+ {
+ B = inbuf[0];
+ G = inbuf[1];
+ R = inbuf[2];
+ B1 = inbuf[3];
+ G1 = inbuf[4];
+ R1 = inbuf[5];
+ Bd = inbuf1[0];
+ Gd = inbuf1[1];
+ Rd = inbuf1[2];
+ Bd1 = inbuf1[3];
+ Gd1 = inbuf1[4];
+ Rd1 = inbuf1[5];
+ inbuf += 6;
+ inbuf1 += 6;
+ j++;
+ if (j >= image_width / 2)
+ {
+ j = 0;
+ inbuf += (image_width * 3);
+ inbuf1 += (image_width * 3);
+ }
+ Y = CLIP ((77 * R + 150 * G + 29 * B) >> 8);
+ Y11 = CLIP ((77 * R1 + 150 * G1 + 29 * B1) >> 8);
+ Yd = CLIP ((77 * Rd + 150 * Gd + 29 * Bd) >> 8);
+ Yd1 = CLIP ((77 * Rd1 + 150 * Gd1 + 29 * Bd1) >> 8);
+ Cb = CLIP (((-43 * R - 85 * G + 128 * B) >> 8) + 128);
+ Cr = CLIP (((128 * R - 107 * G - 21 * B) >> 8) + 128);
+ *input_ptr++ = (UINT8) Y;
+ *input_ptr++ = (UINT8) Y11;
+ *input_ptr++ = (UINT8) Yd;
+ *input_ptr++ = (UINT8) Yd1;
+ *input_ptr++ = (UINT8) Cb;
+ *input_ptr++ = (UINT8) Cr;
+ }
+}
+
+
+/* translate RGB32 to YUV420 in input */
+static void RGB32_2_420 (UINT8 * input_ptr, UINT32 image_width, UINT32 image_height)
+{
+ UINT32 i, j, size;
+ UINT8 R, G, B, R1, G1, B1, Rd, Gd, Bd, Rd1, Gd1, Bd1;
+ INT32 Y, Yd, Y11, Yd1, Cb, Cr;
+ UINT8 * inbuf = input_ptr;
+ UINT8 * inbuf1 = input_ptr + (image_width * 4);
+ size = image_width * image_height >> 2;
+ for (i = size, j = 0; i > 0; i--)
+
+ {
+/*
+ B = inbuf[0];
+ G = inbuf[1];
+ R = inbuf[2];
+ B1 = inbuf[4];
+ G1 = inbuf[5];
+ R1 = inbuf[6];
+ Bd = inbuf1[0];
+ Gd = inbuf1[1];
+ Rd = inbuf1[2];
+ Bd1 = inbuf1[4];
+ Gd1 = inbuf1[5];
+ Rd1 = inbuf1[6];
+*/
+ B = inbuf[3];
+ G = inbuf[2];
+ R = inbuf[1];
+ B1 = inbuf[7];
+ G1 = inbuf[6];
+ R1 = inbuf[5];
+ Bd = inbuf1[3];
+ Gd = inbuf1[2];
+ Rd = inbuf1[1];
+ Bd1 = inbuf1[7];
+ Gd1 = inbuf1[6];
+ Rd1 = inbuf1[5];
+ inbuf += 8;
+ inbuf1 += 8;
+ j++;
+ if (j >= image_width / 2)
+ {
+ j = 0;
+ inbuf += (image_width * 4);
+ inbuf1 += (image_width * 4);
+ }
+ Y = CLIP ((77 * R + 150 * G + 29 * B) >> 8);
+ Y11 = CLIP ((77 * R1 + 150 * G1 + 29 * B1) >> 8);
+ Yd = CLIP ((77 * Rd + 150 * Gd + 29 * Bd) >> 8);
+ Yd1 = CLIP ((77 * Rd1 + 150 * Gd1 + 29 * Bd1) >> 8);
+ Cb = CLIP (((-43 * R - 85 * G + 128 * B) >> 8) + 128);
+ Cr = CLIP (((128 * R - 107 * G - 21 * B) >> 8) + 128);
+ *input_ptr++ = (UINT8) Y;
+ *input_ptr++ = (UINT8) Y11;
+ *input_ptr++ = (UINT8) Yd;
+ *input_ptr++ = (UINT8) Yd1;
+ *input_ptr++ = (UINT8) Cb;
+ *input_ptr++ = (UINT8) Cr;
+ }
+}
+
+
+/* translate RGB565 to YUV420 in input */
+static void RGB565_2_420 (UINT8 * input_ptr, UINT32 image_width, UINT32 image_height)
+{
+ UINT32 i, j, size;
+ UINT8 R, G, B, R1, G1, B1, Rd, Gd, Bd, Rd1, Gd1, Bd1;
+ INT32 Y, Yd, Y11, Yd1, Cb, Cr;
+ UINT8 * inbuf = (UINT8 *) input_ptr;
+ UINT8 * inbuf1 = inbuf + (image_width);
+ size = image_width * image_height >> 2;
+ for (i = size, j = 0; i > 0; i--)
+ { B = inbuf[0] & 0xf8;
+ G = ((inbuf[0] & 0x07) << 5) | ((inbuf[1] & 0xe0) >> 3);
+ R = (inbuf[1] & 0x1f) << 3;
+
+ B1 = inbuf[2] & 0xf8;
+ G1 = ((inbuf[2] & 0x07) << 5) | ((inbuf[3] & 0xe0) >> 3);
+ R1 = (inbuf[3] & 0x1f) << 3;
+
+ Bd = inbuf1[0] & 0xf8;
+ Gd = ((inbuf1[0] & 0x07) << 5) | ((inbuf1[1] & 0xe0) >> 3);
+ Rd = (inbuf1[1] & 0x1f) << 3;
+
+ Bd1 = inbuf1[2] & 0xf8;
+ Gd1 = ((inbuf1[2] & 0x07) << 5) | ((inbuf1[3] & 0xe0) >> 3);
+ Rd1 = (inbuf1[3] & 0x1f) << 3;
+
+ inbuf += 2;
+ inbuf1 += 2;
+ j++;
+ if (j >= image_width / 2)
+ {
+ j = 0;
+ inbuf += (image_width);
+ inbuf1 += (image_width);
+ }
+ Y = CLIP ((77 * R + 150 * G + 29 * B) >> 8);
+ Y11 = CLIP ((77 * R1 + 150 * G1 + 29 * B1) >> 8);
+ Yd = CLIP ((77 * Rd + 150 * Gd + 29 * Bd) >> 8);
+ Yd1 = CLIP ((77 * Rd1 + 150 * Gd1 + 29 * Bd1) >> 8);
+ Cb = CLIP (((-43 * R - 85 * G + 128 * B) >> 8) + 128);
+ Cr = CLIP (((128 * R - 107 * G - 21 * B) >> 8) + 128);
+ *input_ptr++ = (UINT8) Y;
+ *input_ptr++ = (UINT8) Y11;
+ *input_ptr++ = (UINT8) Yd;
+ *input_ptr++ = (UINT8) Yd1;
+ *input_ptr++ = (UINT8) Cb;
+ *input_ptr++ = (UINT8) Cr;
+ }
+}
+
+static void RGB_2_400 (UINT8 * input_ptr, UINT32 image_width, UINT32 image_height)
+{
+ UINT32 i, size;
+ UINT8 R, G, B;
+ INT32 Y;
+ UINT8 * inbuf = input_ptr;
+ size = image_width * image_height;
+ for (i = size; i > 0; i--)
+
+ {
+ B = inbuf[0];
+ G = inbuf[1];
+ R = inbuf[2];
+ inbuf += 3;
+ Y = CLIP ((77 * R + 150 * G + 29 * B) >> 8);
+ *input_ptr++ = (UINT8) Y;
+ }
+}
+
+
+/* translate YUV444P to YUV444 in input */
+static void YUV_2_444 (UINT8 * input_ptr, UINT32 image_width, UINT32 image_height)
+{
+ UINT32 i, size;
+ UINT8 * Ytmp = NULL;
+ UINT8 * Cbtmp = NULL;
+ UINT8 * Crtmp = NULL;
+ UINT8 * Buff = NULL;
+ Buff =
+ (UINT8 *) realloc ((UINT8 *) Buff,
+ (size_t) (image_width * image_height * 3));
+ if (Buff)
+ {
+ memcpy (Buff, input_ptr, image_width * image_height * 3);
+ Ytmp = Buff;
+ Cbtmp = Buff + image_width * image_height;
+ Crtmp = Buff + (image_width * image_height << 1);
+ size = image_width * image_height;
+ for (i = size; i > 0; i--)
+
+ {
+ *input_ptr++ = (UINT8) * Ytmp++;
+ *input_ptr++ = (UINT8) * Cbtmp++;
+ *input_ptr++ = (UINT8) * Crtmp++;
+ }
+ free (Buff);
+ Buff = NULL;
+ }
+}
+
+
+/* translate YUV422P to YUV422 in input */
+static void YUV_2_422 (UINT8 * input_ptr, UINT32 image_width, UINT32 image_height)
+{
+ UINT32 i, size;
+// UINT8 * inbuf = input_ptr;
+ UINT8 * Ytmp = NULL;
+ UINT8 * Cbtmp = NULL;
+ UINT8 * Crtmp = NULL;
+ UINT8 * Buff = NULL;
+ Buff =
+ (UINT8 *) realloc ((UINT8 *) Buff,
+ (size_t) (image_width * image_height * 2));
+ if (Buff)
+ {
+ memcpy (Buff, input_ptr, image_width * image_height * 2);
+ Ytmp = Buff;
+ Cbtmp = Buff + image_width * image_height;
+ Crtmp = Cbtmp + (image_width * image_height >> 1);
+ size = image_width * image_height;
+ for (i = size; i > 0; i--)
+
+ {
+ *input_ptr++ = (UINT8) * Ytmp++;
+ *input_ptr++ = (UINT8) * Cbtmp++;
+ *input_ptr++ = (UINT8) * Ytmp++;
+ *input_ptr++ = (UINT8) * Crtmp++;
+ }
+ free (Buff);
+ Buff = NULL;
+ }
+}
+
+
+/* translate YUV420P to YUV420 in input */
+static void YUV_2_420 (UINT8 * input_ptr, UINT32 image_width, UINT32 image_height)
+{
+ UINT32 x, y, size;
+// UINT8 * inbuf = input_ptr;
+ UINT8 * Ytmp = NULL;
+ UINT8 * Y2tmp = NULL;
+ UINT8 * Cbtmp = NULL;
+ UINT8 * Crtmp = NULL;
+ UINT8 * Buff = NULL;
+ Buff =
+ (UINT8 *) realloc ((UINT8 *) Buff,
+ (size_t) ((image_width * image_height * 3) >> 1));
+ if (Buff)
+ {
+ memcpy (Buff, input_ptr, (image_width * image_height * 3) >> 1);
+ Ytmp = Buff;
+ Y2tmp = Buff + image_width;
+ Cbtmp = Buff + image_width * image_height;
+ Crtmp = Cbtmp + (image_width * image_height >> 2);
+ size = image_width * image_height >> 2;
+ for (y = 0; y < image_height; y += 2)
+
+ {
+ for (x = 0; x < image_width; x += 2)
+ {
+ *input_ptr++ = (UINT8) * Ytmp++;
+ *input_ptr++ = (UINT8) * Ytmp++;
+ *input_ptr++ = (UINT8) * Y2tmp++;
+ *input_ptr++ = (UINT8) * Y2tmp++;
+ *input_ptr++ = (UINT8) * Cbtmp++;
+ *input_ptr++ = (UINT8) * Crtmp++;
+ }
+ Ytmp += image_width;
+ Y2tmp += image_width;
+ }
+ free (Buff);
+ Buff = NULL;
+ }
+}
+
+/////////// ENCODER //////////////////
+
+static void initialization (JPEG_ENCODER_STRUCTURE * jpeg, UINT32 image_format, UINT32 image_width, UINT32 image_height)
+{
+ UINT16 mcu_width, mcu_height, bytes_per_pixel;
+ jpeg->lcode = 0;
+ jpeg->bitindex = 0;
+
+ if (image_format == FOUR_ZERO_ZERO || image_format == FOUR_FOUR_FOUR)
+
+ {
+ jpeg->mcu_width = mcu_width = 8;
+ jpeg->mcu_height = mcu_height = 8;
+ jpeg->horizontal_mcus = (UINT16) ((image_width + mcu_width - 1) >> 3);
+ jpeg->vertical_mcus = (UINT16) ((image_height + mcu_height - 1) >> 3);
+ if (image_format == FOUR_ZERO_ZERO)
+
+ {
+ bytes_per_pixel = 1;
+ jpeg->read_format_choice = 400;
+ }
+
+ else
+
+ {
+ bytes_per_pixel = 3;
+ jpeg->read_format_choice = 444;
+ }
+ }
+
+ else
+
+ {
+ jpeg->mcu_width = mcu_width = 16;
+ jpeg->horizontal_mcus = (UINT16) ((image_width + mcu_width - 1) >> 4);
+ if (image_format == FOUR_TWO_ZERO)
+
+ {
+ jpeg->mcu_height = mcu_height = 16;
+ jpeg->vertical_mcus = (UINT16) ((image_height + mcu_height - 1) >> 4);
+ bytes_per_pixel = 3;
+ jpeg->read_format_choice = 420;
+ }
+
+ else
+
+ {
+ jpeg->mcu_height = mcu_height = 8;
+ jpeg->vertical_mcus = (UINT16) ((image_height + mcu_height - 1) >> 3);
+ bytes_per_pixel = 2;
+ jpeg->read_format_choice = 422;
+ }
+ }
+ jpeg->rows_in_bottom_mcus = (UINT16) (image_height - (jpeg->vertical_mcus - 1) * mcu_height);
+ jpeg->cols_in_right_mcus = (UINT16) (image_width - (jpeg->horizontal_mcus - 1) * mcu_width);
+ jpeg->length_minus_mcu_width = (UINT16) ((image_width - mcu_width) * bytes_per_pixel);
+ jpeg->length_minus_width = (UINT16) ((image_width - jpeg->cols_in_right_mcus) * bytes_per_pixel);
+ jpeg->mcu_width_size = (UINT16) (mcu_width * bytes_per_pixel);
+ if (image_format != FOUR_TWO_ZERO)
+ jpeg->offset = (UINT16) ((image_width * (mcu_height - 1) - (mcu_width - jpeg->cols_in_right_mcus)) * bytes_per_pixel);
+
+ else
+ jpeg->offset = (UINT16) ((image_width * ((mcu_height >> 1) - 1) - (mcu_width - jpeg->cols_in_right_mcus)) * bytes_per_pixel);
+ jpeg->ldc1 = 0;
+ jpeg->ldc2 = 0;
+ jpeg->ldc3 = 0;
+}
+
+UINT8* encodeMCU (JPEG_ENCODER_STRUCTURE *jpeg_encoder_structure, UINT32 image_format, UINT8 *output_ptr)
+{
+ DCT (jpeg_encoder_structure->Y1);
+ quantization (jpeg_encoder_structure, jpeg_encoder_structure->Y1, jpeg_encoder_structure->ILqt);
+ output_ptr = huffman (jpeg_encoder_structure, 1, output_ptr);
+
+ if (image_format == FOUR_TWO_ZERO || image_format == FOUR_TWO_TWO)
+ {
+ DCT (jpeg_encoder_structure->Y2);
+ quantization (jpeg_encoder_structure, jpeg_encoder_structure->Y2, jpeg_encoder_structure->ILqt);
+ output_ptr = huffman (jpeg_encoder_structure, 1, output_ptr);
+
+ if (image_format == FOUR_TWO_ZERO)
+ {
+ DCT (jpeg_encoder_structure->Y3);
+ quantization (jpeg_encoder_structure, jpeg_encoder_structure->Y3, jpeg_encoder_structure->ILqt);
+ output_ptr = huffman (jpeg_encoder_structure, 1, output_ptr);
+
+ DCT (jpeg_encoder_structure->Y4);
+ quantization (jpeg_encoder_structure, jpeg_encoder_structure->Y4, jpeg_encoder_structure->ILqt);
+ output_ptr = huffman (jpeg_encoder_structure, 1, output_ptr);
+ }
+ }
+
+ if (image_format != FOUR_ZERO_ZERO)
+ {
+ DCT (jpeg_encoder_structure->CB);
+ quantization (jpeg_encoder_structure, jpeg_encoder_structure->CB, jpeg_encoder_structure->ICqt);
+ output_ptr = huffman (jpeg_encoder_structure, 2, output_ptr);
+
+ DCT (jpeg_encoder_structure->CR);
+ quantization (jpeg_encoder_structure, jpeg_encoder_structure->CR, jpeg_encoder_structure->ICqt);
+ output_ptr = huffman (jpeg_encoder_structure, 3, output_ptr);
+ }
+ return output_ptr;
+}
+
+UINT32 encode_image (UINT8 * input_ptr, UINT8 * output_ptr,
+ UINT32 quality_factor, UINT32 image_format,
+ UINT32 image_width, UINT32 image_height)
+{ UINT16 i, j;
+ UINT8 *output, *tmp=NULL;
+ JPEG_ENCODER_STRUCTURE JpegStruct;
+ JPEG_ENCODER_STRUCTURE * jpeg_encoder_structure = &JpegStruct;
+ output = output_ptr;
+
+ switch (image_format)
+ {
+
+ case RGBto444:
+ { tmp = (UINT8 *)malloc(image_width * image_height * 3);
+ memcpy(tmp, input_ptr, image_width * image_height * 3);
+ image_format = FOUR_FOUR_FOUR;
+ RGB_2_444 (tmp, image_width, image_height);
+ input_ptr = tmp;
+ }
+ break;
+
+ case BGRto444:
+ { tmp = (UINT8 *)malloc(image_width * image_height * 3);
+ memcpy(tmp, input_ptr, image_width * image_height * 3);
+ image_format = FOUR_FOUR_FOUR;
+ BGR_2_444 (tmp, image_width, image_height);
+ input_ptr = tmp;
+ }
+ break;
+
+ case RGBto422:
+ { tmp = (UINT8 *)malloc(image_width * image_height * 3);
+ memcpy(tmp, input_ptr, image_width * image_height * 3);
+ image_format = FOUR_TWO_TWO;
+ RGB_2_422 (tmp, image_width, image_height);
+ input_ptr = tmp;
+ }
+ break;
+
+ case RGBto420:
+ { tmp = (UINT8 *)malloc(image_width * image_height * 3);
+ memcpy(tmp, input_ptr, image_width * image_height * 3);
+ image_format = FOUR_TWO_ZERO;
+ RGB_2_420 (tmp, image_width, image_height);
+ input_ptr = tmp;
+ }
+ break;
+
+ case RGB565to420:
+ { tmp = (UINT8 *)malloc(image_width * image_height * 2);
+ memcpy(tmp, input_ptr, image_width * image_height * 2);
+ image_format = FOUR_TWO_ZERO;
+ RGB565_2_420 (tmp, image_width, image_height);
+ input_ptr = tmp;
+ }
+ break;
+
+ case RGB32to420:
+ { tmp = (UINT8 *)malloc(image_width * image_height * 4);
+ memcpy(tmp, input_ptr, image_width * image_height * 4);
+ image_format = FOUR_TWO_ZERO;
+ RGB32_2_420 (tmp, image_width, image_height);
+ input_ptr = tmp;
+ }
+ break;
+
+ case RGBto400:
+ { tmp = (UINT8 *)malloc(image_width * image_height * 3);
+ memcpy(tmp, input_ptr, image_width * image_height * 3);
+ image_format = FOUR_ZERO_ZERO;
+ RGB_2_400 (tmp, image_width, image_height);
+ input_ptr = tmp;
+ }
+ break;
+
+ case YUVto444:
+ { tmp = (UINT8 *)malloc(image_width * image_height * 3);
+ memcpy(tmp, input_ptr, image_width * image_height * 3);
+ image_format = FOUR_FOUR_FOUR;
+ YUV_2_444 (tmp, image_width, image_height);
+ input_ptr = tmp;
+ }
+ break;
+
+ case YUVto422:
+ { tmp = (UINT8 *)malloc(image_width * image_height * 3);
+ memcpy(tmp, input_ptr, image_width * image_height * 3);
+ image_format = FOUR_TWO_TWO;
+ YUV_2_422 (tmp, image_width, image_height);
+ input_ptr = tmp;
+ }
+ break;
+
+ case YUVto420:
+ { tmp = (UINT8 *)malloc(image_width * image_height * 3);
+ memcpy(tmp, input_ptr, image_width * image_height * 3);
+ image_format = FOUR_TWO_ZERO;
+ YUV_2_420 (tmp, image_width, image_height);
+ input_ptr = tmp;
+ }
+ break;
+ }
+
+ /* Initialization of JPEG control structure */
+ initialization (jpeg_encoder_structure, image_format, image_width,
+ image_height);
+
+ /* Quantization Table Initialization */
+ initialize_quantization_tables (jpeg_encoder_structure, quality_factor);
+
+ /* Writing Marker Data */
+ output_ptr =
+ write_markers (jpeg_encoder_structure, output_ptr, image_format, image_width, image_height);
+
+ for (i = 1; i <= jpeg_encoder_structure->vertical_mcus; i++)
+ {
+ if (i < jpeg_encoder_structure->vertical_mcus)
+ jpeg_encoder_structure->rows = jpeg_encoder_structure->mcu_height;
+
+ else
+ jpeg_encoder_structure->rows = jpeg_encoder_structure->rows_in_bottom_mcus;
+
+ for (j = 1; j <= jpeg_encoder_structure->horizontal_mcus; j++)
+ {
+ if (j < jpeg_encoder_structure->horizontal_mcus)
+
+ {
+ jpeg_encoder_structure->cols = jpeg_encoder_structure->mcu_width;
+ jpeg_encoder_structure->incr = jpeg_encoder_structure->length_minus_mcu_width;
+ }
+
+ else
+
+ {
+ jpeg_encoder_structure->cols = jpeg_encoder_structure->cols_in_right_mcus;
+ jpeg_encoder_structure->incr = jpeg_encoder_structure->length_minus_width;
+ }
+ switch(jpeg_encoder_structure->read_format_choice)
+ { case 400: read_400_format (jpeg_encoder_structure, input_ptr); break;
+ case 444: read_444_format (jpeg_encoder_structure, input_ptr); break;
+ case 420: read_420_format (jpeg_encoder_structure, input_ptr); break;
+ case 422: read_422_format (jpeg_encoder_structure, input_ptr); break;
+ }
+
+ /* Encode the data in MCU */
+ output_ptr = encodeMCU (jpeg_encoder_structure, image_format, output_ptr);
+ input_ptr += jpeg_encoder_structure->mcu_width_size;
+ }
+ input_ptr += jpeg_encoder_structure->offset;
+ }
+
+ /* Close Routine */
+ output_ptr = close_bitstream (jpeg_encoder_structure, output_ptr);
+ free(tmp);
+
+ return (UINT32) (output_ptr - output);
+}
+
+/*
+int WRITE_JPEG2_compute(AVSfield_char *input, char *filename, int quality)
+{ FILE *fpt;
+
+ if (input->veclen==3)
+ { UINT8 *output = (UINT8 *)malloc(input->dimensions[0] * input->dimensions[1] * 3);
+ UINT32 len;
+ len = encode_image ((UINT8 *)(input->data), output, quality, RGBto444, input->dimensions[0], input->dimensions[1]);
+ fpt = fopen (filename, "wb");
+ fwrite (output, 1, len, fpt);
+ fclose (fpt);
+ free (output);
+ return AVS_OK;
+ }
+ else if (input->veclen==1)
+ { UINT8 *output = (UINT8 *)malloc(input->dimensions[0] * input->dimensions[1] * 3);
+ UINT32 len;
+ len = encode_image ((UINT8 *)(input->data), output, quality, FOUR_ZERO_ZERO, input->dimensions[0], input->dimensions[1]);
+ fpt = fopen (filename, "wb");
+ fwrite (output, 1, len, fpt);
+ fclose (fpt);
+ free (output);
+ return AVS_OK;
+ }
+ else if (input->veclen==4)
+ { UINT8 *output = (UINT8 *)malloc(input->dimensions[0] * input->dimensions[1] * 3);
+ UINT32 len;
+ len = encode_image ((UINT8 *)(input->data), output, quality, RGB32to420, input->dimensions[0], input->dimensions[1]);
+ fpt = fopen (filename, "wb");
+ fwrite (output, 1, len, fpt);
+ fclose (fpt);
+ free (output);
+ return AVS_OK;
+ }
+ else
+ { AVSerror("WRITE_JPEG2: only 3-vector byte fields allowed");
+ return AVS_ERROR;
+ }
+}
+*/
diff --git a/lex.cpp b/lex.cpp
new file mode 100644
index 0000000..59303f1
--- /dev/null
+++ b/lex.cpp
@@ -0,0 +1,393 @@
+/*
+20000822 ljz Created
+20000823 ljz Support cases where the input-file is empty or contains
+ only white-space.
+20010716 ljz Fix: Allow TOKENs that are substrings of other TOKENs.
+ The largest TOKEN that fits will be the result.
+20050103 mvh Changed include file to lower case (for linux)
+20050108 mvh Removed windows.h for linux compile
+20050118 mvh GNU C++ knows BOOL etc, do not redefine
+20090620 jf Include file stuff
+20100120 mvh Fixed const issue detected with ms8
+20100309 bcb Changed int to unsigned int, add ui as unsigned int in for loop (gcc4.2 Warnings)
+20100619 bcb Fix gcc4 warnings, improve speed and UNUSED_ARGUMENT.
+20100717 bcb Merged
+*/
+
+/*
+ Lex.cpp contains the implementation of two classes:
+ - TK
+ - Lex
+
+ These two classes are defined in Lex.hpp
+
+ The original UCDMC code was shipped with only an object-file 'lex.o', and
+ not with the source-code of these classes.
+
+ The only compiler that could cope with lex.o was M$VC++.
+ However: project-settings had to include a statement to exclude a standard
+ library (msvcrt.lib??). This caused crashes when dgate was not launched by
+ ConquestDicomServer.exe, but was running stand-alone.
+ Print-statements to the console crashed the program...
+
+ For this reason, and in order to be able to compile dgate with other
+ compilers, lex.cpp had to be written.
+
+ Lex.hpp has been left 'as is'
+
+ The code is used in:
+ - amap.cpp: read acrnema.map
+ - parse.cpp: read dicom.sql
+
+ The class TK is just a dummy.
+*/
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include "dgate.hpp"
+#include "lex.hpp"
+
+#ifndef UNUSED_ARGUMENT
+#define UNUSED_ARGUMENT(x) (void)x
+#endif
+
+TK::TK()
+#ifdef __GNUC__ //Faster with member initialization.
+:Value(0),
+Str(NULL)
+#endif
+{
+}
+
+TK::TK (const int i)
+#ifdef __GNUC__ //Faster with member initialization.
+:Value(0),
+Str(NULL)
+#endif
+{
+ UNUSED_ARGUMENT(i);
+}
+
+TK::TK (const int i, int j, char* s)
+#ifdef __GNUC__ //Faster with member initialization.
+:Value(0),
+Str(NULL)
+#endif
+{
+ UNUSED_ARGUMENT(i);
+ UNUSED_ARGUMENT(j);
+ UNUSED_ARGUMENT(s);
+}
+
+TK::~TK ()
+{
+}
+
+
+/*---------------------------------------------------------*/
+
+typedef struct TOKEN_LIST
+{
+ int val;
+ char* token;
+ TOKEN_LIST* pNext;
+} TOKEN_LIST;
+
+
+Lex::Lex()
+#ifdef __GNUC__ //Faster with member initialization.
+:fp(NULL),
+Tree(NULL),
+Tk()
+{
+#else
+{
+ fp = NULL; /* Not used */
+ Tree = NULL; /* Mis-used as a pointer to the root of TOKEN_LIST */
+#endif
+ Tk.Str = NULL; /* Mis-used as a ponter to the current TOKEN_LIST element */
+}
+
+Lex::~Lex()
+{
+ TOKEN_LIST* pCur;
+ TOKEN_LIST* pNext;
+
+ pCur = (TOKEN_LIST*)Tree;
+ while (pCur)
+ { if (pCur->token)
+ free(pCur->token);
+ pNext = pCur->pNext;
+ free(pCur);
+ pCur = pNext;
+ }
+}
+
+
+BOOL Lex::Start (char *filename, TOKENSTRUCT *TKS)
+{
+ FILE* f;
+ int i, j, iFileLength;
+ unsigned int ui;
+ char* pBuf;
+ int iNbTokens;
+ TOKENSTRUCT* pToken;
+ char** ppPos;
+ char* pCurPos;
+ int iFirst, iFirstToken;
+ TOKEN_LIST* pCur = NULL;
+// TOKEN_LIST* pPrev = NULL; /* LJ */
+ char cSave = 0;
+ char bWasWhiteSpace;
+ const char* pTmp;
+
+ /* Sensible parameters? */
+ if ((!filename) || (!TKS))
+ return FALSE;
+
+ /* How many tokens are to be identified in the file? */
+ pToken = TKS;
+ iNbTokens = 0;
+ while (TRUE)
+ { if (pToken->val != 0)
+ if ((pToken->token == NULL) || (pToken->token[0] == 0))
+ return FALSE; /* A search-string must be supplied */
+ else
+ iNbTokens++;
+ else
+ if (!iNbTokens)
+ return FALSE; /* At least one token must be supplied */
+ else
+ break;
+ pToken++;
+ }
+
+ /* Read the file in memory */
+ f = fopen(filename, "rb");
+ if (!f)
+ return FALSE;
+
+ fseek(f, 0, SEEK_END);
+ iFileLength = ftell(f);
+ fseek(f, 0, SEEK_SET);
+
+ pBuf = (char*)malloc(iFileLength + 1);
+ if (!pBuf)
+ { fclose(f);
+ return FALSE;
+ }
+
+ if (fread(pBuf, 1, iFileLength, f) != (unsigned int)iFileLength)
+ { fclose(f);
+ free(pBuf);
+ return FALSE;
+ }
+ fclose(f);
+ pBuf[iFileLength] = 0;
+
+ /* Search all tokens */
+ ppPos = (char**)malloc(iNbTokens * sizeof(char*));
+ if (!ppPos)
+ { fclose(f);
+ free(pBuf);
+ return FALSE;
+ }
+ pToken = TKS;
+ for (i=0; i<iNbTokens; i++)
+ { ppPos[i] = strstr(pBuf, (pToken + i)->token);
+ while (ppPos[i])
+ { /* Is this token a substring of another one? */
+ for (j=0; j<iNbTokens; j++)
+ { if (j == i)
+ continue;
+ pTmp = strstr((pToken + j)->token, (pToken + i)->token);
+ if (pTmp)
+ /* Yep, current token is a substring of another one...
+ Does the larger token also match here? If so,
+ continue searching.
+ */
+ if (strncmp(ppPos[i] - (pTmp - (pToken + j)->token),
+ (pToken + j)->token, strlen((pToken + j)->token)) == 0)
+ { ppPos[i] = strstr(ppPos[i] + 1, (pToken + i)->token);
+ break;
+ }
+ }
+ if (j == iNbTokens)
+ break;
+ }
+
+ }
+
+ /* What is the first found token? */
+ iFirst = iFileLength + 1;
+ iFirstToken = -1;
+ for (i=0; i<iNbTokens; i++)
+ if (ppPos[i] && (ppPos[i] - pBuf < iFirst))
+ { iFirst = ppPos[i] - pBuf;
+ iFirstToken = i;
+ }
+
+ pCurPos = pBuf;
+ while (TRUE)
+ {
+ /* A word may not start with white-space */
+ while ((*pCurPos == '\r') || (*pCurPos == '\n') ||
+ (*pCurPos == '\t') || (*pCurPos == ' '))
+ pCurPos++;
+ if (*pCurPos == 0)
+ break; /* Finished */
+
+ /* Add a new entry */
+ if (!pCur)
+ { Tree = malloc(sizeof(TOKEN_LIST));
+ pCur = (TOKEN_LIST*)Tree;
+ }
+ else
+ { pCur->pNext = (TOKEN_LIST*)malloc(sizeof(TOKEN_LIST));
+ pCur = pCur->pNext;
+ }
+
+ if (pCurPos < pBuf + iFirst)
+ { /* A USER entry */
+ pCur->val = TOKEN_USER;
+ /* Entry is terminated at the start of the next TOKEN... */
+ if (iFirstToken != -1)
+ { cSave = pBuf[iFirst];
+ pBuf[iFirst] = 0;
+ }
+ /* ... or at the first occurance of white-space */
+ bWasWhiteSpace = 0;
+ for (ui=0; ui<strlen(pCurPos); ui++)
+ if ((pCurPos[ui] == '\r') || (pCurPos[ui] == '\n') ||
+ (pCurPos[ui] == '\t') || (pCurPos[ui] == ' '))
+ { pCurPos[ui] = 0;
+ bWasWhiteSpace = 1;
+ break;
+ }
+ pCur->token = strdup(pCurPos);
+ if (bWasWhiteSpace)
+ pCurPos[ui] = ' ';
+ pCurPos += strlen(pCur->token);
+ if (iFirstToken != -1)
+ pBuf[iFirst] = cSave;
+ }
+ else
+ { /* A TOKEN entry */
+ pCur->val = (pToken + iFirstToken)->val;
+ pCur->token = NULL;
+ pCurPos += strlen((pToken + iFirstToken)->token);
+
+ /* Update the next occurance of this token */
+ ppPos[iFirstToken] = strstr(pCurPos, (pToken + iFirstToken)->token);
+ while (ppPos[iFirstToken])
+ { /* Is this token a substring of another one? */
+ for (j=0; j<iNbTokens; j++)
+ { if (j == iFirstToken)
+ continue;
+ pTmp = strstr((pToken + j)->token, (pToken + iFirstToken)->token);
+ if (pTmp)
+ /* Yep, current token is a substring of another one...
+ Does the larger token also match here? If so,
+ continue searching.
+ */
+ if (strncmp(ppPos[iFirstToken] - (pTmp - (pToken + j)->token),
+ (pToken + j)->token, strlen((pToken + j)->token)) == 0)
+ { ppPos[iFirstToken] = strstr(ppPos[iFirstToken] + 1, (pToken + iFirstToken)->token);
+ break;
+ }
+ }
+ if (j == iNbTokens)
+ break;
+ }
+
+ /* Update the first token */
+ iFirst = iFileLength + 1;
+ iFirstToken = -1;
+ for (i=0; i<iNbTokens; i++)
+ if (ppPos[i] && (ppPos[i] - pBuf < iFirst))
+ { iFirst = ppPos[i] - pBuf;
+ iFirstToken = i;
+ }
+ }
+ pCur->pNext = NULL;
+ }
+
+ /* Finally add an END token */
+ if (!pCur)
+ { Tree = malloc(sizeof(TOKEN_LIST));
+ pCur = (TOKEN_LIST*)Tree;
+ }
+ else
+ { pCur->pNext = (TOKEN_LIST*)malloc(sizeof(TOKEN_LIST));
+ pCur = pCur->pNext;
+ }
+ pCur->val = TOKEN_END;
+ pCur->token = NULL;
+ pCur->pNext = NULL;
+
+
+ /* Cleanup */
+ free(ppPos);
+ free(pBuf);
+
+ return TRUE;
+}
+
+BOOL Lex::Stop ()
+{
+ return TRUE;
+}
+
+int Lex::Peek (TK* pTK)
+{
+ TOKEN_LIST* pCur;
+
+ pCur = (TOKEN_LIST*)Tk.Str;
+ if (!pCur)
+ { /* No entries in token-list */
+ pTK->Value = TOKEN_END;
+ pTK->Str = NULL;
+ }
+ else
+ { pTK->Value = pCur->val;
+ pTK->Str = pCur->token;
+ }
+ return pTK->Value;
+}
+
+int Lex::Get (TK* pTK)
+{
+ TOKEN_LIST* pCur;
+
+ pCur = (TOKEN_LIST*)Tk.Str;
+ if (!pCur)
+ /* The first time */
+ pCur = (TOKEN_LIST*)Tree;
+ else
+ /* Get next token, or stay at EOF */
+ if (pCur->pNext)
+ pCur = pCur->pNext;
+ Tk.Str = (char*)pCur;
+
+ if (!pCur)
+ { /* No entries in token-list */
+ pTK->Value = TOKEN_END;
+ pTK->Str = NULL;
+ }
+ else
+ { pTK->Value = pCur->val;
+ pTK->Str = pCur->token;
+ }
+
+ return pTK->Value;
+}
+
+int Lex::GetString (TK* pTK, char c)
+{
+ UNUSED_ARGUMENT(pTK);
+ UNUSED_ARGUMENT(c);
+ /* Not implemented */
+ return 0;
+}
+
diff --git a/lex.hpp b/lex.hpp
new file mode 100644
index 0000000..91721f7
--- /dev/null
+++ b/lex.hpp
@@ -0,0 +1,60 @@
+// 20091231 bcb Changed char* to const char* for gcc4.2 warnings
+// 20100111 mvh Merged
+// 20100619 bcb Added no-copy to the classes.
+// 20100717 mvh Merged
+
+#ifndef _LEX_H
+# define _LEX_H
+
+typedef struct _TOKENSTRUCT
+{
+ int val;
+ const char *token;
+} TOKENSTRUCT;
+
+#define TOKEN_END -2
+#define TOKEN_USER 0
+#define NEW_LINE -3
+
+class TK
+ {
+ public:
+ int Value;
+ char *Str;
+ TK ();
+ TK (const int);
+ TK (const int, int, char *);
+
+ ~TK ();
+#ifdef __GNUC__
+ private:// This will prevent it from being copied (it has a pointer)
+ TK(const TK&);
+ const TK & operator = (const TK&);
+#endif
+ };
+
+class Lex
+ {
+ FILE *fp;
+ void *Tree;
+ TK Tk;
+ public:
+ Lex();
+ ~Lex();
+ BOOL Start (char *filename, TOKENSTRUCT *TKS);
+ BOOL Stop ();
+ int Peek (TK *);
+ int Get (TK *);
+ int GetString ( TK *, char );
+#ifdef __GNUC__
+ private:// This will prevent it from being copied (it has pointers)
+ Lex(const Lex&);
+ const Lex & operator = (const Lex&);
+#endif
+ };
+
+#define TOKEN_END -2
+#define TOKEN_USER 0
+#define kNEW_LINE -3
+
+#endif
diff --git a/linuxmanual.pdf b/linuxmanual.pdf
new file mode 100644
index 0000000..4e9f0b8
Binary files /dev/null and b/linuxmanual.pdf differ
diff --git a/loadddo.cpp b/loadddo.cpp
new file mode 100644
index 0000000..c5f2b7e
--- /dev/null
+++ b/loadddo.cpp
@@ -0,0 +1,464 @@
+/*
+ * Reads DICOMObject's from disk. As well as makes Windows BITMAP
+ * Structures.
+ *
+ * Bugs: Does not handle sequence objects
+ * Does not support the recent change to DICOM Chapter 10
+ * Only works on 32 bit little-endian architecture
+ * Notes:
+ *
+ * Eventually this routine will be not be needed. I will
+ * add Disk I/O to the PDU_Service class, which will be a much cleaner,
+ * and much more portable solution.
+ * Mark Oskin
+ *
+ */
+
+/*
+19980409 mvh Added NKI private decompression engine VR 0x7fdf,0x0010
+19980410 mvh Added run length encoding of zero differences
+19980410 ljz+mvh Fix 16 bit absolute value decode
+19980415 ljz+mvh Fix leak on decompress
+19980625 mvh Added compression in SaveDicomDataObject(C10)
+19980703 mvh+ljz Made DObjectSerialize thread save (removed statics)
+19990105 ljz Fix: SaveDICOMDataObjectC10 created VR 0x0002 0x0013 twice
+ Added comment in SaveDICOMDataObjectC10; CleanUp
+ Put the nki-routines also in dgate.hpp
+ Added LoadImplicitLittleEndianFile
+19990317 ljz Decompression removed from LoadImplicitLittleEndianFile; added a
+ VR-sizelimit of that reader
+19990827 mvh NOTE: LoadImplicitLittleEndianFile allocates 100 MB and crashes when passing
+ chapter 10 file (happens when extension is wrongly .v2)
+19990830 ljz Fixed problem above: 'LoadImplicitLittleEndianFile' uses
+ 'PDU.LoadDICOMDataObject' in such cases.
+19991117 ljz Added parameter FileCompressMode to in nki_private_compress call
+20000629 ljz Logging of trouble now starts with '***'
+20001104 mvh Renamed _LittleEndianUID to _LittleEndianUID_space
+20001105 mvh Fixed where malloc and new were mixed (vr->data)
+20001106 mvh Use delete [] operation for vr->Data
+20001128 ljz Fix in 'Implicit length' code in LoadImplicitLittleEndian
+20010429 mvh Use faster and safer decompressor
+20020412 ljz Added class CBufferedIO for faster reading from DVD (stream functions
+ do not seem to be cacheing...)
+20020415 mvh Removed diagnostic time code (did not compile on ms4.2)
+ Made buffer size dependent on iVrSizelimit
+ (i.e, use smaller for regen, slightly faster)
+20030706 mvh Attach VRType to PDU's for implicit little endian support
+20041130 mvh Documented crash on win2000 server in code - remain to be fixed
+20050107 mvh Adapted for linux compile
+20051219 mvh Use ReAlloc instead of new BYTE[] to fill VR data
+20070308 bcb And little/big endian.
+20081116 mvh Adapted for very large objects (use unsigned int for length)
+20090211 mvh Safety checks in LoadImplicitLittleEndian to avoid crash on corrupted V2 file
+ Removed lots of dead code
+20090412 mvh Fixed for linux compile (tell does not exist)
+20091215 ljz Fixed LoadImplicitLittleEndian() when iVrSizeLimit is used (e.g. regen)
+ (assumption that the pixeldata would be the last VR is not correct).
+20091231 bcb Changed char* to const char* for gcc4.2 warnings
+20100111 mvh Merged
+20100210 bcb Fixed reading some old V2 files.
+20100309 bcb Changed int to unsigned int, cast m_iNbBytesInBuffer to long (gcc4.2 Warnings)
+20100309 bcb Commented out unused (gcc4.2 Warnings)
+20100619 bcb Fix gcc4 warnings, improve speed and prevent CBufferIO from being copied.
+20100717 mvh Merged
+*/
+
+
+#ifdef WIN32
+#include <io.h>
+#else
+#include <unistd.h>
+#endif
+
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <stdio.h>
+
+#ifndef WHEDGE
+# include "dgate.hpp"
+#else
+# include "master.h"
+#endif
+
+/*-----------------------------------------------------------------------*/
+
+class CBufferedIO
+{
+ private:
+ char* m_pBuf;
+ int m_iBufSize;
+ int m_iCurPos;
+ int m_iNbBytesInBuffer;
+ int m_iNbBlocksRead;
+ public:
+ CBufferedIO(int iBufSize = 0x4000);
+ ~CBufferedIO();
+ int read (int handle, void *buffer, unsigned int count);
+ long lseek(int handle, long offset, int origin);
+#ifdef __GNUC__
+private:// This will prevent it from being copied (it has a pointer)
+ CBufferedIO(const CBufferedIO&);
+ const CBufferedIO & operator = (const CBufferedIO&);
+#endif
+};
+
+CBufferedIO::CBufferedIO(int iBufSize)
+#ifdef __GNUC__ // Faster with member initialization.
+:m_pBuf(NULL),
+m_iBufSize(iBufSize),
+m_iCurPos(0),
+m_iNbBytesInBuffer(0),
+m_iNbBlocksRead(0) {}
+#else
+{
+ m_pBuf = NULL;
+ m_iBufSize = iBufSize;
+ m_iCurPos = 0;
+ m_iNbBytesInBuffer = 0;
+ m_iNbBlocksRead = 0;
+};
+#endif
+
+CBufferedIO::~CBufferedIO()
+{
+ if (m_pBuf)
+ free(m_pBuf);
+}
+
+int CBufferedIO::read (int handle, void *buffer, unsigned int count)
+{ int iNbBytesCopied = 0;
+
+ if (!m_pBuf)
+ { if (m_iBufSize <= 0)
+ return -1;
+ m_pBuf = (char*)malloc(m_iBufSize);
+ if (!m_pBuf)
+ return -1;
+ }
+
+ while ((signed int)count - iNbBytesCopied > m_iNbBytesInBuffer - m_iCurPos)
+ { memcpy(buffer, m_pBuf + m_iCurPos, m_iNbBytesInBuffer - m_iCurPos);
+ buffer = (char*)buffer + m_iNbBytesInBuffer - m_iCurPos;
+ iNbBytesCopied += m_iNbBytesInBuffer - m_iCurPos;
+ m_iCurPos = 0;
+ m_iNbBytesInBuffer = ::read(handle, m_pBuf, m_iBufSize);
+ m_iNbBlocksRead ++;
+ if (m_iNbBytesInBuffer <= 0)
+ return iNbBytesCopied;
+ }
+
+/* crash probably when read failed of file after:
+
+2004-11-30 09:46:48 [RT8769103] Sending file : y:\dv0_0001\20001314\1.2.840.113619.2.22.287.1.369.2.20000619.221935_0002_000014_96263112199.V2
+
+ 0001:0001fb70 ?read at CBufferedIO@@QAEHHPAXI at Z 00420b70 f loadddo.obj
+ 0001:0001fc40 ?lseek at CBufferedIO@@QAEJHJH at Z 00420c40 f loadddo.obj
+
+
+function: <nosymbols>
+ 00420c0d 5b pop ebx
+ 00420c0e c20c00 ret 0xc
+ 00420c11 8b44241c mov eax,[esp+0x1c] ss:0b6c89cf=????????
+ 00420c15 8b7500 mov esi,[ebp+0x0] ss:02b85cb6=????????
+ 00420c18 8bd0 mov edx,eax
+ 00420c1a 037508 add esi,[ebp+0x8] ss:02b85cb6=????????
+ 00420c1d 2bd3 sub edx,ebx
+ 00420c1f 8b7c2418 mov edi,[esp+0x18] ss:0b6c89cf=????????
+ 00420c23 8bca mov ecx,edx
+ 00420c25 c1e902 shr ecx,0x2
+FAULT ->00420c28 f3a5 rep movsd ds:023c2000=???????? es:1f838480=00000000
+ 00420c2a 8bca mov ecx,edx
+ 00420c2c 83e103 and ecx,0x3
+ 00420c2f f3a4 rep movsb ds:023c2000=?? es:1f838480=00
+ 00420c31 8bc8 mov ecx,eax
+ 00420c33 2bcb sub ecx,ebx
+ 00420c35 014d08 add [ebp+0x8],ecx ss:02b85cb6=????????
+ 00420c38 5d pop ebp
+ 00420c39 5f pop edi
+ 00420c3a 5e pop esi
+ 00420c3b 5b pop ebx
+ 00420c3c c20c00 ret 0xc
+
+*/
+
+ memcpy(buffer, m_pBuf + m_iCurPos, count - iNbBytesCopied);
+ m_iCurPos += count - iNbBytesCopied;
+ return count;
+}
+
+long CBufferedIO::lseek(int handle, long offset, int origin)
+{ long rc;
+
+ /* Just handle the special case for the 'DICM' test */
+ if ((origin == SEEK_SET) &&
+ (offset < (long)m_iNbBytesInBuffer) &&
+ (m_iNbBlocksRead == 1))
+ { m_iCurPos = offset;
+ rc = offset;
+ }
+ else
+ { /* Make sure that above special case does not re-appear */
+ m_iNbBlocksRead = 999;
+ if (origin == SEEK_CUR)
+ /* Adjust the file-position to where the caller thinks it is */
+ offset = offset - (m_iNbBytesInBuffer - m_iCurPos);
+ rc = (long)::lseek(handle, offset, origin);
+ m_iCurPos = 0;
+ m_iNbBytesInBuffer = 0;
+ }
+ return rc;
+}
+
+/*-----------------------------------------------------------------------*/
+
+extern void MyDcmError(int error, const char *message, int count);
+
+
+static BOOL
+LoadImplicitLittleEndian(DICOMDataObject* pDDO, CBufferedIO* pBufferedIO,
+ int handle, unsigned int iVrSizeLimit, unsigned int uFileSize)
+{
+ DICOMDataObject* pNewDDO;
+ VR* pVR;
+ char Buf[2 + 2 + 4];
+ unsigned int CurrentGroup = 0;
+ unsigned int CurrentElement = 0;
+
+ SetDicomErrorHandler(NULL);
+
+ while (pBufferedIO->read(handle, Buf, sizeof(Buf)) == sizeof(Buf))
+ {
+ /* Group, Element and Size could be read */
+ pVR = new VR;
+ if (!pVR)
+ {
+ OperatorConsole.printf("*** failed to allocate memory during load of V2 file (previous %04x:%04x)\n", CurrentGroup, CurrentElement);
+ SetDicomErrorHandler(MyDcmError);
+ return FALSE;
+ }
+
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ pVR->Group = *((unsigned short*) Buf);
+ pVR->Element = *((unsigned short*)(Buf + 2));
+ pVR->Length = *((unsigned int*) (Buf + 2 + 2));
+#else //Big Endian like Apple power pc
+ pVR->Group = SwitchEndian( *((UINT16*) Buf));
+ pVR->Element = SwitchEndian( *((UINT16*)(Buf + 2)));
+ pVR->Length = SwitchEndian( *((UINT32*) (Buf + 2 + 2)));
+#endif //Big Endian
+
+ if (pVR->Group < CurrentGroup)
+ {
+ OperatorConsole.printf("*** Encountered an invalid group order during load of V2 file (current %04x:%04x, previous %04x:%04x)\n", pVR->Group, pVR->Element, CurrentGroup, CurrentElement);
+ SetDicomErrorHandler(MyDcmError);
+ return FALSE;
+ }
+
+ if (pVR->Group != CurrentGroup)
+ {
+ CurrentGroup = pVR->Group;
+ CurrentElement = 0;
+ }
+
+ if (pVR->Element < CurrentElement)
+ {
+ OperatorConsole.printf("*** Encountered an invalid element order during load of V2 file (current %04x:%04x, previous %04x:%04x)\n", pVR->Group, pVR->Element, CurrentGroup, CurrentElement);
+ SetDicomErrorHandler(MyDcmError);
+ return FALSE;
+ }
+
+ CurrentElement = pVR->Element;
+
+ if (pVR->Group == 0xfffe)
+ {
+ /* A deliminator */
+ if ((pVR->Element == 0xe0dd) || (pVR->Element == 0xe00d))
+ {
+ delete pVR;
+ SetDicomErrorHandler(MyDcmError);
+ return TRUE;
+ }
+ if (pVR->Length == 0xffffffff)
+ {
+ /* Implicit length... Go until deliminator */
+ pVR->Length = 0;
+ delete pVR;
+ pNewDDO = new DICOMDataObject;
+ if (LoadImplicitLittleEndian(pNewDDO, pBufferedIO, handle, iVrSizeLimit, uFileSize))
+ {
+ pDDO->Push(pNewDDO);
+ continue;
+ }
+ else
+ {
+ delete pNewDDO;
+ SetDicomErrorHandler(MyDcmError);
+ return FALSE;
+ }
+ }
+ if (pVR->Element == 0xe000)
+ {
+ /* BCB- Found a v2 file with a length != 0 and pixel data here (see LJZ below) */
+ if(pVR->Length == 0)
+ {
+ /* Sequence begin ? */
+ // pVR->Length = 0;
+ delete pVR;
+ pNewDDO = new DICOMDataObject;
+ if (LoadImplicitLittleEndian(pNewDDO, pBufferedIO, handle, iVrSizeLimit, uFileSize))
+ {
+ pDDO->Push(pNewDDO);
+ continue;
+ }
+ else
+ {
+ delete pNewDDO;
+ SetDicomErrorHandler(MyDcmError);
+ return FALSE;
+ }
+ }
+ }
+ }
+ if (pVR->Length == 0xffffffff)
+ {
+ pVR->Length = 0;
+ pDDO->Push(pVR);
+ if (!LoadImplicitLittleEndian(pDDO, pBufferedIO, handle, iVrSizeLimit, uFileSize))
+ {
+ SetDicomErrorHandler(MyDcmError);
+ return FALSE;
+ }
+ continue;
+ }
+ else if (pVR->Length>uFileSize || (pVR->Length&1))
+ {
+ OperatorConsole.printf("*** Encountered an invalid item length (%u) during load of V2 file in %04x:%04x\n",
+ pVR->Length, CurrentGroup, CurrentElement);
+ SetDicomErrorHandler(MyDcmError);
+ return FALSE;
+ }
+
+ /* Check whether the current VR has to be read.
+ NKI DicomNodes can restrict what has to be read
+ Following code assumes that reading is finished when pixeldata
+ are encountered. (Maybe a problem here!!!)
+ LJZ: indeed, there are examples of pixeldata inside a sequence, when the 'real'
+ pixeldata (amongst other VRs) still have to come...
+ */
+ if (pVR->Length > iVrSizeLimit)
+ {
+ if (((pVR->Group == 0x7fdf) || (pVR->Group == 0x7fe0)) &&
+ (pVR->Element == 0x0010))
+ {
+ /* Ready !? */
+/*
+ pVR->Length = 0;
+ delete pVR;
+ SetDicomErrorHandler(MyDcmError);
+ return TRUE;
+*/
+ pBufferedIO->lseek(handle, pVR->Length, SEEK_CUR);
+ pVR->Length = 0;
+ delete pVR;
+ continue;
+ }
+ else
+ { /* Read it, throw it away and continue */
+ pVR->ReAlloc(pVR->Length);
+ if (!pVR->Data)
+ {
+ OperatorConsole.printf("*** Element too large during load of V2 file in %04x:%04x\n",
+ CurrentGroup, CurrentElement);
+ SetDicomErrorHandler(MyDcmError);
+ return FALSE;
+ }
+ pBufferedIO->read(handle, pVR->Data, pVR->Length);
+ delete pVR;
+ continue;
+ }
+ }
+ if (pVR->Length)
+ {
+ pVR->ReAlloc(pVR->Length);
+ if (!pVR->Data)
+ {
+ OperatorConsole.printf("*** Element too large during load of V2 file in %04x:%04x\n",
+ CurrentGroup, CurrentElement);
+ SetDicomErrorHandler(MyDcmError);
+ return FALSE;
+ }
+ pBufferedIO->read(handle, pVR->Data, pVR->Length);
+ }
+ else
+ pVR->Data = NULL;
+ pDDO->Push(pVR);
+ }
+
+ SetDicomErrorHandler(MyDcmError);
+ return TRUE;
+}
+
+
+DICOMDataObject*
+LoadImplicitLittleEndianFile(char* filename, unsigned int iVrSizeLimit)
+{
+ DICOMDataObject* pDDO;
+ int handle;
+ char Buf[128 + 4];
+ PDU_Service PDU;
+ unsigned int uFileSize;//,iLastTime, iCurTime;
+ CBufferedIO* pBufferedIO;
+
+ PDU.AttachRTC(&VRType);
+
+#ifdef WIN32
+ handle = sopen( filename, O_RDONLY | O_BINARY, SH_DENYNO, S_IREAD);
+#else
+ handle = open( filename, O_RDONLY);
+#endif
+
+ if (handle == -1)
+ {
+ return NULL;
+ }
+
+ uFileSize = (long)lseek(handle, 0, SEEK_END);
+ // uFileSize = tell(handle); /* ask position */
+ lseek(handle, 0, SEEK_SET);
+
+ pBufferedIO = new CBufferedIO(iVrSizeLimit < 0x1000 ? 0x1000 : 0x8000);
+ /* Find out whether marker 'DICM' exists */
+ if (pBufferedIO->read(handle, Buf, 128 + 4) != 128 + 4)
+ {
+ delete pBufferedIO;
+ close(handle);
+ return NULL;
+ }
+ else
+ {
+ if (strncmp(Buf + 128, "DICM", 4) != 0)
+ {
+ pBufferedIO->lseek(handle, 0, SEEK_SET);
+ /* We are at beginning of the VRs */
+ pDDO = new DICOMDataObject;
+ if (!LoadImplicitLittleEndian(pDDO, pBufferedIO, handle, iVrSizeLimit, uFileSize))
+ {
+ delete pDDO;
+ return NULL;
+ }
+ delete pBufferedIO;
+ close(handle);
+ return pDDO;
+ }
+ else
+ {
+ /* The function 'LoadImplicitLittleEndianFile' is not intended for
+ DICM files, however don't be fuzzy about it... */
+ delete pBufferedIO;
+ close(handle);
+ pDDO = PDU.LoadDICOMDataObject(filename);
+ return pDDO;
+ }
+ }
+}
+
diff --git a/lua/ChangeReturnIPAddress.lua b/lua/ChangeReturnIPAddress.lua
new file mode 100644
index 0000000..6c33453
--- /dev/null
+++ b/lua/ChangeReturnIPAddress.lua
@@ -0,0 +1,26 @@
+-- This script, when run from
+-- [lua]
+-- association=dofile('ChangeReturnIPAddress.lua')
+-- will update the return adress for each AE to match the called
+-- address i.e., this will allow devices without fixed IP adress to
+-- c-move images to them.
+
+--[[ Test code; r-click evaluate in console after project-run:
+Association.ConnectedIP = '5.5.5.5'
+Association.Calling = 'RTDICOM01'
+dofile('ChangeReturnIPAddress.lua')
+for i=0,10 do
+ print('AE', i, get_amap(i))
+end
+]]
+
+local i
+for i=0,100 do
+ local AE,IP,P,C = get_amap(i)
+ if AE==nil then break end
+ print('testing AEs', i, AE, IP, P, C)
+ if Association.Calling==AE and Association.ConnectedIP~=IP then
+ print('changing AE to:', i, AE, Association.ConnectedIP, P, C)
+ servercommand('put_amap:'..i..','..AE..','..Association.ConnectedIP..','..P..','..C)
+ end
+end
diff --git a/lua/FixRTDicom.lua b/lua/FixRTDicom.lua
new file mode 100644
index 0000000..90fd4d2
--- /dev/null
+++ b/lua/FixRTDicom.lua
@@ -0,0 +1,228 @@
+-- This module attempts to fix UID's in a CT/RTSTRUCT/RTPLAN/RTIMAGE/RTDOSE set
+-- Marcel van Herk, 20120817
+-- mvh+bs: prints with ***; note: do not use with DBF driver
+-- Some cleanup after fixes of Barbara Stam, Marcel van Herk, 20120920
+
+-- gets sop of rtplan for this study - note assumes there is only one
+function getrtplan(data)
+ local StudyUID = data.StudyInstanceUID;
+ local SeriesInst = dbquery('DICOMSeries', 'SeriesInst', 'StudyInsta = "'..StudyUID..'" and Modality = "RTPLAN"')[1][1]
+ local PlanSOP = dbquery('DICOMImages', 'SOPInstanc', 'SeriesInst = "'..SeriesInst..'"')[1][1]
+ return PlanSOP
+end;
+
+-- gets sop of rtstruct for this study - note assumes there is only one
+function getrtstruct(data)
+ local StudyUID = data.StudyInstanceUID;
+ local SeriesInst = dbquery('DICOMSeries', 'SeriesInst', 'StudyInsta = "'..StudyUID..'" and Modality = "RTSTRUCT"')[1][1]
+ local StructSOP = dbquery('DICOMImages', 'SOPInstanc', 'SeriesInst = "'..SeriesInst..'"')[1][1]
+ return StructSOP
+end;
+
+-- gets CT series for this study - note assumes there is only one
+function getctseries(data)
+ local StudyUID = data.StudyInstanceUID;
+ local SeriesInst = dbquery('DICOMSeries', 'SeriesInst', 'StudyInsta = "'..StudyUID..'" and Modality = "CT"')[1][1]
+ return SeriesInst;
+end;
+
+-- gets CT frame of reference for this study - note assumes there is only one
+function getctframeofref(data)
+ local StudyUID = data.StudyInstanceUID;
+ local FrameOfRef = dbquery('DICOMSeries', 'FrameOfRef', 'StudyInsta = "'..StudyUID..'" and Modality = "CT"')[1][1]
+ return FrameOfRef;
+end;
+
+-- gets study for this study
+function getstudy(data)
+ local StudyUID = data.StudyInstanceUID;
+ return StudyUID;
+end;
+
+-- returns correct CT slice sop for incorrect CT slice sop in RTSTRUCT
+-- input: data = RTSTRUCT
+-- sops = table of incorrect sops extracted from RTSTRUCT
+-- sop = incorrect sop
+-- assumption: number and order of incorrect CT slice sops matches those of correct CT slice sops
+-- note: if this is not true, the RTSTRUCT will still be readable, but syntactically incorrect
+function getsop(data, sops, sop)
+ local t=1;
+ for i=1, #sops do
+ if sops[i]==sop then
+ t = i;
+ end;
+ end;
+
+ local StudyUID = data.StudyInstanceUID;
+ local SeriesInst = dbquery('DICOMSeries', 'SeriesInst', 'StudyInsta = "'..StudyUID..'" and Modality = "CT"')[1][1]
+ local CTSOPS = dbquery('DICOMImages', 'SOPInstanc', 'SeriesInst = "'..SeriesInst..'"', 'ImageNumbe');
+
+ if t > #CTSOPS then
+ t = #CTSOPS;
+ end;
+ return CTSOPS[t][1];
+end;
+
+-- process RTSTRUCT, prints UIDS, referenced UIDS and new referenced UIDS
+if Data.Modality=='RTSTRUCT' then
+ local i, j, k;
+
+ -- print sops
+ print('*** Processing RTSTRUCT for patient ' .. Data.PatientName .. ' ' .. Data.PatientID);
+ print('*** Date of RTSTRUCT is ' .. Data.StructureSetDate);
+ print('*** study', Data.StudyInstanceUID);
+ print('*** series', Data.SeriesInstanceUID);
+ print('*** sop', Data.SOPInstanceUID)
+
+ -- print references
+ print('*** r study', Data.ReferencedStudySequence[0].ReferencedSOPInstanceUID);
+ print('*** r frameofref', Data.ReferencedFrameOfReferenceSequence[0].FrameOfReferenceUID)
+ print('*** r study', Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].ReferencedSOPInstanceUID)
+ print('*** r series', Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].SeriesInstanceUID) --]]
+
+ --for i=0, #Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].ContourImageSequence-1 do
+ -- print('*** r sop', i, Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].ContourImageSequence[i].ReferencedSOPInstanceUID)
+ --end;
+
+ --[[
+ for i=0, #Data.StructureSetROISequence-1 do
+ print('*** frameofref', i, Data.StructureSetROISequence[i].ReferencedFrameOfReferenceUID)
+ end;
+ for i=0, #Data.ROIContourSequence-1 do
+ for j=0, #Data.ROIContourSequence[i].ContourSequence-1 do
+ for k=0, #Data.ROIContourSequence[i].ContourSequence[j].ContourImageSequence-1 do
+ print('*** r sop', i, j, k, Data.ROIContourSequence[i].ContourSequence[j].ContourImageSequence[k].ReferencedSOPInstanceUID)
+ end
+ end
+ end;
+ --]]
+
+ -- build table of incorrect sops
+ local sops = {}
+ for i=0, #Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].ContourImageSequence-1 do
+ sops[i+1] = Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].ContourImageSequence[i].ReferencedSOPInstanceUID
+ end;
+ table.sort(sops);
+
+ -- fix references
+ Data.ReferencedStudySequence[0].ReferencedSOPInstanceUID = getstudy(Data);
+ Data.ReferencedFrameOfReferenceSequence[0].FrameOfReferenceUID = getctframeofref(Data);
+ Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].ReferencedSOPInstanceUID = getstudy(Data);
+ Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].SeriesInstanceUID = getctseries(Data);
+
+ for i=0, #Data.StructureSetROISequence-1 do
+ Data.StructureSetROISequence[i].ReferencedFrameOfReferenceUID = getctframeofref(Data);
+ end;
+
+ for i=0, #Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].ContourImageSequence-1 do
+ Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].ContourImageSequence[i].ReferencedSOPInstanceUID =
+ getsop(Data, sops, Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].ContourImageSequence[i].ReferencedSOPInstanceUID);
+ end;
+
+ if Data.ROIContourSequence then
+ for i=0, #Data.ROIContourSequence-1 do
+ if Data.ROIContourSequence[i].ContourSequence then
+ for j=0, #Data.ROIContourSequence[i].ContourSequence-1 do
+ if Data.ROIContourSequence[i].ContourSequence[j].ContourImageSequence then
+ for k=0, #Data.ROIContourSequence[i].ContourSequence[j].ContourImageSequence-1 do
+ Data.ROIContourSequence[i].ContourSequence[j].ContourImageSequence[k].ReferencedSOPInstanceUID =
+ getsop(Data, sops, Data.ROIContourSequence[i].ContourSequence[j].ContourImageSequence[k].ReferencedSOPInstanceUID);
+ end
+ end
+ end
+ end
+ end
+ end;
+
+
+ -- print new fixed references
+ print('*** new study', Data.ReferencedStudySequence[0].ReferencedSOPInstanceUID);
+ print('*** new frameofref', Data.ReferencedFrameOfReferenceSequence[0].FrameOfReferenceUID)
+ print('*** new study', Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].ReferencedSOPInstanceUID)
+ print('*** new series', Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].SeriesInstanceUID)--]]
+
+ --for i=0, #Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].ContourImageSequence-1 do
+ -- print('*** new sop', i, Data.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].ContourImageSequence[i].ReferencedSOPInstanceUID)
+ --end;
+
+ --[[
+ for i=0, #Data.StructureSetROISequence-1 do
+ print('new frameofref', i, Data.StructureSetROISequence[i].ReferencedFrameOfReferenceUID)
+ end;
+
+ if Data.ROIContourSequence then
+ for i=0, #Data.ROIContourSequence-1 do
+ if Data.ROIContourSequence[i].ContourSequence then
+ for j=0, #Data.ROIContourSequence[i].ContourSequence-1 do
+ if Data.ROIContourSequence[i].ContourSequence[j].ContourImageSequence then
+ for k=0, #Data.ROIContourSequence[i].ContourSequence[j].ContourImageSequence-1 do
+ print('new sop', i, j, k, Data.ROIContourSequence[i].ContourSequence[j].ContourImageSequence[k].ReferencedSOPInstanceUID)
+ end
+ end
+ end
+ end
+ end
+ end;
+ --]]
+
+end;
+
+-- idem for RTPLAN
+if Data.Modality=='RTPLAN' then
+ print('*** Processing RTPLAN for patient ' .. Data.PatientName .. ' ' .. Data.PatientID);
+ print('*** Date of RTPLAN is ' .. Data.RTPlanDate);
+ print('*** study', Data.StudyInstanceUID);
+ print('*** series', Data.SeriesInstanceUID);
+ print('*** sop', Data.SOPInstanceUID)
+
+ print('*** r study', Data.ReferencedStudySequence[0].ReferencedSOPInstanceUID);
+ print('*** r rtstruct', Data.ReferencedStructureSetSequence[0].ReferencedSOPInstanceUID)
+ Data.ReferencedStudySequence[0].ReferencedSOPInstanceUID = getstudy(Data);
+ Data.ReferencedStructureSetSequence[0].ReferencedSOPInstanceUID = getrtstruct(Data)
+
+ print('*** new study', Data.ReferencedStudySequence[0].ReferencedSOPInstanceUID);
+ print('*** new rtstruct', Data.ReferencedStructureSetSequence[0].ReferencedSOPInstanceUID)
+end
+
+-- idem for RTDOSE
+if Data.Modality=='RTDOSE' then
+ print('*** Processing RTDOSE for patient ' .. Data.PatientName .. ' ' .. Data.PatientID);
+ print('*** Date of RTDOSE is ' .. Data.ImageDate);
+ print('*** study', Data.StudyInstanceUID);
+ print('*** series', Data.SeriesInstanceUID);
+ print('*** sop', Data.SOPInstanceUID)
+
+ print('*** r study', Data.ReferencedStudySequence[0].ReferencedSOPInstanceUID);
+ print('*** r rtplan', Data.ReferencedRTPlanSequence[0].ReferencedSOPInstanceUID)
+ Data.ReferencedStudySequence[0].ReferencedSOPInstanceUID = getstudy(Data);
+ Data.ReferencedRTPlanSequence[0].ReferencedSOPInstanceUID = getrtplan(Data);
+
+ print('*** new study', Data.ReferencedStudySequence[0].ReferencedSOPInstanceUID);
+ print('*** new rtplan', Data.ReferencedRTPlanSequence[0].ReferencedSOPInstanceUID)
+end
+
+-- idem for RTIMAGE
+if Data.Modality=='RTIMAGE' then
+ print('*** Processing RTIMAGE for patient ' .. Data.PatientName .. ' ' .. Data.PatientID);
+ print('*** Date of RTIMAGE is ' .. Data.ImageDate);
+ print('*** study', Data.StudyInstanceUID);
+ print('*** series', Data.SeriesInstanceUID);
+ print('*** sop', Data.SOPInstanceUID)
+
+ print('*** r study', Data.ReferencedStudySequence[0].ReferencedSOPInstanceUID);
+ print('*** r rtplan', Data.ReferencedRTPlanSequence[0].ReferencedSOPInstanceUID);
+ Data.ReferencedStudySequence[0].ReferencedSOPInstanceUID = getstudy(Data);
+ Data.ReferencedRTPlanSequence[0].ReferencedSOPInstanceUID = getrtplan(Data);
+
+ print('*** new study', Data.ReferencedStudySequence[0].ReferencedSOPInstanceUID);
+ print('*** new rtplan', Data.ReferencedRTPlanSequence[0].ReferencedSOPInstanceUID);
+end
+
+-- CT does not require processing, just print sops
+if Data.Modality=='CT' then
+ print('*** Processing CT for patient ' .. Data.PatientName .. ' ' .. Data.PatientID);
+ print('*** study', Data.StudyInstanceUID);
+ print('*** series', Data.SeriesInstanceUID);
+ print('*** sop', Data.SOPInstanceUID)
+ print('*** frame', Data.FrameOfReferenceUID)--]]
+end
diff --git a/lua/LuaXml.lua b/lua/LuaXml.lua
new file mode 100644
index 0000000..67b2997
--- /dev/null
+++ b/lua/LuaXml.lua
@@ -0,0 +1,119 @@
+require("LuaXML_lib")
+
+local base = _G
+local xml = xml
+module("xml")
+
+-- symbolic name for tag index, this allows accessing the tag by var[xml.TAG]
+TAG = 0
+
+-- sets or returns tag of a LuaXML object
+function tag(var,tag)
+ if base.type(var)~="table" then return end
+ if base.type(tag)=="nil" then
+ return var[TAG]
+ end
+ var[TAG] = tag
+end
+
+-- creates a new LuaXML object either by setting the metatable of an existing Lua table or by setting its tag
+function new(arg)
+ if base.type(arg)=="table" then
+ base.setmetatable(arg,{__index=xml, __tostring=xml.str})
+ return arg
+ end
+ local var={}
+ base.setmetatable(var,{__index=xml, __tostring=xml.str})
+ if base.type(arg)=="string" then var[TAG]=arg end
+ return var
+end
+
+-- appends a new subordinate LuaXML object to an existing one, optionally sets tag
+function append(var,tag)
+ if base.type(var)~="table" then return end
+ local newVar = new(tag)
+ var[#var+1] = newVar
+ return newVar
+end
+
+-- converts any Lua var into an XML string
+function str(var,indent,tagValue)
+ if base.type(var)=="nil" then return end
+ local indent = indent or 0
+ local indentStr=""
+ for i = 1,indent do indentStr=indentStr.." " end
+ local tableStr=""
+
+ if base.type(var)=="table" then
+ local tag = var[0] or tagValue or base.type(var)
+ local s = indentStr.."<"..tag
+ for k,v in base.pairs(var) do -- attributes
+ if base.type(k)=="string" then
+ if base.type(v)=="table" and k~="_M" then -- otherwise recursiveness imminent
+ tableStr = tableStr..str(v,indent+1,k)
+ else
+ s = s.." "..k.."=\""..encode(base.tostring(v)).."\""
+ end
+ end
+ end
+ if #var==0 and #tableStr==0 then
+ s = s.." />\n"
+ elseif #var==1 and base.type(var[1])~="table" and #tableStr==0 then -- single element
+ s = s..">"..encode(base.tostring(var[1])).."</"..tag..">\n"
+ else
+ s = s..">\n"
+ for k,v in base.ipairs(var) do -- elements
+ if base.type(v)=="string" then
+ s = s..indentStr.." "..encode(v).." \n"
+ else
+ s = s..str(v,indent+1)
+ end
+ end
+ s=s..tableStr..indentStr.."</"..tag..">\n"
+ end
+ return s
+ else
+ local tag = base.type(var)
+ return indentStr.."<"..tag.."> "..encode(base.tostring(var)).." </"..tag..">\n"
+ end
+end
+
+
+-- saves a Lua var as xml file
+function save(var,filename)
+ if not var then return end
+ if not filename or #filename==0 then return end
+ local file = base.io.open(filename,"w")
+ file:write("<?xml version=\"1.0\"?>\n<!-- file \"",filename, "\", generated by LuaXML -->\n\n")
+ file:write(str(var))
+ base.io.close(file)
+end
+
+
+-- recursively parses a Lua table for a substatement fitting to the provided tag and attribute
+function find(var, tag, attributeKey,attributeValue)
+ -- check input:
+ if base.type(var)~="table" then return end
+ if base.type(tag)=="string" and #tag==0 then tag=nil end
+ if base.type(attributeKey)~="string" or #attributeKey==0 then attributeKey=nil end
+ if base.type(attributeValue)=="string" and #attributeValue==0 then attributeValue=nil end
+ -- compare this table:
+ if tag~=nil then
+ if var[0]==tag and ( attributeValue == nil or var[attributeKey]==attributeValue ) then
+ base.setmetatable(var,{__index=xml, __tostring=xml.str})
+ return var
+ end
+ else
+ if attributeValue == nil or var[attributeKey]==attributeValue then
+ base.setmetatable(var,{__index=xml, __tostring=xml.str})
+ return var
+ end
+ end
+ -- recursively parse subtags:
+ for k,v in base.ipairs(var) do
+ if base.type(v)=="table" then
+ local ret = find(v, tag, attributeKey,attributeValue)
+ if ret ~= nil then return ret end
+ end
+ end
+end
diff --git a/lua/Plan2AlingRT.lua b/lua/Plan2AlingRT.lua
new file mode 100644
index 0000000..2a69509
--- /dev/null
+++ b/lua/Plan2AlingRT.lua
@@ -0,0 +1,34 @@
+--[[
+Date Name Description
+20120330 mvh + cp Created script for forwarding RTPLAN and RTSTRUCT to AlignRT PC
+]]--
+
+print('checking for alignRT')
+if Data.Modality == "RTPLAN" and string.find(Data.RTPlanDescription, ' A1')~=NIL then
+ -- print (Data.ReferencedStructureSetSequence[0].ReferencedSOPInstanceUID)
+
+ -- Read StructureSet
+ StructureSet = newdicomobject()
+ StructureSet:Read(Data.PatientID..':'..Data.ReferencedStructureSetSequence[0].ReferencedSOPInstanceUID);
+
+ -- Query SeriesDescription
+ local SeriesUID = (StructureSet.ReferencedFrameOfReferenceSequence[0].RTReferencedStudySequence[0].RTReferencedSeriesSequence[0].SeriesInstanceUID)
+ local SeriesDesc = dbquery('DICOMSeries', 'SeriesDesc', 'SeriesInst = "'..SeriesUID..'"')[1][1]
+ print (SeriesDesc)
+
+ s = string.find(SeriesDesc, "mamBreath")
+ if s~=NIL then
+ -- Send RTSTRUCT
+ b=newdicomobject();
+ b.PatientID = Data.PatientID;
+ b.SOPInstanceUID = StructureSet.SOPInstanceUID
+ b.QueryRetrieveLevel = 'IMAGE'; dicommove('SDA05365','SGALINGALE' , b);
+
+ -- Send RTPLAN
+ b=newdicomobject();
+ b.PatientID = Data.PatientID;
+ b.SOPInstanceUID = Data.SOPInstanceUID
+ b.QueryRetrieveLevel = 'IMAGE'; dicommove('SDA05365','SGALINGALE' , b);
+ print('RTPLAN and RTSTUCT is sent to AlignRTA1')
+ end;
+end
diff --git a/lua/anonymize_script.lua b/lua/anonymize_script.lua
new file mode 100644
index 0000000..4c318cc
--- /dev/null
+++ b/lua/anonymize_script.lua
@@ -0,0 +1,157 @@
+-- =============================================================================
+-- Anonymize DICOM tags to protect Private Health Information (HIPAA)
+-- Based on: DicomAnonymize.cq (c) Bart Hoekstra UMCG
+-- Author: Marcel van Herk
+-- Reference: PS 3.15-2009 Table E.1-1
+-- Modification
+-- 20120827 mvh Use script() instead of os.execute() to avoid blinking window
+-- 20130127 mvh for 1.4.17beta: Match updated dictionary; added MaintainAge, MaintainSex,
+-- Reversible options; use lua crc calls
+-- 20130211 mvh Make sure PatientID used as filename has no invalid characters
+-- 20130522 mvh Cleanup for release; fixed when birthdate empty
+-- 20130718 mvh Set logroot not to c:\DicomAnonymized but to DicomAnonymized_Log
+-- 20130813 mvh Command line overrules generated patientid and patientname
+-- =============================================================================
+
+local scriptversion = "1.4; date 20130813"
+
+---------------------------------- configuration -----------------------------
+-- entries that show up in log but are NOT modified (except implicitly the UIDs)
+local TagsToPrint = {
+"FrameOfReferenceUID", "StudyInstanceUID", "SeriesInstanceUID", "SOPInstanceUID",
+"Modality", "BodyPartExamined", "Manufacturer", "ManufacturerModelName",
+"StudyDate", "StudyTime", "SeriesNumber", "ImageID"}
+
+-- entries that are emptied
+local TagsToEmpty = {
+"AccessionNumber", "InstitutionName", "ReferringPhysicianName", "PerformingPhysicianName", "StudyID"}
+
+-- entries that are removed
+local TagsToRemove = {
+"InstanceCreatorUID", "InstitutionAddress", "ReferringPhysicianAddress", "ReferringPhysicianTelephoneNumbers",
+"StationName", "StudyDescription", --[["SeriesDescription",]] "InstitutionalDepartmentName",
+"PhysiciansOfRecord", "NameOfPhysiciansReadingStudy", "OperatorsName", "AdmittingDiagnosesDescription",
+"DerivationDescription", "OtherPatientIDs", "OtherPatientNames", "PatientAge",
+"PatientSize", "PatientWeight", "MedicalRecordLocator", "EthnicGroup",
+"Occupation", "AdditionalPatientHistory", "DeviceSerialNumber", "ProtocolName",
+"ImageComments", "RequestAttributesSequence", "ContentSequence", "StorageMediaFileSetUID",
+"PatientInsurancePlanCodeSequence", "PatientBirthName", "PatientAddress", "InsurancePlanIdentification",
+"PatientMotherBirthName", "MilitaryRank", "BranchOfService", "RegionOfResidence",
+"PatientTelephoneNumbers", "PatientComments", "StudyComments", "ScheduledPerformingPhysicianName",
+"PerformingPhysicianIdentificationSequence" }
+
+local MaintainAge = false
+local MaintainSex = false
+local reversible = true
+local logroot = "DicomAnonymized_Log\\"
+
+---------------------------------- end configuration -----------------------------
+
+-- entries that show up in log and that are individually modified
+local TagsToModify = {
+"PatientID", "PatientName", "PatientBirthDate", "PatientSex"}
+
+local function CRC32(val)
+ return crc(tostring(val))
+end;
+
+-- remove characters that are not allowed in a filename
+local pid = string.gsub(Data.PatientID, '[\\/:*?"<>|]', '_')
+
+-- Log file handling (trailing backslash required for mkdir)
+local logdir = logroot..pid.."\\";
+--
+local logfile = pid..'_'..Data.StudyDate..'_'..Data.Modality..'_'..Data.SOPInstanceUID..'.log'
+script('mkdir '..logdir);
+
+local f = io.open(logdir .. logfile, "wt");
+f:write("DicomAnonymize.lua script version: ", scriptversion, "\n")
+f:write("Logfile name : ", logfile, "\n")
+f:write("Logfile created : ", os.date(), "\n")
+
+-- Check dictionary
+for key2, val2 in ipairs({TagsToModify, TagsToPrint, TagsToEmpty, TagsToRemove}) do
+ for key, val in ipairs(val2) do
+ if dictionary(val)==nil and string.sub(val,1,1)~='0' then
+ f:write("*** Error: '", val, "' not in dictionary\n")
+ end
+ end
+end
+
+-- Log data in original object
+f:write("===== ORIGINAL DICOM DATA =====\n");
+for key2, val2 in ipairs({TagsToModify, TagsToPrint, TagsToEmpty, TagsToRemove}) do
+ for key, val in ipairs(val2) do
+ f:write(val, ': ', tostring(Data[val]), "\n")
+ end
+end
+
+-- modify and log modified object
+f:write("===== MODIFIED DICOM DATA =====\n");
+script('newuids');
+f:write("Generated new UIDs\n")
+
+if Data.PatientBirthDate==nil or Data.PatientBirthDate=='' then
+ Data.PatientBirthDate='00000000'
+end
+
+-- the changes in patient ID etc are hardcoded
+local pre = CRC32(Data.PatientID)..'.'..CRC32(Data.PatientBirthDate);
+local pne = 'PAT'..CRC32(Data.PatientID)
+if version and command_line and command_line~='' then pre=command_line end
+if version and command_line and command_line~='' then pne=command_line end
+
+if Data.PatientName~='' then
+ if reversible==true then
+ Data.PatientName = changeuid(Data.PatientName, pne)
+ else
+ Data.PatientName = pne;
+ end
+ f:write('Anonymized PatientName to: ', Data.PatientName, "\n");
+end
+if Data.PatientID~='' then
+ if reversible==true then
+ Data.PatientID = changeuid(Data.PatientID, pre)
+ else
+ Data.PatientID = pre;
+ end
+ f:write('Anonymized PatientID to: ', Data.PatientID, "\n");
+end
+if Data.PatientBirthDate~='' then
+ local org = Data.PatientBirthDate;
+ if MaintainAge==true then
+ Data.PatientBirthDate = string.sub(org, 1, 4)..'0101'
+ else
+ Data.PatientBirthDate = '';
+ end
+ if reversible==true then
+ changeuid(pre..'.bd.'..org, pre..'.bd.'..Data.PatientBirthDate)
+ end
+ f:write('Changed patient birthdate to: ', tostring(Data.PatientBirthDate), "\n");
+end
+if (MaintainSex==false) and (Data.PatientSex~='') then
+ local org = Data.PatientSex;
+ Data.PatientSex = '';
+ f:write('Made patient sex empty: ', tostring(Data.PatientSex), "\n");
+ if reversible==true then
+ changeuid(pre..'.ps.'..org, pre..'.ps.'..Data.PatientSex)
+ end
+end
+
+-- log modified UIDs
+local i;
+for i=1, 4 do
+ f:write(TagsToPrint[i], ': ', tostring(Data[TagsToPrint[i]]), "\n");
+end
+-- empty tags
+for key, val in ipairs(TagsToEmpty) do
+ Data[val]='';
+ f:write('Made ', val, ' empty: ', tostring(Data[val]), "\n");
+end
+-- remove tags
+for key, val in ipairs(TagsToRemove) do
+ Data[val]=nil;
+ f:write('Removed ', val, ': ', tostring(Data[val]), "\n");
+end
+
+f:close();
diff --git a/lua/changewedge.lua b/lua/changewedge.lua
new file mode 100644
index 0000000..b8d1474
--- /dev/null
+++ b/lua/changewedge.lua
@@ -0,0 +1,23 @@
+-- This script modifies 'STANDARD' wedges to 'MOTORIZED' in RTPLAN
+--[[ To test; r-click evaluate in console after project-run:
+readdicom('c:\\data\\rtplan.dcm')
+Data.Dump('c:\\data\\rtplan_in.txt')
+dofile('changewedge.lua')
+Data.Dump('c:\\data\\rtplan_out.txt')
+]]
+
+if Data.Modality=='RTPPLAN' then
+ print('Processing RTPLAN for patient ' .. Data.PatientName .. ' ' .. Data.PatientID);
+ print('Date of RTPLAN is ' .. Data.RTPlanDate);
+
+ local i
+ for i=0, #Data.BeamSequence-1 do
+ if Data.BeamSequence[i].WedgeSequence then
+ print('Wedge type in beam ' .. i .. ' is ' .. Data.BeamSequence[i].WedgeSequence[0].WedgeType);
+ if Data.BeamSequence[i].WedgeSequence[0].WedgeType == 'STANDARD' then
+ Data.BeamSequence[i].WedgeSequence[0].WedgeType = 'MOTORIZED'
+ end
+ print('Modified wedge type in beam ' .. i .. ' to ' .. Data.BeamSequence[i].WedgeSequence[0].WedgeType)
+ end
+ end
+end
diff --git a/lua/checkbsn.lua b/lua/checkbsn.lua
new file mode 100644
index 0000000..c5929da
--- /dev/null
+++ b/lua/checkbsn.lua
@@ -0,0 +1,80 @@
+-- check where Dutch BSN is used as PatientID in CareStream,
+-- mvh 20120424
+-- mvh+mb+cp 201200713: some more prints; mask virtual
+-- servers from RT systems
+
+pacs = 'avlpacsFIR';
+
+--initiate query
+b=newdicomobject();
+b.PatientID = '';
+b.StudyInstanceUID='';
+b.StudyDate='';
+b.OtherPatientIDsSequence={};
+b.OtherPatientIDsSequence[0].PatientID='';
+b.StudyDate='20120101-20120712';
+
+print('****** quering', pacs, 'date=', b.StudyDate);
+if pacs~='avlpacsFIR' then
+ b['9999,0802']=0; -- set virtualserver mask to 0
+end;
+b.QueryLevel='STUDY';
+
+--do the study query
+a=dicomquery(pacs, 'STUDY', b);
+print('****** query done, records = ', #a);
+
+function q(s, index)
+ return string.byte(s, index)-string.byte('0')
+end;
+
+--for each study
+for i=0,#a-1 do
+ s = a[i].PatientID;
+ if (#s==9) then
+ check = q(s,1)*9+q(s,2)*8+q(s,3)*7+q(s,4)*6+q(s,5)*5+q(s,6)*4+q(s,7)*3+q(s,8)*2-q(s,9)*1;
+ if math.modf(check/11)==check/11 then
+ print('Processing study', a[i].PatientID, a[i].StudyInstanceUID, a[i].StudyDate);
+
+ -- initiate an image query
+ c=newdicomobject();
+ c.PatientID = a[i].PatientID;
+ c.StudyInstanceUID = a[i].StudyInstanceUID;
+ c.SOPInstanceUID = "";
+ if pacs~='avlpacsFIR' then
+ c['9999,0802']=0; -- set virtualserver mask to 0
+ end;
+ d=dicomquery(pacs, 'IMAGE', c);
+
+ -- initiate a move of the first image
+ print('Processing first image', a[i].PatientID, SOPInstanceUID, 'of images: ', #d);
+ SOPInstanceUID = d[0].SOPInstanceUID;
+ d[0].QueryRetrieveLevel = 'IMAGE';
+ if pacs~='RTDICOM01' then
+ dicommove(pacs, 'RTDICOM01', d[0]);
+ end;
+
+
+ -- test that the move was succesful
+--[[ c=newdicomobject();
+ c.PatientID = a[i].PatientID;
+ c.StudyInstanceUID = a[i].StudyInstanceUID;
+ c.SOPInstanceUID = SOPInstanceUID;
+]]
+ d=dbquery("DICOMImages", "SOPInstanc", "ImagePat='"..a[i].PatientID.."' and SOPInstanc='"..SOPInstanceUID.."'");
+ if #d==0 then
+ print('***** error', a[i].PatientID, a[i].StudyInstanceUID, SOPInstanceUID, a[i].StudyDate);
+ else
+ -- read the image into memory and log the mapping
+ e=newdicomobject();
+ e:Read(a[i].PatientID..':'..SOPInstanceUID);
+ if e.OtherPatientIDsSequence~=nil then
+ print('***** got', a[i].PatientID, e.OtherPatientIDsSequence[0].PatientID, a[i].StudyDate)
+ else
+ print('***** no-id', a[i].PatientID, a[i].StudyInstanceUID, SOPInstanceUID, a[i].StudyDate);
+ end;
+ end;
+ end;
+ end
+end;
+print('***** done');
diff --git a/lua/compressiontest.lua b/lua/compressiontest.lua
new file mode 100644
index 0000000..2c1a7c6
--- /dev/null
+++ b/lua/compressiontest.lua
@@ -0,0 +1,142 @@
+-- This program tests DICOM communication with any compression on sending and/or receiving server
+-- It times c-store over the local network and read from file (still in cache) and decompression
+-- Author: Marcel van Herk, 20130818
+
+require('niftyutil')
+
+function filesize(f)
+ local h = io.open(f)
+ if h==nil then
+ return 0
+ else
+ local s = h:seek('end', 0)
+ h:close()
+ return s
+ end
+end
+
+receivecompression = {
+ --'un',
+ 'j1', 'j2', 'j3', 'j4', 'j450', 'j5', 'j6',
+ --'jk', 'jl', 'jl25', 'jl10', 'jl05',
+ --'n2', 'n3', 'n4', 'k4'
+ }
+
+sendcompression = {
+ 'un'
+ }
+
+testimage = '0009703828:1.3.46.670589.5.2.10.2156913941.892665340.475317'
+--testimage = 'c:\\t.dcm'
+--testimage = 'head_mri.dcm'
+
+count = 100
+
+-- cleanup possible leftovers
+if fileexists('compressiontest.txt') then
+ os.remove('compressiontest.txt')
+end
+os.execute('del /q/s testserver\\*.*')
+os.execute('rmdir /q/s testserver')
+
+-- add testserver to ACRNEMA.MAP in memory (last item, be aware of conflicting wildcard entries)
+servercommand('put_amap:99,testserver,127.0.0.1,4433')
+
+-- start log file
+g = io.open('compressiontest.txt', 'wt')
+g:write('servercomp', '\t', 'clientcomp', '\t', 'write', '\t', 'read', '\t', 'lossless', '\t', 'ratio', '\n')
+
+for k,serversidecompression in ipairs(receivecompression) do
+ for k2,clientsidecompression in ipairs(sendcompression) do
+ -- create minimal server (4 files and a data folder)
+ script('mkdir testserver')
+ script('mkdir testserver\\data')
+ filecopy('acrnema.map', 'testserver\\acrnema.map')
+ filecopy('dgate.dic', 'testserver\\dgate.dic')
+ filecopy('dicom.sql', 'testserver\\dicom.sql')
+ syntax = '4'
+ if string.sub(serversidecompression, 1, 1)=='n' then syntax=3 end
+ f = io.open('testserver\\dicom.ini', 'wt')
+ f:write([[
+[sscscp]
+MicroPACS = sscscp
+TCPPort = 4433
+SqLite = 1
+SQLServer = testserver\testserver.db3
+MAGDevice0 = testserver\Data\
+UseBuiltInJPEG = 1
+TruncateFieldNames = 10
+FileNameSyntax = ]]..syntax..[[
+
+incomingcompression = ]]..serversidecompression..[[
+]])
+ f:close()
+
+ -- create serverside test program to uncompress all images
+ f = io.open('testserver\\test.lua', 'wt')
+ f:write([[
+d = DicomObject:new()
+for line in io.lines('testserver\\files.txt') do
+ d:Read(line)
+ d:Script('compression un')
+ print(line)
+end
+ ]])
+ f:close()
+
+ -- initialize the test server's database and start it
+ os.execute('dgate.exe -wtestserver -v -r')
+ servercommand("luastart:os.execute('dgate -wtestserver -v')")
+ sleep(100)
+
+ -- get a test image and uncompress it
+ d = DicomObject:new()
+ d:Read(testimage)
+ d:Script('compression un')
+ d:Write('testserver\\testimage.dcm')
+ dsize = filesize('testserver\\testimage.dcm')
+
+ -- send it count times to test server
+ print('compression', serversidecompression, clientsidecompression)
+ t = os.clock()
+ for i=0, count-1 do
+ d.SOPInstanceUID = genuid()
+ if (i%10)==0 then d.SeriesInstanceUID = genuid() end
+ if (i%100)==0 then d.StudyInstanceUID = genuid() end
+ d:Script('forward compressed as '.. clientsidecompression.. ' to testserver channel *')
+ end
+ sending = os.clock()-t
+
+ -- list filenames of all files stored in test server
+ os.execute('dgate.exe -wtestserver "--imagelister:local|||%s|testserver\\files.txt"')
+
+ -- do a test read with uncompress in the test server
+ t = os.clock()
+ os.execute('dgate.exe -wtestserver "--lua:dofile([[testserver/test.lua]])"')
+ readtime = os.clock()-t
+
+ -- measure the compression on the first file
+ e = DicomObject:new()
+ for line in io.lines('testserver\\files.txt') do
+ e:Read(line)
+ ratio = filesize(line) / dsize
+ e:Script('compression un')
+ break
+ end
+
+ -- check if the compression was lossless
+ d1 = d:GetImage(0)
+ e1 = e:GetImage(0)
+ lossless = d1==e1
+
+ -- log the results
+ g:write(serversidecompression, '\t', clientsidecompression, '\t', sending/count, '\t', readtime/count, '\t', tostring(lossless), '\t', ratio, '\n')
+
+ -- remove the test server
+ os.execute('dgate.exe -wtestserver --quit:')
+ sleep(100)
+ os.execute('del /q/s testserver\\*.*')
+ os.execute('rmdir /q/s testserver')
+ end
+end
+g:close()
diff --git a/lua/deanonymize_script.lua b/lua/deanonymize_script.lua
new file mode 100644
index 0000000..1499d43
--- /dev/null
+++ b/lua/deanonymize_script.lua
@@ -0,0 +1,73 @@
+-- =============================================================================
+-- DeAnonymize DICOM tags
+-- Author: Marcel van Herk
+-- 20130125 mvh Created
+-- 20130211 mvh Take out invalid characters for filenames
+-- 20130522 mvh Cleanup for release
+-- 20130718 mvh Moved log folder
+-- 20130802 mvh Detect if patientID cannot be deanonymized
+-- =============================================================================
+
+--[[ To test; r-click evaluate in console after project-run:
+readdicom('0009703828:1.3.46.670589.5.2.10.2156913941.892665340.475317')
+Data.Dump('c:\\data\\image_in.txt')
+dofile('lua/anonymize_script.lua')
+Data.Dump('c:\\data\\image_anonymized.txt')
+dofile('lua/deanonymize_script.lua')
+Data.Dump('c:\\data\\image_restored.txt')
+]]
+
+local scriptversion = "1.1; date 20130802"
+
+local pre, pid = Data.PatientID
+
+if Data.PatientID~='' then
+ pid = changeuidback(pre)
+ if pid==nil then
+ print('** patient '..pre..' was not anonymized on this system **')
+ return
+ end
+end
+
+-- remove characters that are not allowed in a filename
+local pid2 = string.gsub(pid, '[\\/:*?"<>|]', '_')
+
+-- Log file handling (trailing backslash required for mkdir)
+local logdir = "DicomAnonymized_Log\\"..pid2.."\\";
+local logfile = pid2..'_'..Data.StudyDate..'_'..Data.Modality..'_'..Data.SOPInstanceUID..'.deanonymize.log'
+script('mkdir '..logdir);
+
+f = io.open(logdir .. logfile, "wt");
+f:write("DicomDeAnonymize.lua script version: ", scriptversion, "\n")
+f:write("Logfile name : ", logfile, "\n")
+f:write("Logfile created : ", os.date(), "\n")
+
+-- modify and log modified object
+f:write("===== MODIFIED DICOM DATA =====\n");
+script('olduids');
+f:write("Restoring UIDs\n")
+
+if Data.PatientID~='' then
+ Data.PatientID = changeuidback(pre)
+ f:write('Restored patient ID to: ', Data.PatientID, '\n');
+end
+
+if true then
+ local s= changeuidback(pre..'.bd.'..Data.PatientBirthDate)
+ Data.PatientBirthDate = string.sub(s, string.find(s, '%.', -10)+1);
+ f:write('Restored patient birthdate to: ', tostring(Data.PatientBirthDate), "\n");
+end
+
+if Data.PatientName~='' then
+ local s = changeuidback(Data.PatientName)
+ Data.PatientName = s;
+ f:write('DeAnonymized PatientName to: ', Data.PatientName, "\n")
+end
+
+if (Data.PatientSex=='') then
+ local s = changeuidback(pre .. '.ps.' .. Data.PatientSex)
+ Data.PatientSex = string.sub(s, string.find(s, '%.', -3)+1);
+ f:write('Restored patient sex to: ', tostring(Data.PatientSex), "\n");
+end
+
+f:close();
diff --git a/lua/deletebody.lua b/lua/deletebody.lua
new file mode 100644
index 0000000..e5e8129
--- /dev/null
+++ b/lua/deletebody.lua
@@ -0,0 +1,30 @@
+-- This script delete the 'BODY' contour in RTSTRUCT
+--[[ To test; r-click evaluate in console after project-run:
+readdicom('c:\\data\\rtstruct.dcm')
+Data.Dump('c:\\data\\rtstruct_in.txt')
+dofile('deletebody.lua')
+Data.Dump('c:\\data\\rtstruct_out.txt')
+]]
+
+local roinumber, index, i
+for i=0, #Data.StructureSetROISequence-1 do
+ if Data.StructureSetROISequence[i].ROIName=='BODY' then
+ roinumber = Data.StructureSetROISequence[i].ROINumber
+ index = i
+ end
+end
+Data.StructureSetROISequence[index]=nil
+
+for i=0, #Data.ROIContourSequence-1 do
+ if Data.ROIContourSequence[i].ReferencedROINumber==roinumber then
+ index = i
+ end
+end
+Data.ROIContourSequence[index]=nil
+
+for i=0, #Data.RTROIObservationsSequence-1 do
+ if Data.RTROIObservationsSequence[i].ReferencedROINumber==roinumber then
+ index = i
+ end
+end
+Data.RTROIObservationsSequence[index]=nil
diff --git a/lua/deletebydate.lua b/lua/deletebydate.lua
new file mode 100644
index 0000000..0dc3209
--- /dev/null
+++ b/lua/deletebydate.lua
@@ -0,0 +1,23 @@
+x = DicomObject:new()
+x.PatientName = ''
+x.PatientID = ''
+x.StudyDate = '20030101-20050322' -- date range match
+x.PatientBirthDate = '19000101-19920322'
+x.QueryRetrieveLevel = 'STUDY'
+x.StudyInstanceUID = '' -- you want these returned for the loop
+x.ModalitiesInStudy = ''
+
+y = dicomquery('CONQUESTSRV1', 'STUDY', x)
+-- now y is an array with all requested items
+
+print('fixin to delete', #y, 'Studies')
+for i=0, #y-1 do
+ print('testing', y[i].PatientID, y[i].PatientName, y[i].StudyDate, y[i].ModalitiesInStudy)
+ if string.find(y[i].ModalitiesInStudy, 'MG')==nil then
+ z = DicomObject:new()
+ z.PatientID = y[i].PatientID
+ z.StudyInstanceUID = y[i].StudyInstanceUID
+ print('deleting', y[i].PatientID, y[i].PatientName, y[i].StudyDate, y[i].ModalitiesInStudy)
+ --dicomdelete(z)
+ end
+end
diff --git a/lua/distxfm.lua b/lua/distxfm.lua
new file mode 100644
index 0000000..1209fef
--- /dev/null
+++ b/lua/distxfm.lua
@@ -0,0 +1,52 @@
+--[[ Sample of image processing; computes city block
+ distance transform ]]
+
+--[[ To test; r-click evaluate in console after project-run:
+d=DicomObject:new();
+d:Read('c:\\1.dcm')
+local t=os.clock()
+dofile('distxfm.lua')
+print(os.clock()-t)
+d:Write('c:\\ta.dcm')
+os.execute('"C:\\Program Files (x86)\\IrfanView\\i_view32.exe" c:\\ta.dcm')
+]]
+
+local rows = d.Rows
+local cols = d.Columns
+local a, i, j
+
+for i=0,rows-1 do
+ a=d:GetRow(i)
+ for j=0,cols-1 do
+ if a[j]>1700 then
+ a[j]=0
+ else
+ a[j]=1000
+ end
+ end
+ d:SetRow(i,0,a)
+end
+
+for i=0,rows-1 do
+ a=d:GetRow(i)
+ for j=1,cols-1 do
+ a[j]=math.min(a[j], a[j-1]+1)
+ end
+ for j=1,cols-1 do
+ k = cols-1-j
+ a[k]=math.min(a[k], a[k+1]+1)
+ end
+ d:SetRow(i,0,a)
+end
+
+for i=0,cols-1 do
+ a=d:GetColumn(i)
+ for j=1,rows-1 do
+ a[j]=math.min(a[j], a[j-1]+1)
+ end;
+ for j=1,rows-1 do
+ k = rows-1-j
+ a[k]=math.min(a[k], a[k+1]+1)
+ end
+ d:SetColumn(i,0,a)
+end
diff --git a/lua/filterquery.lua b/lua/filterquery.lua
new file mode 100644
index 0000000..b28f2a1
--- /dev/null
+++ b/lua/filterquery.lua
@@ -0,0 +1,2 @@
+[lua]
+QueryConverter0 = if ((Data.PatientID=="*") or (Data.PatientID==nil)) and ((Data.StudyDate=="*") or (Data.StudyDate==nil)) and ((Data.PatientName=="*") or (Data.PatientName==nil)) then script('destroy') end
diff --git a/lua/importconverter.lua b/lua/importconverter.lua
new file mode 100644
index 0000000..fa3e71a
--- /dev/null
+++ b/lua/importconverter.lua
@@ -0,0 +1,7 @@
+if Data.ProtocolName == "RTP Retrospective Gating" then
+ str = Data.SeriesDescription
+ str = str:match('[^/]*' )
+ Data.SeriesDescription = str
+ print (Data.SeriesDescription)
+ print (str)
+end
\ No newline at end of file
diff --git a/lua/livecoding.lua b/lua/livecoding.lua
new file mode 100644
index 0000000..e87ae68
--- /dev/null
+++ b/lua/livecoding.lua
@@ -0,0 +1,10 @@
+a=DicomObject:new()
+a.QueryRetrieveLevel='STUDY'
+a.StudyInstanceUID=''
+a.StudyDate='20090101-20130404'
+b=dicomquery('CONQUESTSRV1', 'STUDY', a)
+f=io.open('file.txt', 'wt')
+for i=0, #b-1 do
+ f:write(b[i].StudyInstanceUID .. '\n')
+end
+f:close()
\ No newline at end of file
diff --git a/lua/makefilename.lua b/lua/makefilename.lua
new file mode 100644
index 0000000..315167e
--- /dev/null
+++ b/lua/makefilename.lua
@@ -0,0 +1,5 @@
+-- Use with FileNameSyntax=lua:dofile('makefilename.lua')
+
+local n = Data.PatientName
+-- process n here
+return n .. Data.PatientSex .. Data.PatientAge .. Data.PatientBirthDate .. Data.SOPInstanceUID .. '.dcm'
diff --git a/lua/mobdebug.lua b/lua/mobdebug.lua
new file mode 100644
index 0000000..0b7b54a
--- /dev/null
+++ b/lua/mobdebug.lua
@@ -0,0 +1,1422 @@
+--
+-- MobDebug 0.5362
+-- Copyright 2011-13 Paul Kulchenko
+-- Based on RemDebug 1.0 Copyright Kepler Project 2005
+--
+
+local mobdebug = {
+ _NAME = "mobdebug",
+ _VERSION = 0.5362,
+ _COPYRIGHT = "Paul Kulchenko",
+ _DESCRIPTION = "Mobile Remote Debugger for the Lua programming language",
+ port = os and os.getenv and os.getenv("MOBDEBUG_PORT") or 8172,
+ checkcount = 200,
+ yieldtimeout = 0.02,
+}
+
+local coroutine = coroutine
+local error = error
+local getfenv = getfenv
+local setfenv = setfenv
+local loadstring = loadstring or load -- "load" replaced "loadstring" in Lua 5.2
+local io = io
+local os = os
+local pairs = pairs
+local require = require
+local setmetatable = setmetatable
+local string = string
+local tonumber = tonumber
+local unpack = table.unpack or unpack
+
+-- if strict.lua is used, then need to avoid referencing some global
+-- variables, as they can be undefined;
+-- use rawget to to avoid complaints from strict.lua at run-time.
+-- it's safe to do the initialization here as all these variables
+-- should get defined values (of any) before the debugging starts.
+-- there is also global 'wx' variable, which is checked as part of
+-- the debug loop as 'wx' can be loaded at any time during debugging.
+local genv = _G or _ENV
+local jit = rawget(genv, "jit")
+local MOAICoroutine = rawget(genv, "MOAICoroutine")
+
+if not setfenv then -- Lua 5.2
+ -- based on http://lua-users.org/lists/lua-l/2010-06/msg00314.html
+ -- this assumes f is a function
+ local function findenv(f)
+ local level = 1
+ repeat
+ local name, value = debug.getupvalue(f, level)
+ if name == '_ENV' then return level, value end
+ level = level + 1
+ until name == nil
+ return nil end
+ getfenv = function (f) return(select(2, findenv(f)) or _G) end
+ setfenv = function (f, t)
+ local level = findenv(f)
+ if level then debug.setupvalue(f, level, t) end
+ return f end
+end
+
+-- check for OS and convert file names to lower case on windows
+-- (its file system is case insensitive, but case preserving), as setting a
+-- breakpoint on x:\Foo.lua will not work if the file was loaded as X:\foo.lua.
+-- OSX and Windows behave the same way (case insensitive, but case preserving)
+local iscasepreserving = os and os.getenv and (os.getenv('WINDIR')
+ or (os.getenv('OS') or ''):match('[Ww]indows')
+ or os.getenv('DYLD_LIBRARY_PATH'))
+ or not io.open("/proc")
+
+-- turn jit off based on Mike Pall's comment in this discussion:
+-- http://www.freelists.org/post/luajit/Debug-hooks-and-JIT,2
+-- "You need to turn it off at the start if you plan to receive
+-- reliable hook calls at any later point in time."
+if jit and jit.off then jit.off() end
+
+local socket = require "socket"
+local debug = require "debug"
+local coro_debugger
+local coro_debugee
+local coroutines = {}; setmetatable(coroutines, {__mode = "k"}) -- "weak" keys
+local events = { BREAK = 1, WATCH = 2, RESTART = 3, STACK = 4 }
+local breakpoints = {}
+local watches = {}
+local lastsource
+local lastfile
+local watchescnt = 0
+local abort -- default value is nil; this is used in start/loop distinction
+local seen_hook = false
+local checkcount = 0
+local step_into = false
+local step_over = false
+local step_level = 0
+local stack_level = 0
+local server
+local buf
+local outputs = {}
+local iobase = {print = print}
+local basedir = ""
+local deferror = "execution aborted at default debugee"
+local debugee = function ()
+ local a = 1
+ for _ = 1, 10 do a = a + 1 end
+ error(deferror)
+end
+local function q(s) return s:gsub('([%(%)%.%%%+%-%*%?%[%^%$%]])','%%%1') end
+
+local serpent = (function() ---- include Serpent module for serialization
+local n, v = "serpent", 0.24 -- (C) 2012-13 Paul Kulchenko; MIT License
+local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
+local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
+local badtype = {thread = true, userdata = true, cdata = true}
+local keyword, globals, G = {}, {}, (_G or _ENV)
+for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
+ 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
+ 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
+for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
+for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
+ for k,v in pairs(G[g]) do globals[v] = g..'.'..k end end
+
+local function s(t, opts)
+ local name, indent, fatal = opts.name, opts.indent, opts.fatal
+ local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
+ local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
+ local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
+ local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
+ local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
+ -- tostring(val) is needed because __tostring may return a non-string value
+ function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return syms[s] end)) end
+ local function safestr(s) return type(s) == "number" and (huge and snum[tostring(s)] or s)
+ or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
+ or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
+ local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
+ local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
+ and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
+ local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
+ local n = name == nil and '' or name
+ local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
+ local safe = plain and n or '['..safestr(n)..']'
+ return (path or '')..(plain and path and '.' or '')..safe, safe end
+ local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
+ local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
+ local function padnum(d) return ("%0"..maxn.."d"):format(d) end
+ table.sort(k, function(a,b)
+ -- sort numeric keys first: k[key] is non-nil for numeric keys
+ return (k[a] and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
+ < (k[b] and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
+ local function val2str(t, name, indent, insref, path, plainindex, level)
+ local ttype, level, mt = type(t), (level or 0), getmetatable(t)
+ local spath, sname = safename(path, name)
+ local tag = plainindex and
+ ((type(name) == "number") and '' or name..space..'='..space) or
+ (name ~= nil and sname..space..'='..space or '')
+ if seen[t] then -- already seen this element
+ table.insert(sref, spath..space..'='..space..seen[t])
+ return tag..'nil'..comment('ref', level) end
+ if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
+ seen[t] = insref or spath
+ if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
+ ttype = type(t) end -- new value falls through to be serialized
+ if ttype == "table" then
+ if level >= maxl then return tag..'{}'..comment('max', level) end
+ seen[t] = insref or spath
+ if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
+ local maxn, o, out = #t, {}, {}
+ for key = 1, maxn do table.insert(o, key) end
+ for key in pairs(t) do if not o[key] or key > maxn then table.insert(o, key) end end
+ if opts.sortkeys then alphanumsort(o, t, opts.sortkeys) end
+ for n, key in ipairs(o) do
+ local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
+ if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
+ or opts.keyallow and not opts.keyallow[key]
+ or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
+ or sparse and value == nil then -- skipping nils; do nothing
+ elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
+ if not seen[key] and not globals[key] then
+ table.insert(sref, 'placeholder')
+ local sname = safename(iname, gensym(key)) -- iname is table for local variables
+ sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
+ table.insert(sref, 'placeholder')
+ local path = seen[t]..'['..(seen[key] or globals[key] or gensym(key))..']'
+ sref[#sref] = path..space..'='..space..(seen[value] or val2str(value,nil,indent,path))
+ else
+ table.insert(out,val2str(value,key,indent,insref,seen[t],plainindex,level+1))
+ end
+ end
+ local prefix = string.rep(indent or '', level)
+ local head = indent and '{\n'..prefix..indent or '{'
+ local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
+ local tail = indent and "\n"..prefix..'}' or '}'
+ return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
+ elseif badtype[ttype] then
+ seen[t] = insref or spath
+ return tag..globerr(t, level)
+ elseif ttype == 'function' then
+ seen[t] = insref or spath
+ local ok, res = pcall(string.dump, t)
+ local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
+ "loadstring("..safestr(res)..",'@serialized')")..comment(t, level))
+ return tag..(func or globerr(t, level))
+ else return tag..safestr(t) end -- handle all other types
+ end
+ local sepr = indent and "\n" or ";"..space
+ local body = val2str(t, name, indent) -- this call also populates sref
+ local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
+ local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
+ return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
+end
+
+local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
+return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
+ dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
+ line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
+ block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
+end)() ---- end of Serpent module
+
+local function removebasedir(path, basedir)
+ if iscasepreserving then
+ -- check if the lowercased path matches the basedir
+ -- if so, return substring of the original path (to not lowercase it)
+ return path:lower():find('^'..q(basedir:lower()))
+ and path:sub(#basedir+1) or path
+ else
+ return string.gsub(path, '^'..q(basedir), '')
+ end
+end
+
+local function stack(start)
+ local function vars(f)
+ local func = debug.getinfo(f, "f").func
+ local i = 1
+ local locals = {}
+ while true do
+ local name, value = debug.getlocal(f, i)
+ if not name then break end
+ if string.sub(name, 1, 1) ~= '(' then locals[name] = {value, tostring(value)} end
+ i = i + 1
+ end
+ i = 1
+ local ups = {}
+ while func and true do -- check for func as it may be nil for tail calls
+ local name, value = debug.getupvalue(func, i)
+ if not name then break end
+ ups[name] = {value, tostring(value)}
+ i = i + 1
+ end
+ return locals, ups
+ end
+
+ local stack = {}
+ for i = (start or 0), 100 do
+ local source = debug.getinfo(i, "Snl")
+ if not source then break end
+
+ local src = source.source
+ if src:find("@") == 1 then
+ src = src:sub(2):gsub("\\", "/")
+ if src:find("%./") == 1 then src = src:sub(3) end
+ end
+
+ table.insert(stack, { -- remove basedir from source
+ {source.name, removebasedir(src, basedir), source.linedefined,
+ source.currentline, source.what, source.namewhat, source.short_src},
+ vars(i+1)})
+ if source.what == 'main' then break end
+ end
+ return stack
+end
+
+local function set_breakpoint(file, line)
+ if file == '-' and lastfile then file = lastfile
+ elseif iscasepreserving then file = string.lower(file) end
+ if not breakpoints[line] then breakpoints[line] = {} end
+ breakpoints[line][file] = true
+end
+
+local function remove_breakpoint(file, line)
+ if file == '-' and lastfile then file = lastfile
+ elseif iscasepreserving then file = string.lower(file) end
+ if breakpoints[line] then breakpoints[line][file] = nil end
+end
+
+local function has_breakpoint(file, line)
+ return breakpoints[line]
+ and breakpoints[line][iscasepreserving and string.lower(file) or file]
+end
+
+local function restore_vars(vars)
+ if type(vars) ~= 'table' then return end
+
+ -- locals need to be processed in the reverse order, starting from
+ -- the inner block out, to make sure that the localized variables
+ -- are correctly updated with only the closest variable with
+ -- the same name being changed
+ -- first loop find how many local variables there is, while
+ -- the second loop processes them from i to 1
+ local i = 1
+ while true do
+ local name = debug.getlocal(3, i)
+ if not name then break end
+ i = i + 1
+ end
+ i = i - 1
+ local written_vars = {}
+ while i > 0 do
+ local name = debug.getlocal(3, i)
+ if not written_vars[name] then
+ if string.sub(name, 1, 1) ~= '(' then debug.setlocal(3, i, vars[name]) end
+ written_vars[name] = true
+ end
+ i = i - 1
+ end
+
+ i = 1
+ local func = debug.getinfo(3, "f").func
+ while true do
+ local name = debug.getupvalue(func, i)
+ if not name then break end
+ if not written_vars[name] then
+ if string.sub(name, 1, 1) ~= '(' then debug.setupvalue(func, i, vars[name]) end
+ written_vars[name] = true
+ end
+ i = i + 1
+ end
+end
+
+local function capture_vars(level)
+ local vars = {}
+ local func = debug.getinfo(level or 3, "f").func
+ local i = 1
+ while true do
+ local name, value = debug.getupvalue(func, i)
+ if not name then break end
+ if string.sub(name, 1, 1) ~= '(' then vars[name] = value end
+ i = i + 1
+ end
+ i = 1
+ while true do
+ local name, value = debug.getlocal(level or 3, i)
+ if not name then break end
+ if string.sub(name, 1, 1) ~= '(' then vars[name] = value end
+ i = i + 1
+ end
+ setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) })
+ return vars
+end
+
+local function stack_depth(start_depth)
+ for i = start_depth, 0, -1 do
+ if debug.getinfo(i, "l") then return i+1 end
+ end
+ return start_depth
+end
+
+local function is_safe(stack_level)
+ -- the stack grows up: 0 is getinfo, 1 is is_safe, 2 is debug_hook, 3 is user function
+ if stack_level == 3 then return true end
+ for i = 3, stack_level do
+ -- return if it is not safe to abort
+ local info = debug.getinfo(i, "S")
+ if not info then return true end
+ if info.what == "C" then return false end
+ end
+ return true
+end
+
+local function in_debugger()
+ local this = debug.getinfo(1, "S").source
+ -- only need to check few frames as mobdebug frames should be close
+ for i = 3, 7 do
+ local info = debug.getinfo(i, "S")
+ if not info then return false end
+ if info.source == this then return true end
+ end
+ return false
+end
+
+local function is_pending(peer)
+ -- if there is something already in the buffer, skip check
+ if not buf and checkcount >= mobdebug.checkcount then
+ peer:settimeout(0) -- non-blocking
+ buf = peer:receive(1)
+ peer:settimeout() -- back to blocking
+ checkcount = 0
+ end
+ return buf
+end
+
+local function debug_hook(event, line)
+ -- (1) LuaJIT needs special treatment. Because debug_hook is set for
+ -- *all* coroutines, and not just the one being debugged as in regular Lua
+ -- (http://lua-users.org/lists/lua-l/2011-06/msg00513.html),
+ -- need to avoid debugging mobdebug's own code as LuaJIT doesn't
+ -- always correctly generate call/return hook events (there are more
+ -- calls than returns, which breaks stack depth calculation and
+ -- 'step' and 'step over' commands stop working; possibly because
+ -- 'tail return' events are not generated by LuaJIT).
+ -- the next line checks if the debugger is run under LuaJIT and if
+ -- one of debugger methods is present in the stack, it simply returns.
+ if jit then
+ local coro = coroutine.running()
+ if coro_debugee and coro ~= coro_debugee and not coroutines[coro]
+ or not coro_debugee and (in_debugger() or coro and not coroutines[coro])
+ then return end
+ end
+
+ -- (2) check if abort has been requested and it's safe to abort
+ if abort and is_safe(stack_level) then error(abort) end
+
+ -- (3) also check if this debug hook has not been visited for any reason.
+ -- this check is needed to avoid stepping in too early
+ -- (for example, when coroutine.resume() is executed inside start()).
+ if not seen_hook and in_debugger() then return end
+
+ if event == "call" then
+ stack_level = stack_level + 1
+ elseif event == "return" or event == "tail return" then
+ stack_level = stack_level - 1
+ elseif event == "line" then
+ -- may need to fall through because of the following:
+ -- (1) step_into
+ -- (2) step_over and stack_level <= step_level (need stack_level)
+ -- (3) breakpoint; check for line first as it's known; then for file
+ -- (4) socket call (only do every Xth check)
+ -- (5) at least one watch is registered
+ if not (
+ step_into or step_over or breakpoints[line] or watchescnt > 0
+ or is_pending(server)
+ ) then checkcount = checkcount + 1; return end
+
+ checkcount = mobdebug.checkcount -- force check on the next command
+
+ -- this is needed to check if the stack got shorter or longer.
+ -- unfortunately counting call/return calls is not reliable.
+ -- the discrepancy may happen when "pcall(load, '')" call is made
+ -- or when "error()" is called in a function.
+ -- in either case there are more "call" than "return" events reported.
+ -- this validation is done for every "line" event, but should be "cheap"
+ -- as it checks for the stack to get shorter (or longer by one call).
+ -- start from one level higher just in case we need to grow the stack.
+ -- this may happen after coroutine.resume call to a function that doesn't
+ -- have any other instructions to execute. it triggers three returns:
+ -- "return, tail return, return", which needs to be accounted for.
+ stack_level = stack_depth(stack_level+1)
+
+ local caller = debug.getinfo(2, "S")
+
+ -- grab the filename and fix it if needed
+ local file = lastfile
+ if (lastsource ~= caller.source) then
+ file, lastsource = caller.source, caller.source
+ -- technically, users can supply names that may not use '@',
+ -- for example when they call loadstring('...', 'filename.lua').
+ -- Unfortunately, there is no reliable/quick way to figure out
+ -- what is the filename and what is the source code.
+ -- The following will work if the supplied filename uses Unix path.
+ if file:find("^@") then
+ file = file:gsub("^@", ""):gsub("\\", "/")
+ -- need this conversion to be applied to relative and absolute
+ -- file names as you may write "require 'Foo'" to
+ -- load "foo.lua" (on a case insensitive file system) and breakpoints
+ -- set on foo.lua will not work if not converted to the same case.
+ if iscasepreserving then file = string.lower(file) end
+ if file:find("%./") == 1 then file = file:sub(3)
+ else file = file:gsub('^'..q(basedir), '') end
+ -- some file systems allow newlines in file names; remove these.
+ file = file:gsub("\n", ' ')
+ else
+ -- this is either a file name coming from loadstring("chunk", "file"),
+ -- or the actual source code that needs to be serialized (as it may
+ -- include newlines); assume it's a file name if it's all on one line.
+ file = file:find("[\r\n]") and serpent.line(file) or file
+ end
+
+ -- set to true if we got here; this only needs to be done once per
+ -- session, so do it here to at least avoid setting it for every line.
+ seen_hook = true
+ lastfile = file
+ end
+
+ local vars, status, res
+ if (watchescnt > 0) then
+ vars = capture_vars()
+ for index, value in pairs(watches) do
+ setfenv(value, vars)
+ local ok, fired = pcall(value)
+ if ok and fired then
+ status, res = coroutine.resume(coro_debugger, events.WATCH, vars, file, line, index)
+ break -- any one watch is enough; don't check multiple times
+ end
+ end
+ end
+
+ -- need to get into the "regular" debug handler, but only if there was
+ -- no watch that was fired. If there was a watch, handle its result.
+ local getin = (status == nil) and
+ (step_into
+ or (step_over and stack_level <= step_level)
+ or has_breakpoint(file, line)
+ or is_pending(server))
+
+ if getin then
+ vars = vars or capture_vars()
+ step_into = false
+ step_over = false
+ status, res = coroutine.resume(coro_debugger, events.BREAK, vars, file, line)
+ end
+
+ -- handle 'stack' command that provides stack() information to the debugger
+ if status and res == 'stack' then
+ while status and res == 'stack' do
+ -- resume with the stack trace and variables
+ if vars then restore_vars(vars) end -- restore vars so they are reflected in stack values
+ -- this may fail if __tostring method fails at run-time
+ local ok, snapshot = pcall(stack, 4)
+ status, res = coroutine.resume(coro_debugger, ok and events.STACK or events.BREAK, snapshot, file, line)
+ end
+ end
+
+ -- need to recheck once more as resume after 'stack' command may
+ -- return something else (for example, 'exit'), which needs to be handled
+ if status and res and res ~= 'stack' then
+ if abort == nil and res == "exit" then os.exit(1); return end
+ abort = res
+ -- only abort if safe; if not, there is another (earlier) check inside
+ -- debug_hook, which will abort execution at the first safe opportunity
+ if is_safe(stack_level) then error(abort) end
+ elseif not status and res then
+ error(res, 2) -- report any other (internal) errors back to the application
+ end
+
+ if vars then restore_vars(vars) end
+ end
+end
+
+local function stringify_results(status, ...)
+ if not status then return status, ... end -- on error report as it
+
+ local t = {...}
+ for i,v in pairs(t) do -- stringify each of the returned values
+ local ok, res = pcall(serpent.line, v, {nocode = true, comment = 1})
+ t[i] = ok and res or ("%q"):format(res):gsub("\010","n"):gsub("\026","\\026")
+ end
+ -- stringify table with all returned values
+ -- this is done to allow each returned value to be used (serialized or not)
+ -- intependently and to preserve "original" comments
+ return pcall(serpent.dump, t, {sparse = false})
+end
+
+local function debugger_loop(sev, svars, sfile, sline)
+ local command
+ local app, osname
+ local eval_env = svars or {}
+ local function emptyWatch () return false end
+ local loaded = {}
+ for k in pairs(package.loaded) do loaded[k] = true end
+
+ while true do
+ local line, err
+ local wx = rawget(genv, "wx") -- use rawread to make strict.lua happy
+ if (wx or mobdebug.yield) and server.settimeout then server:settimeout(mobdebug.yieldtimeout) end
+ while true do
+ line, err = server:receive()
+ if not line and err == "timeout" then
+ -- yield for wx GUI applications if possible to avoid "busyness"
+ app = app or (wx and wx.wxGetApp and wx.wxGetApp())
+ if app then
+ local win = app:GetTopWindow()
+ local inloop = app:IsMainLoopRunning()
+ osname = osname or wx.wxPlatformInfo.Get():GetOperatingSystemFamilyName()
+ if win and not inloop then
+ -- process messages in a regular way
+ -- and exit as soon as the event loop is idle
+ if osname == 'Unix' then wx.wxTimer(app):Start(10, true) end
+ local exitLoop = function()
+ win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_IDLE)
+ win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_TIMER)
+ app:ExitMainLoop()
+ end
+ win:Connect(wx.wxEVT_IDLE, exitLoop)
+ win:Connect(wx.wxEVT_TIMER, exitLoop)
+ app:MainLoop()
+ end
+ elseif mobdebug.yield then mobdebug.yield()
+ end
+ elseif not line and err == "closed" then
+ error("Debugger connection unexpectedly closed", 0)
+ else
+ -- if there is something in the pending buffer, prepend it to the line
+ if buf then line = buf .. line; buf = nil end
+ break
+ end
+ end
+ if server.settimeout then server:settimeout() end -- back to blocking
+ command = string.sub(line, string.find(line, "^[A-Z]+"))
+ if command == "SETB" then
+ local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$")
+ if file and line then
+ set_breakpoint(file, tonumber(line))
+ server:send("200 OK\n")
+ else
+ server:send("400 Bad Request\n")
+ end
+ elseif command == "DELB" then
+ local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$")
+ if file and line then
+ remove_breakpoint(file, tonumber(line))
+ server:send("200 OK\n")
+ else
+ server:send("400 Bad Request\n")
+ end
+ elseif command == "EXEC" then
+ local _, _, chunk = string.find(line, "^[A-Z]+%s+(.+)$")
+ if chunk then
+ local func, res = loadstring(chunk)
+ local status
+ if func then
+ setfenv(func, eval_env)
+ status, res = stringify_results(pcall(func))
+ end
+ if status then
+ server:send("200 OK " .. #res .. "\n")
+ server:send(res)
+ else
+ server:send("401 Error in Expression " .. #res .. "\n")
+ server:send(res)
+ end
+ else
+ server:send("400 Bad Request\n")
+ end
+ elseif command == "LOAD" then
+ local _, _, size, name = string.find(line, "^[A-Z]+%s+(%d+)%s+(%S.-)%s*$")
+ size = tonumber(size)
+
+ if abort == nil then -- no LOAD/RELOAD allowed inside start()
+ if size > 0 then server:receive(size) end
+ if sfile and sline then
+ server:send("201 Started " .. sfile .. " " .. sline .. "\n")
+ else
+ server:send("200 OK 0\n")
+ end
+ else
+ -- reset environment to allow required modules to load again
+ -- remove those packages that weren't loaded when debugger started
+ for k in pairs(package.loaded) do
+ if not loaded[k] then package.loaded[k] = nil end
+ end
+
+ if size == 0 and name == '-' then -- RELOAD the current script being debugged
+ server:send("200 OK 0\n")
+ coroutine.yield("load")
+ else
+ -- receiving 0 bytes blocks (at least in luasocket 2.0.2), so skip reading
+ local chunk = size == 0 and "" or server:receive(size)
+ if chunk then -- LOAD a new script for debugging
+ local func, res = loadstring(chunk, "@"..name)
+ if func then
+ server:send("200 OK 0\n")
+ debugee = func
+ coroutine.yield("load")
+ else
+ server:send("401 Error in Expression " .. #res .. "\n")
+ server:send(res)
+ end
+ else
+ server:send("400 Bad Request\n")
+ end
+ end
+ end
+ elseif command == "SETW" then
+ local _, _, exp = string.find(line, "^[A-Z]+%s+(.+)%s*$")
+ if exp then
+ local func, res = loadstring("return(" .. exp .. ")")
+ if func then
+ watchescnt = watchescnt + 1
+ local newidx = #watches + 1
+ watches[newidx] = func
+ server:send("200 OK " .. newidx .. "\n")
+ else
+ server:send("401 Error in Expression " .. #res .. "\n")
+ server:send(res)
+ end
+ else
+ server:send("400 Bad Request\n")
+ end
+ elseif command == "DELW" then
+ local _, _, index = string.find(line, "^[A-Z]+%s+(%d+)%s*$")
+ index = tonumber(index)
+ if index > 0 and index <= #watches then
+ watchescnt = watchescnt - (watches[index] ~= emptyWatch and 1 or 0)
+ watches[index] = emptyWatch
+ server:send("200 OK\n")
+ else
+ server:send("400 Bad Request\n")
+ end
+ elseif command == "RUN" then
+ server:send("200 OK\n")
+
+ local ev, vars, file, line, idx_watch = coroutine.yield()
+ eval_env = vars
+ if ev == events.BREAK then
+ server:send("202 Paused " .. file .. " " .. line .. "\n")
+ elseif ev == events.WATCH then
+ server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n")
+ elseif ev == events.RESTART then
+ -- nothing to do
+ else
+ server:send("401 Error in Execution " .. #file .. "\n")
+ server:send(file)
+ end
+ elseif command == "STEP" then
+ server:send("200 OK\n")
+ step_into = true
+
+ local ev, vars, file, line, idx_watch = coroutine.yield()
+ eval_env = vars
+ if ev == events.BREAK then
+ server:send("202 Paused " .. file .. " " .. line .. "\n")
+ elseif ev == events.WATCH then
+ server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n")
+ elseif ev == events.RESTART then
+ -- nothing to do
+ else
+ server:send("401 Error in Execution " .. #file .. "\n")
+ server:send(file)
+ end
+ elseif command == "OVER" or command == "OUT" then
+ server:send("200 OK\n")
+ step_over = true
+
+ -- OVER and OUT are very similar except for
+ -- the stack level value at which to stop
+ if command == "OUT" then step_level = stack_level - 1
+ else step_level = stack_level end
+
+ local ev, vars, file, line, idx_watch = coroutine.yield()
+ eval_env = vars
+ if ev == events.BREAK then
+ server:send("202 Paused " .. file .. " " .. line .. "\n")
+ elseif ev == events.WATCH then
+ server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n")
+ elseif ev == events.RESTART then
+ -- nothing to do
+ else
+ server:send("401 Error in Execution " .. #file .. "\n")
+ server:send(file)
+ end
+ elseif command == "BASEDIR" then
+ local _, _, dir = string.find(line, "^[A-Z]+%s+(.+)%s*$")
+ if dir then
+ basedir = iscasepreserving and string.lower(dir) or dir
+ -- reset cached source as it may change with basedir
+ lastsource = nil
+ server:send("200 OK\n")
+ else
+ server:send("400 Bad Request\n")
+ end
+ elseif command == "SUSPEND" then
+ -- do nothing; it already fulfilled its role
+ elseif command == "STACK" then
+ -- first check if we can execute the stack command
+ -- as it requires yielding back to debug_hook it cannot be executed
+ -- if we have not seen the hook yet as happens after start().
+ -- in this case we simply return an empty result
+ local vars, ev = {}
+ if seen_hook then
+ ev, vars = coroutine.yield("stack")
+ end
+ if ev and ev ~= events.STACK then
+ server:send("401 Error in Execution " .. #vars .. "\n")
+ server:send(vars)
+ else
+ local ok, res = pcall(serpent.dump, vars, {nocode = true, sparse = false})
+ if ok then
+ server:send("200 OK " .. res .. "\n")
+ else
+ server:send("401 Error in Execution " .. #res .. "\n")
+ server:send(res)
+ end
+ end
+ elseif command == "OUTPUT" then
+ local _, _, stream, mode = string.find(line, "^[A-Z]+%s+(%w+)%s+([dcr])%s*$")
+ if stream and mode and stream == "stdout" then
+ -- assign "print" in the global environment
+ genv.print = mode == 'd' and iobase.print or coroutine.wrap(function(...)
+ -- wrapping into coroutine.wrap protects this function from
+ -- being stepped through in the debugger
+ local tbl = {...}
+ while true do
+ if mode == 'c' then iobase.print(unpack(tbl)) end
+ for n = 1, #tbl do
+ tbl[n] = select(2, pcall(serpent.line, tbl[n], {nocode = true, comment = false})) end
+ local file = table.concat(tbl, "\t").."\n"
+ server:send("204 Output " .. stream .. " " .. #file .. "\n" .. file)
+ tbl = {coroutine.yield()}
+ end
+ end)
+ server:send("200 OK\n")
+ else
+ server:send("400 Bad Request\n")
+ end
+ elseif command == "EXIT" then
+ server:send("200 OK\n")
+ coroutine.yield("exit")
+ else
+ server:send("400 Bad Request\n")
+ end
+ end
+end
+
+local function connect(controller_host, controller_port)
+ return (socket.connect4 or socket.connect)(controller_host, controller_port)
+end
+
+local function isrunning()
+ return coro_debugger and coroutine.status(coro_debugger) == 'suspended'
+end
+
+local lasthost, lastport
+
+-- Starts a debug session by connecting to a controller
+local function start(controller_host, controller_port)
+ -- only one debugging session can be run (as there is only one debug hook)
+ if isrunning() then return end
+
+ lasthost = controller_host or lasthost
+ lastport = controller_port or lastport
+
+ controller_host = lasthost or "localhost"
+ controller_port = lastport or mobdebug.port
+
+ server = (socket.connect4 or socket.connect)(controller_host, controller_port)
+ if server then
+ -- correct stack depth which already has some calls on it
+ -- so it doesn't go into negative when those calls return
+ -- as this breaks subsequence checks in stack_depth().
+ -- start from 16th frame, which is sufficiently large for this check.
+ stack_level = stack_depth(16)
+
+ -- provide our own traceback function to report the error remotely
+ do
+ local dtraceback = debug.traceback
+ debug.traceback = function (...)
+ if select('#', ...) >= 1 then
+ local err, lvl = ...
+ if err and type(err) ~= 'thread' then
+ local trace = dtraceback(err, (lvl or 2)+1)
+ if genv.print == iobase.print then -- no remote redirect
+ return trace
+ else
+ genv.print(trace) -- report the error remotely
+ return -- don't report locally to avoid double reporting
+ end
+ end
+ end
+ -- direct call to debug.traceback: return the original.
+ -- debug.traceback(nil, level) doesn't work in Lua 5.1
+ -- (http://lua-users.org/lists/lua-l/2011-06/msg00574.html), so
+ -- simply remove first frame from the stack trace
+ return (dtraceback(...):gsub("(stack traceback:\n)[^\n]*\n", "%1"))
+ end
+ end
+ coro_debugger = coroutine.create(debugger_loop)
+ debug.sethook(debug_hook, "lcr")
+ seen_hook = nil -- reset in case the last start() call was refused
+ step_into = true -- start with step command
+ return true
+ else
+ print("Could not connect to " .. controller_host .. ":" .. controller_port)
+ end
+end
+
+local function controller(controller_host, controller_port, scratchpad)
+ -- only one debugging session can be run (as there is only one debug hook)
+ if isrunning() then return end
+
+ lasthost = controller_host or lasthost
+ lastport = controller_port or lastport
+
+ controller_host = lasthost or "localhost"
+ controller_port = lastport or mobdebug.port
+
+ local exitonerror = not scratchpad
+ server = (socket.connect4 or socket.connect)(controller_host, controller_port)
+ if server then
+ local function report(trace, err)
+ local msg = err .. "\n" .. trace
+ server:send("401 Error in Execution " .. #msg .. "\n")
+ server:send(msg)
+ return err
+ end
+
+ seen_hook = true -- allow to accept all commands
+ coro_debugger = coroutine.create(debugger_loop)
+
+ while true do
+ step_into = true -- start with step command
+ abort = false -- reset abort flag from the previous loop
+ if scratchpad then checkcount = mobdebug.checkcount end -- force suspend right away
+
+ coro_debugee = coroutine.create(debugee)
+ debug.sethook(coro_debugee, debug_hook, "lcr")
+ local status, err = coroutine.resume(coro_debugee)
+
+ -- was there an error or is the script done?
+ -- 'abort' state is allowed here; ignore it
+ if abort then
+ if tostring(abort) == 'exit' then break end
+ else
+ if status then -- normal execution is done
+ break
+ elseif err and not tostring(err):find(deferror) then
+ -- report the error back
+ -- err is not necessarily a string, so convert to string to report
+ report(debug.traceback(coro_debugee), tostring(err))
+ if exitonerror then break end
+ -- resume once more to clear the response the debugger wants to send
+ -- need to use capture_vars(2) as three would be the level of
+ -- the caller for controller(), but because of the tail call,
+ -- the caller may not exist;
+ -- This is not entirely safe as the user may see the local
+ -- variable from console, but they will be reset anyway.
+ -- This functionality is used when scratchpad is paused to
+ -- gain access to remote console to modify global variables.
+ local status, err = coroutine.resume(coro_debugger, events.RESTART, capture_vars(2))
+ if not status or status and err == "exit" then break end
+ end
+ end
+ end
+ else
+ print("Could not connect to " .. controller_host .. ":" .. controller_port)
+ return false
+ end
+ return true
+end
+
+local function scratchpad(controller_host, controller_port)
+ return controller(controller_host, controller_port, true)
+end
+
+local function loop(controller_host, controller_port)
+ return controller(controller_host, controller_port, false)
+end
+
+local function on()
+ if not (isrunning() and server) then return end
+
+ local co = coroutine.running()
+ if co then
+ if not coroutines[co] then
+ coroutines[co] = true
+ debug.sethook(co, debug_hook, "lcr")
+ end
+ else
+ debug.sethook(debug_hook, "lcr")
+ end
+end
+
+local function off()
+ if not (isrunning() and server) then return end
+
+ local co = coroutine.running()
+ if co then
+ if coroutines[co] then coroutines[co] = false end
+ -- don't remove coroutine hook under LuaJIT as there is only one (global) hook
+ if not jit then debug.sethook(co) end
+ else
+ debug.sethook()
+ end
+end
+
+-- Handles server debugging commands
+local function handle(params, client, options)
+ local _, _, command = string.find(params, "^([a-z]+)")
+ local file, line, watch_idx
+ if command == "run" or command == "step" or command == "out"
+ or command == "over" or command == "exit" then
+ client:send(string.upper(command) .. "\n")
+ client:receive() -- this should consume the first '200 OK' response
+ while true do
+ local done = true
+ local breakpoint = client:receive()
+ if not breakpoint then
+ print("Program finished")
+ os.exit()
+ return -- use return here for those cases where os.exit() is not wanted
+ end
+ local _, _, status = string.find(breakpoint, "^(%d+)")
+ if status == "200" then
+ -- don't need to do anything
+ elseif status == "202" then
+ _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$")
+ if file and line then
+ print("Paused at file " .. file .. " line " .. line)
+ end
+ elseif status == "203" then
+ _, _, file, line, watch_idx = string.find(breakpoint, "^203 Paused%s+(.-)%s+(%d+)%s+(%d+)%s*$")
+ if file and line and watch_idx then
+ print("Paused at file " .. file .. " line " .. line .. " (watch expression " .. watch_idx .. ": [" .. watches[watch_idx] .. "])")
+ end
+ elseif status == "204" then
+ local _, _, stream, size = string.find(breakpoint, "^204 Output (%w+) (%d+)$")
+ if stream and size then
+ local msg = client:receive(tonumber(size))
+ print(msg)
+ if outputs[stream] then outputs[stream](msg) end
+ -- this was just the output, so go back reading the response
+ done = false
+ end
+ elseif status == "401" then
+ local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)$")
+ if size then
+ local msg = client:receive(tonumber(size))
+ print("Error in remote application: " .. msg)
+ os.exit(1)
+ return nil, nil, msg -- use return here for those cases where os.exit() is not wanted
+ end
+ else
+ print("Unknown error")
+ os.exit(1)
+ -- use return here for those cases where os.exit() is not wanted
+ return nil, nil, "Debugger error: unexpected response '" .. breakpoint .. "'"
+ end
+ if done then break end
+ end
+ elseif command == "setb" then
+ _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$")
+ if file and line then
+ -- if this is a file name, and not a file source
+ if not file:find('^".*"$') then
+ file = string.gsub(file, "\\", "/") -- convert slash
+ file = removebasedir(file, basedir)
+ end
+ client:send("SETB " .. file .. " " .. line .. "\n")
+ if client:receive() == "200 OK" then
+ set_breakpoint(file, line)
+ else
+ print("Error: breakpoint not inserted")
+ end
+ else
+ print("Invalid command")
+ end
+ elseif command == "setw" then
+ local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$")
+ if exp then
+ client:send("SETW " .. exp .. "\n")
+ local answer = client:receive()
+ local _, _, watch_idx = string.find(answer, "^200 OK (%d+)%s*$")
+ if watch_idx then
+ watches[watch_idx] = exp
+ print("Inserted watch exp no. " .. watch_idx)
+ else
+ local _, _, size = string.find(answer, "^401 Error in Expression (%d+)$")
+ if size then
+ local err = client:receive(tonumber(size)):gsub(".-:%d+:%s*","")
+ print("Error: watch expression not set: " .. err)
+ else
+ print("Error: watch expression not set")
+ end
+ end
+ else
+ print("Invalid command")
+ end
+ elseif command == "delb" then
+ _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$")
+ if file and line then
+ -- if this is a file name, and not a file source
+ if not file:find('^".*"$') then
+ file = string.gsub(file, "\\", "/") -- convert slash
+ file = removebasedir(file, basedir)
+ end
+ client:send("DELB " .. file .. " " .. line .. "\n")
+ if client:receive() == "200 OK" then
+ remove_breakpoint(file, line)
+ else
+ print("Error: breakpoint not removed")
+ end
+ else
+ print("Invalid command")
+ end
+ elseif command == "delallb" then
+ for line, breaks in pairs(breakpoints) do
+ for file, _ in pairs(breaks) do
+ client:send("DELB " .. file .. " " .. line .. "\n")
+ if client:receive() == "200 OK" then
+ remove_breakpoint(file, line)
+ else
+ print("Error: breakpoint at file " .. file .. " line " .. line .. " not removed")
+ end
+ end
+ end
+ elseif command == "delw" then
+ local _, _, index = string.find(params, "^[a-z]+%s+(%d+)%s*$")
+ if index then
+ client:send("DELW " .. index .. "\n")
+ if client:receive() == "200 OK" then
+ watches[index] = nil
+ else
+ print("Error: watch expression not removed")
+ end
+ else
+ print("Invalid command")
+ end
+ elseif command == "delallw" then
+ for index, exp in pairs(watches) do
+ client:send("DELW " .. index .. "\n")
+ if client:receive() == "200 OK" then
+ watches[index] = nil
+ else
+ print("Error: watch expression at index " .. index .. " [" .. exp .. "] not removed")
+ end
+ end
+ elseif command == "eval" or command == "exec"
+ or command == "load" or command == "loadstring"
+ or command == "reload" then
+ local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$")
+ if exp or (command == "reload") then
+ if command == "eval" or command == "exec" then
+ exp = (exp:gsub("%-%-%[(=*)%[.-%]%1%]", "") -- remove comments
+ :gsub("%-%-.-\n", " ") -- remove line comments
+ :gsub("\n", " ")) -- convert new lines
+ if command == "eval" then exp = "return " .. exp end
+ client:send("EXEC " .. exp .. "\n")
+ elseif command == "reload" then
+ client:send("LOAD 0 -\n")
+ elseif command == "loadstring" then
+ local _, _, _, file, lines = string.find(exp, "^([\"'])(.-)%1%s+(.+)")
+ if not file then
+ _, _, file, lines = string.find(exp, "^(%S+)%s+(.+)")
+ end
+ client:send("LOAD " .. #lines .. " " .. file .. "\n")
+ client:send(lines)
+ else
+ local file = io.open(exp, "r")
+ if not file and pcall(require, "winapi") then
+ -- if file is not open and winapi is there, try with a short path;
+ -- this may be needed for unicode paths on windows
+ winapi.set_encoding(winapi.CP_UTF8)
+ file = io.open(winapi.short_path(exp), "r")
+ end
+ if not file then error("Cannot open file " .. exp) end
+ -- read the file and remove the shebang line as it causes a compilation error
+ local lines = file:read("*all"):gsub("^#!.-\n", "\n")
+ file:close()
+
+ local file = string.gsub(exp, "\\", "/") -- convert slash
+ file = removebasedir(file, basedir)
+ client:send("LOAD " .. #lines .. " " .. file .. "\n")
+ if #lines > 0 then client:send(lines) end
+ end
+ while true do
+ local params, err = client:receive()
+ if not params then
+ return nil, nil, "Debugger connection " .. (err or "error")
+ end
+ local done = true
+ local _, _, status, len = string.find(params, "^(%d+).-%s+(%d+)%s*$")
+ if status == "200" then
+ len = tonumber(len)
+ if len > 0 then
+ local status, res
+ local str = client:receive(len)
+ -- handle serialized table with results
+ local func, err = loadstring(str)
+ if func then
+ status, res = pcall(func)
+ if not status then err = res
+ elseif type(res) ~= "table" then
+ err = "received "..type(res).." instead of expected 'table'"
+ end
+ end
+ if err then
+ print("Error in processing results: " .. err)
+ return nil, nil, "Error in processing results: " .. err
+ end
+ print(unpack(res))
+ return res[1], res
+ end
+ elseif status == "201" then
+ _, _, file, line = string.find(params, "^201 Started%s+(.-)%s+(%d+)%s*$")
+ elseif status == "202" or params == "200 OK" then
+ -- do nothing; this only happens when RE/LOAD command gets the response
+ -- that was for the original command that was aborted
+ elseif status == "204" then
+ local _, _, stream, size = string.find(params, "^204 Output (%w+) (%d+)$")
+ if stream and size then
+ local msg = client:receive(tonumber(size))
+ print(msg)
+ if outputs[stream] then outputs[stream](msg) end
+ -- this was just the output, so go back reading the response
+ done = false
+ end
+ elseif status == "401" then
+ len = tonumber(len)
+ local res = client:receive(len)
+ print("Error in expression: " .. res)
+ return nil, nil, res
+ else
+ print("Unknown error")
+ return nil, nil, "Debugger error: unexpected response after EXEC/LOAD '" .. params .. "'"
+ end
+ if done then break end
+ end
+ else
+ print("Invalid command")
+ end
+ elseif command == "listb" then
+ for l, v in pairs(breakpoints) do
+ for f in pairs(v) do
+ print(f .. ": " .. l)
+ end
+ end
+ elseif command == "listw" then
+ for i, v in pairs(watches) do
+ print("Watch exp. " .. i .. ": " .. v)
+ end
+ elseif command == "suspend" then
+ client:send("SUSPEND\n")
+ elseif command == "stack" then
+ client:send("STACK\n")
+ local resp = client:receive()
+ local _, _, status, res = string.find(resp, "^(%d+)%s+%w+%s+(.+)%s*$")
+ if status == "200" then
+ local func, err = loadstring(res)
+ if func == nil then
+ print("Error in stack information: " .. err)
+ return nil, nil, err
+ end
+ local ok, stack = pcall(func)
+ if not ok then
+ print("Error in stack information: " .. stack)
+ return nil, nil, stack
+ end
+ for _,frame in ipairs(stack) do
+ print(serpent.line(frame[1], {comment = false}))
+ end
+ return stack
+ elseif status == "401" then
+ local _, _, len = string.find(resp, "%s+(%d+)%s*$")
+ len = tonumber(len)
+ local res = len > 0 and client:receive(len) or "Invalid stack information."
+ print("Error in expression: " .. res)
+ return nil, nil, res
+ else
+ print("Unknown error")
+ return nil, nil, "Debugger error: unexpected response after STACK"
+ end
+ elseif command == "output" then
+ local _, _, stream, mode = string.find(params, "^[a-z]+%s+(%w+)%s+([dcr])%s*$")
+ if stream and mode then
+ client:send("OUTPUT "..stream.." "..mode.."\n")
+ local resp = client:receive()
+ local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$")
+ if status == "200" then
+ print("Stream "..stream.." redirected")
+ outputs[stream] = type(options) == 'table' and options.handler or nil
+ else
+ print("Unknown error")
+ return nil, nil, "Debugger error: can't redirect "..stream
+ end
+ else
+ print("Invalid command")
+ end
+ elseif command == "basedir" then
+ local _, _, dir = string.find(params, "^[a-z]+%s+(.+)$")
+ if dir then
+ dir = string.gsub(dir, "\\", "/") -- convert slash
+ if not string.find(dir, "/$") then dir = dir .. "/" end
+
+ local remdir = dir:match("\t(.+)")
+ if remdir then dir = dir:gsub("/?\t.+", "/") end
+ basedir = dir
+
+ client:send("BASEDIR "..(remdir or dir).."\n")
+ local resp = client:receive()
+ local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$")
+ if status == "200" then
+ print("New base directory is " .. basedir)
+ else
+ print("Unknown error")
+ return nil, nil, "Debugger error: unexpected response after BASEDIR"
+ end
+ else
+ print(basedir)
+ end
+ elseif command == "help" then
+ print("setb <file> <line> -- sets a breakpoint")
+ print("delb <file> <line> -- removes a breakpoint")
+ print("delallb -- removes all breakpoints")
+ print("setw <exp> -- adds a new watch expression")
+ print("delw <index> -- removes the watch expression at index")
+ print("delallw -- removes all watch expressions")
+ print("run -- runs until next breakpoint")
+ print("step -- runs until next line, stepping into function calls")
+ print("over -- runs until next line, stepping over function calls")
+ print("out -- runs until line after returning from current function")
+ print("listb -- lists breakpoints")
+ print("listw -- lists watch expressions")
+ print("eval <exp> -- evaluates expression on the current context and returns its value")
+ print("exec <stmt> -- executes statement on the current context")
+ print("load <file> -- loads a local file for debugging")
+ print("reload -- restarts the current debugging session")
+ print("stack -- reports stack trace")
+ print("output stdout <d|c|r> -- capture and redirect io stream (default|copy|redirect)")
+ print("basedir [<path>] -- sets the base path of the remote application, or shows the current one")
+ print("exit -- exits debugger")
+ else
+ local _, _, spaces = string.find(params, "^(%s*)$")
+ if not spaces then
+ print("Invalid command")
+ return nil, nil, "Invalid command"
+ end
+ end
+ return file, line
+end
+
+-- Starts debugging server
+local function listen(host, port)
+ host = host or "*"
+ port = port or mobdebug.port
+
+ local socket = require "socket"
+
+ print("Lua Remote Debugger")
+ print("Run the program you wish to debug")
+
+ local server = socket.bind(host, port)
+ local client = server:accept()
+
+ client:send("STEP\n")
+ client:receive()
+
+ local breakpoint = client:receive()
+ local _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$")
+ if file and line then
+ print("Paused at file " .. file )
+ print("Type 'help' for commands")
+ else
+ local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)%s*$")
+ if size then
+ print("Error in remote application: ")
+ print(client:receive(size))
+ end
+ end
+
+ while true do
+ io.write("> ")
+ local line = io.read("*line")
+ handle(line, client)
+ end
+end
+
+local cocreate
+local function coro()
+ if cocreate then return end -- only set once
+ cocreate = cocreate or coroutine.create
+ coroutine.create = function(f, ...)
+ return cocreate(function(...)
+ require("mobdebug").on()
+ return f(...)
+ end, ...)
+ end
+end
+
+local moconew
+local function moai()
+ if moconew then return end -- only set once
+ moconew = moconew or (MOAICoroutine and MOAICoroutine.new)
+ if not moconew then return end
+ MOAICoroutine.new = function(...)
+ local thread = moconew(...)
+ local mt = getmetatable(thread)
+ local patched = mt.run
+ mt.run = function(self, f, ...)
+ return patched(self, function(...)
+ require("mobdebug").on()
+ return f(...)
+ end, ...)
+ end
+ return thread
+ end
+end
+
+-- this is a function that removes all hooks and closes the socket to
+-- report back to the controller that the debugging is done.
+-- the script that called `done` can still continue.
+local function done()
+ if not (isrunning() and server) then return end
+
+ if not jit then
+ for co, debugged in pairs(coroutines) do
+ if debugged then debug.sethook(co) end
+ end
+ end
+
+ debug.sethook()
+ server:close()
+
+ coro_debugger = nil -- to make sure isrunning() returns `false`
+ seen_hook = nil -- to make sure that the next start() call works
+ abort = nil -- to make sure that callback calls use proper "abort" value
+end
+
+-- make public functions available
+mobdebug.listen = listen
+mobdebug.loop = loop
+mobdebug.scratchpad = scratchpad
+mobdebug.handle = handle
+mobdebug.connect = connect
+mobdebug.start = start
+mobdebug.on = on
+mobdebug.off = off
+mobdebug.moai = moai
+mobdebug.coro = coro
+mobdebug.done = done
+mobdebug.line = serpent.line
+mobdebug.dump = serpent.dump
+mobdebug.yield = nil -- callback
+
+-- this is needed to make "require 'modebug'" to work when mobdebug
+-- module is loaded manually
+package.loaded.mobdebug = mobdebug
+
+return mobdebug
diff --git a/lua/movepatientsfromlist.lua b/lua/movepatientsfromlist.lua
new file mode 100644
index 0000000..881fdbf
--- /dev/null
+++ b/lua/movepatientsfromlist.lua
@@ -0,0 +1,13 @@
+ inputFile = 'list1.txt'
+ srcAet = 'ABC'
+ destAet = 'XYZ'
+
+ for line in io.lines(inputFile) do
+ ptId = line
+
+ cmd = newdicomobject()
+ cmd.QueryRetrieveLevel = 'PATIENT'
+ cmd.PatientID = ptId
+
+ dicommove(srcAet, destAet, cmd);
+ end
diff --git a/lua/nifty_test.lua b/lua/nifty_test.lua
new file mode 100644
index 0000000..1d0a931
--- /dev/null
+++ b/lua/nifty_test.lua
@@ -0,0 +1,70 @@
+require "pack"
+dofile('nifty.lua')
+
+-- query all series
+x=DicomObject:new()
+x.QueryRetrieveLevel='SERIES'
+x.PatientID='VeiCat'
+x.SOPInstanceUID=''
+x.SeriesInstanceUID=''
+x.SeriesTime=''
+y=dicomquery('CONQUESTSRV1', 'SERIES', x)
+
+-- select and sort all longer series on time
+t = {}
+for i=0,#y-1 do
+ -- query just to count
+ z=DicomObject:new()
+ z.QueryRetrieveLevel='IMAGE'
+ z.PatientID=y[i].PatientID
+ z.SOPInstanceUID=''
+ z.SeriesInstanceUID=y[i].SeriesInstanceUID
+ u=dicomquery('CONQUESTSRV1', 'IMAGE', z)
+ if #u>20 then
+ table.insert(t, {y[i].SeriesInstanceUID, y[i].SeriesTime})
+ end
+end
+table.sort(t, function(a, b) return a[2]<b[2] end)
+
+-- this will will log all converted slices
+f = io.open('converted\\' .. x.PatientID .. '_timestamps.txt', 'wt')
+
+start = 0;
+for i=1, #t do
+ names = {}
+ outnames = {}
+
+ -- query to get AcquisitionTime and InstanceUID for each slice
+ z=DicomObject:new()
+ z.QueryRetrieveLevel='IMAGE'
+ z.PatientID=x.PatientID
+ z.SOPInstanceUID=''
+ z.SeriesInstanceUID=t[i][1]
+ z.AcquisitionTime=''
+ u=dicomquery('CONQUESTSRV1', 'IMAGE', z)
+ for j=0,#u-1 do
+ names[j+1] = {u[j].PatientID..':'..u[j].SOPInstanceUID, u[j].AcquisitionTime}
+ end
+
+ -- sort slices on acquisitiontime
+ table.sort(names, function(a, b) return a[2]<b[2] end)
+
+ -- tag each slice with a sequence number
+ for j=1,#names do
+ names[j][3] = j+start-1
+ outnames[j] = string.format('converted\\%s_%05d.nii', x.PatientID, j+start-1)
+ end
+ start = start + #u
+
+ print(unpack(names[1]))
+ write_nifty(names, outnames, 3) -- outnames table --> mode where each slice is converted
+
+ -- log the processed data
+ for j=1,#names do
+ names[j]=table.concat(names[j], ',')
+ end
+ f:write(table.concat(names, '\n'))
+ f:write('\n\n')
+end
+
+f:close();
diff --git a/lua/niftydicom.lua b/lua/niftydicom.lua
new file mode 100644
index 0000000..4770fd4
--- /dev/null
+++ b/lua/niftydicom.lua
@@ -0,0 +1,454 @@
+--[[
+#Basic Nifty/DICOM functions
+for [Conquest](http://ingenium.home.xs4all.nl/dicom.html) dicom server, version 1.4.17beta or higher expected
+
+ function `write_nifty(imagefiles, filenames, replicateslices)`
+ saves a DICOM series in nifty1.1 s-form format
+ `imagefiles` is a table of strings (dicom filenames), must be in correct order
+ if it is a table of tables, only [1] or .name is used to get the filename
+ `filenames` is the name of the output nifty1.1 file or a table of output files
+ to create nifty files of individual slices, which may be replicated if
+ parameter `replicateslices` is passed and set to >1
+
+ function `reread_nifty(imagefiles, filename, usecoords, replacevalues)`
+ take a nifty1.1 file and puts its pixel value into new dicom series
+ `imagefiles` is a table of strings (filenames) or tables of the original dicom data
+ `filename` is the name of the input nifty1.1 file (must be same dimensions as dicom data)
+ `usecoords` (optional) if set, nifty s-form changes ImagePosition/OrientationPatient
+ `replacevalues` is an (optional) table with replacement dicom tags, e.g., {SeriesDescription = 'ReOriented'}
+
+ function `append_nifty(to, from)`
+ Appends nifty file `from` to nifty file `to`, making `to` 4D if needed.
+ This routine assumes `to` and `from` have the same dimensions, type etc.
+ `append_nifty` is not DICOM server specific, it may be run from any lua interpreter
+
+ function `slice_nifty(from, to, slice)`
+ Slices timeframe `slice` out of nifty file `from` to nifty file `to`.
+ `slice_nifty` is not DICOM server specific, it may be run from any lua interpreter
+
+ function `reread_interfile(imagefiles, headerfilename, replacevalues, shift, scale)`
+ take a SIRT interfile file and puts its pixel value into new dicom series
+ `imagefiles` is a table of strings (filenames) or tables of the original dicom data
+ `filename` is the name of the input SIRT interfile header file. Coordinates and
+ dimensions are taken from the interfile. `replacevalues` is an (optional) table
+ with replacement dicom tags, e.g., {SeriesDescription = 'ReOriented'}.
+ `shift` is the optional magic z-axis shift (must be 136?), `scale` is used if the
+ interfile data is float, prior to conversion to short. Note 1: requires conquest
+ 1.4.17a to be able to change image dimensions. Note 2: need to pass
+ AcquisitionTime, SeriesTime, FrameReferenceTime, ActualFrameDuration,
+ RescaleIntercept, RescaleSlope in `replacevalues` to make a valid PET
+]]
+
+-- 20130621 mvh Fix for linux
+-- 20130628 mvh Fix to allow reading of 4D DICOM data;
+-- accept table as filenames for reread_nifty
+-- Fix for reading and wrting DICOM series that are 4D volumes
+-- Reject series without SliceLocation and color series
+-- 20130701 mvh imagefiles may be table of string or table of tables with t[1] or t.name
+-- Fix ndim and added slice_nifty
+-- Todo: support multiframe object
+-- 20130702 mvh Fix matrices in 4D data
+-- 20130703 mvh Fixed dimz for replicateslices, extended error messages
+-- 20130708 mvh Reject invalid 4D data
+-- 20130709 mvh Added reread_interfile to convert SIRT recons back to dicom
+-- 20130711 mvh Made it to work - required conquest 1.4.17a
+-- 20130813 mvh Use DicomObject:addimage from 1.4.17b
+
+require('niftyutil')
+
+function write_nifty(imagefiles, filenames, replicateslices)
+ require "pack"
+
+ function image(i)
+ local t=imagefiles[i]
+ if type(t)=='table' then
+ return t[1] or t.name
+ else
+ return t
+ end
+ end
+
+ if #imagefiles<2 then
+ error('*** write_nifty: requires at least 2 images ')
+ return
+ end
+
+ replicateslices = replicateslices or 1
+
+ local headerkey = string.pack('iAAihAA',
+ 348, -- sizeof header
+ string.rep('\000', 10), -- data_type
+ string.rep('\000', 18), -- db_name
+ 16384, -- extents
+ 0, -- session_error
+ 'r', -- regular
+ '\000' -- hkey_un0
+ )
+
+ -- need two images to compute Z direction from ImagePositionPatient, 3rd image to check on 4D or inconsistent data
+ local i1 = DicomObject:new(); i1:Read(image(1))
+ local i2 = DicomObject:new(); i2:Read(image(2))
+ local i3 = DicomObject:new(); i3:Read(image(#imagefiles))
+
+ if (i1.SliceLocation or '') == '' then
+ print('*** write_nifty does not support images without slice location')
+ return
+ end
+
+ vl = (i1.SamplesPerPixel or '1') + 0
+ if vl~=1 then
+ print('*** write_nifty does not support color images')
+ return
+ end
+
+ local ps = i1.PixelSpacing or '1\\1'
+ local p1 = string.gsub(ps, '.*\\', '') + 0
+ local p2 = string.gsub(ps, '\\.*', '') + 0
+ local slicespacing = ((i3.SliceLocation+0) - (i1.SliceLocation+0)) / (#imagefiles-1)
+
+ local ndim=3
+ local dimz=#imagefiles
+ local dimt=1
+
+ -- is there a slicing inconsistency or is the data is 4D ?
+ if math.abs((i2.SliceLocation+0) - (i1.SliceLocation+0) - slicespacing) > 0.01 then
+ -- compute #timeframes from the slicelocation range
+ local lastfirst = (i3.SliceLocation+0) - (i1.SliceLocation+0)
+ local scndfirst = (i2.SliceLocation+0) - (i1.SliceLocation+0)
+ local dimt2 = #imagefiles / ((lastfirst / scndfirst) + 1)
+
+ -- more than one --> 4D
+ if math.floor(dimt2)+0.5 > 1 then
+ dimt = math.floor(#imagefiles / ((lastfirst / scndfirst) + 1) + 0.5)
+ dimz = math.floor(dimz/dimt + 0.5)
+ print('detected 4D data', dimt, dimz, ((lastfirst / scndfirst) + 1))
+ if dimt*dimz ~= #imagefiles then
+ print('*** rejected 4D data, because there are ', #imagefiles, ' slices while the dimensions require ', dimt*dimz, 'slices')
+ dimz=#imagefiles
+ dimt=1
+ return
+ else
+ ndim = 4
+ slicespacing = ((i3.SliceLocation+0) - (i1.SliceLocation+0)) / (dimz-1)
+ end
+ else
+ print('*** Slice spacing inconsistent, is this a localizer?')
+ print('*** There are', #imagefiles, 'slices and the last slice number is ', i3.InstanceNumber)
+ end
+ end
+
+ local mz = 1
+ if slicespacing < 0 then
+ mz = -1
+ slicespacing = -slicespacing
+ end
+
+ local tdimz=dimz
+ if type(filenames)=='table' then
+ tdimz=replicateslices
+ end
+
+ local imagedimensions = string.pack(
+ 'hhhhhhhh hhhhhhh hhh ffffffff ffffffff ii',
+ ndim, i1.Columns, i1.Rows, tdimz, dimt, vl, 0, 0, -- dim
+ 0, 0, 0, 0, 0, 0, 0, -- unused
+ 4, 16, 0, -- short, 16 bits, unused
+ mz, p1, p2, slicespacing, 0, 0, 0, 0, -- pixdim
+ 352, 0, 0, 0, 0, 0, 0, 0, -- voxoffset
+ 0, 0)
+
+ -- calculate that which is the same for each slice (if writing loose slices)
+ local t
+ t = split(i1.ImagePositionPatient, '\\')
+ local xs1, ys1, zs1 = unpack(t);
+ t = split(i3.ImagePositionPatient, '\\')
+ local xs2, ys2, zs2 = unpack(t);
+ t = split(i1.ImageOrientationPatient, '\\')
+ local rx1, rx2, rx3, ry1, ry2, ry3 = unpack(t);
+ local rz1 = (xs2-xs1) / (dimz-1)
+ local rz2 = (ys2-ys1) / (dimz-1)
+ local rz3 = (zs2-zs1) / (dimz-1)
+
+ if type(filenames)~='table' then
+ filenames = {filenames}
+ end
+
+ local f
+ for i=1, #imagefiles do -- write pixel values or nifty image of all images
+ i1:Read(image(i))
+
+ if i <= #filenames then
+ xs1, ys1, zs1 = unpack(split(i1.ImagePositionPatient, '\\'));
+ local df = (replicateslices-1)/2
+ local sx={p1*rx1, p2*ry1, rz1, xs1 - df*rz1}
+ local sy={p1*rx2, p2*ry2, rz2, ys1 - df*rz2}
+ local sz={p1*rx3, p2*ry3, rz3, zs1 - df*rz3}
+ local nifty_extensions= string.pack(
+ 'AA hh ffffff ffff ffff ffff A A',
+ 'hoi '..string.rep('\000', 76), -- descrip
+ string.rep('\000', 24), -- aux_file
+ 0, 1, -- qform_code, sform_code
+ 0, 0, 0, 0, 0, 0, -- quaternion (unused)
+ -sx[1],-sx[2],-sx[3],-sx[4], -- srow_x
+ -sy[1],-sy[2],-sy[3],-sy[4], -- srow_y
+ sz[1], sz[2], sz[3], sz[4], -- srow_z
+ string.rep('\000', 16), -- intent_name
+ 'n+1\000' -- magic (nifty 1.1, embedded data)
+ )
+ f = io.open(filenames[i], 'wb')
+ if f==nil then
+ error('nifty_write: cannot write file '..filenames[i])
+ return
+ end
+ f:write(headerkey)
+ f:write(imagedimensions)
+ f:write(nifty_extensions)
+ f:write(string.rep('\000', 4)) -- empty minimal extension
+ end
+
+ local y=i1:GetImage(0)
+ for j=1, replicateslices do
+ f:write(y)
+ end
+
+ if #filenames>1 or i==#imagefiles then
+ f:close()
+ end
+ end
+end
+
+function reread_nifty(imagefiles, filename, usecoords, replacevalues)
+ require "pack"
+
+ function image(i)
+ local t=imagefiles[i]
+ if type(t)=='table' then
+ return t[1] or t.name
+ else
+ return t
+ end
+ end
+
+ local f = io.open(filename, 'rb')
+ local suid = genuid()
+ local header, nxt, dim0, dim1, dim2, dim3, dim4;
+
+ usecoords = usecoords or false
+ replacevalues = replacevalues or {}
+
+ if f==nil then
+ error('pixelread_nifty: cannot read file '..filename)
+ return
+ end
+
+ local i1 = DicomObject:new();
+ i1:Read(image(1))
+ local ps = i1.PixelSpacing
+ local p1 = string.gsub(ps, '.*\\', '') + 0
+ local p2 = string.gsub(ps, '\\.*', '') + 0
+
+ header = f:read(352) -- read some parts of nifty header only
+ nxt = string.unpack(header, 'iA10A18ihA1A1')
+ nxt, dim0, dim1, dim2, dim3, dim4 = string.unpack(header, 'hhhhhhhh hhhhhhh hhh ffffffff ffffffff ii', nxt);
+ local nex,dsc,aux,q,s,q1,q2,q3,q4,q5,q6,sx1,sx2,sx3,sx4,sy1,sy2,sy3,sy4,sz1,sz2,sz3,sz4
+ = string.unpack(header, 'A80A24 hh ffffff ffff ffff ffff A16 A4', nxt);
+ local rx={-sx1/p1, -sy1/p1, sz1/p1}
+ local ry={-sx2/p2, -sy2/p2, sz2/p2}
+
+ local k,v
+
+ for i=1, #imagefiles do
+ i1:Read(image(i))
+ i1.SeriesInstanceUID = suid
+ i1.SOPInstanceUID = genuid()
+ for k,v in pairs(replacevalues) do
+ i1[k] = v
+ end
+ i1:SetImage(0, f:read(i1.Rows*i1.Columns*(i1.BitsAllocated/8)))
+ if usecoords then
+ local z = math.fmod(i, dim4)
+ i1.ImagePositionPatient = string.format('%.8g\\%.8g\\%.8g', -sx4-(z-1)*sx3, -sy4-(z-1)*sy3, sz4+(z-1)*sz3)
+ i1.ImageOrientationPatient = string.format('%.8g\\%.8g\\%.8g\\%.8g\\%.8g\\%.8g', rx[1], rx[2], rx[3], ry[1], ry[2], ry[3])
+ end
+ i1:AddImage()
+ end
+
+ f:close()
+end
+
+function append_nifty(to, from)
+ require "pack"
+
+ function pack(...)
+ return arg
+ end
+
+ local f = io.open(from, 'rb')
+ if f==nil then
+ error('append_nifty: cannot read file '..from)
+ end
+ local g = io.open(to, 'r+b')
+ if g==nil then
+ error('append_nifty: cannot update file '..to)
+ end
+
+ local header = g:read(352) -- read some parts of nifty header only
+ local headerkey = pack(string.unpack(header, 'iA10A18ihA1A1'))
+ local imagedimensions = pack(string.unpack(header, 'hhhhhhhh hhhhhhh hhh ffffffff ffffffff ii', headerkey[1]));
+ local nifty_extensions = pack(string.unpack(header, 'A80A24 hh ffffff ffff ffff ffff A16 A4', imagedimensions[1]))
+ table.remove(headerkey, 1)
+ table.remove(imagedimensions, 1)
+ table.remove(nifty_extensions, 1)
+
+ imagedimensions[1] = 4
+ if imagedimensions[5]==0 then
+ imagedimensions[5] = 2
+ else
+ imagedimensions[5] = imagedimensions[5]+1
+ end
+
+ f:read(352)
+ local data = f:read('*all')
+
+ g:seek('set', 0)
+ g:write(string.pack('iAAihAA', unpack(headerkey)))
+ g:write(string.pack('hhhhhhhh hhhhhhh hhh ffffffff ffffffff ii', unpack(imagedimensions)))
+ g:seek('end', 0)
+ g:write(data)
+
+ f:close()
+ g:close()
+end
+
+function slice_nifty(from, to, slice)
+ require "pack"
+
+ function pack(...)
+ return arg
+ end
+
+ local f = io.open(from, 'rb')
+ if f==nil then
+ error('slice_nifty: cannot read file '..from)
+ end
+
+ local header = f:read(352)
+ local headerkey = pack(string.unpack(header, 'iA10A18ihA1A1'))
+ local imagedimensions = pack(string.unpack(header, 'hhhhhhhh hhhhhhh hhh ffffffff ffffffff ii', headerkey[1]));
+ local nifty_extensions = pack(string.unpack(header, 'A80A24 hh ffffff ffff ffff ffff A16 A4', imagedimensions[1]))
+ table.remove(headerkey, 1)
+ table.remove(imagedimensions, 1)
+ table.remove(nifty_extensions, 1)
+ imagedimensions[1] = 3
+ imagedimensions[5] = 1
+
+ f:seek('set', 352+imagedimensions[2]*imagedimensions[3]*imagedimensions[4]*2*slice)
+ local data = f:read(imagedimensions[2]*imagedimensions[3]*imagedimensions[4]*2)
+ f:close()
+
+ local g = io.open(to, 'wb')
+ if g==nil then
+ error('slice_nifty: cannot write file '..to)
+ end
+ g:write(string.pack('iAAihAA', unpack(headerkey)))
+ g:write(string.pack('hhhhhhhh hhhhhhh hhh ffffffff ffffffff ii', unpack(imagedimensions)))
+ g:write(string.pack('AA hh ffffff ffff ffff ffff A A', unpack(nifty_extensions)))
+ g:write(string.rep('\000', 4)) -- empty minimal extension
+ g:write(data)
+
+ g:close()
+end
+
+function reread_interfile(imagefiles, headerfilename, replacevalues, shift, scale)
+ function image(i)
+ local t=imagefiles[i]
+ if type(t)=='table' then
+ return t[1] or t.name
+ else
+ return t
+ end
+ end
+ local function get(s, item)
+ return string.match(s, item .. ' := (.-)\n')
+ end
+
+ -- default parameters
+ replacevalues = replacevalues or {}
+ scale = scale or 1
+ shift = shift or 0
+
+ local f = io.open(headerfilename, 'rt')
+ if f==nil then
+ error('pixelread_interfile: cannot read header file '..headerfilename)
+ return
+ end
+ local h = f:read('*all')
+ f:close()
+
+ -- read SIRT specific interfile header, % is escape character
+ local datafilename = get(h, 'name of data file')
+ local numberformat = get(h, 'number format') or 'float'
+ local numberofbytesperpixel = get(h, 'number of bytes per pixel') or 4
+ local numberofdimensions = get(h, 'number of dimensions') or 3
+ local matrixsize = {}
+ matrixsize[1] = get(h, 'matrix size %[1%]')
+ matrixsize[2] = get(h, 'matrix size %[2%]')
+ matrixsize[3] = get(h, 'matrix size %[3%]')
+ scalingfactor = {}
+ scalingfactor[1] = get(h, 'scaling factor %(mm/pixel%) %[1%]')
+ scalingfactor[2] = get(h, 'scaling factor %(mm/pixel%) %[2%]')
+ scalingfactor[3] = get(h, 'scaling factor %(mm/pixel%) %[3%]')
+ firstpixeloffset = {}
+ firstpixeloffset[1] = get(h, 'first pixel offset %(mm%) %[1%]')
+ firstpixeloffset[2] = get(h, 'first pixel offset %(mm%) %[2%]')
+ firstpixeloffset[3] = get(h, 'first pixel offset %(mm%) %[3%]')
+
+ local fulldatafilename = string.match(headerfilename, '^(.*\\)') .. datafilename
+ local suid = genuid()
+
+ local i1 = DicomObject:new();
+ local i2 = DicomObject:new();
+ i1:Read(image(1))
+ i2:Read(image(#imagefiles))
+
+ local a, b
+ local ps = {}
+ local center = {}
+ local pos1 = {}
+ local pos2 = {}
+ a, b, ps[1], ps[2] = string.find(i1.PixelSpacing, '^(.-)\\(.-)$')
+ a, b, pos1[1], pos1[2], pos1[3] = string.find(i1.ImagePositionPatient, '^(.-)\\(.-)\\(.-)$')
+ a, b, pos2[1], pos2[2], pos2[3] = string.find(i2.ImagePositionPatient, '^(.-)\\(.-)\\(.-)$')
+
+ center[1] = pos1[1] + ((i1.Rows -1)/2) * ps[1]
+ center[2] = pos1[2] + ((i1.Columns-1)/2) * ps[2]
+ center[3] = (pos1[3] + pos2[3])/2
+
+ for i=1, #imagefiles do
+ i1.SeriesInstanceUID = suid
+ i1.SOPInstanceUID = genuid()
+ i1.PixelSpacing = string.format('%f\\%f', scalingfactor[1], scalingfactor[2])
+ i1.Rows = matrixsize[1]
+ i1.Columns = matrixsize[2]
+ for k,v in pairs(replacevalues) do
+ i1[k] = v
+ end
+
+ -- slice and write input data
+ local f = io.open(fulldatafilename, 'rb')
+ f:seek('set', matrixsize[1]*matrixsize[2]*numberofbytesperpixel*(i-1))
+ i1:SetImage(0, f:read(matrixsize[1]*matrixsize[2]*numberofbytesperpixel), scale)
+ f:close()
+
+ i1.ImagePositionPatient = string.format('%.8g\\%.8g\\%.8g',
+ firstpixeloffset[1] + 0*center[1],
+ firstpixeloffset[2] + 0*center[2],
+ firstpixeloffset[3] + center[3] + shift - scalingfactor[3] * (i-1))
+ i1.SliceLocation = string.format('%.8g',
+ firstpixeloffset[3] + center[3] + shift - scalingfactor[3] * (i-1))
+ i1.InstanceNumber = i
+
+ i1:AddImage()
+ end
+end
+
diff --git a/lua/niftytest.lua b/lua/niftytest.lua
new file mode 100644
index 0000000..05a4ceb
--- /dev/null
+++ b/lua/niftytest.lua
@@ -0,0 +1,28 @@
+--[[add the following 2 lines to dicom.ini for automatic processing of series sent to SMOOTH after 10 s
+[lua]
+importconverter0 = if Association.Called=="SMOOTH" then script("process series after 10 by lua/niftytest.lua " .. Data.PatientID .. ":" .. Data.SeriesInstanceUID) end
+]]--
+
+require('niftyutil')
+require('niftydicom')
+
+command_line = command_line or 'testpat:1.3.12.2.1107.5.1.4.28001.4.0.3215162956741568'
+print('processing', command_line)
+
+local t = split(command_line, ':')
+x = DicomObject:new()
+x.QueryRetrieveLevel = 'IMAGE'
+x.PatientID = t[1]
+x.SeriesInstanceUID = t[2]
+x.SOPInstanceUID = ''
+y = dicomquery('CONQUESTSRV1', 'IMAGE', x)
+names = {}
+for i=0, #y-1 do
+ names[i+1] = y[i].PatientID .. ':' .. y[i].SOPInstanceUID
+end
+table.sort(names)
+
+write_nifty(names, 'c:\\data\\test.nii')
+osexecute('"C:\\Program Files\\NiftyReg\\bin\\reg_tools.exe" -in c:\\data\\test.nii -out c:\\data\\test.nii -smoG 2 2 1')
+
+reread_nifty(names, 'c:\\data\\test.nii', false, {SeriesDescription = 'Smoothed by reg_tools', SeriesNumber = 100})
diff --git a/lua/niftyutil.lua b/lua/niftyutil.lua
new file mode 100644
index 0000000..07a29f7
--- /dev/null
+++ b/lua/niftyutil.lua
@@ -0,0 +1,115 @@
+--[[
+Some utility functions used by nifty.lua and niftydicom.lua
+-- 20130701 mvh added secdiff
+-- 20130702 mvh catch missing input file in filecopy
+-- 20130715 mvh filecopy uses small buffer when copying entire file; added secadd
+-- 20130823 mvh added filesize()
+]]
+
+function split(str, pat)
+ local t = {}
+ local fpat = "(.-)" .. pat
+ local last_end = 1
+ local s, e, cap = str:find(fpat, 1)
+ while s do
+ if s ~= 1 or cap ~= "" then
+ table.insert(t,cap)
+ end
+ last_end = e+1
+ s, e, cap = str:find(fpat, last_end)
+ end
+ if last_end <= #str then
+ cap = str:sub(last_end)
+ table.insert(t, cap)
+ end
+ return t
+end
+
+function osexecute(cmd)
+ local t=os.clock()
+ local prog = string.gsub(cmd, "\.exe.*$", "")
+ prog = string.gsub(prog, "^.*\\", "");
+ print('running', cmd)
+ if system then
+ system(cmd)
+ else
+ os.execute(cmd)
+ end
+ print(prog, 'took', os.clock()-t, 's')
+end
+
+function fileexists(f)
+ local h = io.open(f)
+ if h==nil then
+ return false
+ else
+ h:close()
+ return true
+ end
+end
+
+function filesize(f)
+ local h = io.open(f)
+ if h==nil then
+ return 0
+ else
+ local s = h:seek('end', 0)
+ h:close()
+ return s
+ end
+end
+
+
+function filecopy(a, b, start, length)
+ start = start or 0
+
+ local f=io.open(a, 'rb')
+ if f==nil then
+ print('cannot open source file for copying: ' .. a)
+ return
+ end
+
+ local g=io.open(b, 'wb')
+ if g==nil then
+ print('cannot open target file for copying: ' .. b)
+ return
+ end
+
+ f:seek('set', start)
+ while true do
+ local block=f:read(length or 8192)
+ if not block then break end
+ g:write(block)
+ if length then break end
+ end
+
+ f:close();
+ g:close();
+end
+
+function secdiff(initialTime,finalTime)
+ local initialHour=tonumber(string.sub(initialTime,1,2)) *3600
+ local initialMinute=tonumber(string.sub(initialTime,3,4))*60
+ local initialSecond=tonumber(string.sub(initialTime,5,99))
+
+ local finalHour=tonumber(string.sub(finalTime,1,2))*3600
+ local finalMinute=tonumber(string.sub(finalTime,3,4))*60
+ local finalSecond=tonumber(string.sub(finalTime,5,99))
+
+ local totalInitialTime=initialHour+initialMinute+initialSecond
+ local totalFinalTime=finalHour+finalMinute+finalSecond
+ return totalFinalTime-totalInitialTime
+end
+
+function secadd(initialTime, s_to_add)
+ local initialHour=tonumber(string.sub(initialTime,1,2)) *3600
+ local initialMinute=tonumber(string.sub(initialTime,3,4))*60
+ local initialSecond=tonumber(string.sub(initialTime,5,99))
+
+ local totalInitialTime=initialHour+initialMinute+initialSecond + s_to_add
+ return string.format('%02d%02d%02f',
+ math.floor(totalInitialTime/3600),
+ math.floor((totalInitialTime%3600)/60),
+ totalInitialTime%60)
+end
+
diff --git a/lua/overview.lua b/lua/overview.lua
new file mode 100644
index 0000000..0ad3f92
--- /dev/null
+++ b/lua/overview.lua
@@ -0,0 +1,323 @@
+--[[
+
+#Conquest DICOM server scripting overview
+
+Brief demo of _all_ scripting options in **Conquest Dicom Server**.
+If you run this script from **ZeroBrane Studio**, you can put
+breakpoints on any line, single step, inspect data with the mouse,
+and display arbitrary data and enter arbitrary commands to the
+DICOM Server in the `Local console` window.
+
+In version 1.4.17 for Windows the following modules are
+embedded in the executable:
+-- `require('socket')`
+-- `require('pack')`
+]]
+
+-- for demo fill the global variable Data which normally contains
+-- the incoming DICOM object. You can read from disk or from the
+-- server using a PatientID:SOPInstanceUID format.
+-- readdicom('c:\\t.dcm') -- from disk
+readdicom('0009703828:1.3.46.670589.5.2.10.2156913941.892665340.475317')
+-- Note that in this demo Data is undefined until after this call
+-- I.e., Data:Read() is not allowed as first call
+
+-- association info available from lua:
+print(Association.Calling, Association.Called, Association.Thread, Association.ConnectedIP)
+
+-- all counters available from lua:
+print('------ All counters --------')
+print(Global.StartTime)
+print(Global.TotalTime)
+print(Global.LoadTime)
+print(Global.ProcessTime)
+print(Global.SaveTime)
+print(Global.ImagesSent)
+print(Global.ImagesReceived)
+print(Global.ImagesSaved)
+print(Global.ImagesForwarded)
+print(Global.ImagesExported)
+print(Global.ImagesCopied)
+print(Global.IncomingAssociations)
+print(Global.EchoRequest)
+print(Global.C_Find_PatientRoot)
+print(Global.C_Move_PatientRootNKI)
+print(Global.C_Move_PatientRoot)
+print(Global.C_Find_StudyRoot)
+print(Global.C_Move_StudyRootNKI)
+print(Global.C_Move_StudyRoot)
+print(Global.C_Find_PatientStudyOnly)
+print(Global.C_Find_ModalityWorkList)
+print(Global.C_Move_PatientStudyOnlyNKI)
+print(Global.C_Move_PatientStudyOnly)
+print(Global.UnknownRequest)
+print(Global.CreateBasicFilmSession)
+print(Global.DeleteBasicFilmSession)
+print(Global.ActionBasicFilmSession)
+print(Global.SetBasicFilmSession)
+print(Global.CreateBasicFilmBox)
+print(Global.ActionBasicFilmBox)
+print(Global.SetBasicFilmBox)
+print(Global.DeleteBasicFilmBox)
+print(Global.SetBasicGrayScaleImageBox)
+print(Global.SetBasicColorImageBox)
+print(Global.GuiRequest)
+print(Global.ImagesToGifFromGui)
+print(Global.ImagesToDicomFromGui)
+print(Global.ExtractFromGui)
+print(Global.QueryFromGui)
+print(Global.DeleteImageFromGui)
+print(Global.DeletePatientFromGui)
+print(Global.DeleteStudyFromGui)
+print(Global.DeleteStudiesFromGui)
+print(Global.DeleteSeriesFromGui)
+print(Global.MovePatientFromGui)
+print(Global.MoveStudyFromGui)
+print(Global.MoveStudiesFromGui)
+print(Global.MoveSeriesFromGui)
+print(Global.AddedFileFromGui)
+print(Global.DumpHeaderFromGui)
+print(Global.ForwardFromGui)
+print(Global.GrabFromGui)
+print(Global.DatabaseOpen)
+print(Global.DatabaseClose)
+print(Global.DatabaseQuery)
+print(Global.DatabaseAddRecord)
+print(Global.DatabaseDeleteRecord)
+print(Global.DatabaseNextRecord)
+print(Global.DatabaseCreateTable)
+print(Global.DatabaseUpdateRecords)
+print(Global.QueryTime)
+print(Global.SkippedCachedUpdates)
+print(Global.UpdateDatabase)
+print(Global.AddedDatabase)
+print(Global.NKIPrivateCompress)
+print(Global.NKIPrivateDecompress)
+print(Global.DownSizeImage)
+print(Global.DecompressJpeg)
+print(Global.CompressJpeg)
+print(Global.DecompressJpeg2000)
+print(Global.CompressJpeg2000)
+print(Global.DecompressedRLE)
+print(Global.DePlaned)
+print(Global.DePaletted)
+print(Global.RecompressTime)
+print(Global.gpps)
+print(Global.gppstime)
+
+-- all configuration items are available from lua (read/write)
+print(Global.NoDicomCheck)
+print(Global.DebugLevel)
+print(Global.ThreadCount)
+print(Global.OpenThreadCount)
+print(Global.EnableReadAheadThread)
+print(Global.WorkListMode)
+print(Global.StorageFailedErrorCode)
+print(Global.FailHoldOff)
+print(Global.RetryDelay)
+print(Global.QueueSize)
+print(Global.ForwardCollectDelay)
+print(Global.CacheVirtualData)
+print(Global.gJpegQuality)
+print(Global.gUseOpenJpeg)
+print(Global.FixKodak)
+print(Global.NumIndexing)
+print(Global.DoubleBackSlashToDB)
+print(Global.UseEscapeStringConstants)
+print(Global.EnableComputedFields)
+print(Global.FileCompressMode)
+print(Global.RootConfig)
+print(Global.BaseDir)
+print(Global.ConfigFile)
+print(Global.DicomDict)
+print(Global.AutoRoutePipe)
+print(Global.AutoRouteExec)
+print(Global.DroppedFileCompression)
+print(Global.IncomingCompression)
+print(Global.TransmitCompression)
+print(Global.DefaultNKITransmitCompression)
+print(Global.ArchiveCompression)
+print(Global.TestMode)
+print(Global.StatusString)
+
+print('------ Set a config item --------')
+Global.DebugLevel = 4
+
+print('----- Read any dicom.ini item -----')
+section = 'sscscp'; item = 'TCPPort'; default='';
+print(gpps(section, item, default))
+
+-- all command items are available from lua (read only)
+print('------ testing debug log (typically not shown) --------', 1234)
+debuglog('Command priority', Command.Priority)
+
+-- set Data storage
+print('------ test setting storage --------')
+Data.Storage = 'MAG2'
+print('You can only read/write storage in an import converter', Data.Storage);
+
+-- read/write data, create sequences, and write into sequences (if [] not passed, [0] is assumed)
+print('------ test read/write Data --------')
+Data.PatientName = Data.PatientID
+Data.ReferencedStudySequence = {}
+print('Number of elements in sequence', #Data.ReferencedStudySequence);
+print('This is a sequence: ', Data.ReferencedStudySequence);
+Data.ReferencedStudySequence[0].StudyInstanceUID = Data.StudyInstanceUID
+Data.ReferencedStudySequence.StudyInstanceUID = Data.StudyInstanceUID
+Data.ReferencedStudySequence[1].StudyInstanceUID = Data.StudyInstanceUID
+print(#Data.ReferencedStudySequence);
+print('This is a sequence item: ', Data.ReferencedStudySequence[0].StudyInstanceUID);
+
+-- delete items
+print('------ test delete item --------')
+Data.ReferencedStudySequence = nil
+print('This was a sequence: ', Data.ReferencedStudySequence);
+
+-- inspect dictionary (results in 16, 32 vs PatientID)
+print(dictionary('PatientID'))
+print(dictionary(16, 32))
+
+-- inspect sql definition (database, row) results in 16, 32 PatientID 64 SQL_STR DT_STR)
+print(get_sqldef(0, 0))
+
+-- send a script to conquest
+print('------ test conquest script call --------')
+script('nop this is an ImportConverter script') -- only works when Data defined
+Data:Script('nop this is an ImportConverter script running on a specified DICOM object')
+
+-- send a servercommand to conquest and read its result
+print('------ test conquest command call --------')
+print(servercommand('display_status:'))
+
+-- run executable in the background
+system('dgate.exe -?')
+
+-- get an item from ACRNEMA.MAP
+print('------ test reading ACRNEMA.MAP --------')
+print(get_amap(0))
+-- results in 'CONQUESTSRV1 127.0.0.1 5678 un'
+
+-- remap UIDs (in 1.4.17)
+print(changeuid('12jgkfjgfkgjax', 'aapnootmies'))
+print(changeuidback('aapnootmies'))
+print(changeuid('1.1'))
+print(changeuidback('1.2.826.0.1.3680043.2.135.734877.42238624.7.1359125302.31.0'))
+print(genuid())
+-- results in:
+-- [CONQUESTSRV1] aapnootmies
+-- [CONQUESTSRV1] 12jgkfjgfkgjax
+-- [CONQUESTSRV1] 1.2.826.0.1.3680043.2.135.734877.42238624.7.1359125302.31.0
+-- [CONQUESTSRV1] 1.1
+-- [CONQUESTSRV1] .... a new uid here ....
+-- To remap all uids use script('newuids') and reverse (1.4.17) with script('olduids')
+
+-- query the local database (also possible from CGI interface, if the database is setup in the CGI dicom.ini)
+print('------ test quering a database --------')
+print(dbquery('DICOMPatients', 'PatientNam', 'PatientID LIKE \'2%\'')[1][1])
+
+-- set and get pixels in the current image or any loaded image
+print('------ test reading and writing pixels --------')
+x=0; y=0; frame=0;
+print(getpixel(x, y, frame));
+setpixel(x, y, frame, getpixel(x, y, frame)*2+10);
+print(getpixel(x, y, frame));
+print(Data:GetPixel(x, y, frame))
+
+-- set and get rows and colums in the image
+print('------ test reading and writing rows and columns --------')
+a = getrow(Data.Rows / 2)
+a = Data:GetRow(Data.Rows / 2)
+print(a[0], a[1], a[2], a[3], a[128]);
+setcolumn(Data.Columns / 2, frame, a)
+Data:SetColumn(Data.Columns / 3, frame, a)
+
+-- get / set image as binary string, also allow efficient binary image conversion (1.4.17)
+a = getimage(frame); a = Data:GetImage(frame)
+setimage(frame, a)
+Data:SetImage(frame, a)
+
+-- get / set image as binary string with floats (1.4.17a)
+-- read a from a floating point image, i.e., it has 4 bytes per pixel, scale passed
+-- setimage(frame, a, 1000); Data:SetImage(frame, a, 1000)
+
+-- create/read/write/destroy a dicom object
+print('------ test create/read/write dicom object --------')
+a = newdicomobject()
+a = DicomObject:new() -- preferred notation in 1.4.17
+a.PatientID = 'test'
+writedicom(a, 'c:\\file1.dcm')
+b = newdicomobject()
+readdicom(b, 'c:\\file1.dcm')
+writeheader(b, 'c:\\file1.txt')
+a:Write('c:\\file2.dcm')
+a:Read('c:\\file2.dcm')
+a:Dump('c:\\file2.txt')
+a:GetPixel(x, y, z)
+a:SetPixel(x, y, z, value)
+a:GetRow(x, y, z)
+a:SetRow(x, y, z, table)
+a:GetColumn(x, y, z)
+a:SetColumn(x, y, z, table)
+deletedicomobject(a) -- not required: will be freed automatically
+-- a:free() -- also allowed in 1.4.17:
+
+-- query a dicomserver (returns a dicomobjectarray)
+print('------ test query a dicom server --------')
+b=newdicomobject(); b.PatientName = '*'; a=dicomquery('CONQUESTSRV1', 'PATIENT', b);
+print ('First query result has this patientname:', a[0].PatientName);
+-- deletedicomobject(a) -- not required: will be freed automatically
+
+-- delete data from local dicomserver (use with care)
+print('------ delete from dicom server --------')
+b=newdicomobject(); b.PatientID = 'hopedoesntexist'; dicomdelete(b);
+
+-- create a dicomobjectarray
+print('------ test creating dicom array --------')
+a=newdicomarray(); a[0].PatientID='a'; a[1].PatientID='b';
+-- in 1.4.17 also: a = DicomObject:newarray()
+
+-- read the filename of a dropped file if any
+print('------ test Filename variable --------')
+print('Is there a file dropped?', Filename)
+
+-- access to long and sequence VRs
+print('------ test reading / writing long VRs --------')
+y = Data:GetVR(0x7fe0, 0x10);
+print('Length of y', #y);
+y = getvr(0x7fe0, 0x10);
+setvr(0x7fe0, 0x10, y);
+Data:SetVR(0x7fe0, 0x10, y);
+-- where y is either a table starting at 0, or a dicomobjectarray for a sequence
+-- In 1.4.17 these command can also return a more efficient binary string:
+y = Data:GetVR(0x7fe0, 0x10, true);
+Data:SetVR(0x7fe0, 0x10, y);
+
+-- memory allocation debugging
+print('------ memory alloc check NOTE: CALL IS NOT THREAD SAFE --------')
+print(heapinfo());
+
+-- move
+print('------ testing a C-MOVE --------')
+AE = 'CONQUESTSRV1';
+b=newdicomobject(); b.PatientName = 'HEAD EXP2'; b.QueryRetrieveLevel = 'STUDY'; dicommove('CONQUESTSRV1', AE, b);
+b=newdicomobject(); b.PatientName = 'HEAD EXP2'; b.QueryRetrieveLevel = 'STUDY'; dicommove('CONQUESTSRV1', AE, b, 0, 'print(Global.StatusString)');
+
+-- sql
+print('------ testing an SQL statement --------')
+sql("CREATE TABLE UserTable (CounterID varchar(99), Val integer)");
+sql("INSERT INTO UserTable (CounterID,Val) VALUES ('CT',1) ON DUPLICATE KEY UPDATE Val=Val+1");
+
+-- sleep, delay in ms
+sleep(1000)
+
+-- enter object into server:
+x = DicomObject:new()
+x:Read('c:\\t.dcm'); x:AddImage() -- or addimage(x)
+
+-- special script command 'retry'
+print('------ testing retry script command --------')
+script('retry') -- when used in RejectedImageWorkListConverter0 and RejectedImageConverter0; will re-attempt to store the object after the script is done
+
+-- special script command 'defer'
+print('------ testing defer script command --------')
+script('defer') -- when used in an ExportConverter, the convert will re-attempt to process or forward the object later
diff --git a/lua/persistence.lua b/lua/persistence.lua
new file mode 100644
index 0000000..6330e8a
--- /dev/null
+++ b/lua/persistence.lua
@@ -0,0 +1,168 @@
+-- ---------------------
+-- persistence functions
+
+local write, writeIndent, writers, refCount;
+
+persistence =
+{
+ store = function (path, ...)
+ local file, e = io.open(path, "w");
+ if not file then
+ return error(e);
+ end
+ local n = select("#", ...);
+ -- Count references
+ local objRefCount = {}; -- Stores reference that will be exported
+ for i = 1, n do
+ refCount(objRefCount, (select(i,...)));
+ end;
+ -- Export Objects with more than one ref and assign name
+ -- First, create empty tables for each
+ local objRefNames = {};
+ local objRefIdx = 0;
+ file:write("-- Persistent Data\n");
+ file:write("local multiRefObjects = {\n");
+ for obj, count in pairs(objRefCount) do
+ if count > 1 then
+ objRefIdx = objRefIdx + 1;
+ objRefNames[obj] = objRefIdx;
+ file:write("{};"); -- table objRefIdx
+ end;
+ end;
+ file:write("\n} -- multiRefObjects\n");
+ -- Then fill them (this requires all empty multiRefObjects to exist)
+ for obj, idx in pairs(objRefNames) do
+ for k, v in pairs(obj) do
+ file:write("multiRefObjects["..idx.."][");
+ write(file, k, 0, objRefNames);
+ file:write("] = ");
+ write(file, v, 0, objRefNames);
+ file:write(";\n");
+ end;
+ end;
+ -- Create the remaining objects
+ for i = 1, n do
+ file:write("local ".."obj"..i.." = ");
+ write(file, (select(i,...)), 0, objRefNames);
+ file:write("\n");
+ end
+ -- Return them
+ if n > 0 then
+ file:write("return obj1");
+ for i = 2, n do
+ file:write(" ,obj"..i);
+ end;
+ file:write("\n");
+ else
+ file:write("return\n");
+ end;
+ file:close();
+ end;
+
+ load = function (path)
+ local f, e = loadfile(path);
+ if f then
+ return f();
+ else
+ return nil, e;
+ end;
+ end;
+}
+
+-- Private methods
+
+-- write thing (dispatcher)
+write = function (file, item, level, objRefNames)
+ writers[type(item)](file, item, level, objRefNames);
+end;
+
+-- write indent
+writeIndent = function (file, level)
+ for i = 1, level do
+ file:write("\t");
+ end;
+end;
+
+-- recursively count references
+refCount = function (objRefCount, item)
+ -- only count reference types (tables)
+ if type(item) == "table" then
+ -- Increase ref count
+ if objRefCount[item] then
+ objRefCount[item] = objRefCount[item] + 1;
+ else
+ objRefCount[item] = 1;
+ -- If first encounter, traverse
+ for k, v in pairs(item) do
+ refCount(objRefCount, k);
+ refCount(objRefCount, v);
+ end;
+ end;
+ end;
+end;
+
+-- Format items for the purpose of restoring
+writers = {
+ ["nil"] = function (file, item)
+ file:write("nil");
+ end;
+ ["number"] = function (file, item)
+ file:write(tostring(item));
+ end;
+ ["string"] = function (file, item)
+ file:write(string.format("%q", item));
+ end;
+ ["boolean"] = function (file, item)
+ if item then
+ file:write("true");
+ else
+ file:write("false");
+ end
+ end;
+ ["table"] = function (file, item, level, objRefNames)
+ local refIdx = objRefNames[item];
+ if refIdx then
+ -- Table with multiple references
+ file:write("multiRefObjects["..refIdx.."]");
+ else
+ -- Single use table
+ file:write("{\n");
+ for k, v in pairs(item) do
+ writeIndent(file, level+1);
+ file:write("[");
+ write(file, k, level+1, objRefNames);
+ file:write("] = ");
+ write(file, v, level+1, objRefNames);
+ file:write(";\n");
+ end
+ writeIndent(file, level);
+ file:write("}");
+ end;
+ end;
+ ["function"] = function (file, item)
+ -- Does only work for "normal" functions, not those
+ -- with upvalues or c functions
+ local dInfo = debug.getinfo(item, "uS");
+ if dInfo.nups > 0 then
+ file:write("nil --[[functions with upvalue not supported]]");
+ elseif dInfo.what ~= "Lua" then
+ file:write("nil --[[non-lua function not supported]]");
+ else
+ local r, s = pcall(string.dump,item);
+ if r then
+ file:write(string.format("loadstring(%q)", s));
+ else
+ file:write("nil --[[function could not be dumped]]");
+ end
+ end
+ end;
+ ["thread"] = function (file, item)
+ file:write("nil --[[thread]]\n");
+ end;
+ ["userdata"] = function (file, item)
+ file:write("nil --[[userdata]]\n");
+ end;
+}
+
+-- end persistence functions
+-- -------------------------
diff --git a/lua/query.lua b/lua/query.lua
new file mode 100644
index 0000000..45f7adf
--- /dev/null
+++ b/lua/query.lua
@@ -0,0 +1,10 @@
+-- query a dicom server
+
+a=DicomObject:new()
+a.QueryRetrieveLevel='STUDY'
+a.StudyInstanceUID=''
+a.StudyDate='20010101-20130404'
+b=dicomquery('CONQUESTSRV1', 'STUDY', a)
+for i=0, #b-1 do
+ print(b[i].StudyInstanceUID)
+end
diff --git a/lua/socket.lua b/lua/socket.lua
new file mode 100644
index 0000000..72af097
--- /dev/null
+++ b/lua/socket.lua
@@ -0,0 +1,133 @@
+-----------------------------------------------------------------------------
+-- LuaSocket helper module
+-- Author: Diego Nehab
+-- RCS ID: $Id: socket.lua 1418 2006-04-25 09:38:15Z 3rdparty $
+-----------------------------------------------------------------------------
+
+-----------------------------------------------------------------------------
+-- Declare module and import dependencies
+-----------------------------------------------------------------------------
+local base = _G
+local string = require("string")
+local math = require("math")
+local socket = require("socket.core")
+module("socket")
+
+-----------------------------------------------------------------------------
+-- Exported auxiliar functions
+-----------------------------------------------------------------------------
+function connect(address, port, laddress, lport)
+ local sock, err = socket.tcp()
+ if not sock then return nil, err end
+ if laddress then
+ local res, err = sock:bind(laddress, lport, -1)
+ if not res then return nil, err end
+ end
+ local res, err = sock:connect(address, port)
+ if not res then return nil, err end
+ return sock
+end
+
+function bind(host, port, backlog)
+ local sock, err = socket.tcp()
+ if not sock then return nil, err end
+ sock:setoption("reuseaddr", true)
+ local res, err = sock:bind(host, port)
+ if not res then return nil, err end
+ res, err = sock:listen(backlog)
+ if not res then return nil, err end
+ return sock
+end
+
+try = newtry()
+
+function choose(table)
+ return function(name, opt1, opt2)
+ if base.type(name) ~= "string" then
+ name, opt1, opt2 = "default", name, opt1
+ end
+ local f = table[name or "nil"]
+ if not f then base.error("unknown key (".. base.tostring(name) ..")", 3)
+ else return f(opt1, opt2) end
+ end
+end
+
+-----------------------------------------------------------------------------
+-- Socket sources and sinks, conforming to LTN12
+-----------------------------------------------------------------------------
+-- create namespaces inside LuaSocket namespace
+sourcet = {}
+sinkt = {}
+
+BLOCKSIZE = 2048
+
+sinkt["close-when-done"] = function(sock)
+ return base.setmetatable({
+ getfd = function() return sock:getfd() end,
+ dirty = function() return sock:dirty() end
+ }, {
+ __call = function(self, chunk, err)
+ if not chunk then
+ sock:close()
+ return 1
+ else return sock:send(chunk) end
+ end
+ })
+end
+
+sinkt["keep-open"] = function(sock)
+ return base.setmetatable({
+ getfd = function() return sock:getfd() end,
+ dirty = function() return sock:dirty() end
+ }, {
+ __call = function(self, chunk, err)
+ if chunk then return sock:send(chunk)
+ else return 1 end
+ end
+ })
+end
+
+sinkt["default"] = sinkt["keep-open"]
+
+sink = choose(sinkt)
+
+sourcet["by-length"] = function(sock, length)
+ return base.setmetatable({
+ getfd = function() return sock:getfd() end,
+ dirty = function() return sock:dirty() end
+ }, {
+ __call = function()
+ if length <= 0 then return nil end
+ local size = math.min(socket.BLOCKSIZE, length)
+ local chunk, err = sock:receive(size)
+ if err then return nil, err end
+ length = length - string.len(chunk)
+ return chunk
+ end
+ })
+end
+
+sourcet["until-closed"] = function(sock)
+ local done
+ return base.setmetatable({
+ getfd = function() return sock:getfd() end,
+ dirty = function() return sock:dirty() end
+ }, {
+ __call = function()
+ if done then return nil end
+ local chunk, err, partial = sock:receive(socket.BLOCKSIZE)
+ if not err then return chunk
+ elseif err == "closed" then
+ sock:close()
+ done = 1
+ return partial
+ else return nil, err end
+ end
+ })
+end
+
+
+sourcet["default"] = sourcet["until-closed"]
+
+source = choose(sourcet)
+
diff --git a/lua/test.lua b/lua/test.lua
new file mode 100644
index 0000000..1d0a931
--- /dev/null
+++ b/lua/test.lua
@@ -0,0 +1,70 @@
+require "pack"
+dofile('nifty.lua')
+
+-- query all series
+x=DicomObject:new()
+x.QueryRetrieveLevel='SERIES'
+x.PatientID='VeiCat'
+x.SOPInstanceUID=''
+x.SeriesInstanceUID=''
+x.SeriesTime=''
+y=dicomquery('CONQUESTSRV1', 'SERIES', x)
+
+-- select and sort all longer series on time
+t = {}
+for i=0,#y-1 do
+ -- query just to count
+ z=DicomObject:new()
+ z.QueryRetrieveLevel='IMAGE'
+ z.PatientID=y[i].PatientID
+ z.SOPInstanceUID=''
+ z.SeriesInstanceUID=y[i].SeriesInstanceUID
+ u=dicomquery('CONQUESTSRV1', 'IMAGE', z)
+ if #u>20 then
+ table.insert(t, {y[i].SeriesInstanceUID, y[i].SeriesTime})
+ end
+end
+table.sort(t, function(a, b) return a[2]<b[2] end)
+
+-- this will will log all converted slices
+f = io.open('converted\\' .. x.PatientID .. '_timestamps.txt', 'wt')
+
+start = 0;
+for i=1, #t do
+ names = {}
+ outnames = {}
+
+ -- query to get AcquisitionTime and InstanceUID for each slice
+ z=DicomObject:new()
+ z.QueryRetrieveLevel='IMAGE'
+ z.PatientID=x.PatientID
+ z.SOPInstanceUID=''
+ z.SeriesInstanceUID=t[i][1]
+ z.AcquisitionTime=''
+ u=dicomquery('CONQUESTSRV1', 'IMAGE', z)
+ for j=0,#u-1 do
+ names[j+1] = {u[j].PatientID..':'..u[j].SOPInstanceUID, u[j].AcquisitionTime}
+ end
+
+ -- sort slices on acquisitiontime
+ table.sort(names, function(a, b) return a[2]<b[2] end)
+
+ -- tag each slice with a sequence number
+ for j=1,#names do
+ names[j][3] = j+start-1
+ outnames[j] = string.format('converted\\%s_%05d.nii', x.PatientID, j+start-1)
+ end
+ start = start + #u
+
+ print(unpack(names[1]))
+ write_nifty(names, outnames, 3) -- outnames table --> mode where each slice is converted
+
+ -- log the processed data
+ for j=1,#names do
+ names[j]=table.concat(names[j], ',')
+ end
+ f:write(table.concat(names, '\n'))
+ f:write('\n\n')
+end
+
+f:close();
diff --git a/lua/test2.lua b/lua/test2.lua
new file mode 100644
index 0000000..922adee
--- /dev/null
+++ b/lua/test2.lua
@@ -0,0 +1,3 @@
+Data:Read('c:\\t.dcm')
+readdicom('c:\\t.dcm')
+print(1)
diff --git a/lua/testanon.lua b/lua/testanon.lua
new file mode 100644
index 0000000..d8d95f4
--- /dev/null
+++ b/lua/testanon.lua
@@ -0,0 +1,6 @@
+readdicom('0009703828:1.3.46.670589.5.2.10.2156913941.892665340.475317')
+Data.Dump('image_in.txt')
+dofile('lua/anonymize_script.lua')
+Data.Dump('image_anonymized.txt')
+dofile('lua/deanonymize_script.lua')
+Data.Dump('image_restored.txt')
\ No newline at end of file
diff --git a/lua/testload.lua b/lua/testload.lua
new file mode 100644
index 0000000..8e6b320
--- /dev/null
+++ b/lua/testload.lua
@@ -0,0 +1,26 @@
+-- high load test of a dicom server
+t = os.clock()
+
+if p==nil then
+ for j=1,3 do servercommand("luastart:p="..j..";dofile('c:/dicomserver/lua/testload.lua')") end
+ return
+end
+
+x = DicomObject:new()
+x:Read('c:\\t.dcm')
+--x:Script('compression jl')
+for i=0, 1000 do
+ x.SOPInstanceUID = genuid()..p
+ if (i%1000)==0 then x.SeriesInstanceUID = genuid()..p end
+ if (i%1000)==0 then x.StudyInstanceUID = genuid()..p end
+ x:Script('forward to CONQUESTSRV1 channel *')
+ --x:AddImage()
+ print(i)
+
+-- b=newdicomobject(); b.PatientName = '*'; a=dicomquery('CONQUESTSRV1', 'PATIENT', b);
+-- print ('First query result has this patientname:', a[0].PatientName);
+--
+-- b=newdicomobject(); b.PatientName = 'HEAD EXP2'; b.QueryRetrieveLevel = 'STUDY'; dicommove('CONQUESTSRV1', 'DENCOMROUTER', b, 0, 'print(Global.StatusString)');
+end
+
+print('*** time lapse', os.clock()-t)
diff --git a/lua/welcome.lua b/lua/welcome.lua
new file mode 100644
index 0000000..7eccdde
--- /dev/null
+++ b/lua/welcome.lua
@@ -0,0 +1,11 @@
+--[[ These are sample scripts that can be run by [Conquest DICOM server](http://forum.image-systems.biz/viewforum.php?f=33).
+You need to use version 1.4.17beta or later for this to work and copy
+mobdebug.lua from the .
+
+- Switch to a standalone Conquest interpreter by going to `Project | Lua Interpreter | Conquest DICOM Utility`.
+- Connect to a running Conquest server by going to `Project | Lua Interpreter | Conquest DICOM Server`.
+
+- Open one of the following scripts:
+ - [livecoding](+/livecoding.lua): a simple live coding script
+ - Run this script using `Project | Run as Scratchpad`.
+--]]
diff --git a/lua/wxsample.lua b/lua/wxsample.lua
new file mode 100644
index 0000000..9c38598
--- /dev/null
+++ b/lua/wxsample.lua
@@ -0,0 +1,43 @@
+require('wx')
+
+frame = wx.wxFrame(wx.NULL, wx.wxID_ANY, "wxLua Minimal Demo",
+ wx.wxDefaultPosition, wx.wxSize(450, 450),
+ wx.wxDEFAULT_FRAME_STYLE)
+
+-- create a simple file menu
+local fileMenu = wx.wxMenu()
+fileMenu:Append(wx.wxID_EXIT, "E&xit", "Quit the program")
+-- create a simple help menu
+local helpMenu = wx.wxMenu()
+helpMenu:Append(wx.wxID_ABOUT, "&About",
+ "About the wxLua Minimal Application")
+
+-- create a menu bar and append the file and help menus
+local menuBar = wx.wxMenuBar()
+menuBar:Append(fileMenu, "&File")
+menuBar:Append(helpMenu, "&Help")
+-- attach the menu bar into the frame
+frame:SetMenuBar(menuBar)
+
+-- create a simple status bar
+frame:CreateStatusBar(1)
+frame:SetStatusText("Welcome to wxLua.")
+
+-- connect the selection event of the exit menu item to an
+-- event handler that closes the window
+frame:Connect(wx.wxID_EXIT, wx.wxEVT_COMMAND_MENU_SELECTED,
+ function (event) frame:Close(true) end )
+-- connect the selection event of the about menu item
+frame:Connect(wx.wxID_ABOUT, wx.wxEVT_COMMAND_MENU_SELECTED,
+ function (event)
+ wx.wxMessageBox('This is the "About" dialog of the Minimal wxLua sample.',
+ "About wxLua",
+ wx.wxOK + wx.wxICON_INFORMATION,
+ frame)
+ end )
+
+-- finally, show the frame window
+frame:Show(true)
+
+wx.wxGetApp():MainLoop()
+
diff --git a/nkiqrsop.cpp b/nkiqrsop.cpp
new file mode 100644
index 0000000..7ffa5a5
--- /dev/null
+++ b/nkiqrsop.cpp
@@ -0,0 +1,9086 @@
+/*
+19990317 ljz NKI-specific code
+19990903 ljz Implemented NKI MaxRowColumn VR in DCO
+19990906 ljz Improved implementation of MaxRowColumn
+19991022 ljz Changed the root of NKI-made UIDs to the official one supplied by
+ Medical Connections(UK): 1.2.826.0.1.3680043.2.135.1066.xxxxxxxxxx
+19991122 ljz Added NKI-CompressionMode 2: safer, with CRC checks
+20000131 ljz Regardless the FileCompressMode in Dicom.ini, always send images
+ compressed (mode=2) when communicating with an NKI application.
+20001105 mvh Fixed where malloc and new were mixed (vr->data)
+20001106 mvh Use delete [] operation for vr->Data
+20001106 mvh Temporary fix of BC leak in CompressNKI and DecompressNKI
+20001120 mvh Fix bug - vr->data was reallocated without changing vr->length
+20001127 ljz Fix: Crashes happened when more than one 'ServerChildThread' was
+ active. m_pDCO is wrongly shared by all threads !!
+20010424 mvh Plugged in faster and safer decompress
+20010426 ljz Fixed leak when connection is aborted
+20010429 mvh Interleaved CRC computation with compress code (factor 2 faster)
+ Added GetADDO to allow read ahead within calling program
+20010501 mvh Merged ljz's change of 20010426
+20010502 mvh Added extrabytes pointer to Read and RetrieveOn
+20010502 mvh Added vr(9999,0300)=SliceLimit: send at most so many slices
+20010502 mvh Changed this vr to (9999,0500)=SliceLimit
+20011219 ljz Added extra check in case other manufacturers than NKI use
+ VR (0x7fe0, 0x0010), such as ACUSON
+20020317 mvh Replace true by TRUE
+20020415 mvh Added error handling on ProcessDDO
+20020429 mvh fixed reporting of number of complete slices (now starts with 1)
+ return cancel status if C_STORE failed
+20020609 mvh Added compressor modes 3 and 4
+20020609 mvh Added VR (9999,0600): MaxCompressionLevel (default 2)
+ Note: This level (max of 4) is also used when downsizing
+20020613 ljz Exported DecompressNKI and CompressNKI
+20020619 ljz Damn! ELSCINT uses (0x7fe0, 0x0010) too (see modification on 20011219)
+ Extra check on zero-length pixeldata
+20020930 mvh Fixed SliceLimit VR
+20021016 mvh Removed __BORLANDC__ language construct - to fix downsize with BC55
+20021115 mvh Added Generic style retrieve classes; print error messages from c-move
+20030522 ljz Added function ComputeCRC
+20030605 ljz Fix in DecompressNKI: dgate crashed when DCMTK's 'storescu.exe' wants
+ to send an NKIcompressed image to dgate; it refuses to send the pixeldata!
+20030701 mvh QualifyOn now also has compression parameter; transfer syntax work in progress
+20030703 mvh Tested recompress functions
+20030704 mvh Disabled decompression in ProcessDDO for non-nki clients; is done by recompress
+ When downsizing use DecompressImage(); also supports JPEG; Removed MaybeRecompress
+ Recompression for NKI clients only when downsizing; otherwise as specified in acrnema.map
+20030705 mvh Moved recompression out of ProcessDDO into StandardRetrieveNKI::Read
+ Skip recompression to same level as incoming
+20030706 mvh Optional filename parameter for recompress (not used yet); set env for offis tools
+20030706 mvh Attach VRType to PDU's for implicit little endian support
+20030709 mvh Removed DCMDICPATH; is not needed
+20030819 mvh Allow longer filenames
+20030905 mvh Note: recompressfile; DecompressImageFile and CompressJPEGImageFile do not allow spaces in filename
+20040401 mvh Added Changed and ActualMode flags to compress routines; only give compress message if something changed
+ Set maxcompression to 4 for NKI send
+20040403 mvh Added own SaveDICOMDataObject as in dgate.cpp
+20040406 ljz Also copy TypeCode in DecompressNKI when converting (0x7fdf, 0x0010) to (0x7fe0, 0x0010)
+ Make TypeCode of (0x7fdf, 0x0010) OW instead of OB, because OFFIS refuses to compress OB
+20040406 mvh Always use EXPLICIT syntax for jpeg, fix v2 always use DUMP
+ Use -F +ti option for dcmdjpeg for writing to v2: creates raw dump, implicit
+ Refuse to jpeg compress V2 files and images != 16 bits; \n is all messages
+ Fix error handling of CompressJpegImage
+20040530 mvh Removed unused variable
+20040722 mvh Added "nj" compression: leaves JPEG as is; else MAXNKICOMPRESSION
+20041101 ljz Added built-in JPEG and RLE decompressor
+20041102 mvh Fix problem with external JPEG compression: clear transfer syntax prior
+ to save for OFFIS tools with DICOM_CHAPTER_10_EXPLICIT
+20041103 mvh Added k1,k2,k4,k8 compressors: downsize to 1024,512,256,128 pixels if bigger to start with
+20041112 mvh Called AE SERVER~xx in C-MOVE lets xx override outgoing compression as well
+ (e.g., call CONQUESTSRV1~k4 to always get images downsized to 256x256)
+20050102 mvh Added NOINTJPEG flag to allow compile through total.cxx
+20050103 mvh Changed include file to lower case (for linux)
+20050108 mvh Adapted for linux compile (work in progress)
+20050109 mvh Added configurable TCPIPTimeOut
+20050118 mvh replaced thread local storage under linux with variables in object
+20050119 mvh added rudimentary support to start external (de)compressors under linux
+20050121 mvh Changed filename to lower case
+20050122 mvh Improved external jpeg support under Linux: load dictionary, wait until ready
+20050130 mvh Added To8BitMonochrome and ToGif
+20050204 mvh Small fix in ToGif for non-square images; also interpret RescaleIntercept as float
+20050205 mvh Added counters for compression activity
+20050206 mvh Optimized downsizing: do not decompress if no downsizing to occur
+20050206 mvh Note: replaced thread local storage under linux with variables in object is INCORRECT
+ Under linux, the server now can also serve one at a time
+ Fix for color to gif; added limited auto scaling in 16 bits to gif
+20050211 mvh Removed need for thread local storage
+20051210 mvh Added "vX" compression (same as as is)
+20051217 mvh Use system() to call on offis apps in linux (now works)
+20051217 mvh Use new VR::ReAlloc method to replace data in VR; fixed 2 float warnings
+20051229 mvh Fixed several leaks in (jpeg)compression code; changed alloc for nki compression
+20051230 mvh Added +sr option to dcmcjpeg: compress without changing rescaleslope/intercept
+ This option is required for our viewers: slices must all have same rescale
+20060219 mvh Removed warning in writegif
+20060222 mvh Added extra checks (not on ID strings) to pass as NKI compressed data
+20060311 mvh dcmcjpeg opts string got truncated (thanks Rainer Libowski)
+ fixed unused CompressJPEGImageFile (wrong exe called)
+ external decompress temporary files now in printer_files (thanks Rainer Libowski)
+20060324 mvh Added StripGroup2 option to recompress; strip group 2 from outgoing c-stores if not compression "as" or "is"
+20060328 mvh Use IsAbstractSyntaxAccepted(iUID) to test if host accepts image
+20060402 mvh Fix crash when recieving or dropping jpeg compressed color images
+ Consider not removing transfer syntax (0x0002, 0x0010) prior to dcmdjpeg/dcmcjpeg
+ Would fix problem with external decoding color jpeg images
+20060402 mvh Changed IsAbstractSyntaxAccepted(iUID) test back (thanks Andrej Savelov)
+20060405 mvh That was not the problem
+20060618 mvh Tested IsAbstractSyntaxAccepted - seems to work. Removed need for min()
+20060619 mvh Do not remove transfer syntax before decompression (20060402 suggestion)
+ Maintain original object when decompression fails, changed wording of message
+ Only complain about internal decompressor for jpeg
+20070104 mvh Export automatic SaveDICOMDataObject
+20070113 mvh Never delete transfer syntax (was left in CompressJpegImage, solves coding error in jpeg store)
+ Tested with $c server debug command
+20070210 mvh Export MaybeDownsize and check on 0 for passed size
+20070307 mvh Added several debug prints in retrieve, e.g. at bail out because connection dropped
+20070308 bcb removed #include <wait.h> from DARWIN
+20070314 mvh Send 0000,1030 (MoveOriginatorAE) and 0000,1031 (MoveOriginatorMessageID) in SS->Write as result of Move
+20070315 mvh Merged bcb DARWIN stuff; Set TCPIPTimeOut for PDU that moves images
+20070316 mvh Added (color) ToBMP for convert_to_bmp; added level and window to ToGif and ToBMP
+20070407 mvh Use ~p1..9A..Z to override C-MOVE port (adds 1..36 to port number)
+20070902 mvh WriteGif now cpp
+20071027 mvh Added quotes around filenames passed to dcmdjpeg and dcmcjpeg: avoids errors with spaces in paths
+20071101 mvh Enabled JPEG compression and decompression of non-16 bit data
+20071104 mvh Added DecompressNon16BitsJpeg (default TRUE)
+20071105 mvh Restore image when dcmc/djpeg failed to start
+20080103 mvh Added mode 'uj': leave jpeg as is, otherwise uncompress
+ Added DecompressImage to recompress()
+20080820 mvh Solaris fix (do not use variable name SS)
+20081116 mvh Adapted for very large objects (use unsigned int for length)
+20081201 mvh Added JPG converter
+20081203 mvh Enabled internal decompressor for color, added frame extraction for jpg etc
+ Add frame extraction control = 0x09999,0x0201
+20090209 mvh Added QueryMoveScript callback; removed unused variable
+20090325 mvh Added RetrieveResult converter, impact on performance to be tested
+20090412 mvh Changed jpeg encode_image mode to correct BGR RGB mixup
+20090513 mvh Added modes 's0' to 's9' call script CompressionConverter0 to 9
+20090518 mvh Added modes ka, kb and kc to downsize to 64, 32 and 16
+20090921 mvh Added ExtractFrames
+20090927 mvh Stop jpg compression for PR SR and RT
+20091231 bcb Added HAVE_LIBJPEG (version 6c!) and HAVE_LIBJASPER for external library support (beta for now)
+ Changed char* to const char* and cast time_t as int for gcc4.2 warnings
+20100111 mvh Fixed downsize for 32 bits pixel; bcb const; cast of Time() to (int)
+20100112 mvh Merged
+20100113 mvh A few more errors in downsize for 32 bits
+20100116 mvh Fixed DecompressImage compile error if HAVE_LIBJPEG is defined
+20100118 mvh Added one missing else in CompressJPEG2K
+20100119 bcb The else was not really missing; added some const
+20100120 mvh Catch jpeg2000 configuration if HAVE_LIBJASPER not defined
+20100121 bcb+mvh Blocked out old jpeg decompressor if HAVE_LIBJPEG,
+ removed color checks as both decompressors do color now
+ mvh Made lossy to lossless switch a warning not error in CompressImage
+ Set mode to '1' instead of 1 after switch
+20100122 mvh Note: the HAVE_LIBJPEG code supresses RLE support
+20100122 mvh Added experimental C-CANCEL support for all C-MOVES
+20100123 mvh Added counters for jpeg2000
+20100124 mvh Added GetNumberOfFrames
+20100125 mvh GetPrivateProfileString -> MyGetPrivateProfileString
+20100126 mvh Include gpps.hpp
+20100207 mvh Fixed ExtractFrame(s) for frames packaged into pixel data without sequences
+20100209 mvh Run RetrieveResult also for non-nki clients
+20100210 bcb Fix memory leak
+20100214 mvh Merged
+20100223 bcb Combined DecompressImage and DecompressImageFile
+ Add FUJI_FIX for evil LittleEndianImplicit jpeg compressed images.
+20100224 bcb Added libopenjpeg to use in place of Jasper, fixed more warnings (-Wall)
+20100227 mvh After 1.4.16alpha3: crash when jpeg compressing RT object
+20100330 bcb Frames to LIBJPEG, JASPER, and OPENJPEG
+20100619 bcb Many fixes for leaks, allow both Jasper and openJPEG as a dicom.ini choice (not finished).
+20100703 mvh Merged; snprintf to _snprintf
+20100706 bcb Merged, replaced _snprintf with memcpy.
+20100721 mvh Merged back; fixed a few ascii to int conversions with atoi
+20100723 mvh Merged bcb fixes in new version of ToJPG
+20100728 bcb Installed RLE support with HAVE_LIBJPEG, used new deivr Get's and ChangeVR's
+20100815 mvh Merged; do not use GETUINT8 for US type; added space =TRUE to setting PixelSpacing
+ Simplified DecompressRLE
+20100815 mvh Fixed bug 30 in t=2127: YBR_FULL_422 images not passed to dcmcjpg
+20100823 mvh bcb moved that check to the right place
+20100824 mvh Pass local VariableVRs to script engine
+20100826 mvh bcb fixed lossy jpeg2000 for signed data
+20100901 mvh bcb Added fix for PlanarConfiguration=1 data
+20100905 mvh Removed file functions: now RecompressFile uses Recompress
+20100905 mvh Merged; Added UseBuiltInJPEG flag
+20100914 bcb Fixed RLE decode for frames, added Deplane, DecodePalette for regular and segmented palettes
+20100918 mvh Attempted merged (very difficult as fixes were made in older version)
+20100920 bcb Fixed warnings
+20100922 mvh Merged
+20100928 mvh Fixed ExtractFrame(s) for NKI compressed data
+20101003 mvh Added 9999,0900 script
+20101004 mvh Use updated gif codec; started on animated gif
+20101009 mvh Protected gif coder for out of memory
+20101018 mvh Swap BGR to RGB for ToJPG
+20100920 bcb Fixed j2k decompressing of j2k file instead of just the stream (used by Accusoft Pegasus).
+20100923 mvh ToJPG can be used to create MPG files using external tools
+20101116 bcb Add UL, UB, UI, and UE compression to fix big endian recieve, merged, warnings
+20101121 mvh Merged
+20101220 mvh Fixed color swap for jpg and bmp; fix deplane and depalette are called when needed
+20101227 mvh Fixed 'un' in bcb 'ui' etc code in recompress
+20110106 mvh Fix ToBMP for linux 64 bits (used long)
+20110119 mvh Use ExtendedPDU_Service to pass scripting state
+20110320 mvh Fix downsize & tojpg when #bytes in image is odd
+ Only apply RescaleIntercept for CT in tojp
+20110326 mvh Increased temp string in linux ExecHidden that caused decompress crash
+20110413 mvh Allow test of jpeg or rle decompression even if no group 0002 data
+20110414 mvh Moved jpeg decompression height errors to SystemDebug
+20110419 mvh normalized line endings; taken out superfluous prints
+20110423 mvh Fixed "UJ" broken when UI etc were introduced
+20110502 mvh always write bitstored 0x0028,0x0101 when writing highbit 0x0028,0x0102
+20110904 bcb Fixed J1 and J2 distiction
+20110926 mvh Added DcmConvertPixelData for tomono and crop
+20111010 mvh Fix in J1 and J2 distiction fix: '2' was not translated into 2 invalidating subs. tests
+20111011 mvh Fix in SaveDicomDataObject (archive): 'cannot rewrite .. in v2 format' led to a double DDO->Free
+20111018 mvh Added TempDir ini file option
+20111022 mvh Added private move command option 0x9999, 0a000 ConquestMoveOriginatorAE; let retrieveconverter work with command
+20111113 mvh Restored the original float DeYBRFULL code; the modified code did not work; read VR again, is used for deplane
+20120214 mvh Allow size==0 in DICOM to image conversion
+20120327 mvh Fix LossyQuality entry in dicom.ini for built-in JPEG compression
+20120401 mvh Fix in print (crashes when modality not passed)
+20120402 mvh Default UseBuiltInJpeg properly to 0
+20120624 mvh Set Header (0028,2110) to 01 after lossy compression
+20120624 mvh Do not modify bitsstored, highbit and numberofbits after compression
+20120628 mvh Some layout of debug prints
+20120630 mvh Reverse .dcm check (dicom if not .V2);
+ Pass lossy quality to CompressJPEGImage from compression string
+20120723 mvh Fixed 'l' or 'l' to 'l' or 'L' found by bcb
+20120918 ljz Fixed comparison with .v2 in SaveDICOMDataObject()
+20121208 mvh Block deplane if SamplesPerPixel is not 3
+20130218 mvh JPEG compression did not set right sopclass!!!!
+20130823 mvh Fixed lossy jpeg compression for 12 bits data
+20130920 ea Corrected the calculation of new pixel spacing in MaybeDownsize
+20131013 mvh Default UseBuiltInJPEG set to 1; added quality parameter to ToJPG
+*/
+
+#define bool BOOL
+#define true TRUE
+#define false FALSE
+#ifndef UNUSED_ARGUMENT
+#define UNUSED_ARGUMENT(x) (void)x
+#endif
+
+#include "dicom.hpp"
+#include "nkiqrsop.hpp"
+#include "dgate.hpp"
+#include "gpps.hpp"
+#include <time.h>
+
+#ifdef HAVE_LIBJPEG
+#include <jpeglib.h>
+#include <jerror.h>
+#include <setjmp.h>
+#endif
+#ifdef HAVE_LIBJASPER
+#include <jasper/jasper.h>
+#endif
+#ifdef HAVE_LIBOPENJPEG
+#include <openjpeg.h>
+#endif
+
+// JPEG2000 quality
+#ifndef DEFAULT_LOSSY
+#define DEFAULT_LOSSY "95"
+#endif
+#define DEFAULT_LOSSY_INT 95
+#define MIN_QUALITY 1
+
+int TCPIPTimeOut = 300; // timeout for TCP/IP in seconds
+
+int NKIPrivateCompress=0; // counters
+int NKIPrivateDecompress=0;
+int DownSizeImage=0;
+int DecompressJpeg=0;
+int CompressJpeg=0;
+int DecompressJpeg2000=0;
+int CompressJpeg2000=0;
+int DecompressedRLE=0;
+int DePlaned=0;
+int DePaletted=0;
+int RecompressTime=0;
+
+#define MAXNKICOMPRESSION 4
+
+static const unsigned int CRC32_table[256] = {
+ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
+ 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
+ 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
+ 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
+ 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
+ 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
+ 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
+ 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
+ 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
+ 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
+ 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
+ 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
+ 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
+ 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
+ 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
+ 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
+ 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
+ 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
+ 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
+ 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
+ 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
+ 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
+ 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
+ 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
+ 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
+ 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
+ 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
+ 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
+ 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
+ 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
+ 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
+ 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
+ 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
+ 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
+ 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
+ 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
+ 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
+ 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
+ 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
+ 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
+ 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
+ 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
+ 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
+};
+
+#ifdef HAVE_LIBJPEG
+extern int gJpegQuality;// The quality of the lossy jpeg or j2k image from dicom.ini.
+
+ /* Here's the extended error handler struct for libjpeg:
+ (from jpeg example.c)*/
+struct jerror_mgr
+{
+ struct jpeg_error_mgr pub; /* "public" fields */
+ jmp_buf setjmp_buffer; /* for return to caller */
+};
+typedef struct jerror_mgr * jerror_ptr;
+
+typedef struct
+{
+ struct jpeg_source_mgr pub; /* public fields */
+} jsource_mgr;
+
+typedef jsource_mgr * jsrc_ptr;
+#endif
+
+#ifdef HAVE_J2K
+#ifndef HAVE_LIBJPEG// Don't want it twice
+extern int gJpegQuality;// The quality of the lossy jpeg or j2k image from dicom.ini.
+#endif
+#endif
+#ifdef HAVE_BOTH_J2KLIBS
+extern int gUseOpenJpeg;// If we have both Jasper and OpenJPEG, it lets the dicom.ini choose.
+#endif
+
+#define CLRSPC_FAM_UNKNOWN 0
+#define CLRSPC_FAM_GRAYSCALE 1
+#define CLRSPC_FAM_RGB 2
+#define CLRSPC_FAM_YBR_FULL 3
+/*Skipped numbers for Jasper */
+#define CLRSPC_FAM_YCBCR_ICT 6
+#define CLRSPC_FAM_YCBCR_RCT 7
+#define CLRSPC_FAM_YCBCR_F422 8
+#define CLRSPC_FAM_YCBCR_422 9
+#define CLRSPC_FAM_YCBCR_420 10
+
+/* Following function used in 'dgate.cpp' when executing the commandline switch
+ '-fa'. This is when a dicomfile has to be stored in the dicomserver.
+ The problem is that filenames generated in 'dgatefn.cpp' may be not unique
+ if many files are dropped in the dicomserver. The static 'counter' intended
+ to solve this problem is reset to zero each time dgate is launched.
+ Now this 'counter' is initialized with a CRC of the filename.
+*/
+unsigned int ComputeCRC(char* pcData, int iNbChars)
+{ int i;
+ unsigned int uiCRC = 0;
+
+ for (i=0; i<iNbChars; i++)
+ uiCRC = CRC32_table[(unsigned char)uiCRC ^ (unsigned char)pcData[i]] ^ ((uiCRC >> 8) & 0x00FFFFFF);
+ return uiCRC;
+}
+
+/* Read and cache UseBuiltInDecompressor and DecompressNon16BitsJpeg variable from dicom.ini
+*/
+
+#ifndef RootConfig
+extern char RootConfig[];
+#endif
+#ifndef ConfigFile
+extern char ConfigFile[];
+#endif
+
+BOOL UseBuiltInDecompressor(BOOL *DecompressNon16BitsJpeg = NULL)
+{ char RootSC[64];
+ char Temp[128];
+ static int res=-1, dn16=1;
+
+ if (res==-1)
+ { MyGetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig,
+ (char*) RootSC, 64, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "UseBuiltInDecompressor", "1",
+ (char*) Temp, 128, ConfigFile);
+ res = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "UseBuiltInJPEG", "1",
+ (char*) Temp, 128, ConfigFile);
+ res = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "DecompressNon16BitsJpeg", "1",
+ (char*) Temp, 128, ConfigFile);
+ dn16 = atoi(Temp);
+ }
+
+ if (DecompressNon16BitsJpeg) *DecompressNon16BitsJpeg = dn16;
+ return(res);
+}
+
+/******************* NKI specific Retrieve Classes *************************/
+int CallImportConverterN(DICOMDataObject *DDO, int N, char *pszModality, char *pszStationName, char *pszSop, char *patid, ExtendedPDU_Service *PDU, char *Storage, char *Script);
+
+StandardRetrieveNKI::StandardRetrieveNKI()
+{
+}
+
+BOOL StandardRetrieveNKI :: Read (
+ ExtendedPDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ void *ExtraBytes)
+ {
+ UID MyUID, uid, iUID, AppUID ("1.2.840.10008.3.1.1.1");
+ VR *vr;
+ DICOMDataObject DDO;
+ Array < DICOMDataObject *> ADDO;
+ UINT Index;
+ BYTE IP [ 64 ], lPort [ 64 ], ACRNema [ 17 ], MyACR[17], Compress[64];
+ StandardStorage *SStorage;
+ DICOMDataObject *iDDO;
+ ExtendedPDU_Service NewPDU;
+ UINT16 Failed;
+ unsigned int iVrSliceLimit = 0xffffffff;
+ int status = 0;
+ UID TrnSyntaxUID;
+// int ContextID;
+ char *AcceptedCompress, *Compression;
+ char Called[20], Calling[20];
+ BOOL StripGroup2, Cancelled;
+
+ if (DCO)
+ {
+ vr = DCO->GetVR(0x9999, 0x0500);
+ if (vr && vr->Length)iVrSliceLimit = vr->GetUINT();
+ }
+
+ GetUID(MyUID);
+
+ if( ! PDU )
+ return ( FALSE );
+
+ if( ! DCO )
+ return ( FALSE );
+
+ vr = DCO->GetVR(0x0000, 0x0002);
+ SetUID(uid, vr);
+ if (!(MyUID == uid))
+ return ( FALSE );
+
+ strcpy(Calling, (char *)(((AAssociateAC *)PDU)->CallingApTitle));
+ while (Calling[strlen(Calling)-1]==' ') Calling[strlen(Calling)-1] = 0;
+
+ if (! CMoveRQ :: Read (DCO, PDU, &DDO) )
+ {
+ SystemDebug.printf("Retrieve: wrong command\n");
+ return ( FALSE ); // my SOP, but wrong command
+ }
+
+ NewPDU.AttachRTC(&VRType);
+ NewPDU.SetTimeOut(TCPIPTimeOut);
+
+ if (! QueryMoveScript (PDU, DCO, &DDO))
+ {
+ CMoveRSP :: Write (PDU, DCO, 0xc013, 0, 0, 0, 0, NULL );
+ SystemDebug.printf("Retrieve: operation blocked by script\n");
+ return ( TRUE );
+ }
+
+ vr = DCO->GetVR(0x0000, 0x0600);
+ if(!vr)
+ {
+ CMoveRSP :: Write ( PDU, DCO, 0xc001 , 0, 0, 0, 0, NULL );
+ SystemDebug.printf("Retrieve: move destination missing\n");
+ return ( TRUE );
+ }
+
+ memset((void*)ACRNema, 0, 17);
+ if(vr->Length > 16)
+ vr->Length = 16;
+ memcpy((void*)ACRNema, vr->Data, (int) vr->Length);
+ if(!vr->Length)
+ {
+ CMoveRSP :: Write ( PDU, DCO, 0xc002 , 0, 0, 0, 0, NULL );
+ SystemDebug.printf("Retrieve: move destination empty\n");
+ return ( TRUE );
+ }
+ if(ACRNema[vr->Length-1]==' ')
+ ACRNema[vr->Length-1] = '\0';
+
+ if(!QualifyOn(ACRNema, MyACR, IP, lPort, Compress))
+ {
+ CMoveRSP :: Write (PDU, DCO, 0xc003, 0, 0, 0, 0, NULL );
+ SystemDebug.printf("Retrieve: move destination not allowed or known\n: %s", ACRNema);
+ return ( TRUE );
+ }
+
+ vr = DCO->GetVR(0x9999, 0x0a00);
+ if (vr)
+ {
+ strncpy((char *)MyACR, (const char*)vr->Data, vr->Length);
+ MyACR[vr->Length] = 0;
+ }
+
+ if (! SearchOn (&DDO, &ADDO) )//bcb, mvh: fills ADDO, must delete before exit
+ {
+ CMoveRSP :: Write (PDU, DCO, 0xc004, 0, 0, 0, 0, NULL );
+ SystemDebug.printf("Retrieve: move search failed\n");
+ return ( TRUE );
+ }
+
+ if (iVrSliceLimit < 0xffffffff)
+ while (ADDO.GetSize() > iVrSliceLimit)
+ {
+ delete ADDO.Get(ADDO.GetSize()-1);
+ ADDO.RemoveAt(ADDO.GetSize()-1);
+ }
+
+ // If the called AE looks like SERVER~j2, then the last 2 characters override the outgoing compression set in ACRNEMA.MAP
+ strcpy(Called, (char *)(((AAssociateAC *)PDU)->CalledApTitle));
+ while (Called[strlen(Called)-1]==' ') Called[strlen(Called)-1] = 0;
+ Compression = strchr(Called, '~');
+ if (!Compression) Compression = (char *)Compress; else Compression++;
+
+ // If the called AE looks like SERVER~p2, then the last character overrides the outgoing port set in ACRNEMA.MAP
+ if (Compression[0]=='P' || Compression[0]=='p') // override port
+ {
+ sprintf((char *)lPort, "%d", atoi((char *)lPort)+Compression[1]-'0');
+ Compression= (char *)Compress; // use default compress
+ }
+
+ NewPDU.SetRequestedCompressionType((char *)Compression); // propose compression type
+
+ NewPDU.SetApplicationContext ( AppUID );
+ NewPDU.SetLocalAddress ( MyACR );
+ NewPDU.SetRemoteAddress ( ACRNema );
+
+ // Add all the Abstract Syntaxs we need
+
+ Index = 0;
+ while ( Index < ADDO.GetSize() )
+ {
+ vr = ADDO.Get ( Index ) -> GetVR(0x0008, 0x0016);
+ if(!vr)
+ {
+ delete ADDO.Get ( Index );
+ ADDO.RemoveAt ( Index );
+ }
+ else
+ {
+ SetUID ( iUID, vr );
+ NewPDU.AddAbstractSyntax ( iUID );
+ ++Index;
+ }
+ }
+
+ NewPDU.SetTimeOut(TCPIPTimeOut);
+
+ if (!NewPDU.Connect (IP, lPort))
+ {
+ CMoveRSP :: Write ( PDU, DCO, 0xc005 , 0, 0, 0, 0, NULL );
+ OperatorConsole.printf("Host '%s' did not accept the connection\n", ACRNema);
+ while(ADDO.GetSize())//bcb, was leak if fail?
+ {
+ delete ADDO.Get ( 0 );
+ ADDO.RemoveAt ( 0 );
+ }
+ return ( TRUE );
+ }
+
+
+ Index = 0;
+ Failed = 0;
+ Cancelled = FALSE;
+
+ while ( Index < ADDO.GetSize() )
+ {
+ if (Cancelled)
+ {
+ ++Failed;
+ delete ADDO.Get(Index);
+ ++Index;
+ continue;
+ }
+ else
+ {
+ if (PDU->Link.Poll())
+ {
+ OperatorConsole.printf("Recieved cancel request\n", ACRNema);
+ Cancelled = TRUE;
+ }
+ }
+
+ vr = ADDO.Get ( Index ) -> GetVR(0x0008, 0x0016);
+ SetUID ( iUID, vr );
+
+// ContextID = NewPDU.GetPresentationContextID(iUID);
+// if ( !ContextID )
+
+ if ( !NewPDU.IsAbstractSyntaxAccepted(iUID) )
+ {
+ ++Failed;
+ OperatorConsole.printf("Host '%s' will not accept image\n", ACRNema);
+ // Remote end did not accept this UID
+ }
+ else
+ {
+ AcceptedCompress = NewPDU.GetAcceptedCompressionType(iUID);
+ StripGroup2 = memicmp(AcceptedCompress, "as", 2)!=0 && memicmp(AcceptedCompress, "is", 2)!=0;
+
+ if ( !RetrieveOn (ADDO.Get(Index), &iDDO, &SStorage, DCO, &ADDO, ExtraBytes))
+ ++Failed;
+ else
+ {
+ // non NKI client
+ if (DCO==NULL)
+ recompress(&iDDO, AcceptedCompress, "", StripGroup2, PDU);
+
+ // NKI client has 2 vr's to control (re)compression
+ // 9999,0600=MaxSupportedCompression (old, nki only)
+ // 9999,0700=RequestedCompression (new, nki or jpeg)
+ else
+ {
+ char mode[16];
+ int MaxCompression=4;
+ char script[1024];
+ script[0]=0;
+
+ // compression from transfer syntax negotiation
+ strcpy(mode, AcceptedCompress);
+
+ // optional requested custom compression
+ vr = DCO->GetVR(0x9999, 0x0700);
+ if (vr)
+ {
+ strncpy(mode, (const char*)vr->Data, vr->Length);
+ mode[vr->Length] = 0;
+ }
+
+ // optional requested custom script
+ vr = DCO->GetVR(0x9999, 0x0900);
+ if (vr)
+ {
+ strncpy(script, (const char*)vr->Data, vr->Length);
+ script[vr->Length] = 0;
+ }
+
+ vr = DCO->GetVR(0x9999, 0x0600);
+ if (vr && vr->Length)MaxCompression = vr->GetUINT();
+ if (MaxCompression > 4) MaxCompression = 4;
+
+ // limit nki compression to MaxCompression
+ if ((mode[0]=='n' || mode[0]=='N') && (mode[1]!='j' && mode[1]!='J'))
+ if (atoi(mode+1) > MaxCompression)
+ mode[1] = MaxCompression + '0';
+
+ recompress(&iDDO, mode, "", StripGroup2, PDU);
+
+ if (script[0])
+ CallImportConverterN(iDDO, -1, NULL, NULL, NULL, NULL, PDU, NULL, script);
+ }
+
+ if(!SStorage->Write(&NewPDU, iDDO, DCO->GetVR(0x0000, 0x0110), (unsigned char *)Calling))
+ {
+ //++Failed;
+ // Remote end should accept this image. if it did
+ // not, then just bail out. Probably means the
+ // TCP/IP link has been dropped.
+ Failed += (ADDO.GetSize() - Index);
+
+ SystemDebug.printf("Retrieve: remote connection dropped after %d images, %d not sent\n", Index, Failed);
+
+ /* LJ: This also happens when CqDicom has had 'enough'
+ e.g. when retrieving properties. It caused a small
+ leak
+ */
+ status = 0xfe00; // mvh 20020429: return cancel status
+ delete iDDO;
+ break;
+ }
+ delete iDDO;
+ }
+ }
+
+ CMoveRSP :: Write ( PDU,
+ DCO,
+ 0xff00, ADDO.GetSize() - Index - 1,
+ (UINT16) Index+1, Failed, 0, // mvh 20020429: added +1
+ ADDO.Get ( Index ));
+
+
+ delete ADDO.Get(Index);
+
+ ++Index;
+ }
+
+
+ CMoveRSP :: Write ( PDU, DCO, status, 0, (UINT16) Index, Failed, 0, NULL ); // mvh 20020429: replaced 0 by status
+
+ // In case we broke out from above..
+
+ while ( Index < ADDO.GetSize() )
+ {
+ delete ADDO.Get(Index);
+ ++Index;
+ }
+
+
+ return ( TRUE );
+ }
+
+BOOL StandardRetrieveNKI :: Write (
+ PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ BYTE *ACRNema )
+ {
+ DICOMCommandObject *DCO;
+ DICOMDataObject *RDDO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! CMoveRQ :: Write ( PDU, DDO, ACRNema ) )
+ return ( FALSE );
+
+ CallBack ( NULL, DDO );
+
+ DCO = new DICOMCommandObject;
+
+ while ( PDU->Read ( DCO ) )
+ {
+ RDDO = new DICOMDataObject;
+
+ if (! (CMoveRSP :: Read ( DCO, PDU, RDDO) ) )
+ {
+ return ( FALSE );
+ }
+ if ( DCO->GetUINT16(0x0000, 0x0800) == 0x0101)
+ {
+ CallBack ( DCO, NULL );
+ delete RDDO;
+ if ( DCO->GetUINT16(0x0000, 0x0900) != 0x0000)
+ {
+ VR *vr;
+ while ((vr = DCO->Pop()))
+ {
+ delete vr;
+ }
+ delete DCO;
+ return ( FALSE );
+ }
+ delete DCO;
+ return ( TRUE );
+ }
+ CallBack ( DCO, RDDO );
+ delete RDDO;
+ delete DCO;
+ DCO = new DICOMCommandObject;
+ }
+
+ delete DCO;
+ return ( FALSE );
+ }
+
+BOOL PatientRootRetrieveNKI :: GetUID ( UID &uid )
+ {
+ uid.Set ( "1.2.826.0.1.3680043.2.135.1066.5.1.4.1.2.1.2" );
+ return ( TRUE );
+ }
+
+BOOL StudyRootRetrieveNKI :: GetUID ( UID &uid )
+ {
+ uid.Set ( "1.2.826.0.1.3680043.2.135.1066.5.1.4.1.2.2.2" );
+ return ( TRUE );
+ }
+
+BOOL PatientStudyOnlyRetrieveNKI :: GetUID ( UID &uid )
+ {
+ uid.Set ( "1.2.826.0.1.3680043.2.135.1066.5.1.4.1.2.3.2" );
+ return ( TRUE );
+ }
+
+BOOL PatientRootRetrieveGeneric :: GetUID ( UID &uid )
+ {
+ uid.Set ( "1.2.840.10008.5.1.4.1.2.1.2" );
+ return ( TRUE );
+ }
+
+BOOL StudyRootRetrieveGeneric :: GetUID ( UID &uid )
+ {
+ uid.Set ( "1.2.840.10008.5.1.4.1.2.2.2" );
+ return ( TRUE );
+ }
+
+BOOL PatientStudyOnlyRetrieveGeneric :: GetUID ( UID &uid )
+ {
+ uid.Set ( "1.2.840.10008.5.1.4.1.2.3.2" );
+ return ( TRUE );
+ }
+
+/************ NKI specific processing of a loaded image *************************/
+
+typedef struct
+{
+ unsigned int iOrgSize; /* NOTE: this is the number of short pixels !!!! */
+ unsigned int iMode;
+ unsigned int iCompressedSize; /* in bytes, not pixels */
+ unsigned int iOrgCRC;
+ unsigned int iCompressedCRC; /* Excluding this header */
+} NKI_MODE2;
+
+
+/* coder for NKI private compressed pixel data VR 0x7fdf,0x0010
+ arguments: dest = (in) points to area where compressed destination data is written (byte)
+ src = (in) points to uncompressed source data (short)
+ npixels = (in) number of pixels to compress
+ iMode = (in) type of compression (1 .. 4)
+
+ The return value is the number of bytes in the compressed data (maximal 3*npixels+10, typical 0.52*npixels)
+
+ if iMode == 1 then
+ - The first 4 bytes contain the number of short-int pixels
+ - The following 4 bytes contain iMode=1
+ - The rest is the compressed image
+
+ if iMode == 2 then
+ - The first 4 bytes contain the number of short-int pixels
+ - The following 4 bytes contain iMode=2
+ - The following 4 bytes contain the size of the compressed image (in bytes)
+ - The following 4 bytes contain the CRC of the original image
+ - The following 4 bytes contain the CRC of the compressed image
+ - The rest is the compressed image
+ - The compressed size will be even (padded by a zero if necessary).
+
+ if iMode == 3 then
+ - The first 4 bytes contain the number of short-int pixels
+ - The following 4 bytes contain iMode=3
+ - The rest is the compressed image, including 4 bit differences
+
+ if iMode == 4 then
+ - The first 4 bytes contain the number of short-int pixels
+ - The following 4 bytes contain iMode=4
+ - The following 4 bytes contain the size of the compressed image (in bytes)
+ - The following 4 bytes contain the CRC of the original image
+ - The following 4 bytes contain 0
+ - The rest is the compressed image, including 4 bit differences
+ - The compressed size will be even (padded by a zero if necessary).
+*/
+
+// optimized settings for the 4 bit run compressor (mode 3 and 4)
+
+#define MINZEROS 5 // shortest RLE (2 byte overhead, but breaks 4bit run)
+#define MIN4BIT 6 // shortest 4 bit run (6 bytes compressed to 5 bytes)
+
+// This internal routine converts an 8 bit difference string into a 4 bit one
+static signed char *recompress4bit(int n, signed char *dest)
+{ signed char *p, *q;
+ int val;
+
+ n = n & 0xfe;
+ dest -= n;
+ p = dest;
+ val = (((int)p[0])<<4) | (p[1]&15);
+ p += 2;
+ *dest++ = 0xc0;
+ *dest++ = n;
+ q = dest++;
+ n -= 2;
+ while(n>0)
+ { *dest++ = (((int)p[0])<<4) | (p[1]&15);
+ p += 2;
+ n -= 2;
+ }
+ q[0] = val;
+
+ return dest;
+}
+
+int nki_private_compress(signed char *dest, short int *src, int npixels, int iMode)
+{ unsigned int iCRC;
+ unsigned int iCRC2;
+ register int val, i, j;
+ NKI_MODE2* pHeader = (NKI_MODE2*)dest;
+
+ NKIPrivateCompress++;
+
+ /* Up till now only Mode=1 .. 4 are supported */
+ if ((iMode < 1) || (iMode > 4))
+ return 0;
+
+ /* Create the header */
+ pHeader->iOrgSize = npixels;
+ pHeader->iMode = iMode;
+ switch (iMode)
+ { case 1:
+ dest += 8;
+ break;
+ case 2:
+ dest += sizeof(NKI_MODE2);
+ break;
+ case 3:
+ dest += 8;
+ break;
+ case 4:
+ dest += sizeof(NKI_MODE2);
+ break;
+ }
+
+ /* Create the compressed image */
+
+ if (iMode == 1)
+ { *(short int *)dest = *src;
+ dest+=2;
+
+ npixels--;
+
+ do
+ { val = src[1] - src[0];
+ src++;
+
+ if (val == 0) /* run length-encode zero differences */
+ { for (i=2;; i++)
+ { if (i>=npixels || src[i-1]!=src[-1] || i==256)
+ { if (i==2)
+ *dest++=0;
+ else
+ { *dest++ = 0x80;
+ *dest++ = (i-1);
+ npixels -= (i-2);
+ src += (i-2);
+ }
+ break;
+ }
+ }
+ }
+ else if (val >= -64 && val <= 63) /* small difference coded as one byte */
+ { *dest = val;
+ dest++;
+ }
+ else if (val >= -0x3F00 && val <= 0x3EFF) /* large differences coded as two bytes */
+ { dest[0] = (val>>8) ^ 0x40;
+ dest[1] = val;
+ dest+=2;
+ }
+ else /* if very large differences code abs val as three bytes */
+ { *dest++ = 0x7F;
+ *dest++ = src[0]>>8;
+ *dest++ = src[0];
+ }
+ }
+ while (--npixels);
+ }
+
+ else if (iMode == 2)
+ { iCRC = 0;
+ iCRC2 = 0;
+
+ *(short int *)dest = val = *src;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char) val ] ^ ((iCRC2 >> 8));
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8));
+ iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char) val ] ^ ((iCRC >> 8));
+ iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char)(val>>8)] ^ ((iCRC >> 8));
+ dest+=2;
+ npixels--;
+
+ do
+ { val = src[1] - src[0];
+ src++;
+ iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char) src[0] ] ^ ((iCRC >> 8));
+ iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char)(src[0]>>8)] ^ ((iCRC >> 8));
+
+ if (val == 0) /* run length-encode zero differences */
+ { for (i=2;; i++)
+ { if (i>=npixels || src[i-1]!=src[-1] || i==256)
+ { if (i==2)
+ { *dest++=0;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ 0 ] ^ ((iCRC2 >> 8));
+ }
+ else
+ { *dest++ = 0x80;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ 0x80 ] ^ ((iCRC2 >> 8));
+ *dest++ = (i-1);
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (i-1)] ^ ((iCRC2 >> 8));
+ npixels -= (i-2);
+
+ for (j=0; j<i-2; j++)
+ { src++;
+ iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char) src[0] ] ^ ((iCRC >> 8));
+ iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char)(src[0]>>8)] ^ ((iCRC >> 8));
+ }
+ }
+ break;
+ }
+ }
+ }
+ else if (val >= -64 && val <= 63) /* small difference coded as one byte */
+ { *dest = val;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val ] ^ ((iCRC2 >> 8));
+ dest++;
+ }
+ else if (val >= -0x3F00 && val <= 0x3EFF) /* large differences coded as two bytes */
+ { dest[0] = (val>>8) ^ 0x40;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)dest[0] ] ^ ((iCRC2 >> 8));
+ dest[1] = val;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val ] ^ ((iCRC2 >> 8));
+ dest+=2;
+ }
+ else /* if very large differences code abs val as three bytes */
+ { dest[0] = 0x7F;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ 0x7f ] ^ ((iCRC2 >> 8));
+ val = src[0];
+ dest[1] = val>>8;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8));
+ dest[2] = val;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val ] ^ ((iCRC2 >> 8));
+ dest+=3;
+ }
+ }
+ while (--npixels);
+
+ pHeader->iCompressedSize = dest - (signed char*)pHeader - sizeof(NKI_MODE2);
+
+ /* Pad it to get an even length */
+ if (pHeader->iCompressedSize & 1)
+ { *dest++ = 0;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ 0] ^ ((iCRC2 >> 8));
+ pHeader->iCompressedSize++;
+ }
+
+ pHeader->iOrgCRC = iCRC;
+ pHeader->iCompressedCRC = iCRC2;
+ }
+
+ /* Create the compressed image - compressor with added 4 bit run */
+
+ else if (iMode == 3)
+ { int n4bit=0;
+ *(short int *)dest = *src;
+ dest+=2;
+ npixels--;
+
+ do
+ { val = src[1] - src[0];
+ src++;
+
+ if (val == 0) /* run length-encode zero differences */
+ { for (i=2;; i++)
+ { if (i>=npixels || src[i-1]!=src[-1] || i==256)
+ { if (i<=MINZEROS) /* too short run -> write zeros */
+ { for (j=0; j<i-1; j++)
+ { *dest++=0;
+ n4bit++;
+
+ if(n4bit>=254) /* maximum length 4 bit run */
+ { dest = recompress4bit(n4bit, dest);
+ n4bit = 0;
+ }
+ }
+ }
+ else
+ { if (n4bit>=MIN4BIT) /* end (and write) 4 bit run */
+ dest = recompress4bit(n4bit, dest);
+
+ n4bit=0;
+ *dest++ = 0x80;
+ *dest++ = (i-1);
+ }
+
+ npixels -= (i-2);
+ src += (i-2);
+ break;
+ }
+ }
+ }
+ else if (val >= -63 && val <= 63) /* small difference coded as one byte */
+ { if (val >= -8 && val <= 7)
+ { *dest++ = val;
+ n4bit++;
+
+ if(n4bit>=254) /* maximum length 4 bit run */
+ { dest = recompress4bit(n4bit, dest);
+ n4bit=0;
+ }
+ }
+ else if(n4bit>=MIN4BIT) /* end and write 4 bit run */
+ { j = val;
+ dest = recompress4bit(n4bit, dest);
+ n4bit=0;
+ *dest++ = j;
+ }
+ else
+ { *dest++ = val; /* end 4 bit run */
+ n4bit = 0;
+ }
+ }
+ else if (val >= -0x3F00 && val <= 0x3EFF) /* large differences coded as two bytes */
+ { j = val;
+
+ if(n4bit>=MIN4BIT) /* end (and write) 4 bit run */
+ dest = recompress4bit(n4bit, dest);
+
+ n4bit=0;
+ dest[0] = (j>>8) ^ 0x40;
+ dest[1] = j;
+ dest+=2;
+ }
+ else /* if very large differences code abs val as three bytes */
+ { j = src[0];
+
+ if(n4bit>=MIN4BIT) /* end (and write) 4 bit run */
+ dest = recompress4bit(n4bit, dest);
+
+ n4bit=0;
+ *dest++ = 0x7F;
+ *dest++ = j>>8;
+ *dest++ = j;
+ }
+ }
+ while (--npixels);
+ }
+
+ /* Create the compressed image - compressor with added 4 bit run and CRC */
+
+ else if (iMode == 4)
+ { int n4bit=0;
+ iCRC = 0;
+
+ *(short int *)dest = val = *src;
+ iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char) val ] ^ ((iCRC >> 8));
+ iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char)(val>>8)] ^ ((iCRC >> 8));
+ dest+=2;
+ npixels--;
+
+ do
+ { val = src[1] - src[0];
+ src++;
+ iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char) src[0] ] ^ ((iCRC >> 8));
+ iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char)(src[0]>>8)] ^ ((iCRC >> 8));
+
+ if (val == 0) /* run length-encode zero differences */
+ { for (i=2;; i++)
+ { if (i>=npixels || src[i-1]!=src[-1] || i==256)
+ { if (i<=MINZEROS) /* too short run -> write zeros */
+ { for (j=0; j<i-1; j++)
+ { *dest++=0;
+ n4bit++;
+
+ if(n4bit>=254) /* maximum length 4 bit run */
+ { dest = recompress4bit(n4bit, dest);
+ n4bit = 0;
+ }
+ }
+ }
+ else
+ { if (n4bit>=MIN4BIT) /* end (and write) 4 bit run */
+ dest = recompress4bit(n4bit, dest);
+
+ n4bit=0;
+ *dest++ = 0x80;
+ *dest++ = (i-1);
+ }
+
+ npixels -= (i-2);
+ for (j=0; j<i-2; j++)
+ { src++;
+ iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char) src[0] ] ^ ((iCRC >> 8));
+ iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char)(src[0]>>8)] ^ ((iCRC >> 8));
+ }
+ break;
+ }
+ }
+ }
+ else if (val >= -63 && val <= 63) /* small difference coded as one byte */
+ { if (val >= -8 && val <= 7)
+ { *dest++ = val;
+ n4bit++;
+
+ if(n4bit>=254) /* maximum length 4 bit run */
+ { dest = recompress4bit(n4bit, dest);
+ n4bit=0;
+ }
+ }
+ else if(n4bit>=MIN4BIT) /* end and write 4 bit run */
+ { j = val;
+ dest = recompress4bit(n4bit, dest);
+ n4bit=0;
+ *dest++ = j;
+ }
+ else
+ { *dest++ = val; /* end 4 bit run */
+ n4bit = 0;
+ }
+ }
+ else if (val >= -0x3F00 && val <= 0x3EFF) /* large differences coded as two bytes */
+ { j = val;
+
+ if(n4bit>=MIN4BIT) /* end (and write) 4 bit run */
+ dest = recompress4bit(n4bit, dest);
+
+ n4bit=0;
+ dest[0] = (j>>8) ^ 0x40;
+ dest[1] = j;
+ dest+=2;
+ }
+ else /* if very large differences code abs val as three bytes */
+ { j = src[0];
+
+ if(n4bit>=MIN4BIT) /* end (and write) 4 bit run */
+ dest = recompress4bit(n4bit, dest);
+
+ n4bit=0;
+ *dest++ = 0x7F;
+ *dest++ = j>>8;
+ *dest++ = j;
+ }
+ }
+ while (--npixels);
+
+ pHeader->iCompressedSize = dest - (signed char*)pHeader - sizeof(NKI_MODE2);
+
+ /* Pad it to get an even length */
+ if (pHeader->iCompressedSize & 1)
+ { *dest++ = 0;
+ pHeader->iCompressedSize++;
+ }
+
+ pHeader->iOrgCRC = iCRC;
+ pHeader->iCompressedCRC = 0;
+ }
+
+ return dest - (signed char*)pHeader;
+}
+
+int get_nki_private_decompressed_length(signed char *src)
+{ int npixels = *(int *)src;
+ return 2*npixels;
+}
+
+int get_nki_private_compress_mode(signed char *src)
+{ int mode = *(int *)(src+4);
+ return mode;
+}
+
+/* decoder for NKI private compressed pixel data - faster and safe version
+ arguments: dest = (in) points to area where destination data is written (short)
+ src = (in) points compressed source data (byte stream)
+ size = (in) number of bytes source data (safety)
+
+ The return value is the number of pixels that have been processed.
+
+ The compressed data looks like:
+ (number of pixels)-1 times:
+ OR 1 byte = LL 7 bits signed (difference pixel[1] - pixel[0]);
+ OR 2 bytes = HHLL 15 bits signed (difference pixel[1] - pixel[0]) xored with 0x4000;
+ OR 3 bytes = 7FHHLL 16 bits absolute pixel data if 15 bits difference is exceeded
+ OR 2 bytes = 80NN run length encode NN zero differences (max 255)
+for mode 3 and 4 added:
+ OR 2 bytes = CONN encode NN 4 bit differences (max 255)
+
+ Performance on typical CT or MRI is >2x compression and a very good speed
+
+ This code is not valid on HIGHENDIAN (high byte first) machines
+*/
+
+int nki_private_decompress(short int *dest, signed char *src, int size)
+{ int npixels, retvalue, mode, iMode, val, j;
+ NKI_MODE2* pHeader = (NKI_MODE2*)src;
+ unsigned int iCRC=0, iCRC2=0;
+ signed char *save, *end;
+
+ NKIPrivateDecompress++;
+
+ retvalue = npixels = pHeader->iOrgSize;
+ iMode = pHeader->iMode; // safety: this value is checked in case statement
+
+ if (npixels<1) return 0; // safety: check for invalid npixels value
+
+ /* Up till now only Mode=1, 2, 3, and 4 are supported */
+
+ switch (iMode)
+ { case 1:
+ src += 8; // mode 1 only has 8 bytes header: iOrgSize and iMode
+ end = src + size - 3; // for overflow check if we are close to end of input buffer
+
+ *dest = *(short int *)src;
+ src += 2;
+ npixels--;
+
+ do
+ { if (src > end) // check whether the last few messages fit in input buffer
+ { if (src<end+3) val = *src;
+ else val = 0;
+
+ if (val >= -64 && val <= 63) mode = 1; // 7 bit difference
+ else if (val==0x7f) mode = 3; // 16 bit value
+ else if ((val&0xff)==0x80) mode = 2; // run length encoding
+ else mode = 2;
+
+ if (src+mode > end+3)
+ return 0; // safety: overflow input data
+ }
+
+ val = *src;
+
+ if (val >= -64 && val <= 63) // 7 bit difference
+ { dest[1] = dest[0] + val;
+ dest++;
+ src++;
+ }
+ else if (val==0x7f) // 16 bit value
+ { dest[1] = val = ((int)(((unsigned char *)src)[1])<<8) + ((unsigned char*)src)[2];
+ dest++;
+ src+=3;
+ }
+ else if ((val&0xff)==0x80) // run length encoding
+ { mode = ((unsigned char *)src)[1];
+ npixels -= mode-1;
+ if (npixels<=0) return 0; // safety: overflow output data
+ do
+ { dest[1] = dest[0];
+ dest++;
+ }
+ while (--mode);
+ src+=2;
+ }
+ else
+ { signed short diff = ((val^0x40)<<8) + (unsigned char)(src[1]);
+ dest[1] = dest[0] + diff; // 15 bit difference
+ dest++;
+ src+=2;
+ }
+ }
+ while (--npixels);
+
+ break;
+
+ case 2:
+ src += sizeof(NKI_MODE2);
+ save = src;
+ end = src + pHeader->iCompressedSize - 3;
+
+ if (end > src + size - 3)
+ end = src + size - 3; // may occur if pHeader is corrupted
+
+ *dest = val = *(short int *)src;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8));
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8));
+ src+=2;
+
+ npixels--;
+
+ do
+ { if (src > end) // check whether the last few messages fit in input buffer
+ { if (src<end+3) val = *src;
+ else val = 0;
+
+ if (val >= -64 && val <= 63) mode = 1; // 7 bit difference
+ else if (val==0x7f) mode = 3; // 16 bit value
+ else if ((val&0xff)==0x80) mode = 2; // run length encoding
+ else mode = 2;
+
+ if (src+mode > end+3)
+ break; // safety: overflow input data
+ }
+
+ val = *src;
+
+ if (val >= -64 && val <= 63) // 7 bits difference
+ { dest[1] = val = dest[0] + val;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8));
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8));
+ dest++;
+ src++;
+ }
+ else if (val==0x7f) // 16 bit value
+ { dest[1] = val = ((int)(((unsigned char *)src)[1])<<8) + ((unsigned char*)src)[2];
+
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8));
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8));
+ dest++;
+ src+=3;
+ }
+ else if ((val&0xff)==0x80) // run length encoding
+ { mode = ((unsigned char *)src)[1];
+ npixels -= mode-1;
+ if (npixels<=0) break; // safety: overflow output data
+ do
+ { dest[1] = val = dest[0];
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8));
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8));
+ dest++;
+ }
+ while (--mode);
+ src+=2;
+ }
+ else
+ { signed short diff = ((val^0x40)<<8) + ((unsigned char *)src)[1];
+ dest[1] = val = dest[0] + diff; // 15 bit difference
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8));
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8));
+ dest++;
+ src+=2;
+ }
+ }
+ while (--npixels);
+
+ if (iCRC2 != pHeader->iOrgCRC) // if error in output CRC:
+ { src = save; // check input CRC
+ while (src < end)
+ { iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char)src[0]] ^ ((iCRC >> 8));
+ src++;
+ }
+
+ if (iCRC != pHeader->iCompressedCRC)
+ { //OperatorConsole.printf("NKI decompression: the file is corrupted\n");
+ retvalue=0;
+ }
+ else
+ { //OperatorConsole.printf("NKI private decompression: internal error\n");
+ retvalue=0;
+ }
+ }
+
+ break;
+
+ case 3:
+ src += 8; // mode 3 only has 8 bytes header: iOrgSize and iMode
+ end = src + size - 3; // for overflow check if we are close to end of input buffer
+
+ *dest = *(short int *)src;
+ src += 2;
+ npixels--;
+
+ do
+ { if (src > end) // check whether the last few messages fit in input buffer
+ { if (src<end+3) val = *src;
+ else val = 0;
+
+ if (val >= -63 && val <= 63) mode = 1; // 7 bit difference
+ else if (val==0x7f) mode = 3; // 16 bit value
+ else if ((val&0xff)==0x80) mode = 2; // run length encoding
+ else if ((val&0xff)==0xC0) mode = 2; // 4 bit encoding
+ else mode = 2;
+
+ if (src+mode > end+3)
+ return 0; // safety: overflow input data
+ }
+
+ val = *src;
+
+ if (val >= -63 && val <= 63) // 7 bit difference
+ { dest[1] = dest[0] + val;
+ dest++;
+ src++;
+ }
+ else if (val==0x7f) // 16 bit value
+ { dest[1] = val = ((int)(((unsigned char *)src)[1])<<8) + ((unsigned char*)src)[2];
+ dest++;
+ src+=3;
+ }
+ else if ((val&0xff)==0x80) // run length encoding
+ { mode = ((unsigned char *)src)[1];
+ npixels -= mode-1;
+ if (npixels<=0) return 0; // safety: overflow output data
+ do
+ { dest[1] = dest[0];
+ dest++;
+ }
+ while (--mode);
+ src+=2;
+ }
+ else if ((val&0xff)==0xC0) // 4 bit run
+ { mode = ((unsigned char *)src)[1];
+ npixels -= mode-1;
+ mode/=2;
+ src+=2;
+ if (npixels<=0) return 0; // safety: overflow output data
+ do
+ { val = *src++;
+ dest[1] = dest[0] + (val>>4);
+ dest++;
+ if (val&8) val |= 0xfffffff0; else val &= 0x0f;
+ dest[1] = dest[0] + val;
+ dest++;
+ }
+ while (--mode);
+ }
+ else
+ { signed short diff = ((val^0x40)<<8) + (unsigned char)(src[1]);
+ dest[1] = dest[0] + diff; // 15 bit difference
+ dest++;
+ src+=2;
+ }
+ }
+ while (--npixels);
+
+ break;
+
+ case 4:
+ src += sizeof(NKI_MODE2);
+ save = src;
+ end = src + pHeader->iCompressedSize - 3;
+
+ if (end > src + size - 3)
+ end = src + size - 3; // may occur if pHeader is corrupted
+
+ *dest = val = *(short int *)src;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8));
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8));
+ src += 2;
+ npixels--;
+
+ do
+ { if (src > end) // check whether the last few messages fit in input buffer
+ { if (src<end+3) val = *src;
+ else val = 0;
+
+ if (val >= -63 && val <= 63) mode = 1; // 7 bit difference
+ else if (val==0x7f) mode = 3; // 16 bit value
+ else if ((val&0xff)==0x80) mode = 2; // run length encoding
+ else if ((val&0xff)==0xC0) mode = 2; // 4 bit encoding
+ else mode = 2;
+
+ if (src+mode > end+3)
+ return 0; // safety: overflow input data
+ }
+
+ val = *src;
+
+ if (val >= -63 && val <= 63) // 7 bit difference
+ { dest[1] = val = dest[0] + val;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8));
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8));
+ dest++;
+ src++;
+ }
+ else if (val==0x7f) // 16 bit value
+ { dest[1] = val = ((int)(((unsigned char *)src)[1])<<8) + ((unsigned char*)src)[2];
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8));
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8));
+ dest++;
+ src+=3;
+ }
+ else if ((val&0xff)==0x80) // run length encoding
+ { mode = ((unsigned char *)src)[1];
+ npixels -= mode-1;
+ if (npixels<=0) return 0; // safety: overflow output data
+ do
+ { dest[1] = val = dest[0];
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8));
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8));
+ dest++;
+ }
+ while (--mode);
+ src+=2;
+ }
+ else if ((val&0xff)==0xC0) // 4 bit run
+ { mode = ((unsigned char *)src)[1];
+ npixels -= mode-1;
+ mode/=2;
+ src+=2;
+ if (npixels<=0) return 0; // safety: overflow output data
+ do
+ { val = *src++;
+ dest[1] = j = dest[0] + (val>>4);
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)j] ^ ((iCRC2 >> 8));
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(j>>8)] ^ ((iCRC2 >> 8));
+ dest++;
+ if (val&8) val |= 0xfffffff0; else val &= 0x0f;
+ dest[1] = j = dest[0] + val;
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)j] ^ ((iCRC2 >> 8));
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(j>>8)] ^ ((iCRC2 >> 8));
+ dest++;
+ }
+ while (--mode);
+ }
+ else
+ { signed short diff = ((val^0x40)<<8) + (unsigned char)(src[1]);
+ dest[1] = val = dest[0] + diff; // 15 bit difference
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8));
+ iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8));
+ dest++;
+ src+=2;
+ }
+ }
+ while (--npixels);
+
+ if (iCRC2 != pHeader->iOrgCRC) // if error in output CRC:
+ retvalue=0;
+
+ break;
+
+ default:
+ //OperatorConsole.printf("NKI private decompression: unsupported mode\n");
+ return 0;
+ }
+
+ return retvalue;
+}
+
+BOOL DecompressNKI(DICOMDataObject* pDDO)
+{ VR* pVR;
+ VR* pNewVR;
+ signed char* pCompressed;
+ unsigned int iDecompressedLength, iCompressedLength;
+
+ pVR = pDDO->GetVR(0x7fdf, 0x0010);
+ if (pVR)
+ { /* Are the 'normal' pixel-data also present? If so, then 'our' tag is not
+ made by us!
+ */
+ pNewVR = pDDO->GetVR(0x7fe0, 0x0010);
+ if (pNewVR)
+ return TRUE;
+
+ /* Acuson and Elscint use this tag: test whether we or they made it */
+ if ((pVR->Length > 6) &&
+ ((strncmp((char*)pVR->Data, "ACUSON", 6) == 0) ||
+ (strncmp((char*)pVR->Data, "ELSCIN", 6) == 0)))
+ return TRUE;
+
+ /* no data in our tag (always starts with 2 dwords): cannot be compresssed */
+ if (pVR->Length<=8)
+ return TRUE;
+
+ /* check compression level: if invalid it cannot be our data */
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ if (pVR->Length>8 && ((unsigned int*)pVR->Data)[1]>MAXNKICOMPRESSION)
+#else //Big Endian like Apple power pc
+ if (pVR->Length>8 && SwitchEndian(((unsigned int*)pVR->Data)[1])>MAXNKICOMPRESSION)
+#endif
+ return TRUE;
+
+ /* Decompress it */
+ pCompressed = ((signed char *)(pVR->Data));
+ if (!pCompressed)
+ return FALSE;
+
+ iCompressedLength = pVR->Length;
+ iDecompressedLength = get_nki_private_decompressed_length(pCompressed);
+ if (!iDecompressedLength)
+ return FALSE;
+
+ pNewVR = new VR(0x7fe0, 0x0010, iDecompressedLength, TRUE);
+ if (!pNewVR)
+ return FALSE;
+
+ if (!nki_private_decompress((short *)(pNewVR->Data), pCompressed, iCompressedLength))
+ { delete pNewVR;
+ return FALSE;
+ }
+
+ /* Push the new VR, and delete the old one */
+ pDDO->Push(pNewVR);
+ pDDO->DeleteVR(pVR);
+ }
+ return TRUE;
+}
+
+BOOL CompressNKI(DICOMDataObject* pDDO, int CompressMode /* = 2 */)
+{ VR* pVR;
+ VR* pNewVR;
+ signed char* pCompressed;
+ unsigned int iCompressedLength;
+
+ /* First check whether the image already contains 0x7fdf, 0x0010.
+ If so, compression was already done, or 'our' VR is occupied.
+ Also do not compress the 'ugly' variable-length sequence of pixeldata.
+ */
+ pVR = pDDO->GetVR(0x7fdf, 0x0010);
+ if (pVR)
+ return TRUE;
+
+ /* Pixeldata present? */
+ pVR = pDDO->GetVR(0x7fe0, 0x0010);
+ if (pVR && (pVR->Length != 0xffffffff) && (pVR->Length != 0x0))
+ { /* Compress it */
+ pCompressed = (signed char*) malloc((pVR->Length/2) * 3 + 10);
+ if (!pCompressed)
+ return FALSE;
+
+ iCompressedLength = nki_private_compress(pCompressed, (short int *)(pVR->Data), pVR->Length/2, CompressMode);
+ if (iCompressedLength & 0x01)
+ pCompressed[iCompressedLength++] = 0;
+
+ /* Create a new VR, and delete the old one */
+ pNewVR = new VR(0x7fdf, 0x0010, iCompressedLength, pCompressed);
+ pNewVR->TypeCode = pVR->TypeCode;
+ pDDO->Push(pNewVR);
+ pDDO->DeleteVR(pVR);
+ }
+ return TRUE;
+}
+
+/* Get a frame from a multi-frame object */
+
+BOOL ExtractFrame(DICOMDataObject* pDDO, unsigned int Frame)
+{// int rc;
+ unsigned int iNbFrames=1;
+ VR *pVR, *vrs;
+ Array < DICOMDataObject *> *pADDO;
+
+ iNbFrames = pDDO->Getatoi(0x0028, 0x0008);
+ if (iNbFrames<=1 || Frame>=iNbFrames || Frame<0) return FALSE;
+
+ DecompressNKI(pDDO);
+
+ /* PixelData */
+ pVR = pDDO->GetVR(0x7fe0, 0x0010);
+ if (!pVR) return FALSE;
+
+ pADDO = (Array<DICOMDataObject*>*)pVR->SQObjectArray;
+ if (pADDO==NULL)
+ { unsigned int size = pDDO->GetUINT(0x0028, 0x0010) * pDDO->GetUINT(0x0028, 0x0011) *
+ pDDO->GetUINT(0x0028, 0x0002) * pDDO->GetUINT(0x0028, 0x0101) / 8; // Assumes 8 bits byte
+ // note: uses bitstored instead of bitsallocated; no problem in practice
+
+ if (size * iNbFrames > pVR->Length) return FALSE;
+
+// repackage it crudeley but efficiently (the VR will be deleted shortly after anyway)
+ memcpy(pVR->Data, ((BYTE *)pVR->Data) + size*Frame, size);
+ pVR->Length = size;
+ }
+ else
+ { if (Frame>=pADDO->GetSize()-1) return FALSE;
+ Array < DICOMDataObject * > *SQE = new Array < DICOMDataObject * >;
+
+ DICOMDataObject *D = MakeCopy(pADDO->Get(0)); // basic offset table
+ SQE->Add(D);
+
+ vrs = D->GetVR(0xfffe, 0xe000); // basic offset table (may be zero length)
+ if (vrs->Length) vrs->Length = 4; // keep offset to first frame: will now be valid
+
+ D = MakeCopy(pADDO->Get(Frame+1)); // selected frame
+ SQE->Add(D);
+ // repackage it
+ pVR->Reset();// Say goodbye to old data.
+ pVR->SQObjectArray = (void*) SQE;// Connect it to the new array.
+ // No need to push, already in the dicom object
+ }
+
+ /* replace number of frames with 1 */
+ pVR = pDDO->GetVR(0x0028, 0x0008);
+ if (pVR)
+ { pVR->ReAlloc(2);
+ memcpy(pVR->Data, "1 ", 2);
+ }
+
+ return TRUE;
+}
+
+int GetNumberOfFrames(DICOMDataObject* pDDO)
+{ int iNbFrames = pDDO->Getatoi(0x0028, 0x0008);
+ return iNbFrames;
+}
+
+/* Crop frames from a multi-frame object */
+
+BOOL ExtractFrames(DICOMDataObject* pDDO, unsigned int FirstFrame, unsigned int LastFrame, int skip)
+{ //int rc;
+ unsigned int iNbFrames=1, tFrames;
+ VR *pVR, *vrs;
+ Array < DICOMDataObject *> *pADDO;
+
+ iNbFrames = pDDO->Getatoi(0x0028, 0x0008);
+ if (iNbFrames<=1 || FirstFrame>=iNbFrames || FirstFrame<0) return FALSE;
+ if (LastFrame>=iNbFrames || LastFrame<0) LastFrame = iNbFrames-1;
+ if (skip<1) skip = 1;
+
+ tFrames = (LastFrame - FirstFrame + 1)/skip;// How many do we need?
+ if (tFrames>iNbFrames) return FALSE;// More than we have?
+ if (tFrames<1) tFrames=1;// Must do at least 1.
+
+ int count=0;
+
+ DecompressNKI(pDDO);
+
+ /* PixelData */
+ pVR = pDDO->GetVR(0x7fe0, 0x0010);
+ if (!pVR) return FALSE;
+
+ pADDO = (Array<DICOMDataObject*>*)pVR->SQObjectArray;
+ if (pADDO==NULL)
+ { unsigned int size = pDDO->GetUINT(0x0028, 0x0010) * pDDO->GetUINT(0x0028, 0x0011) *
+ pDDO->GetUINT(0x0028, 0x0002) * pDDO->GetUINT(0x0028, 0x0101) / 8;
+ // note: uses bitstored instead of bitsallocated; no problem in practice
+
+#if 1
+ // repackage it crudeley but efficiently (the object will soon be sent and destroyed anyway)
+ while (FirstFrame <= LastFrame)
+ { if (size * FirstFrame > pVR->Length) return FALSE;
+ memcpy(((BYTE *)pVR->Data) + count*size, ((BYTE *)pVR->Data) + FirstFrame*size, size);
+ FirstFrame += skip;
+ count ++;
+ }
+ pVR->Length = size * count;
+#else
+ pVR->Length = size * count;*/
+ unsigned int tSize = tFrames * size; // How big in the end.
+ if (tSize & 01) tSize++;// No odd data!
+ if (!(nData = (BYTE *)malloc(tSize))) return FALSE;// our new correctly allocated memory.
+ nData[tSize - 1] = 0;//Doesn't hurt.
+ while (FirstFrame <= LastFrame)
+ { if (size * FirstFrame > tSize)
+ {
+ free(nData);
+ return FALSE;
+ }
+ memcpy( nData + (count * size), ((BYTE *)pVR->Data) + (FirstFrame * size), size);
+ FirstFrame += skip;
+ count ++;
+ }
+ pVR->Reset();// Say goodbye to old data.
+ pVR->Data = (void*)nData;// Give it the new data.
+ pVR->Length = size;// Tell it how long.
+ pVR->ReleaseMemory = TRUE;// Make it responsible for it
+#endif
+ }
+ else
+ { if (FirstFrame>=pADDO->GetSize()-1) return FALSE;
+
+ Array < DICOMDataObject * > *SQE = new Array < DICOMDataObject * >;
+
+ DICOMDataObject *D = MakeCopy(pADDO->Get(0)); // basic offset table
+ SQE->Add(D);
+
+ vrs = D->GetVR(0xfffe, 0xe000); // basic offset table (may be zero length)
+ if (vrs->Length) vrs->Length = 0; // lose offsets (easier)
+
+ while (FirstFrame <= LastFrame)
+ { if (FirstFrame>=pADDO->GetSize()-1) return FALSE;
+ D = MakeCopy(pADDO->Get(FirstFrame+1)); // selected frame
+ SQE->Add(D);
+ FirstFrame += skip;
+ }
+
+ // repackage it
+ pVR->Reset();// Say goodbye to old data.
+ pVR->SQObjectArray = (void*) SQE;// Connect it to the new array.
+ // No need to push, already in the dicom object
+
+ count = SQE->GetSize()-1;
+ }
+
+// replace number of frames with new count.
+ pVR = pDDO->GetVR(0x0028, 0x0008);
+/* I have large number of frames, may not work > 99 frames in, < 10 out. bcb
+ sprintf((char *)pVR->Data, "%d", count);// trailing 0 overwrite?
+ if (((char *)pVR->Data)[pVR->Length-1]==0) ((char *)pVR->Data)[pVR->Length-1] = ' ';
+ mvh bcb correct but replaced by something less ugly...
+*/
+ if (pVR)
+ { char str[20];
+ sprintf(str, "%d", count);
+ pVR->ReAlloc(strlen(str));
+ memcpy(pVR->Data, (BYTE *)str, pVR->Length);
+ if (((char *)pVR->Data)[pVR->Length-1]==0) ((char *)pVR->Data)[pVR->Length-1] = ' ';
+ }
+
+ pVR = new VR(0x200d, 0x3016, 0, (void *)NULL, FALSE);
+ if (pVR) pDDO->DeleteVR(pVR); // (temp) remove philips private pixel data
+
+ return TRUE;
+}
+
+/* Downsizing of pixeldata only when VR (0x9999, 0x0200) is present in the
+ DicomCommandObject. when VR (0x9999, 0x0201) is present, a single frame is extracted
+ NOTE: these VR's are NKI specific.
+ Note: changing a VR length leaves some memory unused, but will be freed soon after anyway
+*/
+
+int MaybeDownsize(DICOMDataObject* pDDO, DICOMCommandObject* pDCO, int size)
+{ int i, j;
+ VR *pVR1=NULL, *pVR2=NULL;
+ unsigned int iMaxRowsColumns=0;
+ unsigned short iRows, iColumns, iNewRows, iNewColumns, iDownsizeFactor;
+ char s[256];
+ char* pSeparator;
+ float fSpacingX, fSpacingY;
+ unsigned int iImageSize, iNbBytesPerPixel, iNbPixels, iSkip;
+ char* pcSrc;
+ char* pcDest;
+ short* psSrc;
+ short* psDest;
+ int* piSrc;
+ int* piDest;
+
+ if (pDCO)
+ { pVR1 = pDCO->GetVR(0x9999, 0x0200); /* MaxRowsColumns */
+ pVR2 = pDCO->GetVR(0x9999, 0x0201); /* Frame */
+ }
+ else
+ iMaxRowsColumns = size;
+
+ if (pVR1) iMaxRowsColumns = pVR1->GetUINT();
+
+ if (pVR2) ExtractFrame(pDDO, pVR2->GetUINT());
+
+ if (!iMaxRowsColumns)
+ return TRUE; /* Downsizing to zero doesn't make sense */
+
+ /* NumberOfFrames */
+ if(pDDO->Getatoi(0x0028, 0x0008) > 1) return FALSE;/* not implemented for multi-frame */
+
+ /* OK. Now check whether all necessary PixelData-info is present in pDDO */
+ iRows = pDDO->GetUINT16(0x0028, 0x0010);
+ iColumns = pDDO->GetUINT16(0x0028, 0x0011);
+ iNbPixels = iRows * iColumns;
+
+ if ((!iNbPixels) || /* Image must make sense */
+ ((iRows <= iMaxRowsColumns) &&
+ (iColumns <= iMaxRowsColumns))) /* Image is already 'small' enough */
+ return TRUE;
+
+ DownSizeImage++;
+
+ if (iRows >= iColumns)
+ { iDownsizeFactor = iRows / iMaxRowsColumns;
+ if (iRows % iMaxRowsColumns)
+ iDownsizeFactor ++;
+ }
+ else
+ { iDownsizeFactor = iColumns / iMaxRowsColumns;
+ if (iColumns % iMaxRowsColumns)
+ iDownsizeFactor ++;
+ }
+
+ pVR1 = pDDO->GetVR(0x0028, 0x0030); /* Pixelspacing */
+ if (!pVR1)
+ return TRUE;
+ strncpy(s, (const char*)pVR1->Data, pVR1->Length);
+ s[pVR1->Length] = 0;
+ fSpacingX = (float)(atof(s));
+ pSeparator = strchr(s, '\\');
+ if (pSeparator)
+ fSpacingY = (float)(atof(pSeparator + 1));
+ else
+ fSpacingY = fSpacingX;
+
+ if (!DecompressNKI(pDDO)) /* Pixeldata must first be decompressed */
+ return FALSE;
+
+ pVR1 = pDDO->GetVR(0x7fe0, 0x0010); /* Pixeldata */
+ if (!pVR1)
+ return TRUE;
+ iImageSize = pVR1->Length;
+ if ((iImageSize < iNbPixels) ||
+ (iImageSize % iNbPixels > 1)) /* allow 1 byte padding */
+ return TRUE; /* Image doesn't make sense */
+ iNbBytesPerPixel = iImageSize / iNbPixels;
+ if (iNbBytesPerPixel > 4)
+ return TRUE; /* Image is too beautiful to downsize! */
+
+ /* LETS DO IT !
+ The downsized image is stored in the same memory-block as the original one:
+ Just be sure to adjust the length-indicator. The image will be (re)compressed anyway
+ later on.
+ */
+
+ iNewRows = iRows / iDownsizeFactor;
+ if (!iNewRows)
+ iNewRows++;
+ iNewColumns = iColumns / iDownsizeFactor;
+ if (!iNewColumns)
+ iNewColumns++;
+ switch (iNbBytesPerPixel)
+ { case 1:
+ pcSrc = (char*)pVR1->Data;
+ pcDest = pcSrc;
+ for (i=0; i<iNewRows; i++)
+ { for (j=0; j<iNewColumns; j++)
+ { *pcDest++ = *pcSrc;
+ pcSrc += iDownsizeFactor;
+ }
+ pcSrc = (char*)pVR1->Data + iDownsizeFactor * iColumns * (i + 1);
+ }
+ break;
+ case 2:
+ psSrc = (short*)pVR1->Data;
+ psDest = psSrc;
+ for (i=0; i<iNewRows; i++)
+ { for (j=0; j<iNewColumns; j++)
+ { *psDest++ = *psSrc;
+ psSrc += iDownsizeFactor;
+ }
+ psSrc = (short*)pVR1->Data + iDownsizeFactor * iColumns * (i + 1);
+ }
+ break;
+ case 3:
+ pcSrc = (char*)pVR1->Data;
+ pcDest = pcSrc;
+ iSkip = (iDownsizeFactor - 1) * 3;
+ for (i=0; i<iNewRows; i++)
+ { for (j=0; j<iNewColumns; j++)
+ { *pcDest++ = *pcSrc++;
+ *pcDest++ = *pcSrc++;
+ *pcDest++ = *pcSrc++;
+ pcSrc += iSkip;
+ }
+ pcSrc = (char*)pVR1->Data + iDownsizeFactor * 3 * iColumns * (i + 1);
+ }
+ break;
+ case 4:
+ piSrc = (int*)pVR1->Data;
+ piDest = piSrc;
+ for (i=0; i<iNewRows; i++)
+ { for (j=0; j<iNewColumns; j++)
+ { *piDest++ = *piSrc;
+ piSrc += iDownsizeFactor;
+ }
+ piSrc = (int*)pVR1->Data + iDownsizeFactor * iColumns * (i + 1);
+ }
+ break;
+ }
+
+ /* FINALLY: adjust Rows, Columns, Pixelspacing and (the length of) PixelData */
+ pDDO->ChangeVR(0x0028, 0x0010, (UINT16)iNewRows, 'US');
+ pDDO->ChangeVR(0x0028, 0x0011, (UINT16)iNewColumns, 'US');
+
+ if (pSeparator)
+ sprintf(s, "%g\\%g", (iColumns*fSpacingY)/iNewColumns, (iRows*fSpacingX)/iNewRows);
+ else
+ sprintf(s, "%g", (iRows*fSpacingX)/iNewRows);
+ pDDO->ChangeVR(0x0028, 0x0030, s, 'DS', TRUE);
+
+ pVR1 = pDDO->GetVR(0x7fe0, 0x0010); // Pixeldata
+ pVR1->Length = iNewRows * iNewColumns * iNbBytesPerPixel;
+ return 2; // Downsizing actually occurred
+}
+
+/* Test if downsizing will occur */
+
+static int TestDownsize(DICOMDataObject* pDDO, DICOMCommandObject* pDCO, int size)
+{// VR* pVR;
+ unsigned int iMaxRowsColumns;
+ unsigned short iRows, iColumns;
+ int iNbPixels;
+
+ if (pDCO)
+ { iMaxRowsColumns = pDCO->GetUINT(0x9999, 0x0200);
+
+ if (!iMaxRowsColumns)
+ return FALSE; /* Downsizing to zero doesn't make sense */
+ }
+ else
+ iMaxRowsColumns = size;
+
+ /* OK. Now check whether all necessary PixelData-info is present in pDDO */
+ iRows = pDDO->GetUINT16(0x0028, 0x0010);
+
+ iColumns = pDDO->GetUINT16(0x0028, 0x0011);
+
+ iNbPixels = iRows * iColumns;
+
+ if ((!iNbPixels) || /* Image must make sense */
+ ((iRows <= iMaxRowsColumns) &&
+ (iColumns <= iMaxRowsColumns))) /* Image is already 'small' enough */
+ return FALSE;
+
+ return TRUE; /* image would be downsized */
+}
+
+BOOL ProcessDDO(DICOMDataObject** pDDO, DICOMCommandObject* pDCO, ExtendedPDU_Service *PDU)
+{ VR *pVR;
+ int dum;
+
+ if (pDCO) // nki clients
+ { /* pDCO possibly contains specifications of how the NKI clients
+ want the data the be sent/processed. Only downsize is
+ implemented for now.
+ */
+
+ pVR = pDCO->GetVR(0x9999, 0x0200); // MaxRowsColumns
+ if (pVR)
+ { if (TestDownsize(*pDDO, pDCO, 0))
+ { DecompressImage(pDDO, &dum); // will also decompress JPEG images
+
+ if (!MaybeDownsize(*pDDO, pDCO, 0)) // downsize
+ return FALSE;
+ }
+ }
+ }
+
+ // De-compression is left to recompress in StandardRetrieveNKI::Read
+ // but run RetrieveResultConverter if present
+
+ char dest[20];
+ memset(dest, 0, 20);
+ VR *vr;
+ if (pDCO)
+ { vr = pDCO->GetVR(0x0000, 0x0600);
+ if (vr) memcpy(dest, (char *)(vr->Data), vr->Length);
+ }
+ while (strlen(dest)>0 && dest[strlen(dest)-1]==' ') dest[strlen(dest)-1] = 0;
+
+// CallImportConverterN(*pDDO, 1300, NULL, dest, NULL, NULL, "calling", "called", NULL, NULL, VariableVRs);
+ CallImportConverterN(*pDDO, 1300, NULL, dest, NULL, NULL, PDU, NULL, NULL);
+ return TRUE;
+}
+
+/*************************************************************************************************/
+
+static void RgbToMono(unsigned char* pSrc, unsigned char* pDest, int iNbPixels)
+{ int i;
+
+ for (i=0; i<iNbPixels; i++)
+ pDest[i] = (pSrc[3*i] + pSrc[3*i+1] + pSrc[3*i+2] + 1)/3;
+}
+
+static bool CropImage(unsigned char* pSrc, unsigned char* pDest,
+ int iSizeX, int iSizeY, int iPixelSize,
+ int iStartX, int iEndX, int iStartY, int iEndY)
+{ int i, iSize;
+
+ if ((iStartX>=iSizeX) || (iEndX>=iSizeX) || (iStartX>iEndX) || (iStartX < 0))
+ return false;
+ if ((iStartY>=iSizeY) || (iEndX>=iSizeY) || (iStartX>iEndY) || (iStartY < 0))
+ return false;
+
+ pSrc = pSrc + (iStartY*iSizeX + iStartX) * iPixelSize;
+ iSize = (iEndX - iStartX + 1) * iPixelSize;
+ for (i=iStartY; i<=iEndY; i++)
+ { memmove(pDest, pSrc, iSize);
+ pSrc += iSizeX * iPixelSize;
+ pDest += iSize;
+ }
+ return true;
+}
+
+#define UNDEFINED_FLOAT 0
+
+void SetStringVR(VR **vr, int g, int e, const char *String);
+
+int DcmConvertPixelData(DICOMDataObject*pDDO, bool bConvertToMono, bool bCrop,
+ int iStartX, int iEndX, int iStartY, int iEndY,
+ float fPixelSizeX, float fPixelSizeY, float fPixelSizeZ)
+{ int i;
+ VR* pVR;
+ char s[100];
+ int iSizeX, iSizeY, iBitsAllocated;
+ int iNbSamplesPerPixel = 1, iNbFrames = 1;
+ int iSrcSliceSize, iDestSliceSize;
+ char *pSrc, *pDest, *pNextSrc;
+ char* pszGridFrameOffsetVector;
+
+ /* Anything to do? */
+ if ((bConvertToMono == false) && (bCrop == false))
+ return FALSE;
+
+ if (!pDDO)
+ return FALSE;
+
+ /* Get the slice-size */
+ pVR = pDDO->GetVR(0x0028,0x0010); // Rows
+ if (pVR)
+ { iSizeY = *((short*)pVR->Data);
+ pVR = pDDO->GetVR(0x0028,0x0011); // Columns
+ if (pVR)
+ { iSizeX = *((short*)pVR->Data);
+ pVR = pDDO->GetVR(0x0028,0x0100); // BitsAllocated
+ if (pVR)
+ { iBitsAllocated = *((short*)pVR->Data);
+ pVR = pDDO->GetVR(0x0028,0x0002); // SamplesPerPixel
+ if (pVR)
+ iNbSamplesPerPixel = *((short*)pVR->Data);
+ }
+ }
+ }
+ if (!pVR)
+ { return FALSE;
+ }
+ iSrcSliceSize = iDestSliceSize = iSizeX * iSizeY * iNbSamplesPerPixel * iBitsAllocated / 8;
+ if (bCrop)
+ iDestSliceSize = (iEndX - iStartX + 1) * (iEndY - iStartY + 1) * iNbSamplesPerPixel * iBitsAllocated / 8;
+ if (bConvertToMono)
+ iDestSliceSize /= 3;
+
+ /* Check whether ConvertToMonochrome is possible */
+ if (bConvertToMono)
+ { if ((iNbSamplesPerPixel != 3) || (iBitsAllocated != 8))
+ { return FALSE;
+ }
+ pVR = pDDO->GetVR(0x0028,0x0004); // PhotometricInterpretation
+ if (!pVR)
+ { return FALSE;
+ }
+ if (strncmp((char*)pVR->Data, "RGB", 3) != 0)
+ { return FALSE;
+ }
+ iNbSamplesPerPixel = 1;
+ }
+
+ /* Get the pixels */
+ pVR = pDDO->GetVR(0x7fe0,0x0010); // PixelData
+ if (!pVR)
+ { return FALSE;
+ }
+ pSrc = (char*)pVR->Data;
+
+ /* Maybe more than one frame */
+ pVR = pDDO->GetVR(0x0028,0x0008); // NumberOfFrames
+ if (pVR)
+ { strncpy(s, (char*)pVR->Data, pVR->Length);
+ s[pVR->Length] = 0;
+ iNbFrames = atoi(s);
+ }
+
+ /* The main loop */
+ pDest = pSrc;
+ for (i=0; i<iNbFrames; i++)
+ { pNextSrc = pSrc;
+
+ if (bConvertToMono)
+ { RgbToMono((unsigned char*)pNextSrc, (unsigned char*)pDest,
+ iSizeX * iSizeY);
+ pNextSrc = pDest;
+ }
+
+ if (bCrop)
+ { if (!CropImage((unsigned char*)pNextSrc, (unsigned char*)pDest,
+ iSizeX, iSizeY, iNbSamplesPerPixel * iBitsAllocated / 8,
+ iStartX, iEndX, iStartY, iEndY))
+ { return FALSE;
+ }
+ pNextSrc = pDest;
+ }
+
+ pSrc += iSrcSliceSize;
+ pDest += iDestSliceSize;
+ }
+
+
+ /* Fix the affected VRs */
+ pVR = pDDO->GetVR(0x7fe0,0x0010); // PixelData
+ pVR->Length = iNbFrames * iDestSliceSize;
+ if (pVR->Length & 0x01) pVR->Length ++;
+
+ if (bCrop)
+ { pVR = pDDO->GetVR(0x0028,0x0010); // Rows
+ *(short*)pVR->Data = (iEndY - iStartY + 1);
+ pVR = pDDO->GetVR(0x0028,0x0011); // Columns
+ *(short*)pVR->Data = (iEndX - iStartX + 1);
+ }
+
+ if (bConvertToMono)
+ { pVR = pDDO->GetVR(0x0028,0x0002); // SamplesPerPixel
+ *(short*)pVR->Data = 1;
+ pVR = pDDO->GetVR(0x0028,0x0004); // PhotometricInterpretation
+ free(pVR->Data);
+ pVR->Data = strdup("MONOCHROME2 ");
+ pVR->Length = 12;
+ }
+
+ if ((fPixelSizeX != UNDEFINED_FLOAT) && (fPixelSizeY != UNDEFINED_FLOAT))
+ { sprintf(s, "%f\\%f", fPixelSizeX, fPixelSizeY);
+ // pVR = NewStringVR(0x0028,0x0030, s); // PixelSpacing
+ SetStringVR(&pVR, 0x0008, 0x0030, s);
+ if (pDDO->GetVR(0x0028,0x0030))
+ pDDO->ReplaceVR(pVR);
+ else
+ pDDO->Push(pVR);
+ }
+ if ((fPixelSizeZ != UNDEFINED_FLOAT) && (iNbFrames > 1))
+ { pszGridFrameOffsetVector = (char*)malloc(50000);
+ strcpy(pszGridFrameOffsetVector, "0");
+ for (i=1; i<iNbFrames; i++)
+ sprintf(pszGridFrameOffsetVector + strlen(pszGridFrameOffsetVector), "\\%f", i*fPixelSizeZ);
+ // pVR = NewStringVR(0x3004,0x000c, pszGridFrameOffsetVector); // GridFrameOffsetVector
+ SetStringVR(&pVR, 0x3004, 0x000c, pszGridFrameOffsetVector);
+ if (pDDO->GetVR(0x3004,0x000c))
+ pDDO->ReplaceVR(pVR);
+ else
+ pDDO->Push(pVR);
+ }
+
+ return TRUE;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////
+// JPEG and NKI utility compression code
+///////////////////////////////////////////////////////////////////////////////////////////////
+
+#ifdef WIN32
+#include <windows.h>
+
+// Runs external executable hidden
+static BOOL ExecHidden(
+ const char *ProcessBinary, // name of executable
+ const char *Arg1, const char *Arg2, const char *Arg3, const char *Arg4) // arguments
+ {
+ PROCESS_INFORMATION PINFO;
+ STARTUPINFO SINFO;
+ SECURITY_ATTRIBUTES SA;
+ HANDLE hMap;
+ char CommandLine[1024];
+
+ memset((void*)&SINFO, 0, sizeof(STARTUPINFO));
+ SINFO.cb = sizeof(STARTUPINFO);
+ SINFO.wShowWindow = SW_HIDE;
+
+ SA.nLength = sizeof (SECURITY_ATTRIBUTES);
+ SA.lpSecurityDescriptor = NULL;
+
+ sprintf(CommandLine, "%s %s \"%s\" \"%s\" %s", ProcessBinary, Arg1, Arg2, Arg3, Arg4);
+ if(!CreateProcess(ProcessBinary, CommandLine, NULL, NULL, FALSE,
+ DETACHED_PROCESS, NULL /* "DCMDICTPATH=offis.dic\0\0" */, NULL, &SINFO, &PINFO))
+ {
+ OperatorConsole.printf("***Failed to create process: %s - error %d\n", ProcessBinary, GetLastError());
+ return ( FALSE );
+ }
+ else
+ {
+ WaitForSingleObject(PINFO.hProcess, INFINITE);
+ CloseHandle(PINFO.hThread);
+ CloseHandle(PINFO.hProcess);
+ }
+
+ return ( TRUE );
+ }
+#else
+
+#ifndef DARWIN
+#include <wait.h>
+#endif //DARWIN
+
+static BOOL ExecHidden(
+ const char *ProcessBinary, // name of executable
+ const char *Arg1, const char *Arg2, const char *Arg3, const char *Env) // arguments
+ {
+ char line[1024];
+ sprintf(line, "export %s;%s %s \"%s\" \"%s\"", Env, ProcessBinary, Arg1, Arg2, Arg3);
+ system(line);
+ return TRUE;
+ }
+#endif
+
+// Replaces PDU.SaveDICOMDataObject; automatically detects transfer syntax to use
+void SaveDICOMDataObject(char *Filename, DICOMDataObject* pDDO)
+ {
+ int len, has_dcm_extension=0, UseChapter10=FALSE, bForcedImplicit=FALSE;
+ VR *pVR;
+ char s[256];
+ PDU_Service PDU;
+
+ PDU.AttachRTC(&VRType);
+
+ len = strlen(Filename);
+ if (len>3)
+ has_dcm_extension = (stricmp(Filename+len-3, ".v2")!=0);
+
+ /* Type of save depends on file name extension is .dcm (UseChapter10)
+ and on the transfer syntax (not ImplicitLittleEndian, not
+ ExplicitLittleEndian and not ExplicitBigEndian)
+ */
+ pVR = pDDO->GetVR(0x0002, 0x0010); // TransferSyntaxUID
+ if (pVR && pVR->Data)
+ {
+ strncpy(s, (char*)pVR->Data, pVR->Length);
+ s[pVR->Length] = 0;
+ if ((strcmp(s, "1.2.840.10008.1.2") != 0) &&
+ (strcmp(s, "1.2.840.10008.1.2.1") != 0) &&
+ (strcmp(s, "1.2.840.10008.1.2.2") != 0))
+ {
+ if (!has_dcm_extension)
+ {
+ OperatorConsole.printf("Recompress: cannot rewrite jpeg/rle image in v2 format\n");
+ Filename[0]=0;
+ pDDO->Reset();
+ return;
+ }
+ UseChapter10 = has_dcm_extension;
+ }
+ else
+ {
+ UseChapter10 = has_dcm_extension;
+ //bForcedImplicit = TRUE; // 20040406
+ }
+ }
+ else
+ UseChapter10 = has_dcm_extension;
+
+ if (!UseChapter10)
+ PDU.SaveDICOMDataObject(Filename, ACRNEMA_VR_DUMP, pDDO);
+ else if (bForcedImplicit)
+ PDU.SaveDICOMDataObject(Filename, DICOM_CHAPTER_10_IMPLICIT, pDDO);
+ else
+ PDU.SaveDICOMDataObject(Filename, DICOM_CHAPTER_10_EXPLICIT, pDDO);
+ }
+
+
+/***********************************************************************************/
+/*
+ Code from CqGlobal.h (CqDicom.dll)
+*/
+/***********************************************************************************/
+
+#define DCM_E_OK 0
+#define DCM_E_MEMORY 5
+#define DCM_E_UNSUPPORTED_COMPRESSION 26
+#define DCM_E_UNSUPPORTED_FORMAT 28
+
+typedef struct
+{
+ char szModality[16];
+ char szSeriesInstanceUID[256];
+ float fSpacingX;
+ float fSpacingY;
+ int iDimX;
+ int iDimY;
+ int iNbFrames;
+ int iNbTimeSequences;
+ char szPatientPosition[16];
+ int iDataSize;
+ BOOL bNkiCompressed;
+ int iPixelRepresentation;
+ int iBitsStored;
+ float fRescaleIntercept;
+ float fRescaleSlope;
+ float fDoseGridScaling;
+ BOOL bRtImagePosOK;
+ float fRtImagePosX;
+ float fRtImagePosY;
+ char szPhotometricInterpretation[20];
+} SLICE_INFO;
+
+SLICE_INFO* getpSliceInfo(DICOMDataObject* pDDO)
+{
+ VR *pVR;
+ SLICE_INFO *pSliceInfo;
+
+ if(!(pSliceInfo = (SLICE_INFO*)malloc(sizeof(SLICE_INFO))))return NULL;
+ memset(pSliceInfo, 0x00, sizeof(SLICE_INFO));
+
+ // Rows
+ pSliceInfo->iDimY = pDDO->GetUINT(0x0028, 0x0010);
+ if(!pSliceInfo->iDimY)// Zero height.
+ {
+ free(pSliceInfo);
+ return NULL;
+ }
+ // Columns
+ pSliceInfo->iDimX = pDDO->GetUINT(0x0028, 0x0011);
+ if(!pSliceInfo->iDimX) // Zero width.
+ {
+ free(pSliceInfo);
+ return NULL;
+ }
+ // BitsStored
+ pSliceInfo->iBitsStored = pDDO->GetBYTE(0x0028, 0x0101);
+
+ // NumberOfFrames
+ pVR = pDDO->GetVR(0x0028, 0x0008);
+ if (pVR && pVR->Length)
+ {
+ pSliceInfo->iNbFrames = pVR->Getatoi();
+ pSliceInfo->iNbTimeSequences = 1;
+
+ // NumberOfSlices
+ pVR = pDDO->GetVR(0x0054, 0x0081);
+ if (pVR)
+ { /* Seems like a 3D time-sequence:
+ - Keep on using the iNbFrames member to designate the number of slices
+ - Use the iNbTimeSequences member for the number of volumes
+ */
+ int iNbSlices, iNbVolumes;
+ iNbSlices = pVR->GetUINT();
+ if (iNbSlices > 0)
+ { iNbVolumes = pSliceInfo->iNbFrames / iNbSlices;
+ if (iNbVolumes * iNbSlices == pSliceInfo->iNbFrames)
+ {
+ pSliceInfo->iNbFrames = iNbSlices;
+ pSliceInfo->iNbTimeSequences = iNbVolumes;
+ }
+ }
+ }
+ }
+ // PhotometricInterpretation
+ pVR = pDDO->GetVR(0x0028, 0x0004);
+ if (pVR && pVR->Length && pVR->Data)
+ strncpy(pSliceInfo->szPhotometricInterpretation,
+ (char*)pVR->Data, pVR->Length<19 ? pVR->Length : 19);
+
+ return pSliceInfo;
+
+}
+
+char * DePlane(char* data, int length)
+{
+ char *noPlane, *nPtr, *rPtr, *gPtr, *bPtr;
+
+ if((noPlane = (char *) malloc(length)))
+ {// Planes are 8 bit RGB (or should be).
+ noPlane[length -1] = 0;// Never hurts, maybe an extra 0.
+ length /= 3;// Each plane
+ nPtr = noPlane;
+ rPtr = data;
+ gPtr = rPtr + length;
+ bPtr = gPtr + length;
+ for ( ;length > 0; length-- )
+ {
+ *nPtr++ = *rPtr++;
+ *nPtr++ = *gPtr++;
+ *nPtr++ = *bPtr++;
+ }
+ }
+ return noPlane;// Memory error returns null.
+}
+
+void DeYBRFULL(char* data, int length)
+{
+ unsigned char *nPtr;
+ int r, g, b;
+
+ length /= 3; // each color
+ nPtr = (unsigned char *)data;
+ for ( ;length > 0; length-- )
+ {
+
+ r = nPtr[0] + 1.40200 * (nPtr[2]-128);
+ g = nPtr[0] - 0.34414 * (nPtr[1]-128) - 0.71414 * (nPtr[2]-128);
+ b = nPtr[0] + 1.77200 * (nPtr[1]-128);
+ if (r>255) r=255;
+ if (g>255) g=255;
+ if (b>255) b=255;
+ if (r<0) r=0;
+ if (g<0) g=0;
+ if (b<0) b=0;
+ *nPtr++ = r;
+ *nPtr++ = g;
+ *nPtr++ = b;
+
+/* r = ((int)nPtr[0] * 128) + ((int)nPtr[2] * 179) - 22970;
+ g = ((int)nPtr[0] * 128) - (44 * (int)nPtr[1]) - (91 * (int)nPtr[2]) - 17338;
+ b = ((int)nPtr[0] * 128) + (277 * (int)nPtr[1]) - 29032;
+ if(r & 0x8000) *nPtr++ = 0;
+ else if(r & 0x4000) *nPtr++ = 255;
+ else *nPtr++ = (r >> 6) & 0xFF;
+ if(g & 0x8000) *nPtr++ = 0;
+ else if(r & 0x4000) *nPtr++ = 255;
+ else *nPtr++ = (g >> 6) & 0xFF;
+ if(b & 0x8000) *nPtr++ = 0;
+ else if(b & 0x4000) *nPtr++ = 255;
+ else *nPtr++ = (b >> 6) & 0xFF;
+*/
+ }
+}
+
+static int DecompressRLE(SLICE_INFO* pSliceInfo, VR* pSequence,
+ void** ppResult, unsigned int * piResultSize)
+{ int rc = DCM_E_UNSUPPORTED_COMPRESSION;
+ unsigned int iFrameCnt, storedBitWidth, iDecompressedTotal;
+ unsigned int i, n, iNbRleSegments;
+ Array<DICOMDataObject*> *pADDO;
+ DICOMDataObject* pDDO;
+ VR* pVR;
+ char *pIn, *pOut, *outPtr, *endPtr, *pSeq, **hSeq, *cPtr, *endSeqPtr;
+ int* piHeader;
+ unsigned int iCompressedSize, iDecompressedSize, iNbCompressed, iNbDecompressed;
+ char cCurrent;
+ char *pR, *pG, *pB;
+ bool bIsRGB = false;
+
+// Init stuff
+ pOut = NULL;
+ pSeq = NULL;
+ endPtr = NULL;
+ pG = NULL;
+ pB = NULL;
+ cPtr = NULL;
+ iDecompressedSize = 0;
+ iNbDecompressed = 0;
+ *ppResult = NULL;
+ *piResultSize = 0;
+// Find out how big the output is.
+ if(pSliceInfo->iBitsStored > 8) storedBitWidth = 2;
+ else storedBitWidth = 1;
+ iDecompressedTotal = pSliceInfo->iDimX * pSliceInfo->iDimY * storedBitWidth;
+ if (pSliceInfo->iNbFrames)
+ iDecompressedTotal *= pSliceInfo->iNbFrames;
+ if (strncmp(pSliceInfo->szPhotometricInterpretation, "RGB", 3) == 0)
+ bIsRGB = true;
+// Of all color-representations, just support RGB for now.
+ if (bIsRGB)
+ iDecompressedTotal *= 3;
+// Get the data.
+ pADDO = (Array<DICOMDataObject*>*)pSequence->SQObjectArray;
+// Frames can be RLE segments or sequences.
+ for(iFrameCnt = 1; iFrameCnt < pADDO->GetSize(); iFrameCnt++)
+ {
+ pDDO = pADDO->Get(iFrameCnt);
+ pVR = pDDO->GetVR(0xfffe, 0xe000);
+
+ /* The RLE data should start with 16 INT32 (Dicom chapter 5 annex G):
+ - 1st contains how many RLE segments there are (15 max)
+ - 2nd-16th contain offsets of each RLE segment
+ All non-used segments have offset 0 in this small table
+ Since this 16 INT32 header has a size of 64 bytes, the first offset should
+ be 64. All integers are stored in little-endian format.
+ */
+ /* Check the header */
+ if ((!pVR->Data) || (pVR->Length < 64))
+ {
+ if(pOut)free(pOut);
+ return rc;
+ }
+ piHeader = (int*)pVR->Data;
+#if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian
+ for(i=0; i<16; i++) piHeader[i] = SwitchEndian(piHeader[i]);
+#endif
+// How many segments, min 1, max of 15.
+ iNbRleSegments = piHeader[0];
+ if ((iNbRleSegments < 1) || (iNbRleSegments > 15))
+ {
+ if(pOut)free(pOut);
+ return rc;
+ }
+// The first offset must be 64, the RLE header length.
+ if (piHeader[1] != 64)
+ {
+ if(pOut)free(pOut);
+ return rc;
+ }
+// Check all segments, each offset must be more than before.
+ for (i=2; i<=iNbRleSegments; i++)
+ if (piHeader[i] < piHeader[i-1])
+ {
+ if(pOut)free(pOut);
+ return rc;
+ }
+// All unused segments are zero.
+ for (i=iNbRleSegments + 1; i<=15; i++)
+ if (piHeader[i] != 0)
+ {
+ if(pOut)free(pOut);
+ return rc;
+ }
+// OK, it probably is RLE-compressed, time to make memory.
+ if(!pOut) // Made already?
+ {
+ if(iDecompressedTotal & 1) iDecompressedTotal++;
+ if(!(pOut = (char*)malloc(iDecompressedTotal)))
+ return DCM_E_MEMORY;
+ memset(pOut, 0xff, iDecompressedTotal);
+ outPtr = pOut;
+ endPtr = outPtr + iDecompressedTotal;
+ }
+ iNbCompressed = 0;
+ iCompressedSize = pVR->Length - 64;// Take out the header
+ pIn = ((char*)piHeader) + 64;// Start of the data.
+// Create a color buffer if needed.
+ if (bIsRGB && storedBitWidth == 1 && iNbRleSegments == 3)
+ {
+ iDecompressedSize = pSliceInfo->iDimX * pSliceInfo->iDimY * storedBitWidth;
+ if( outPtr + (iDecompressedTotal * 3) > endPtr) break; // Should fail?
+ if(!(cPtr = (char*)malloc(iDecompressedTotal * 3)))
+ {
+ if(pOut)free(pOut);
+ return DCM_E_MEMORY;
+ }
+ hSeq = &pR;// Make the handle's pointer valid.
+ pR = cPtr;// Copy the pointer to the handle.
+ pG = pR + iDecompressedSize;
+ pB = pG + iDecompressedSize;
+ endSeqPtr = pB + iDecompressedSize;
+ }
+ else
+ {
+ hSeq = &outPtr;// Give the pointer to the handle.
+ endSeqPtr = endPtr;// End does not incrament.
+ }
+// while (iNbDecompressed < iDecompressedSize)
+ while (iNbCompressed < iCompressedSize)
+ {
+ cCurrent = pIn[iNbCompressed++];// Det the count.
+ if (cCurrent >= 0)// Positive is a Literal Run.
+ {// Check the length in & out?
+ cCurrent++;// The real count
+ if ((iNbCompressed + (int)cCurrent <= iCompressedSize) &&
+ (*hSeq + cCurrent <= endSeqPtr))
+ { // Good, room to copy
+ memcpy(*hSeq, pIn + iNbCompressed, cCurrent);
+ iNbCompressed += cCurrent;
+ *hSeq += cCurrent;
+ }
+ else // What happened, no room or seq ending 0?
+ break;// Run away!
+ }
+ else if (cCurrent == -128)break;// Just not allowed, may fail here.
+ else// Replicate run.
+ { n = ((int)-cCurrent) + 1;
+ if (*hSeq + n > endPtr)// Enough room out?
+ break;
+ for (i=0; i<n; i++)
+ *((*hSeq)++) = pIn[iNbCompressed];
+ iNbCompressed++;
+ }
+ }
+ if (bIsRGB && storedBitWidth == 1 && iNbRleSegments == 3)
+ { /* Convert the R, G and B image planes to triplets */
+ pR = cPtr;// Reset the red.
+ for (i=0; i<iDecompressedSize; i++)// Already devided by 3
+ {
+ *outPtr++ = *pR++;
+ *outPtr++ = *pG++;
+ *outPtr++ = *pB++;
+ }
+ free(cPtr);
+ cPtr = NULL;
+ }
+ }
+ *ppResult = pOut;
+ *piResultSize = iDecompressedTotal;
+ return DCM_E_OK;
+}
+
+#if 0
+static int DecompressRLE(SLICE_INFO* pSliceInfo, VR* pSequence,
+ void** ppResult, unsigned int * piResultSize)
+{ int rc = DCM_E_UNSUPPORTED_COMPRESSION;
+ int i, n, iNbRleSegments;
+ Array<DICOMDataObject*> *pADDO;
+ DICOMDataObject* pDDO;
+ VR* pVR;
+ char *pIn, *pOut;
+ int* piHeader;
+ int iCompressedSize, iDecompressedSize, iNbCompressed, iNbDecompressed;
+ char cCurrent;
+ char *pR, *pG, *pB;
+ bool bIsRGB = false;
+
+ pADDO = (Array<DICOMDataObject*>*)pSequence->SQObjectArray;
+ pDDO = pADDO->Get(1);
+ pVR = pDDO->GetVR(0xfffe, 0xe000);
+
+ /* The RLE data should start with 16 INT32 (Dicom chapter 5 annex G):
+ - 1st contains how many RLE segments there are (15 max)
+ - 2nd-16th contain offsets of each RLE segment
+ All non-used segments have offset 0 in this small table
+ Since this 16 INT32 header has a size of 64 bytes, the first offset should
+ be 64. All integers are stored in little-endian format.
+ */
+ /* Check the header */
+ if ((!pVR->Data) || (pVR->Length < 64))
+ return rc;
+
+ piHeader = (int*)pVR->Data;
+#if NATIVE_ENDIAN != LITTLE_ENDIAN //Big Endian
+ for(i=0; i<16; i++) piHeader[i] = SwitchEndian(piHeader[i]);
+#endif
+
+ iNbRleSegments = piHeader[0];
+ if ((iNbRleSegments < 1) || (iNbRleSegments > 15))
+ return rc;
+
+ if (piHeader[1] != 64)
+ return rc;
+ for (i=2; i<=iNbRleSegments; i++)
+ if (piHeader[i] < piHeader[i-1])
+ return rc;
+ for (i=iNbRleSegments + 1; i<=15; i++)
+ if (piHeader[i] != 0)
+ return rc;
+
+ /* OK, it probably is RLE-compressed */
+
+ /* Find out how big the output is */
+ iDecompressedSize = pSliceInfo->iDimX * pSliceInfo->iDimY *
+ (pSliceInfo->iBitsStored / 8);
+ if (pSliceInfo->iNbFrames)
+ iDecompressedSize *= pSliceInfo->iNbFrames;
+ if (strncmp(pSliceInfo->szPhotometricInterpretation, "RGB", 3) == 0)
+ bIsRGB = true;
+ /* Of all color-representations, just support RGB for now */
+
+ if (bIsRGB)
+ iDecompressedSize = iDecompressedSize * 3;
+ pOut = (char*)malloc(iDecompressedSize);
+ if (!pOut)
+ return DCM_E_MEMORY;
+ memset(pOut, 0xff, iDecompressedSize);
+
+ iNbCompressed = 0;
+ iNbDecompressed = 0;
+ iCompressedSize = pVR->Length - 64;
+ pIn = ((char*)piHeader) + 64;
+ while (iNbDecompressed < iDecompressedSize)
+ { cCurrent = pIn[iNbCompressed++];
+ if (cCurrent >= 0)
+ { if ((iNbCompressed + ((int)cCurrent) + 1 <= iCompressedSize) &&
+ (iNbDecompressed + ((int)cCurrent) + 1 <= iDecompressedSize))
+ { memcpy(pOut + iNbDecompressed, pIn + iNbCompressed, ((int)cCurrent) + 1);
+ iNbCompressed += ((int)cCurrent) + 1;
+ iNbDecompressed += ((int)cCurrent) + 1;
+ }
+ else
+ break;
+ }
+ else if (cCurrent == -128)
+ iNbCompressed = iNbCompressed;
+ else
+ { n = ((int)-cCurrent) + 1;
+ if (iNbDecompressed + n > iDecompressedSize)
+ break;
+ for (i=0; i<n; i++)
+ pOut[iNbDecompressed + i] = pIn[iNbCompressed];
+ iNbDecompressed += n;
+ iNbCompressed++;
+ }
+ }
+
+ if (bIsRGB)
+ { /* Convert the R, G and B image planes to triplets */
+ pR = pOut;
+ pOut = (char*)malloc(iDecompressedSize);
+ if (!pOut)
+ { free(pR);
+ return DCM_E_MEMORY;
+ }
+ pG = pR + iDecompressedSize / 3;
+ pB = pG + iDecompressedSize / 3;
+ for (i=0; i<iDecompressedSize / 3; i++)
+ { *pOut++ = pR[i];
+ *pOut++ = pG[i];
+ *pOut++ = pB[i];
+ }
+ pOut -= iDecompressedSize;
+ free(pR);
+ }
+
+
+ rc = DCM_E_OK;
+
+ if (rc == DCM_E_OK)
+ { *ppResult = pOut;
+ *piResultSize = iDecompressedSize;
+ }
+ else
+ { *ppResult = NULL;
+ *piResultSize = 0;
+ }
+ return rc;
+}
+#endif
+
+// Make a palette color table for a segmented vr, don't forget to free it.
+unsigned char * MakeSegTable(VR *pVR, unsigned int tableSize,unsigned int *bitsWidth)
+{
+ unsigned char *table, *table8, *table8Ptr, *inPtr, *endPtr, *tablePtr;
+ unsigned int cnt, cTableSize, step, sEnd, last;
+ unsigned int type, words;
+ *bitsWidth = 1;
+
+ cTableSize = tableSize * 2;// Ints.
+ if(!(table = (unsigned char*)malloc(cTableSize)))
+ {
+ OperatorConsole.printf( "***[MakeSegTable]: Memory error.\n");
+ return(NULL);
+ }
+ cnt = 0;
+ inPtr = (unsigned char *)pVR->Data;
+ endPtr = inPtr + pVR->Length;//Min type length.
+ while(inPtr < endPtr)
+ {
+ type = *inPtr++;
+ inPtr++;// To next int.
+/*#if NATIVE_ENDIAN == LITTLE_ENDIAN
+ words = ((UINT16*)pVR->Data)[pos];
+#else*/
+ words = *inPtr + (*(inPtr + 1) << 8);
+ inPtr += 2;// Move char counter over to next int.
+//#endif
+//printf("%X ", cnt);
+ if(cnt + (2 * words) > cTableSize)
+ {//Overrun.
+ free(table);
+ OperatorConsole.printf(
+ "***[MakeSegTable]: A count of %d + %d words would overrun %d of output memory.\n",
+ cnt, 2 * words, cTableSize);
+ return(NULL);
+ }
+ switch (type)
+ {
+ case 0://Discrete Segment Type
+ if(inPtr + (2 * words) > endPtr)
+ {//Overrun.
+ free(table);
+ OperatorConsole.printf(
+ "***[MakeSegTable]: %d words would overrun %d left of vr input.\n",
+ 2 * words, endPtr - inPtr);
+ return(NULL);
+ }
+ for(;words > 0; words--)
+ {
+ table[cnt] = *inPtr++;
+ if(table[cnt++] != *inPtr) *bitsWidth = 2;
+ table[cnt++] = *inPtr++;
+ }
+ break;
+ case 1://Linear Segment Type
+ if(inPtr + 2 > endPtr)
+ {//Overrun.
+ free(table);
+ OperatorConsole.printf(
+ "***[MakeSegTable]: 1 word would overrun %d left of vr input.\n",
+ endPtr - inPtr);
+ }
+ if(cnt < 2)//Not allowed first.
+ {
+ free(table);
+ OperatorConsole.printf( "***[MakeSegTable]: A Linear Segment can not be first.\n");
+ return(NULL);
+ }
+ last = table[cnt - 2] + (table[cnt - 1] << 8);
+ sEnd = *inPtr++;
+ if(*inPtr != sEnd) *bitsWidth = 2;
+ sEnd += ((*inPtr++) << 8);
+ step = (sEnd - last)/ words;
+ for(;words > 1; words--)
+ {
+ last += step;
+ table[cnt++] = last & 0xFF;
+ table[cnt++] = (last & 0xFF00) >> 8;
+ }
+ table[cnt++] = sEnd & 0xFF;
+ table[cnt++] = (sEnd & 0xFF00) >> 8;
+// last = sEnd;
+ break;
+ case 2:// Indirect Sgment type
+#if NATIVE_ENDIAN == LITTLE_ENDIAN
+ sEnd = *((UINT*)inPtr);
+#else
+ sEnd = SwitchEndian(*((UINT*)inPtr));
+#endif
+ inPtr += 4;
+ for(;words > 1; words--)
+ {
+ table[cnt++] = table[sEnd];
+ table[cnt++] = table[sEnd];
+ }
+ break;
+ default:
+ OperatorConsole.printf( "***[MakeSegTable]: Opt code wrong or reserved type, %d.\n",type);
+ return(NULL);//Opt code wrong or reserved!
+ break;
+ }
+ }
+ if(*bitsWidth == 1)
+ {
+ if(!(table8 = (unsigned char*)malloc(tableSize)))
+ {
+ free(table);
+ OperatorConsole.printf( "***[MakeSegTable]: Memory error.\n");
+ return(NULL);
+ }
+ tablePtr = table;
+ table8Ptr = table8;
+ for(cnt = 0; cnt < tableSize; cnt++)
+ {
+ *table8Ptr++ = *tablePtr++;
+ tablePtr++;
+ }
+ return((unsigned char*)table8);
+ }
+ return((unsigned char*)table);
+}
+
+//Will turn any palette into Gray or RGB. The image Pixel Data (7FE0,0010) is decompressed.
+bool DecodePalette(DICOMDataObject* pDDO)
+{
+ VR *pVR, *vrImage;
+ unsigned int cmpts, inputArrayCnt, outSize, outLen, cnt, byteOffset, tableStep;
+ unsigned int tableSize, outBits, outBitw, allBitw, inBitw, offset, tableMin;
+ unsigned char *rTable, *gTable = NULL, *bTable = NULL, *outPtr, *outImage, *inPtr, *rPtr;
+ bool bSegmented, bLSBzero, bMSBzero;
+ DICOMDataObject *DDO;
+ Array<DICOMDataObject *> *arrayImage;
+// Init locals
+ bSegmented =FALSE;
+ inputArrayCnt = 0;
+ byteOffset = 0;// Data in lsb.
+ tableStep = 1;
+ bLSBzero = TRUE;
+ bMSBzero = TRUE;
+ cmpts = 1;
+// Check if its Palette Color
+ pVR = pDDO->GetVR(0x0028, 0x0004);
+ if(!pVR || pVR->Length != 14 || strncmp( (char *)pVR->Data, "PALETTE COLOR", 13))
+ {
+ OperatorConsole.printf("***[DecodePalette]: Not Palette Color.\n");
+ return(FALSE);
+ }
+
+ // Check that is decompressed.
+ pVR = pDDO->GetVR(0x0002, 0x0010);
+ if(!pVR || pVR->Length > 20 || // Longer than 20 is some kind of jpeg or deflated.
+ (pVR->Length == 20 && ((char *)pVR->Data)[18] <= 32))// 1 & 2 are uncompressed LE & BE
+ return(FALSE);
+// Check the samples per pixel.
+ if(pDDO->GetBYTE(0x0028, 0x0002) != 1)
+ {
+ OperatorConsole.printf("***[DecodePalette]: Palette color cannot %d samples per pixel.\n",
+ pDDO->GetBYTE(0x0028, 0x0002));
+ return(FALSE);
+ }
+ // If debug > 2, print info.
+ if (DebugLevel > 2)
+ SystemDebug.printf("Found Palette Color, depalatizing.\n");
+// Look for palette stuff
+ pVR = pDDO->GetVR(0x0028,0x1100); //The grayscale palette info..
+ if(!pVR) pVR = pDDO->GetVR(0x0028,0x1101);//The red palette info..
+ if(pVR && pVR->Length == 6)
+ {
+ tableSize = *(char *)pVR->Data + (((char *)pVR->Data)[1] << 8);
+ tableMin = ((char *)pVR->Data)[2] + (((char *)pVR->Data)[3] << 8);
+ outBits = ((char *)pVR->Data)[4];// 8 or 16 only allowed. Test?
+ }
+// Not palette color or Retired Large palette color. (Not supported here)
+// I may add here code to fix the Photometric Interpretation.
+// It would haxe to check 0x0002,0x0010 and 0x0028,0x0002 and guess.
+ else
+ {
+ OperatorConsole.printf("***[DecodePalette]: No Palette information.\n", cmpts);
+ return(FALSE);
+ }
+// Fix the table size.
+ if(tableSize == 0)tableSize = 0x10000;// Fix the 2 byte table size.
+// Count the colors.
+ pVR = pDDO->GetVR(0x0028,0x1102);//The green palette info..
+ if(pVR && pVR->Length == 6)cmpts++;// All are the same.
+ pVR = pDDO->GetVR(0x0028,0x1103);//The blue palette info..
+ if(pVR && pVR->Length == 6)cmpts++;
+// Check for correct components.
+ if (cmpts != 1 && cmpts != 3)
+ {
+ OperatorConsole.printf("***[DecodePalette]: %d components is not supported.\n", cmpts);
+ return(FALSE);
+ }
+// If debug > 3, print info.
+ if (DebugLevel > 3)
+ SystemDebug.printf("Palette table size = %d, Minimum value = %d in %d bytes.\n",
+ tableSize, tableMin, outBits);
+// Lets look at the color palette.
+ pVR = pDDO->GetVR(0x0028,0x1200); //The grayscale palette.
+ if(!pVR) pVR = pDDO->GetVR(0x0028,0x1201);//The red palette.
+ if(pVR && pVR->Length)
+ {
+ rTable = (unsigned char*)pVR->Data;
+ if(pVR->TypeCode == 'OB' || outBits <= 8) outBitw = 1;//tableStep = 1.
+ else
+ {
+ tableStep = 2;
+ if(tableSize == pVR->Length) outBitw = 2;
+ else outBitw = 1;// tableSize * 2 == pVR->Length, will check later.
+ }
+// Check the table size.
+ if(pVR->Length != tableSize * tableStep / outBitw)
+ {
+ OperatorConsole.printf(
+ "***[DecodePalette]: Palette length should be %d, is %d, %d bits out.\n",
+ tableSize * outBits/8, pVR->Length, outBits);
+ return(FALSE);
+ }
+// Get the other colors.
+ if(cmpts == 3)
+ {
+ pVR = pDDO->GetVR(0x0028,0x1202);//The green palette.
+ if(!pVR || pVR->Length != tableSize * tableStep / outBitw)
+ {
+ OperatorConsole.printf(
+ "***[DecodePalette]: Green palette length is %d, should be %d.\n",
+ pVR->Length, tableSize * outBits/8);
+ return(FALSE);
+ }
+ gTable = (unsigned char*)pVR->Data;
+ pVR = pDDO->GetVR(0x0028,0x1203);//The blue palette.
+ if(!pVR || pVR->Length != tableSize * tableStep / outBitw)
+ {
+ OperatorConsole.printf(
+ "***[DecodePalette]: Blue palette length is %d, should be %d.\n",
+ pVR->Length, tableSize * outBits/8);
+ return(FALSE);
+ }
+ bTable = (unsigned char*)pVR->Data;
+ }
+// If debug > 3, print info.
+ if (DebugLevel > 3)
+ SystemDebug.printf("%d components in standard palette(s).\n",cmpts);
+ }
+ else //No gray or red table.
+ {// Segmented look up table.
+ pVR = pDDO->GetVR(0x0028,0x1220);//The gray segmented palette info..
+ if(!pVR )pVR = pDDO->GetVR(0x0028,0x1221);//The red segmented palette info..
+ if(!pVR || !pVR->Length)
+ {
+ OperatorConsole.printf("***[DecodePalette]: No palettes were found\n");
+ return(FALSE);
+ }
+ if(!(rTable = MakeSegTable(pVR, tableSize, &outBitw)))return(FALSE);
+ bSegmented = TRUE;
+ allBitw = outBitw;
+ if( cmpts == 3 )
+ {
+ if(!(pVR = pDDO->GetVR(0x0028,0x1222)) || !pVR->Length ||
+ !(gTable = MakeSegTable(pVR, tableSize, &outBitw)))
+ {
+ free(rTable);
+ OperatorConsole.printf("***[DecodePalette]: Green palette was not found\n");
+ return(FALSE);
+ }
+ if (allBitw != outBitw)
+ {
+ free(rTable);
+ OperatorConsole.printf(
+ "***[DecodePalette]: Green palette bit width does't match the red.\n");
+ free(rTable);
+ if(gTable)free(gTable);
+ return(FALSE);
+ }
+ if(!(pVR = pDDO->GetVR(0x0028,0x1223)) || !pVR->Length ||
+ !(bTable = MakeSegTable(pVR, tableSize, &outBitw)))
+ {
+ OperatorConsole.printf("***[DecodePalette]: Blue palette was not found\n");
+ return(FALSE);
+ free(rTable);
+ free(gTable);
+ if(bTable)free(bTable);
+ }
+ if (allBitw != outBitw)
+ {
+ free(rTable);
+ free(gTable);
+ free(bTable);
+ OperatorConsole.printf(
+ "***[DecodePalette]: Blue palettes bit width does't match the red.\n");
+ return(FALSE);
+ }
+ }
+ tableStep = outBitw;
+// If debug > 3, print info.
+ if (DebugLevel > 3)
+ SystemDebug.printf("%d components in segmented palette(s).\n",cmpts);
+ }
+// Look for 8 in 16 with zeros in one byte.
+ if(tableStep == 2)
+ {
+ rPtr = rTable;
+ for(cnt = 0; cnt < pVR->Length; cnt += 2)
+ {// Look for all zeros
+ if(*rPtr++ != 0)bLSBzero = FALSE;
+ if(*rPtr++ != 0)bMSBzero = FALSE;
+ }
+
+ if(bMSBzero == TRUE)
+ {
+
+ if(bLSBzero == TRUE)
+ {
+ OperatorConsole.printf("***[DecodePalette]: The whole table is zero.\n");
+ if(bSegmented == TRUE)
+ {
+ free(rTable);
+ if(gTable)free(gTable);
+ if(bTable)free(bTable);
+ }
+ return (FALSE);
+ }
+ byteOffset = 0;//LSB has the data
+ outBitw = 1;
+ }
+ if(bLSBzero == TRUE)
+ {
+ byteOffset = 1;//MSB has the data
+ outBitw = 1;
+ }
+ }
+// Get the input data size.
+ if(!(inBitw = pDDO->GetBYTE(0x0028, 0x0101)))inBitw = 8;
+ if(inBitw > 8)inBitw = 2;
+ else inBitw = 1;
+// If debug > 3, print info.
+ if (DebugLevel > 3)
+ {
+ if(outBitw == 2) SystemDebug.printf("Output data is words from \n");
+ else
+ {
+ SystemDebug.printf("Output data is bytes in the \n");
+ if(byteOffset == 0)SystemDebug.printf("LSB from \n");
+ else SystemDebug.printf("MSB from \n");
+ }
+ if(inBitw == 1)SystemDebug.printf("8 bits in.\n");
+ else SystemDebug.printf("16 bits in.\n");
+ }
+ // Now for the image data.
+ pVR = pDDO->GetVR(0x7fe0, 0x0010); // Get the Image VR.
+ vrImage = pVR;//Should be done here.
+ if(pVR && pVR->Length)
+ {
+ if(pVR->SQObjectArray)
+ {// Can be here for frames.
+ arrayImage = (Array<DICOMDataObject *> *) pVR->SQObjectArray;
+ while (inputArrayCnt < arrayImage->GetSize())
+ {
+ DDO = arrayImage->Get(inputArrayCnt++);//Get the array.
+ vrImage = DDO->GetVR(0xfffe, 0xe000);//Get the data
+ if(vrImage && vrImage->Length >= 0x10) break;
+ }
+ if(inputArrayCnt == arrayImage->GetSize())
+ {
+ OperatorConsole.printf("***[DecodePalette]: Could not find the image data.\n");
+ if(bSegmented == TRUE)
+ {
+ free(rTable);
+ if(gTable)free(gTable);
+ if(bTable)free(bTable);
+ }
+ return (FALSE);
+ }
+ }
+ }
+// Set the output size
+ outLen = outSize = vrImage->Length * cmpts * outBitw;
+ inPtr = (unsigned char*)vrImage->Data;
+ if(outLen & 1)outLen++;
+ if(!(outImage = (unsigned char*)malloc(outLen)))
+ {
+ OperatorConsole.printf("***[DecodePalette]: Could not allocate %d bytes.\n", outLen);
+ if(bSegmented == TRUE)
+ {
+ free(rTable);
+ if(gTable)free(gTable);
+ if(bTable)free(bTable);
+ }
+ return (FALSE);
+ }
+// Copy the data.
+ outPtr = outImage;
+// cmpts--;// Make cmpts into a bool.
+ for(cnt = 0; cnt < vrImage->Length; cnt++)
+ {
+ offset = *inPtr++;// Get the LSB or byte value.
+ if(inBitw == 2)
+ {
+ offset += (*inPtr++ << 8);// Add the MSB if there.
+ cnt++;
+ }
+ if(offset < tableMin) offset = 0;
+ else offset -= tableMin;
+ if( offset >= tableSize)offset = tableSize - 1;
+ offset *= tableStep;// Double for words only.
+ offset += byteOffset;// Off set for msb byte.
+ *outPtr++ = rTable[offset];
+ if(outBitw == 2)*outPtr++ = rTable[offset + 1];//Next value for words.
+ if(cmpts == 3)
+ {
+ *outPtr++ = gTable[offset];
+ if(outBitw == 2) *outPtr++ = gTable[offset + 1];//Next value for words.
+ *outPtr++ = bTable[offset];
+ if(outBitw == 2) *outPtr++ = bTable[offset + 1];//Next value for words.
+ }
+ }
+// Done with the tables, free if ours.
+ if(bSegmented == TRUE)
+ {
+ free(rTable);
+ if(gTable)free(gTable);
+ if(bTable)free(bTable);
+ }
+// Fix the last zero if needed.
+ if(outSize & 1)outImage[outSize] = 0;
+// Change the image data.
+ vrImage->Reset(); // Deletes the pixel data
+ vrImage->Length = outLen;
+ vrImage->Data = outImage;
+ if(outBitw == 2) vrImage->TypeCode = 'OW';
+ else vrImage->TypeCode = 'OB';
+ vrImage->ReleaseMemory = TRUE;//Give the memory to the vr.
+// Fix the Photometric Interpretation and Samples per.
+ if(cmpts == 1)pDDO->ChangeVR( 0x0028, 0x0004, "MONOCHROME2\0", 'CS');
+ else
+ {
+ pDDO->ChangeVR( 0x0028, 0x0004, "RGB\0", 'CS');
+ pDDO->ChangeVR( 0x0028, 0x0002, (UINT16)3, 'US');
+ }
+// Fix output widths (DecodePalette).
+ if(outBitw == 2)
+ {
+ pDDO->ChangeVR( 0x0028, 0x0100, (BYTE)16, 'US');
+ pDDO->ChangeVR( 0x0028, 0x0101, (BYTE)16, 'US');
+ pDDO->ChangeVR( 0x0028, 0x0102, (BYTE)15, 'US');
+ }
+ else
+ {
+ pDDO->ChangeVR( 0x0028, 0x0100, (BYTE)8, 'US');
+ pDDO->ChangeVR( 0x0028, 0x0101, (BYTE)8, 'US');
+ pDDO->ChangeVR( 0x0028, 0x0102, (BYTE)7, 'US');
+ }
+// Delete the no longer needed palette vr's.
+// Palette Color Lookup Table Descriptors
+ if((pVR = pDDO->GetVR(0x0028,0x1100)) && pVR->Length)pDDO->DeleteVR(pVR);
+ if((pVR = pDDO->GetVR(0x0028,0x1101)) && pVR->Length)pDDO->DeleteVR(pVR);
+ if((pVR = pDDO->GetVR(0x0028,0x1102)) && pVR->Length)pDDO->DeleteVR(pVR);
+ if((pVR = pDDO->GetVR(0x0028,0x1103)) && pVR->Length)pDDO->DeleteVR(pVR);
+// Palette Color Lookup Table UID
+ if((pVR = pDDO->GetVR(0x0028,0x1199)) && pVR->Length)pDDO->DeleteVR(pVR);
+// Regular palette tables
+ if((pVR = pDDO->GetVR(0x0028,0x1200)) && pVR->Length)pDDO->DeleteVR(pVR);
+ if((pVR = pDDO->GetVR(0x0028,0x1201)) && pVR->Length)pDDO->DeleteVR(pVR);
+ if((pVR = pDDO->GetVR(0x0028,0x1202)) && pVR->Length)pDDO->DeleteVR(pVR);
+ if((pVR = pDDO->GetVR(0x0028,0x1203)) && pVR->Length)pDDO->DeleteVR(pVR);
+// Segmented palette tables
+ if((pVR = pDDO->GetVR(0x0028,0x1220)) && pVR->Length)pDDO->DeleteVR(pVR);
+ if((pVR = pDDO->GetVR(0x0028,0x1221)) && pVR->Length)pDDO->DeleteVR(pVR);
+ if((pVR = pDDO->GetVR(0x0028,0x1222)) && pVR->Length)pDDO->DeleteVR(pVR);
+ if((pVR = pDDO->GetVR(0x0028,0x1223)) && pVR->Length)pDDO->DeleteVR(pVR);
+ return(TRUE);
+}
+
+#ifndef NOINTJPEG
+#ifndef HAVE_LIBJPEG //Not needed for the jpeg library
+
+/***********************************************************************************/
+/*
+ Code from CqJPEG.cpp (CqDicom.dll)
+*/
+/***********************************************************************************/
+
+/* There was no way to incorporate following functions in one file */
+extern int DecompressJPEG16(SLICE_INFO* pSliceInfo, VR* pSequence,
+ void** ppResult, unsigned int * piResultSize);
+extern int DecompressJPEG12(SLICE_INFO* pSliceInfo, VR* pSequence,
+ void** ppResult, unsigned int * piResultSize);
+extern int DecompressJPEG8(SLICE_INFO* pSliceInfo, VR* pSequence,
+ void** ppResult, unsigned int * piResultSize);
+
+/* Forward declaration of RLE decompressor */
+static int DecompressRLE(SLICE_INFO* pSliceInfo, VR* pSequence,
+ void** ppResult, unsigned int * piResultSize);
+
+
+#define Uint8 unsigned char
+#define Uint16 unsigned short
+#define Uint32 unsigned int
+
+
+/* Following two functions are to find out which version of the ijg libraries
+ to use in order to decompress.
+*/
+static Uint16 readUint16(const Uint8* pData)
+{ return (((Uint16)(*pData) << 8) | ((Uint16)(*(pData+1))));
+}
+
+static Uint8 scanJpegDataForBitDepth(
+ const Uint8 *data,
+ const Uint32 fragmentLength)
+{
+ Uint32 offset = 0;
+ while(offset+4 < fragmentLength)
+ {
+ switch(readUint16(data+offset))
+ {
+ case 0xffc0: // SOF_0: JPEG baseline
+ return data[offset+4];
+ /* break; */
+ case 0xffc1: // SOF_1: JPEG extended sequential DCT
+ return data[offset+4];
+ /* break; */
+ case 0xffc2: // SOF_2: JPEG progressive DCT
+ return data[offset+4];
+ /* break; */
+ case 0xffc3 : // SOF_3: JPEG lossless sequential
+ return data[offset+4];
+ /* break; */
+ case 0xffc5: // SOF_5: differential (hierarchical) extended sequential, Huffman
+ return data[offset+4];
+ /* break; */
+ case 0xffc6: // SOF_6: differential (hierarchical) progressive, Huffman
+ return data[offset+4];
+ /* break; */
+ case 0xffc7: // SOF_7: differential (hierarchical) lossless, Huffman
+ return data[offset+4];
+ /* break; */
+ case 0xffc8: // Reserved for JPEG extentions
+ offset += readUint16(data+offset+2)+2;
+ break;
+ case 0xffc9: // SOF_9: extended sequential, arithmetic
+ return data[offset+4];
+ /* break; */
+ case 0xffca: // SOF_10: progressive, arithmetic
+ return data[offset+4];
+ /* break; */
+ case 0xffcb: // SOF_11: lossless, arithmetic
+ return data[offset+4];
+ /* break; */
+ case 0xffcd: // SOF_13: differential (hierarchical) extended sequential, arithmetic
+ return data[offset+4];
+ /* break; */
+ case 0xffce: // SOF_14: differential (hierarchical) progressive, arithmetic
+ return data[offset+4];
+ /* break; */
+ case 0xffcf: // SOF_15: differential (hierarchical) lossless, arithmetic
+ return data[offset+4];
+ /* break; */
+ case 0xffc4: // DHT
+ offset += readUint16(data+offset+2)+2;
+ break;
+ case 0xffcc: // DAC
+ offset += readUint16(data+offset+2)+2;
+ break;
+ case 0xffd0: // RST m
+ case 0xffd1:
+ case 0xffd2:
+ case 0xffd3:
+ case 0xffd4:
+ case 0xffd5:
+ case 0xffd6:
+ case 0xffd7:
+ offset +=2;
+ break;
+ case 0xffd8: // SOI
+ offset +=2;
+ break;
+ case 0xffd9: // EOI
+ offset +=2;
+ break;
+ case 0xffda: // SOS
+ offset += readUint16(data+offset+2)+2;
+ break;
+ case 0xffdb: // DQT
+ offset += readUint16(data+offset+2)+2;
+ break;
+ case 0xffdc: // DNL
+ offset += readUint16(data+offset+2)+2;
+ break;
+ case 0xffdd: // DRI
+ offset += readUint16(data+offset+2)+2;
+ break;
+ case 0xffde: // DHP
+ offset += readUint16(data+offset+2)+2;
+ break;
+ case 0xffdf: // EXP
+ offset += readUint16(data+offset+2)+2;
+ break;
+ case 0xffe0: // APPn
+ case 0xffe1:
+ case 0xffe2:
+ case 0xffe3:
+ case 0xffe4:
+ case 0xffe5:
+ case 0xffe6:
+ case 0xffe7:
+ case 0xffe8:
+ case 0xffe9:
+ case 0xffea:
+ case 0xffeb:
+ case 0xffec:
+ case 0xffed:
+ case 0xffee:
+ case 0xffef:
+ offset += readUint16(data+offset+2)+2;
+ break;
+ case 0xfff0: // JPGn
+ case 0xfff1:
+ case 0xfff2:
+ case 0xfff3:
+ case 0xfff4:
+ case 0xfff5:
+ case 0xfff6:
+ case 0xfff7:
+ case 0xfff8:
+ case 0xfff9:
+ case 0xfffa:
+ case 0xfffb:
+ case 0xfffc:
+ case 0xfffd:
+ offset += readUint16(data+offset+2)+2;
+ break;
+ case 0xfffe: // COM
+ offset += readUint16(data+offset+2)+2;
+ break;
+ case 0xff01: // TEM
+ break;
+ default:
+ if ((data[offset]==0xff) && (data[offset+1]>2) && (data[offset+1] <= 0xbf)) // RES reserved markers
+ {
+ offset += 2;
+ }
+ else return 0; // syntax error, stop parsing
+ break;
+ }
+ } // while
+ return 0; // no SOF marker found
+}
+
+
+/* This JPEG decompression function accepts a dicom VR with pixeldata-sequence,
+ and replaces the sequence by a 'normal' VR.
+ returns:
+ - DCM_E_UNSUPPORTED_FORMAT when the sequence was not understood
+ - DCM_E_UNSUPPORTED_COMPRESSION when the data are not supported by the ijg lib
+ - DCM_E_MEMORY when out of memory
+ - DCM_E_OK
+*/
+static int DecompressJPEG(SLICE_INFO* pSliceInfo, VR* pSequence)
+{ int rc = DCM_E_UNSUPPORTED_FORMAT;
+ Array<DICOMDataObject*>* pADDO;
+ DICOMDataObject* pDDO;
+ VR* pVR;
+ int iNbBitsPerSample;
+ void* pResult = NULL;
+ unsigned int iSize = 0;
+
+ /* Is the dicom-sequence OK? */
+ pADDO = (Array<DICOMDataObject*>*)pSequence->SQObjectArray;
+ if (!pADDO)
+ return rc;
+ pDDO = pADDO->Get(1);
+ if (!pDDO)
+ return rc;
+ pVR = pDDO->GetVR(0xfffe, 0xe000);
+ if (!pVR)
+ return rc;
+ if ((!pVR->Data) || (pVR->Length <= 0))
+ return rc;
+
+ /* Does ijg support the compression? */
+ iNbBitsPerSample = scanJpegDataForBitDepth((unsigned char*)pVR->Data, pVR->Length);
+ if ((iNbBitsPerSample <= 0) || (iNbBitsPerSample > 16))
+ { /* It is not a supported JPEG image. Maybe it is RLE compressed */
+ DecompressedRLE++;
+ rc = DecompressRLE(pSliceInfo, pSequence, &pResult, &iSize);
+ if (rc != DCM_E_OK)
+ return rc;
+ }
+ else
+ { /* Depending on iNbBitsPerSample, a different ijg libs/includes are used */
+ DecompressJpeg++;
+
+ if (iNbBitsPerSample > 12)
+ rc = DecompressJPEG16(pSliceInfo, pSequence, &pResult, &iSize);
+ else if (iNbBitsPerSample > 8)
+ rc = DecompressJPEG12(pSliceInfo, pSequence, &pResult, &iSize);
+ else
+ rc = DecompressJPEG8(pSliceInfo, pSequence, &pResult, &iSize);
+ }
+
+
+ /* When OK, replace the VR */
+ if (rc == DCM_E_OK)
+ { /* TO DO: add consistency checks iSize <--> DicomTags */
+ /* Cleanup the sequence, and make a normal VR */
+// delete[] pADDO;
+// pSequence->SQObjectArray = NULL;
+ pSequence->Reset();
+ pSequence->Data = pResult;
+ pSequence->ReleaseMemory = TRUE;
+ if (iSize & 0x01)
+ { ((char*)pResult)[iSize] = 0;
+ iSize++;
+ }
+ pSequence->Length = iSize;
+ }
+
+ return rc;
+}
+
+/***********************************************************************************/
+/*
+ JPEG decompression interface for dgate
+*/
+/***********************************************************************************/
+
+static int dcmdjpeg(DICOMDataObject* pDDO)
+{
+ /* Functions above (from CqDicom.dll) will do the work.
+ Here:
+ - Get the necessary parameters from pDDO, and put them in SLICE_INFO structure
+ - Adjust some dicom-tags
+ */
+ char s[100];
+ int rc;
+ VR *pVR;
+ SLICE_INFO *pSliceInfo;
+
+ rc = DCM_E_UNSUPPORTED_FORMAT;
+ if(!(pSliceInfo = getpSliceInfo(pDDO))) return rc;
+ if(pSliceInfo->iBitsStored == 0) pSliceInfo->iBitsStored = 16; // Default 16 bits
+
+ /* PixelData */
+ pVR = pDDO->GetVR(0x7fe0, 0x0010);
+
+ if(pVR)rc = DecompressJPEG(pSliceInfo, pVR); // And RLE
+
+ free(pSliceInfo);
+ if (rc != DCM_E_OK)
+ return rc;
+
+ /* Some tags need to been changed */
+
+ /*
+ The Attribute Lossy Image Compression (0028,2110) conveys that the Image has undergone
+ lossy compression. It provides a means to record that the Image has been compressed (at a
+ point in its lifetime) with a lossy algorithm and changes have been introduced into the pixel data.
+ Once the value has been set to '01', it shall not be reset.
+ Note: If an image is compressed with a lossy algorithm, the attribute Lossy Image Compression
+ (0028,2110) is set to '01'. Subsequently, if the image is decompressed and transferred in
+ uncompressed format, this attribute value remains '01'.
+ */
+
+ /* It seems we only have to change the TransferSyntaxUID to LittleEndianExplicit */
+ pDDO->ChangeVR( 0x0002, 0x0010, "1.2.840.10008.1.2.1\0", 'IU');
+
+ return rc;
+}
+
+#endif // #ifndef HAVE_LIBJPEG
+#endif // #ifndef NOINTJPEG
+
+/***********************************************************************************/
+/*
+
+*/
+/***********************************************************************************/
+
+// create tempory filename in printer_files directory for (de)compression
+
+static void NewTempFileWExt(char *name, const char *ext)
+ {
+ int i;
+ char name2[70], szTemp[256], szRootSC[256];
+
+ MyGetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile);
+ MyGetPrivateProfileString(szRootSC, "TempDir", "", szTemp, 64, ConfigFile);
+
+ if (szTemp[0]==0)
+ {
+ name[0]=0;
+ GetPhysicalDevice("MAG0", name);
+ strcat(name, "printer_files");
+ }
+ else
+ strcpy(name, szTemp);
+
+#ifndef WIN32
+ mkdir(name, 0777);
+#else
+ mkdir(name);
+#endif
+
+ i = strlen(name);
+ name[i] = PATHSEPCHAR;
+ name[i+1] = 0;
+
+ GenUID(name2);
+ strcat(name2, ext);
+
+ strcat(name, name2);
+ }
+
+static void NewTempFile(char *name)
+ {
+ NewTempFileWExt(name, ".dcm");
+ }
+
+// Decompress JPEG or NKI coded image file
+/*
+BOOL
+DecompressImageFile(char *file, int *Changed)
+ {
+ DICOMDataObject *pDDO;
+ PDU_Service PDU;
+// char name[1024];
+// VR *pVR;
+// BOOL nki, jpeg;
+// char option[20];
+// int len;
+
+// *Changed = 0;
+
+ PDU.AttachRTC(&VRType);
+
+ pDDO = PDU.LoadDICOMDataObject(file);
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[DecompressImageFile] %s -FAILED: Error on Load\n", file);
+ return FALSE;
+ }
+ if(!DecompressImage(&pDDO, Changed)) return FALSE;
+ if(*Changed) SaveDICOMDataObject(file, pDDO);
+ delete pDDO;
+ return ( TRUE );
+
+ }
+*/
+
+// Decompress NKI and/or JPEG coded image
+BOOL
+DecompressImage(DICOMDataObject **pDDO, int *Changed)
+ {
+ PDU_Service PDU;
+ char name[1024], name2[1024];
+ char *noPlane;
+ VR* pVR;
+ BOOL nki, jpeg;
+ int rc;
+ void* pResult = NULL;
+ unsigned int iSize = 0;
+ SLICE_INFO *pSliceInfo = NULL;
+
+ *Changed = 0;
+ noPlane = NULL;
+
+ PDU.AttachRTC(&VRType);
+
+ // is it nki compressed ?
+ nki = ((*pDDO)->GetVR(0x7fdf, 0x0010))!=NULL && ((*pDDO)->GetVR(0x7fe0, 0x0010))==NULL;
+
+ // is it jpeg compressed ?
+ pVR = (*pDDO)->GetVR(0x7fe0, 0x10);
+ jpeg = (pVR && pVR->SQObjectArray);
+#ifdef FUJI_FIX
+ // Look for a Jfif header. (LittleEndianImplicit, jpeg compressed, how evil)
+ if (!jpeg && pVR && ((unsigned char *)pVR->Data)[0] == 0xFF && ((unsigned char *)pVR->Data)[1] == 0xD8
+ && ((unsigned char*)pVR->Data)[2] == 0xFF && ((unsigned char *)pVR->Data)[3] == 0xE0
+ && ((char*)pVR->Data)[4] == 0x00 && ((char*)pVR->Data)[5] == 0x10
+ && strncmp(&((char *)pVR->Data)[6],"JFIF", 4) == 0)
+ {
+ jpeg = TRUE;
+ }
+#endif
+
+ if(jpeg) // or RLE
+ {
+// distinguish RLE converted from jpeg without TrnSyntaxUID mvh 20110413
+ BOOL isrle = FALSE;
+ Array < DICOMDataObject *> *pADDO;
+ pVR = (*pDDO)->GetVR(0x7fe0, 0x0010);
+ if (pVR && pVR->SQObjectArray)
+ {
+ pADDO = (Array<DICOMDataObject*>*)pVR->SQObjectArray;
+ if (pADDO->GetSize() > 1)
+ {
+ pVR = pADDO->Get(1)->GetVR(0xfffe, 0xe000);
+ if (pVR && pVR->Length>64)
+ {
+ int *piHeader = (int*)pVR->Data;
+ int offs1;
+#if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian
+ offs1 = SwitchEndian(piHeader[1]);
+#else
+ offs1 = piHeader[1];
+#endif
+ isrle = offs1==64;
+ }
+ }
+ }
+// end distinguish RLE converted from jpeg without TrnSyntaxUID mvh 20110413
+
+ pVR = (*pDDO)->GetVR(0x0002, 0x0010);
+ if ((!pVR || (pVR->Length == 20 && ((char*)pVR->Data)[18] == '5')) && isrle) //RLE or no 0x0002, 0x0010
+ {
+ rc = DCM_E_UNSUPPORTED_FORMAT;
+
+ if((pSliceInfo = getpSliceInfo(*pDDO)))
+ {
+ if(pSliceInfo->iBitsStored == 0)
+ pSliceInfo->iBitsStored = 16; // Default 16 bits
+
+ pVR = (*pDDO)->GetVR(0x7fe0, 0x0010);
+ if(pVR) rc = DecompressRLE(pSliceInfo, pVR, &pResult, &iSize);
+ free(pSliceInfo);
+ if (rc == DCM_E_OK)// RLE decompressed
+ {
+ // Fix the image
+ pVR->Reset();
+ pVR->Data = pResult;
+ pVR->ReleaseMemory = TRUE;
+ if (iSize & 0x01)
+ {
+ ((char*)pResult)[iSize] = 0;
+ iSize++;
+ }
+ pVR->Length = iSize;
+ if(!(pVR = (*pDDO)->GetVR(0x0002, 0x0010)))
+ {
+ pVR = new VR(0x0002, 0x0010, 0, (void *)NULL, FALSE);
+ (*pDDO)->Push(pVR);
+ }
+ pVR->ReAlloc(20);
+ memcpy((char *)pVR->Data, "1.2.840.10008.1.2.1\0",20);// LittleEndianExplict
+ DecompressedRLE++;
+ *Changed = 1;
+ jpeg = FALSE;// Check for planes
+ }
+ }
+ }
+#ifdef HAVE_J2K // JPEG 2000 stuff
+ else if(pVR && pVR->Length == 22 && ((char*)pVR->Data)[20] == '9')//90 or 91 is jpeg 2000.
+ {
+#ifndef HAVE_BOTH_J2KLIBS
+#ifdef HAVE_LIBJASPER
+ if(!DecompressJPEG2K(*pDDO))
+#endif
+#ifdef HAVE_LIBOPENJPEG
+ if(!DecompressJPEG2Ko(*pDDO))
+#endif
+#else //HAVE_BOTH_J2KLIBS
+ if(gUseOpenJpeg)
+ {
+ if(!DecompressJPEG2Ko(*pDDO))
+ {
+ OperatorConsole.printf("***[DecompressImage]:OpenJPEG failed to decompress JP2000\n");
+ delete pDDO;
+ return FALSE;
+ }
+ }
+ else if(!DecompressJPEG2K(*pDDO))
+#endif
+ {
+ OperatorConsole.printf("***[DecompressImage]: failed to decompress JP2000\n");
+ delete pDDO;
+ return ( FALSE );
+ }
+ DecompressJpeg2000++;
+ *Changed = 1;
+ return ( TRUE );
+ }
+#endif //End HAVE_J2K
+ }
+
+ if (nki && !jpeg) // nki compressed
+ {
+ DecompressNKI(*pDDO);
+ *Changed = 1;
+ nki = FALSE; //Check for planes next
+ }
+
+ if (!nki && !jpeg) // not compressed
+ {
+ // Check if its Palette Color
+ pVR = (*pDDO)->GetVR(0x0028, 0x0004);
+ if(pVR && pVR->Length == 14 && strncmp( (char *)pVR->Data, "PALETTE COLOR", 13) == 0)
+ {
+ DecodePalette(*pDDO);
+ DePaletted++;
+ // palette is never planar; fix for colorzipped.tar test images
+ (*pDDO)->ChangeVR( 0x0028, 0x0006, (UINT8)0, 'US');// Not any more.
+ *Changed = 1;
+ }
+
+ //Planar check, done after RLE (& deflate?) decompression; only for RGB or YBR
+ if((*pDDO)->GetBYTE(0x0028, 0x0006))
+ if((*pDDO)->GetBYTE(0x0028, 0x0002)==3)
+ {
+ pVR = (*pDDO)->GetVR(0x7fe0, 0x0010);
+ if(pVR->Length) noPlane = DePlane((char *)pVR->Data, pVR->Length);
+ if(noPlane)
+ {
+ free(pVR->Data);
+ pVR->Data = noPlane;
+ (*pDDO)->ChangeVR( 0x0028, 0x0006, (UINT8)0, 'US');// Not any more.
+ DePlaned++;
+ *Changed = 1;
+ }
+ }
+
+ // Check if its YBR
+ pVR = (*pDDO)->GetVR(0x0028, 0x0004);// Have from above
+ if(pVR && pVR->Length == 8 && strncmp( (char *)pVR->Data, "YBR_FULL", 8) == 0)
+ {
+ pVR = (*pDDO)->GetVR(0x7fe0, 0x0010);
+ if(pVR->Length) DeYBRFULL((char *)pVR->Data, pVR->Length);
+ (*pDDO)->ChangeVR( 0x0028, 0x0004, "RGB\0", 'CS');
+ DePaletted++;
+ *Changed = 1;
+ }
+
+ return TRUE;
+ }
+
+ if(!UseBuiltInDecompressor())
+ {
+ NewTempFile(name);
+ NewTempFile(name2);
+
+ PDU.SaveDICOMDataObject(name, DICOM_CHAPTER_10_EXPLICIT, *pDDO);
+ delete *pDDO;
+ *pDDO=NULL;
+
+#ifdef WIN32
+ if (!ExecHidden("dcmdjpeg.exe", "-F +ti", name, name2, ""))
+#else
+ if (!ExecHidden("dcmdjpeg", "-F +ti", name, name2, "DCMDICTPATH=dicom.dic\0"))
+#endif
+
+ {
+ *pDDO = PDU.LoadDICOMDataObject(name);
+ unlink(name);
+ return FALSE;
+ }
+
+ *pDDO = PDU.LoadDICOMDataObject(name2);
+ if(!*pDDO)
+ {
+ OperatorConsole.printf("***[DecompressImage]: Error on load after external decompression, image not decompressed\n");
+ *pDDO = PDU.LoadDICOMDataObject(name); // mvh 20060402: restore original object
+ unlink(name);
+ //return FALSE;
+ return TRUE;
+ }
+
+ unlink(name);
+ unlink(name2);
+ DecompressJpeg++;
+ }
+#ifndef NOINTJPEG
+ else
+
+#ifdef HAVE_LIBJPEG
+ {
+ if(!DecompressJPEGL(*pDDO))
+ {
+ OperatorConsole.printf("***[DecompressImage]: JPEG library decompression error\n");
+ return(FALSE);
+ }
+ DecompressJpeg++;
+ }
+#else
+ {
+ if (dcmdjpeg(*pDDO) != DCM_E_OK)
+ {
+ OperatorConsole.printf("***[DecompressImage]: JPEG decompression error\n");
+ return FALSE;
+ }
+ DecompressJpeg++;
+ }
+#endif //HAVE_LIBJPEG #else
+#endif
+
+ *Changed = 1;
+ return ( TRUE );
+
+ }
+
+/*
+// Compress NKI coded image (FileCompressMode must be in [0..4], 0=uncompressed)
+BOOL
+CompressNKIImageFile(char *file, int lFileCompressMode, int *ActualMode)
+ {
+ DICOMDataObject *pDDO;
+ PDU_Service PDU;
+ int dum;
+
+ *ActualMode = -1;
+
+ PDU.AttachRTC(&VRType);
+
+ pDDO = PDU.LoadDICOMDataObject(file);
+
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[CompressNKIImageFile] %s -FAILED: Error on Load\n", file);
+ return FALSE;
+ }
+
+ DecompressImage(&pDDO, &dum); // make sure it is not NKI or JPEG compressed
+ if (dum) *ActualMode = 0;
+
+ if (lFileCompressMode>0 && lFileCompressMode<5)
+ if (!CompressNKI(pDDO, lFileCompressMode))
+ {
+ OperatorConsole.printf("***[CompressNKIImageFile]: failed to compress DICOM object %s\n", file);
+ delete pDDO;
+ return FALSE;
+ }
+
+ SaveDICOMDataObject(file, pDDO);
+
+ delete pDDO;
+ *ActualMode = lFileCompressMode;
+ return ( TRUE );
+}
+
+// Downsize image (lFileCompressMode must be in ['1','2', '4','8', 'a', 'b', 'c'], '1' = to 1024)
+BOOL
+DownSizeImageFile(char *file, int lFileCompressMode, int *ActualMode)
+ {
+ DICOMDataObject *pDDO;
+ PDU_Service PDU;
+ int dum, rc, size;
+
+ *ActualMode = -1;
+
+ PDU.AttachRTC(&VRType);
+
+ switch(lFileCompressMode)
+ {
+ case '1': size = 1024; break;
+ case '2': size = 512; break;
+ case '4': size = 256; break;
+ case '8': size = 128; break;
+ case 'A': case 'a': size = 64; break;
+ case 'B': case 'b': size = 32; break;
+ case 'C': case 'c': size = 16; break;
+ default : size =65536; break;
+ }
+
+ pDDO = PDU.LoadDICOMDataObject(file);
+
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[CompressNKIImageFile] %s -FAILED: Error on Load\n", file);
+ return FALSE;
+ }
+
+ if (TestDownsize(pDDO, NULL, size))
+ {
+ DecompressImage(&pDDO, &dum); // make sure it is not NKI or JPEG compressed
+ if (dum) *ActualMode = 0;
+
+ rc = MaybeDownsize(pDDO, NULL, size);
+
+ if (!rc)
+ {
+ OperatorConsole.printf("***[CompressNKIImageFile]: failed to downsize DICOM object %s\n", file);
+ delete pDDO;
+ return FALSE;
+ }
+
+ SaveDICOMDataObject(file, pDDO);
+
+ if (rc==2) *ActualMode = lFileCompressMode;
+ }
+
+ delete pDDO;
+ return ( TRUE );
+ }
+*/
+
+// Compress JPEG coded image file (lFileCompressMode must be in [0..6], 0=uncompressed)
+/*
+BOOL
+CompressJPEGImageFile(char *file, int lFileCompressMode, int *ActualMode)
+ {
+ DICOMDataObject *pDDO;
+ PDU_Service PDU;
+ char name[1024];
+ int dum, len, qual;
+ VR* pVR;
+
+ len = strlen(file);
+ if (len>3)
+ if (stricmp(file+len-3, ".v2")==0)
+ {
+ OperatorConsole.printf("[CompressJPEGImageFile]: cannot compress v2 file\n");
+ return FALSE;
+ }
+
+ *ActualMode = -1;
+
+ if (lFileCompressMode=='0')
+ {
+ *ActualMode = '0';
+ return DecompressImageFile(file, &dum);
+ }
+
+ PDU.AttachRTC(&VRType);
+
+ NewTempFile(name);
+
+ pDDO = PDU.LoadDICOMDataObject(file);
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[CompressJPEGImageFile] %s -FAILED: Error on Load\n", file);
+ return FALSE;
+ }
+
+ pVR = pDDO->GetVR(0x0008, 0x0060);
+ if (pVR)
+ {
+ if (pVR->Length>=2 && (memcmp(pVR->Data, "PR", 2)==0 ||
+ memcmp(pVR->Data, "SR", 2)==0 ||
+ memcmp(pVR->Data, "RT", 2)==0))
+ {
+ OperatorConsole.printf("[CompressJPEGImageFile]: JPEG compression not allowed for PR/SR/RT\n");
+ delete pDDO;
+ return FALSE;
+ }
+ }
+
+ if ((pDDO->GetVR(0x7fdf, 0x0010)) != NULL)
+ if (!DecompressNKI(pDDO))
+ {
+ OperatorConsole.printf("***[CompressJPEGImageFile]: failed to NKI decompress DICOM object %s\n", file);
+ delete pDDO;
+ return FALSE;
+ }
+
+#ifdef HAVE_J2K
+ if (lFileCompressMode=='K' || lFileCompressMode=='k' || lFileCompressMode=='L' || lFileCompressMode=='l')
+ {
+ if( lFileCompressMode=='L' || lFileCompressMode=='l')qual = 0;
+ else qual = 100;
+#ifndef HAVE_BOTH_J2KLIBS
+#ifdef HAVE_LIBJASPER
+ if(!CompressJPEG2K(pDDO,qual))
+#endif
+#ifdef HAVE_LIBOPENJPEG
+ if(!CompressJPEG2Ko(pDDO,qual))
+#endif
+#else //HAVE_BOTH_J2KLIBS
+ if(gUseOpenJpeg)
+ {
+ if(!CompressJPEG2Ko(pDDO,qual))
+ {
+ delete pDDO;
+ return FALSE;
+ }
+ }
+ else if(!CompressJPEG2K(pDDO,qual))
+#endif
+ {
+ delete pDDO;
+ return FALSE;
+ }
+ PDU.SaveDICOMDataObject(file, DICOM_CHAPTER_10_IMPLICIT, pDDO);
+ *ActualMode = lFileCompressMode;
+ delete pDDO;
+ CompressJpeg2000++;
+ return ( TRUE );
+ }
+#else //HAVE_J2K
+ if (lFileCompressMode=='K' || lFileCompressMode=='k' || lFileCompressMode=='L' || lFileCompressMode=='l')
+ {
+ OperatorConsole.printf("***[CompressJPEGImageFile]: jpeg 2000 not supported\n");
+ return FALSE;
+ }
+#endif //HAVE_J2K
+
+#ifdef HAVE_LIBJPEG
+// Jpeg standard is lossy = 8 or 12 bits.
+ if(lFileCompressMode > '2')//Lossy
+ {
+ int BitsAllocated = (pDDO)->GetBYTE(0x0028, 0x0100);
+ if(BitsAllocated > 12)
+ {
+ OperatorConsole.printf(
+ "Warn[CompressJPEGImage]: JPEG changed to lossless (J1) for %d bits data\n",
+ BitsAllocated);
+ lFileCompressMode = '1';//Most likely a store, we can take lossless, so change it.
+ }
+ }
+ if(!CompressJPEGL(pDDO, lFileCompressMode, 0))
+ {
+ delete pDDO;
+ return FALSE;
+ }
+ PDU.SaveDICOMDataObject(file, DICOM_CHAPTER_10_IMPLICIT, pDDO);
+ CompressJpeg++;
+ delete pDDO;
+
+#else //No LIBJPEG, do it the old way.
+
+ pVR = pDDO->GetVR(0x0028, 0x0004);
+ if (pVR)
+ {
+ if (pVR->Length>=12 && (memcmp(pVR->Data, "YBR_FULL_422", 12)==0))
+ {
+ OperatorConsole.printf("[CompressJPEGImageFile]: JPEG compression not allowed for YBR_FULL_422\n");
+ delete pDDO;
+ return FALSE;
+ }
+ }
+
+ pVR = pDDO->GetVR(0x0028, 0x0100);
+ if (pVR)
+ {
+ BOOL DecompressNon16BitsJpeg;
+ UseBuiltInDecompressor(&DecompressNon16BitsJpeg);
+
+ int BitsAllocated = *((UINT8 *)pVR->Data);
+ if (BitsAllocated!=16 && !DecompressNon16BitsJpeg)
+ {
+ OperatorConsole.printf("[CompressJPEGImageFile]: JPEG compression only supported for 16 bits data\n");
+ delete pDDO;
+ return FALSE;
+ }
+ }
+
+ switch(lFileCompressMode)
+ {
+ case '1': strcpy(opts, "+e1 +un +sr"); break; // default lossless SV1 "1.2.840.10008.1.2.4.70" = jpeg 14 (33%)
+ case '2': strcpy(opts, "+el +un +sr"); break; // lossless SV6 "1.2.840.10008.1.2.4.57" = jpeg 14 (33%)
+ case '3': strcpy(opts, "+eb +un +sr"); break; // baseline (8 bits ) "1.2.840.10008.1.2.4.50" = jpeg 1 (15%)
+ case '4': strcpy(opts, "+ee +un +sr"); break; // extended (12 bits) "1.2.840.10008.1.2.4.51" = jpeg 4 (15%)
+ case '5': strcpy(opts, "+es +un +sr"); break; // spectral sel "1.2.840.10008.1.2.4.53" = jpeg 8 (15%)
+ case '6': strcpy(opts, "+ep +un +sr"); break; // progressive "1.2.840.10008.1.2.4.55" = jpeg 12 (14%)
+
+ default:strcpy(opts, "+e1 +un +sr"); break; // default = lossless SV1
+ }
+
+ pVR = pDDO->GetVR(0x7fe0, 0x0010);
+ if (pVR)
+ pVR->TypeCode = 'OW';
+
+// mvh 20040602: why is this deleted at all?
+// pVR = pDDO->GetVR(0x0002, 0x0010);
+// if (pVR) pDDO->DeleteVR(pVR);
+
+ PDU.SaveDICOMDataObject(name, DICOM_CHAPTER_10_EXPLICIT, pDDO);
+ delete pDDO;
+
+#ifdef WIN32
+ if (!ExecHidden("dcmcjpeg.exe", opts, name, file, ""))
+#else
+ if (!ExecHidden("dcmcjpeg", opts, name, file, "DCMDICTPATH=dicom.dic\0"))
+#endif
+ { // if executable fails file did not change
+ unlink(name);
+ return ( FALSE );
+ }
+
+ unlink(name);
+ CompressJpeg++;
+#endif //HAVE_LIBJPEG #else
+ *ActualMode = lFileCompressMode;
+ return ( TRUE );
+ }
+*/
+
+// Compress JPEG coded image (lFileCompressMode must be in [0..6], 0=uncompressed)
+// CompressJPEGImage() used in one place later in this file, pDDO already decompressed. BCB
+BOOL
+CompressJPEGImage(DICOMDataObject **pDDO, int lFileCompressMode, int *ActualMode, int qual)
+ {
+ PDU_Service PDU;
+ char name[1024], name2[1024];
+ VR* pVR;
+ char opts[80];
+
+ *ActualMode = -1;
+
+ if (lFileCompressMode=='0')
+ {
+ *ActualMode = '0';
+ // return DecompressImage(pDDO, &dum); BCB
+ return TRUE;
+ }
+
+ PDU.AttachRTC(&VRType);
+
+ NewTempFile(name);
+ NewTempFile(name2);
+
+ pVR = (*pDDO)->GetVR(0x0008, 0x0060);
+ if (pVR)
+ {
+ if (pVR->Length>=2 && (memcmp(pVR->Data, "PR", 2)==0 ||
+ memcmp(pVR->Data, "SR", 2)==0 ||
+ memcmp(pVR->Data, "RT", 2)==0))
+ {
+ OperatorConsole.printf("[CompressJPEGImage]: JPEG compression not allowed for PR/SR/RT\n");
+ return FALSE;
+ }
+ }
+
+ if (((*pDDO)->GetVR(0x7fdf, 0x0010)) != NULL)
+ if (!DecompressNKI(*pDDO))
+ {
+ OperatorConsole.printf("***[CompressJPEGImage]: failed to NKI decompress DICOM object\n");
+ return FALSE;
+ }
+
+#ifdef HAVE_J2K
+ if (lFileCompressMode=='K' || lFileCompressMode=='k' || lFileCompressMode=='L' || lFileCompressMode=='l')
+ {
+ if( lFileCompressMode=='K' || lFileCompressMode=='k') qual = 100;
+#ifndef HAVE_BOTH_J2KLIBS
+#ifdef HAVE_LIBJASPER
+ if(!CompressJPEG2K(*pDDO,qual)) return FALSE;
+#endif
+#ifdef HAVE_LIBOPENJPEG
+ if(!CompressJPEG2Ko(*pDDO,qual)) return FALSE;
+#endif
+#else //HAVE_BOTH_J2KLIBS
+ if(gUseOpenJpeg)
+ {
+ if(!CompressJPEG2Ko(*pDDO,qual)) return FALSE;
+ }
+ else if(!CompressJPEG2K(*pDDO,qual)) return FALSE;
+#endif
+ *ActualMode = lFileCompressMode;
+ CompressJpeg2000++;
+ return ( TRUE );
+ }
+#else //HAVE_J2K
+ if (lFileCompressMode=='K' || lFileCompressMode=='k' || lFileCompressMode=='L' || lFileCompressMode=='l')
+ {
+ OperatorConsole.printf("***[CompressJPEGImage]: jpeg2000 not supported\n");
+ return FALSE;
+ }
+#endif //HAVE_J2K
+
+#ifdef HAVE_LIBJPEG
+ if(!UseBuiltInDecompressor())
+#else
+ if(1)
+#endif
+ {
+ pVR = (*pDDO)->GetVR(0x0028, 0x0100);
+ if (pVR)
+ {
+ BOOL DecompressNon16BitsJpeg;
+ UseBuiltInDecompressor(&DecompressNon16BitsJpeg);
+
+ int BitsAllocated = *((UINT8 *)pVR->Data);
+ if (BitsAllocated!=16 && !DecompressNon16BitsJpeg)
+ {
+ OperatorConsole.printf("[CompressJPEGImage]: JPEG compression only supported for 16 bits data\n");
+ return FALSE;
+ }
+ }
+
+ pVR = (*pDDO)->GetVR(0x0028, 0x0004);
+ if (pVR)
+ {
+ if (pVR->Length>=12 && (memcmp(pVR->Data, "YBR_FULL_422", 12)==0))
+ {
+ OperatorConsole.printf("[CompressJPEGImage]: JPEG compression not allowed for YBR_FULL_422\n");
+ return FALSE;
+ }
+ }
+
+ switch(lFileCompressMode)
+ {
+ case '1': strcpy(opts, "+e1 +un +sr"); break; // default lossless SV1 "1.2.840.10008.1.2.4.70" = jpeg 14 (33%)
+ case '2': strcpy(opts, "+el +un +sr"); break; // lossless SV6 "1.2.840.10008.1.2.4.57" = jpeg 14 (33%)
+ case '3': strcpy(opts, "+eb +un +sr"); break; // baseline (8 bits ) "1.2.840.10008.1.2.4.50" = jpeg 1 (15%)
+ case '4': strcpy(opts, "+ee +un +sr"); break; // extended (12 bits) "1.2.840.10008.1.2.4.51" = jpeg 4 (15%)
+ case '5': strcpy(opts, "+es +un +sr"); break; // spectral sel "1.2.840.10008.1.2.4.53" = jpeg 8 (15%)
+ case '6': strcpy(opts, "+ep +un +sr"); break; // progressive "1.2.840.10008.1.2.4.55" = jpeg 12 (14%)
+
+ default:strcpy(opts, "+e1 +un +sr"); break; // default = lossless SV1
+ }
+
+ pVR = (*pDDO)->GetVR(0x7fe0, 0x0010);
+ if (pVR)
+ pVR->TypeCode = 'OW';
+
+ PDU.SaveDICOMDataObject(name, DICOM_CHAPTER_10_EXPLICIT, *pDDO);
+ delete *pDDO;
+ *pDDO = NULL;
+
+#ifdef WIN32
+ if (!ExecHidden("dcmcjpeg.exe", opts, name, name2, ""))
+#else
+ if (!ExecHidden("dcmcjpeg", opts, name, name2, "DCMDICTPATH=dicom.dic\0"))
+#endif
+ {
+ *pDDO = PDU.LoadDICOMDataObject(name); // get back original image
+ unlink(name);
+ return FALSE;
+ }
+
+ *pDDO = PDU.LoadDICOMDataObject(name2);
+ if(!*pDDO)
+ {
+ OperatorConsole.printf("***[CompressJPEGImage]: Error on load after: dcmcjpeg %s %s out.dcm)\n", opts, name);
+ *pDDO = PDU.LoadDICOMDataObject(name); // get back original image
+ return FALSE;
+ }
+
+ unlink(name);
+ unlink(name2);
+ CompressJpeg++;
+
+ *ActualMode = lFileCompressMode;
+ return ( TRUE );
+ }
+
+#ifdef HAVE_LIBJPEG
+/* Jpeg standard is lossy = 8 or 12 bits. */
+ if(lFileCompressMode > '2')//Lossy
+ {
+ int BitsStored = (*pDDO)->GetBYTE(0x0028, 0x0101);
+ if(BitsStored > 12)
+ {
+ //OperatorConsole.printf(
+ //"Warn[CompressJPEGImage]: JPEG lossy compression does not support for %d bits data\n",
+ //BitsAllocated);
+ //return FALSE;//Most likely a c-move, don't know if they can take lossless, so don't compress.
+
+ OperatorConsole.printf(
+ "Warn[CompressJPEGImage]: JPEG changed to lossless (J1) for %d bits data\n",
+ BitsStored);
+ lFileCompressMode = '1';//Most likely a store, we can take lossless, so change it.
+ }
+ }
+ if(!CompressJPEGL(*pDDO, lFileCompressMode, qual)) return FALSE;
+ CompressJpeg++;
+#endif //HAVE_LIBJPEG #else
+ *ActualMode = lFileCompressMode;
+ return ( TRUE );
+ }
+
+BOOL recompressFile(char *File, char *Compression, ExtendedPDU_Service *PDU)
+ {
+// int status = 0;
+ BOOL rc = FALSE;
+
+ if (stricmp(Compression, "" )==0) return TRUE;
+ if (memicmp(Compression, "as", 2)==0) return TRUE;
+ if (stricmp(Compression, "is" )==0) return TRUE;
+
+ if (1)
+ { DICOMDataObject *pDDO;
+ PDU_Service PDU2;
+
+ PDU2.AttachRTC(&VRType);
+ pDDO = PDU2.LoadDICOMDataObject(File);
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[recompressFile] %s -FAILED: Error on Load\n", File);
+ return FALSE;
+ }
+
+ if ((rc=recompress(&pDDO, Compression, "", Compression[0]=='n' || Compression[0]=='N', PDU)))
+ SaveDICOMDataObject(File, pDDO);
+ delete pDDO;
+ }
+
+ return rc;
+/*
+ if (memicmp(Compression, "un", 2)==0) rc = DecompressImageFile(File, &status);
+ else if (memicmp(Compression, "j", 1)==0) rc = CompressJPEGImageFile(File, Compression[1], &status);
+ else if (memicmp(Compression, "nj", 2)==0)
+ {
+ DICOMDataObject* pDDO;
+ PDU_Service PDU;
+ char s[64];
+ VR *vr;
+
+ PDU.AttachRTC(&VRType);
+ pDDO = PDU.LoadDICOMDataObject(File);
+
+ s[0] = 0;
+ vr = pDDO->GetVR(0x0002, 0x0010);
+ if (vr && vr->Data)
+ strncpy(s, (char*)vr->Data, vr->Length); s[vr->Length] = 0;
+
+ delete pDDO;
+
+ // leave JPEG as is
+#ifdef HAVE_J2K // JPEG 2000 stuff
+ if (strcmp(s, "1.2.840.10008.1.2.4.91")==0) return TRUE;
+ if (strcmp(s, "1.2.840.10008.1.2.4.90")==0) return TRUE;
+#endif
+ if (strcmp(s, "1.2.840.10008.1.2.4.70")==0) return TRUE;
+ if (strcmp(s, "1.2.840.10008.1.2.4.57")==0) return TRUE;
+ if (strcmp(s, "1.2.840.10008.1.2.4.50")==0) return TRUE;
+ if (strcmp(s, "1.2.840.10008.1.2.4.51")==0) return TRUE;
+ if (strcmp(s, "1.2.840.10008.1.2.4.53")==0) return TRUE;
+ if (strcmp(s, "1.2.840.10008.1.2.4.55")==0) return TRUE;
+
+ if (!DecompressImageFile(File, &status)) return FALSE;
+ rc = CompressNKIImageFile (File, MAXNKICOMPRESSION, &status);
+ }
+ else if (memicmp(Compression, "uj", 2)==0)
+ {
+ DICOMDataObject* pDDO;
+ PDU_Service PDU;
+ char s[64];
+ VR *vr;
+
+ PDU.AttachRTC(&VRType);
+ pDDO = PDU.LoadDICOMDataObject(File);
+
+ s[0] = 0;
+ vr = pDDO->GetVR(0x0002, 0x0010);
+ if (vr && vr->Data)
+ strncpy(s, (char*)vr->Data, vr->Length); s[vr->Length] = 0;
+
+ delete pDDO;
+
+ // leave JPEG as is
+#ifdef HAVE_J2K // JPEG 2000 stuff
+ if (strcmp(s, "1.2.840.10008.1.2.4.91")==0) return TRUE;
+ if (strcmp(s, "1.2.840.10008.1.2.4.90")==0) return TRUE;
+#endif
+ if (strcmp(s, "1.2.840.10008.1.2.4.70")==0) return TRUE;
+ if (strcmp(s, "1.2.840.10008.1.2.4.57")==0) return TRUE;
+ if (strcmp(s, "1.2.840.10008.1.2.4.50")==0) return TRUE;
+ if (strcmp(s, "1.2.840.10008.1.2.4.51")==0) return TRUE;
+ if (strcmp(s, "1.2.840.10008.1.2.4.53")==0) return TRUE;
+ if (strcmp(s, "1.2.840.10008.1.2.4.55")==0) return TRUE;
+
+ rc = DecompressImageFile(File, &status);
+ }
+ else if (memicmp(Compression, "n", 1)==0)
+ {
+ if (!DecompressImageFile(File, &status)) return FALSE;
+ if (Compression[1]=='0') rc = TRUE;
+ else rc = CompressNKIImageFile (File, Compression[1]-'0', &status);
+ }
+ else if (memicmp(Compression, "k", 1)==0)
+ {
+ if (!DecompressImageFile(File, &status)) return FALSE;
+ if (Compression[1]=='0') rc = TRUE;
+ else rc = DownSizeImageFile (File, Compression[1], &status);
+ }
+ else if (memicmp(Compression, "s", 1)==0)
+ {
+ DICOMDataObject *pDDO;
+ PDU_Service PDU;
+// int dum;
+
+ PDU.AttachRTC(&VRType);
+ pDDO = PDU.LoadDICOMDataObject(File);
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[recompressFile] %s -FAILED: Error on Load\n", File);
+ return FALSE;
+ }
+
+ //VR *VariableVRs[3] = {NULL, NULL, NULL};
+ CallImportConverterN(pDDO, 1400 + Compression[1] - '0', NULL, NULL, NULL, NULL,
+ "calling", "called", NULL, NULL);
+
+ SaveDICOMDataObject(File, pDDO);
+ delete pDDO;
+ rc=status=1;
+ }
+
+ if (rc && status>0)
+ OperatorConsole.printf("[recompressFile]: recompressed with mode = %s\n", Compression);
+
+ return rc;
+*/
+ }
+
+static void Strip2(DICOMDataObject *pDDO)
+{ DICOMObject DO2;
+ VR *vr;
+
+ while((vr=pDDO->Pop()))
+ {
+ if (vr->Group==2) delete vr;
+ else DO2.Push(vr);
+ }
+
+ pDDO->Reset();
+ while((vr=DO2.Pop())) pDDO->Push(vr);
+}
+
+// use Filename to optionally forbid illegal compressions (e.g. nki->.dcm & jpeg->.v2)
+BOOL recompress(DICOMDataObject **pDDO, const char *Compression, const char *Filename, BOOL StripGroup2, ExtendedPDU_Service *PDU)
+ {
+ int status = 0;
+ BOOL rc = FALSE, pass, all;
+ UNUSED_ARGUMENT(Filename);
+
+ // no strip group 2 for these options!
+ if (stricmp(Compression, "" )==0) return TRUE;
+ if (memicmp(Compression, "as", 2)==0) return TRUE;
+ if (stricmp(Compression, "is" )==0) return TRUE;
+ if (memicmp(Compression, "v" , 1)==0) return TRUE;
+
+ int t = (int)time(NULL);
+
+ if (memicmp(Compression, "uj", 2)==0)
+ {
+ char s[64];
+ VR *vr = (*pDDO)->GetVR(0x0002, 0x0010);
+ if (vr && vr->Data)
+ {
+ strncpy(s, (char*)vr->Data, vr->Length); s[vr->Length] = 0;
+
+ // leave JPEG as is
+ if ((strcmp(s, "1.2.840.10008.1.2.4.70")==0) ||
+#ifdef HAVE_J2K // JPEG 2000 stuff
+ (strcmp(s, "1.2.840.10008.1.2.4.90")==0) ||
+ (strcmp(s, "1.2.840.10008.1.2.4.91")==0) ||
+#endif
+ (strcmp(s, "1.2.840.10008.1.2.4.57")==0) ||
+ (strcmp(s, "1.2.840.10008.1.2.4.50")==0) ||
+ (strcmp(s, "1.2.840.10008.1.2.4.51")==0) ||
+ (strcmp(s, "1.2.840.10008.1.2.4.53")==0) ||
+ (strcmp(s, "1.2.840.10008.1.2.4.55")==0))
+ {
+ if (StripGroup2) Strip2(*pDDO);
+ return TRUE;
+ }
+ }
+
+ rc = DecompressImage(pDDO, &status);
+ }
+
+ //added uncompressed LittleEndianImplicit, LittleEndianExplicit or BigEndianExplicit. bcb
+ else if (*Compression == 'u' || *Compression == 'U' )
+ {
+ char s[64];
+ VR *vr = (*pDDO)->GetVR(0x0002, 0x0010);
+ if (vr && vr->Data)
+ {
+ strncpy(s, (char*)vr->Data, vr->Length); s[vr->Length] = 0;
+ s[18] = '0';// Used for switch in LittleEndianImplicit.
+
+ // skip recompression to original level, only LittleEndianImplicit is 17 long
+ if (strncmp(s, "1.2.840.10008.1.2", 17)==0)
+ {
+ pass = FALSE;
+ all = TRUE;// Stays true for all except default
+
+ switch (s[18])
+ {
+ case '0': if (Compression[1]=='i'|| Compression[1]=='I')
+ pass = TRUE;
+ break;
+ case '1': if (Compression[1]=='l'|| Compression[1]=='L')
+ pass = TRUE;
+ break;
+ case '2': if (Compression[1]=='b'|| Compression[1]=='B')
+ pass = TRUE;
+ break;
+ default: all = FALSE;// RLE
+ break;
+ }
+ // Test for "un"
+ if (all && (Compression[1]=='n' || Compression[1]=='N')) pass = FALSE;
+
+ if((*pDDO)->GetBYTE(0x0028, 0x0006)) pass=FALSE; // deplaning should happen 20101220
+
+ VR *pVR = (*pDDO)->GetVR(0x0028, 0x0004); // depalette should happen 20101220
+ if(pVR && pVR->Length == 14 && strncmp( (char *)pVR->Data, "PALETTE COLOR", 13) == 0) pass = FALSE;
+
+ if (pass)
+ {
+ if (StripGroup2) Strip2(*pDDO);
+ return TRUE;
+ }
+ }
+ }
+ if((rc = DecompressImage(pDDO, &status)))
+ {
+ // Tell "DCM to VR" what it is. May want to set "un" to a specific type
+ if(Compression[1]=='i'|| Compression[1] == 'I')
+ (*pDDO)->ChangeVR( 0x0002, 0x0010, "1.2.840.10008.1.2\0", 'IU');
+ if(Compression[1]=='l'|| Compression[1] == 'L')
+ (*pDDO)->ChangeVR( 0x0002, 0x0010, "1.2.840.10008.1.2.1\0", 'IU');
+ if(Compression[1]=='b'|| Compression[1] == 'B')
+ (*pDDO)->ChangeVR( 0x0002, 0x0010, "1.2.840.10008.1.2.2\0", 'IU');
+ }
+ }
+
+ else if (memicmp(Compression, "j", 1)==0)
+ {
+ char s[64];
+ VR *vr = (*pDDO)->GetVR(0x0002, 0x0010);
+ if (vr && vr->Data)
+ {
+ strncpy(s, (char*)vr->Data, vr->Length); s[vr->Length] = 0;
+
+ // skip recompression to original level
+ if(strncmp(s,"1.2.840.10008.1.2.4.",20)==0)//Common to all jpeg
+ {
+ pass = FALSE;
+ all = TRUE;// Stays true for all except default
+ switch (atoi(s + 20))
+ {
+ case 50: if (Compression[1]=='3') pass = TRUE;
+ break;
+ case 51: if (Compression[1]=='4') pass = TRUE;
+ break;
+ case 53: if (Compression[1]=='5') pass = TRUE;
+ break;
+ case 55: if (Compression[1]=='6') pass = TRUE;
+ break;
+ case 57: if (Compression[1]=='2') pass = TRUE;
+ break;
+ case 70: if (Compression[1]=='1') pass = TRUE;
+ break;
+#ifdef HAVE_J2K // JPEG 2000 stuff
+ case 90: if (Compression[1]=='k' || Compression[1]=='k') pass = TRUE;
+ break;
+ case 91: if (Compression[1]=='l' || Compression[1]=='L') pass = TRUE;
+ break;
+#endif
+ default: all = FALSE;// What is this, unknown jpeg.
+ break;
+ }
+ // Test for "ja"
+ if (all && (Compression[1]=='a' || Compression[1]=='A')) pass = TRUE;
+ if (pass)
+ {
+ if (StripGroup2) Strip2(*pDDO);
+ return TRUE;
+ }
+ }
+/* The switch is easier to add ja (all)
+ if ((strcmp(s, "1.2.840.10008.1.2.4.70")==0 && Compression[1]=='1') ||
+ (strcmp(s, "1.2.840.10008.1.2.4.57")==0 && Compression[1]=='2') ||
+ (strcmp(s, "1.2.840.10008.1.2.4.50")==0 && Compression[1]=='3') ||
+ (strcmp(s, "1.2.840.10008.1.2.4.51")==0 && Compression[1]=='4') ||
+ (strcmp(s, "1.2.840.10008.1.2.4.53")==0 && Compression[1]=='5') ||
+ (strcmp(s, "1.2.840.10008.1.2.4.55")==0 && Compression[1]=='6')
+#ifdef HAVE_J2K // JPEG 2000 stuff
+ || (strcmp(s, "1.2.840.10008.1.2.4.90")==0 && (Compression[1]=='k' || Compression[1]=='K')) ||
+ (strcmp(s, "1.2.840.10008.1.2.4.91")==0 && (Compression[1]=='l' || Compression[1]=='L'))
+#endif
+ )
+ {
+ if (StripGroup2) Strip2(*pDDO);
+ return TRUE;
+ }*/
+ }
+
+ int qual = 0; // default as configured in dicom.ini
+ if (Compression[2]) qual = atoi(Compression+2);
+
+ if (!DecompressImage(pDDO, &status)) return FALSE;
+ rc = CompressJPEGImage(pDDO, Compression[1], &status, qual);
+ if (strchr("3456lL", Compression[1]))
+ (*pDDO)->ChangeVR(0x0028, 0x2110, "01", 'CS'); // 20120624: set lossy compression
+ }
+
+ else if (memicmp(Compression, "nj", 2)==0)
+ {
+ char s[64];
+ VR *vr = (*pDDO)->GetVR(0x0002, 0x0010);
+ if (vr && vr->Data)
+ {
+ strncpy(s, (char*)vr->Data, vr->Length); s[vr->Length] = 0;
+
+ // leave JPEG as is
+ if ((strcmp(s, "1.2.840.10008.1.2.4.70")==0) ||
+#ifdef HAVE_J2K // JPEG 2000 stuff
+ (strcmp(s, "1.2.840.10008.1.2.4.90")==0) ||
+ (strcmp(s, "1.2.840.10008.1.2.4.91")==0) ||
+#endif
+ (strcmp(s, "1.2.840.10008.1.2.4.57")==0) ||
+ (strcmp(s, "1.2.840.10008.1.2.4.50")==0) ||
+ (strcmp(s, "1.2.840.10008.1.2.4.51")==0) ||
+ (strcmp(s, "1.2.840.10008.1.2.4.53")==0) ||
+ (strcmp(s, "1.2.840.10008.1.2.4.55")==0))
+ {
+ if (StripGroup2) Strip2(*pDDO);
+ return TRUE;
+ }
+ }
+
+ if (!DecompressImage(pDDO, &status)) return FALSE;
+ rc = CompressNKI(*pDDO, MAXNKICOMPRESSION);
+ status = rc;
+ }
+
+ else if (memicmp(Compression, "n", 1)==0)
+ {
+ // skip recompression to original level
+ signed char *p;
+ VR *vr = (*pDDO)->GetVR(0x7fdf, 0x0010);
+ if (vr)
+ {
+ p = ((signed char *)(vr->Data));
+ if (p && get_nki_private_compress_mode(p)==Compression[1]-'0')
+ {
+ if (StripGroup2) Strip2(*pDDO);
+ return TRUE;
+ }
+ }
+
+ if (!DecompressImage(pDDO, &status)) return FALSE;
+
+ if (Compression[1]=='0') rc = TRUE;
+ else
+ {
+ rc = CompressNKI(*pDDO, Compression[1]-'0');
+ status = rc;
+ }
+ }
+
+ else if (memicmp(Compression, "k", 1)==0)
+ {
+ int size;
+
+ switch (Compression[1])
+ {
+ case '1': size = 1024; break;
+ case '2': size = 512; break;
+ case '4': size = 256; break;
+ case '8': size = 128; break;
+ case 'A': case 'a': size = 64; break;
+ case 'B': case 'b': size = 32; break;
+ case 'C': case 'c': size = 16; break;
+ default : size =65536; break;
+ }
+
+ if (TestDownsize(*pDDO, NULL, size))
+ {
+ if (!DecompressImage(pDDO, &status)) return FALSE;
+
+ switch (Compression[1])
+ {
+ case '1': rc = MaybeDownsize(*pDDO, NULL, 1024); break;
+ case '2': rc = MaybeDownsize(*pDDO, NULL, 512); break;
+ case '4': rc = MaybeDownsize(*pDDO, NULL, 256); break;
+ case '8': rc = MaybeDownsize(*pDDO, NULL, 128); break;
+ case 'A': case 'a': rc = MaybeDownsize(*pDDO, NULL, 64); break;
+ case 'B': case 'b': rc = MaybeDownsize(*pDDO, NULL, 32); break;
+ case 'C': case 'c': rc = MaybeDownsize(*pDDO, NULL, 16); break;
+ }
+ if (rc==2) status = 1;
+ }
+ else
+ status = 1;
+ }
+
+ else if (memicmp(Compression, "s", 1)==0)
+ {
+ //CallImportConverterN(*pDDO, 1400 + Compression[1] - '0', NULL, NULL, NULL, NULL, "calling", "called", NULL, NULL, VariableVRs);
+ CallImportConverterN(*pDDO, 1400 + Compression[1] - '0', NULL, NULL, NULL, NULL, PDU, NULL, NULL);
+ rc = status = 1;
+ }
+
+ if (StripGroup2) Strip2(*pDDO);
+
+ if (rc && status>0)
+ OperatorConsole.printf("[recompress]: recompressed with mode = %s (strip=%d)\n", Compression, StripGroup2);
+
+ RecompressTime += (int)time(NULL)-t;
+
+ return rc;
+ }
+
+///////////////////////////////////////////////////////////////////////////////////////////////
+// PDU with dgate compression styles
+///////////////////////////////////////////////////////////////////////////////////////////////
+
+BOOL
+ExtendedPDU_Service :: AddTransferSyntaxs(PresentationContext &PresContext)
+ {
+ UID uid;
+ TransferSyntax TrnSyntax;
+
+ // as-is not correctly implemented (hard to do, since each image will require other compression)
+ // will now tranmsit over ImplicitLittleEndian - OK for NKI clients
+
+ if (memicmp(RequestedCompressionType, "as", 2)==0 || memicmp(RequestedCompressionType, "is", 2)==0)
+ {
+ OperatorConsole.printf("Warning: use of as is compression for outgoing associations not fully implemented\n");
+ }
+ // Added uncompressed LittleEndianExplicit. bcb
+ if (memicmp(RequestedCompressionType, "ul", 2)==0)
+ {
+ uid.Set("1.2.840.10008.1.2.1"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ }
+ // Added uncompressed BigEndianExplicit. bcb
+ if (memicmp(RequestedCompressionType, "ub", 2)==0)
+ {
+ uid.Set("1.2.840.10008.1.2.2"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ }
+ // Added uncompressed LittleEndianExplicit or BigEndianExplicit. bcb
+ if (memicmp(RequestedCompressionType, "ue", 2)==0)
+ {
+ uid.Set("1.2.840.10008.1.2.1"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ uid.Set("1.2.840.10008.1.2.2"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ }
+
+ // only jpeg requires other tranmission syntaxes
+
+ if (RequestedCompressionType[0]=='j' || RequestedCompressionType[0]=='J')
+ {
+ switch(RequestedCompressionType[1])
+ {
+/* case '1': // lossless
+ uid.Set("1.2.840.10008.1.2.4.70"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ break;
+*/
+ // bcb: should not j1 & J2 offer both types of lossless.
+ case '1': // lossless
+ case '2': // losless sv 6
+ uid.Set("1.2.840.10008.1.2.4.57"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ uid.Set("1.2.840.10008.1.2.4.70"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ break;
+
+ case '3': // lossy baseline (8bit) + extended(12 bit)
+ case '4': uid.Set("1.2.840.10008.1.2.4.51"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ uid.Set("1.2.840.10008.1.2.4.50"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ break;
+
+ case '5': // spectral selection
+ uid.Set("1.2.840.10008.1.2.4.53"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ uid.Set("1.2.840.10008.1.2.4.51"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ uid.Set("1.2.840.10008.1.2.4.50"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ break;
+
+ case '6': // progressive
+ uid.Set("1.2.840.10008.1.2.4.55"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ uid.Set("1.2.840.10008.1.2.4.51"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ uid.Set("1.2.840.10008.1.2.4.50"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ break;
+
+#ifdef HAVE_J2K // JPEG 2000 stuff
+ case 'K':
+ case 'k': // 2K lossless only
+ uid.Set("1.2.840.10008.1.2.4.90"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ break;
+
+ case 'L':
+ case 'l': // 2K lossy or lossless
+ uid.Set("1.2.840.10008.1.2.4.91"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ uid.Set("1.2.840.10008.1.2.4.90"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ break;
+#endif
+
+ default: // lossless
+ // bcb added .57 here
+ uid.Set("1.2.840.10008.1.2.4.57"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ uid.Set("1.2.840.10008.1.2.4.70"); TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ break;
+ }
+ }
+
+ uid.Set("1.2.840.10008.1.2"); // ImplicitLittleEndian
+ TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+
+ return ( TRUE );
+ }
+
+BOOL
+ExtendedPDU_Service :: SetRequestedCompressionType(const char *type)
+ {
+ strcpy(RequestedCompressionType, type);
+ return ( TRUE );
+ }
+
+char*
+ExtendedPDU_Service :: GetAcceptedCompressionType(UID uid)
+ {
+ UID TrnSyntaxUID;
+ int ContextID = GetPresentationContextID(uid);
+ char *p;
+
+ if ( !ContextID )
+ {
+ strcpy(AcceptedCompressionType, "");
+ return ( AcceptedCompressionType );
+ }
+
+ GetTransferSyntaxUID(ContextID, TrnSyntaxUID);
+
+ if (RequestedCompressionType[0]!='j' && RequestedCompressionType[0]!='J')
+ {
+ strcpy(AcceptedCompressionType, RequestedCompressionType);
+ return ( AcceptedCompressionType );
+ }
+
+ p = (char *)TrnSyntaxUID.GetBuffer(1);
+ if (strcmp(p, "1.2.840.10008.1.2.4.70")==0) strcpy(AcceptedCompressionType, "j1");
+ else if (strcmp(p, "1.2.840.10008.1.2.4.57")==0) strcpy(AcceptedCompressionType, "j2");
+ else if (strcmp(p, "1.2.840.10008.1.2.4.50")==0) strcpy(AcceptedCompressionType, "j3");
+ else if (strcmp(p, "1.2.840.10008.1.2.4.51")==0) strcpy(AcceptedCompressionType, "j4");
+ else if (strcmp(p, "1.2.840.10008.1.2.4.53")==0) strcpy(AcceptedCompressionType, "j5");
+ else if (strcmp(p, "1.2.840.10008.1.2.4.55")==0) strcpy(AcceptedCompressionType, "j6");
+#ifdef HAVE_J2K // JPEG 2000 stuff
+ else if (strcmp(p, "1.2.840.10008.1.2.4.90")==0) strcpy(AcceptedCompressionType, "jk");
+ else if (strcmp(p, "1.2.840.10008.1.2.4.91")==0) strcpy(AcceptedCompressionType, "jl");
+#endif
+ // Added uncompressed LittleEndianImplicit, LittleEndianExplicit or BigEndianExplicit. bcb
+ else if (strcmp(p, "1.2.840.10008.1.2.1")==0) strcpy(AcceptedCompressionType, "ul");
+ else if (strcmp(p, "1.2.840.10008.1.2.2")==0) strcpy(AcceptedCompressionType, "ub");
+ else if (strcmp(p, "1.2.840.10008.1.2")==0) strcpy(AcceptedCompressionType, "ui");
+ else strcpy(AcceptedCompressionType, "un");
+
+ OperatorConsole.printf("Accepted compression: %s\n", AcceptedCompressionType);
+
+
+ return ( AcceptedCompressionType );
+ }
+
+
+////////////////////////////////////////////////////////////////////////////////////////////
+
+/* Downsize and convert image to 8 bit monochrome or RGB */
+
+static BOOL To8bitMonochromeOrRGB(DICOMDataObject* pDDO, int size, int *Dimx, int *Dimy, unsigned char **out, int RGBout=0, int level=0, int window=0, unsigned int frame=0)
+{ int i, j, dum;
+ VR* pVR;
+ unsigned int iMaxRowsColumns;
+ unsigned short iRows, iColumns, iNewRows, iNewColumns, iDownsizeFactor;
+ unsigned int iImageSize, iNbBytesPerPixel, iNbPixels, iSkip;
+ char* pcSrc;
+ unsigned char* pcDest;
+ short* psSrc;
+// int* piSrc;//Anything that points to VR->Data should be the same size on all systems. BCB
+ INT32* piSrc;
+ int r, g, b;
+ int pixeloffset = 0;
+
+ ExtractFrame(pDDO, frame);
+
+ if (size==0) iMaxRowsColumns = 16384;
+ else iMaxRowsColumns = size;
+
+ /* OK. Now check whether all necessary PixelData-info is present in pDDO */
+ iRows = pDDO->GetUINT16(0x0028, 0x0010);
+ iColumns = pDDO->GetUINT16(0x0028, 0x0011);
+ iNbPixels = iRows * iColumns;
+
+ if (!iNbPixels) /* Image must make sense */
+ return FALSE;
+
+ pVR = pDDO->GetVR(0x0008, 0x0060); /* Modality */
+ if (pVR && pVR->Length==2 && memcmp(pVR->Data, "CT", 2)==0)
+ { pVR = pDDO->GetVR(0x0028, 0x1052); /* RescaleIntercept */
+ if ( pVR) pixeloffset = pVR->Getatoi() + 1024;
+ }
+
+ if (iRows >= iColumns)
+ { iDownsizeFactor = iRows / iMaxRowsColumns;
+ if (iRows % iMaxRowsColumns)
+ iDownsizeFactor ++;
+ }
+ else
+ { iDownsizeFactor = iColumns / iMaxRowsColumns;
+ if (iColumns % iMaxRowsColumns)
+ iDownsizeFactor ++;
+ }
+
+ if (iDownsizeFactor<1) iDownsizeFactor=1;
+
+ if (!DecompressImage(&pDDO, &dum)) /* make sure it is not NKI or JPEG compressed */
+ return FALSE;
+
+ pVR = pDDO->GetVR(0x7fe0, 0x0010); /* Pixeldata */
+ if (!pVR)
+ return TRUE;
+ iImageSize = pVR->Length;
+
+ if ((iImageSize < iNbPixels) ||
+ (iImageSize % iNbPixels > 1)) /* allow 1 byte padding */
+ return FALSE; /* Image doesn't make sense */
+
+ iNbBytesPerPixel = iImageSize / iNbPixels;
+ if (iNbBytesPerPixel > 4)
+ return FALSE; /* Image is too beautiful to convert! */
+
+ /* LETS DO IT !
+ The downsized image is stored in the same memory-block as the original one:
+ Just be sure to adjust the length-indicator. The image will be (re)compressed anyway
+ later on.
+ */
+
+ iNewRows = iRows / iDownsizeFactor;
+ if (!iNewRows)
+ iNewRows++;
+ iNewColumns = iColumns / iDownsizeFactor;
+ if (!iNewColumns)
+ iNewColumns++;
+
+ if (RGBout & (iNewColumns&3)!=0)
+ iNewColumns &= 0xfffffffc; // make multiple of 4 (truncate some columns if needed)
+
+ *Dimy = iNewRows;
+ *Dimx = iNewColumns;
+
+ *out = (unsigned char *)malloc(iNewRows * iNewColumns * (RGBout?3:1));
+ if (*out==NULL) return FALSE;
+ pcDest = *out;
+
+ switch (iNbBytesPerPixel + 10 * RGBout)
+ { case 1:
+ pcSrc = (char*)pVR->Data;
+ for (i=0; i<iNewRows; i++)
+ { for (j=0; j<iNewColumns; j++)
+ { *pcDest++ = *pcSrc;
+ pcSrc += iDownsizeFactor;
+ }
+ pcSrc = (char*)pVR->Data + iDownsizeFactor * iColumns * (i + 1);
+ }
+ break;
+
+ case 2:
+ { int max=0;
+ psSrc = (short*)pVR->Data;
+
+ if (window)
+ { for (i=0; i<iNewRows; i++)
+ { for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ r = *psSrc + pixeloffset;
+#else //Big Endian like Apple power pc
+ r = SwitchEndian(*psSrc) + pixeloffset;
+#endif
+ r = 255 * (r - level + window/2) / window;
+ if (r>255) r=255;
+ if (r<0) r=0;
+ *pcDest++ = r;
+ psSrc += iDownsizeFactor;
+ }
+ psSrc = (short*)pVR->Data + iDownsizeFactor * iColumns * (i + 1);
+ }
+ }
+ else
+ { for (i=0; i<iNewRows; i++)
+ { for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ r = *psSrc + pixeloffset;
+#else //Big Endian like Apple power pc
+ r = SwitchEndian(*psSrc) + pixeloffset;
+#endif
+ if (r > max) max=r;
+ if (r>2047) r=2047;
+ if (r<0) r=0;
+ r = r/8;
+ *pcDest++ = r;
+ psSrc += iDownsizeFactor;
+ }
+ psSrc = (short*)pVR->Data + iDownsizeFactor * iColumns * (i + 1);
+ }
+
+ // auto scale if too dark or too bright
+
+ if (max < 1024 || max > 4095)
+ { int factor = (int)((max / 256.0) + 0.5);
+ if (factor==0) factor=1;
+
+ pcDest = *out;
+ psSrc = (short*)pVR->Data;
+ for (i=0; i<iNewRows; i++)
+ { for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ r = *psSrc + pixeloffset;
+#else //Big Endian like Apple power pc
+ r = SwitchEndian(*psSrc) + pixeloffset;
+#endif
+ r = r/factor;
+ if (r>255) r=255;
+ if (r<0) r=0;
+ *pcDest++ = r;
+ psSrc += iDownsizeFactor;
+ }
+ psSrc = (short*)pVR->Data + iDownsizeFactor * iColumns * (i + 1);
+ }
+ }
+ }
+
+ break;
+ }
+
+ case 3:
+ pcSrc = (char*)pVR->Data;
+ iSkip = (iDownsizeFactor - 1) * 3;
+ for (i=0; i<iNewRows; i++)
+ { for (j=0; j<iNewColumns; j++)
+ { r = *pcSrc++;
+ g = *pcSrc++;
+ b = *pcSrc++;
+ *pcDest++ = (r+g+b)/3;
+ pcSrc += iSkip;
+ }
+ pcSrc = (char*)pVR->Data + iDownsizeFactor * 3 * iColumns * (i + 1);
+ }
+ break;
+
+ case 4:
+ piSrc = (INT32*)pVR->Data;//Changed from (int*)
+ if (window)
+ { for (i=0; i<iNewRows; i++)
+ { for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ r = *piSrc + pixeloffset;
+#else //Big Endian like Apple power pc
+ r = SwitchEndian(*piSrc) + pixeloffset;
+#endif
+ r = 255 * (r - level + window/2) / window;
+ if (r>255) r=255;
+ if (r<0) r=0;
+ *pcDest++ = r;
+ piSrc += iDownsizeFactor;
+ }
+ piSrc = (INT32*)pVR->Data + iDownsizeFactor * iColumns * (i + 1);// was (int*)
+ }
+ }
+ else
+ { for (i=0; i<iNewRows; i++)
+ { for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ *pcDest++ = (*piSrc + pixeloffset) / 8;
+#else //Big Endian like Apple power pc
+ *pcDest++ = (SwitchEndian(*piSrc) + pixeloffset) / 8;
+#endif
+ piSrc += iDownsizeFactor;
+ }
+ piSrc = (INT32*)pVR->Data + iDownsizeFactor * iColumns * (i + 1);//Was(int*)
+ }
+ }
+ break;
+
+ case 11:
+ for (i=0; i<iNewRows; i++)
+ { pcSrc = (char*)pVR->Data + iDownsizeFactor * iColumns * (iNewRows-1-i);
+ for (j=0; j<iNewColumns; j++)
+ { *pcDest++ = *pcSrc;
+ *pcDest++ = *pcSrc;
+ *pcDest++ = *pcSrc;
+ pcSrc += iDownsizeFactor;
+ }
+ }
+ break;
+
+ case 12:
+ { int max=0;
+ if (window)
+ { for (i=0; i<iNewRows; i++)
+ { psSrc = (short*)pVR->Data + iDownsizeFactor * iColumns * (iNewRows-1-i);
+ for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ r = *psSrc + pixeloffset;
+#else //Big Endian like Apple power pc
+ r = SwitchEndian(*psSrc) + pixeloffset;
+#endif
+ r = 255 * (r - level + window/2) / window;
+ if (r>255) r=255;
+ if (r<0) r=0;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ psSrc += iDownsizeFactor;
+ }
+ }
+ }
+ else
+ { for (i=0; i<iNewRows; i++)
+ { psSrc = (short*)pVR->Data + iDownsizeFactor * iColumns * (iNewRows-1-i);
+ for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ r = *psSrc + pixeloffset;
+#else //Big Endian like Apple power pc
+ r = SwitchEndian(*psSrc) + pixeloffset;
+#endif
+ if (r > max) max=r;
+ if (r>2047) r=2047;
+ if (r<0) r=0;
+ r = r/8;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ psSrc += iDownsizeFactor;
+ }
+ }
+
+ // auto scale if too dark or too bright
+
+ if (max < 1024 || max > 4095)
+ { int factor = (int)((max / 256.0) + 0.5);
+ if (factor==0) factor=1;
+
+ pcDest = *out;
+ for (i=0; i<iNewRows; i++)
+ { psSrc = (short*)pVR->Data + iDownsizeFactor * iColumns * (iNewRows-1-i);
+ for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ r = *psSrc + pixeloffset;
+#else //Big Endian like Apple power pc
+ r = SwitchEndian(*psSrc) + pixeloffset;
+#endif
+ r = r/factor;
+ if (r>255) r=255;
+ if (r<0) r=0;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ psSrc += iDownsizeFactor;
+ }
+ }
+ }
+ }
+
+ break;
+ }
+
+ case 13:
+ iSkip = (iDownsizeFactor - 1) * 3;
+ for (i=0; i<iNewRows; i++)
+ { pcSrc = (char*)pVR->Data + iDownsizeFactor * 3 * iColumns * (iNewRows-1-i);
+ for (j=0; j<iNewColumns; j++)
+ { *pcDest++ = *pcSrc++;
+ *pcDest++ = *pcSrc++;
+ *pcDest++ = *pcSrc++;
+ pcSrc += iSkip;
+ }
+ }
+ break;
+
+ case 14:
+ if (window)
+ { for (i=0; i<iNewRows; i++)
+ { piSrc = (INT32*)pVR->Data + iDownsizeFactor * iColumns * (iNewRows-1-i);//Was (int*)
+ for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ r = *piSrc + pixeloffset;
+#else //Big Endian like Apple power pc
+ r = SwitchEndian(*piSrc) + pixeloffset;
+#endif
+ r = 255 * (r - level + window/2) / window;
+ if (r>255) r=255;
+ if (r<0) r=0;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ piSrc += iDownsizeFactor;
+ }
+ }
+ }
+ else
+ { for (i=0; i<iNewRows; i++)
+ { piSrc = (INT32*)pVR->Data + iDownsizeFactor * iColumns * (iNewRows-1-i);//Was (int*)
+ for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ *pcDest++ = (*piSrc + pixeloffset) / 8;
+ *pcDest++ = (*piSrc + pixeloffset) / 8;
+ *pcDest++ = (*piSrc + pixeloffset) / 8;
+#else //Big Endian like Apple power pc
+ *pcDest++ = (SwitchEndian(*piSrc) + pixeloffset) / 8;
+ *pcDest++ = (SwitchEndian(*piSrc) + pixeloffset) / 8;
+ *pcDest++ = (SwitchEndian(*piSrc) + pixeloffset) / 8;
+#endif
+ piSrc += iDownsizeFactor;
+ }
+ }
+ }
+ break;
+
+ case 21:
+ for (i=0; i<iNewRows; i++)
+ { pcSrc = (char*)pVR->Data + iDownsizeFactor * iColumns * i;
+ for (j=0; j<iNewColumns; j++)
+ { *pcDest++ = *pcSrc;
+ *pcDest++ = *pcSrc;
+ *pcDest++ = *pcSrc;
+ pcSrc += iDownsizeFactor;
+ }
+ }
+ break;
+
+ case 22:
+ { int max=0;
+ if (window)
+ { for (i=0; i<iNewRows; i++)
+ { psSrc = (short*)pVR->Data + iDownsizeFactor * iColumns * i;
+ for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ r = *psSrc + pixeloffset;
+#else //Big Endian like Apple power pc
+ r = SwitchEndian(*psSrc) + pixeloffset;
+#endif
+ r = 255 * (r - level + window/2) / window;
+ if (r>255) r=255;
+ if (r<0) r=0;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ psSrc += iDownsizeFactor;
+ }
+ }
+ }
+ else
+ { for (i=0; i<iNewRows; i++)
+ { psSrc = (short*)pVR->Data + iDownsizeFactor * iColumns * i;
+ for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ r = *psSrc + pixeloffset;
+#else //Big Endian like Apple power pc
+ r = SwitchEndian(*psSrc) + pixeloffset;
+#endif
+ if (r > max) max=r;
+ if (r>2047) r=2047;
+ if (r<0) r=0;
+ r = r/8;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ psSrc += iDownsizeFactor;
+ }
+ }
+
+ // auto scale if too dark or too bright
+
+ if (max < 1024 || max > 4095)
+ { int factor = (int)((max / 256.0) + 0.5);
+ if (factor==0) factor=1;
+
+ pcDest = *out;
+ for (i=0; i<iNewRows; i++)
+ { psSrc = (short*)pVR->Data + iDownsizeFactor * iColumns * i;
+ for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ r = *psSrc + pixeloffset;
+#else //Big Endian like Apple power pc
+ r = SwitchEndian(*psSrc) + pixeloffset;
+#endif
+ r = r/factor;
+ if (r>255) r=255;
+ if (r<0) r=0;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ psSrc += iDownsizeFactor;
+ }
+ }
+ }
+ }
+
+ break;
+ }
+
+ case 23:
+ iSkip = (iDownsizeFactor - 1) * 3;
+ for (i=0; i<iNewRows; i++)
+ { pcSrc = (char*)pVR->Data + iDownsizeFactor * 3 * iColumns * i;
+ for (j=0; j<iNewColumns; j++)
+ { *pcDest++ = *pcSrc++;
+ *pcDest++ = *pcSrc++;
+ *pcDest++ = *pcSrc++;
+ pcSrc += iSkip;
+ }
+ }
+ break;
+
+ case 24:
+ if (window)
+ { for (i=0; i<iNewRows; i++)
+ { piSrc = (INT32*)pVR->Data + iDownsizeFactor * iColumns * i;//Was (int*)
+ for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ r = *piSrc + pixeloffset;
+#else //Big Endian like Apple power pc
+ r = SwitchEndian(*piSrc) + pixeloffset;
+#endif
+ r = 255 * (r - level + window/2) / window;
+ if (r>255) r=255;
+ if (r<0) r=0;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ *pcDest++ = r;
+ piSrc += iDownsizeFactor;
+ }
+ }
+ }
+ else
+ { for (i=0; i<iNewRows; i++)
+ { piSrc = (INT32*)pVR->Data + iDownsizeFactor * iColumns * (iNewRows-1-i);//Was (int*)
+ for (j=0; j<iNewColumns; j++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ *pcDest++ = (*piSrc + pixeloffset) / 8;
+ *pcDest++ = (*piSrc + pixeloffset) / 8;
+ *pcDest++ = (*piSrc + pixeloffset) / 8;
+#else //Big Endian like Apple power pc
+ *pcDest++ = (SwitchEndian(*piSrc) + pixeloffset) / 8;
+ *pcDest++ = (SwitchEndian(*piSrc) + pixeloffset) / 8;
+ *pcDest++ = (SwitchEndian(*piSrc) + pixeloffset) / 8;
+#endif
+ piSrc += iDownsizeFactor;
+ }
+ }
+ }
+ break;
+ }
+
+ return TRUE;
+}
+
+int WriteGIF(FILE *fp, unsigned char *pic, int ptype, int w, int h,
+ unsigned char *rmap, unsigned char *gmap, unsigned char *bmap,
+ int numcols, int colorstyle, const char *comment);
+
+#ifndef hasColorStyleType
+#define hasColorStyleType 1
+enum ColorStyleType {csGlobalPalette, csLocalPalette};
+#endif
+
+int WriteGIFHeader(FILE *fp, int w, int h, BYTE *rmap, BYTE *gmap, BYTE *bmap,
+ int numcols, ColorStyleType colorstyle, char *comment);
+
+int WriteGIFFrame(FILE *fp, BYTE *p, int w, int h,
+ BYTE *rmap, BYTE *gmap, BYTE *bmap,
+ int numcols,
+ int frames, int time, ColorStyleType colorstyle);
+
+BOOL ToGif(DICOMDataObject* pDDO, char *filename, int size, int append, int level, int window, unsigned int frame)
+{ int dimx, dimy;
+ unsigned char *out;
+ FILE *f;
+ unsigned char lut[256];
+ int i;
+ int Ratefps;
+
+ for(i=0; i<256; i++) lut[i]=i;
+
+ if (append) f = fopen(filename, "ab");
+ else f = fopen(filename, "wb");
+ if (!f)
+ return FALSE;
+
+ // create animated GIF here
+ if (frame>10000 && GetNumberOfFrames(pDDO)>1)
+ { DICOMDataObject *DDO2 = MakeCopy(pDDO);
+ To8bitMonochromeOrRGB(DDO2, size, &dimx, &dimy, &out, 0, level, window, 0);
+ WriteGIFHeader(f, dimx, dimy, lut, lut, lut, 256, csLocalPalette, "NETSCAPE2.0");
+ delete DDO2;
+
+ for (i=0; i<GetNumberOfFrames(pDDO); i++)
+ { if (i>0)
+ { DDO2 = MakeCopy(pDDO);
+ To8bitMonochromeOrRGB(DDO2, size, &dimx, &dimy, &out, 0, level, window, i);
+ delete DDO2;
+ }
+
+ Ratefps = (frame % 100);
+ if (Ratefps==0) Ratefps=1;
+ if (out) WriteGIFFrame (f, out, dimx, dimy, lut, lut, lut, 256, 1, 100/Ratefps, csLocalPalette);
+ free(out);
+ }
+
+ fputc(0x3b, f); /* Write GIF file terminator */
+ fclose(f);
+ return TRUE;
+ }
+
+ // create static GIF here
+ if (To8bitMonochromeOrRGB(pDDO, size, &dimx, &dimy, &out, 0, level, window, frame))
+ { WriteGIF(f, out, 0, dimx, dimy, lut, lut, lut, 256, 0, "ConquestDICOMServer");
+ free(out);
+ fclose(f);
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+#pragma pack(1)
+typedef struct
+{ char bfType1; /* Must be 'B' */
+ char bfType2; /* Must be 'M' */
+ int bfSize; /* Size of the file */
+ short bfReserved1; /* Must be 0 */
+ short bfReserved2; /* Must be 0 */
+ int bfOffBits; /* Offset of the ImageBits */
+
+ int biSize; /* size of all biXX (40) */
+ int biWidth;
+ int biHeight;
+ short biPlanes;
+ short biBitCount;
+ int biCompression;
+ int biSizeImage;
+ int biXPelsPerMeter;
+ int biYPelsPerMeter;
+ int biClrUsed;
+ int biClrImportant;
+} BMP_HEADER; /* 24BITS */
+#pragma pack()
+
+BOOL ToBMP(DICOMDataObject* pDDO, char *filename, int size, int append, int level, int window, unsigned int frame)
+{ int dimx, dimy;
+ unsigned char *out, c;
+ FILE *f;
+ int i, t;
+ int iDataSize;
+ BMP_HEADER bmp;
+
+ if (To8bitMonochromeOrRGB(pDDO, size, &dimx, &dimy, &out, 1, level, window, frame))
+ { iDataSize = dimx*dimy*3; // must be multiple of 4: OK because above routine made dimx multiple of 4
+
+ // swap RGB to BGR
+ t = dimx * dimy;
+ for (i=0; i<t; i++) {c=out[i*3]; out[i*3]=out[i*3+2]; out[i*3+2]=c; }
+
+ memset((void*)&bmp, 0, sizeof(BMP_HEADER));
+ bmp.bfType1 = 'B';
+ bmp.bfType2 = 'M';
+ bmp.bfSize = iDataSize + sizeof(BMP_HEADER);
+ bmp.bfOffBits = sizeof(BMP_HEADER);
+
+ bmp.biSize = 40;
+ bmp.biWidth = dimx;
+ bmp.biHeight = dimy;
+ bmp.biPlanes = 1;
+ bmp.biBitCount = 24;
+ bmp.biSizeImage = iDataSize;
+ bmp.biXPelsPerMeter = 0x0ece;
+ bmp.biYPelsPerMeter = 0x0ece;
+
+ if (append) f = fopen(filename, "ab");
+ else f = fopen(filename, "wb");
+ if (!f)
+ { free(out);
+ return FALSE;
+ }
+
+ fwrite((void*)&bmp, sizeof(BMP_HEADER), 1, f);
+ fwrite(out, dimx*dimy*3, 1, f);
+
+ free(out);
+ fclose(f);
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+#ifdef HAVE_LIBJPEG //The jpeg common stuff.
+/* This is a replacement for the libjpeg message printer that normally
+* goes to stderr. */
+METHODDEF(void)
+joutput_message (j_common_ptr cinfo)
+{
+ char buffer[JMSG_LENGTH_MAX];
+
+ /* Create the message */
+ (*cinfo->err->format_message) (cinfo, buffer);
+
+ OperatorConsole.printf("***[JPEG Library]: %s\n", buffer);
+}
+
+/* This is a replacement for the libjpeg error handler that normally
+* halts the program. */
+METHODDEF(void)
+jerror_exit (j_common_ptr cinfo)
+{
+ /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
+ jerror_ptr jerr = (jerror_ptr) cinfo->err;
+
+ /* Always display the message */
+ (*cinfo->err->output_message) (cinfo);
+
+ /* Return control to the setjmp point */
+ longjmp(jerr->setjmp_buffer, 1);
+}
+
+/* Just for routines we do not need or use. */
+METHODDEF(void)
+jdoes_nothing (j_decompress_ptr cinfo)
+{
+/* Nothing */
+ UNUSED_ARGUMENT(cinfo);
+ return;
+}
+#else// Use jpeg_encoder.cpp
+UINT32 encode_image (UINT8 *input_ptr, UINT8 *output_ptr, UINT32 quality_factor, UINT32 image_format, UINT32 image_width, UINT32 image_height);
+#endif
+
+BOOL ToJPG(DICOMDataObject* pDDO, char *filename, int size, int append, int level, int window, unsigned int frame, int quality)
+{ int dimx, dimy;
+ unsigned char *out, c;
+ FILE *f;
+ int i, Ratefps;
+#ifdef HAVE_LIBJPEG
+ struct jpeg_compress_struct cinfo;
+ unsigned int rowWidth;
+ struct jerror_mgr jerr;
+ register JSAMPROW row_pointer;
+#endif
+
+ if (frame>10000 && GetNumberOfFrames(pDDO)>1)
+ { char file[256], file2[256];
+ DICOMDataObject *DDO2 = MakeCopy(pDDO);
+ NewTempFile(file);
+ for (i=0; i<GetNumberOfFrames(pDDO); i++)
+ { sprintf(file2, "%s.%05d", file, i);
+ ToJPG(DDO2, file2, size, 0, level, window, i, quality);
+ delete DDO2;
+ }
+
+ Ratefps = (frame % 100);
+ if (Ratefps==0) Ratefps=1;
+
+ // to convert a row of jpeg images to mpeg2 using mjpegtools:
+// jpeg2yuv -f 25 -I p -j dgate%03d.jpg | mpeg2enc -f 3 -b 1500 -o mpegfile.m2v
+// rate progr files mpg2 bitrate file
+ sprintf(file2, "jpeg2yuv -f %d -I p -j %s%%05d | mpeg2enc -f 3 -b 1500 -o %s", Ratefps, file, filename);
+ system(file2);
+
+ for (i=0; i<GetNumberOfFrames(pDDO); i++)
+ { sprintf(file2, "%s.%05d", file, i);
+ unlink(file2);
+ }
+ return TRUE;
+ }
+
+ if (To8bitMonochromeOrRGB(pDDO, size, &dimx, &dimy, &out, 2, level, window, frame))
+ { if (append) f = fopen(filename, "ab");
+ else f = fopen(filename, "wb");
+ if (!f)
+ { free(out);
+ return FALSE;
+ }
+#ifdef HAVE_LIBJPEG
+
+// Init the default handler.
+ cinfo.err = jpeg_std_error(&jerr.pub);
+// change the error exit so libjpeg can't kill us.
+ jerr.pub.error_exit = jerror_exit;
+// Use our methode for outputting messages.
+ jerr.pub.output_message = joutput_message;
+ if (setjmp(jerr.setjmp_buffer))
+ {
+/* If we get here, the JPEG code has signaled an error.
+ * We need to clean up the JPEG object and return. */
+ jpeg_destroy_compress(&cinfo);
+ if(f != NULL)
+ {
+ fclose(f);
+ if (!append)unlink(filename);
+ free(out);
+ }
+ return (FALSE);
+ }
+//Look for multi-byte version 6c (63) from www.bitsltd.net
+ jpeg_CreateCompress(&cinfo, 63, (size_t) sizeof(struct jpeg_compress_struct));
+// Color space must be set before a call to jpeg_set_defaults.
+ cinfo.in_color_space = JCS_RGB; //To8bitMonochromeOrRGB is set for rgb, gray could be faster.
+ jpeg_set_defaults(&cinfo);
+// Get all the image size stuff.
+ cinfo.image_height = dimy;
+ cinfo.image_width = dimx;
+ cinfo.num_components = 3;
+ cinfo.input_components = cinfo.num_components;
+ cinfo.data_precision = 8;
+ cinfo.data_precision_other = cinfo.data_precision;
+ jpeg_set_quality(&cinfo, 95, true);//100 is silly in lossy and the same as 95.
+ cinfo.jpeg_color_space = cinfo.in_color_space;
+ jpeg_default_colorspace(&cinfo);
+// Set where to put it.
+ jpeg_stdio_dest(&cinfo, f);
+ rowWidth = cinfo.image_width * cinfo.num_components;
+ jpeg_start_compress(&cinfo, TRUE);
+ while (cinfo.next_scanline < cinfo.image_height)
+ {
+ row_pointer = &(((JSAMPROW)out)[cinfo.next_scanline * rowWidth]);
+ jpeg_write_scanlines(&cinfo, &row_pointer, 1);
+ }
+// If here, finished the compression.
+ jpeg_finish_compress(&cinfo);
+ jpeg_destroy_compress(&cinfo);
+#else // Old way.
+ unsigned char *output = (UINT8 *)malloc(dimx * dimy * 3);
+ UINT32 len;
+ len = encode_image (out, output, 256, 14, dimx, dimy);
+ fwrite (output, 1, len, f);
+ free(output);
+#endif
+ free(out);
+ fclose(f);
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+#ifdef HAVE_LIBJPEG
+/* This routine will take all of the listed color spaces in 08_03 of the standard
+* in little endian, uncompressed format and convert it to YBR_FULL and than compress
+* it to jpeg. YBR_FULL is the IJG standard for the Jpeg-6b library used everywhere.
+* I did not use the Jpeg-6b version because it had to be compiled for 8, 12 or 16
+* only. So I wrote Jpeg-6c that can change bit width on the fly. You can get it here:
+* http://www.bitsltd.net/Software/Software-Repository/index.php
+* I included spectral sel "1.2.840.10008.1.2.4.53" and progressive
+* "1.2.840.10008.1.2.4.55", but both are obsolete and maybe I should remove them.
+* jpegQuality is meaningless for lossless and 0 for use "LossyQuality" in dicom.ini.
+* Maybe one day all of the format decoding should be moved into it's own routine.
+* If I have made some mistakes (most likely) you can contact me bruce.barton
+* (the mail symbol goes here) bitsltd.net. Let me know where I can find a sample of
+* the image that didn't work. */
+
+BOOL CompressJPEGL(DICOMDataObject* pDDO, int comp, int jpegQuality)
+{
+ Array < DICOMDataObject* > *ArrayPtr, *ArrayImage;
+ DICOMDataObject *DDO;
+ VR *pVR, *vrImage, *vrs;
+ char *colorASC, name[256], charY, charCb, charCr, *inData;
+ FILE *fp;
+ BOOL oddRow, buffer, progressive;
+ UINT8 colorType;
+ UINT16 frames;
+ register unsigned int rowWidth;
+ register int outInt, outInt1;
+ size_t fileLength, readLength;
+ int err, t;
+ unsigned int currFrame, frameSize, inputArrayCnt;
+ unsigned int byteWidthIn, byteWidth;
+ register JSAMPROW jbuffer, jbuffer_ptr, row_pointer[3];
+ JSAMPARRAY jarray;
+ struct jpeg_compress_struct cinfo;
+ struct jerror_mgr jerr;
+ JDIMENSION width, byteCnt;
+
+// If debug > 0, get start time.
+ t=0;
+ if (DebugLevel > 0)t = (unsigned int)time(NULL);
+ if (DebugLevel > 1) SystemDebug.printf("JPEG compress started.\n");
+// Are there frames?
+ currFrame = 0;
+ inputArrayCnt = 0;
+// Look for the frames vr.
+ if(!(frames = pDDO->Getatoi(0x0028, 0x0008))) frames = 1; // de.
+// Check and set the quality for lossy.
+ if(jpegQuality < MIN_QUALITY)// Set to 0 to use dicom.ini value.
+ {
+ jpegQuality = gJpegQuality;//Use the default or dicom.ini value.
+ }
+
+ if(jpegQuality > 100) jpegQuality = 100;
+// Init the default handler.
+ cinfo.err = jpeg_std_error(&jerr.pub);
+// change the error exit so libjpeg can't kill us.
+ jerr.pub.error_exit = jerror_exit;
+// Use our methode for outputting messages.
+ jerr.pub.output_message = joutput_message;
+
+ fp = NULL;
+ if (setjmp(jerr.setjmp_buffer))
+ {
+/* If we get here, the JPEG code has signaled an error.
+ * We need to clean up the JPEG object and return. */
+ jpeg_destroy_compress(&cinfo);
+ if(fp != NULL)
+ {
+ fclose(fp);
+ unlink(name);
+ }
+ return (FALSE);
+ }
+
+/* Look for multi-byte version 6c (63) from www.bitsltd.net */
+ jpeg_CreateCompress(&cinfo, 63,
+ (size_t) sizeof(struct jpeg_compress_struct));
+/* Color space must be set before a call to jpeg_set_defaults. */
+ cinfo.in_color_space = JCS_RGB; //Default,just a guess
+ jpeg_set_defaults(&cinfo);
+
+/* Get all the image size stuff. */
+// Get the Rows VR and check size
+ if(!(cinfo.image_height = (JDIMENSION)pDDO->GetUINT(0x0028, 0x0010)))
+ {
+ SystemDebug.printf("***[CompressJPEGL]: failed to get image height.\n");
+ jpeg_destroy_compress(&cinfo);
+ return(FALSE);
+ }
+ if(cinfo.image_height > JPEG_MAX_DIMENSION)
+ {
+ OperatorConsole.printf("***[CompressJPEGL]: %d too high for the jpeg standard.\n",
+ cinfo.image_height);
+ jpeg_destroy_compress(&cinfo);
+ return(FALSE);
+ }
+
+ // Get the Columns VR and check size.
+ if(!(cinfo.image_width = (JDIMENSION)pDDO->GetUINT(0x0028, 0x0011)))
+ {
+ OperatorConsole.printf("***[CompressJPEGL]: failed to get image width.\n");
+ jpeg_destroy_compress(&cinfo);
+ return(FALSE);
+ }
+ if(cinfo.image_width > JPEG_MAX_DIMENSION)
+ {
+ OperatorConsole.printf("***[CompressJPEGL]: %d too wide for the jpeg standard.\n",
+ cinfo.image_width);
+ jpeg_destroy_compress(&cinfo);
+ return(FALSE);
+ }
+// Get the number of samples per pixel VR.
+ if(!(cinfo.num_components = pDDO->GetBYTE(0x0028, 0x0002)))
+ cinfo.num_components = 1; // Gray default.
+ cinfo.input_components = cinfo.num_components;
+// Get the number of bits allocated.
+ if(!(cinfo.data_precision_other = pDDO->GetBYTE(0x0028, 0x0100)))
+ cinfo.data_precision_other = 8; // 8 bit default.
+// Get the number of bits stored.
+ if(!(cinfo.data_precision = pDDO->GetBYTE(0x0028, 0x0101)))
+ cinfo.data_precision = 8; // 8 bit default.
+// if(cinfo.data_precision > cinfo.data_precision_other)
+// cinfo.data_precision_other = cinfo.data_precision; /* the bigger one. */
+ if(cinfo.data_precision_other != 8 && cinfo.data_precision_other != 12
+ && cinfo.data_precision_other != 16)
+ {
+ jpeg_destroy_compress(&cinfo);
+ OperatorConsole.printf("***[CompressJPEGL]: Unsuported allocated bit width: %d.\n",
+ cinfo.data_precision_other);
+ return(FALSE);
+ }
+ byteWidthIn = 1;
+ if(cinfo.data_precision_other > 8) byteWidthIn = 2;
+ byteWidth = 1;
+ if(cinfo.data_precision > 8) byteWidth = 2;
+// Set the size of each image
+ frameSize = cinfo.image_width * cinfo.image_height * cinfo.num_components * byteWidthIn;
+ buffer = FALSE;
+// Set the defaults.
+ colorASC = NULL;//Default gray.
+ cinfo.in_color_space = JCS_GRAYSCALE;
+ colorType = CLRSPC_FAM_GRAYSCALE;
+ switch(cinfo.num_components)
+ {
+ case 1:// Leave the defaults.
+ break;
+ case 3:
+ pVR = pDDO->GetVR(0x0028, 0x0004); // Get the color profile.
+ if(pVR && pVR->Length > 2) colorASC = (char *)pVR->Data; //Might be YBR.
+ cinfo.in_color_space = JCS_RGB;// Default color space.
+ colorType = CLRSPC_FAM_RGB;
+ break;
+ default:
+ jpeg_destroy_compress(&cinfo);
+ OperatorConsole.printf("***[CompressJPEGL]: Unsuported number of components: %d.\n",
+ cinfo.num_components );
+ return(FALSE);
+ }
+// Other color types can be added.
+ if (colorType == CLRSPC_FAM_GRAYSCALE)
+ {// Leave defaults
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ if(cinfo.data_precision_other == 12) // Byte fix time
+#else//Big Endian like Apple power pc.
+ if(byteWidthIn == 2) // Byte swap time
+#endif //Big Endian
+ buffer = TRUE;
+ }
+ else if (cinfo.in_color_space == JCS_RGB &&
+ (colorASC == NULL || strncmp(colorASC, "RGB",3)==0))
+ {// Any problems should pick here. Leave color defaults.
+// Planar configuration
+ if(pDDO->GetBYTE(0x0028, 0x0006) == 1) buffer = TRUE;
+ }
+ else if (pVR->Length > 6 && strncmp(colorASC, "YBR_",4)==0)
+ {
+ if(strncmp(&colorASC[4], "ICT", 3)==0 || strncmp(&colorASC[4], "RCT", 3)==0)
+ {
+ OperatorConsole.printf
+ ("Warn[CompressJPEGL]: Uncompressed colorspace can not be YBR_ICT or YBR_RCT. Trying RGB\n");
+ cinfo.in_color_space = JCS_RGB;
+ colorType = CLRSPC_FAM_RGB;
+ }
+ else if (pVR->Length > 7 && strncmp(&colorASC[4], "FULL", 4)==0)//YBR_FULL(_422)
+ {
+ cinfo.in_color_space = JCS_YCbCr;
+ buffer = TRUE;
+ if(pVR->Length > 11 && (strncmp(&colorASC[8], "_422", 4)==0))//YBR_FULL_422
+ colorType = CLRSPC_FAM_YCBCR_F422;
+ else // YBR_FULL
+ colorType = CLRSPC_FAM_YBR_FULL;
+ }
+ else if (pVR->Length > 14 && strncmp(&colorASC[4], "PARTIAL_42", 10)==0)//YBR_PARTIAL_42x
+ {
+ cinfo.in_color_space = JCS_YCbCr;
+ buffer = TRUE;
+ if(colorASC[14] == '0')colorType = CLRSPC_FAM_YCBCR_420;
+ else colorType = CLRSPC_FAM_YCBCR_422;
+ }
+ } // End if YBR_
+ else
+ {
+ if((colorASC = pDDO->GetCString(0x0028, 0x0004)))
+ {
+ OperatorConsole.printf(
+ "***[CompressJPEGL]: Unknown or unsuported color space %s.\n",colorASC);
+ free(colorASC);
+ }
+ else OperatorConsole.printf(
+ "***[CompressJPEGL]: Unknown or unsuported color space record.\n");
+ jpeg_destroy_compress(&cinfo);
+ return(FALSE);
+ }
+
+// Get the data.
+ pVR = pDDO->GetVR(0x7fe0, 0x0010); // Get the Image VR.
+ vrImage = pVR;// Will test for null later.
+ ArrayImage = NULL;// For warning.
+ if(pVR && pVR->Length && pVR->SQObjectArray)
+ {//This should not be for uncompressed.
+ ArrayImage = (Array<DICOMDataObject *> *) pVR->SQObjectArray;
+ while (inputArrayCnt < ArrayImage->GetSize())
+ {
+ DDO = ArrayImage->Get(inputArrayCnt++);//Get the array.
+ vrImage = DDO->GetVR(0xfffe, 0xe000);//Get the data.
+ if(vrImage && vrImage->Length >= frameSize)
+ {
+ OperatorConsole.printf("Warn[CompressJPEGL]:Raw image data in an encapsulation array.\n");
+ break;
+ }
+ }
+ }
+ if(!vrImage || vrImage->Length < frameSize)// Have enough data for at least 1 frame?
+ {
+ OperatorConsole.printf("***[CompressJPEGL]: Could not find the image data.\n");
+ jpeg_destroy_compress(&cinfo);
+ return (FALSE);
+ }
+// Use a temp file to hold the data, easier to get the compressed size(s)
+ NewTempFileWExt(name, ".jpg");
+ if((fp = fopen(name, "wb+")) == NULL )
+ {
+ OperatorConsole.printf("***[CompressJPEGL]: Could not open file %s for write.\n", name);
+ jpeg_destroy_compress(&cinfo);
+ return (FALSE);
+ }
+ jarray = &jbuffer;
+ jbuffer = NULL; // Default is no buffer.
+// Any compression errors from here on are handled by jerror_exit.
+
+/* Check to see if we need a buffer, data in planes or 12 bits storage.
+* We will let libjpeg allocate it, so if any errors it will go away. */
+ if(buffer) jarray = (cinfo.mem->alloc_sarray)
+ ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
+ (JDIMENSION)( cinfo.image_width * cinfo.input_components
+ * byteWidthIn ) + 6, 1);//Add a little extra.
+ jbuffer = *jarray;//jarray is an array of rows. We use just one.
+
+ progressive = FALSE;
+ switch(comp)
+ {
+ case '2':// lossless SV6 "1.2.840.10008.1.2.4.57" = jpeg 14 (33%)
+ jpegQuality = 100;
+ if(cinfo.data_precision > 8)cinfo.lossless = TRUE;
+ comp = 2;
+ break;
+ case '3':// baseline (8 bits ) "1.2.840.10008.1.2.4.50" = jpeg 1 (15%)
+ case '4':// extended (12 bits) "1.2.840.10008.1.2.4.51" = jpeg2, 4 (15%)
+ if(cinfo.data_precision <= 12)// Else fall though 5 and 6 to 1.
+ {
+ if(cinfo.data_precision > 8)
+ {
+ cinfo.data_precision = 12;
+ jpeg_set_quality(&cinfo, jpegQuality, false);
+ comp = 4;
+ }
+ else
+ {
+ cinfo.data_precision = 8;
+ jpeg_set_quality(&cinfo, jpegQuality, true);
+ comp = 3;
+ }
+ break;
+ }
+ case '5': // spectral sel "1.2.840.10008.1.2.4.53" = jpeg 8 (15%) Obsolete!
+ case '6': // progressive "1.2.840.10008.1.2.4.55" = jpeg 12 (14%) Obsolete!
+ if(cinfo.data_precision <= 12)// Else fall though.
+ {
+ progressive = TRUE;
+ if(cinfo.data_precision > 8)
+ {
+ cinfo.data_precision = 12;
+ comp = 6;
+ }
+ else
+ {
+ cinfo.data_precision = 8;
+ comp = 5;
+ }
+ jpeg_set_quality(&cinfo, jpegQuality, false);
+ jpeg_simple_progression(&cinfo);
+ break;
+ }
+ default: //default lossless SV1 "1.2.840.10008.1.2.4.70" = jpeg 14 (33%)
+//16 bit jpeg id always lossless.
+ comp = 1;
+ jpegQuality = 100;
+ if(cinfo.data_precision > 8)cinfo.lossless = TRUE;// Tell 8 bit after colorspace
+ }
+// Setup for compress.
+ cinfo.jpeg_color_space = cinfo.in_color_space;
+ jpeg_default_colorspace(&cinfo);
+// lossless must be set after colorspace, but color space need to know lossless if not 8 bits.
+ if(comp <= 2)// Lossless J1 or J2.
+ {
+ cinfo.lossless = TRUE;
+ cinfo.lossless_scaling = FALSE;
+ if(comp == 2)jpeg_simple_lossless(&cinfo, 6, 0);//(J2)Predictor = 6, point_transform = 0
+ else jpeg_simple_lossless(&cinfo, 1, 0);//(J1)Predictor = 1, point_transform = 0
+ }
+// Set the obsolete progressive if called for.
+ if(progressive)jpeg_simple_progression(&cinfo);
+// Print out some info for debug.
+ if (DebugLevel > 2)
+ {
+ if(cinfo.lossless)SystemDebug.printf("JPEG Lossless\n");
+ else SystemDebug.printf("JPEG Lossy Quality = %d\n", jpegQuality);
+ if (DebugLevel > 3)
+ {
+ if(progressive)SystemDebug.printf(", progressive\n");
+ if(!buffer)SystemDebug.printf(", unbuffered data\n");
+ else SystemDebug.printf(", buffered data\n");
+ }
+ SystemDebug.printf(
+ ", H = %d, W = %d, Bits = %d in %d, Frames = %d, \n",
+ cinfo.image_width, cinfo.image_height, cinfo.data_precision,
+ cinfo.data_precision_other, frames);
+ if((colorASC = pDDO->GetCString(0x0028, 0x0004)))
+ {
+ SystemDebug.printf("color = %s\n", colorASC);
+ free(colorASC);
+ }
+ else SystemDebug.printf("Unknown color space record.\n");
+ }
+// Create the encapsulation array.
+ ArrayPtr = new Array < DICOMDataObject * >;
+// The first blank object.
+ DDO = new DICOMDataObject;
+ vrs = new VR(0xfffe, 0xe000, 0, (void *)NULL, FALSE);
+ DDO->Push(vrs);
+ ArrayPtr->Add(DDO);
+// Start the frames loop
+ while(TRUE)
+ {
+//Start of the frame
+ if( inputArrayCnt == 0)
+ {
+ inData = (char *)vrImage->Data + (currFrame * frameSize);
+ if((++currFrame * frameSize) > vrImage->Length)
+ {
+ OperatorConsole.printf(
+ "Warn[CompressJPEGL]: Ran out of image data on frame %d of %d.\n", ++currFrame, frames);
+ break;
+ }
+ }
+ else inData = (char *)vrImage->Data;// input array, a strange world.
+// Set where to put it.
+ jpeg_stdio_dest(&cinfo, fp);
+// Get the library ready for data.
+ jpeg_start_compress(&cinfo, TRUE);
+/* To send the data there are many routines used. It is done this way for speed rather than code size.
+* I try to not have any 'if' statements in the loops. */
+ if(!buffer)// Easy way, just send.
+ {
+ rowWidth = cinfo.image_width * cinfo.num_components * byteWidthIn;
+ while (cinfo.next_scanline < cinfo.image_height)
+ {
+ row_pointer[0] = &(((JSAMPROW)inData)[cinfo.next_scanline * rowWidth]);
+ jpeg_write_scanlines(&cinfo, &row_pointer[0], 1);
+ }
+ }
+ else // Buffered, copy time.
+ {
+ row_pointer[0] = (JSAMPROW)inData;
+
+ switch (colorType)
+ {
+ case JCS_GRAYSCALE:
+#if NATIVE_ENDIAN == BIG_ENDIAN // Big Endian like Apple power pc
+ if(cinfo.data_precision_other == 16) // 16 Bits, byte swap time.
+ {
+ while (cinfo.next_scanline < cinfo.image_height)
+ {
+ jbuffer_ptr =jbuffer;
+ for(byteCnt = 0;byteCnt < cinfo.image_width; byteCnt++)
+ {
+ *jbuffer_ptr++ = row_pointer[0][1];
+ *jbuffer_ptr++ = *row_pointer[0]++;
+ row_pointer[0]++;
+ }
+ while( 1 != jpeg_write_scanlines(&cinfo, jarray, 1));// Not 1, try again.
+ }
+ }
+ else //Buffer, no planes == 12 Bits allocated.
+ {
+#endif
+ // Each loop gets two words.
+ cinfo.data_precision_other = 16;
+ oddRow = FALSE;
+ if(cinfo.image_width & 1) oddRow = TRUE;
+ rowWidth = cinfo.image_width >> 1;
+ if(oddRow) rowWidth++;// Get the odd bit.
+ while (cinfo.next_scanline < cinfo.image_height)
+ {
+ jbuffer_ptr =jbuffer;
+ for(byteCnt = 0;byteCnt < rowWidth; byteCnt++)
+ {
+#if NATIVE_ENDIAN == BIG_ENDIAN // Big Endian like Apple power pc
+ *jbuffer_ptr = (row_pointer[0][1] && 0xF0) >> 4;
+ *jbuffer_ptr++ |= (*row_pointer[0] && 0x0F) << 4;
+ *jbuffer_ptr++ = (*row_pointer[0]++ && 0xF0) >> 4;
+ *jbuffer_ptr++ = row_pointer[0][1];
+ *jbuffer_ptr++ = (*row_pointer[0]++) && 0x0F;
+ row_pointer[0]++;
+#else //Little Endian
+ *jbuffer_ptr++ = (*row_pointer[0] && 0xF0) >> 4;
+ *jbuffer_ptr = (*row_pointer[0]++ && 0x0F) << 4;
+ *jbuffer_ptr++ |= (*row_pointer[0] && 0xF0) >> 4;
+ *jbuffer_ptr++ = (*row_pointer[0]++) && 0x0F;
+ *jbuffer_ptr++ = *row_pointer[0]++;
+#endif //Little Endian
+ }
+ while( 1 != jpeg_write_scanlines(&cinfo, jarray, 1));// Not 1, try again.
+ if(oddRow && (cinfo.next_scanline < cinfo.image_height))
+ {
+ jbuffer_ptr -= 2; //Back up over the second half of the odd.
+ for(byteCnt = 0; byteCnt < 2; byteCnt++)
+ jbuffer[byteCnt] = *jbuffer_ptr++;
+ jbuffer_ptr = jbuffer + 2;//Reset the buffer pointer.
+ for(byteCnt = 2 ;byteCnt < rowWidth; byteCnt++)
+ {
+#if NATIVE_ENDIAN == BIG_ENDIAN // Big Endian like Apple power pc
+ *jbuffer_ptr++ = row_pointer[0][1];
+ *jbuffer_ptr++ = (*row_pointer[0]++) && 0x0F;
+ row_pointer[0]++;
+ *jbuffer_ptr = (row_pointer[0][1] && 0xF0) >> 4;
+ *jbuffer_ptr++ |= (*row_pointer[0] && 0x0F) << 4;
+ *jbuffer_ptr++ = (*row_pointer[0]++ && 0xF0) >> 4;
+#else //Little Endian
+ *jbuffer_ptr++ = (*row_pointer[0]++) && 0x0F;
+ *jbuffer_ptr++ = *row_pointer[0]++;
+ *jbuffer_ptr++ = (*row_pointer[0] && 0xF0) >> 4;
+ *jbuffer_ptr = (*row_pointer[0]++ && 0x0F) << 4;
+ *jbuffer_ptr++ |= (*row_pointer[0] && 0xF0) >> 4;
+#endif //Little Endian
+ }
+ while( 1 != jpeg_write_scanlines(&cinfo, jarray, 1));// Not 1, try again.
+ }
+ }
+#if NATIVE_ENDIAN == BIG_ENDIAN // Big Endian like Apple power pc
+ } // 16 bit else in BIG_ENDIAN
+#endif
+ break;
+ case JCS_RGB:// 8 bit, Planes. Regular RGB has no buffer.
+ case JCS_YCbCr:
+ row_pointer[1] = row_pointer[0] + (cinfo.image_width * cinfo.image_height);
+ row_pointer[2] = row_pointer[1] + (cinfo.image_width * cinfo.image_height);
+ while (cinfo.next_scanline < cinfo.image_height)
+ {
+ jbuffer_ptr = jbuffer;
+ for(byteCnt = 0;byteCnt < cinfo.image_width; byteCnt ++)
+ {
+ *jbuffer_ptr++ = *row_pointer[0]++;
+ *jbuffer_ptr++ = *row_pointer[1]++;
+ *jbuffer_ptr++ = *row_pointer[2]++;
+ }
+ while( 1 != jpeg_write_scanlines(&cinfo, jarray, 1));// Not 1, try again.
+ }
+ break;
+ case CLRSPC_FAM_YCBCR_F422: // Convert to "YBR_FULL"
+ width = cinfo.image_width > 1; // Done at the Cr,Cb width.
+ while (cinfo.next_scanline < cinfo.image_height)
+ {
+ jbuffer_ptr = jbuffer;
+ for(byteCnt = 0;byteCnt < width; byteCnt ++)
+ {
+ *jbuffer_ptr++ = *row_pointer[0]++;//Y1
+ charY = *row_pointer[0]++;//Y2
+ *jbuffer_ptr++ = charCb = *row_pointer[0]++;// Get the colors twice
+ *jbuffer_ptr++ = charCr = *row_pointer[0]++;
+ *jbuffer_ptr++ = charY;
+ *jbuffer_ptr++ = charCb;
+ *jbuffer_ptr++ = charCr;
+ }
+ while( 1 != jpeg_write_scanlines(&cinfo, jarray, 1));// Not 1, try again.
+ }
+ break;
+ case CLRSPC_FAM_YCBCR_422:
+ width = cinfo.image_width > 1; // Done at the Cr,Cb width.
+ while (cinfo.next_scanline < cinfo.image_height)
+ {
+ jbuffer_ptr = jbuffer;
+ for(byteCnt = 0;byteCnt < width; byteCnt ++)
+ {
+/* For Y the ratio is 256 / 220 (1.1636) and for color 256 / 225 (1.1378).
+* Note: All values are multiplied by 1024 or 1 << 7.
+* Yo = 1.1636(Yi - 16) == Yo = 1.1636Yi - 18.204 ==
+* Yo = [149Yi - 2330]/128 */
+ outInt = (((int)(*row_pointer[0]++)) * 149)
+ - 2330;//Y1
+ if(outInt & 0x10000)*jbuffer_ptr++ = 0;// Neg not allowed here.
+ else if(outInt & 0x8000)*jbuffer_ptr++ = 0xFF;// Over flow.
+ else *jbuffer_ptr++ = (char)((outInt >> 7) & 0xFF);
+ outInt = (((int)(*row_pointer[0]++)) * 149)
+ - 2330;//Y2
+/* Cxo = 1.1378(Cxi - 16) == Cxo = 1.1378Cxi - 18.205 ==
+* Cxo = [73Cxi - 1152]/64 */
+ outInt1 = (((int)(*row_pointer[0]++)) * 73)
+ - 1152;//Cb
+ if(outInt1 & 0x8000) charCb = 0;// Neg not allowed here.
+ else if(outInt1 & 0x4000)charCb = 0xFF;// Over flow.
+ else charCb = (char)((outInt >> 6) & 0xFF);
+ outInt1 = ((((int)(*row_pointer[0]++)) >> 21) * 2440246)
+ - 37129657;//Cr
+ if(outInt1 & 0x8000) charCr = 0;// Neg not allowed here.
+ else if(outInt1 & 0x4000)charCr = 0xFF;// Over flow.
+ else charCr = (char)((outInt >> 6) & 0xFF);
+ *jbuffer_ptr++ = charCr;
+// Put Y2 and Cb, Cr again.
+ if(outInt & 0x10000)*jbuffer_ptr++ = 0;// Neg not allowed here.
+ else if(outInt & 0x8000)*jbuffer_ptr++ = 0xFF;// Over flow.
+ else *jbuffer_ptr++ = (char)((outInt >> 7) & 0xFF);
+ *jbuffer_ptr++ = charCb;
+ *jbuffer_ptr++ = charCr;
+ }
+ while( 1 != jpeg_write_scanlines(&cinfo, jarray, 1));// Not 1, try again.
+ }
+ break;
+ case CLRSPC_FAM_YCBCR_420:
+ width = cinfo.image_width > 1; // Done at the Cr,Cb width.
+ while (cinfo.next_scanline < cinfo.image_height)
+ {
+ jbuffer_ptr = jbuffer;
+ row_pointer[1] = row_pointer[0];// Set last row
+ for(byteCnt = 0;byteCnt < width; byteCnt ++)// First row with color
+ {
+/* For Y the ratio is 256 / 220 (1.1636) and for color 256 / 225 (1.1378).
+* Note: All values are multiplied by 1024 or 1 << 7.
+* Yo = 1.1636(Yi - 16) == Yo = 1.1636Yi - 18.204 ==
+* Yo = [149Yi - 2330]/128 */
+ outInt = (((int)(*row_pointer[0]++)) * 149)
+ - 2330;//Y1
+ if(outInt & 0x10000)*jbuffer_ptr++ = 0;// Neg not allowed here.
+ else if(outInt & 0x8000)*jbuffer_ptr++ = 0xFF;// Over flow.
+ else *jbuffer_ptr++ = (char)((outInt >> 7) & 0xFF);
+/* Cxo = 1.1378(Cxi - 16) == Cxo = 1.1378Cxi - 18.205 ==
+* Cxo = [73Cxi - 1152]/64 */
+ outInt1 = (((int)(*row_pointer[0]++)) * 73)
+ - 1152;//Cb
+ if(outInt1 & 0x8000) charCb = 0;// Neg not allowed here.
+ else if(outInt1 & 0x4000)charCb = 0xFF;// Over flow.
+ else charCb = (char)((outInt >> 6) & 0xFF);
+ *jbuffer_ptr++ = charCb;
+ outInt1 = (((int)(*row_pointer[0]++)) * 73)
+ - 1152;//Cr
+ if(outInt1 & 0x8000) charCr = 0;// Neg not allowed here.
+ else if(outInt1 & 0x4000)charCr = 0xFF;// Over flow.
+ else charCr = (char)((outInt >> 6) & 0xFF);
+ *jbuffer_ptr++ = charCr;
+// Put Y2 and Cb, Cr again.
+ outInt = (((int)(*row_pointer[0]++)) * 149)
+ - 2330;//Y2
+ if(outInt & 0x10000)*jbuffer_ptr++ = 0;// Neg not allowed here.
+ else if(outInt & 0x8000)*jbuffer_ptr++ = 0xFF;// Over flow.
+ else *jbuffer_ptr++ = (char)((outInt >> 7) & 0xFF);
+ *jbuffer_ptr++ = charCb;
+ *jbuffer_ptr++ = charCr;
+ }
+ while( 1 != jpeg_write_scanlines(&cinfo, jarray, 1));// Not 1, try again.
+ jbuffer_ptr = jbuffer;
+ for(byteCnt = 0;byteCnt < width; byteCnt ++)// 2nd row without color.
+ {
+ outInt = (((int)(*row_pointer[0]++)) * 149)
+ - 2330;//Y1
+ if(outInt & 0x10000)*jbuffer_ptr++ = 0;// Neg not allowed here.
+ else if(outInt & 0x8000)*jbuffer_ptr++ = 0xFF;// Over flow.
+ else *jbuffer_ptr++ = (char)((outInt >> 7) & 0xFF);
+ *jbuffer_ptr++;// Reusing the buffer let us skip over
+ *jbuffer_ptr++;// the old values and use them again.
+ outInt = (((int)(*row_pointer[0]++)) * 149)
+ - 2330;//Y2
+ if(outInt & 0x10000)*jbuffer_ptr++ = 0;// Neg not allowed here.
+ else if(outInt & 0x8000)*jbuffer_ptr++ = 0xFF;// Over flow.
+ else *jbuffer_ptr++ = (char)((outInt >> 7) & 0xFF);
+ *jbuffer_ptr++;// Reusing the buffer let us skip over
+ *jbuffer_ptr++;// the old values and use them again.
+ }
+ while( 1 != jpeg_write_scanlines(&cinfo, jarray, 1));// Not 1, try again.
+ }
+ break;
+ default:// Should never get here! Do nothing
+ break;
+ }
+ }
+
+// If here, finished the compression.
+ jpeg_finish_compress(&cinfo);
+// Time to handle errors on our own again, the file is still open and cinfo still exists.
+ if(!fp)
+ {
+ OperatorConsole.printf("***[CompressJPEGL]: jpeglib distroyed file %s\n", name);
+ jpeg_destroy_compress(&cinfo);
+ return ( FALSE );
+ }
+ fseek(fp, 0, SEEK_END);
+ fileLength = ftell(fp);
+ if(-1 == (signed int)fileLength)
+ {
+ OperatorConsole.printf("***[CompressJPEGL]: Could not get file size for %s\n", name);
+ fclose(fp);
+ unlink(name);
+ jpeg_destroy_compress(&cinfo);
+ return ( FALSE );
+ }
+ rewind(fp);
+
+// Jpeg is encapsulated, make a new vr to encapsulate.
+ vrs = new VR(0xfffe, 0xe000, 0, (void *)NULL, FALSE);
+ if(!vrs->ReAlloc(fileLength))//Odd file length, ReAlloc will make it even.
+ {
+ OperatorConsole.printf("***[CompressJPEGL]: Failed to allocate memory.\n");
+ fclose(fp);
+ unlink(name);
+ jpeg_destroy_compress(&cinfo);
+ return ( FALSE );
+ }
+//Zero the added byte, never hurts before the read.
+ ((BYTE *)vrs->Data)[(vrs->Length) - 1] = 0;
+//Read the image data.
+ readLength = fread(vrs->Data,1,fileLength,fp);
+ if(readLength == 0)
+ {
+ err = ferror(fp);
+ if(err) OperatorConsole.printf("***[CompressJPEGL]: File read error %d on %s.\n",err,name);
+ else OperatorConsole.printf("***[CompressJPEGL]: No compressed image data (0 length read).\n");
+ fclose(fp);
+ unlink(name);
+ jpeg_destroy_compress(&cinfo);
+ return ( FALSE );
+ }
+ if(readLength != fileLength)
+ {
+ OperatorConsole.printf("Warn[CompressJPEGL]: Only read %d bytes of %d of the jpeg2k file:%s, will try to save\n",
+ readLength, fileLength, name);
+ }
+ fclose(fp);//File done
+// Encapsulate an image object.
+ DDO = new DICOMDataObject;
+ DDO->Push(vrs);
+ ArrayPtr->Add(DDO);
+ if(currFrame >= frames)break;//Finished while(TRUE) loop
+//Still here, setup for the next frame
+ if((fp = fopen(name, "wb+")) == NULL )//Clear the file.
+ {
+ OperatorConsole.printf("***[CompressJPEGL]: Could not open file %s for write of frame %d.\n", name, currFrame + 1);
+ jpeg_destroy_compress(&cinfo);
+ return (FALSE);
+ }
+// Deal with silly input arrays
+ if(inputArrayCnt > 0)
+ {
+// All in one array would be nice.
+ if((++currFrame * frameSize) > vrImage->Length)
+ {// Look for the next array
+ while (inputArrayCnt < ArrayImage->GetSize())
+ {
+ DDO = ArrayImage->Get(inputArrayCnt++);//Get the array.
+ vrImage = DDO->GetVR(0xfffe, 0xe000);//Get the data
+ if(vrImage && vrImage->Length >= frameSize) break;// Found next one, break inner loop.
+ }
+ }
+ if(!vrImage || vrImage->Length < frameSize) break;// Not enough data for at least 1 frame.
+ }
+ }//End of while(TRUE), go back for the next frame.
+ unlink(name);//Done with the file.
+// All frames compressed, done with cinfo.
+ jpeg_destroy_compress(&cinfo);
+// Should we kill it and keep the uncompressed data?
+ if(currFrame < frames) OperatorConsole.printf(
+ "Warn[CompressJPEGL]: Only %d of %d frames saved.\n",currFrame, frames);
+// The end object.
+ DDO = new DICOMDataObject;
+ vrs = new VR(0xfffe, 0xe0dd, 0, (void *)NULL, FALSE);
+ DDO->Push(vrs);
+ ArrayPtr->Add(DDO);
+// vrs = new VR(0x7fe0, 0x0010, 0, (void *)NULL, FALSE);
+ pVR->Reset();//Clear the old image data including arrays.
+ pVR->SQObjectArray = ArrayPtr;// Replace the data
+ if(byteWidth > 1)pVR->TypeCode ='OW';
+ else pVR->TypeCode ='OB';
+// Change the transfer syntax to JPEG!
+// Change the dicom parameters
+
+// Fix the bits allocated.
+ // 20120624: do not change highbit and bitsstored
+ //if(byteWidth == 1)pDDO->ChangeVR( 0x0028, 0x0100, (UINT8)8, 'US');
+ //else pDDO->ChangeVR( 0x0028, 0x0100, (UINT8)16, 'US');
+
+//Change the transfer syntax to JPEG! Many choices, do it old way.
+ pVR = pDDO->GetVR( 0x0002, 0x0010 );
+ if(pVR)
+ {
+ if(pVR->Length != 22)pVR->ReAlloc(22);
+ }
+ else
+ {
+ pVR = new VR( 0x0002, 0x0010, 22, TRUE);
+ pVR->TypeCode = 'IU';
+ pDDO->Push(pVR);
+ }
+ memcpy((char *)pVR->Data, "1.2.840.10008.1.2.4.", 20);
+ switch(comp) // here was a big bug, used e.g. '2' instead of 2
+ {
+ case 2: memcpy(&((char *)pVR->Data)[20], "57", 2);//Lossless J2, SV6
+ break;
+ case 3: memcpy(&((char *)pVR->Data)[20], "50", 2);//Lossy baseline (8 bits)
+ break;
+ case 4: memcpy(&((char *)pVR->Data)[20], "51", 2);//Lossy extended (12 bits)
+ break;
+ case 5: memcpy(&((char *)pVR->Data)[20], "53", 2);// Obsolete! Progressive (8 bits)
+ break;
+ case 6: memcpy(&((char *)pVR->Data)[20], "55", 2);// Obsolete! Progressive (12 bits)
+ break;
+ default: memcpy(&((char *)pVR->Data)[20], "70", 2);//Lossless J1, SV1
+ }
+//Change the Photometric Interpretation if needed.
+ if(colorType >= CLRSPC_FAM_YCBCR_422)//Color
+ {
+// Reset the plane's VR, if there.
+ pVR = pDDO->GetVR(0x0028, 0x0006);
+ if(pVR && pVR->Length && *(char *)(pVR->Data) == 1) *(char *)(pVR->Data = 0);
+// Set the color profile
+ pDDO->ChangeVR( 0x0028, 0x0004, "YBR_FULL\0", 'CS');// Jpeg standard
+ }
+ if (DebugLevel > 0)
+ SystemDebug.printf("JPEG compress time %u seconds.\n", (unsigned int)time(NULL) - t);
+ return (TRUE);
+}
+
+/* This is a replacement for the get more data for the buffer routine.
+* Because it is passed the whole image, it should never ask for more. */
+METHODDEF(boolean)
+jfill_input_buffer (j_decompress_ptr cinfo)
+{
+/* Passed libjpeg the whole image, there is no more data, error exit */
+ OperatorConsole.printf("***[LIBJPEG]: Ran out of data in image.\n");
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+
+ return TRUE;
+}
+
+/* This was taken directly from the library with the error message changed. */
+METHODDEF(void)
+jskip_input_data (j_decompress_ptr cinfo, long num_bytes)
+{
+ jpeg_source_mgr *src = cinfo->src;
+
+ /* Just a dumb implementation for now. Could use fseek() except
+ * it doesn't work on pipes. Not clear that being smart is worth
+ * any trouble anyway --- large skips are infrequent.
+ */
+ if (num_bytes > 0)
+ if (num_bytes > (long) src->bytes_in_buffer)
+ {
+ OperatorConsole.printf("***[LIBJPEG]: Tried to skip past the end of the image.\n");
+ ERREXIT(cinfo, JERR_INPUT_EOF);
+ }
+ src->next_input_byte += (size_t) num_bytes;
+ src->bytes_in_buffer -= (size_t) num_bytes;
+}
+
+/* This routine will take in a jpeg image and convert it to little endian, uncompressed,
+* RGB or YBR_FULL format. RGB and YBR_FULL is the IJG standard output for the Jpeg-6b
+* library used everywhere. As stated before, I did not use the Jpeg-6b version because
+* it had to be compiled for 8, 12 or 16 only. So I wrote Jpeg-6c that can change bit
+* width on the fly. You can get it here:
+* http://www.bitsltd.net/Software/Software-Repository/index.php
+* If I have made some mistakes (most likely) you can contact me bruce.barton
+* (the mail symbol goes here) bitsltd.net. Let me know where I can find a sample of
+* the image that didn't work. */
+BOOL DecompressJPEGL(DICOMDataObject* pDDO)
+{
+ Array < DICOMDataObject *> *ArrayPtr;
+ DICOMDataObject *DDO;
+ VR *pVR, *vrImage;
+ char *uncompImagPtr, *uncompImageBptr;
+ char *outImageBptr;
+ UINT16 frames;
+ unsigned int outBytes, currFrame, currSQObject;
+ size_t imageLen;
+ BOOL color, leExplict;
+ int t;
+// libjpeg stuff
+ JSAMPARRAY16 outBuffer;
+ JDIMENSION num_scanlines, row, rowWidth, pixcnt;
+ struct jpeg_decompress_struct cinfo;
+ struct jerror_mgr jerr;
+
+// If debug > 0, get start time.
+ t = 0;
+ if (DebugLevel > 0)t = (unsigned int)time(NULL);
+ if (DebugLevel > 1) SystemDebug.printf("JPEG decompress started.\n");
+ leExplict = TRUE; // Only changed by FUJI_FIX
+ uncompImagPtr = NULL;//Output data memory.
+ color = FALSE;
+// Are there frames?
+ if(!(frames = pDDO->Getatoi(0x0028, 0x0008))) frames = 1;
+ currFrame = 0;
+// Get the encapsulated data, unless Fuji.
+ pVR = pDDO->GetVR(0x7fe0, 0x0010); // Get the Image VR.
+ if(!pVR)
+ {
+ OperatorConsole.printf("***[DecompressJPEGL]: No image VR\n");
+ return (FALSE);
+ }
+ currSQObject = 0;// Init now for no warning later.
+ vrImage = pVR;// Init now for no warning later, will use if Fuji fix.
+ ArrayPtr = (Array<DICOMDataObject *> *) pVR->SQObjectArray;
+ if(ArrayPtr)
+ {
+ while(TRUE)
+ {
+ if( currSQObject >= ArrayPtr->GetSize())
+ {
+ OperatorConsole.printf("***[DecompressJPEGL]: No jpeg data found\n");
+ return (FALSE);
+ }
+ DDO = ArrayPtr->Get(currSQObject );//Get the array.
+ vrImage = DDO->GetVR(0xfffe, 0xe000);//Get the data
+//Look for size and jpeg SOI marker
+ if((vrImage->Length) && ((unsigned char *)vrImage->Data)[0] == 0xFF &&
+ ((unsigned char *)vrImage->Data)[1] == 0xD8)break;
+ currSQObject++;
+ }
+ }
+ else
+ {
+#ifdef FUJI_FIX
+// Look for a Jfif header. (LittleEndianImplicit, jpeg compressed,not encapsulated, how evil)
+ if (((unsigned char *)pVR->Data)[0] == 0xFF && ((unsigned char *)pVR->Data)[1] == 0xD8 && ((unsigned char *)pVR->Data)[2] == 0xFF
+ && ((unsigned char *)pVR->Data)[3] == 0xE0 && ((char *)pVR->Data)[4] == 0x00 && ((char *)pVR->Data)[5] == 0x10
+ && strncmp(&(((char *)pVR->Data)[6]),"JFIF", 4) == 0)
+ {
+ SystemDebug.printf("Warn[DecompressJPEGL]: Applying Fuji Fix\n");
+ leExplict = FALSE;
+ }
+ else
+ {
+#else
+ OperatorConsole.printf("***[DecompressJPEGL]: No image VR array\n");
+ return (FALSE);
+#endif
+#ifdef FUJI_FIX
+ }
+#endif
+ }
+// Init the default handler
+ cinfo.err = jpeg_std_error(&jerr.pub);
+// change the error exit so libjpeg can't kill us
+ jerr.pub.error_exit = jerror_exit;
+// Use our methode for outputting messages.
+ jerr.pub.output_message = joutput_message;
+
+ if (setjmp(jerr.setjmp_buffer))
+ {
+// If we get here, the JPEG code has signaled an error.
+// We need to clean up the JPEG object and return.
+ jpeg_destroy_decompress(&cinfo);
+ if(uncompImagPtr != NULL) free(uncompImagPtr);
+ return (FALSE);
+ }
+
+// Look for multi-byte version 6c (63) from www.bitsltd.net
+ jpeg_CreateDecompress(&cinfo, 63,
+ (size_t) sizeof(struct jpeg_decompress_struct));
+// Set the source
+ cinfo.src = (struct jpeg_source_mgr *)
+ (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT,
+ sizeof(struct jpeg_source_mgr));
+ cinfo.src->init_source = jdoes_nothing;
+ cinfo.src->skip_input_data = jskip_input_data;
+ cinfo.src->resync_to_restart = jpeg_resync_to_restart; // use default method
+ cinfo.src->term_source = jdoes_nothing; /* term_source does nothing
+// Pass the whole image, so this is an error that should not happen. */
+ cinfo.src->fill_input_buffer = jfill_input_buffer;
+// Get data for the first or only frame
+ cinfo.src->bytes_in_buffer = vrImage->Length; // forces fill_input_buffer on first read
+ cinfo.src->next_input_byte = (JOCTET *)vrImage->Data; // Image buffer
+// find out what we have.
+ jpeg_read_header(&cinfo, TRUE);
+// Set all of the cinfo information.
+ jpeg_calc_output_dimensions(&cinfo);
+// The default is 8 bits, set it to the image size.
+ cinfo.data_precision_other =cinfo.data_precision;
+ if (cinfo.out_color_components != 1)
+ {
+ if(cinfo.out_color_components!=3)
+ {
+ OperatorConsole.printf(
+ "***[DecompressJPEGL]: Not grayscale, RGB or YCbCr. Number of components = %d\n",
+ cinfo.out_color_components);
+ jpeg_destroy_decompress(&cinfo);
+ return (FALSE);
+ }
+ color = TRUE;
+ }
+// Time to make an output image buffer.
+ if(cinfo.data_precision_other > 8) outBytes = 2;
+ else outBytes = 1;
+ rowWidth = cinfo.output_width * cinfo.output_components * outBytes;
+ imageLen = rowWidth * cinfo.output_height * frames;
+ if ( imageLen & 1 ) imageLen++;//Odd length, make it even.
+ if(!(uncompImagPtr = (char*)malloc(imageLen)))
+ {
+ OperatorConsole.printf(
+ "***[DecompressJPEGL]: Could not allocate decompressed image memory.\n");
+ jpeg_destroy_decompress(&cinfo);
+ return (FALSE);
+ }
+ uncompImagPtr[imageLen - 1] = 0; // In the case of an odd length.
+ outImageBptr = uncompImagPtr;
+/* The size of a pixel is JSAMPLE16, 16 bits, no matter what the size of the original data.
+ This is done because the size of the data in the jpeg image is not known to the library until
+ jpeg_read_header(). So if the buffer is 8 bit, the library will create an internal 16 bit
+ buffer to hold the image data and copy it to the smaller buffer wasting time.
+ So just make a 16 bit buffer array now the height of DCTSIZE (jpeg standard = 8). */
+ outBuffer = (JSAMPARRAY16)(*cinfo.mem->alloc_sarray)
+ ((j_common_ptr) &cinfo, JPOOL_PERMANENT,//JPOOL_IMAGE,
+ (JDIMENSION) cinfo.output_width * cinfo.output_components
+ * sizeof(JSAMPLE16), (JDIMENSION) cinfo.rec_outbuf_height);
+ if(!outBuffer)
+ {
+ OperatorConsole.printf(
+ "***[DecompressJPEGL]: Libjpeg could not allocate image buffer memory.\n");
+ jpeg_destroy_decompress(&cinfo);
+ return (FALSE);
+ }
+// Start the frames loop.
+ while(TRUE)
+ {
+// The library will convert the internal YCbCr to RGB.
+ if (color) cinfo.out_color_space = JCS_RGB;
+ else cinfo.out_color_space = JCS_GRAYSCALE;
+// Ready to decompress
+ jpeg_start_decompress(&cinfo);
+// Tell libjpeg we will use a 16 bit buffer
+ cinfo.buffer_size_char = FALSE;
+// Never scale.
+ cinfo.shft = 0;
+// read the Image loop
+ while (cinfo.output_scanline < cinfo.output_height)
+ {
+ num_scanlines = jpeg_read_scanlines(&cinfo,(JSAMPARRAY) outBuffer,
+ (JDIMENSION) cinfo.rec_outbuf_height);
+ for(row = 0; row < num_scanlines; row++)
+ {
+ uncompImageBptr = (char *)outBuffer[row];
+ if (outBytes == 1)// char
+ {
+ for( pixcnt = 0; pixcnt < rowWidth; pixcnt++)
+ {
+#if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian like PPC
+ uncompImageBptr++;
+#endif
+ *outImageBptr++ = *uncompImageBptr++;
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ uncompImageBptr++;
+#endif
+ }
+ }
+ else //words
+ { /* Row with is 2 x, MSB, LSB */
+ for( pixcnt = 0; pixcnt < rowWidth; pixcnt++)
+ {
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ *outImageBptr++ = *uncompImageBptr++;
+ #else //Big Endian like PPC
+ *outImageBptr++ = uncompImageBptr[1];
+ *outImageBptr++ = *uncompImageBptr++;
+ uncompImageBptr++;
+ pixcnt++;
+ #endif
+ }
+ }
+ }
+ }
+ jpeg_finish_decompress(&cinfo);
+// check for the end
+ if( ++currFrame >= frames )break;
+// More images to read
+ while(++currSQObject <= ArrayPtr->GetSize())
+ {
+ DDO = ArrayPtr->Get(currSQObject);//Get the array.
+ vrImage = DDO->GetVR(0xfffe, 0xe000);//Get the data
+//Look for size and jpeg SOI marker
+ if(vrImage->Length && ((unsigned char *)vrImage->Data)[0] == 0xFF &&
+ ((unsigned char *)vrImage->Data)[1] == 0xD8)break;
+ }
+ if( currSQObject >= ArrayPtr->GetSize() )break;//Should not happen!
+// OK, have another image now, reset decompressor
+// Get data for next frame
+ cinfo.src->bytes_in_buffer = vrImage->Length; // forces fill_input_buffer on first read
+ cinfo.src->next_input_byte = (JOCTET *)vrImage->Data; // Image buffer
+// Read the new header, nothing should change (should we check?)
+ jpeg_read_header(&cinfo, TRUE);
+// The default is 8 bits, set it back to the image size.
+ cinfo.data_precision_other =cinfo.data_precision;
+ }// Loop back to jpeg_start_decompress (while(TRUE))
+ if(currFrame < frames)OperatorConsole.printf(
+ "Warn[DecompressJPEGL]: Found %d of %d frames.\n",currFrame, frames);
+// Should have image(s) here, time to save it.
+ pVR->Reset();// Remove old data.
+ if(outBytes == 2) pVR->TypeCode ='OW';
+ else pVR->TypeCode ='OB';
+// Set it to the image data.
+ pVR->Data = uncompImagPtr;
+// Tell it how long.
+ pVR->Length = imageLen;
+// Give it responsible for it.
+ pVR->ReleaseMemory = TRUE;
+// pDDO->DeleteVR(pVR);// replace the pixel data: corrupts LastVRG
+// pDDO->Push(vrs);
+// Set the number of bits allocated.
+
+ // Need to fix Philips Gyroscan that stores 8 in 16 (now 8 in 8).
+ // 20120624: do not change highbit and bitsstored
+ //if(cinfo.data_precision <= 8) pDDO->ChangeVR( 0x0028, 0x0100, (UINT8)8, 'US');
+ // else pDDO->ChangeVR( 0x0028, 0x0100, (UINT8)16, 'US');
+
+// Should not be needed, but never hurts.
+// mvh, 20110502: DecompressJPEGL either not write 0x0101 (bitstored), or write both 0x0101 and 0x0102 (bitsstored/highbit)
+// mvh, 20110502: need to write highbit for consistency if writing bitstored
+
+ // 20120624: do not change highbit and bitsstored
+ //pDDO->ChangeVR( 0x0028, 0x0101, (UINT8)cinfo.data_precision, 'US');
+ //pDDO->ChangeVR( 0x0028, 0x0102, (UINT8)(cinfo.data_precision-1), 'US');
+
+// Done with libjpeg
+ jpeg_destroy_decompress(&cinfo);
+//Change the Photometric Interpretation.
+ if(color)
+ {
+//Set Planes value if needed, do not create if not there.
+ pVR = pDDO->GetVR(0x0028, 0x0006);
+ if(pVR && pVR->Length && *(char *)pVR->Data == 1)
+ *(char *)pVR->Data = 0;
+//Change the Photometric Interpretation.
+ pDDO->ChangeVR( 0x0028, 0x0004, "RGB\0", 'CS');
+ }
+//Change the transfer syntax to LittleEndianExplict!
+ if(leExplict)// Only false for FUJI_FIX w/ Fuji Image
+ pDDO->ChangeVR( 0x0002, 0x0010, "1.2.840.10008.1.2.1\0", 'IU');
+// If debug > 0, print decompress time.
+ if (DebugLevel > 0)
+ SystemDebug.printf("JPEG decompress time %u seconds.\n", (unsigned int)time(NULL) - t);
+// Done!
+ return(TRUE);
+}
+#endif//End HAVE_LIBJPEG
+#ifdef HAVE_LIBJASPER
+/* This routine will take all of the listed color spaces in 08_03 of the standard
+* in little endian, uncompressed format and compress it to jpeg2000 in whatever
+* format it came in. I don't know if dicom viewers can support this. It uses the
+* Jasper library by Michael D. Adams from the Department of Electrical and
+* Computer Engineering at the University of Victoria. You can get it here:
+* http://www.ece.uvic.ca/~mdadams/jasper/
+* You can also get it here with a few minor changes to use the my Jpeg-6c
+* library, but none of the changes are used by dgate:
+* http://www.bitsltd.net/Software/Software-Repository/index.php
+* Jasper can compress anything, with any size for each plane, but the standard only
+* allows YBR_RCT lossless and YBR_ICT lossy. So if a YBR come in, it is lossy, and
+* RGB is lossless. If this is a problem I can add a forced change in colorspace.
+* If I have made some mistakes (most likely), you can contact me bruce.barton
+* (the mail symbol goes here) bitsltd.net. Let me know where I can find a sample of
+* the image that didn't work. */
+BOOL CompressJPEG2K(DICOMDataObject* pDDO, int j2kQuality)
+{
+ Array < DICOMDataObject *> *ArrayPtr, *ArrayImage;
+ DICOMDataObject *DDO;
+ VR *pVR, *vrImage, *vrs;
+ jas_stream_t *out;
+ jas_image_t *image;
+ jas_image_cmpt_t *cmpt;
+ jas_image_coord_t byteCnt, rowCnt, size;
+ FILE *fp;
+ UINT8 bitwa, prec, colorTypeIn, sgnd;
+ UINT16 cmptno;
+ char *colorASC, name[256], *brcrBuffer, *bufferPtr;
+ char *colorBuffer_ptr[3], *colorBuffer[3];
+ char *buffer_ptr, option[20];
+ int fileLength, lengthRead, tempInt, err;
+ unsigned int currFrame, frames, t, inputArrayCnt, byteWidthIn, byteWidth;
+ BOOL planes, buffers;
+
+// If debug > 0, get start time and set the level.
+ t = 0;
+ if (DebugLevel > 0)
+ {
+ t = (unsigned int)time(NULL);
+ jas_setdbglevel(DebugLevel);
+ }
+ if (DebugLevel > 1) SystemDebug.printf("Jasper compress started.\n");
+ buffers = FALSE;
+ inputArrayCnt = 0;
+// Uninitialized warnings.
+ ArrayImage = NULL;
+ brcrBuffer = NULL;
+ cmpt = NULL;
+// Check and set the quality for lossy.
+ if(j2kQuality < MIN_QUALITY)// Set to 0 to use dicom.ini value.
+ {
+ j2kQuality = gJpegQuality;//Use the default or dicom.ini value.
+ }
+ if(j2kQuality > 100) j2kQuality = 100;
+// Init the jasper library.
+ if(jas_init())
+ {
+ OperatorConsole.printf("***[CompressJPEG2K]: Cannot init the jasper library\n");
+ return (FALSE);
+ }
+ /* Created from jas_image_create and jas_image_create0.
+* It was done so the buffers are not allocated if not needed. */
+ if (!(image = (jas_image_t *)malloc(sizeof(jas_image_t))))
+ {
+ OperatorConsole.printf("***[CompressJPEG2K]: Could not allocate an image structure.\n");
+ return (FALSE);
+ }
+// Set the some defaults for the outer box.
+ image->tlx_ = 0;
+ image->tly_ = 0;
+ image->clrspc_ = JAS_CLRSPC_UNKNOWN;
+ image->numcmpts_ = 0;//Set later
+// Get the number of samples per pixel VR.
+ if(!(image->maxcmpts_ = pDDO->GetBYTE(0x0028, 0x0002))) image->maxcmpts_ = 1;
+// Are there frames?
+ if(!(frames = pDDO->Getatoi(0x0028, 0x0008))) frames = 1;
+ currFrame = 0;
+// Get the Rows VR and check size
+ if(!(image->bry_ = pDDO->GetUINT(0x0028, 0x0010)))
+ {
+ SystemDebug.printf("***[CompressJPEG2K]: Failed to get image height.\n");
+ free(image);
+ return(FALSE);
+ }
+// Get the Columns VR and check size.
+ if(!(image->brx_ = pDDO->GetUINT(0x0028, 0x0011)))
+ {
+ OperatorConsole.printf("***[CompressJPEG2K]: Failed to get image width.\n");
+ free(image);
+ return(FALSE);
+ }
+ byteWidth = 1;
+ byteWidthIn = 1;
+ if(!(bitwa = pDDO->GetBYTE(0x0028, 0x0100)))bitwa = 8; // 8 bit default.
+ if(!(prec = pDDO->GetBYTE(0x0028, 0x0101)))prec = bitwa; // the default.
+ if(prec > bitwa)bitwa = prec;// the bigger one.
+ if(prec > 8)byteWidth = 2;// Will fix 8 in 16 with a buffer.
+ if(bitwa > 8)byteWidthIn = 2;
+// Check if we can do it
+ if(bitwa != 8 && bitwa != 12 && bitwa != 16)
+ {
+ OperatorConsole.printf("***[CompressJPEG2K]: Unsuported allocated bit width: %d.\n", bitwa);
+ free(image);
+ return(FALSE);
+ }
+// Checked if the data is signed,
+ if(!(sgnd = pDDO->GetBYTE(0x0028, 0x0103)))sgnd = 0;
+// Set the image or buffer size
+ size = image->brx_ * image->bry_ * byteWidth;
+// Planar configuration default.
+ planes = FALSE;
+// Sort colors.
+ colorTypeIn = image->clrspc_ = JAS_CLRSPC_FAM_GRAY;// The default
+ colorASC = NULL;
+ if(image->maxcmpts_ == 1)
+ {
+ planes = TRUE;//Just 1 plane.
+ }
+ else if(image->maxcmpts_ == 3)
+ {
+ pVR = pDDO->GetVR(0x0028, 0x0004); // Get the color profile
+ if(pVR && pVR->Length > 2) colorASC = (char *)pVR->Data;
+// Look for the color type
+ if(colorASC == NULL || strncmp(colorASC, "RGB",3)==0)// RGB
+ {// Only RGB can be in planes or R,G,B format, check.
+ if(pDDO->GetBYTE(0x0028, 0x0006)) planes = TRUE;; // Check planes.
+/* pVR = pDDO->GetVR(0x0028, 0x0006); // Get the plane's VR.
+ if(pVR && pVR->Length && (*(char *)(pVR->Data) == 1)) planes = TRUE;*/
+ colorTypeIn = image->clrspc_ = JAS_CLRSPC_FAM_RGB;
+ }
+ else if (pVR->Length > 6 && strncmp(colorASC, "YBR_",4)==0)
+ {
+ image->clrspc_ = JAS_CLRSPC_FAM_YCBCR;
+ if ((strncmp(&colorASC[4], "ICT",3)==0) || (strncmp(&colorASC[4], "RCT",3)==0))
+ {
+ OperatorConsole.printf
+ ("Warn[CompressJPEG2K]: Uncompressed colorspace can not be YBR_ICT or YBR_RCT. Trying RGB\n");
+ colorTypeIn = image->clrspc_ = JAS_CLRSPC_FAM_RGB;
+ planes = FALSE;
+ }
+ if (pVR->Length > 7 && strncmp(&colorASC[4], "FULL",4)==0)// YBR_FULL(_422)
+ {
+ if (pVR->Length > 11 && strncmp(&colorASC[8], "_422",4)==0)// YBR_FULL_422
+ {
+ colorTypeIn = CLRSPC_FAM_YCBCR_F422;
+ planes = FALSE;
+ }
+ else// YBR_FULL
+ {
+ colorTypeIn = JAS_CLRSPC_FAM_YCBCR;
+ planes = TRUE;
+ }
+ }
+ if (pVR->Length > 14 && strncmp(&colorASC[4], "PARTIAL_42",10)==0)// YBR_PARTIAL_42x
+ {
+ planes = FALSE;
+ if(colorASC[14] == '0')colorTypeIn = CLRSPC_FAM_YCBCR_420;
+ else colorTypeIn = CLRSPC_FAM_YCBCR_422;
+ }
+ }// End of YBR_
+// Add more colors here.
+ else
+ {
+ if((colorASC = pDDO->GetCString(0x0028, 0x0004)))
+ {
+ OperatorConsole.printf(
+ "***[CompressJPEGL]: Unknown or unsuported color space %s.\n",colorASC);
+ free(colorASC);
+ }
+ else OperatorConsole.printf(
+ "***[CompressJPEGL]: Unknown or unsuported color space record.\n");
+ free(image);
+ return (FALSE);
+ }
+ }//image->maxcmpts_ == 3
+ else
+ {
+ OperatorConsole.printf("***[CompressJPEG2K]: Unsupported number of components %d.\n",image->maxcmpts_);
+ free(image);
+ return (FALSE);
+ }
+// Get the data.
+ pVR = pDDO->GetVR(0x7fe0, 0x0010); // Get the Image VR.
+ vrImage = pVR;
+ if(pVR && pVR->Length)
+ {
+ if(pVR->SQObjectArray)
+ {//This should not be for uncompressed.
+ ArrayImage = (Array<DICOMDataObject *> *) pVR->SQObjectArray;
+ while (inputArrayCnt < ArrayImage->GetSize())
+ {
+ DDO = ArrayImage->Get(inputArrayCnt++);//Get the array.
+ vrImage = DDO->GetVR(0xfffe, 0xe000);//Get the data.
+ if(vrImage && vrImage->Length >=
+ (unsigned int)(image->brx_ * image->bry_ * byteWidthIn * image->maxcmpts_)) break;
+ }
+ }
+ }
+// Check for a least one frame.
+ if(!vrImage || vrImage->Length < (unsigned int)(size * image->maxcmpts_))
+ {
+ OperatorConsole.printf("***[CompressJPEG2K]: Could not find the image data.\n");
+ free(image);
+ return (FALSE);
+ }
+ buffer_ptr = (char *)vrImage->Data;
+/*#if NATIVE_ENDIAN == LITTLE_ENDIAN // Little Endian
+ if((planes || (image->maxcmpts_ == 1)) && ((bitwa == 8) || (bitwa == 16)))
+#else // Big Endian like Apple power pc*/
+ if((planes || (image->maxcmpts_ == 1)) && (bitwa == 8))
+//#endif
+ {// No need for buffers, just pointers
+ for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno)
+ {
+ colorBuffer[cmptno] = buffer_ptr + (size * cmptno) ;
+ colorBuffer_ptr[cmptno] = colorBuffer[cmptno];
+ }
+ }
+ else// Buffers are needed.
+ {
+ for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno)
+ {
+ if(!(colorBuffer[cmptno] = (char *)malloc(size)))
+ {
+ OperatorConsole.printf(
+ "***[CompressJPEG2K]: Could not allocate a %d byte image buffer #%d.\n",
+ size, cmptno);
+ while(cmptno > 0) free(colorBuffer[--cmptno]);
+ free(image);
+ return (FALSE);
+ }
+ colorBuffer_ptr[cmptno] = colorBuffer[cmptno];
+ }
+ if(colorTypeIn == CLRSPC_FAM_YCBCR_420)
+ {
+ if(!(brcrBuffer = (char *)malloc(image->brx_)))
+ {
+ OperatorConsole.printf(
+ "***[CompressJPEG2K]: Could not allocate a %d byte image 420 buffer.\n",
+ image->brx_);
+ while(cmptno > 0) free(colorBuffer[--cmptno]);
+ free(image);
+ return (FALSE);
+ }
+ }
+ buffers = TRUE;
+ }
+// Allocate memory for the per-component pointer table.
+ if (!(image->cmpts_ = ((jas_image_cmpt_t **)jas_malloc(image->maxcmpts_ *
+ sizeof(jas_image_cmpt_t *)))))
+ {
+ OperatorConsole.printf("***[CompressJPEG2K]: Could not create component pointers.\n");
+ if(buffers)
+ {
+ for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno)
+ {
+ if(colorBuffer[cmptno]) free(colorBuffer[cmptno]);
+ colorBuffer[cmptno] =NULL;
+ }
+ if(colorTypeIn == CLRSPC_FAM_YCBCR_420)if(brcrBuffer)free(brcrBuffer);
+ }
+ free(image);
+ return (FALSE);
+ }
+// Initialize in case of failure so jas_image_destroy can be used.
+ for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno)
+ image->cmpts_[cmptno] = 0;
+ image->inmem_ = TRUE;
+ image->cmprof_ = 0;
+// Allocate memory for the per-component information and init.
+ for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno)
+ {
+ if (!(cmpt = (jas_image_cmpt_t *)jas_malloc(sizeof(jas_image_cmpt_t))))
+ {
+ jas_image_destroy(image);
+ OperatorConsole.printf("***[CompressJPEG2K]: Could not create empty components.\n");
+ if(buffers)
+ {
+ for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno)
+ {
+ if(colorBuffer[cmptno]) free(colorBuffer[cmptno]);
+ colorBuffer[cmptno] = NULL;
+ }
+ if(colorTypeIn == CLRSPC_FAM_YCBCR_420)if(brcrBuffer)free(brcrBuffer);
+ }
+ return (FALSE);
+ }
+ image->cmpts_[cmptno] =cmpt;
+ cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;//Set next.
+ cmpt->tlx_ = 0;
+ cmpt->tly_ = 0;
+ cmpt->hstep_ = 1;
+ cmpt->vstep_ = 1;
+ cmpt->width_ = image->brx_;
+ cmpt->height_ = image->bry_;
+ cmpt->prec_ = prec;
+ cmpt->sgnd_ = sgnd;
+ cmpt->stream_ = 0;
+ cmpt->cps_ = byteWidth;
+ if(!(cmpt->stream_ = jas_stream_memopen( colorBuffer[cmptno], size)))
+ {
+ jas_free(cmpt);
+ jas_image_destroy(image);
+ OperatorConsole.printf("***[CompressJPEG2K]: Jasper could not open the memory as stream.\n");
+ if(buffers)
+ {
+ for (; cmptno < image->maxcmpts_; ++cmptno)// From curr # forward
+ {
+ if(colorBuffer[cmptno]) free(colorBuffer[cmptno]);
+ colorBuffer[cmptno] = NULL;
+ }
+ if(colorTypeIn == CLRSPC_FAM_YCBCR_420)if(brcrBuffer)free(brcrBuffer);
+ }
+ return (FALSE);
+ }
+ ++(image->numcmpts_);
+ }
+// Now set the color type
+ switch (image->clrspc_)
+ {
+ case JAS_CLRSPC_FAM_GRAY:
+ jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
+ jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
+ break;
+ case JAS_CLRSPC_FAM_RGB:
+ jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
+ jas_image_setcmpttype(image, 0,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
+ jas_image_setcmpttype(image, 1,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
+ jas_image_setcmpttype(image, 2,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
+ break;
+ default:
+ jas_image_setclrspc(image, JAS_CLRSPC_SYCBCR);
+ jas_image_setcmpttype(image, 0,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y));
+ jas_image_setcmpttype(image, 1,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB));
+ image->cmpts_[1]->sgnd_ = TRUE;
+ jas_image_setcmpttype(image, 2,
+ JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR));
+ image->cmpts_[2]->sgnd_ = TRUE;
+ }
+// Lossy (ICT) or lossless (RCT)?
+ if((j2kQuality < 100) || (image->clrspc_ == JAS_CLRSPC_FAM_YCBCR))
+ {
+ if(j2kQuality >= 100)j2kQuality = 95;
+ memcpy(option, "mode=real rate=0.", 17);
+ option[17] = (j2kQuality / 10) + '0';//ICT j2kQuality msb
+ option[18] = (j2kQuality % 10) + '0';//ICT j2kQuality lsb
+ option[19] = 0;//end the string.
+ if (DebugLevel > 2)SystemDebug.printf("JPEG2K Lossy Quality = %d\n", j2kQuality);
+ }
+ else
+ {
+ memcpy(option, "mode=int\0", 9);//RCT
+ if (DebugLevel > 2)SystemDebug.printf("JPEG2K Lossless\n");
+ }
+// Use a temp file to hold the data, easier to get the compressed size.
+ NewTempFileWExt(name, ".j2k");
+// Print out some more info for debug.
+ if (DebugLevel > 2)
+ {
+ if (DebugLevel > 3)
+ {
+ if(!buffers)SystemDebug.printf(", unbuffered data\n");
+ else SystemDebug.printf(", buffered data\n");
+ if(planes)SystemDebug.printf(", planes\n");
+ }
+ SystemDebug.printf(
+ ", H = %d, W = %d, Bits = %d in %d, Frames = %d, \n",
+ image->brx_, image->brx_, prec, bitwa, frames);
+ if((colorASC = pDDO->GetCString(0x0028, 0x0004)))
+ {
+ SystemDebug.printf("color = %s\n", colorASC);
+ free(colorASC);
+ }
+ else SystemDebug.printf("Unknown color space record.\n");
+ }
+// Create the encapsulation array.
+ ArrayPtr = new Array < DICOMDataObject * >;
+// The first blank object.
+ DDO = new DICOMDataObject;
+ vrs = new VR(0xfffe, 0xe000, 0, (void *)NULL, FALSE);
+ DDO->Push(vrs);
+ ArrayPtr->Add(DDO);
+// Frames loop.
+ while(TRUE)
+ {
+ if(buffers)
+ {
+// Now to fill the buffers.
+ switch(colorTypeIn)
+ {
+ case JAS_CLRSPC_FAM_GRAY://12 or 12,16 bits here
+/* For sone reason jasper wants the data in big endian on both a LE and BE system.
+* There may be an option switch for this, but I just swpped endian. */
+ if(bitwa == 16) // 16 Bits, byte swap time.
+ {
+ if(prec > 8) //Just swap.
+ {
+ for(byteCnt = 0; byteCnt < size; byteCnt++)
+ {
+ byteCnt++;// 2 bytes per pixel.
+ *colorBuffer_ptr[0]++ = buffer_ptr[1];
+ *colorBuffer_ptr[0]++ = *buffer_ptr++;
+ buffer_ptr++;
+ }
+ break;
+ }
+ for(byteCnt = 0; byteCnt < size; byteCnt++)//Only need 8.
+ {
+ *colorBuffer_ptr[0]++ = *buffer_ptr++;
+ buffer_ptr++;// Skip the zero byte.
+ }
+ break;
+ }
+ else
+ for(byteCnt = 0; byteCnt < size; byteCnt++)//12 bit
+ {
+ colorBuffer_ptr[0][1] = (*buffer_ptr & 0xF0) >> 4;//8-11
+ *colorBuffer_ptr[0] = (*buffer_ptr++ & 0x0F) << 4;//4-7
+ *colorBuffer_ptr[0]++ |= (*buffer_ptr & 0xF0) >> 4;//0-3
+ colorBuffer_ptr[0]++;
+ byteCnt++;
+ if(byteCnt >= size)break;
+ colorBuffer_ptr[0][1] = *buffer_ptr++ & 0x0F;//8-11
+ byteCnt++;
+ *colorBuffer_ptr[0]++ = *buffer_ptr++;//0-7
+ colorBuffer_ptr[0]++;
+ byteCnt++;
+ }
+ break;
+ case JAS_CLRSPC_FAM_RGB:
+ for(byteCnt = 0; byteCnt < size; byteCnt++)
+ {
+ *(colorBuffer_ptr[0])++ = *buffer_ptr++;
+ *(colorBuffer_ptr[1])++ = *buffer_ptr++;
+ *(colorBuffer_ptr[2])++ = *buffer_ptr++;
+ }
+ break;
+ case CLRSPC_FAM_YCBCR_F422://Y1Y2CbCr
+ for(byteCnt = 0; byteCnt < size; byteCnt++)
+ {
+ byteCnt++;// 2 Ys per pixel.
+ *colorBuffer_ptr[0]++ = *buffer_ptr++;
+ *colorBuffer_ptr[0]++ = *buffer_ptr++;
+ *colorBuffer_ptr[1]++ = *buffer_ptr;
+ *colorBuffer_ptr[1]++ = *buffer_ptr++;
+ *colorBuffer_ptr[2]++ = *buffer_ptr;
+ *colorBuffer_ptr[2]++ = *buffer_ptr++;
+ }
+ break;
+ case CLRSPC_FAM_YCBCR_422://Y1Y2CbCr
+ for(byteCnt = 0; byteCnt < size; byteCnt++)
+ {
+ byteCnt++;// 2 Ys per pass.
+/* For Y the ratio is 256 / 220 (1.1636) and for color 256 / 225 (1.1378).
+* Note: All values are multiplied by 1024 or 1 << 7.
+* Yo = 1.1636(Yi - 16) == Yo = 1.1636Yi - 18.204 ==
+* Yo = [149Yi - 2330]/128 */
+ tempInt = (((int)*buffer_ptr) * 149) - 2330;//Y1
+ buffer_ptr++;
+ if(tempInt & 0x10000)*colorBuffer_ptr[0]++ = 0;// Neg not allowed here.
+ else if(tempInt & 0x8000)*colorBuffer_ptr[0]++ = 0xFF;// Over flow.
+ else *colorBuffer_ptr[0]++ = (char)((tempInt >> 7) & 0xFF);
+ tempInt = (((int)*buffer_ptr) * 149) - 2330;//Y2
+ buffer_ptr++;
+ if(tempInt & 0x10000)*colorBuffer_ptr[0]++ = 0;// Neg not allowed here.
+ else if(tempInt & 0x8000)*colorBuffer_ptr[0]++ = 0xFF;// Over flow.
+ else *colorBuffer_ptr[0]++ = (char)((tempInt >> 7) & 0xFF);
+/* Cxo = 1.1378(Cxi - 16) == Cxo = 1.1378Cxi - 18.205 ==
+* Cxo = [73Cxi - 1152]/64 */
+ tempInt = (((int)*buffer_ptr) * 73) - 1152;//Cb
+ buffer_ptr++;
+ if(tempInt & 0x8000)
+ {
+ *colorBuffer_ptr[1]++ = 0;//Negitive
+ *colorBuffer_ptr[1]++ = 0;//Negitive
+ }
+ else if(tempInt & 0x4000)
+ {
+ *colorBuffer_ptr[1]++ = 0xFF;//Over
+ *colorBuffer_ptr[1]++ = 0xFF;//Over
+ }
+ else
+ {
+ *colorBuffer_ptr[1] = (char)((tempInt >> 6) & 0xFF);
+ *colorBuffer_ptr[1]++ = *colorBuffer_ptr[1];
+ *colorBuffer_ptr[1]++;
+ }
+ tempInt = (((int)*buffer_ptr) * 73) - 1152;//Cb
+ buffer_ptr++;
+ if(tempInt & 0x8000)
+ {
+ *colorBuffer_ptr[2]++ = 0;//Negitive
+ *colorBuffer_ptr[2]++ = 0;//Negitive
+ }
+ else if(tempInt & 0x4000)
+ {
+ *colorBuffer_ptr[2]++ = 0xFF;//Over
+ *colorBuffer_ptr[2]++ = 0xFF;//Over
+ }
+ else
+ {
+ *colorBuffer_ptr[2] = (char)((tempInt >> 6) & 0xFF);
+ *colorBuffer_ptr[2]++ = *colorBuffer_ptr[1];
+ *colorBuffer_ptr[2]++;
+ }
+ }
+ break;
+// What a strange standard. See page 323 of 08_03pu.pdf.
+ case CLRSPC_FAM_YCBCR_420://Y1CrCbY2Y3CrCbY4-Y1Y2Y3Y4?
+ for(rowCnt = 0; rowCnt < image->bry_; rowCnt++)// 8 bit only.
+ {
+ rowCnt++;// 2 Ys per vertical pass.
+ bufferPtr = brcrBuffer;
+ for(byteCnt = 0; byteCnt < image->brx_; byteCnt++)
+ {
+ byteCnt++;// 2 Ys per horizantal pass.
+ tempInt = (((int)*buffer_ptr) * 149) - 2330;//Y1, Y3, ...
+ buffer_ptr++;
+ if(tempInt & 0x10000)*colorBuffer_ptr[0]++ = 0;// Neg not allowed here.
+ else if(tempInt & 0x8000)*colorBuffer_ptr[0]++ = 0xFF;// Over flow.
+ else *colorBuffer_ptr[0]++ = (char)((tempInt >> 7) & 0xFF);
+ tempInt = (((int)*buffer_ptr) * 73) - 1152;//Cb
+ buffer_ptr++;
+ if(tempInt & 0x8000)
+ {
+ *bufferPtr++ = 0;//Next time negitive = 0
+ *colorBuffer_ptr[1]++ = 0;//Negitive
+ *colorBuffer_ptr[1]++ = 0;//Negitive
+ }
+ else if(tempInt & 0x4000)
+ {
+ *bufferPtr++ = 0xFF;//Next time over = 255
+ *colorBuffer_ptr[1]++ = 0xFF;//Over
+ *colorBuffer_ptr[1]++ = 0xFF;//Over
+ }
+ else
+ {
+ *bufferPtr = (char)((tempInt >> 6) & 0xFF);
+ *colorBuffer_ptr[1]++ = *bufferPtr;
+ *colorBuffer_ptr[1]++ = *bufferPtr++;
+ }
+ tempInt = (((int)*buffer_ptr) * 73) - 1152;//Cb
+ buffer_ptr++;
+ if(tempInt & 0x8000)
+ {
+ *bufferPtr++ = 0;//Next time negitive = 0
+ *colorBuffer_ptr[2]++ = 0;//Negitive
+ *colorBuffer_ptr[2]++ = 0;//Negitive
+ }
+ else if(tempInt & 0x4000)
+ {
+ *bufferPtr++ = 0xFF;//Next time over = 255
+ *colorBuffer_ptr[2]++ = 0xFF;//Over
+ *colorBuffer_ptr[2]++ = 0xFF;//Over
+ }
+ else
+ {
+ *bufferPtr = (char)((tempInt >> 6) & 0xFF);
+ *colorBuffer_ptr[2]++ = *bufferPtr;
+ *colorBuffer_ptr[2]++ = *bufferPtr++;
+ }
+ }
+ bufferPtr = brcrBuffer;
+ for(byteCnt = 0; byteCnt < image->brx_; byteCnt++)
+ {
+ byteCnt++;// 2 Ys per horizantal pass.
+ tempInt = (((int)*buffer_ptr) * 149) - 2330;//Y1, Y3, ...
+ buffer_ptr++;
+ if(tempInt & 0x10000)*colorBuffer_ptr[0]++ = 0;// Neg not allowed here.
+ else if(tempInt & 0x8000)*colorBuffer_ptr[0]++ = 0xFF;// Over flow.
+ else *colorBuffer_ptr[0]++ = (char)((tempInt >> 7) & 0xFF);
+ tempInt = (((int)*buffer_ptr) * 149) - 2330;//Y1, Y3, ...
+ buffer_ptr++;
+ if(tempInt & 0x10000)*colorBuffer_ptr[0]++ = 0;// Neg not allowed here.
+ else if(tempInt & 0x8000)*colorBuffer_ptr[0]++ = 0xFF;// Over flow.
+ else *colorBuffer_ptr[0]++ = (char)((tempInt >> 7) & 0xFF);
+ *colorBuffer_ptr[1]++ = *bufferPtr;
+ *colorBuffer_ptr[1]++ = *bufferPtr++;
+ *colorBuffer_ptr[2]++ = *bufferPtr;
+ *colorBuffer_ptr[2]++ = *bufferPtr++;
+ }
+ }
+ break;
+ }// End of the switch
+ }// End of buffers.
+// Open the temp file to hold put data.
+ if (!(out = jas_stream_fopen(name, "w+b")))
+ {
+ jas_image_destroy(image);
+ OperatorConsole.printf("***[CompressJPEG2K]: Jasper could not open the file: %s.\n", name);
+ if(buffers)
+ {
+ for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno)
+ {
+ if(colorBuffer[cmptno]) free(colorBuffer[cmptno]);
+ colorBuffer[cmptno] = NULL;
+ }
+ if(colorTypeIn == CLRSPC_FAM_YCBCR_420)if(brcrBuffer)free(brcrBuffer);
+ }
+ while(ArrayPtr->GetSize())
+ {
+ delete ArrayPtr->Get(0);
+ ArrayPtr->RemoveAt(0);
+ }
+ delete ArrayPtr;
+ return (FALSE);
+ }
+// Time to compress.
+ if(jpc_encode(image, out, option))
+ {
+ jas_stream_close(out);
+ unlink(name);
+ jas_image_destroy(image);
+ OperatorConsole.printf("***[CompressJPEG2K]: Jasper could not encode the image.\n");
+ if(buffers)
+ {
+ for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno)
+ {
+ if(colorBuffer[cmptno]) free(colorBuffer[cmptno]);
+ colorBuffer[cmptno] = NULL;
+ }
+ if(colorTypeIn == CLRSPC_FAM_YCBCR_420)if(brcrBuffer)free(brcrBuffer);
+ }
+ while(ArrayPtr->GetSize())
+ {
+ delete ArrayPtr->Get(0);
+ ArrayPtr->RemoveAt(0);
+ }
+ delete ArrayPtr;
+ return (FALSE);
+ }
+ jas_stream_close(out);// Jasper is done with the file.
+// Lets get the data.
+ fp = fopen(name, "rb");
+ if(!fp)
+ {
+ jas_image_destroy(image);
+ OperatorConsole.printf("***[CompressJPEG2K]: Could open the Jasper output file %s.\n",name);
+ if(buffers)
+ {
+ for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno)
+ {
+ if(colorBuffer[cmptno]) free(colorBuffer[cmptno]);
+ colorBuffer[cmptno] = NULL;
+ }
+ if(colorTypeIn == CLRSPC_FAM_YCBCR_420)if(brcrBuffer)free(brcrBuffer);
+ }
+ while(ArrayPtr->GetSize())
+ {
+ delete ArrayPtr->Get(0);
+ ArrayPtr->RemoveAt(0);
+ }
+ delete ArrayPtr;
+ return ( FALSE );
+ }
+ fseek(fp, 0, SEEK_END);
+ fileLength = ftell(fp);
+ if(fileLength == -1 || fileLength == 0)
+ {
+ if(fileLength == 0)
+ OperatorConsole.printf("***[CompressJPEG2K]: File %s has a zero length\n", name);
+ else
+ OperatorConsole.printf("***[CompressJPEG2K]: Could not get file size for %s\n", name);
+ jas_image_destroy(image);
+ fclose(fp);
+ unlink(name);
+ if(buffers)
+ {
+ for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno)
+ {
+ if(colorBuffer[cmptno]) free(colorBuffer[cmptno]);
+ colorBuffer[cmptno] = NULL;
+ }
+ if(colorTypeIn == CLRSPC_FAM_YCBCR_420)if(brcrBuffer)free(brcrBuffer);
+ }
+ while(ArrayPtr->GetSize())
+ {
+ delete ArrayPtr->Get(0);
+ ArrayPtr->RemoveAt(0);
+ }
+ delete ArrayPtr;
+ return ( FALSE );
+ }
+ rewind(fp);
+// Jpeg2k is encapsulated, make a new vr to encapsulate.
+ vrs = new VR(0xfffe, 0xe000, fileLength, TRUE);
+ if(!vrs)
+ {
+ OperatorConsole.printf("***[CompressJPEG2K]: Failed to allocate memory.\n");
+ fclose(fp);
+ unlink(name);
+ jas_image_destroy(image);
+ if(buffers)
+ {
+ for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno)
+ {
+ if(colorBuffer[cmptno]) free(colorBuffer[cmptno]);
+ colorBuffer[cmptno] = NULL;
+ }
+ if(colorTypeIn == CLRSPC_FAM_YCBCR_420)if(brcrBuffer)free(brcrBuffer);
+ }
+ while(ArrayPtr->GetSize())
+ {
+ delete ArrayPtr->Get(0);
+ ArrayPtr->RemoveAt(0);
+ }
+ delete ArrayPtr;
+ return ( FALSE );
+ }
+//If odd data length, zero the added byte.
+ if ( fileLength & 1 ) ((BYTE *)vrs->Data)[fileLength] = 0;
+//Change the Image data.
+ lengthRead = fread(vrs->Data,1,fileLength,fp);
+ if(lengthRead <= 0)
+ {
+ err = ferror(fp);
+ if(err) OperatorConsole.printf("***[CompressJPEG2K]: File read error %d on %s.\n",err,name);
+ else OperatorConsole.printf("***[CompressJPEG2K]: No compressed image data (0 length read).\n");
+ fclose(fp);
+ unlink(name);
+ jas_image_destroy(image);
+ if(buffers)
+ {
+ for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno)
+ {
+ if(colorBuffer[cmptno]) free(colorBuffer[cmptno]);
+ colorBuffer[cmptno] = NULL;
+ }
+ if(colorTypeIn == CLRSPC_FAM_YCBCR_420)if(brcrBuffer)free(brcrBuffer);
+ }
+ while(ArrayPtr->GetSize())
+ {
+ delete ArrayPtr->Get(0);
+ ArrayPtr->RemoveAt(0);
+ }
+ delete ArrayPtr;
+ delete vrs;
+ return ( FALSE );
+ }
+ if( lengthRead != fileLength)// Already checked for - 1.
+ {
+ OperatorConsole.printf("warn[CompressJPEG2K]: Only read %d bytes of %d of the jpeg2k file:%s, will try to save\n",
+ vrs->Length, fileLength, name);
+ }
+ fclose(fp);
+ unlink(name);
+// Save the image object.
+ DDO = new DICOMDataObject;
+ DDO->Push(vrs);
+ ArrayPtr->Add(DDO);
+ if(++currFrame >= frames)break;//Done with all of the frames.
+//Out of data?
+// Deal with silly input arrays
+ if(inputArrayCnt > 0 && (size * image->numcmpts_ * currFrame) < vrImage->Length)
+ {// Look for the next array.
+ while (inputArrayCnt < ArrayImage->GetSize())
+ {
+ DDO = ArrayImage->Get(inputArrayCnt++);//Get the array.
+ vrImage = DDO->GetVR(0xfffe, 0xe000);//Get the data
+// If found next one, break inner loop.
+ if(vrImage && vrImage->Length >= (unsigned int)(size * image->numcmpts_)) break;
+ }
+ if(!vrImage || vrImage->Length < (unsigned int)(size * image->numcmpts_)) break;// Not enough data for at least 1 frame.
+ buffer_ptr = (char *)vrImage->Data; // Piont at the new buffer.
+ }
+// No silly arrays ( or a least one big file in the array).
+ else
+ {
+ if(!buffers) buffer_ptr += (size * image->numcmpts_);//next plane or gray.
+ if((unsigned int)(buffer_ptr - (char *)vrImage->Data + (size * image->numcmpts_))
+ > vrImage->Length)break;
+ }
+ for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno)
+ {
+ if(buffers)
+ {// Reset the buffers and streams.
+ jas_stream_rewind( image->cmpts_[cmptno]->stream_ );
+ colorBuffer_ptr[cmptno] = colorBuffer[cmptno];// Reset the buffers.
+ }
+ else
+ {// Close and reopen the streams at the new locations.
+ jas_stream_close( image->cmpts_[cmptno]->stream_);
+ image->cmpts_[cmptno]->stream_ = NULL;
+ if(!(cmpt->stream_ = jas_stream_memopen( buffer_ptr + (size * cmptno),size )))
+ {
+ jas_image_destroy(image);
+ OperatorConsole.printf("***[CompressJPEG2K]: Jasper could not open the memory as stream.\n");
+ if(buffers) if(colorTypeIn == CLRSPC_FAM_YCBCR_420)if(brcrBuffer)free(brcrBuffer);
+ return (FALSE);
+ }
+ }
+ }
+ }//Back for the next frame, end of while(TRUE)
+// Should we kill it and keep the uncompressed data?
+ if(currFrame < frames) OperatorConsole.printf(
+ "Warn[CompressJPEG2K]: Only %d of %d frames saved.\n",currFrame, frames);
+// If buffers were made, free them.
+ if(buffers)
+ {
+ for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno)
+ {
+ if(colorBuffer[cmptno]) free(colorBuffer[cmptno]);
+ colorBuffer[cmptno] = NULL;
+ }
+ if(colorTypeIn == CLRSPC_FAM_YCBCR_420)if(brcrBuffer)free(brcrBuffer);
+ }
+// The end object.
+ DDO = new DICOMDataObject;
+ vrs = new VR(0xfffe, 0xe0dd, 0, (void *)NULL, FALSE);
+ DDO->Push(vrs);
+ ArrayPtr->Add(DDO);
+// vrs = new VR(0x7fe0, 0x0010, 0, (void *)NULL, FALSE);
+ pVR->Reset();//Clear the old image data including arrays.
+ pVR->SQObjectArray = ArrayPtr;// Replace the data
+ pVR->TypeCode ='OW';
+// pVR->Length = 0xFFFFFFFF;
+// Change the dicom parameters
+ if(image->numcmpts_ > 1)
+ {
+// Reset the plane's VR, if there.
+ pVR = pDDO->GetVR(0x0028, 0x0006);
+ if(pVR && pVR->Length && *(char *)pVR->Data == 1) *(char *)pVR->Data = 0;
+// Set the color profile
+ if(j2kQuality < 100)
+ pDDO->ChangeVR( 0x0028, 0x0004, "YBR_ICT\0", 'CS');
+ else pDDO->ChangeVR( 0x0028, 0x0004, "YBR_RCT\0", 'CS');
+ }
+// Fix the bits allocated.
+ // 20120624: do not change highbit and bitsstored
+ //if(byteWidth == 1)pDDO->ChangeVR( 0x0028, 0x0100, (UINT8)8, 'US');
+ //else pDDO->ChangeVR( 0x0028, 0x0100, (UINT8)16, 'US');
+
+ //Change the transfer syntax to JPEG2K!
+ if(j2kQuality < 100)
+ pDDO->ChangeVR( 0x0002, 0x0010, "1.2.840.10008.1.2.4.91\0", 'IU');
+ else pDDO->ChangeVR( 0x0002, 0x0010, "1.2.840.10008.1.2.4.90\0", 'IU');
+// Done with Jasper.
+ jas_image_destroy(image);
+// If debug > 0, print when finished
+ if (DebugLevel > 0)
+ SystemDebug.printf("Jasper compress time %u seconds.\n", (unsigned int)time(NULL) - t);
+ return (TRUE);
+}
+
+/* This routine will take in a jpeg2000 image and convert it to little endian, uncompressed,
+* RGB or grayscale. It uses the Jasper library by Michael D. Adams from the
+* Department of Electrical and Computer Engineering at the University of Victoria.
+* You can get it here:
+* http://www.ece.uvic.ca/~mdadams/jasper/
+* You can also get it here with a few minor changes to use the my Jpeg-6c
+* library, but none of the changes are used by dgate:
+* http://www.bitsltd.net/Software/Software-Repository/index.php
+* Jasper can compress anything, with any size for each plane. So that means any
+* of the color spaces and formats can be in it. The dicom standard removes the header
+* and color box infromation and sends just the data stream. The standard states only
+* MONO1,2 PALETTE_COLOR YBR_RCT and YBR_ICT can be use. For the color space and
+* image format, I have to trust jasper.
+* If I have made some mistakes (most likely), you can contact me bruce.barton
+* (the mail symbol goes here) bitsltd.net. Let me know where I can find a sample of
+* the image that didn't work. */
+BOOL DecompressJPEG2K(DICOMDataObject* pDDO)
+{
+ Array < DICOMDataObject *> *ArrayPtr;
+ DICOMDataObject *DDO;
+ VR *pVR,p, *vrImage;
+ unsigned char *streamData;
+#ifdef NOVARAD_FIX
+ void *fixPtr;
+ unsigned char *fix1Ptr, *fix2Ptr;
+#endif
+ char *outData;
+ unsigned int frames;
+ unsigned int currFrame, currSQObject;
+ jas_stream_t *jas_in, *jas_out[4];
+ jas_image_t *decompImage;
+// jas_image_cmpt_t *imageComp;
+ char *out_ptr;
+ unsigned int i, cps_jas, t;
+ UINT8 numcmpts, prec;
+// UINT16 bitwa, bitws,;
+ UINT32 stream_len, instream_len, total_len;
+
+// If debug > 1, get start time and set the level.
+ t=0;
+ if (DebugLevel > 0)
+ {
+ t = (unsigned int)time(NULL);
+ jas_setdbglevel(DebugLevel);
+ }
+ if (DebugLevel > 3) SystemDebug.printf("Jasper decompress started.\n");
+// Init the jasper library.
+ if(jas_init())
+ {
+ OperatorConsole.printf("***[DecompressJPEG2K]: cannot init the jasper library\n");
+ return (FALSE);
+ }
+ if (DebugLevel > 3) SystemDebug.printf("Jasper library init completed.\n");
+// Uninitialized warnings.
+ prec = 8;
+ outData = NULL;
+ out_ptr = NULL;
+ total_len = 0;
+ cps_jas = 1;
+ stream_len = 0;
+// Get the number of samples per pixel VR.
+ if(!(numcmpts = pDDO->GetBYTE(0x0028, 0x0002))) numcmpts = 1;// Gray default.
+// Are there frames?
+ currFrame = 0;
+ if(!(frames = pDDO->Getatoi(0x0028, 0x0008))) frames = 1;
+// Get the encapsulated data.
+ pVR = pDDO->GetVR(0x7fe0, 0x0010); // Get the Image VR.
+ if(!pVR)
+ {
+ OperatorConsole.printf("***[DecompressJPEG2K]: No image VR\n");
+ return (FALSE);
+ }
+ currSQObject = 0;// Init now for no warning later.
+ if(pVR->SQObjectArray)
+ {
+ ArrayPtr = (Array<DICOMDataObject *> *) pVR->SQObjectArray;
+ while(TRUE)
+ {
+ if( currSQObject >= ArrayPtr->GetSize())
+ {
+ OperatorConsole.printf("***[DecompressJPEG2K]: No j2k data found\n");
+ return (FALSE);
+ }
+ DDO = ArrayPtr->Get(currSQObject);//Get the last array.
+ vrImage = DDO->GetVR(0xfffe, 0xe000);//Get the data
+//Look for size and j2k marker or jp2 file header.
+ if(vrImage->Length)
+ {
+ streamData = (unsigned char *)vrImage->Data;
+ instream_len = vrImage->Length;
+ if( *streamData == 0xFF) break; //Jpeg stream.
+ if( *streamData == 0x00 && streamData[1] == 0x00 && streamData[2] == 0x00
+ && streamData[3] == 0x0C && streamData[4] == 0x6A && streamData[5] == 0x50)
+ { //Wow, a j2k file header, dicom is normally just the stream.
+ streamData += 6;
+ instream_len -= 6;
+ for(i = 0; i < 512; i++)// I just picked 512.
+ { // Look for stream header.
+ if(*streamData == 0xFF && streamData[1] == 0x4F)break;
+ streamData++;
+ instream_len--;
+ }
+ if( i < 512 )break;// Found the stream.
+ }
+ }
+ currSQObject++;
+ }
+ }
+ else
+ {
+ OperatorConsole.printf("***[DecompressJPEG2K]: No image in encapsulation arrray\n");
+ return (FALSE);
+ }
+// Start the frames loop.
+ while(TRUE)
+ {
+// Fix the stream length.
+ if(streamData[instream_len - 1] == 0) instream_len--;
+#ifdef NOVARAD_FIX
+// Put the end of file back if not present.
+ if ((streamData[instream_len - 2] != 0xFF)
+ || (streamData[instream_len - 1] != 0xD9))
+ {
+ if(!(fixPtr = malloc(vrImage->Length + 2)))
+ {
+ OperatorConsole.printf("***[DecompressJPEG2K]: Can not create memory fix buffer.\n");
+ return (FALSE);
+ }
+ fix1Ptr = (unsigned char*)fixPtr;
+ fix2Ptr = (unsigned char*)vrImage->Data;
+ for( i = instream_len; i > 0; --i ) *fix1Ptr++ = *fix2Ptr++;
+ *fix1Ptr++ = 0xFF;
+ *fix1Ptr++ = 0xD9;
+ if(instream_len & 1 ) *fix1Ptr = 0;
+ free(vrImage->Data);
+ vrImage->Data = fixPtr;
+ vrImage->Length += 2;
+ streamData = (unsigned char*)vrImage->Data;
+ instream_len = vrImage->Length;
+ if(DebugLevel > 0)SystemDebug.printf("Warn[DecompressJPEG2K]: Novarad fix, EOC marker added.\n");
+ }
+#endif
+// Open the memory as a stream.
+ if(!(jas_in = jas_stream_memopen((char*)streamData, instream_len)))
+ {
+ OperatorConsole.printf("***[DecompressJPEG2K]: cannot open jpeg 2K data\n");
+ return (FALSE);
+ }
+// Decopress the stream.
+ if (!(decompImage = jpc_decode(jas_in, NULL)))
+ {
+ OperatorConsole.printf("***[DecompressJPEG2K]: cannot decode the jpeg 2K code stream\n");
+ jas_stream_close(jas_in);
+ return ( FALSE );
+ }
+ jas_stream_close(jas_in);
+// Do this the first time only.
+ if(!currFrame)
+ {
+// Check for color.
+ if(numcmpts > 1)
+ {
+ if((numcmpts != 3) || (decompImage->numcmpts_ != 3))
+ {
+ OperatorConsole.printf(
+ "***[DecompressJPEG2K]: Should be 3 colors, DICOM: %d ,J2K: %d \n",
+ numcmpts , decompImage->numcmpts_);
+ jas_image_destroy(decompImage);
+ return ( FALSE );
+ }
+ }
+// Get the total uncompressed length and rewind all streams and get pointers.
+ stream_len = 0;
+ for ( i = 0; i < numcmpts ; i++ )
+ {
+ jas_out[i] = decompImage->cmpts_[i]->stream_;
+ jas_stream_rewind(jas_out[i]);
+ stream_len += jas_stream_length(jas_out[i]);
+ }
+ total_len = stream_len * frames;
+ prec = decompImage->cmpts_[0]->prec_;//Save for outside loop
+// bits_jas = jas_image_cmptprec(decompImage, 0);
+// signed_jas = jas_image_cmptsgnd(decompImage, 0);
+ cps_jas = decompImage->cmpts_[0]->cps_;// Bytes or words.
+// Allocate the bigger uncompressed and unencapsulated image.
+ if (( total_len & 1) != 0 ) total_len++;//Odd length, make it even.
+ if (DebugLevel > 3)SystemDebug.printf(
+ "Info[DecompressJPEG2K] stream_len = %d, frames = %d, total_len = %d, prec = %d,cps_jas = %d.\n",
+ stream_len,frames,total_len,prec,cps_jas);
+ if(!(outData = (char *)malloc(total_len)))
+ {
+ OperatorConsole.printf(
+ "***[DecompressJPEG2K]: Failed to allocate %d bytes of memory.\n", total_len);
+ jas_image_destroy(decompImage);
+ return ( FALSE );
+ }
+ outData[total_len -1] = 0;// Dosen't hurt.
+ out_ptr = outData;
+ }// end currFrame = 0.
+ else
+ {//Not first, just rewind streams
+ for ( i = 0; i < numcmpts ; i++ )
+ {
+ jas_out[i] = decompImage->cmpts_[i]->stream_;
+ jas_stream_rewind(jas_out[i]);
+ }
+ }
+//Image copy loops.
+ if( numcmpts == 1)
+ {
+// Again, for some reason, Jasper outputs big endian. There may be a switch.
+//#if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian like Apple power pc
+ if(cps_jas == 2)
+ {
+ for(i = 0; i < stream_len; i++)
+ {
+ out_ptr[1] = jas_stream_getc(jas_out[0]);
+ *out_ptr++ = jas_stream_getc(jas_out[0]);
+ out_ptr++;
+ i++;
+ }
+ }
+ else
+//#endif //Big Endian
+ for(i = 0; i < stream_len; i++)
+ *out_ptr++ = jas_stream_getc(jas_out[0]);
+ }
+ else //RGB
+ {
+ stream_len = jas_stream_length(jas_out[0]);
+ for(i = 0; i < stream_len; i++)
+ {
+ *out_ptr++ = jas_stream_getc(jas_out[0]);
+ *out_ptr++ = jas_stream_getc(jas_out[1]);
+ *out_ptr++ = jas_stream_getc(jas_out[2]);
+ }
+ }
+ jas_image_destroy(decompImage);//Done with the image.
+// check for the end
+ if(++currFrame >= frames)break;
+ // More images to read
+ while(++currSQObject < ArrayPtr->GetSize())
+ {
+ DDO = ArrayPtr->Get(currSQObject);//Get the array.
+ vrImage = DDO->GetVR(0xfffe, 0xe000);//Get the data
+//Look for size and j2k marker or jp2 file header.
+ if(vrImage->Length)
+ {
+ streamData = (unsigned char *)vrImage->Data;
+ instream_len = vrImage->Length;
+ if( *streamData == 0xFF) break; //Jpeg stream.
+ if( *streamData == 0x00 && streamData[1] == 0x00 && streamData[2] == 0x00
+ && streamData[3] == 0x0C && streamData[4] == 0x6A && streamData[5] == 0x50)
+ { //Wow, a j2k file header again, dicom is normally just the stream.
+ streamData += 6;
+ instream_len -= 6;
+ for(i = 0; i < 512; i++)// I just picked 512.
+ { // Look for stream header.
+ if(*streamData == 0xFF && streamData[1] == 0x4F)break;
+ streamData++;
+ instream_len--;
+ }
+ if( i < 512 )break;// Found the stream.
+ }
+ }
+ }
+ if( currSQObject >= ArrayPtr->GetSize() )break;//Should not happen!
+// Loop back to open the memory as a stream.
+ }//End of the frames loop
+ if(currFrame < frames)OperatorConsole.printf(
+ "Warn[DecompressJPEG2K]: Found %d of %d frames.\n",currFrame, frames);
+// Change the image vr to the bigger uncompressed and unencapsulated image.
+ pVR->Reset();// Delete the old data including the array.
+ pVR->Length = total_len;
+ pVR->Data = outData;// The new uncompressed data.
+ pVR->ReleaseMemory = TRUE;//Give the memory to the vr.
+// Set the image type.
+ if(cps_jas == 1)// 8 bits
+ {
+ pVR->TypeCode ='OB';
+ }
+ else
+ {
+ pVR->TypeCode ='OW';
+ }
+// pDDO->DeleteVR(pVR);// replace the pixel data
+// pDDO->Push(vrs);
+// Set color stuff if needed.
+ if( numcmpts > 1)//color.
+ {
+ pDDO->ChangeVR( 0x0028, 0x0004, "RGB\0", 'CS');
+/* pVR = pDDO->GetVR( 0x0028, 0x0004 );
+ if(pVR)
+ {
+ if (pVR->Length != 4) pVR->ReAlloc(4);
+ }
+ else
+ {
+ pVR = new VR(0x0028, 0x0004, 4, TRUE);
+ pDDO->Push(pVR);
+ }
+ memcpy((char *)pVR->Data, "RGB\0",4);*/
+// Optional planar configuration.
+ pVR = pDDO->GetVR(0x0028, 0x0006); // Fix the planes VR if there.
+ if(pVR && pVR->Length && *(char *)(pVR->Data) == 1)
+ {
+ *(UINT16 *)pVR->Data = 0;
+ }
+ }
+
+// Set the number of bits allocated.
+ // 20120624: do not change highbit and bitsstored
+ //if(cps_jas == 1) pDDO->ChangeVR( 0x0028, 0x0100, (UINT8)8, 'US');
+ //else pDDO->ChangeVR( 0x0028, 0x0100, (UINT8)16, 'US');
+
+// DecompressJPEG2K: Set the number of bits stored.
+// mvh 20110502: write highbit for consistency
+ // 20120624: do not change highbit and bitsstored
+ // pDDO->ChangeVR( 0x0028, 0x0101, (UINT8)prec, 'US');
+ // pDDO->ChangeVR( 0x0028, 0x0102, (UINT8)(prec-1), 'US');
+
+//Change the transfer syntax to LittleEndianExplict!
+ pDDO->ChangeVR( 0x0002, 0x0010, "1.2.840.10008.1.2.1\0", 'IU');
+// If debug > 1, print when finished
+ if (DebugLevel > 0)
+ SystemDebug.printf("Jasper decompress time %u seconds.\n", (unsigned int)time(NULL) - t);
+ return (TRUE);
+}
+#endif //End for LIBJASPER
+
+#ifdef HAVE_LIBOPENJPEG
+/* Error and message callback does not use the FILE* client object. */
+void error_callback(const char *msg, void *client_data)
+{
+ UNUSED_ARGUMENT(client_data);
+ OperatorConsole.printf("***[Libopenjpeg(J2k)]: %s\n", msg);
+}
+
+/* Warning callback expecting a FILE* client object. */
+void warning_callback(const char *msg, void *client_data)
+{
+ UNUSED_ARGUMENT(client_data);
+ OperatorConsole.printf("Warn[Libopenjpeg(J2k)]: %s\n", msg);
+}
+
+/* Debug callback expecting no client object. */
+void info_callback(const char *msg, void *client_data)
+{
+ UNUSED_ARGUMENT(client_data);
+ if(DebugLevel > 1)SystemDebug.printf("Info[Libopenjpeg(J2k)]: %s\n", msg);
+}
+
+/* This routine will take all of the listed color spaces in 08_03 of the standard
+ * in little endian, uncompressed format and compress it to jpeg2000 in whatever
+ * format it came in. I don't know if dicom viewers can support this. It uses the
+ * openjpeg library from Communications and Remote Sensing Lab (TELE) in the
+ * Universitait Catholique de Louvain (UCL), and CNES with the support of the CS company,
+ * version 1.3. You can get it here:
+ * http://code.google.com/p/openjpeg/downloads/list
+ * The library was built with USE_JPWL defined.
+ * OpenJPEG can compress anything, with any size for each plane, but the standard only
+ * allows YBR_RCT lossless and YBR_ICT lossy. So if a YBR come in, it is lossy, and
+ * RGB is lossless. If this is a problem I can add a forced change in colorspace.
+ * If I have made some mistakes (most likely), you can contact me bruce.barton
+ * (the mail symbol goes here) bitsltd.net. Let me know where I can find a sample of
+ * the image that didn't work. */
+BOOL CompressJPEG2Ko(DICOMDataObject* pDDO, int j2kQuality)
+{
+ Array < DICOMDataObject *> *ArrayPtr, *ArrayImage;
+ DICOMDataObject *DDO;
+ VR *pVR, *vrImage, *vrs;
+ int colorTypeIn, codestream_length;
+ UINT8 bitwa, prec, sgnd;
+ INT32 rowCnt, byteCnt, imgSize;
+ char *colorASC;
+ register char *brcrBuffer, *buffer_ptr, *bufferPtr, *bufferg_ptr, *bufferb_ptr;
+ register unsigned int mask;
+ register int *colorBuffer_ptr[3];
+ int *colorBuffer[3], tempInt;
+ unsigned int currFrame, frames, i, t, inputArrayCnt, byteWidthIn, byteWidth;
+ BOOL planes;
+// OpenJPEG Stuff
+ opj_cparameters_t parameters; // compression parameters.
+ opj_event_mgr_t event_mgr; // event manager.
+ opj_cio_t* cio;
+ opj_cinfo_t* cinfo;
+ opj_image_t *image = NULL;
+ opj_image_comp_t *comp;
+ const char comment[] = "Created by OpenJPEG with JPWL version ";
+ const size_t clen = strlen(comment);
+ const char *version = opj_version();
+
+// If debug > 0, get start time and set the level.
+ t=0;
+ if (DebugLevel > 0) t = (unsigned int)time(NULL);
+ if (DebugLevel > 1) SystemDebug.printf("openJPEG compress started.\n");
+// Uninitialized warnings.
+ ArrayImage = NULL;
+ i = 0;
+// Check and set the quality for lossy.
+ if(j2kQuality < MIN_QUALITY)// Set to 0 to use dicom.ini value.
+ {
+ j2kQuality = gJpegQuality;//Use the default or dicom.ini value.
+ }
+ if(j2kQuality > 100) j2kQuality = 100;
+// Create an image
+ if(!(image = (opj_image_t*)calloc(1, sizeof(opj_image_t))))
+ {
+ OperatorConsole.printf("***[CompressJPEG2K]: Could not allocate an image structure.\n");
+ return (FALSE);
+ }
+// Set image offset
+ image->x0 = 0;
+ image->y0 = 0;
+// How many colors
+ if(!(image->numcomps = pDDO->GetBYTE(0x0028, 0x0002))) image->numcomps = 1;// Gray default.
+// Decide if MCT should be used.
+ parameters.tcp_mct = image->numcomps == 3 ? 1 : 0;
+// Are there frames?
+ if(!(frames = pDDO->Getatoi(0x0028, 0x0008))) frames = 1;
+ currFrame = 0;
+// Get the Rows VR and check size
+ if(!(image->y1 = pDDO->GetUINT(0x0028, 0x0010)))
+ {
+ free(image);
+ SystemDebug.printf("***[CompressJPEG2K]: Failed to get image height.\n");
+ return(FALSE);
+ }
+ if(!(image->x1 = pDDO->GetUINT(0x0028, 0x0011)))
+ {
+ free(image);
+ OperatorConsole.printf("***[CompressJPEG2K]: Failed to get image width.\n");
+ return(FALSE);
+ }
+ imgSize = image->x1 * image->y1;
+
+ if(!(bitwa = pDDO->GetBYTE(0x0028, 0x0100)))bitwa = 8; // 8 bit default.
+ if(!(prec = pDDO->GetBYTE(0x0028, 0x0101)))prec = bitwa; //the default.
+ if(prec > bitwa)bitwa = prec; // the bigger one.
+ byteWidthIn = 1;
+ byteWidth = 1;
+ if(bitwa > 8)byteWidthIn = 2;
+ if(prec > 8)byteWidth = 2;
+ if(bitwa != 8 && bitwa != 12 && bitwa != 16)
+ {
+ free(image);
+ OperatorConsole.printf("***[CompressJPEG2K]: Unsuported allocated bit width: %d.\n", bitwa);
+ return(FALSE);
+ }
+// Checked if the data is signed,
+ if(!(sgnd = pDDO->GetBYTE(0x0028, 0x0103)))sgnd = 0;
+// Planar configuration default.
+ planes = FALSE;
+//Sort colors.
+ colorTypeIn = image->color_space = CLRSPC_GRAY;// Set the default.
+ colorASC = NULL;
+ if(image->numcomps == 3)
+ {
+ pVR = pDDO->GetVR(0x0028, 0x0004); // Get the color profile
+ if(pVR && pVR->Length > 2)colorASC = (char *)pVR->Data;
+// Look for the color type
+ if(colorASC == NULL || strncmp(colorASC, "RGB",3)==0)// RGB
+ {// Only RGB can be in planes or R,G,B format, check.
+ if(pDDO->GetBYTE(0x0028, 0x0006)) planes = TRUE; // Check planes.
+/* pVR = pDDO->GetVR(0x0028, 0x0006); // Get the plane's VR.
+ if(pVR && pVR->Length && (*(char *)(pVR->Data) == 1)) planes = TRUE;*/
+ colorTypeIn = image->color_space = CLRSPC_SRGB;
+ }
+ else if ( pVR->Length > 6 && strncmp(colorASC, "YBR_",4) == 0 )
+ {
+ image->color_space = CLRSPC_SYCC;
+ if ((strncmp(colorASC+4, "ICT",3)==0) || (strncmp(colorASC+4, "RCT",3)==0))
+ {//Some decompressor forgot to change it.
+ OperatorConsole.printf
+ ("Warn[CompressJPEG2K]: Uncompressed colorspace can not be YBR_ICT or YBR_RCT. Trying RGB\n");
+ colorTypeIn = image->color_space = CLRSPC_SRGB;
+ }
+ else if (pVR->Length > 7 && strncmp(colorASC+4, "FULL",4)==0)// YBR_FULL(_422)
+ {
+ if (pVR->Length > 11 && strncmp(colorASC+8, "_422",4)==0)// YBR_FULL_422
+ {
+ colorTypeIn = CLRSPC_FAM_YCBCR_F422;
+ }
+ else// YBR_FULL
+ {//Change color in to use planes, the compressor knows what it is.
+ colorTypeIn = CLRSPC_SRGB;
+ planes = TRUE;
+ }
+ }
+ else if (pVR->Length > 14 && strncmp(&colorASC[4], "PARTIAL_42",10)==0)// YBR_PARTIAL_42x
+ {
+ if(colorASC[14] == '2')colorTypeIn = CLRSPC_FAM_YCBCR_422;
+ else colorTypeIn = CLRSPC_FAM_YCBCR_420;
+ }
+ }// End of YBR_
+// Add more colors here.
+ else
+ {
+ if((colorASC = pDDO->GetCString(0x0028, 0x0004)))
+ {
+ OperatorConsole.printf(
+ "***[CompressJPEGL]: Unknown or unsuported color space %s.\n",colorASC);
+ free(colorASC);
+ }
+ else OperatorConsole.printf(
+ "***[CompressJPEGL]: Unknown or unsuported color space record.\n");
+ free(image);
+ return (FALSE);
+ }//End of while color profile
+ }//image->numcomps == 3
+ else if(image->numcomps != 1 )// Must be gray or error.
+ {
+ OperatorConsole.printf("***[CompressJPEG2K]: Unsupported number of components %d.\n",
+ image->numcomps);
+ free(image);
+ return (FALSE);
+ }
+// Get the data.
+ inputArrayCnt = 0;
+ pVR = pDDO->GetVR(0x7fe0, 0x0010); // Get the Image VR.
+ vrImage = pVR;//Should be done here.
+ if(pVR && pVR->Length)
+ {
+ if(pVR->SQObjectArray)
+ {// Should not be here for uncompressed.
+ ArrayImage = (Array<DICOMDataObject *> *) pVR->SQObjectArray;
+ while (inputArrayCnt < ArrayImage->GetSize())
+ {
+ DDO = ArrayImage->Get(inputArrayCnt++);//Get the array.
+ vrImage = DDO->GetVR(0xfffe, 0xe000);//Get the data
+ if(vrImage && vrImage->Length >= (unsigned int)(imgSize *image->numcomps * byteWidthIn)) break;
+ }
+ if(inputArrayCnt == ArrayImage->GetSize())
+ {
+ free(image);
+ OperatorConsole.printf("***[CompressJPEG2K]: Could not find the image data.\n");
+ return (FALSE);
+ }
+ }
+ }
+// Check for a least one frame.
+ if(!vrImage || vrImage->Length < (unsigned int)(imgSize *image->numcomps * byteWidthIn))
+ {
+ free(image);
+ OperatorConsole.printf("***[CompressJPEG2K]: Could not find the image data.\n");
+ return (FALSE);
+ }
+//Create comment for codestream.
+ if(!(parameters.cp_comment = (char*)malloc(clen+strlen(version)+1)))
+ {
+ free(image);
+ OperatorConsole.printf("***[CompressJPEG2K]: Could allocate the coment buffer.\n");
+ return (FALSE);
+ }
+ memcpy(parameters.cp_comment, comment, clen);
+ memcpy(¶meters.cp_comment[clen], version, strlen(version));
+ parameters.cp_comment[+strlen(version)] = 0;
+// Buffers are always needed for ints.
+ for (tempInt = 0; tempInt < image->numcomps; tempInt++)
+ {
+ if(!(colorBuffer[tempInt] = (int *)malloc(imgSize * sizeof(int))))
+ {
+ free(image);
+ free(parameters.cp_comment);
+ parameters.cp_comment = NULL;
+ OperatorConsole.printf(
+ "***[CompressJPEG2K]: Could not allocate a %d int image buffer #%d.\n",
+ imgSize, tempInt);
+ while(i > 0) free(colorBuffer[--tempInt]);
+ return (FALSE);
+ }
+ colorBuffer_ptr[tempInt] = (int *)colorBuffer[tempInt];
+ }
+ buffer_ptr = (char *)vrImage->Data;
+//Almost never used (planes)
+ bufferg_ptr = buffer_ptr + imgSize;
+ bufferb_ptr = bufferg_ptr + imgSize;
+// Now for some more openJPEG.
+// Created from image_to_j2k.c and convert.c.
+// configure the event callbacks.
+ memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
+ event_mgr.error_handler = error_callback;
+ event_mgr.warning_handler = warning_callback;
+ event_mgr.info_handler = info_callback;
+// set encoding parameters values.
+ opj_set_default_encoder_parameters(¶meters);
+ if(j2kQuality < 100)parameters.tcp_rates[0] = 100/j2kQuality;
+ else parameters.tcp_rates[0] = 0;// MOD antonin : losslessbug
+ parameters.tcp_numlayers++;
+ parameters.cp_disto_alloc = 1;
+// Lossy (ICT) or lossless (RCT)?
+ if((j2kQuality < 100) || (image->color_space == CLRSPC_SYCC)) parameters.irreversible = 1;//ICT
+// allocate memory for the per-component information.
+ if(!(image->comps = (opj_image_comp_t*)calloc(image->numcomps,sizeof(opj_image_comp_t))))
+ {
+ for(tempInt = 0; tempInt < image->numcomps; tempInt++)
+ {
+ if(colorBuffer[tempInt])
+ {
+ free(colorBuffer[tempInt]);
+ colorBuffer[tempInt] = NULL;
+ }
+ }
+ free(image);
+ free(parameters.cp_comment);
+ parameters.cp_comment = NULL;
+ OperatorConsole.printf("***[CompressJPEG2K]: Could not create empty components.\n");
+ return FALSE;
+ }
+// Create the individual image components.
+ for(tempInt = 0; tempInt < image->numcomps; tempInt++)
+ {
+ comp = &image->comps[tempInt];
+ comp->dx = parameters.subsampling_dx;
+ comp->dy = parameters.subsampling_dy;
+ comp->w = image->x1;
+ comp->h = image->y1;
+ comp->x0 = 0;
+ comp->y0 = 0;
+ comp->prec = prec;
+ comp->bpp = prec;
+ comp->sgnd = sgnd;
+// From now, forward, opj_image_destroy(image) will free the buffers.
+ comp->data = (int*)colorBuffer[tempInt];
+ }
+ // Print out some more info for debug.
+ if (DebugLevel > 2)
+ {
+ if(parameters.irreversible == 0) SystemDebug.printf("JPEG2K Lossless\n");
+ else SystemDebug.printf("JPEG2K Lossy Quality = %d\n", j2kQuality);
+ SystemDebug.printf(", H = %d, W = %d, Bits = %d in %d, Frames = %d\n",
+ image->x1, image->y1, prec, bitwa, frames);
+ if((colorASC = pDDO->GetCString(0x0028, 0x0004)))
+ {
+ SystemDebug.printf("color = %s\n", colorASC);
+ free(colorASC);
+ }
+ else SystemDebug.printf("Unknown color space record.\n");
+ }
+// Create the encapsulation array.
+ ArrayPtr = new Array < DICOMDataObject * >;
+// The first blank object.
+ DDO = new DICOMDataObject;
+ vrs = new VR(0xfffe, 0xe000, 0, (void *)NULL, FALSE);
+ DDO->Push(vrs);
+ ArrayPtr->Add(DDO);
+// Now to fill the buffers.
+ mask = ((1 << prec) - 1);
+// Frames loop.
+ while(TRUE)
+ {
+// Get a J2K compressor handle.
+ cinfo = opj_create_compress(CODEC_J2K);
+//Catch events using our callbacks and give a local context.
+ opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
+// Setup the encoder parameters using the current image and user parameters.
+ opj_setup_encoder(cinfo, ¶meters, image);
+// Open a byte stream for writing.
+ if(!(cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0)))
+ {
+ OperatorConsole.printf("***[CompressJPEG2K]: Failed to allocate output stream memory.\n");
+ opj_destroy_compress(cinfo);
+ opj_image_destroy(image);
+ free(parameters.cp_comment);
+ parameters.cp_comment = NULL;
+ return ( FALSE );
+ }
+ switch(colorTypeIn)
+ {
+ case CLRSPC_GRAY://12 or 12,16 bits here
+ if(bitwa == 8) // 8 Bits, char to int.
+ {
+ for(byteCnt = 0; byteCnt < imgSize; byteCnt++)
+ {
+ *colorBuffer_ptr[0]++ = ((int)*buffer_ptr & mask);
+ buffer_ptr++;
+ }
+ break;
+ }
+ if(bitwa == 16)
+ {
+ if(prec > 8)//Byte swap
+ {
+ for(byteCnt = 0; byteCnt < imgSize; byteCnt++)
+ {
+ *colorBuffer_ptr[0] = ((int)*buffer_ptr & 0xFF);
+ buffer_ptr++;
+ *colorBuffer_ptr[0]++ |= (((int)*buffer_ptr & 0xFF) << 8) & mask;
+ buffer_ptr++;
+ }
+ break;
+ }
+ for(byteCnt = 0; byteCnt < imgSize; byteCnt++)// 8 in 16.
+ {
+ *colorBuffer_ptr[0] = ((int)*buffer_ptr & mask);
+ buffer_ptr++;
+ buffer_ptr++;
+ }
+ break;
+ }
+ for(byteCnt = 0; byteCnt < imgSize; byteCnt++)// 12 bits allocated
+ {
+ *colorBuffer_ptr[0] = (((int)*buffer_ptr & 0xFF) << 4) & mask;//4-11
+ buffer_ptr++;
+ *colorBuffer_ptr[0]++ |= (((int)*buffer_ptr & 0x0F) << 4);// 0-3
+ byteCnt++;
+ if(byteCnt >= imgSize)break;
+ *colorBuffer_ptr[0] = (((int)*buffer_ptr & 0x0F) << 8) & mask;//8-11
+ buffer_ptr++;
+ *colorBuffer_ptr[0]++ = (int)*buffer_ptr & 0xFF;//0-7
+ buffer_ptr++;
+ }
+ break;
+ case CLRSPC_SRGB:// or YBR_FULL
+ if(planes)
+ {
+ for(byteCnt = 0; byteCnt < imgSize; byteCnt++)
+ {
+ *(colorBuffer_ptr[0])++ = (int)*buffer_ptr & mask;
+ buffer_ptr++;
+ *(colorBuffer_ptr[1])++ = (int)*bufferg_ptr & mask;
+ bufferg_ptr++;
+ *(colorBuffer_ptr[2])++ = (int)*bufferb_ptr & mask;
+ bufferb_ptr++;
+ }
+ break;
+ }
+ for(byteCnt = 0; byteCnt < imgSize; byteCnt++)
+ {
+ *(colorBuffer_ptr[0])++ = (int)*buffer_ptr & mask;
+ buffer_ptr++;
+ *(colorBuffer_ptr[1])++ = (int)*buffer_ptr & mask;
+ buffer_ptr++;
+ *(colorBuffer_ptr[2])++ = (int)*buffer_ptr & mask;
+ buffer_ptr++;
+ }
+ break;
+ case CLRSPC_FAM_YCBCR_F422://Y1Y2CbCr
+ for(byteCnt = 0; byteCnt < imgSize; byteCnt++)
+ {
+ byteCnt++;// 2 Ys per pass.
+ *colorBuffer_ptr[0]++ = (int)*buffer_ptr & mask;
+ buffer_ptr++;
+ *colorBuffer_ptr[0]++ = (int)*buffer_ptr & mask;
+ buffer_ptr++;
+ *colorBuffer_ptr[1]++ = (int)*buffer_ptr & mask;
+ *colorBuffer_ptr[1]++ = (int)*buffer_ptr & mask;
+ buffer_ptr++;
+ *colorBuffer_ptr[2]++ = (int)*buffer_ptr & mask;
+ *colorBuffer_ptr[2]++ = (int)*buffer_ptr & mask;
+ buffer_ptr++;
+ }
+ break;
+ case CLRSPC_FAM_YCBCR_422://Y1Y2CbCr
+ for(byteCnt = 0; byteCnt < imgSize; byteCnt++)
+ {
+ byteCnt++;// 2 Ys per pass.
+ /* For Y the ratio is 256 / 220 (1.1636) and for color 256 / 225 (1.1378).
+ * Note: All values are multiplied by 1024 or 1 << 7.
+ * Yo = 1.1636(Yi - 16) == Yo = 1.1636Yi - 18.204 ==
+ * Yo = [149Yi - 2330]/128 */
+ tempInt = (((int)*buffer_ptr) * 149) - 2330;//Y1
+ buffer_ptr++;
+ if(tempInt & 0x10000)*colorBuffer_ptr[0]++ = 0;// Neg not allowed here.
+ else if(tempInt & 0x8000)*colorBuffer_ptr[0]++ = 0xFF;// Over flow.
+ else *colorBuffer_ptr[0]++ = ((tempInt >> 7) & 0xFF);
+ tempInt = (((int)*buffer_ptr) * 149) - 2330;//Y2
+ buffer_ptr++;
+ if(tempInt & 0x10000)*colorBuffer_ptr[0]++ = 0;// Neg not allowed here.
+ else if(tempInt & 0x8000)*colorBuffer_ptr[0]++ = 0xFF;// Over flow.
+ else *colorBuffer_ptr[0]++ = ((tempInt >> 7) & 0xFF);
+ /* Cxo = 1.1378(Cxi - 16) == Cxo = 1.1378Cxi - 18.205 ==
+ * Cxo = [73Cxi - 1152]/64 */
+ tempInt = (((int)*buffer_ptr) * 73) - 1152;//Cb
+ buffer_ptr++;
+ if(tempInt & 0x8000)
+ {
+ *colorBuffer_ptr[1]++ = 0;//Negitive
+ *colorBuffer_ptr[1]++ = 0;//Negitive
+ }
+ else if(tempInt & 0x4000)
+ {
+ *colorBuffer_ptr[1]++ = 0xFF;//Over
+ *colorBuffer_ptr[1]++ = 0xFF;//Over
+ }
+ else
+ {
+ *colorBuffer_ptr[1]++ = ((tempInt >> 6) & 0xFF);
+ *colorBuffer_ptr[1]++ = ((tempInt >> 6) & 0xFF);
+ }
+ tempInt = (((int)*buffer_ptr) * 73) - 1152;//Cb
+ buffer_ptr++;
+ if(tempInt & 0x8000)
+ {
+ *colorBuffer_ptr[2]++ = 0;//Negitive
+ *colorBuffer_ptr[2]++ = 0;//Negitive
+ }
+ else if(tempInt & 0x4000)
+ {
+ *colorBuffer_ptr[2]++ = 0xFF;//Over
+ *colorBuffer_ptr[2]++ = 0xFF;//Over
+ }
+ else
+ {
+ *colorBuffer_ptr[2]++ = ((tempInt >> 6) & 0xFF);
+ *colorBuffer_ptr[2]++ = ((tempInt >> 6) & 0xFF);
+ *colorBuffer_ptr[2]++;
+ }
+ }
+ break;
+ /* What a strange standard. See page 323 of 08_03pu.pdf. */
+ case CLRSPC_FAM_YCBCR_420://Y1CrCbY2Y3CrCbY4-Y1Y2Y3Y4?
+ brcrBuffer = (char *)malloc(image->x1);
+ for(rowCnt = 0; rowCnt < image->y1; rowCnt++)// 8 bit only.
+ {
+ rowCnt++;
+ bufferPtr = brcrBuffer;
+ for(byteCnt = 0; byteCnt < image->x1; byteCnt++)
+ {
+ byteCnt++;// 2 Ys per horizantal pass.
+ tempInt = (((int)*buffer_ptr) * 149) - 2330;//Y1, Y3, ...
+ buffer_ptr++;
+ if(tempInt & 0x10000)*colorBuffer_ptr[0]++ = 0;// Neg not allowed here.
+ else if(tempInt & 0x8000)*colorBuffer_ptr[0]++ = 0xFF;// Over flow.
+ else *colorBuffer_ptr[0]++ = ((tempInt >> 7) & 0xFF);
+ tempInt = (((int)*buffer_ptr) * 73) - 1152;//Cb
+ buffer_ptr++;
+ if(tempInt & 0x8000)
+ {
+ *bufferPtr++ = 0;//Next time negitive = 0
+ *colorBuffer_ptr[1]++ = 0;//Negitive
+ *colorBuffer_ptr[1]++ = 0;//Negitive
+ }
+ else if(tempInt & 0x4000)
+ {
+ *bufferPtr++ = 0xFF;//Next time over = 255
+ *colorBuffer_ptr[1]++ = 0xFF;//Over
+ *colorBuffer_ptr[1]++ = 0xFF;//Over
+ }
+ else
+ {
+ *bufferPtr = (char)((tempInt >> 6) & 0xFF);
+ *colorBuffer_ptr[1]++ = (int)*bufferPtr & 0xFF;
+ *colorBuffer_ptr[1]++ = (int)*bufferPtr & 0xFF;
+ bufferPtr++;
+ }
+ tempInt = (((int)*buffer_ptr) * 73) - 1152;//Cb
+ buffer_ptr++;
+ if(tempInt & 0x8000)
+ {
+ *bufferPtr++ = 0;//Next time negitive = 0
+ *colorBuffer_ptr[2]++ = 0;//Negitive
+ *colorBuffer_ptr[2]++ = 0;//Negitive
+ }
+ else if(tempInt & 0x4000)
+ {
+ *bufferPtr++ = 0xFF;//Next time over = 255
+ *colorBuffer_ptr[2]++ = 0xFF;//Over
+ *colorBuffer_ptr[2]++ = 0xFF;//Over
+ }
+ else
+ {
+ *bufferPtr = (char)((tempInt >> 6) & 0xFF);
+ *colorBuffer_ptr[2]++ = (int)*bufferPtr & 0xFF;
+ *colorBuffer_ptr[2]++ = (int)*bufferPtr & 0xFF;
+ bufferPtr++;
+ }
+ }
+ bufferPtr = brcrBuffer;
+ for(byteCnt = 0; byteCnt < image->x1; byteCnt++)
+ {
+ byteCnt++;// 2 Ys per horizantal pass.
+ tempInt = (((int)*buffer_ptr) * 149) - 2330;//Y1, Y3, ...
+ buffer_ptr++;
+ if(tempInt & 0x10000)*colorBuffer_ptr[0]++ = 0;// Neg not allowed here.
+ else if(tempInt & 0x8000)*colorBuffer_ptr[0]++ = 0xFF;// Over flow.
+ else *colorBuffer_ptr[0]++ = ((tempInt >> 7) & 0xFF);
+ tempInt = (((int)*buffer_ptr) * 149) - 2330;//Y1, Y3, ...
+ buffer_ptr++;
+ if(tempInt & 0x10000)*colorBuffer_ptr[0]++ = 0;// Neg not allowed here.
+ else if(tempInt & 0x8000)*colorBuffer_ptr[0]++ = 0xFF;// Over flow.
+ else *colorBuffer_ptr[0]++ = (char)((tempInt >> 7) & 0xFF);
+ *colorBuffer_ptr[1]++ = (int)*bufferPtr & 0xFF;
+ *colorBuffer_ptr[1]++ = (int)*bufferPtr & 0xFF;
+ bufferPtr++;
+ *colorBuffer_ptr[2]++ = (int)*bufferPtr & 0xFF;
+ *colorBuffer_ptr[2]++ = (int)*bufferPtr & 0xFF;
+ bufferPtr++;
+ }
+ }
+ free(brcrBuffer);
+ break;
+ }// End of the colorType switch.
+// encode the image.
+ if(!(opj_encode(cinfo, cio, image, NULL)))
+ {
+ OperatorConsole.printf("***[CompressJPEG2K]: OpenJpeg could not encode the image.\n");
+ while(ArrayPtr->GetSize())
+ {
+ delete ArrayPtr->Get(0);
+ ArrayPtr->RemoveAt(0);
+ }
+ delete ArrayPtr;
+ opj_destroy_compress(cinfo);
+ opj_image_destroy(image);
+ opj_cio_close(cio);
+ free(parameters.cp_comment);
+ parameters.cp_comment = NULL;
+ return FALSE;
+ }
+ opj_destroy_compress(cinfo);//Done with cinfo.
+ codestream_length = cio_tell(cio);
+// Jpeg2k is encapsulated, make a new vr to encapsulate.
+ vrs = new VR(0xfffe, 0xe000, (UINT32)codestream_length, TRUE);
+ if(!vrs)
+ {
+ OperatorConsole.printf("***[CompressJPEG2K]: Failed to allocate memory.\n");
+ while(ArrayPtr->GetSize())
+ {
+ delete ArrayPtr->Get(0);
+ ArrayPtr->RemoveAt(0);
+ }
+ delete ArrayPtr;
+ opj_image_destroy(image);
+ opj_cio_close(cio);
+ free(parameters.cp_comment);
+ parameters.cp_comment = NULL;
+ return ( FALSE );
+ }
+//If odd data length, zero the added byte.
+ if ( codestream_length & 1 ) ((BYTE *)vrs->Data)[codestream_length] = 0;
+// Copy the Image data.
+ brcrBuffer = (char *)vrs->Data;
+ bufferPtr = (char *)cio->buffer;
+ for(i = codestream_length; i > 0; --i) *brcrBuffer++ = *bufferPtr++;
+// Done with the code stream and cinfo.
+ opj_cio_close(cio);
+// Save the image object. */
+ DDO = new DICOMDataObject;
+ DDO->Push(vrs);
+ ArrayPtr->Add(DDO);
+//Out of data?
+ if(++currFrame >= frames)break;//Done with all of the frames.
+// Deal with silly input arrays
+ if(inputArrayCnt > 0 && (unsigned int)(imgSize *image->numcomps * byteWidthIn) < vrImage->Length)
+ {// Look for the next array.
+ while (inputArrayCnt < ArrayImage->GetSize())
+ {
+ DDO = ArrayImage->Get(inputArrayCnt++);//Get the array.
+ vrImage = DDO->GetVR(0xfffe, 0xe000);//Get the data
+// If found next one, break inner loop.
+ if(vrImage && vrImage->Length >= (unsigned int)(imgSize *image->numcomps * byteWidthIn)) break;
+ }
+// Not enough data for at least 1 frame, end frames loop.
+ if(!vrImage || vrImage->Length < (unsigned int)(imgSize *image->numcomps * byteWidthIn)) break;
+ buffer_ptr = (char *)vrImage->Data; // Point at the new buffer.
+ }
+// No silly arrays ( or a least one big file in the array).
+ else
+ {
+ if((unsigned int)(buffer_ptr - (char *)vrImage->Data + imgSize)
+ > vrImage->Length)break; //Out of data?
+ }
+// Reset the buffers.
+ for( tempInt = 0; tempInt < image->numcomps; tempInt++)
+ colorBuffer_ptr[tempInt] = (int *)colorBuffer[tempInt];
+ if(planes)//Jump the next 2 planes.
+ {
+ buffer_ptr = bufferb_ptr;
+ bufferg_ptr = buffer_ptr + imgSize;
+ bufferb_ptr = bufferg_ptr + imgSize;
+ }
+ }//Back for the next frame, end of while(TRUE)
+//Done with the comments.
+ free(parameters.cp_comment);
+ parameters.cp_comment = NULL;
+// Should we kill it and keep the uncompressed data?
+ if(currFrame < frames) OperatorConsole.printf(
+ "Warn[CompressJPEG2K]: Only %d of %d frames saved.\n",currFrame, frames);
+// Finish encapsulating.
+ DDO = new DICOMDataObject;
+ vrs = new VR(0xfffe, 0xe0dd, 0, (void *)NULL, FALSE);
+ DDO->Push(vrs);
+ ArrayPtr->Add(DDO);
+// Attach the array to the vr.
+ pVR->Reset(); // Deletes the pixel data
+ pVR->SQObjectArray = ArrayPtr;
+ pVR->TypeCode ='OW';
+ // mvh: should not be needed - pDDO->Length = 0xFFFFFFFF;
+// Change the dicom parameters.
+ if(image->numcomps == 3)
+ {
+// Reset the plane's VR, if there.
+ pVR = pDDO->GetVR(0x0028, 0x0006);
+ if(pVR && pVR->Length && *(char *)(pVR->Data) == 1) *(char *)(pVR->Data = 0);
+// Set the color profile
+ if((j2kQuality < 100) || (image->color_space == CLRSPC_SYCC))
+ pDDO->ChangeVR( 0x0028, 0x0004, "YBR_ICT\0", 'CS');
+ else pDDO->ChangeVR( 0x0028, 0x0004, "YBR_RCT\0", 'CS');
+/* pVR = pDDO->GetVR(0x0028, 0x0004); if(pVR)
+ {
+ pVR->Length = 8;
+ if(pVR->ReAlloc(pVR->Length))
+ {
+ if((j2kQuality < 100) || (image->color_space == CLRSPC_SYCC))
+ memcpy(pVR->Data, "YBR_ICT\0",8);
+ else memcpy(pVR->Data, "YBR_RCT\0",8);
+ }
+ }*/
+ }
+// Fix the bits allocated.
+ // 20120624: do not change highbit and bitsstored
+ //if(byteWidth == 1)pDDO->ChangeVR( 0x0028, 0x0100, (UINT8)8, 'US');
+ //else pDDO->ChangeVR( 0x0028, 0x0100, (UINT8)16, 'US');
+
+//Change the transfer syntax to JPEG2K!
+ if((j2kQuality < 100) || (image->color_space == CLRSPC_SYCC))
+ pDDO->ChangeVR( 0x0002, 0x0010, "1.2.840.10008.1.2.4.91\0", 'IU');
+ else pDDO->ChangeVR( 0x0002, 0x0010, "1.2.840.10008.1.2.4.90\0", 'IU');
+// At last, done with the image.
+ opj_image_destroy(image);
+// If debug > 0, print when finished
+ if (DebugLevel > 0)
+ SystemDebug.printf("OpenJPEG compress time %u seconds.\n", (unsigned int)time(NULL) - t);
+ return (TRUE);
+}
+
+/* This routine will take in a jpeg2000 image and convert it to little endian, uncompressed,
+ * RGB or grayscale. It uses the openjpeg library from Communications and Remote Sensing Lab (TELE)
+ * in the Universitait Catholique de Louvain (UCL), and CNES with the support of the CS company.
+ * You can get it here:
+ * http://code.google.com/p/openjpeg/downloads/list
+ * The library was built with USE_JPWL defined.
+ * JPEG200 can compress almost anything, with any size for each plane. So that means any
+ * of the color spaces and formats can be in it. The dicom standard removes the header
+ * and color box infromation and sends just the data stream. The standard states only
+ * MONO1,2 PALETTE_COLOR YBR_RCT and YBR_ICT can be use. For the color space and
+ * image format, I have to trust libopenjpeg.
+ * If I have made some mistakes (most likely) you can contact me bruce.barton
+ * (the mail symbol goes here) bitsltd.net. Let me know where I can find a sample of
+ * the image that didn't work. */
+BOOL DecompressJPEG2Ko(DICOMDataObject* pDDO)
+{
+ Array < DICOMDataObject *> *ArrayPtr;
+ DICOMDataObject *DDO;
+ VR *pVR, *vrImage;
+ register unsigned char *outc_ptr;
+ register UINT16 *out16_ptr;
+ unsigned char *streamData;
+#ifdef NOVARAD_FIX
+ void *fixPtr;
+ unsigned char *fix1Ptr, *fix2Ptr;
+#endif
+ unsigned char *outData;
+ UINT16 frames;
+ unsigned int i, t;
+ register int *jpc_out[3], mask;
+ int bytes_jpc, prec_jpc;
+ unsigned int currFrame, currSQObject;
+ UINT8 numcmpts;
+ // UINT16 bitwa, bitws,;
+ UINT32 stream_len, instream_len, total_len;
+ // bool bResult;
+#if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian like Apple power pc
+ register int masked;
+#endif //Big Endian
+// openJPEG stuff.
+ opj_dparameters_t parameters; // decompression parameters.
+ opj_image_t *decompImage = NULL;
+ opj_event_mgr_t event_mgr; // event manager.
+ opj_dinfo_t *dinfo = NULL; // handle to a decompressor.
+ opj_cio_t *cio = NULL;
+
+// If debug > 0, get start time.
+ t = 0;
+ if (DebugLevel > 0)t = (unsigned int)time(NULL);
+ if (DebugLevel > 1) SystemDebug.printf("openJPEG decompress started.\n");
+// Init some variables
+ outData = NULL;
+// Uninitialized warnings.
+ outc_ptr = NULL;
+ out16_ptr = NULL;
+ mask = 0;
+ bytes_jpc = 1;
+ prec_jpc = 8;
+ total_len = 0;
+ stream_len = 0;
+// Get the number of samples per pixel VR.
+ if(!(numcmpts = pDDO->GetBYTE(0x0028, 0x0002))) numcmpts = 1;// Gray default.
+// Are there frames?
+ if(!(frames = pDDO->Getatoi(0x0028, 0x0008))) frames = 1;
+ currFrame = 0;
+// Get the encapsulated data.
+ pVR = pDDO->GetVR(0x7fe0, 0x0010); // Get the Image VR.
+ if(!pVR)
+ {
+ OperatorConsole.printf("***[DecompressJPEG2K]: No image VR\n");
+ return (FALSE);
+ }
+ currSQObject = 0;// Init now for no warning later.
+ if(pVR->SQObjectArray)
+ {
+ ArrayPtr = (Array<DICOMDataObject *> *) pVR->SQObjectArray;
+ while(TRUE)
+ {
+ if( currSQObject >= ArrayPtr->GetSize())
+ {
+ OperatorConsole.printf("***[DecompressJPEG2K]: No j2k data found\n");
+ return (FALSE);
+ }
+ DDO = ArrayPtr->Get(currSQObject );//Get the array.
+ vrImage = DDO->GetVR(0xfffe, 0xe000);//Get the data
+ //Look for size and j2k marker or jp2 file header.
+ if(vrImage->Length)
+ {
+ streamData = (unsigned char *)vrImage->Data;
+ instream_len = vrImage->Length;
+ if( *streamData == 0xFF) break; //Jpeg stream.
+ if( *streamData == 0x00 && streamData[1] == 0x00 && streamData[2] == 0x00
+ && streamData[3] == 0x0C && streamData[4] == 0x6A && streamData[5] == 0x50)
+ { //Wow, a j2k file header, dicom is normally just the stream.
+ streamData += 6;
+ instream_len -= 6;
+ for(i = 0; i < 512; i++)// I just picked 512.
+ { // Look for stream header.
+ if(*streamData == 0xFF && streamData[1] == 0x4F)break;
+ streamData++;
+ instream_len--;
+ }
+ if( i < 512 )break;// Found the stream.
+ }
+ }
+ currSQObject++;
+ }
+ }
+ else
+ {
+ OperatorConsole.printf("***[DecompressJPEG2K]: No image in encapsulation arrray\n");
+ return (FALSE);
+ }
+// configure the event callbacks.
+ memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
+ event_mgr.error_handler = error_callback;
+ event_mgr.warning_handler = warning_callback;
+ event_mgr.info_handler = info_callback;
+// set decoding parameters to default values.
+ opj_set_default_decoder_parameters(¶meters);
+// set decoding parameter format to stream.
+ parameters.decod_format = CODEC_J2K;
+// Start the frames loop.
+ while(TRUE)
+ {
+ // Fix the stream length.
+ if(streamData[instream_len - 1] == 0) instream_len--;
+#ifdef NOVARAD_FIX
+ // Put the end of file back if not present.
+ if ((streamData[instream_len - 2] != 0xFF)
+ || (streamData[instream_len - 1] != 0xD9))
+ {
+ if(!(fixPtr = malloc(vrImage->Length + 2)))
+ {
+ OperatorConsole.printf("***[DecompressJPEG2K]: Can not create memory fix buffer.\n");
+ return (FALSE);
+ }
+ fix1Ptr = (unsigned char*)fixPtr;
+ fix2Ptr = (unsigned char*)vrImage->Data;
+ for( i = instream_len; i > 0; --i ) *fix1Ptr++ = *fix2Ptr++;
+ *fix1Ptr++ = 0xFF;
+ *fix1Ptr++ = 0xD9;
+ if(instream_len & 1 ) *fix1Ptr = 0;
+ free(vrImage->Data);
+ vrImage->Data = fixPtr;
+ vrImage->Length += 2;
+ streamData = (unsigned char*)vrImage->Data;
+ instream_len = vrImage->Length;
+ if(DebugLevel > 0)SystemDebug.printf("Warn[DecompressJPEG2K]: Novarad fix, EOC marker added.\n");
+ }
+#endif
+ // get a decoder handle.
+ dinfo = opj_create_decompress(CODEC_J2K);//Bad openjpeg, can't be reused!
+// catch events using our callbacks and give a local context.
+ opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
+// setup the decoder decoding parameters using user parameters.
+ opj_setup_decoder(dinfo, ¶meters);
+// Open the memory as a stream.
+ if(!(cio = opj_cio_open((opj_common_ptr)dinfo, streamData, instream_len)))
+ {
+ opj_destroy_decompress(dinfo);
+ OperatorConsole.printf("***[DecompressJPEG2K]: cannot open jpeg 2K data\n");
+ return (FALSE);
+ }
+// decode the stream and fill the image structure
+ decompImage = opj_decode(dinfo, cio);
+// Check the image
+ if (!decompImage)
+ {
+ OperatorConsole.printf("***[DecompressJPEG2K]: Jpeg 2K code stream decode did not create an image\n");
+ opj_destroy_decompress(dinfo);
+ opj_cio_close(cio);
+ return FALSE;
+ }
+// close the byte stream
+ opj_cio_close(cio);
+// Do this the first time only
+ if(!currFrame)
+ {//Make the buffer.
+// Check for color.
+ if(numcmpts > 1)
+ {
+ if((numcmpts != 3) || (decompImage->numcomps != 3))
+ {
+ OperatorConsole.printf(
+ "***[DecompressJPEG2K]: Should be 3 colors, DICOM: %d ,J2K: %d \n",
+ numcmpts , decompImage->numcomps);
+ opj_image_destroy(decompImage);
+ return ( FALSE );
+ }
+ }
+// Get the total uncompressed length.
+ prec_jpc =decompImage->comps[0].prec;//Need it at the end
+ bytes_jpc = ((prec_jpc -1) / 8) + 1;// Bytes or words.
+ total_len = decompImage->comps[0].w * decompImage->comps[0].h
+ * bytes_jpc * numcmpts * frames;
+ if (( total_len & 1) != 0 ) total_len++;
+ if(!(outData = (unsigned char *)malloc(total_len)))
+ {
+ OperatorConsole.printf(
+ "***[DecompressJPEG2K]: Failed to allocate %d bytes of memory.\n", total_len);
+ opj_image_destroy(decompImage);
+ return ( FALSE );
+ }
+ outData[total_len -1] = 0;// Dosen't hurt.
+ outc_ptr = outData;
+ out16_ptr = (UINT16 *)outData;
+// The same for all images
+ mask = (1 << prec_jpc) - 1;
+ stream_len = (decompImage->comps[0].w * decompImage->comps[0].h);
+ }//End of make the data buffer
+//Get the data pointer(s)
+ for ( i = 0; i < numcmpts ; i++ )
+ {
+ jpc_out[i] = decompImage->comps[i].data;
+ }
+// Image copy loops, open JPEG outputs ints.
+ if( numcmpts == 1)
+ {
+ if(bytes_jpc == 2)
+ {
+ for(i = 0; i < stream_len; i++)
+ {
+#if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian like Apple power pc
+ masked = (UINT16)(*jpc_out[0]++ & mask);
+ *outc_ptr++ = (char)(masked & 0xFF);
+ *outc_ptr++ = (char)((masked >> 8) & 0xFF);
+#else //Little Endian
+ *out16_ptr++ = (UINT16)(*jpc_out[0]++ & mask);
+#endif //Big Endian
+ }
+
+ }
+ else
+ for(i = 0; i < stream_len; i++)
+ *outc_ptr++ = (unsigned char)(*jpc_out[0]++ & mask);
+ }
+ else //RGB
+ {
+ for(i = 0; i < stream_len; i++)
+ {
+ *outc_ptr++ = (unsigned char)(*jpc_out[0]++ & mask);
+ *outc_ptr++ = (unsigned char)(*jpc_out[1]++ & mask);
+ *outc_ptr++ = (unsigned char)(*jpc_out[2]++ & mask);
+
+ }
+ }
+// Done with libopenjpeg for this loop.
+ opj_destroy_decompress(dinfo);
+ opj_image_destroy(decompImage);
+// check for the end
+ if(++currFrame >= frames)break;
+// More images to read
+ while(++currSQObject < ArrayPtr->GetSize())
+ {
+ DDO = ArrayPtr->Get(currSQObject);//Get the array.
+ vrImage = DDO->GetVR(0xfffe, 0xe000);//Get the data
+ //Look for size and j2k marker or jp2 file header.
+ if(vrImage->Length)
+ {
+ streamData = (unsigned char *)vrImage->Data;
+ instream_len = vrImage->Length;
+ if( *streamData == 0xFF) break; //Jpeg stream.
+ if( *streamData == 0x00 && streamData[1] == 0x00 && streamData[2] == 0x00
+ && streamData[3] == 0x0C && streamData[4] == 0x6A && streamData[5] == 0x50)
+ { //Wow, a j2k file header again, dicom is normally just the stream.
+ streamData += 6;
+ instream_len -= 6;
+ for(i = 0; i < 512; i++)// I just picked 512.
+ { // Look for stream header.
+ if(*streamData == 0xFF && streamData[1] == 0x4F)break;
+ streamData++;
+ instream_len--;
+ }
+ if( i < 512 )break;// Found the stream.
+ }
+ }
+ }
+ if( currSQObject >= ArrayPtr->GetSize() )break;//Should not happen!
+// Loop back to open the memory as a stream.
+ }//End of the frames loop
+// Done with libjpeg.
+// if(dinfo) opj_destroy_decompress(dinfo);
+ if(currFrame < frames)OperatorConsole.printf(
+ "Warn[DecompressJPEG2K]: Found %d of %d frames.\n",currFrame, frames);
+// Change the image vr to the bigger uncompressed and unencapsulated image.
+ pVR->Reset(); // Deletes the pixel data
+ pVR->Length = total_len;
+ pVR->Data = outData;
+ pVR->ReleaseMemory = TRUE;//Give the memory to the vr.
+// Set the image type.
+ if(bytes_jpc == 1)// 8 bits
+ {
+ pVR->TypeCode ='OB';
+ }
+ else
+ {
+ pVR->TypeCode ='OW';
+ }
+
+// The color stuff
+ if(numcmpts > 1)
+ {
+//Set Planes value if needed, do not create if not there.
+ pVR = pDDO->GetVR(0x0028, 0x0006);
+ if(pVR && pVR->Length && *(char *)pVR->Data == 1)
+ *(char *)pVR->Data = 0;
+//Change the Photometric Interpretation.
+ pDDO->ChangeVR( 0x0028, 0x0004, "RGB\0", 'CS');
+ }
+// Set the number of bits allocated.
+ // 20120624: do not change highbit and bitsstored
+ // if(bytes_jpc == 1) pDDO->ChangeVR( 0x0028, 0x0100, (UINT8)8, 'US');
+ // else pDDO->ChangeVR( 0x0028, 0x0100, (UINT8)16, 'US');
+
+// mvh 20110502: DecompressJPEG2Ko: write highbit for consistency
+ // 20120624: do not change highbit and bitsstored
+ //pDDO->ChangeVR( 0x0028, 0x0101, (UINT8)prec_jpc, 'US');// Set the number of bits stored.
+ //pDDO->ChangeVR( 0x0028, 0x0102, (UINT8)(prec_jpc-1), 'US');// Set high bit.
+
+//Change the transfer syntax to LittleEndianExplict!
+ pDDO->ChangeVR( 0x0002, 0x0010, "1.2.840.10008.1.2.1\0", 'IU');
+// If debug > 0, print decompress time.
+ if (DebugLevel > 0)
+ SystemDebug.printf("OpenJPEG decompress time %u seconds.\n", (unsigned int)time(NULL) - t);
+ return (TRUE);
+}
+#endif //End for libopenjpeg
+
diff --git a/nkiqrsop.hpp b/nkiqrsop.hpp
new file mode 100644
index 0000000..6e5ba69
--- /dev/null
+++ b/nkiqrsop.hpp
@@ -0,0 +1,231 @@
+#ifndef _NKIQRSOP_H_
+# define _NKIQRSOP_H_
+
+/*
+19990317 ljz NKI-specific code
+20001128 ljz Fix: Crashes happened when more than one 'ServerChildThread' was
+ active. m_pDCO was wrongly shared by all threads !!
+20010429 mvh Added GETADDO to allow optional read ahead withing calling program
+20010502 mvh Added extrabytes pointer to Read and RetrieveOn
+20020415 mvh ProcessDDO now returns status (to allow compression error check)
+20020613 ljz Added prototypes for DecompressNKI and CompressNKI
+20021115 mvh Added Generic retrieve classes
+20030522 ljz Added prototype of ComputeCRC
+20030701 mvh QualifyOn now also has compression parameter
+20030702 mvh added ExtendedPDU_Service
+20030704 mvh Changed ProcessDDO parameter to **DDO (for recompress)
+20050118 mvh replaced thread local storage under linux with variables in object
+20050121 mvh Changed filename to lower case
+20050211 mvh Removed need for thread local storage
+20090209 mvh Added QueryMoveScript callback
+20091231 bcb Added HAVE_LIBJPEG (version 6c!) and HAVE_JASPER for external library support (beta for now)
+ Changed char* to const char* and cast time_t as int for gcc4.2 warnings
+20100111 mvh Merged
+20100703 mvh Merged some bcb OpenJPG changes
+20100706 bcb Added support for J2K and Jasper
+20100721 mvh Merged
+20110118 mvh Derived ExtendedPDU_Service from CheckedPDU_Service
+20110118 mvh Added lua_State to ExtendedPDU_Service
+20110119 mvh Added *VariableVRs and ThreadNum to ExtendedPDU_Service
+20110122 mvh Added ExtendedPDU_Service destructor
+*/
+
+#include "lua.hpp"
+
+class ExtendedPDU_Service :
+ public CheckedPDU_Service
+ {
+ BOOL AddTransferSyntaxs(PresentationContext &); // override original function
+ char RequestedCompressionType[64];
+ char AcceptedCompressionType[64];
+ public:
+ BOOL SetRequestedCompressionType(const char *type);
+ char* GetAcceptedCompressionType(UID uid);
+ ExtendedPDU_Service (char *filename = NULL) : CheckedPDU_Service(filename)
+ { L = NULL;
+ memset(VariableVRs, 0, sizeof(VariableVRs));
+ ThreadNum = 0;
+ };
+ ~ExtendedPDU_Service ()
+ { if (L) lua_close(L);
+ if (VariableVRs[0]) delete VariableVRs[0];
+ if (VariableVRs[1]) delete VariableVRs[1];
+ if (VariableVRs[2]) delete VariableVRs[2];
+ };
+
+ // scripting state per association
+ lua_State *L;
+ VR *VariableVRs[3];
+ int ThreadNum;
+ };
+
+class StandardRetrieveNKI :
+ public CMoveRQ,
+ public CMoveRSP
+ {
+ public:
+ StandardRetrieveNKI();
+ virtual BOOL GetUID (UID &uid) { return (uGetUID(uid)); };
+ virtual BOOL uGetUID ( UID &) = 0;
+ virtual BOOL QueryMoveScript (PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO) = 0;
+ virtual BOOL SearchOn ( DICOMDataObject *,
+ Array < DICOMDataObject *> *) = 0;
+ virtual BOOL RetrieveOn ( DICOMDataObject *,
+ DICOMDataObject **,
+ StandardStorage **,
+ DICOMCommandObject *,
+ Array < DICOMDataObject *> *,
+ void *) = 0;
+ virtual BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE *, BYTE * ) = 0;
+ virtual BOOL CallBack ( DICOMCommandObject *,
+ DICOMDataObject * ) = 0;
+ BOOL Read ( ExtendedPDU_Service *, DICOMCommandObject *, void *ExtraBytes );
+ BOOL Write ( PDU_Service *, DICOMDataObject *, BYTE *);
+ };
+
+
+class PatientRootRetrieveNKI :
+ public StandardRetrieveNKI
+ {
+ public:
+ BOOL GetUID ( UID & );
+ BOOL uGetUID ( UID &uid ) { return ( GetUID(uid) ); };
+
+ inline BOOL Read ( ExtendedPDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ void *ExtraBytes )
+ { return ( StandardRetrieveNKI :: Read ( PDU, DCO, ExtraBytes ) ); };
+
+ BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ BYTE *ACRNema)
+ { return ( StandardRetrieveNKI :: Write ( PDU,
+ DDO, ACRNema )); };
+ };
+
+
+class StudyRootRetrieveNKI :
+ public StandardRetrieveNKI
+ {
+ public:
+ BOOL GetUID ( UID & );
+ BOOL uGetUID ( UID &uid ) { return ( GetUID(uid) ); };
+
+ inline BOOL Read ( ExtendedPDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ void *ExtraBytes )
+ { return ( StandardRetrieveNKI :: Read ( PDU, DCO, ExtraBytes ) ); };
+
+ BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ BYTE *ACRNema)
+ { return ( StandardRetrieveNKI :: Write ( PDU,
+ DDO, ACRNema )); };
+ };
+
+
+class PatientStudyOnlyRetrieveNKI :
+ public StandardRetrieveNKI
+ {
+ public:
+ BOOL GetUID ( UID & );
+ BOOL uGetUID ( UID &uid ) { return ( GetUID(uid) ); };
+
+ inline BOOL Read ( ExtendedPDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ void *ExtraBytes )
+ { return ( StandardRetrieveNKI :: Read ( PDU, DCO, ExtraBytes ) ); };
+
+ BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ BYTE *ACRNema)
+ { return ( StandardRetrieveNKI :: Write ( PDU,
+ DDO, ACRNema )); };
+ };
+
+
+class PatientRootRetrieveGeneric :
+ public StandardRetrieveNKI
+ {
+ public:
+ BOOL GetUID ( UID & );
+ BOOL uGetUID ( UID &uid ) { return ( GetUID(uid) ); };
+
+ inline BOOL Read ( ExtendedPDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ void *ExtraBytes )
+ { return ( StandardRetrieveNKI :: Read ( PDU, DCO, ExtraBytes ) ); };
+
+ BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ BYTE *ACRNema)
+ { return ( StandardRetrieveNKI :: Write ( PDU,
+ DDO, ACRNema )); };
+ };
+
+
+class StudyRootRetrieveGeneric :
+ public StandardRetrieveNKI
+ {
+ public:
+ BOOL GetUID ( UID & );
+ BOOL uGetUID ( UID &uid ) { return ( GetUID(uid) ); };
+
+ inline BOOL Read ( ExtendedPDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ void *ExtraBytes )
+ { return ( StandardRetrieveNKI :: Read ( PDU, DCO, ExtraBytes ) ); };
+
+ BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ BYTE *ACRNema)
+ { return ( StandardRetrieveNKI :: Write ( PDU,
+ DDO, ACRNema )); };
+ };
+
+
+class PatientStudyOnlyRetrieveGeneric :
+ public StandardRetrieveNKI
+ {
+ public:
+ BOOL GetUID ( UID & );
+ BOOL uGetUID ( UID &uid ) { return ( GetUID(uid) ); };
+
+ inline BOOL Read ( ExtendedPDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ void *ExtraBytes )
+ { return ( StandardRetrieveNKI :: Read ( PDU, DCO, ExtraBytes ) ); };
+
+ BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ BYTE *ACRNema)
+ { return ( StandardRetrieveNKI :: Write ( PDU,
+ DDO, ACRNema )); };
+ };
+
+BOOL ProcessDDO(DICOMDataObject** pDDO, DICOMCommandObject* pDCO, ExtendedPDU_Service *PDU);
+BOOL DecompressNKI(DICOMDataObject* pDDO);
+BOOL CompressNKI(DICOMDataObject* pDDO, int iCompressMode = 2);
+
+#ifdef HAVE_LIBJPEG
+BOOL CompressJPEGL(DICOMDataObject* pDDO, int comp = '1', int jpegQuality = 95 );
+BOOL DecompressJPEGL(DICOMDataObject* pDDO);
+#endif //End HAVE_LIBJEPG
+
+#ifdef HAVE_J2K // JPEG 2000 stuff
+extern int DebugLevel;
+#endif //End HAVE_J2K
+#ifdef HAVE_LIBJASPER
+BOOL CompressJPEG2K(DICOMDataObject* pDDO, int j2kQuality);
+BOOL DecompressJPEG2K(DICOMDataObject* pDDO);
+#endif //End LIBJASPER
+#ifdef HAVE_LIBOPENJPEG
+BOOL CompressJPEG2Ko(DICOMDataObject* pDDO, int j2kQuality);
+BOOL DecompressJPEG2Ko(DICOMDataObject* pDDO);
+#endif //End LIBOPENJPEG
+
+unsigned int ComputeCRC(char* pcData, int iNbChars);
+BOOL recompress(DICOMDataObject **pDDO, const char *Compression, const char *Filename, BOOL StripGroup2, ExtendedPDU_Service *PDU);
+BOOL recompressFile(char *File, char *Compression, ExtendedPDU_Service *PDU);
+
+#endif
diff --git a/npipe.cpp b/npipe.cpp
new file mode 100644
index 0000000..f3209da
--- /dev/null
+++ b/npipe.cpp
@@ -0,0 +1,351 @@
+// Named Pipe facility somewhat similar to local named pipes
+// available under Win32
+// This is implemented for Unix SysV where named pipes are available
+// the package could be implemented using BSD UNIX Domain sockets
+// if SysV named pipes were not available
+
+// 20050111 mvh Blocked out sys/conf.h; compiles with linux but gives
+// linker warning: fattach not implemented and will always fail
+// 20051217 mvh Return (unsigned) 0xFFFFFFFF instead of signed -1
+// 20070308 bcb Change things for BSD and DARWIN.
+// 20070316 bcb Some more fixes
+// 20091229 mvh Completely disabled call to fattach, ioctl, and isastream as per
+// http://www.image-systems.biz/forum/viewtopic.php?f=33&t=1666&start=0#p6879
+// 20100111 mvh Some layout
+// 20100619 bcb Fix gcc4 warnings.
+// 20100717 mvh Merged
+
+#include "npipe.hpp"
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <signal.h>
+#ifndef BSD
+//#include <stropts.h>
+#endif //BSD
+//#include <sys/conf.h>
+#include <string.h>
+#include <sys/ioctl.h>
+
+NamedPipe::NamedPipe(char *theName) :
+ itsName(NULL),
+ itsCreatedHere(FALSE),
+ itsControlReadFd(-1),
+ itsControlWriteFd(-1),
+#ifndef BSD
+ itsConnectionFd(-1)
+#else //BSD
+ itsConnectionFd(NULL)
+#endif //BSD
+{
+ int aLength = theName ? strlen(theName) : 0;
+ itsName = theName ? new char[aLength + 1] : NULL;
+ if(theName)
+ {
+ strncpy(itsName, theName, aLength + 1);
+ }
+}
+
+NamedPipe::~NamedPipe()
+{
+ Destroy();
+}
+
+void
+NamedPipe::Destroy()
+{
+ if(itsName)
+ {
+ if(itsCreatedHere)
+ {
+ (void)unlink(itsName);
+ }
+ delete [] itsName;
+ itsName = NULL;
+ if(itsControlReadFd >= 0)
+ {
+#ifndef BSD //Doesn't have a read field
+ close(itsControlReadFd);
+#endif //BSD
+ itsControlReadFd = 0;
+ }
+ if(itsControlWriteFd >= 0)
+ {
+#ifndef BSD //Doesn't have a write field
+ close(itsControlWriteFd);
+#endif //BSD
+ close(itsControlWriteFd);
+ itsControlWriteFd = 0;
+ }
+ }
+#ifndef BSD
+ if(itsConnectionFd >= 0)
+ {
+ close(itsConnectionFd);
+ itsConnectionFd = 0;
+ }
+#else //BSD uses fclose for a stream
+ if(itsConnectionFd != NULL)
+ {
+ fclose(itsConnectionFd);
+ itsConnectionFd = NULL;
+ }
+#endif //BSD
+ itsCreatedHere = FALSE;
+}
+
+BOOL
+NamedPipe::Create()
+{
+#ifndef BSD //Not used by dgate, no need to port
+ if(itsCreatedHere)
+ {
+ // already created
+
+ return TRUE;
+ }
+
+ if(!itsName)
+ {
+ // call it invalid argument...
+ errno = EINVAL;
+ return FALSE;
+ }
+
+ // see if the name exists in the file system
+ // if not, create it error checking done via fattach() below...
+
+ int aNamedFd = creat(itsName, 0770);
+
+ if(aNamedFd >= 0)
+ {
+ // just needed the name in the file system...
+
+ close(aNamedFd);
+ }
+
+ int anFdList[2];
+
+ if(pipe(anFdList))
+ {
+ // can't create a pipe
+
+ return FALSE;
+ }
+
+ itsControlReadFd = anFdList[0];
+ itsControlWriteFd = anFdList[1];
+ itsConnectionFd = -1;
+
+ // bind the desired name to the end of pipe used by writer
+ // fails if name doesn't exist or is already bound to a stream
+
+ //if(fattach(itsControlWriteFd, itsName))
+ if (0)
+ {
+ // error binding to desired name -- name probably in use already
+ // as a named pipe
+
+ int anError = errno;
+ close(itsControlWriteFd);
+ itsControlWriteFd = -1;
+ close(itsControlReadFd);
+ itsControlReadFd = -1;
+ errno = anError;
+ return FALSE;
+ }
+
+ // push the connection-oriented line discipline module onto the
+ // writer's end of the stream -- this will have the effect of
+ // creating a new stream each time an open is done on the named
+ // object, and sending a file descriptor to the new stream to us
+ // via the original stream we created -- thus yielding a separate
+ // stream for each connection established (like mulitple instances
+ // of an NT named pipe)
+
+ //if(ioctl(itsControlWriteFd, I_PUSH, "connld"))
+ if (0)
+ {
+ int anError = errno;
+ close(itsControlWriteFd);
+ itsControlWriteFd = -1;
+ close(itsControlReadFd);
+ itsControlReadFd = -1;
+ errno = anError;
+ return FALSE;
+ }
+
+ itsCreatedHere = TRUE;
+#endif //BSD
+
+ return TRUE;
+}
+
+size_t
+NamedPipe::Read(unsigned char *theBuffer, size_t theLength)
+{
+ if(!itsName || !Connect())
+ {
+ errno = EBADF;
+ return 0xFFFFFFFF;
+ }
+
+ int aReadCount;
+
+#ifndef BSD
+ aReadCount = read(itsConnectionFd, theBuffer, theLength);
+#else //BSD uses fread to read streams
+ rewind(itsConnectionFd);
+ aReadCount = fread(theBuffer,1, theLength, itsConnectionFd);
+#endif //BSD
+ return aReadCount;
+}
+
+size_t
+NamedPipe::Write(unsigned char *theBuffer, size_t theLength)
+{
+ if(!itsName || !Connect())
+ {
+ errno = EBADF;
+ return 0xFFFFFFFF;
+ }
+
+ int aWriteCount;
+
+ void (*aPreviousDisposal)(int) = signal(SIGPIPE, SIG_IGN);
+#ifndef BSD
+ aWriteCount = write(itsConnectionFd, theBuffer, theLength);
+#else //BSD uses fwrite for streams.
+ fseek(itsConnectionFd, 0, SEEK_END);
+ aWriteCount = fwrite(theBuffer,1, theLength, itsConnectionFd);
+#endif //BSD
+ signal(SIGPIPE, aPreviousDisposal);
+
+ return aWriteCount;
+}
+
+BOOL
+NamedPipe::Wait(size_t theWaitSeconds)
+{
+ BOOL aWaitForeverFlag = (theWaitSeconds == 0 ? TRUE : FALSE);
+ unsigned char aBuffer;
+
+ do
+ {
+ // remain in loop when waiting until it happens...
+
+ if(aWaitForeverFlag)
+ {
+ ++theWaitSeconds;
+ }
+
+ if(Connect() && Write(&aBuffer, 0) == 0)
+ {
+ // connected and succeeded in writing 0 bytes
+ // which actually do get transmitted as a 0 byte message
+
+ Disconnect();
+ return TRUE;
+ }
+
+ // sleep 1 second then try again...
+ // unless time is up
+
+ if(theWaitSeconds > 0)
+ {
+ sleep(1);
+ }
+ }
+ while(theWaitSeconds-- > 0);
+
+ // times up...
+
+ return FALSE;
+}
+
+BOOL
+NamedPipe::Connect()
+{
+#ifndef BSD //Darwin uses fopen to open a stream.
+ if(itsConnectionFd >= 0)
+ {
+ // already connected...
+
+ return TRUE;
+ }
+
+ // client or server depending upon whether or not we created it
+
+ if(itsCreatedHere)
+ {
+ // server style -- wait to receive a connection via our
+ // control read fd (this ioctl returns a new fd for a
+ // connection when one occurs)
+
+ //if(ioctl(itsControlReadFd, I_RECVFD, &itsConnectionFd))
+ if (0)
+ {
+ return FALSE;
+ }
+ }
+ else
+ {
+ // client style
+
+ itsConnectionFd = open(itsName, O_RDWR | O_NONBLOCK);
+
+ if(itsConnectionFd == -1)
+ {
+ return FALSE;
+ }
+
+ // ensure that its a stream...
+
+ //if(!isastream(itsConnectionFd))
+ if (1)
+ {
+ close(itsConnectionFd);
+ itsConnectionFd = -1;
+ return FALSE;
+ }
+ }
+#else //Darwin uses fopen to open a stream.
+
+ if(itsConnectionFd != NULL)
+ {
+ // already connected...
+
+ return TRUE;
+ }
+
+ itsConnectionFd = fopen(itsName, "w+");
+
+ if(itsConnectionFd == NULL)
+ {
+ return FALSE;
+ }
+
+#endif //BSD
+ return TRUE;
+}
+
+void
+NamedPipe::Disconnect()
+{
+#ifndef BSD
+ if(itsConnectionFd >= 0)
+ {
+ close(itsConnectionFd);
+ itsConnectionFd = -1;
+ }
+#else //BSD uses fclose.
+ if(itsConnectionFd != NULL)
+ {
+ fclose(itsConnectionFd);
+ itsConnectionFd = NULL;
+ }
+#endif //BSD
+}
diff --git a/npipe.hpp b/npipe.hpp
new file mode 100644
index 0000000..9c895c3
--- /dev/null
+++ b/npipe.hpp
@@ -0,0 +1,44 @@
+// npipe.hpp -- define UNIX implementation of a minimal
+// windows NT named pipe service
+// 20070308 bcb Added changes for BSD and DARWIN
+// 20100619 bcb Added no-copy to the NamedPipe class.
+// 20100717 mvh Merged
+
+#ifndef NPIPE_HPP
+#define NPIPE_HPP
+#include <sys/types.h>
+#include "dicom.hpp"
+
+class NamedPipe
+{
+ public:
+ NamedPipe(char *theName);
+ ~NamedPipe();
+ BOOL Create();
+ void Destroy();
+ size_t Write(unsigned char *theBuffer, size_t theLength);
+ size_t Read(unsigned char *theBuffer, size_t theLength);
+ BOOL Wait(size_t theWaitTime);
+ BOOL Connect(); // establish connection
+ void Disconnect(); // terminate connection
+
+ private:
+
+ char *itsName;
+ BOOL itsCreatedHere;
+ int itsControlReadFd; // connections received here
+ int itsControlWriteFd; // this FD bound to name in filesystem
+#ifndef BSD
+ int itsConnectionFd; // this is the FD used for a connection
+ // which has been established
+#else //BSD
+ FILE *itsConnectionFd;
+#endif
+#ifdef __GNUC__
+private:// This will prevent it from being copied (it has a pointer)
+ NamedPipe(const NamedPipe&);
+ const NamedPipe & operator = (const NamedPipe&);
+#endif
+};
+
+#endif
diff --git a/odbci.cpp b/odbci.cpp
new file mode 100644
index 0000000..acaa233
--- /dev/null
+++ b/odbci.cpp
@@ -0,0 +1,5977 @@
+/*
+19980415 MvH blocked one error message
+19990628 MvH+ljz experimental locking call
+19990628 MvH temp defined DB_DEBUG and introduced experimental statement options
+19990707 MvH undefined DB_DEBUG and removed statement options
+19990827 MvH Added CreateIndex
+20000629 ljz Logging of trouble now starts with '***'
+20001105 MvH Run-time load ODBC routines for BC and WC
+20001128 ljz Added InitializeCriticalSection in 'Open' and DeleteCriticalSection
+ in 'Close'
+20010829 mvh Enabled DB_DEBUG to show db errors in verbose mode
+20020412 mvh Use SQLExecDirectWithRetry to retry in case of any error (deadlock=1205)
+ Added CreateUniqueIndex function, and GetLastError
+ Ignore error from unique index to make multi-user safe
+20020413 mvh NOTE: A SINGLE DB MAY NOT BE USED BY MULTIPLE THREADS
+20020417 mvh Extended deadlock wait time to about 1 min for safety
+20021014 mvh Added built-in dbf support for stable ODBC less-operation
+ Note: requires fully de-normalized database
+ notes: in dbsql, first bind row not set; in vrtosql; debug query print with %s in search crashes
+20021016 mvh Added about 1 MB of in-memory hashed index in patient ID for all tables; speed OK to 10.000 objects
+ pack db on server start (for speed it is wise to keep DBF files on local harddisk)
+20021017 mvh Made NeedPack a global for control from dgate; fix dbase_trunc; fix in Updaterecords;
+ fix first num field in AddRecord
+20021020 mvh Made querymodes an array, so that each query field can be key, key% or %key%
+ Use querymode also when hashing the entries (part of db entry)
+ Fix process_escape for '' and \[ and also use it before dbase_write
+20021028 mvh Set open retries shorter for normal readonly access
+20021030 mvh Match alternative patientID fieldname such that built-in DBF queries work
+20021113 mvh Added <= comparison in dbase_query (used for date comparison)
+20030113 mvh Do not use () in sort order when multiple columns specified
+20030128 mvh Added alternative field names for series
+20030321 ljz Also handle 'write lock' for M$Access (NativeError 1205 for sql-server
+ equals -1102 in M$Access). Other dbf-drivers???
+20030819 mvh Allow longer filenames
+20031104 mvh Added \\ to process_escape
+20040425 mvh Added DoubleBackSlashToDB control
+20040520 mvh Speedup by fix dbaseIII hashing, setting hashfield was wrong
+20040523 mvh Implemented in-memory index to speed dbase queries; added IndexDBF and PackDBF settings
+20040528 mvh Fix built-in DbaseIII for > 2 GB; index fixed at 10.000.000 records
+ Fix problem when spaces in patient ID in index generation
+20040528 mvh Added ExtractRecords (dbase III only); fix update/delete for record 0
+20040530 mvh IndexDBF gives MB extra to allocate; skip dbf files starting with X
+ Convert normal queries in SeriesInstanceUID or StudyInstanceUID to indexed ones
+20040601 mvh Added LongQueryDBF flag: report if query took longer than LongQueryDBF ms (default 1000)
+ Min 20 MB index during regen; allow pack on command (NeedPack=TRUE; DB.Open)
+ Increase query buffer size to 16384 (often reread), pack buffer to 65536
+20040605 mvh Optimize speed for huge files, extract max 100000 records; made lockstart __int64
+ Do not lock for read in extract (is very slow for huge files)
+ Record lock no longer on physical bytes but on rec#; attempt to speed memory index
+ NeedPack==3 -> force pack
+20040606 mvh Fix lock whole file; fix index patient ID database; fix in dbcreate for test
+20040609 mvh Implemented fast in-memory locking and enabled for all shared files
+20040610 mvh on dbase_create set indexcount to 0; dbase_trunc truncs indexcount
+20040612 mvh put index creation in a thread; server runs (but does not find non yet indexed
+ records) during indexing; implemented indexdbf command NeedPack=4
+20040614 mvh Added NeedPack=5: create non-threaded index (for archival options)
+20040615 mvh Added warning when index is full; keep indices when creating db
+20040930 mvh Added multiple value query; protect length of copy of where string
+20041003 mvh Reused very long SQLStatement string for wheres string
+ For lenghts see dbsql.cpp; tructated debug printfs
+ set cols length to 4096; malloc tmp in query at 310000;
+ for length calculation see dbsql.cpp
+20041013 mvh Used MAXQUERYLENGTH
+20041029 mvh Fixes in multiple query (query string truncated + mode mix problem)
+20041101 mvh DB is read only while in-memory indexing of DbaseIII active
+20050102 mvh Small modifications to allow compile through total.cxx
+20050107 mvh Export NumIndexing to tell dgate when indexing is done
+20050116 mvh Adapted for use with LINUX (built-in dbase driver only)
+ Notes: 1) delay poorly implemented; 2) no support for >2 GB db
+20050118 mvh Detach pthreads to avoid leaks
+20050119 mvh Documented rare crash in Fill_Memory_Index
+20050124 mvh Added support for huge files under Linux (not suitable for ext2 filesystem)
+ Allow = without spaces in query
+20050205 mvh Added counters for db activity
+20050206 mvh Small fixes to counters; allow "&" instead of " and " for CGI use
+20050905 mvh Postgres code by Piotr Filipczuk checked by mvh, will not affect
+ other operations, but not tested yet (postgres will not compile on
+ my linux system)
+20050907 mvh Merged change by Hans-Peter Hellemann: lseek64 not always defined, should be mapped by unistd.h
+20050909 mvh Put check for = in query below >=: date range matching failed (Thanks Paolo Marcheschi)
+20050911 mvh Removed postgres print statements
+20051125 mvh Fixed BindField for postgres - now returns actual and not reserved length
+20051217 mvh Maximum locks in dbaseIII driver from 1000 to 100 to speed up qunlock (20% regen speed)
+20051218 mvh Respond to -b = NOTHREAD: run server as single process, useful for debugging and profiling
+20051219 mvh Fixed slow leak of queryfields for built-in dbase driver
+20051230 mvh Put index of DicomWorkList on AccessionNumber
+20060219 mvh Start on native mysql driver
+20060220 mvh Some more work: get correct length in bindfield; todo: user and password
+20060226 mvh Runtime load MYSQL in WIN32
+20060313 mvh Use username and password for mysql
+20060402 mvh Start index threads with a short delay to give GUI priority to test startup
+20060607 mvh Changed escape char processing for sql values (not queries) to match dbsql.cpp change
+20060618 mvh Fix for Borland C++ builder
+20060628 mvh Moved location of disabled query logging
+20060630 mvh Speeded dbaseIII AddRecord lots and linux string handling
+20060701 mvh Added and use mysql_fetch_lengths; protect query result
+20060702 mvh Tested native mysql driver: does not like fast open/close
+ clonedb crashed after 4000 or so (avoided now)
+20061212 mvh Found critical error in built-in dbase driver sql parser:
+ Adding patient with ID containing certain character sequences will
+ immediately overwrite the whole patient database. Queries with these
+ sequences will return too many records (less dangerous)
+ Issue not yet realy fixed but greatly reduced its likelyhood
+20061213 mvh Fixed issue by replacing spaces inside strings in sql statement
+ with non breaking spaces. Only match on keywords and field names
+ which include spaces; replace with normal spaces in process_escape
+20070123 mvh clear NativeError, State and Msg on db.open (e.g. for dbf that does not use them but prints)
+20070126 mvh Added missing break in non breaking space field of process_escape: failed on multiple spaces in string
+20070127 mvh NativeError etc only defined in win32 version
+20070201 mvh DebugLevel 4 prints all sql activity
+20070203 mvh Fixed >2GB file support in linux: use O_LARGEFILE and lseek64() - sorry Hans-Peter Hellemann
+20070206 mvh Added CreateDatabase (created db and login)
+20070207 mvh Removed creation of login from CreateDtabase for mysql and postgres
+20070210 mvh Moved debug prints to SystemDebug; removed double log in QueryDistinct for dbaseIII
+20070218 mvh Added SqLite (win32 dll version): seems to run now; very slow when sync, very fast async
+20070307 mvh Made database type flag local, added Database(type) creator
+20770308 bcb Fixed DARWIN ifs, made DARWIN/MySQL auto start.( MySQL is included with DARWIN )
+20070315 mvh Merged; changed two nested ifs that had an else that would be wrong
+20070406 mvh Use reentrant rand_r and localtime_r when available
+20070507 mvh Native mysql does not correctly return empty fields (Steini)
+20070702 mvh Fixed above fix; test version for Stephan Winter
+20070703 mvh Removed test version code; display mysql connection errors on OperatorConsole
+20070705 mvh Added DT_DBASEIIINOINDEX: disables indexing and packing
+ #define USESQLITE_DLL to load DLL; otherwise use statically linked sqlite3.c
+ Extented max number of dbf files to 20
+20070709 mvh Fixed crash when mysql not started: format error in the error print
+20070711 mvh Some fixes to compile with sqlite under linux
+20070715 mvh Removed debug print statements for sqlite
+20071027 mvh Maybe fix postgres error handling: reset ntuples
+20071030 mvh More fixes to postgres error handling: missing returns in PrintLastError
+20071115 mvh Fixed SQL database creation for SQL server 2005
+20071118 mvh Adapted for 64 bits (use SQLLEN for BindField)
+20071124 mvh Removed dangling WHERE and ORDER in SQL server interface when passing "" instead of NULL
+20081116 mvh Adapted for 64 bits linux (avoid use of "long", in dbase code and when reading SQL_C_ULONG)
+20081117 mvh Allow compile with both POSTGRES and USEMYSQL
+20081119 mvh added run-time loading of postgres for WIN32
+20081120 mvh Added UseEscapeStringConstants for dbase (is needed only in one place because in other
+ place the E in E'\\...' is igored by the current code)
+20081121 mvh Implemented CreateDatabase for Postgres; also try load libmysql64.dll (for easy 64 bit deployment)
+20081124 mvh Added DT_NULL (black hole)
+20081125 mvh Fix critical section in DT_NULL
+20081126 mvh Todo: all realloc of dbase index when full; don't use threads to fill
+20090202 mvh Fixed problem of database fail open in GUI after install:
+ XADICOMPatients was never closed, as connected was not set when there were no databases
+20090203 mvh Fix crash on SQLite error
+20090429 mvh Added libpq64.dll
+20090616 mvh Added OldUID as hashfield: indices UIDMods table; increased default index to 10 MB
+20090620 jf Include file stuff
+20091230 mvh Merged bcb change
+20091231 bcb Changed char* to const char* and added blank[]="" for gcc4.2 warnings
+20100111 mvh Merged
+20100123 mvh Allow host:port syntax for hostname in MySQL and PostGres
+20100125 mvh GetPrivateProfileString -> MyGetPrivateProfileString
+20100309 bcb Cast k to unsigned int, commented out unused variables (gcc4.2 Warnings)
+20100309 bcb Added retunn FALSE to the end of CreateDatabase
+20100309 bcb Added double parentheses (gcc4.2 Warnings)
+20100619 bcb Fix gcc4 warnings, improve speed and added #ifndefs and UNUSED_ARGUMENT.
+20100703 mvh Merged; but fixed random seed change (initialize static)
+20100717 mvh Merged
+20100815 mvh Fixed linux compile for SqLite
+20100816 mvh removed (a) from #ifndef EnterCriticalSection(a) etc
+20101121 mvh use strncpy to avoid access errors in Sqlite where fields may exceed defined length
+20101121 mvh Disallow SqLite with DoubleBackSlashToDB
+20101129 mvh Filter [x] like sequences in dbaseIII driver process_escape
+20110102 mvh retry connect to postgres once; more postgres error handling
+20110104 mvh Undone [x] change of 20101129
+20110305 mvh Replaced Sleep(555) in linux code by delay(555)
+20110319 mvh Normalized line endings
+20110502 mvh Added db:Exec
+20111113 mvh Fixed leak in DT_NULL driver (SQLStatement not freed)
+20120107 mvh Accept 64 bits DLL's also as e.g., x64\libpq.dll
+20131029 mvh typo in lPassword
+*/
+
+/*
+
+Hi Stephan,
+
+it is a mysql/windows issue: mysql uses temporary ports that are not
+released quickly enough. Mysql dies after several thousand
+connects/disconnects because all temporary ports are allocated. With the
+debug log, the server is slightly slower and the problem does not happen.
+
+See:
+
+http://support.microsoft.com/kb/q196271/
+
+http://bugs.mysql.com/bug.php?id=6580
+
+http://bugs.mysql.com/bug.php?id=10498
+
+
+Quotes:
+
+2. Locate the following subkey in the registry, and then click Parameters:
+HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
+
+3. On the Edit menu, click New, and then add the following registry entry:
+Value Name: MaxUserPort
+Value Type: DWORD
+Value data: 65534
+Valid Range: 5000-65534 (decimal)
+Default: 0x1388 (5000 decimal)
+Description: This parameter controls the maximum port number that is used
+when a program requests any available user port from the system. Typically
+, ephemeral (short-lived) ports are allocated between the values of 1024
+and 5000 inclusive.
+4. Quit Registry Editor.
+Note An additional TCPTimedWaitDelay registry parameter determines how
+long a closed port waits until the closed port can be reused.
+
+
+So in the registry:
+
+HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
+
+set:
+
+MaxUserPort = 65534
+TcpTimedWaitDelay = 30
+
+
+*/
+
+#ifndef DEBUG_MODE
+# define DEBUG_MODE
+#endif
+//#define USESQLITE_DLL
+#ifndef UNUSED_ARGUMENT
+#define UNUSED_ARGUMENT(x) (void)x
+#endif
+
+#ifdef WIN32
+# include <stdio.h>
+# include <windows.h>
+# include <sql.h>
+# include <sqlext.h>
+#endif
+//#ifdef POSTGRES
+//# include "libpq-fe.h"
+//#endif
+
+#include <string.h> //DUCKHEAD92
+#include <ctype.h> //DUCKHEAD92
+#include <time.h> //DUCKHEAD92
+
+#ifdef WIN32
+# include <io.h>
+# include <sys\stat.h>
+# include <sys/locking.h>
+# include <dos.h>
+# define delay Sleep
+# define O_LARGEFILE 0
+#else
+# include <unistd.h>
+# include <dirent.h>
+# define delay(a) sleep(1)
+# define O_BINARY 0
+# define sopen(a, b, c, d) open(a, b)
+#ifndef EnterCriticalSection
+# define EnterCriticalSection(a) pthread_mutex_lock(a)
+#endif
+#ifndef LeaveCriticalSection
+# define LeaveCriticalSection(a) pthread_mutex_unlock(a)
+#endif
+#ifndef CRITICAL_SECTION
+# define CRITICAL_SECTION pthread_mutex_t
+#endif
+#ifndef InitializeCriticalSection
+# define InitializeCriticalSection(a) pthread_mutex_init(a, NULL);
+#endif
+#ifndef DeleteCriticalSection
+# define DeleteCriticalSection(a) pthread_mutex_destroy(a);
+#endif
+ void strupr(char *s)
+ { int L=strlen(s); for (int i=0; i<L; i++) s[i]=toupper(s[i]);
+ }
+ void strlwr(char *s)
+ { int L=strlen(s); for (int i=0; i<L; i++) s[i]=tolower(s[i]);
+ }
+ int GetTickCount()
+ { return time(NULL)*1000;
+ }
+ #define WINAPI
+#ifdef BSD
+# define O_LARGEFILE 0
+#endif //BSD
+#endif
+
+# include <fcntl.h>
+# include <errno.h>
+
+# ifndef _LK_NBLCK
+# define _LK_NBLCK LK_NBLCK
+# define _LK_UNLCK LK_UNLCK
+# endif
+# if !defined(_errno)
+# define _errno errno
+# endif
+
+# define open_retry_count 4
+# define open_retry_delay 50
+# define lock_retry_count 4
+# define lock_retry_delay 50
+# define file_lock_error -1
+# define file_access_error 5
+
+#include "gpps.hpp" //DUCKHEAD92
+#include "dgate.hpp"
+
+int NeedPack = TRUE; // controls pack of dbase files on startup
+static int OdbcDoubleBackSlashToDB=0;
+static int OdbcUseEscapeStringConstants=0;
+static int PackDBF=0;
+static int IndexDBF=0;
+static int LongQueryDBF=1000;
+int NumIndexing=-1; // is >0 during in-memory indexing
+
+extern BOOL NoThread; // debug non-threaded
+
+static short *Indices[20] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
+static int IndicesCount[20] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+
+// end for built-in dbase support
+
+# include "odbci.hpp"
+# include "dicom.hpp"
+# include "dprintf.hpp"
+
+typedef unsigned char BYTE;
+typedef unsigned int UINT;
+
+#ifndef DB_DEBUG
+# define DB_DEBUG
+#endif
+# define QUERY 1
+# define INSERT 2
+
+#if defined(__BORLANDC__) || defined(__WATCOMC__)
+typedef SQLRETURN (SQL_API *_SQLAllocConnect)(SQLHENV EnvironmentHandle,
+ SQLHDBC *ConnectionHandle);
+
+typedef SQLRETURN (SQL_API *_SQLAllocEnv)(SQLHENV *EnvironmentHandle);
+
+typedef SQLRETURN (SQL_API *_SQLAllocStmt)(SQLHDBC ConnectionHandle,
+ SQLHSTMT *StatementHandle);
+
+typedef SQLRETURN (SQL_API *_SQLConnect)(SQLHDBC ConnectionHandle,
+ SQLCHAR *ServerName, SQLSMALLINT NameLength1,
+ SQLCHAR *UserName, SQLSMALLINT NameLength2,
+ SQLCHAR *Authentication, SQLSMALLINT NameLength3);
+
+typedef SQLRETURN (SQL_API *_SQLDisconnect)(SQLHDBC ConnectionHandle);
+
+typedef SQLRETURN (SQL_API *_SQLFreeConnect)(SQLHDBC ConnectionHandle);
+
+typedef SQLRETURN (SQL_API *_SQLFreeEnv)(SQLHENV EnvironmentHandle);
+
+typedef SQLRETURN (SQL_API *_SQLFreeStmt)(SQLHSTMT StatementHandle,
+ SQLUSMALLINT Option);
+
+typedef SQLRETURN (SQL_API *_SQLTables)(SQLHSTMT StatementHandle,
+ SQLCHAR *CatalogName, SQLSMALLINT NameLength1,
+ SQLCHAR *SchemaName, SQLSMALLINT NameLength2,
+ SQLCHAR *TableName, SQLSMALLINT NameLength3,
+ SQLCHAR *TableType, SQLSMALLINT NameLength4);
+
+typedef SQLRETURN (SQL_API *_SQLBindCol)(SQLHSTMT StatementHandle,
+ SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType,
+ SQLPOINTER TargetValue, SQLINTEGER BufferLength,
+ SQLINTEGER *StrLen_or_Ind);
+
+typedef SQLRETURN (SQL_API *_SQLFetch)(SQLHSTMT StatementHandle);
+
+typedef SQLRETURN (SQL_API *_SQLError)(SQLHENV EnvironmentHandle,
+ SQLHDBC ConnectionHandle, SQLHSTMT StatementHandle,
+ SQLCHAR *Sqlstate, SQLINTEGER *NativeError,
+ SQLCHAR *MessageText, SQLSMALLINT BufferLength,
+ SQLSMALLINT *TextLength);
+
+typedef SQLRETURN (SQL_API *_SQLExecDirect)(SQLHSTMT StatementHandle,
+ SQLCHAR *StatementText, SQLINTEGER TextLength);
+
+_SQLAllocConnect __SQLAllocConnect;
+_SQLAllocEnv __SQLAllocEnv;
+_SQLAllocStmt __SQLAllocStmt;
+_SQLConnect __SQLConnect;
+_SQLDisconnect __SQLDisconnect;
+_SQLFreeConnect __SQLFreeConnect;
+_SQLFreeEnv __SQLFreeEnv;
+_SQLFreeStmt __SQLFreeStmt;
+_SQLTables __SQLTables;
+_SQLBindCol __SQLBindCol;
+_SQLFetch __SQLFetch;
+_SQLError __SQLError;
+_SQLExecDirect __SQLExecDirect;
+#endif
+
+// for built-in dbase support
+
+// code for in-memory record locking
+
+struct LOCK_DATA
+{ int start;
+ int end;
+ char filename[512];
+};
+
+CRITICAL_SECTION lock_critical;
+int lock_count = 100;
+struct LOCK_DATA *lock_table = NULL;
+
+// wait for lock to be passed and/or place lock in the lock table
+int qlock(char *filename, int start, int len)
+{ int i, lock_failure=1, end=start+len-1;
+
+ // initialize
+ if (lock_table==NULL)
+ { lock_table = (struct LOCK_DATA*)malloc(lock_count * sizeof(LOCK_DATA));
+ memset(lock_table, 0, lock_count * sizeof(LOCK_DATA));
+ InitializeCriticalSection(&lock_critical);
+ }
+
+ // scan all locks
+ EnterCriticalSection(&lock_critical);
+ for (i=0; i<lock_count; i++)
+ { if (lock_table[i].start==0 && lock_table[i].end==0)
+ { lock_table[i].start=start;
+ lock_table[i].end=end;
+ strcpy(lock_table[i].filename, filename);
+ lock_failure=0;
+ break;
+ }
+
+ if (start<lock_table[i].start && end<lock_table[i].start) continue;
+ if (start>lock_table[i].end && end>lock_table[i].end ) continue;
+ if (stricmp(lock_table[i].filename, filename)) continue;
+ break;
+ }
+
+ LeaveCriticalSection(&lock_critical);
+ return lock_failure;
+}
+
+// unlock earlier made entry in the lock table
+int qunlock(char *filename, int start, int len)
+{ int i, unlock_failure=1, end=start+len-1;//, j;
+
+ // initialize
+ if (lock_table==NULL)
+ { lock_table = (struct LOCK_DATA*)malloc(lock_count * sizeof(LOCK_DATA));
+ memset(lock_table, 0, lock_count * sizeof(LOCK_DATA));
+ InitializeCriticalSection(&lock_critical);
+ }
+
+ // scan all locks
+ EnterCriticalSection(&lock_critical);
+ for (i=0; i<lock_count; i++)
+ { if (lock_table[i].start!=start) continue;
+ if (lock_table[i].end !=end ) continue;
+ if (stricmp(lock_table[i].filename, filename)) continue;
+ lock_table[i].start=lock_table[i].end=0;
+ unlock_failure=0;
+ break;
+ }
+ LeaveCriticalSection(&lock_critical);
+ return unlock_failure;
+}
+
+#if defined(__BORLANDC__)
+#define _lseeki64 lseek
+#endif
+#ifdef BSD
+#define lseek64 lseek
+#endif //BSD
+
+#ifdef WIN32
+static void LongerSeek(int fh, int rec, int mult, int add)
+{ __int64 t;
+ t = (__int64)rec * (__int64)mult + (__int64)add;
+
+ if (t>(__int64)0x7fff * (__int64)0xffff)
+ _lseeki64(fh, t, SEEK_SET);
+ else
+ lseek(fh, t, SEEK_SET);
+}
+#else
+static void LongerSeek(int fh, int rec, int mult, int add)
+#ifdef __GNUC__ //ISO C++ does not support long long (and my long long was 32).
+{ uint64_t t;
+ t = (uint64_t)rec * (uint64_t)mult + (uint64_t)add;
+#else
+{ long long t;
+ t = (long long)rec * (long long)mult + (long long)add;
+#endif
+ // lseek(fh, t, SEEK_SET);
+ // unistd.h should map lseek to
+ lseek64(fh, t, SEEK_SET);
+}
+#endif
+
+
+//static int qlock(int fh, __int64 start, long length)
+//{ int s;
+// int l;
+// s = tell(fh);
+// if (s!=start) lseek(fh, start, SEEK_SET);
+// l = locking(fh, _LK_NBLCK, length);
+// if (s!=start) lseek(fh, s, SEEK_SET);
+// return l;
+//}
+
+//static int qunlock(int fh, __int64 start, long length)
+//{ int s;
+// int l;
+// s = tell(fh);
+// if (s!=start) lseek(fh, start, SEEK_SET);
+// l = locking(fh, _LK_UNLCK, length);
+// if (s!=start) lseek(fh, s, SEEK_SET);
+// return l;
+//}
+
+void write_dbheader(struct dbase_header *th)
+ /* write new header (recordcount) */
+{ lseek (th->filehandle,0,SEEK_SET); /* seek to file start */
+ write(th->filehandle,&th->junk1,32); /* write the header */
+ th->currentrecord=-1; /* force new seek for next access */
+}
+
+void read_dbheader(struct dbase_header *th)
+ /* read file header (recordcount) */
+{ lseek(th->filehandle,0,SEEK_SET); /* seek to file start */
+ read(th->filehandle,&th->junk1,32); /* and read the header */
+
+ if (th->oldupdatecount) /* auto-move the updatecount field */
+ { th->updatecount = th->oldupdatecount; /* for DBASEIII compatibility */
+ th->oldupdatecount = 0;
+ }
+
+ th->currentrecord=-1; /* force new seek for next access */
+}
+
+#ifndef localtime_r
+#define localtime_r(a, b) memcpy(b, localtime(a), sizeof(struct tm))
+#endif
+
+void set_dbdate(struct dbase_header *th)
+ /* put current date in file header */
+{
+ time_t time_of_day;
+ struct tm tmbuf;
+
+ time_of_day = time(NULL);
+ localtime_r(&time_of_day, &tmbuf);
+
+ th->junk1[1] = tmbuf.tm_year%100; /* put in the header */
+ th->junk1[2] = tmbuf.tm_mon+1;
+ th->junk1[3] = tmbuf.tm_mday;
+}
+
+
+/* lock_dbheader : locks database header;
+ returns : 0=OK, 1=no network, 2,3=error
+*/
+
+static unsigned int seedp = 0x55555555;
+
+#ifndef rand_r
+#define rand_r(a) rand()
+#endif
+ /* lock file header only */
+int lock_dbheader(struct dbase_header *th)
+{ int i;
+ /* already locked or not shared */
+ if ((th->lockcount!=0 && th->lockstart==0) || !th->sharemode) return 1;
+
+ for (i=0; i<lock_retry_count; i++)
+ { if (qlock(th->filename,0,1/*th->headerlength*/)==0) return 0;
+ /* lock succeeded */
+
+ if (i!=lock_retry_count-1) delay(rand_r(&seedp)%lock_retry_delay);
+ /* wait a while and retry */
+ }
+ UNUSED_ARGUMENT(seedp);//For unused variable gcc warning
+ return 3; /* failed after retries */
+}
+
+void unlock_dbheader(struct dbase_header *th)
+{ if ((th->lockcount!=0 && th->lockstart==0) || !th->sharemode) return;
+
+ qunlock(th->filename,0,1/*th->headerlength*/);
+}
+
+int dbase_lock(struct dbase_header *th, int firstrec, int reccount, int retries);
+
+/*************** open a dbase file for read and or write ***************/
+
+/* shared open (will also retry 10 s)
+
+ Returns 0, returns -errorcode on failure.
+
+ Will retry each 500 ms for 20 times if 'access denied'. If 'access denied'
+ the routine will not try to use another dbase_path entry.
+
+ mvh, 16-12-91: do NOT set handle pointer before complete success !
+*/
+
+#define ER_INARGUMENTS 1
+#define ER_NOSUCHFILE 2
+#define ER_NOSUCHFIELD 3
+#define ER_ONCREATINGFILE 4
+#define ER_ONDBASETRUNC 5
+#define ER_FAULTYHANDLE 6
+#define ER_SRCEQUALSDEST 7
+#define ER_DBLOCKFAILED 8
+#define ER_INVPACK1 9
+#define ER_INVPACK2 10
+#define ER_OUTOFHANDLES 11
+#define ER_TOOMANYFIELDS 12
+#define ER_TOOMANYFILES 13
+#define ER_NOACCESS 14
+#define ER_OPEN 15
+#define ER_INVALIDHANDLE 16
+#define ER_INVALIDRECORD 17
+#define ER_HEADERREAD 18
+#define ER_HEADERWRITE 19
+#define ER_RECORDREAD 20
+#define ER_RECORDWRITE 21
+#define ER_SHAREDTRUNC 22
+#define ER_SHAREDPACK 23
+#define ER_SHAREDEXTRACT 24
+#define ER_SHAREDSORT 25
+#define ER_SORTTOOLARGE 26
+#define ER_OPENOUTPUTFILE 27
+#define ER_WRITETOREADONLY 28
+#define ER_FILEALREADYOPEN 29
+#define ER_INVALIDFORMAT 30
+#define ER_OUTOFMEMORY 31
+#define ER_INTERNAL 32
+
+int dbase_open(char *filename, struct dbase_header **th)
+{ int i,j,h,l,rret;
+ int errcond, rdonly;
+ char string[1024], blank[] = "", *p;
+ int mode=1;
+
+ strcpy(string,filename); /* search path */
+ p=blank;
+
+ errcond = file_lock_error; /* DBUSE dos error = -1 */
+
+ if (mode)
+ errcond = file_access_error; /* DBSHARE dos error = 5 */
+
+ rdonly = 0;
+
+ while (1)
+ { for (i=0; i<open_retry_count; i++) /* retry some times */
+ { if (!mode)
+ h = sopen(string, O_RDWR + O_BINARY + O_LARGEFILE, SH_DENYRW, 0);
+ else
+ h = sopen(string, O_RDWR + O_BINARY + O_LARGEFILE, SH_DENYNO, 0);
+
+ /* OK / other error 'no access' */
+ if (h != -1 ) break;
+//|| (h == -1 &&
+// (int)_doserrno!=errcond &&
+// (int)_doserrno!=ERROR_SHARING_VIOLATION
+// )) break;
+
+ if (i!=open_retry_count-1) delay(rand_r(&seedp)%open_retry_delay);
+ }
+
+ /* break path search if : found/path empty/path exhausted/access denied */
+
+ if ( h != -1 || p==NULL || *p==0 ) break;
+//||
+// (h == -1 && ((int)_doserrno==errcond ||
+// (int)_doserrno==ERROR_SHARING_VIOLATION)))
+// break;
+
+ strcpy(string,p); /* get new path entry */
+ l = strcspn(p,";");
+ if (string[l-1] != PATHSEPCHAR) string[l] = PATHSEPCHAR;
+ string[l+1] = 0;
+ strcat(string,filename);
+ p += l+1;
+ }
+
+ /* try once to open read only (without path) if read/write open failed (useful for CDROM access) */
+
+ if (h == -1)
+ { strcpy(string, filename);
+
+ if (!mode)
+ h = sopen(string, O_RDONLY+ O_BINARY+ O_LARGEFILE, SH_DENYRW, 0);
+ else
+ h = sopen(string, O_RDONLY+ O_BINARY+ O_LARGEFILE, SH_DENYNO, 0);
+
+ if (h != -1) rdonly = 1;
+ }
+
+ if (h == -1)
+ { switch (_errno) /* return failure */
+ { case ENOENT : return -ER_NOSUCHFILE;
+ case EMFILE : return -ER_TOOMANYFILES;
+ case EACCES : return -ER_NOACCESS;
+#if defined(__WATCOMC__) && defined(WIN32)
+ case -1: switch (_doserrno)
+ { case ERROR_SHARING_VIOLATION:
+ return -ER_NOACCESS;
+ }
+ /* else fall through */
+#endif /* __WATCOMC__ && WIN32 */
+ default : perror("dbase_open"); return -ER_OPEN;
+ }
+ }
+
+ /* must allocate also for extra header space before junk1 */
+ if (((*th)=(struct dbase_header *)malloc(sizeof(struct dbase_header)+32*MAXFIELDS+512))==NULL)
+ { close (h);
+ return -ER_OUTOFMEMORY;
+ }
+
+ strcpy((*th)->filename, string);
+
+ /* read and process the header */
+ if (mode)
+ { (*th)->filehandle = h; /* assume some header to lock */
+ (*th)->currentrecord=-1;
+ (*th)->bufrecord =-1;
+ (*th)->rawrecord =-1;
+ (*th)->recordlength = 1;
+ (*th)->headerlength =32; /* first lock 'raw' header only */
+ (*th)->touched = 0;
+ (*th)->fieldcount = 1;
+ (*th)->lockstart = 0;
+ (*th)->lockcount = 0;
+ (*th)->sharemode = 1;
+
+ if (lock_dbheader((*th)) > 0) /* lock header with 1 sec. retry */
+ mode=0; /* if no network, disable locking */
+ }
+
+ rret=read(h,&(*th)->junk1,32); /* read 'raw' header */
+
+ if ((*th)->oldupdatecount) /* auto-move the updatecount field */
+ { (*th)->updatecount = (*th)->oldupdatecount; /* for DBASEIII compatibility */
+ (*th)->oldupdatecount = 0;
+ }
+
+ if (mode) unlock_dbheader((*th));
+
+ if (rret != 32) /* failed to read 'raw' header ? */
+ {
+ free((*th)); close(h); return -ER_HEADERREAD;
+ }
+
+ if ((*th)->hlength>32*MAXFIELDS+32 || (*th)->hlength<64) /* DBASE IV etc has much larger header */
+ { free((*th)); close(h); return -ER_INVALIDFORMAT; }
+
+ (*th)->headerlength = (*th)->hlength; /* read rest of the header */
+ if (mode) lock_dbheader((*th));
+ rret = read(h, &(*th)->fd, (*th)->hlength-32);
+ if (mode) unlock_dbheader((*th));
+
+ (*th)->recordlength=1; /* count fields and recordsize */
+ for(j=0; j<MAXFIELDS; j++)
+ { if ((*th)->fd[j].name[0] == 0x0d) break;
+ (*th)->recordlength += (*th)->fd[j].len;
+ }
+
+ if (j==MAXFIELDS) /* too many fields --> fail */
+ { free((*th)); close(h); return -ER_TOOMANYFIELDS; }
+
+ if (rret != (*th)->hlength-32) /* failed to read complete header ? */
+ { free((*th)); close(h); return -ER_HEADERREAD; }
+
+ /* allocate record buffers */
+ (*th)->recordbuffer = (char *)malloc(2 * (*th)->recordlength + j + 2);
+ (*th)->rawbuffer = (*th)->recordbuffer + (*th)->recordlength + j + 1;
+ if ((*th)->recordbuffer == NULL)
+ { free((*th)); close(h); return -ER_OUTOFMEMORY; }
+
+ (*th)->fieldcount = j; /* fill in the dbase handle */
+ (*th)->filehandle = h;
+ (*th)->currentrecord= 0;
+ (*th)->bufrecord = -1;
+ (*th)->rawrecord = -1;
+ (*th)->headerlength = (j+1)*32+1;
+ (*th)->touched = 0;
+
+ (*th)->lockstart = 0; /* file not locked at start */
+ (*th)->lockcount = 0;
+ (*th)->sharemode = mode;
+ (*th)->readonly = rdonly;
+
+ return 0; /* and return OK */
+}
+
+/* Note : will lock whole file shortly in shared mode when touched.
+ The routine must be careful to read fresh file length before the
+ file is closed and a trailing ctrl-z is added.
+
+ update, 15-12-91, mvh: just like write, lock only when has been touched
+*/
+
+void dbase_close(struct dbase_header *th)
+{ char c;
+ /* update header if file changed */
+ if (th->touched)
+ { if (th->sharemode) /* lock whole file if shared */
+ { dbase_lock(th,-1,0x7fffffff,lock_retry_count);
+ read_dbheader(th); /* get latest record count */
+ }
+
+ set_dbdate(th);
+ write_dbheader(th);
+
+ /* and add trailing ctrl-z */
+ LongerSeek( th->filehandle,
+ th->reccount, th->recordlength, th->headerlength
+ );
+ c=0x1a; write(th->filehandle,&c,1);
+
+ if (th->sharemode) /* unlock the file */
+ dbase_lock(th,0,0,lock_retry_count);
+ }
+
+
+ if (th->lockcount) /* free 'hanging' locks */
+ dbase_lock(th,0,0,lock_retry_count);
+
+ close(th->filehandle);
+
+ free(th->recordbuffer);
+ free(th);
+}
+
+/*************** create a dbase file for read and or write ***************/
+/*
+ The **fielddata array should point to strings with the
+ following structure (last pointer should be NULL) :
+
+ NAME:Cnn for nn (decimal) length character field
+ NAME:Nnn for nn (decimal) length numerical field
+ NAME:L logical field (one byte)
+ NAME:D date field (8 bytes in form YYYYMMDD).
+ NAME may be followed by spaces.
+
+ Returns 0, returns -errorcode on failure.
+
+*/
+
+int dbase_create(char *filename, char **fielddata, struct dbase_header **th)
+{ int i,j,h,len;
+ char name[20], *p, type;
+
+ h = creat(filename, S_IWRITE | S_IREAD);
+ if (h == -1) return -ER_ONCREATINGFILE; /* return creation failure */
+
+ close(h);
+ h = open(filename, O_RDWR | O_BINARY | O_LARGEFILE, 0);
+
+ /* must allocate also for extra header space before junk1 */
+ if (((*th)=(struct dbase_header *)malloc(sizeof(struct dbase_header)+32*MAXFIELDS+512))==NULL)
+ { close(h);
+ return -ER_OUTOFMEMORY;
+ }
+
+ (*th)->recordlength=1; /* count fields and recordsize */
+ for(j=0; j<MAXFIELDS; j++) /* fill in the field data */
+ { if (fielddata[j]==NULL) break;
+
+ p = strchr(fielddata[j], ':'); /* split in name, type and length */
+ if (p==NULL) /* no : found, use default type/len */
+ { len = 1;
+ type = 'C';
+ }
+ else /* get type and length if necessary */
+ { *p++ = 0;
+
+ while (isspace(*p) && *p!=0) p++;
+ type = toupper(*p);
+
+ if (type == 0) type = 'L'; /* when no type specified, use 'L' */
+
+ if (type == 'L') len = 1; /* get lenght or use default */
+ else if (type == 'D') len = 8;
+ else len = atoi(p+1);
+ }
+
+ strupr(fielddata[j]); /* polish up the name a bit */
+ sprintf(name,"%-10.10s",fielddata[j]);
+ for (i=9; i>=0; i--) if (isspace(name[i])) name[i]=0;
+
+ memcpy ((*th)->fd[j].name,name,11); /* fill in the field data */
+ memset ((*th)->fd[j].junk1,0,4);
+ memset ((*th)->fd[j].junk2,0,14);
+
+ (*th)->fd[j].type = type;
+ (*th)->fd[j].len = len;
+ (*th)->fd[j].deccount = 0;
+
+ (*th)->recordlength += (*th)->fd[j].len; /* and count the total recordlength */
+ }
+
+ if (j==MAXFIELDS) /* too many fields --> fail */
+ { free((*th));
+ close(h);
+ unlink(filename);
+ return -ER_TOOMANYFIELDS;
+ }
+
+ (*th)->fd[j].name[0] = 0x0d; /* place a field terminator */
+
+ memset((*th)->junk2, 0, 20); /* fill in the dbase handle */
+
+ (*th)->fieldcount = j;
+ (*th)->filehandle = h;
+ (*th)->currentrecord = 0;
+ (*th)->bufrecord = -1;
+ (*th)->rawrecord = -1;
+ (*th)->reccount = 0;
+ (*th)->updatecount = 0;
+ (*th)->oldupdatecount= 0;
+
+ (*th)->headerlength = (j+1)*32+1;
+
+ (*th)->hlength = (*th)->headerlength;
+ (*th)->rlength = (*th)->recordlength;
+
+ (*th)->junk1[0] = 0x03; /* dbase III file identifier */
+
+ (*th)->touched = 1;
+
+ (*th)->lockstart = 0; /* file not locked at start */
+ (*th)->lockcount = 0;
+ (*th)->sharemode = 0;
+ (*th)->readonly = 0;
+
+#if 1 /* set filename for check double opens */
+ strcpy((*th)->filename, filename);
+#endif
+
+ /* allocate record buffer */
+ (*th)->recordbuffer= (char *)malloc(2 * (*th)->recordlength + (*th)->fieldcount + 2);
+ (*th)->rawbuffer = (*th)->recordbuffer + (*th)->recordlength + (*th)->fieldcount + 1;
+ if ((*th)->recordbuffer == NULL)
+ { free((*th));
+ close(h);
+ unlink(filename);
+ return -ER_OUTOFMEMORY;
+ }
+
+ set_dbdate((*th));
+
+ /* write the fresh header */
+ i = write((*th)->filehandle,&(*th)->junk1,(*th)->headerlength);
+
+ if (i != (*th)->headerlength) /* write failed ? */
+ { free((*th)->recordbuffer);
+ free((*th));
+ close(h);
+ unlink(filename);
+ return -ER_HEADERWRITE;
+ }
+
+ lseek(h, (*th)->headerlength, SEEK_SET); /* rewind file to record 0 */
+
+ dbase_close((*th));
+ dbase_open(filename, th);
+
+ return 0; /* and return ok */
+}
+
+/************************ record locking operator **************************/
+
+/* Parameters : handle = dbase handle of file to lock
+ firstrec = first record to lock, use -1 to lock header also
+ reccount = number of records to lock (use 0 to unlock file)
+ retries = number of 100 ms retries before failure
+
+ Returns : 0 : locked O.K.
+ 1 : no network/multitasking locking function available
+ 2 : error
+ 3 : lock failed after some retries
+
+ Note : Locking a new file part automatically frees previous lock.
+*/
+
+
+int dbase_lock(struct dbase_header *th, int firstrec, int reccount, int retries)
+{ int i,j;
+ int locks;
+ int lockc;
+
+ /********** Check file handle *********/
+
+ if (!th->sharemode) return 1; /* no locking on normal file */
+
+ th->bufrecord = -1; /* invalidate buffer(s) */
+ th->rawrecord = -1;
+
+ /******** Free previous lock *********/
+
+ if (th->lockcount)
+ { i = qunlock(th->filename, th->lockstart, th->lockcount);
+ th->lockstart=0;
+ th->lockcount=0;
+ if (i) return 2; /* failed to unlock error */
+ }
+
+ /********** make a new lock *********/
+
+ if (reccount == 0x7fffffff) /* use LONG_MAX to lock all */
+ reccount = (0x7fffffff - th->headerlength - 256) / th->recordlength;
+ /* but filesize < 32 bits */
+
+
+ if (firstrec != -1) /* calculate lock range */
+ { if (reccount==0) return 0;
+ locks = firstrec+1; //(__int64) th->headerlength + (__int64) th->recordlength * (__int64)firstrec;
+ lockc = 1; //(long) th->recordlength * reccount;
+ }
+ else
+ {
+ locks = 0;
+ lockc = reccount+1; //(long) th->headerlength + (long) th->recordlength * reccount;
+ }
+
+ for (j=0; j<retries; j++)
+ { i = qlock(th->filename,locks,lockc);
+
+ if (i==0) /* lock succeeded */
+ { th->lockstart=locks;
+ th->lockcount=lockc;
+ return 0;
+ }
+
+ if (j!=retries-1) delay(rand_r(&seedp)%lock_retry_delay);
+ /* wait a while and retry */
+ }
+
+ return 3; /* failed after retries */
+}
+
+/************** query a dbase file : find matching records **************/
+
+/* Note : records in the file may NOT be locked manually during a query.
+ The routine will lock the whole file during query, and will get the
+ latest record count from the file, if the file is shared.
+
+ mode values are :
+ 0 : search for exact match of key.
+ 1 : search for "field contains key" match.
+ +2 : if set, comparison is case insensitive.
+ +4 : if set, query backwards (much slower).
+ 8 : search for "field starts with key" match.
+ 9 : as 8, but trailing spaces trimmed of keys first.
+ 16: field >= value comparison (identical string length only)
+ 32: field <= comparison (identical string length only)
+ 48: field inclusive range comparison ((identical string length only, limits must be concatenated)
+ 64: multiple exact value matching (a|b|c)
+*/
+
+// help routine: match data[len] against values = a|b|c
+BOOL mmatch(char *data, char *values, int len, int mode)
+{ char temp[256];
+ char *p, *q;
+
+ q = values;
+ p = strchr(values, '|');
+
+ while(p)
+ { *p = 0;
+ sprintf(temp,"%-*s", len, q);
+ *p = '|';
+ if (mode&2)
+ { if (memicmp(data, temp, len)==0) return TRUE;
+ }
+ else
+ { if (memcmp(data, temp, len)==0) return TRUE;
+ }
+ q = p+1;
+ p = strchr(q, '|');
+ }
+
+ sprintf(temp,"%-*s", len, q);
+ if (mode&2)
+ { if (memicmp(data, temp, len)==0) return TRUE;
+ }
+ else
+ { if (memcmp(data, temp, len)==0) return TRUE;
+ }
+
+ return FALSE;
+}
+
+int dbase_query(struct dbase_header *th, int *recno, char **fields, int *mode, int indexval)
+{ int i,k,found,j,offs,offsets[MAXFIELDS],buffers,rbuflen,rlength, b;//, t;
+ char *comparestrings[MAXFIELDS],*p,*q,*pbuffer;
+ int record, count, returnvalue;
+ int clens[MAXFIELDS], flens[MAXFIELDS], types[MAXFIELDS], fcount=0, backwards = mode[0]&4;
+ int *of, *of1, cl0, fl0, of0, first=1;
+ char **cs, *cs0, **cs1, *q0;
+ short *index = NULL;
+ int indexcount = 0;
+
+//OperatorConsole.printf("enter query at record %d, indexval = %d\n", *recno, indexval);
+// Init for warnings
+ b = 0;
+ pbuffer = NULL;
+
+ if (Indices[th->n] && indexval)
+ { index = Indices[th->n];
+ indexcount = IndicesCount[th->n];
+ }
+
+ for (i=0; i<MAXFIELDS; i++)
+ { offsets[i]=0;
+ comparestrings[i]=NULL;
+ types[i]=0;
+ }
+
+ buffers=16384/(th->recordlength+1);
+ if (buffers==0 || mode[0]&4 || index) buffers=1;
+
+ q=(char *)malloc(th->recordlength*buffers);
+ if (q==NULL) return -ER_OUTOFMEMORY;
+
+ p=(char *)malloc(th->recordlength+1);
+ if (p==NULL) {free(q); return -ER_OUTOFMEMORY; }
+
+ offs=1;
+
+ /* process the comparestrings */
+
+ for(i=0; i<th->fieldcount; i++)
+ { if (fields[i] != NULL)
+ { if (strlen(fields[i])!=0)
+ { k = th->fd[i].len; /* range comparison requires double input string */
+ if ((mode[i]&(64+48))==48) k *= 2;
+ else if ((mode[i]&64)==64) k = strlen(fields[i]); /* multiple match */
+
+ comparestrings[fcount]=(char *)malloc(k + 1);
+
+ /* truncate key at field length */
+ if (strlen(fields[i]) > (unsigned int)k)
+ fields[i][k]=0;
+ /* out of memory ? */
+ if (comparestrings[fcount]==NULL)
+ { returnvalue = -ER_OUTOFMEMORY; goto error; }
+
+ switch(mode[i] & (64+9)) /* processing depends on search mode */
+ { case 0: /* exact comparison or >= etc comparison: */
+ if (th->fd[i].type == 'C') /* character field left justified */
+ sprintf(comparestrings[fcount],"%-*s", k, fields[i]);
+
+ else /* other fields right justified */
+ sprintf(comparestrings[fcount],"%*s", k, fields[i]);
+
+ types[fcount] = mode[i]&(48+11);
+
+ break;
+
+ case 1: /* "includes" or "starts with" II */
+ case 9:
+ strcpy(comparestrings[fcount],fields[i]);
+ for (j=strlen(comparestrings[fcount])-1; j>=0; j--)
+ if (comparestrings[fcount][j]!=' ') break;
+ comparestrings[fcount][j+1]=0; /* trim trailing spaces */
+ types[fcount] = mode[i]&(48+11);
+ break;
+
+ case 8: /* exact key for "starts with" I */
+ strcpy(comparestrings[fcount],fields[i]);
+ types[fcount] = mode[i]&(48+11);
+
+ default: // multiple exact value matching
+ strcpy(comparestrings[fcount],fields[i]);
+ types[fcount] = mode[i]&(64+2);
+ }
+
+ if (mode[i] & 2) /* mode & 2 --> non case sensitive */
+ strlwr(comparestrings[fcount]);
+
+ offsets[fcount] = offs;
+ clens [fcount] = strlen(comparestrings[fcount]);
+ flens [fcount] = th->fd[i].len;
+ fcount++;
+ }
+ }
+ offs += th->fd[i].len;
+ }
+
+ if (th->sharemode) /* get latest record count */
+ { lock_dbheader (th);
+ read_dbheader (th);
+ unlock_dbheader(th);
+ }
+
+ if (th->currentrecord != *recno)
+ { LongerSeek( th->filehandle, /* seek first record */
+ *recno, th->recordlength, th->headerlength
+ );
+ th->currentrecord = *recno;
+ }
+
+ of0 = offsets[0];
+ of1 = &offsets[1];
+ cl0 = clens[0];
+ fl0 = flens[0];
+ cs0 = comparestrings[0];
+ cs1 = &comparestrings[1];
+
+ for (k=0; k<fcount; k++)
+ offsets[k] -= of0;
+
+ count = th->reccount;
+
+ k = buffers;
+ rlength = th->recordlength;
+ rbuflen = rlength * buffers;
+ found = 0;
+ record = *recno;
+ q0 = q + of0;
+
+ if (fcount==0) types[0] = -1; /* no fields to compare */
+
+ /* scan records for match */
+
+ if (record >= 0 && record < count)
+ { while (1)
+ { if (index)
+ { /* skip records with wrong index */
+ while (record<indexcount && record<count && index[record]!=(short)indexval)
+ record++;
+
+ if (th->currentrecord != record)
+ { LongerSeek( th->filehandle, /* seek first record */
+ record, th->recordlength, th->headerlength
+ );
+ th->currentrecord = record;
+ }
+
+ k = buffers;
+ first = 1;
+ }
+
+ if (++k >= buffers) /* read new buffer full of records */
+ { if (backwards)
+ { if (!first) record--; else first=0;
+ if (record < 0) break;
+ LongerSeek ( th->filehandle,
+ record, th->recordlength, th->headerlength
+ );
+ th->currentrecord = record;
+ }
+ else
+ { if (!first) record += buffers; else first=0;
+ if (count - record < buffers)
+ { buffers = count - record;
+ if (buffers <= 0) break; /* out of record range */
+ }
+ }
+
+ if ( dbase_lock(th,record,buffers,lock_retry_count) > 1) break;
+ if ( read(th->filehandle, q, rbuflen) < 1)
+ { dbase_lock(th, 0, 0, lock_retry_count) ; /* free lock after failed read */
+ break;
+ };
+ if ( dbase_lock(th, 0, 0,lock_retry_count) > 1) break;
+ th->currentrecord += buffers;
+
+ pbuffer = q0;
+ k = 0;
+ }
+
+ switch (types[0]) /* all bits except 4 (backwards) */
+ { case 0: /* exact compare (strcmp->memcmp) */
+ if (!memcmp(pbuffer, cs0, fl0))
+ { found = 1;
+ cs = cs1;
+ of = of1;
+ for (i=1; i<fcount; i++)
+ { if (types[i]==0)
+ { if (memcmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==2)
+ { if (memicmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==8 || types[i]==9)
+ { if (memcmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==10 || types[i]==11)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==16)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) < 0)
+ { found=0; break; }
+ }
+ else if (types[i]==32)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) > 0)
+ { found=0; break; }
+ }
+ else if (types[i]==48)
+ { int a = (memicmp(pbuffer + *of, *cs, clens[i]/2) < 0);
+ a |= (memicmp(pbuffer + *of, *cs + clens[i]/2, clens[i]/2) > 0);
+ of++; cs++;
+ if (a)
+ { found=0; break; }
+ }
+ else if (types[i]==64 || types[i]==66)
+ { if (!mmatch(pbuffer + *of++, *cs++, flens[i], types[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==1)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ else if (types[i]==3)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; strlwr(p); /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ }
+ }
+ break;
+
+ case 2: /* idem, case insensitive */
+ if (!memicmp(pbuffer, cs0, fl0))
+ { found = 1;
+ cs = cs1;
+ of = of1;
+ for (i=1; i<fcount; i++)
+ { if (types[i]==0)
+ { if (memcmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==2)
+ { if (memicmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==8 || types[i]==9)
+ { if (memcmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==10 || types[i]==11)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==16)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) < 0)
+ { found=0; break; }
+ }
+ else if (types[i]==32)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) > 0)
+ { found=0; break; }
+ }
+ else if (types[i]==48)
+ { int a = (memicmp(pbuffer + *of, *cs, clens[i]/2) < 0);
+ a |= (memicmp(pbuffer + *of, *cs + clens[i]/2, clens[i]/2) > 0);
+ of++; cs++;
+ if (a)
+ { found=0; break; }
+ }
+ else if (types[i]==64 || types[i]==66)
+ { if (!mmatch(pbuffer + *of++, *cs++, flens[i], types[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==1)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ else if (types[i]==3)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; strlwr(p); /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ }
+ }
+ break;
+
+ case 1: /* "includes" compare */
+ memcpy(p, pbuffer, fl0);
+ p[fl0]=0; /* copy: buffer needed for EXTRACT */
+ if (strstr(p, cs0))
+ { found = 1;
+ cs = cs1;
+ of = of1;
+ for (i=1; i<fcount; i++)
+ { if (types[i]==0)
+ { if (memcmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==2)
+ { if (memicmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==8 || types[i]==9)
+ { if (memcmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==10 || types[i]==11)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==16)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) < 0)
+ { found=0; break; }
+ }
+ else if (types[i]==32)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) > 0)
+ { found=0; break; }
+ }
+ else if (types[i]==48)
+ { int a = (memicmp(pbuffer + *of, *cs, clens[i]/2) < 0);
+ a |= (memicmp(pbuffer + *of, *cs + clens[i]/2, clens[i]/2) > 0);
+ of++; cs++;
+ if (a)
+ { found=0; break; }
+ }
+ else if (types[i]==64 || types[i]==66)
+ { if (!mmatch(pbuffer + *of++, *cs++, flens[i], types[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==1)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ else if (types[i]==3)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; strlwr(p); /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ }
+ }
+ break;
+
+ case 3: /* idem, case insensitive */
+ memcpy(p, pbuffer, fl0);
+ p[fl0]=0; strlwr(p); /* copy: buffer needed for EXTRACT */
+ if (strstr(p, cs0))
+ { found = 1;
+ cs = cs1;
+ of = of1;
+ for (i=1; i<fcount; i++)
+ { if (types[i]==0)
+ { if (memcmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==2)
+ { if (memicmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==8 || types[i]==9)
+ { if (memcmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==10 || types[i]==11)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==16)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) < 0)
+ { found=0; break; }
+ }
+ else if (types[i]==32)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) > 0)
+ { found=0; break; }
+ }
+ else if (types[i]==48)
+ { int a = (memicmp(pbuffer + *of, *cs, clens[i]/2) < 0);
+ a |= (memicmp(pbuffer + *of, *cs + clens[i]/2, clens[i]/2) > 0);
+ of++; cs++;
+ if (a)
+ { found=0; break; }
+ }
+ else if (types[i]==64 || types[i]==66)
+ { if (!mmatch(pbuffer + *of++, *cs++, flens[i], types[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==1)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ else if (types[i]==3)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; strlwr(p); /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ }
+ }
+ break;
+
+ case 8: /* "starts with" compare I and II */
+ case 9:
+ if (!memcmp(pbuffer, cs0, cl0))
+ { found = 1;
+ cs = cs1;
+ of = of1;
+ for (i=1; i<fcount; i++)
+ { if (types[i]==0)
+ { if (memcmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==2)
+ { if (memicmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==8 || types[i]==9)
+ { if (memcmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==10 || types[i]==11)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==16)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) < 0)
+ { found=0; break; }
+ }
+ else if (types[i]==32)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) > 0)
+ { found=0; break; }
+ }
+ else if (types[i]==48)
+ { int a = (memicmp(pbuffer + *of, *cs, clens[i]/2) < 0);
+ a |= (memicmp(pbuffer + *of, *cs + clens[i]/2, clens[i]/2) > 0);
+ of++; cs++;
+ if (a)
+ { found=0; break; }
+ }
+ else if (types[i]==64 || types[i]==66)
+ { if (!mmatch(pbuffer + *of++, *cs++, flens[i], types[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==1)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ else if (types[i]==3)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; strlwr(p); /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ }
+ }
+ break;
+
+ case 10: /* idem, case insensitive */
+ case 11:
+ if (!memicmp(pbuffer, cs0, cl0))
+ { found = 1;
+ cs = cs1;
+ of = of1;
+ for (i=1; i<fcount; i++)
+ { if (types[i]==0)
+ { if (memcmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==2)
+ { if (memicmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==8 || types[i]==9)
+ { if (memcmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==10 || types[i]==11)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==16)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) < 0)
+ { found=0; break; }
+ }
+ else if (types[i]==32)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) > 0)
+ { found=0; break; }
+ }
+ else if (types[i]==48)
+ { int a = (memicmp(pbuffer + *of, *cs, clens[i]/2) < 0);
+ a |= (memicmp(pbuffer + *of, *cs + clens[i]/2, clens[i]/2) > 0);
+ of++; cs++;
+ if (a)
+ { found=0; break; }
+ }
+ else if (types[i]==64 || types[i]==66)
+ { if (!mmatch(pbuffer + *of++, *cs++, flens[i], types[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==1)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ else if (types[i]==3)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; strlwr(p); /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ }
+ }
+ break;
+
+ case 16: /* >= comparison etc */
+ case 32:
+ case 48:
+ if (types[0]==16) b = (memicmp(pbuffer, cs0, cl0) < 0);
+ if (types[0]==32) b = (memicmp(pbuffer, cs0, cl0) > 0);
+ if (types[0]==48) b = (memicmp(pbuffer, cs0, cl0/2) < 0)
+ || (memicmp(pbuffer, cs0 + cl0/2, cl0/2) > 0);
+
+ if (!b)
+ { found = 1;
+ cs = cs1;
+ of = of1;
+ for (i=1; i<fcount; i++)
+ { if (types[i]==0)
+ { if (memcmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==2)
+ { if (memicmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==8 || types[i]==9)
+ { if (memcmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==10 || types[i]==11)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==16)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) < 0)
+ { found=0; break; }
+ }
+ else if (types[i]==32)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) > 0)
+ { found=0; break; }
+ }
+ else if (types[i]==48)
+ { int a = (memicmp(pbuffer + *of, *cs, clens[i]/2) < 0);
+ a |= (memicmp(pbuffer + *of, *cs + clens[i]/2, clens[i]/2) > 0);
+ of++; cs++;
+ if (a)
+ { found=0; break; }
+ }
+ else if (types[i]==64 || types[i]==66)
+ { if (!mmatch(pbuffer + *of++, *cs++, flens[i], types[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==1)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ else if (types[i]==3)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; strlwr(p); /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ }
+ }
+ break;
+
+ case 64: /* multiple comparison */
+ case 66:
+ if (mmatch(pbuffer, cs0, fl0, types[0]))
+ { found = 1;
+ cs = cs1;
+ of = of1;
+ for (i=1; i<fcount; i++)
+ { if (types[i]==0)
+ { if (memcmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==2)
+ { if (memicmp(pbuffer + *of++, *cs++, flens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==8 || types[i]==9)
+ { if (memcmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==10 || types[i]==11)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==16)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) < 0)
+ { found=0; break; }
+ }
+ else if (types[i]==32)
+ { if (memicmp(pbuffer + *of++, *cs++, clens[i]) > 0)
+ { found=0; break; }
+ }
+ else if (types[i]==48)
+ { int a = (memicmp(pbuffer + *of, *cs, clens[i]/2) < 0);
+ a |= (memicmp(pbuffer + *of, *cs + clens[i]/2, clens[i]/2) > 0);
+ of++; cs++;
+ if (a)
+ { found=0; break; }
+ }
+ else if (types[i]==64 || types[i]==66)
+ { if (!mmatch(pbuffer + *of++, *cs++, flens[i], types[i]))
+ { found=0; break; }
+ }
+ else if (types[i]==1)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ else if (types[i]==3)
+ { memcpy(p, pbuffer + *of++, flens[i]);
+ p[flens[i]]=0; strlwr(p); /* copy: buffer needed for EXTRACT */
+ if (strstr(p, *cs++)==NULL)
+ { found=0; break; }
+ }
+ }
+ }
+ break;
+
+ case -1: /* no fields to compare */
+ found = 1; /* so always found */
+ break;
+ }
+
+ if (found) /* this record matches */
+ { if (pbuffer[-of0] != '*') /* don't process marked records */
+ { *recno = record + (int)k;
+ break; /* after action, compare more ? */
+ }
+ found = 0;
+ }
+
+ pbuffer += rlength;
+ if (index) record++;
+ }
+ }
+
+ if (!found)
+ { *recno= -1; returnvalue = 0; }
+ else
+ { returnvalue = *recno; }
+
+error :
+ free(p); free(q);
+ for (i=0; i<MAXFIELDS; i++) free(comparestrings[i]);
+
+// th->currentrecord = -1;
+ return returnvalue;
+}
+
+/********* duplicate dbase file structure to new empty file ***********/
+
+/* Note : duplicated database is NOT opened for shared access,
+ so preferably store it on local disk.
+
+ The parameter oldhandle must be a handle of database to clone.
+ Return new filehandle, returns -errorcode on failure.
+*/
+
+struct dbase_header *dbase_dup(char *filename, struct dbase_header *th)
+{ int file,wret;//, i;
+ struct dbase_header *newth;
+
+ file = creat(filename, S_IWRITE | S_IREAD); /* try and create the file */
+ if (file == -1) return NULL;
+
+ close(file);
+ file = open(filename, O_RDWR | O_BINARY | O_LARGEFILE, 0);
+
+ /* allocate filehandle storage */
+ if ((newth=(struct dbase_header *)malloc(sizeof(struct dbase_header)+32*MAXFIELDS+512))==NULL)
+ { close(file);
+ return NULL;
+ }
+
+ memcpy(newth, /* duplicate the old handle */
+ th,
+ sizeof(struct dbase_header)+32*MAXFIELDS+512
+ );
+
+ newth->filehandle = file; /* fill in some fields */
+ newth->currentrecord = 0;
+ newth->bufrecord = -1;
+ newth->rawrecord = -1;
+ newth->reccount = 0;
+ newth->touched = 1;
+
+ newth->lockstart = 0; /* don't duplicate locks */
+ newth->lockcount = 0;
+ newth->sharemode = 0;
+ newth->readonly = 0;
+
+ strcpy(newth->filename, filename);
+
+ newth->updatecount = 0;
+ newth->oldupdatecount= 0;
+ set_dbdate(newth); /* fill in the date */
+
+ /* allocate record buffer */
+ newth->recordbuffer= (char *)malloc(2 * newth->recordlength + newth->fieldcount + 2);
+ newth->rawbuffer = newth->recordbuffer + newth->recordlength + newth->fieldcount + 1;
+ if (newth->recordbuffer == NULL)
+ { free(newth);
+ close(file);
+ unlink(filename);
+ return NULL;
+ }
+
+ /* and write the fresh header */
+ wret = write(file,&newth->junk1,newth->headerlength);
+
+ if (wret != newth->headerlength) /* check for errors */
+ { free(newth->recordbuffer);
+ free(newth);
+ close(file);
+ unlink(filename);
+ return NULL;
+ }
+
+ return newth;
+}
+
+/******************** read a record from a dbase file ******************/
+
+/* Note : will lock record during read, UNLESS manual lock is active.
+ In the latter case, you are out on your own ! Use manual locking
+ only to lock a quick read/write transfer or when appending to dbase.
+
+ Single record buffering is now applied for exclusively opened
+ databases or when a manual file lock is active.
+
+ The pointer array fields[] is filled with (fieldcount) pointers to the
+ newly read data. These pointers should not be freed anymore.
+
+ Returns -errorcode on failure, 0 on success, 1 when record is marked.
+*/
+
+int dbase_read(dbase_header *th, int recno, char** fields)
+{ int i,j,offs,rret,newdata=1;
+ char *p;
+
+ if (recno >= th->reccount || recno < 0) return -ER_INVALIDRECORD;
+
+ p = th->rawbuffer; /* use rawbuffer as workspace */
+
+ if (th->currentrecord != recno) /* seek the requested entry */
+ { LongerSeek ( th->filehandle,
+ recno, th->recordlength, th->headerlength
+ );
+ th->currentrecord = recno;
+ }
+
+ if (th->sharemode && !th->lockcount)
+ { dbase_lock(th,recno,1,lock_retry_count); /* lock if needed */
+ read(th->filehandle,p,th->recordlength); /* and read it */
+ dbase_lock(th,0,0,lock_retry_count); /* unlock if locked */
+ th->currentrecord++;
+ th->bufrecord = -1; /* invalidate buf. */
+ th->rawrecord = -1;
+ }
+ else
+ { if (recno != th->rawrecord) /* not in buffer so read */
+ { rret = read(th->filehandle,p,th->recordlength);
+
+ if (rret != th->recordlength && newdata) /* check for error */
+ return -ER_RECORDREAD;
+
+ th->currentrecord++;
+ th->rawrecord = recno;
+ }
+
+ if (recno == th->bufrecord) newdata = 0;
+ else th->bufrecord = recno;
+ }
+
+ offs=1; /* fill in the fields */
+ for(i=0; i<th->fieldcount; i++)
+ { fields[i] = th->recordbuffer + offs + i;
+ if (newdata) /* process new data */
+ { if (th->fd[i].type == 'C') /* trim trailing of character field */
+ { for (j=th->fd[i].len-1; j>=0; j--)
+ if (p[offs+j]!=' ') break;
+ j++;
+ memcpy(fields[i],p+offs,j);
+ fields[i][j]=0;
+ }
+ else /* trim leading spaces of any other */
+ { for (j=0; j < th->fd[i].len; j++)
+ if (p[offs+j]!=' ') break;
+ if (j < th->fd[i].len) memcpy(fields[i],p+offs+j,th->fd[i].len - j);
+ fields[i][th->fd[i].len - j]=0;
+ }
+ }
+ offs += th->fd[i].len;
+ }
+
+ if (newdata)
+ th->recordbuffer[0] = *p; /* buffer the record mark ! */
+
+ if (th->recordbuffer[0] == '*') i=1;
+ else i=0; /* record marked ? */
+
+ return i;
+}
+
+/****************** write a record to a dbase file *******************/
+
+/* Note : will lock record during update, UNLESS manual lock is active.
+ In the latter case, you are out in your own ! Use manual locking
+ only to lock a quick read/write transfer or for appending to dbase.
+
+ It is allowed to append records to the file. In that case it is advised
+ to lock the WHOLE file manually before you get the recordcount that is
+ used as recordnumber for the append. If you don't do that, the routine
+ will still work. It can't assure, however, that the recordcount hasn't
+ changed inbetween you asking it, and the actual write.
+
+ The pointers in fields[] must point to valid strings or be NULL.
+
+ Returns -errorcode on failure, 0 on success.
+
+ mvh, 15-12-91: modification: writes only when data will be changed.
+*/
+
+int dbase_write(dbase_header *th, int recno, char** fields, int mark)
+{ int i,j,offs,rwret,locked=0,modified=0,goread=1;
+ char *p, *save;
+
+ /* attempt to write illegal record */
+ if (recno > th->reccount || recno < 0 ) return -ER_INVALIDRECORD;
+
+ if (th->readonly) return -ER_WRITETOREADONLY;
+
+ p = th->rawbuffer; /* use rawbuffer as workspace */
+
+ save=(char *)malloc(th->recordlength+1); /* allocate more workspace */
+ if (save==NULL) return -ER_OUTOFMEMORY;
+
+ if (th->sharemode) /* shared : get latest record count */
+ { lock_dbheader(th);
+ read_dbheader(th);
+
+ if (th->lockcount == 0) /* and lock the record to update */
+ { dbase_lock(th, recno, 1, lock_retry_count);
+ locked=1;
+ }
+ }
+
+ if (recno == th->reccount) /* append a record so : */
+ { memset(p,' ',th->recordlength); /* blank the buffer */
+ goread = 0;
+ modified = 1;
+ }
+
+ if (th->currentrecord != recno) /* seek the requested entry */
+ { LongerSeek ( th->filehandle,
+ recno, th->recordlength, th->headerlength
+ );
+ th->currentrecord = recno;
+ }
+
+ if (th->sharemode && !th->lockcount)
+ { th->bufrecord = -1;
+ th->rawrecord = -1;
+ }
+ else
+ if (recno == th->rawrecord) goread = 0;
+
+ th->rawrecord = recno;
+
+ if (goread)
+ { rwret=read(th->filehandle,p,th->recordlength);
+ th->currentrecord++;
+
+ if (rwret != th->recordlength) /* check for errors */
+ { free(save);
+
+ if (locked) /* unlock if needed */
+ dbase_lock(th,0,0,lock_retry_count);
+
+ unlock_dbheader(th);
+ return -ER_RECORDREAD;
+ }
+ }
+
+ if (!modified)
+ memcpy(save, p, th->recordlength); /* save data for later compare */
+
+ if (mark) *p = '*'; else *p = ' '; /* mark as deleted / not deleted */
+
+ if (!modified) /* change in mark is modification ! */
+ modified = (*p != save[0]);
+
+ offs=1; /* fill in the fields */
+ for(i=0; i<th->fieldcount; i++)
+ { if (fields[i]!=NULL) /* field contains data */
+ { j=strlen(fields[i]);
+ if (th->fd[i].type != 'N') /* left justify non-numerical field */
+ { strncpy(p+offs,fields[i],th->fd[i].len);
+ if (j < th->fd[i].len) memset(p+offs+j,' ',th->fd[i].len-j);
+ }
+ else /* right justify numeric field */
+ { if (j<th->fd[i].len)
+ { memset(p+offs,' ',th->fd[i].len-j);
+ memcpy(p+offs+th->fd[i].len-j, fields[i], j);
+ }
+ else
+ memcpy(p+offs, fields[i], th->fd[i].len);
+ }
+ if (!modified) /* test if write will modify data */
+ modified = memcmp(save+offs, p+offs, th->fd[i].len) != 0;
+ }
+ offs += th->fd[i].len;
+ }
+
+ if (modified) /* write modified data only */
+ { if (th->currentrecord != recno) /* seek the requested entry */
+ { LongerSeek( th->filehandle, /* seek record */
+ recno, th->recordlength, th->headerlength
+ );
+ th->currentrecord = recno;
+ }
+
+ /* invalidate buffer when written */
+ if (th->bufrecord == recno) th->bufrecord = -1;
+
+ /* and write the updated record */
+ rwret=write(th->filehandle,p,th->recordlength);
+ th->currentrecord++;
+
+ if (rwret != th->recordlength) /* check for errors */
+ { free(save);
+
+ if (locked) /* unlock if needed */
+ dbase_lock(th,0,0,lock_retry_count);
+
+ unlock_dbheader(th);
+ return -ER_RECORDWRITE;
+ }
+ }
+
+ if (th->reccount==recno) /* appended so : */
+ th->reccount++; /* increase record count */
+
+ th->updatecount++; /* suppressed write is an update ! */
+ th->touched=1; /* register that file has changed */
+
+ if (th->sharemode) /* and update header if shared */
+ { set_dbdate(th);
+ write_dbheader(th);
+ unlock_dbheader(th);
+ }
+
+ if (locked) /* unlock if needed */
+ dbase_lock(th,0,0,lock_retry_count);
+
+ free(save);
+
+ return 0;
+}
+
+/************ dbase_trunc : truncate database to certain length *********/
+
+/* Truncates a database to a length of reccount records.
+ Returns -errorcode on failure, 0 on success.
+
+ NOTE: FAILS FOR TRUNC AT >2GB
+*/
+
+int dbase_trunc(dbase_header *th, int reccount)
+{ unsigned file_end;
+ char eof_marker=0x1a;
+ int r;
+
+ if (th->readonly) return -ER_WRITETOREADONLY;
+
+#ifdef WIN32
+ if ((__int64)reccount * (__int64)th->recordlength > (__int64)65536 * (__int64)32767)
+#else
+#ifdef __GNUC__ //ISO C++ does not support long long (and my long long was 32).
+ if ((uint64_t)reccount * (uint64_t)th->recordlength > (uint64_t)65536 * (uint64_t)32767)
+#else
+ if ((long long)reccount * (long long)th->recordlength > (long long)65536 * (long long)32767)
+#endif
+#endif
+ return ER_ONDBASETRUNC;
+
+ dbase_lock(th,-1,0x7fffffff,lock_retry_count);
+
+ file_end=(long)th->recordlength * reccount + (long) th->headerlength;
+
+ lseek(th->filehandle,file_end,SEEK_SET);
+
+ write(th->filehandle,&eof_marker,1); /* write EOF marker */
+#ifdef WIN32
+ r=chsize(th->filehandle,file_end+1); /* and truncate the file */
+#else
+ r=ftruncate(th->filehandle,file_end+1); /* and truncate the file */
+#endif
+
+ if (r == -1) return -ER_ONDBASETRUNC; /* error exit */
+
+ th->reccount = reccount; /* log the changes in handle */
+ th->currentrecord = -1;
+ th->bufrecord = -1;
+ th->rawrecord = -1;
+ th->touched = 1;
+ th->updatecount++;
+
+ write_dbheader(th); /* write the header */
+ dbase_lock(th,0,0,lock_retry_count);
+
+ return 0;
+}
+
+/***************** pack a dbase file : remove marked records *************/
+
+/* Returns -errorcode on failure, 0 on success.
+ Notes : 1) should only be used single-user; 2) invalidates the patient ID index.
+*/
+
+int dbase_pack(struct dbase_header *th)
+{ int k,buffers,bytesread,wbuffer;
+ int readrec,writerec;
+ char *buf,*p,*q;
+
+// Init for warnings
+ wbuffer = 0;
+ p = q = NULL;
+
+ if (th->reccount==0) return 0; /* no need to pack empty file */
+ if (th->readonly) return -ER_WRITETOREADONLY;
+
+ dbase_trunc(th, th->reccount); /* invalidates buffer(s) */
+
+ dbase_lock(th,-1,0x7fffffff,lock_retry_count);
+
+ buffers=65536/(th->recordlength+1); /* allocate 64 k buffer space */
+ if (buffers==0) buffers=1;
+
+ buf=(char *) malloc(th->recordlength*buffers);
+ if (buf==NULL) return -ER_OUTOFMEMORY;
+
+ k=0; readrec=0; writerec=0;
+
+ do
+ { if (k==0) /* if no more records : read buffer */
+ { p=buf; q=buf; wbuffer=0;
+ LongerSeek ( th->filehandle,
+ readrec, th->recordlength, th->headerlength
+ );
+ bytesread = read(th->filehandle,buf,th->recordlength*buffers);
+ if (bytesread==0 || bytesread==-1) break;
+ }
+
+ if (*p == ' ') /* process records : copy non-marked */
+ { if (p != q) memcpy(q,p,th->recordlength);
+ wbuffer++;
+ p += th->recordlength;
+ q += th->recordlength;
+ }
+ else if (*p == '*') /* skip marked records */
+ { p += th->recordlength;
+ }
+ else if (*p == 0x1a) break; /* break at end-of-file */
+
+ k++; if (k >= buffers) /* all 8 k processed -> write */
+ { k=0;
+ if (writerec!=readrec || p!=q) /* write if something changed */
+ { LongerSeek ( th->filehandle,
+ writerec, th->recordlength, th->headerlength
+ );
+ if(wbuffer) write(th->filehandle,buf,th->recordlength*wbuffer);
+ /* if.. added, 17/11/91, mvh */
+ }
+ writerec+=wbuffer;
+ readrec+=buffers;
+ }
+ } while (1);
+
+ /* flush buffer at end of file */
+ if (wbuffer != 0 && (p!=q || writerec!=readrec))
+ { LongerSeek ( th->filehandle,
+ writerec, th->recordlength, th->headerlength
+ );
+ if (wbuffer) write(th->filehandle,buf,th->recordlength*wbuffer);
+ /* if.. added, 17/11/91, mvh */
+ }
+ writerec+=wbuffer;
+
+ dbase_trunc(th, writerec); /* truncate database file */
+ free(buf);
+
+ dbase_lock(th,0,0,lock_retry_count);
+ return 0;
+}
+
+// filters SQL escape characters from dbase_query string
+
+void process_escape(char *in)
+{ signed char *p=(signed char *)in, *q=(signed char *)in;
+ while (*p)
+ { switch (*p)
+ { case '\\': p++; if (*p!='%' && *p!='_' && *p!='[' && (*p!='\\' || !OdbcDoubleBackSlashToDB))
+ *q++='\\'; break; // \% \_ \[ -> % _ [
+ // \\ -> \ is optional
+ // case '[': p++; *q++ = *p++; p++; break; // [x] -> x
+ case '\'': p++; if (*p=='\'') *q++='\'', p++; break; // '' -> '
+ case -1 : *q++ = ' ', p++; break; // 20061213: non breaking space used internally by query parser as space
+ default : *q++ = *p++;
+ }
+ }
+ *q = 0;
+}
+
+// filters SQL escape characters from dbase_write string
+
+void process_escapeValue(char *in)
+{ char *p=in, *q=in;
+ while (*p)
+ { switch (*p)
+ { case '\\': p++; if (*p!='\\' || !OdbcDoubleBackSlashToDB)
+ *q++='\\'; break; // \\ -> \ is optional
+ case '\'': p++; if (*p=='\'') *q++='\'', p++; break; // '' -> '
+ default : *q++ = *p++;
+ }
+ }
+ *q = 0;
+}
+
+// code for hashed in-memory index on patient ID
+
+struct HASH_DATA
+{ int hash;
+ int db;
+ int record;
+ char ID[68];
+};
+
+char hash_fields[4][11] = {"PATIENTID", "STUDYPAT", "IMAGEPAT", "SERIESPAT"};
+CRITICAL_SECTION hash_critical;
+int hash_count = 12345;
+struct HASH_DATA *hash_table = NULL;
+
+// number of entries to attempt on hash collision
+#define TRY_FURTHER 5
+
+// compute hash function
+int hash_id(char *ID, int db)
+{ int i, v=db * 7654321, L=strlen(ID);
+ for (i=0; i<L; i++)
+ if (ID[i]>='a' && ID[i]<='z') v = v*13 + ID[i] - 32;
+ else v = v*13 + ID[i];
+ if (v==0) v=1;
+ return v;
+}
+
+// search an entry in the hash index; returns first record at with ID is used
+int search_hash(char *ID, int db)
+{ int i, h, n;
+
+ // initialize
+ if (hash_table==NULL)
+ { hash_table = (struct HASH_DATA*)malloc(hash_count * sizeof(HASH_DATA));
+ memset(hash_table, 0, hash_count * sizeof(HASH_DATA));
+ InitializeCriticalSection(&hash_critical);
+ }
+
+ h = hash_id(ID, db);
+ n = abs(h % hash_count);
+
+ EnterCriticalSection(&hash_critical);
+
+ // search exact match
+ if (hash_table[n].hash==h && hash_table[n].db == db)
+ if (strcmp(ID, hash_table[n].ID)==0)
+ { LeaveCriticalSection(&hash_critical);
+ return hash_table[n].record;
+ }
+
+ // search some further; may have been placed there
+ for (i=0; i<TRY_FURTHER; i++)
+ { n++;
+ if (n>hash_count) n=0;
+
+ if (hash_table[n].hash==h && hash_table[n].db == db)
+ if (strcmp(ID, hash_table[n].ID)==0)
+ { LeaveCriticalSection(&hash_critical);
+ return hash_table[n].record;
+ }
+ }
+
+ // not found
+ LeaveCriticalSection(&hash_critical);
+ return 0;
+}
+
+// enter the first record for a patient ID into the hash index
+void enter_hash(char *ID, int db, int record)
+{ int i, h, n, o;
+
+ h = hash_id(ID, db);
+ n = o = abs(h % hash_count);
+
+ EnterCriticalSection(&hash_critical);
+
+ // search exact match
+ if (hash_table[n].hash==0)
+ if (hash_table[n].ID[0]==0)
+ { hash_table[n].record= record;
+ hash_table[n].hash = h;
+ hash_table[n].db = db;
+ strcpy(hash_table[n].ID, ID);
+ LeaveCriticalSection(&hash_critical);
+ return;
+ }
+
+ // search some further; may be placed there
+ for (i=0; i<TRY_FURTHER; i++)
+ { n++;
+ if (n>hash_count) n=0;
+
+ if (hash_table[n].hash==0)
+ if (hash_table[n].ID[0]==0)
+ { hash_table[n].record= record;
+ hash_table[n].hash = h;
+ hash_table[n].db = db;
+ strcpy(hash_table[n].ID, ID);
+ LeaveCriticalSection(&hash_critical);
+ return;
+ }
+ }
+
+ // no place: overwrite original item
+ hash_table[o].record= record;
+ hash_table[o].hash = h;
+ hash_table[o].db = db;
+ strcpy(hash_table[o].ID, ID);
+ LeaveCriticalSection(&hash_critical);
+}
+
+static int findhashfield(struct dbase_header *th)
+{ int i, k;
+
+ if (stricmp(th->fd[0].name, "ACCESSIONN")==0)
+ return 0;
+
+ if (th->fieldcount>1)
+ if (stricmp(th->fd[1].name, "OLDUID")==0)
+ return 1;
+
+ for (i=0; i<th->fieldcount; i++)
+ for (k=0; k<4; k++)
+ if (stricmp(th->fd[i].name, hash_fields[k])==0)
+ return i;
+
+ return -1;
+}
+
+static BOOL WINAPI Fill_Memory_Index(struct dbase_header *th)
+{ int i, j, hashfield=-1, offset, len;//, k, m;
+ int t = GetTickCount();
+ char *field;
+ int totalrec=th->TotalRec;
+ int MBextra=th->MBExtra;
+ int f;
+
+ // free old index
+ if (Indices[th->n]) free(Indices[th->n]);
+ Indices[th->n] = NULL;
+
+ hashfield = findhashfield(th);
+ if (hashfield<0) return TRUE;
+
+ NumIndexing++;
+
+ // divide MBextra free space according to current DB size or equally
+ if (totalrec > 1000) i = (int)(500000.0*(float)MBextra*(float)th->reccount/(float)totalrec);
+ else i = (int)(500000.0*(float)MBextra/5.0);
+ if (i<10000) i = 10000;
+
+ // allocate index
+ IndicesCount[th->n] = th->reccount + i;
+ Indices[th->n] = (short *)malloc(IndicesCount[th->n] * sizeof(short));
+ memset(Indices[th->n], 0, IndicesCount[th->n] * sizeof(short)); // rare crash: page fault about 2k before end of memset
+
+ // field spec
+ offset = th->headerlength + 1;
+ for (i=0; i<hashfield; i++) offset += th->fd[i].len;
+ len = th->fd[hashfield].len;
+
+ OperatorConsole.printf("Creating index on field %d for %s with %d records\n", hashfield, th->filename, th->reccount);
+
+ // mvh 20060402
+ delay(rand_r(&seedp) % 500);
+
+ field = (char *)malloc(th->recordlength * 64 + 1);
+
+ f = sopen(th->filename, O_RDWR + O_BINARY + O_LARGEFILE, SH_DENYNO, 0);
+
+ for (i=0; i<th->reccount; i++)
+ { LongerSeek(f, i, th->recordlength, offset);
+ read(f, field, len);
+ field[len] = 0;
+ for (j=len-1; j>=0; j--) if(field[j]==' ') field[j]=0; else break; // dbaseIII pads with spaces
+
+ Indices[th->n][i] = hash_id(field, 0);
+ if ((i%100000)==99999) OperatorConsole.printf("Indexing %s: %d records processed\n", th->filename, i+1);
+ }
+ close(f);
+ free(field);
+ OperatorConsole.printf("Index for %s finished in %d ms; total space = %d records\n", th->filename, GetTickCount()-t, IndicesCount[th->n]);
+
+ free(th);
+
+ NumIndexing--;
+
+ return TRUE;
+}
+
+void UpdateIndex(struct dbase_header *th, int rec, int hashfield)
+{ char *strings[MAXFIELDS];
+
+ if (Indices[th->n] && rec<IndicesCount[th->n] && hashfield>=0)
+ { dbase_read(th, rec, strings);
+ Indices[th->n][rec] = hash_id(strings[hashfield], 0);
+ }
+
+ if (Indices[th->n] && rec>=IndicesCount[th->n] && hashfield>=0)
+ { OperatorConsole.printf("***Index for %s is full - speed will degrade until server is restarted\n", th->filename);
+ }
+}
+
+// end for built-in dbase support
+
+///////////////////////////////////////////////////////////////////////////
+
+int DatabaseOpen=0; // counters for db activity
+int DatabaseClose=0;
+int DatabaseQuery=0;
+int DatabaseAddRecord=0;
+int DatabaseDeleteRecord=0;
+int DatabaseNextRecord=0;
+int DatabaseCreateTable=0;
+int DatabaseUpdateRecords=0;
+int QueryTime=0;
+
+#ifndef RootConfig
+extern char RootConfig[];
+#endif
+#ifndef ConfigFile
+extern char ConfigFile[];
+#endif
+
+#ifdef USEMYSQL
+#ifdef WIN32
+ _mysql_close mysql_close=NULL;
+ _mysql_init mysql_init=NULL;
+ _mysql_real_connect mysql_real_connect=NULL;
+ _mysql_select_db mysql_select_db=NULL;
+ _mysql_free_result mysql_free_result=NULL;
+ _mysql_query mysql_query=NULL;
+ _mysql_store_result mysql_store_result=NULL;
+ _mysql_num_rows mysql_num_rows=NULL;
+ _mysql_num_fields mysql_num_fields=NULL;
+ _mysql_fetch_row mysql_fetch_row=NULL;
+ _mysql_error mysql_error=NULL;
+ _mysql_fetch_field_direct mysql_fetch_field_direct=NULL;
+ _mysql_fetch_lengths mysql_fetch_lengths=NULL;
+ void LoadMySQL(void)
+ { HINSTANCE hInst;
+ if (mysql_close) return;
+
+ hInst = LoadLibrary("libmysql.dll");
+ if (!hInst) hInst = LoadLibrary("libmysql64.dll");
+ if (!hInst) hInst = LoadLibrary("x64\\libmysql.dll");
+ if (hInst)
+ { mysql_close = (_mysql_close)GetProcAddress(hInst, "mysql_close");
+ mysql_init = (_mysql_init)GetProcAddress(hInst, "mysql_init");
+ mysql_real_connect = (_mysql_real_connect)GetProcAddress(hInst, "mysql_real_connect");
+ mysql_select_db = (_mysql_select_db)GetProcAddress(hInst, "mysql_select_db");
+ mysql_free_result = (_mysql_free_result)GetProcAddress(hInst, "mysql_free_result");
+ mysql_query = (_mysql_query)GetProcAddress(hInst, "mysql_query");
+ mysql_store_result = (_mysql_store_result)GetProcAddress(hInst, "mysql_store_result");
+ mysql_num_rows = (_mysql_num_rows)GetProcAddress(hInst, "mysql_num_rows");
+ mysql_num_fields = (_mysql_num_fields)GetProcAddress(hInst, "mysql_num_fields");
+ mysql_fetch_row = (_mysql_fetch_row)GetProcAddress(hInst, "mysql_fetch_row");
+ mysql_error = (_mysql_error)GetProcAddress(hInst, "mysql_error");
+ mysql_fetch_field_direct = (_mysql_fetch_field_direct)GetProcAddress(hInst, "mysql_fetch_field_direct");
+ mysql_fetch_lengths = (_mysql_fetch_lengths)GetProcAddress(hInst, "mysql_fetch_lengths");
+ }
+ else
+ { MessageBox(NULL, "*** Fatal error: could not load libmysql.dll or libmysql64.dll to access mysql", "dgate.exe", 0);
+ exit(999);
+ }
+ }
+#endif
+#endif
+
+#ifdef POSTGRES
+#ifdef WIN32
+ _PQfinish __PQfinish=NULL;
+ _PQstatus __PQstatus=NULL;
+ _PQsetdbLogin __PQsetdbLogin=NULL;
+ _PQclear __PQclear=NULL;
+ _PQexec __PQexec=NULL;
+ _PQresultStatus __PQresultStatus=NULL;
+ _PQntuples __PQntuples=NULL;
+ _PQnfields __PQnfields=NULL;
+ _PQfmod __PQfmod=NULL;
+ _PQgetvalue __PQgetvalue=NULL;
+ _PQgetlength __PQgetlength=NULL;
+ _PQresultErrorMessage __PQresultErrorMessage=NULL;
+ _PQerrorMessage __PQerrorMessage=NULL;
+
+ void LoadPostgres(void)
+ { HINSTANCE hInst;
+ if (PQfinish) return;
+
+ hInst = LoadLibrary("libpq.dll");
+ if (!hInst) hInst = LoadLibrary("libpq64.dll");
+ if (!hInst) hInst = LoadLibrary("x64\\libpq.dll");
+ if (hInst)
+ { PQfinish = (_PQfinish)GetProcAddress(hInst, "PQfinish");
+ PQstatus = (_PQstatus)GetProcAddress(hInst, "PQstatus");
+ PQsetdbLogin = (_PQsetdbLogin)GetProcAddress(hInst, "PQsetdbLogin");
+ PQclear = (_PQclear)GetProcAddress(hInst, "PQclear");
+ PQexec = (_PQexec)GetProcAddress(hInst, "PQexec");
+ PQresultStatus = (_PQresultStatus)GetProcAddress(hInst, "PQresultStatus");
+ PQntuples = (_PQntuples)GetProcAddress(hInst, "PQntuples");
+ PQnfields = (_PQnfields)GetProcAddress(hInst, "PQnfields");
+ PQfmod = (_PQfmod)GetProcAddress(hInst, "PQfmod");
+ PQgetvalue = (_PQgetvalue)GetProcAddress(hInst, "PQgetvalue");
+ PQgetlength = (_PQgetlength)GetProcAddress(hInst, "PQgetlength");
+ PQresultErrorMessage = (_PQresultErrorMessage)GetProcAddress(hInst, "PQresultErrorMessage");
+ PQerrorMessage = (_PQerrorMessage)GetProcAddress(hInst, "PQerrorMessage");
+
+ if (!PQfinish || !PQstatus || !PQsetdbLogin || !PQclear || !PQexec || !PQresultStatus || !PQntuples || !PQnfields || !PQfmod || !PQgetvalue || !PQgetlength || !PQresultErrorMessage || !PQerrorMessage)
+ { MessageBox(NULL, "*** Fatal error: libpq.dll for accessing postgres 8.x is not compatible", "dgate.exe", 0);
+ exit(999);
+ }
+ }
+ else
+ { MessageBox(NULL, "*** Fatal error: could not load libpq.dll to access postgres8", "dgate.exe", 0);
+ exit(999);
+ }
+ }
+#endif
+#endif
+
+#if USESQLITE
+#include "sqlite3.h"
+#endif
+
+#ifdef USESQLITE_DLL
+typedef int (*sqlite3_callback)(void*,int,char**, char**);
+typedef int (*_sqlite3_open)(const char *filename, struct sqlite3 **ppDb);
+typedef int (*_sqlite3_exec)(struct sqlite3*, const char *sql, sqlite3_callback, void *, char **errmsg);
+typedef int (*_sqlite3_get_table)(struct sqlite3 *, const char *sql, char ***resultp, int *nrow, int *ncolumn, char **errmsg);
+typedef int (*_sqlite3_free_table)(char **result);
+typedef int (*_sqlite3_close)(struct sqlite3 *);
+typedef int (*_sqlite3_free)(void *);
+
+ _sqlite3_open __sqlite3_open=NULL;
+ _sqlite3_exec __sqlite3_exec=NULL;
+ _sqlite3_get_table __sqlite3_get_table=NULL;
+ _sqlite3_free_table __sqlite3_free_table=NULL;
+ _sqlite3_close __sqlite3_close=NULL;
+ _sqlite3_free __sqlite3_free=NULL;
+
+ void LoadSQLITE(void)
+ { HINSTANCE hInst;
+ if (__sqlite3_close) return;
+
+ hInst = LoadLibrary("sqlite3.dll");
+ if (!hinst) hInst = LoadLibrary("sqlite364.dll");
+ if (!hinst) hInst = LoadLibrary("x64\\sqlite3.dll");
+ if (hInst)
+ { __sqlite3_open = (_sqlite3_open )GetProcAddress(hInst, "sqlite3_open");
+ __sqlite3_exec = (_sqlite3_exec )GetProcAddress(hInst, "sqlite3_exec");
+ __sqlite3_get_table = (_sqlite3_get_table )GetProcAddress(hInst, "sqlite3_get_table");
+ __sqlite3_free_table = (_sqlite3_free_table)GetProcAddress(hInst, "sqlite3_free_table");
+ __sqlite3_close = (_sqlite3_close )GetProcAddress(hInst, "sqlite3_close");
+ __sqlite3_free = (_sqlite3_free )GetProcAddress(hInst, "sqlite3_free");
+ }
+ else
+ { MessageBox(NULL, "*** Fatal error: could not load sqlite3.dll to access SQLite", "dgate.exe", 0);
+ exit(999);
+ }
+ }
+
+#define sqlite3_open __sqlite3_open
+#define sqlite3_exec __sqlite3_exec
+#define sqlite3_get_table __sqlite3_get_table
+#define sqlite3_free_table __sqlite3_free_table
+#define sqlite3_close __sqlite3_close
+#define sqlite3_free __sqlite3_free
+#else
+#if USESQLITE
+void LoadSQLITE(void)
+{
+}
+#endif
+#endif
+
+#if defined(__BORLANDC__) || defined(__WATCOMC__)
+ void LoadODBC(void)
+ { HINSTANCE hInst = LoadLibrary("odbc32.dll");
+
+ __SQLAllocConnect = (_SQLAllocConnect)GetProcAddress(hInst, "SQLAllocConnect");
+ __SQLAllocEnv = (_SQLAllocEnv)GetProcAddress(hInst, "SQLAllocEnv");
+ __SQLAllocStmt = (_SQLAllocStmt)GetProcAddress(hInst, "SQLAllocStmt");
+ __SQLConnect = (_SQLConnect)GetProcAddress(hInst, "SQLConnect");
+ __SQLDisconnect = (_SQLDisconnect)GetProcAddress(hInst, "SQLDisconnect");
+ __SQLFreeConnect = (_SQLFreeConnect)GetProcAddress(hInst, "SQLFreeConnect");
+ __SQLFreeEnv = (_SQLFreeEnv)GetProcAddress(hInst, "SQLFreeEnv");
+ __SQLFreeStmt = (_SQLFreeStmt)GetProcAddress(hInst, "SQLFreeStmt");
+ __SQLTables = (_SQLTables)GetProcAddress(hInst, "SQLTables");
+ __SQLBindCol = (_SQLBindCol)GetProcAddress(hInst, "SQLBindCol");
+ __SQLFetch = (_SQLFetch)GetProcAddress(hInst, "SQLFetch");
+ __SQLError = (_SQLError)GetProcAddress(hInst, "SQLError");
+ __SQLExecDirect = (_SQLExecDirect)GetProcAddress(hInst, "SQLExecDirect");
+ }
+#endif
+
+Database :: Database()
+#ifdef __GNUC__ //Faster with member initialization.
+:db_type(DT_ODBC),
+#ifdef WIN32
+hEnv(NULL),
+hDbc(NULL),
+hStmt(NULL),
+Mode(NULL),
+//SWORD
+//SDWORD
+//State
+//Msg
+#endif //WIN32
+#ifdef POSTGRES
+conn(NULL),
+pgres(NULL),
+#endif //POSTGRES
+#ifdef USEMYSQL
+mydata(NULL),
+res(NULL),
+#endif
+#ifdef USESQLITE
+sqlitedata(NULL),
+// sqlitedata(NULL),
+resultp(NULL),
+#endif //USESQLITE
+#ifdef POSTGRES
+Postgres(0),
+#endif //POSTGRES
+#ifdef USEMYSQL
+Mysql(0),
+#endif //USEMYSQL
+#ifdef USESQLITE
+SqLite(0),
+#endif //USESQLITE
+#if defined(POSTGRES) || defined(USEMYSQL) || defined (USESQLITE)
+ncolumns(0),
+ntuples(0),
+current_tuple(0),
+#endif
+Connected(FALSE),
+thq(),
+queryrecno(0),
+hashfield(-1),
+m_Critical(),
+#ifdef WIN32
+RetCode(),
+#endif
+SQLStatement(NULL)
+{
+#else
+{
+ db_type = DT_ODBC;
+#endif
+
+#ifdef WIN32
+#ifndef __GNUC__
+ hEnv = NULL;
+ hDbc = NULL;
+ hStmt = NULL;
+ Mode = 0;
+#endif
+#endif
+
+#ifdef POSTGRES
+ {
+ char RootSC[64];
+ char Temp[128];
+
+ MyGetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig,
+ (char*) RootSC, 64, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "Postgres", "0", (char*) Temp, 128, ConfigFile);
+ Postgres = atoi(Temp);
+ if (Postgres) db_type = DT_POSTGRES;
+
+#ifndef __GNUC__
+ conn = NULL;
+ pgres = NULL;
+ ntuples = 0;
+ current_tuple = 0;
+#endif
+#ifdef WIN32
+ if (Postgres) LoadPostgres();
+#endif
+ }
+#endif
+
+#ifdef USEMYSQL
+ {
+ char RootSC[64];
+ char Temp[128];
+
+ MyGetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig,
+ (char*) RootSC, 64, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "Mysql", "0", (char*) Temp, 128, ConfigFile);
+ Mysql = atoi(Temp);
+ if (Mysql) db_type = DT_MYSQL;
+
+#ifndef __GNUC__
+ mydata = NULL;
+ res = NULL;
+ ntuples = 0;
+ current_tuple = 0;
+#endif
+
+#ifdef WIN32
+ if (Mysql) LoadMySQL();
+#endif
+ }
+#endif
+
+#ifdef USESQLITE
+ {
+ char RootSC[64];
+ char Temp[128];
+
+ MyGetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig,
+ (char*) RootSC, 64, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "SqLite", "0", (char*) Temp, 128, ConfigFile);
+ SqLite = atoi(Temp);
+ if (SqLite) db_type = DT_SQLITE;
+
+#ifndef __GNUC__
+ sqlitedata = NULL;
+ resultp = NULL;
+ ntuples = 0;
+ current_tuple = 0;
+#endif
+
+#ifdef WIN32
+ if (SqLite) LoadSQLITE();
+#endif
+ }
+#endif
+
+#ifndef __GNUC__
+ Connected = FALSE;
+#endif
+ SQLStatement = (char *)malloc(MAXQUERYLENGTH);
+
+ // built-in dbase support (when datasource is a directory, must end with \)
+ for (int i=0; i<20; i++) dbase_handles[i]=NULL;
+ memset(queryfields, 0, sizeof(queryfields));
+ dir[0] = 0;
+
+#if defined(__BORLANDC__) || defined(__WATCOMC__)
+ LoadODBC();
+#endif
+ }
+
+Database :: Database(enum DBTYPE dbtype)
+#ifdef __GNUC__ //Faster with member initialization.
+ :db_type(dbtype),
+#ifdef WIN32
+ hEnv(NULL),
+ hDbc(NULL),
+ hStmt(NULL),
+ Mode(NULL),
+ //SWORD
+ //SDWORD
+ //State
+ //Msg
+#endif //WIN32
+#ifdef POSTGRES
+ conn(NULL),
+ pgres(NULL),
+#endif //POSTGRES
+#ifdef USEMYSQL
+ mydata(NULL),
+ res(NULL),
+#endif
+#ifdef USESQLITE
+ sqlitedata(NULL),
+ // sqlitedata(NULL),
+ resultp(NULL),
+#endif //USESQLITE
+#ifdef POSTGRES
+ Postgres(0),
+#endif //POSTGRES
+#ifdef USEMYSQL
+ Mysql(0),
+#endif //USEMYSQL
+#ifdef USESQLITE
+ SqLite(0),
+#endif //USESQLITE
+#if defined(POSTGRES) || defined(USEMYSQL) || defined (USESQLITE)
+ ncolumns(0),
+ ntuples(0),
+ current_tuple(0),
+#endif
+ Connected(FALSE),
+ thq(),
+ queryrecno(0),
+ hashfield(-1),
+ m_Critical(),
+#ifdef WIN32
+ RetCode(),
+#endif
+ SQLStatement(NULL)
+ {
+#else
+ {
+ db_type = dbtype;
+#endif
+ if (db_type == DT_NULL) return;
+
+#ifdef WIN32
+#ifndef __GNUC__
+ hEnv = NULL;
+ hDbc = NULL;
+ hStmt = NULL;
+ Mode = 0;
+#endif
+#endif
+
+#ifdef POSTGRES
+ Postgres = db_type==DT_POSTGRES;
+#ifndef __GNUC__
+ conn = NULL;
+ pgres = NULL;
+ ntuples = 0;
+ current_tuple = 0;
+#endif
+#endif
+
+#ifdef USEMYSQL
+ Mysql = db_type==DT_MYSQL;
+#ifndef __GNUC__
+ mydata = NULL;
+ res = NULL;
+ ntuples = 0;
+ current_tuple = 0;
+#endif
+
+#ifdef WIN32
+ if (Mysql) LoadMySQL();
+#endif
+#endif
+
+#ifdef USESQLITE
+ SqLite = db_type==DT_SQLITE;
+#ifndef __GNUC__
+ sqlitedata = NULL;
+ resultp = NULL;
+ ntuples = 0;
+ current_tuple = 0;
+#endif
+
+#ifdef WIN32
+ if (SqLite) LoadSQLITE();
+#endif
+#endif
+
+#ifndef __GNUC__
+ Connected = FALSE;
+#endif
+ SQLStatement = (char *)malloc(MAXQUERYLENGTH);
+
+ // built-in dbase support (when datasource is a directory, must end with \)
+ for (int i=0; i<20; i++) dbase_handles[i]=NULL;
+ memset(queryfields, 0, sizeof(queryfields));
+ dir[0] = 0;
+
+#if defined(__BORLANDC__) || defined(__WATCOMC__)
+ LoadODBC();
+#endif
+ }
+
+#if defined(__BORLANDC__) || defined(__WATCOMC__)
+#define SQLAllocConnect __SQLAllocConnect
+#define SQLAllocEnv __SQLAllocEnv
+#define SQLAllocStmt __SQLAllocStmt
+#define SQLConnect __SQLConnect
+#define SQLDisconnect __SQLDisconnect
+#define SQLFreeConnect __SQLFreeConnect
+#define SQLFreeEnv __SQLFreeEnv
+#define SQLFreeStmt __SQLFreeStmt
+#define SQLTables __SQLTables
+#define SQLBindCol __SQLBindCol
+#define SQLFetch __SQLFetch
+#define SQLError __SQLError
+#define SQLExecDirect __SQLExecDirect
+#endif
+
+Database :: ~Database()
+ {
+ Close();
+ //if (db_type == DT_NULL) return;
+
+#ifdef POSTGRES
+ if (Postgres)
+ if (conn != NULL)
+ {
+ PQfinish(conn);
+ conn = NULL;
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (mydata != NULL)
+ {
+ mysql_close(mydata);
+ mydata = NULL;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (sqlitedata != NULL)
+ {
+ if (resultp)
+ {
+ sqlite3_free_table(resultp);
+ resultp = NULL;
+ }
+ sqlite3_close(sqlitedata);
+ sqlitedata = NULL;
+ }
+#endif
+
+ free(SQLStatement);
+ }
+
+struct dbase_header *copies[20];
+
+BOOL Database :: Open (
+ const char *lDataSource, // Made locals.
+ const char *User,
+ const char *lPassword,
+ const char *lServerName) // used in Sybase context, ignored here
+ {
+ UNUSED_ARGUMENT(lServerName);
+
+ if ( Connected )
+ Close();
+
+ DatabaseOpen++;
+
+ if (lDataSource[0]==0)
+ db_type = DT_NULL;
+
+ if (db_type == DT_NULL)
+ {
+ Connected = TRUE;
+ InitializeCriticalSection(&m_Critical);
+ return TRUE;
+ }
+
+ if (NumIndexing<0) NumIndexing=0; // signal dgate.cpp that indexing started
+
+#ifdef WIN32
+ NativeError = 0; // clear error info (maybe filled later)
+ State[0] = 0;
+ Msg [0] = 0;
+#endif
+
+ // test before built-in dbase because sqlite uses a database file that may contain PATHSEPCHAR
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ char RootSC[64];
+ char Temp[128];
+
+ MyGetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig,
+ (char*) RootSC, 64, ConfigFile);
+ MyGetPrivateProfileString ( RootSC, "DoubleBackSlashToDB", "0",
+ (char*) Temp, 128, ConfigFile);
+ if (atoi(Temp))
+ {
+ OperatorConsole.printf ("*** cannot use DoubleBackSlashToDB=1 with sqlite database\n");
+ return FALSE;
+ }
+
+ if (sqlite3_open(lDataSource, &sqlitedata))
+ {
+ OperatorConsole.printf ("*** cannot connect to sqlite database %s\n", lDataSource);
+ return FALSE;
+ }
+ Connected = TRUE;
+ InitializeCriticalSection(&m_Critical);
+
+ SQLITEExec("PRAGMA synchronous = OFF", FALSE); // makes it MUCH faster
+
+ return (TRUE);
+ }
+#endif
+
+ // built-in dbase support (when datasource is a directory, must end with \)
+ if (strchr(lDataSource, PATHSEPCHAR))
+ {
+ if (db_type != DT_DBASEIII && db_type != DT_DBASEIIINOINDEX) db_type = DT_DBASEIII;
+
+#ifdef WIN32
+ WIN32_FIND_DATA FileData;
+ HANDLE fdHandle;
+#else
+ DIR *dird;
+ dirent *diren;
+#endif
+
+ char TempPath[1024];
+ int dbnum=0, n;
+ char RootSC[64];
+ char Temp[128];
+
+ memset(queryfields, 0, sizeof(queryfields));
+
+ MyGetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig,
+ (char*) RootSC, 64, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "DoubleBackSlashToDB", "0",
+ (char*) Temp, 128, ConfigFile);
+ OdbcDoubleBackSlashToDB = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "UseEscapeStringConstants", "0",
+ (char*) Temp, 128, ConfigFile);
+ OdbcUseEscapeStringConstants = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "PackDBF", "0",
+ (char*) Temp, 128, ConfigFile);
+ PackDBF = atoi(Temp);
+ // NeedPack=1: /* normal server operation */
+ if (NeedPack==2) PackDBF = FALSE; /* 20 MB index, no pack - used during full regen (please clear db first) */
+ if (NeedPack==3) PackDBF = TRUE; /* 20 MB index force pack - used for c-echo maintenance */
+ if (NeedPack==4) PackDBF = FALSE; /* 20 MB index force index - used for c-echo maintenance */
+ if (NeedPack==5) PackDBF = FALSE; /* 20 MB index force non-threaded index - used for command line maintenance */
+
+ MyGetPrivateProfileString ( RootSC, "IndexDBF", "10",
+ (char*) Temp, 128, ConfigFile);
+ IndexDBF = atoi(Temp);
+ if (NeedPack>1 && IndexDBF<20) IndexDBF=20; // allocate at least 20 MB during regen - (for 2.5*10^6 images)
+
+ if (db_type == DT_DBASEIIINOINDEX)
+ { IndexDBF = 0;
+ PackDBF = FALSE;
+ }
+
+ MyGetPrivateProfileString ( RootSC, "LongQueryDBF", "1000",
+ (char*) Temp, 128, ConfigFile);
+ LongQueryDBF = atoi(Temp);
+
+ strcpy(dir, lDataSource);
+
+ strcpy(TempPath, lDataSource);
+ strcat(TempPath, "*.dbf");
+
+#ifdef WIN32
+ fdHandle = FindFirstFile(TempPath, &FileData);
+ if(fdHandle == INVALID_HANDLE_VALUE)
+ { Connected = TRUE;
+ InitializeCriticalSection(&m_Critical);
+ return ( TRUE ); // no databases found: is not an error!
+ }
+#else
+ dird = opendir(lDataSource);
+ if(dird == NULL)
+ { Connected = TRUE;
+ InitializeCriticalSection(&m_Critical);
+ return ( TRUE ); // no databases found: is not an error!
+ }
+#endif
+
+ while ( TRUE )
+ {
+#ifdef WIN32
+ if (!(FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
+ { strcpy(TempPath, lDataSource);
+ strcat(TempPath, FileData.cFileName);
+#else
+ diren = readdir(dird);
+ if (diren)
+ { strcpy(TempPath, lDataSource);
+ strcat(TempPath, diren->d_name);
+#endif
+
+ // do not open X files (extracted database parts for selected patient)
+#ifdef WIN32
+ if (FileData.cFileName[0]!='x' && FileData.cFileName[0]!='X')
+#else
+ if (diren->d_name[0]!='x' && diren->d_name[0]!='X' &&
+ (strstr(diren->d_name, ".dbf")||strstr(diren->d_name, ".DBF")))
+#endif
+ { if ((n=dbase_open(TempPath, &dbase_handles[dbnum++]))<0)
+ { OperatorConsole.printf("*** Open dbase %s error code %d\n", TempPath, n);
+#ifdef WIN32
+ FindClose(fdHandle);
+#else
+ closedir(dird);
+#endif
+ return FALSE;
+ }
+ dbase_handles[dbnum-1]->n = dbnum-1;
+ }
+ }
+
+#ifdef WIN32
+ if(!FindNextFile(fdHandle, &FileData))
+#else
+ if (diren==NULL)
+#endif
+ break;
+ }
+
+ if (NeedPack)
+ { int i, totalrec=0;
+#ifdef WIN32
+ HANDLE handles[20];
+#else
+ pthread_t handles[20];
+#endif
+
+ for (i=0; i<dbnum; i++) totalrec += dbase_handles[i]->reccount;
+
+ if (hash_table)
+ memset(hash_table, 0, hash_count * sizeof(HASH_DATA));
+
+ for (i=0; i<dbnum; i++)
+ { if (PackDBF)
+ { OperatorConsole.printf("Packing database %s\n", dbase_handles[i]->filename);
+ dbase_pack(dbase_handles[i]);
+ }
+ if (IndexDBF)
+ {
+#ifdef WIN32
+ unsigned long ThreadID;
+#endif
+
+ dbase_handles[i]->TotalRec = totalrec;
+ dbase_handles[i]->MBExtra = IndexDBF;
+
+ copies[i] = (dbase_header*)malloc(sizeof(dbase_header)+32*MAXFIELDS+512);
+ memcpy(copies[i], dbase_handles[i], sizeof(dbase_header)+32*MAXFIELDS+512);
+
+ if (NeedPack==5 || NeedPack==2 || NoThread)
+ Fill_Memory_Index(copies[i]);
+ else
+#ifdef WIN32
+ handles[i] = CreateThread(NULL, 0x000ff000, (LPTHREAD_START_ROUTINE) Fill_Memory_Index, copies[i], 0, &ThreadID);
+#else
+ { pthread_create(&handles[i], NULL, (void*(*)(void*))Fill_Memory_Index, (void *)copies[i]);
+ pthread_detach(handles[i]);
+ }
+#endif
+ }
+ }
+ }
+
+#ifdef WIN32
+ FindClose(fdHandle);
+#else
+ closedir(dird);
+#endif
+ Connected = TRUE;
+ InitializeCriticalSection(&m_Critical);
+ NeedPack = FALSE;
+ return TRUE;
+ }
+
+#ifdef POSTGRES
+ if (Postgres)
+ { char *port = NULL;
+ char host[256], *p;
+
+ strcpy(host, DataHost); // allows host:port syntax for Postgres
+ if(p=strchr(host, ':'))
+ {
+ port = p+1;
+ *p = 0;
+ }
+ if (conn != NULL && (PQstatus(conn) == CONNECTION_OK))
+ {
+ Connected = TRUE;
+ InitializeCriticalSection(&m_Critical);
+ return (TRUE);
+ }
+ conn = PQsetdbLogin(host,port,NULL,NULL,lDataSource,User,lPassword);
+ if (PQstatus(conn) == CONNECTION_BAD)
+ { // retry once a bit later
+ delay(555);
+ conn = PQsetdbLogin(host,port,NULL,NULL,lDataSource,User,lPassword);
+ if (PQstatus(conn) == CONNECTION_BAD)
+ {
+ OperatorConsole.printf("*** %s\n",PQerrorMessage(conn));
+ PQfinish(conn);
+ conn = NULL;
+ return (FALSE);
+ }
+ }
+ Connected = TRUE;
+ InitializeCriticalSection(&m_Critical);
+ return (TRUE);
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ { int port = MYSQL_PORT;
+ char host[256], *p;
+
+ strcpy(host, DataHost); // allows host:port syntax for MySQL
+ if((p=strchr(host, ':')))
+ {
+ port = atoi(p+1);
+ *p = 0;
+ }
+
+ if (mydata != NULL)
+ {
+ Connected = TRUE;
+ InitializeCriticalSection(&m_Critical);
+ return (TRUE);
+ }
+#ifndef DARWIN
+ if (!((mydata = mysql_init((MYSQL*)NULL)) && mysql_real_connect(mydata,host,User,lPassword,NULL,port,NULL,0)))
+ {
+ OperatorConsole.printf("***Cannot connect to MySQL on port %d\n", port);
+ OperatorConsole.printf("***MySQL Error message: %s\n", mysql_error(mydata));
+ mysql_close(mydata);
+ mydata = NULL;
+ return (FALSE);
+ }
+#else //DARWIN has mysql built in, lets try and start it.
+ if (!((mydata = mysql_init((MYSQL*)NULL)) && mysql_real_connect(mydata,host,User,lPassword,NULL,port,NULL,0)))
+ {
+ mysql_close(mydata);
+ mydata = NULL;
+ char mysqldPath[40] = "/usr/local/mysql/bin";
+ DIR *mysqldDir;
+ // Open the directory, if we can, we have MySQL.
+ if((mysqldDir = opendir(mysqldPath)) != NULL)
+ {
+ closedir(mysqldDir);// Don't need it, just a test.
+ strcat(mysqldPath,"/mysqld_safe &");//Add the file name
+ system(mysqldPath);//Start it
+ sleep(4); //Wait for it to start, it's slow.
+ }
+ //Try again, if not, report & bail
+ if (!((mydata = mysql_init((MYSQL*)NULL)) && mysql_real_connect(mydata,host,User,lPassword,NULL,port,NULL,0)))
+ {
+ OperatorConsole.printf("***Cannot connect to MySQL on port %d\n", port);
+ OperatorConsole.printf("***MySQL Error message: %s\n", mysql_error(mydata));
+ mysql_close(mydata);
+ mydata = NULL;
+ return (FALSE);
+ }
+ }
+#endif //DARWIN Note:I removed the else{}, it's not needed, return()s do it.
+ if (mysql_select_db( mydata, lDataSource)<0)
+ {
+ OperatorConsole.printf("***Cannot select MySQL database %s\n", lDataSource);
+ mysql_close(mydata);
+ mydata = NULL;
+ return (FALSE);
+ }
+ Connected = TRUE;
+ InitializeCriticalSection(&m_Critical);
+ return (TRUE);
+ }
+#endif
+
+#ifdef WIN32
+ if ( (RetCode = SQLAllocEnv (&hEnv)) != SQL_SUCCESS )
+ return ( FALSE );
+ if ( (RetCode = SQLAllocConnect(hEnv, &hDbc)) != SQL_SUCCESS)
+ {
+ SQLFreeEnv ( hEnv );
+ hEnv = NULL;
+#ifdef DB_DEBUG
+ SystemDebug.printf("***Failed to SQLAllocConnect()\n");
+#endif
+ return ( FALSE );
+ }
+ RetCode = SQLConnect(hDbc, (BYTE*)lDataSource, SQL_NTS,
+ (BYTE*)User, SQL_NTS, (BYTE*)lPassword, SQL_NTS);
+ if ( !((RetCode == SQL_SUCCESS) || (RetCode == SQL_SUCCESS_WITH_INFO)))
+ {
+ SQLError (hEnv, hDbc, hStmt, (BYTE*)State, &NativeError,
+ (BYTE*)Msg, 512, &MsgL);
+#ifdef DB_DEBUG
+ PrintLastError();
+#endif
+ SQLFreeConnect ( hDbc );
+ SQLFreeEnv ( hEnv );
+ hDbc = NULL;
+ hEnv = NULL;
+#ifdef DB_DEBUG
+ SystemDebug.printf("***Failed to SQLConnect()\n");
+#endif
+ return ( FALSE );
+ }
+
+
+ if ( (RetCode = SQLAllocStmt (hDbc, &hStmt)) != SQL_SUCCESS)
+ {
+ SQLDisconnect ( hDbc );
+ SQLFreeConnect ( hDbc );
+ SQLFreeEnv ( hEnv );
+ hDbc = NULL;
+ hEnv = NULL;
+ hStmt = NULL;
+#ifdef DB_DEBUG
+ SystemDebug.printf("***Failed to SQLAllocStmt()\n");
+#endif
+ return ( FALSE );
+ }
+ Connected = TRUE;
+ InitializeCriticalSection(&m_Critical);
+#endif
+ return ( TRUE );
+ }
+
+BOOL Database :: Close ()
+ {
+
+ DatabaseClose++;
+ if (db_type == DT_NULL)
+ {
+ DeleteCriticalSection(&m_Critical);
+ Connected = FALSE;
+ return TRUE;
+ }
+
+ // built-in dbf support
+ if (dir[0])
+ { if ( Connected )
+ { int i;
+ for (i=0; i<20; i++)
+ if (dbase_handles[i]!=NULL)
+ { dbase_close(dbase_handles[i]);
+ dbase_handles[i]=NULL;
+ }
+ DeleteCriticalSection(&m_Critical);
+ for(i=0; i<MAXFIELDS; i++) free(queryfields[i]);
+ memset(queryfields, 0, sizeof(queryfields));
+ }
+ Connected = FALSE;
+ return (TRUE);
+ }
+ // end built-in dbf support
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ if (pgres != NULL)
+ {
+ PQclear(pgres);
+ pgres = NULL;
+ }
+ if (Connected)
+ {
+ /*if (conn != NULL)
+ {
+ PQfinish(conn);
+ conn = NULL;
+ }*/
+ DeleteCriticalSection(&m_Critical);
+ Connected = FALSE;
+ }
+ return TRUE;
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ if (res != NULL)
+ {
+ mysql_free_result(res);
+ res = NULL;
+ }
+ if (Connected)
+ {
+ if (mydata != NULL)
+ {
+ mysql_close(mydata);
+ mydata = NULL;
+ }
+ DeleteCriticalSection(&m_Critical);
+ Connected = FALSE;
+ }
+ return TRUE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ if (Connected)
+ {
+ if (resultp)
+ {
+ sqlite3_free_table(resultp);
+ resultp = NULL;
+ }
+ if (sqlitedata != NULL)
+ {
+ sqlite3_close(sqlitedata);
+ sqlitedata = NULL;
+ }
+ DeleteCriticalSection(&m_Critical);
+ Connected = FALSE;
+ }
+ return TRUE;
+ }
+#endif
+
+#ifdef WIN32
+ if ( hStmt )
+ SQLFreeStmt ( hStmt, SQL_DROP );
+ if ( Connected )
+ {
+ if ( hDbc )
+ SQLDisconnect ( hDbc );
+ DeleteCriticalSection(&m_Critical);
+ }
+ if ( hDbc )
+ SQLFreeConnect ( hDbc );
+ if ( hEnv )
+ SQLFreeEnv ( hEnv );
+ hDbc = NULL;
+ hEnv = NULL;
+ hStmt = NULL;
+ Connected = FALSE;
+ return ( TRUE );
+#else
+ return ( FALSE );
+#endif
+ }
+
+BOOL Database :: NewStatement ()
+ {
+
+ if (db_type == DT_NULL)
+ return TRUE;
+
+#ifdef POSTGRES
+ if (Postgres)
+ return TRUE;
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ return TRUE;
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ return TRUE;
+#endif
+
+#ifdef WIN32
+ if ( hStmt )
+ SQLFreeStmt ( hStmt, SQL_DROP );
+
+ Mode = 0;
+ if ( (RetCode = SQLAllocStmt (hDbc, &hStmt)) != SQL_SUCCESS)
+ {
+ hStmt = NULL;
+#ifdef DB_DEBUG
+ SystemDebug.printf("***Failed to SQLAllocStmt()\n");
+#endif
+ return ( FALSE );
+ }
+ return ( TRUE );
+#else
+ return ( FALSE );
+#endif
+ }
+
+BOOL Database :: QueryTables (
+ char *SearchTableQualifier,
+ char *SearchTableOwner,
+ char *SearchTableName,
+ char *SearchTableType )
+ {
+
+ if (db_type == DT_NULL)
+ return FALSE;
+
+ // built-in dbf support - unsupported
+ if (dir[0])
+ return FALSE;
+ // end built-in dbf support
+
+#ifdef POSTGRES
+ if (Postgres)
+ return FALSE;
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ return FALSE;
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ return FALSE;
+#endif
+
+#ifdef WIN32
+ NewStatement();
+
+ RetCode = SQLTables ( hStmt,
+ (BYTE*)SearchTableQualifier, SQL_NTS,
+ (BYTE*)SearchTableOwner, SQL_NTS,
+ (BYTE*)SearchTableName, SQL_NTS,
+ (BYTE*)SearchTableType, SQL_NTS );
+ Mode = QUERY;
+ if ((RetCode != SQL_SUCCESS) &&
+ (RetCode != SQL_SUCCESS_WITH_INFO) )
+ {
+ SQLError (hEnv, hDbc, hStmt, (BYTE*)State, &NativeError,
+ (BYTE*)Msg, 512, &MsgL);
+#ifdef DB_DEBUG
+ SystemDebug.printf("***Failed to SQLTables()\n");
+#endif
+ return ( FALSE );
+ }
+ return ( TRUE );
+#else
+ UNUSED_ARGUMENT(SearchTableQualifier);
+ UNUSED_ARGUMENT(SearchTableOwner);
+ UNUSED_ARGUMENT(SearchTableName);
+ UNUSED_ARGUMENT(SearchTableType);
+
+ return ( FALSE );
+#endif
+ }
+
+
+// since any SQL statement can fail with a DeadLock, one must retry failed statements
+#ifdef POSTGRES
+int Database :: PGSQLExec(char *StatementText)
+ {
+ if (!Postgres) return -1;
+
+ if (pgres != NULL)
+ {
+ PQclear(pgres);
+ pgres = NULL;
+ }
+
+ pgres=PQexec(conn,StatementText);
+
+ if (pgres==NULL)
+ { OperatorConsole.printf("*** %s\n",PQerrorMessage(conn));
+ return -1;
+ }
+
+ if (PQresultStatus(pgres)==PGRES_TUPLES_OK)
+ {
+ ntuples = PQntuples(pgres);
+ ncolumns = PQnfields(pgres);
+ current_tuple = 0;
+ return 0;
+ }
+ else if (PQresultStatus(pgres)==PGRES_BAD_RESPONSE || PQresultStatus(pgres)==PGRES_FATAL_ERROR)
+ { OperatorConsole.printf("*** %s\n",PQerrorMessage(conn));
+ return -1;
+ }
+ else
+ {
+ ntuples = 0;
+ ncolumns = 0;
+ current_tuple = 0;
+ }
+
+ if (PQresultStatus(pgres)==PGRES_COMMAND_OK)
+ return 0;
+
+ return -1;
+
+ }
+#endif
+
+#ifdef USEMYSQL
+int Database :: MYSQLExec(char *StatementText, BOOL q)
+ {
+//SystemDebug.printf ( "MysqlExec %.1000s\n", StatementText);
+ if (res != NULL)
+ {
+ mysql_free_result(res);
+ res=NULL;
+ }
+
+ if (!mysql_query(mydata, StatementText))
+ {
+ if (q)
+ {
+ res = mysql_store_result( mydata );
+ if (res)
+ {
+ ntuples = (long)mysql_num_rows(res);
+ ncolumns = mysql_num_fields(res);
+ }
+ else
+ {
+ ntuples = 0;
+ ncolumns = 0;
+ }
+ current_tuple = 0;
+ return 0;
+ }
+ return 0;
+ }
+
+ return -1;
+ }
+#endif
+
+#ifdef USESQLITE
+#define SQLITE_BUSY 5
+int Database :: SQLITEExec(char *StatementText, BOOL q)
+ {
+ int i, rc;
+ char *err=NULL;
+
+ if (resultp)
+ {
+ sqlite3_free_table(resultp);
+ resultp = NULL;
+ }
+
+ if (!(rc=sqlite3_get_table(sqlitedata, StatementText, &resultp, &ntuples, &ncolumns, &err)))
+ {
+ if (!q && resultp)
+ {
+ sqlite3_free_table(resultp);
+ resultp = NULL;
+ ntuples = 0;
+ ncolumns = 0;
+ current_tuple = 0;
+ return 0;
+ }
+ current_tuple = 0;
+ return 0;
+ }
+
+ if (rc==SQLITE_BUSY)
+ for(i=0; i<60; i++)
+ {
+ sqlite3_free(err);
+ err = NULL;
+
+ delay(100 + rand_r(&seedp)%2000);
+ if (!(rc=sqlite3_get_table(sqlitedata, StatementText, &resultp, &ntuples, &ncolumns, &err)))
+ {
+ if (!q && resultp)
+ {
+ sqlite3_free_table(resultp);
+ resultp = NULL;
+ ntuples = 0;
+ ncolumns = 0;
+ current_tuple = 0;
+ return 0;
+ }
+ current_tuple = 0;
+ return 0;
+ }
+ }
+
+ OperatorConsole.printf("***SQLITEExec error: %s\n", err);
+ sqlite3_free(err);
+
+ return -1;
+ }
+#endif
+
+#ifdef WIN32
+int Database :: SQLExecDirectWithRetry(SQLHSTMT StatementHandle, SQLCHAR *StatementText, SQLINTEGER TextLength)
+ {
+ int RetCode, i;
+
+ RetCode = SQLExecDirect ( StatementHandle, StatementText, TextLength );
+ if ( (RetCode == SQL_SUCCESS) ||
+ (RetCode == SQL_SUCCESS_WITH_INFO) )
+ return ( RetCode );
+
+ SQLError (hEnv, hDbc, hStmt, (BYTE*)State, &NativeError,
+ (BYTE*)Msg, 512, &MsgL);
+
+ if (GetNativeError()==2601)
+ return SQL_SUCCESS_WITH_INFO; // duplicate index -> ignore
+
+ if ((GetNativeError() != 1205) && (GetNativeError() != -1102))// deadlock -> retry
+ return ( RetCode );
+
+ for(i=0; i<60; i++)
+ {
+ Sleep(100 + rand_r(&seedp)%2000);
+ RetCode = SQLExecDirect ( StatementHandle, StatementText, TextLength );
+ if ( (RetCode == SQL_SUCCESS) ||
+ (RetCode == SQL_SUCCESS_WITH_INFO) )
+ return ( RetCode );
+
+ if (i==59)
+ SQLError (hEnv, hDbc, hStmt, (BYTE*)State, &NativeError,
+ (BYTE*)Msg, 512, &MsgL);
+ }
+
+ return ( RetCode );
+ }
+#endif
+
+BOOL Database :: Query ( const char *Table,
+ const char *Columns,
+ const char *Where,
+ const char *Order )
+ { if (DebugLevel>=4)
+ { SystemDebug.printf("Query Tables: %.1000s\n", Table);
+ SystemDebug.printf("Columns : %.1000s\n", Columns);
+ SystemDebug.printf("Where : %.1000s\n", Where);
+ SystemDebug.printf("Order : %.1000s\n", Order);
+ }
+
+ return InternalQuery(Table, Columns, Where, Order, strcmp(Table, WorkListTableName)!=0);
+ } // not worklist->recurse
+
+BOOL Database :: InternalQuery ( const char *Table,
+ const char *Columns,
+ const char *Where,
+ const char *Order,
+ BOOL recurse )
+ {
+
+ DatabaseQuery++;
+
+ if (db_type == DT_NULL)
+ {
+ return TRUE;
+ }
+
+ // built-in dbf support (limited to simple single table queries)
+ if (dir[0])
+ { char *tmp = (char *)malloc(MAXQUERYLENGTH); // need a lot of space!
+ char *wheres = SQLStatement; // need a lot of space!
+ char cols[4096];
+ char fname[64];
+ char *p, *q, *r;
+ int i, j, k, n, a;
+
+ if (tmp==NULL) return FALSE;
+
+ hashfield=-1;
+
+ for(i=0; i<MAXFIELDS; i++) free(queryfields[i]);
+ memset(queryfields, 0, sizeof(queryfields));
+
+ wheres[0]=0;
+ if (Where) if ( Where[0] != '\0' ) strcpy(wheres, Where); // Add second if for DARWIN
+
+ strlwr(wheres);
+
+ // start 20061213
+ if (1) // replace spaces in strings by code -1 = 255 (non breaking space)
+ { int instring=0; // in this way the sql parsing becomes much safer
+ int L = strlen(wheres);
+ for (k=0; k<L; k++)
+ { if (wheres[k]=='\'') instring = !instring;
+ if (wheres[k]==' ' && instring==1) wheres[k] = -1; // non breaking space
+ }
+ }
+ // end 20061213
+
+ strcpy(cols, Columns);
+ strlwr(cols);
+
+ for (i=0; i<MAXFIELDS; i++) querymodes[i] = 2;
+ for (i=0; i<MAXFIELDS; i++) querycolumns[i] = -1;
+
+ strcpy(tmp, Table);
+ p = strchr(tmp, ',');
+ if (p) *p=0;
+ strcat(tmp, ".dbf");
+
+ for (i=0; i<20; i++)
+ { if (!dbase_handles[i]) continue;
+ p = strrchr(dbase_handles[i]->filename, PATHSEPCHAR);
+ if (!p) continue;
+ if (stricmp(p+1, tmp)==0)
+ { thq = dbase_handles[i];
+
+ hashfield = findhashfield(thq);
+
+ for (j=0; j<thq->fieldcount; j++)
+ { strcpy(fname, thq->fd[j].name);
+ strlwr(fname);
+
+ p = strstr(cols, fname); // match the column name
+ if (!p)
+ { if (strcmp(fname, "imagepat")==0)
+ { p = strstr(cols, "patientid"); // match alternative column names
+ if (!p) p = strstr(cols, "seriespat");
+ }
+ else if (strcmp(fname, "seriespat")==0)
+ { p = strstr(cols, "patientid"); // match alternative column names
+ if (!p) p = strstr(cols, "imagepat");
+ }
+ else if (strcmp(fname, "patientid")==0)
+ { p = strstr(cols, "seriespat"); // match alternative column names
+ if (!p) p = strstr(cols, "imagepat");
+ }
+ }
+
+ if (p)
+ { n = 0; for (k=0; k<p-cols; k++) if (cols[k]==',') n++;
+ querycolumns[j] = n;
+ }
+
+ strcat(fname, " "); // 20061213 (plus subsequent constant names adapted)
+ p = strstr(wheres, fname); // match the fieldname (with space no longer possible inside text strings)
+ if (!p)
+ { if (strcmp(fname, "imagepat ")==0)
+ { p = strstr(wheres, "patientid "); // match alternative fieldnames
+ if (!p) p = strstr(wheres, "seriespat ");
+ }
+ else if (strcmp(fname, "seriespat ")==0)
+ { p = strstr(wheres, "patientid "); // match alternative fieldnames
+ if (!p) p = strstr(wheres, "imagepat ");
+ }
+ else if (strcmp(fname, "patientid ")==0)
+ { p = strstr(wheres, "seriespat "); // match alternative fieldnames
+ if (!p) p = strstr(wheres, "imagepat ");
+ }
+ }
+ if (!p) continue;
+
+ strcpy(tmp, p); // get first clause for this field
+
+ p = strstr(tmp, " and "); // clause ends with " AND "
+ if (!p) p = strstr(tmp, " AND ");
+
+ // start 20061213
+ //if (!p) p = strstr(tmp, ") and ");
+ //if (!p) p = strstr(tmp, ") AND ");
+ //if (!p) p = strstr(tmp, "&");
+ //if (!p) p = strstr(tmp, ")&");
+ // end 20061213
+
+ if (p) *p=0;
+ if (p) r = p+1; else r = NULL;
+
+ a = 0;
+
+ p = strstr(tmp, " = "); // value after ' = ' or ' LIKE' or 'in'
+ if (!p) p = strstr(tmp, " LIKE ");
+ if (!p) p = strstr(tmp, " like ");
+ if (!p) { p = strstr(tmp, " in "); if (p) a = 66; }
+ if (!p) { p = strstr(tmp, " IN "); if (p) a = 66; }
+ if (!p) { p = strstr(tmp, " >= "); if (p) a = 16; }
+ if (!p) { p = strstr(tmp, " <= "); if (p) a = 32; }
+ if (!p) p = strstr(tmp, "=" );
+ if (!p) continue;
+
+ q = strrchr(p, '\''); // value must be enclosed by ' : this will ignore E in E'...' or e'....'
+ if (!q) continue;
+ *q=0;
+ q = strchr(p, '\'');
+ if (!q) continue;
+
+ if (q[1]=='%')
+ queryfields[j] = strdup(q+2), querymodes[j]=3; // %key? -> substring
+ else
+ queryfields[j] = strdup(q+1);
+
+ p = strchr(queryfields[j], '%');
+ if (p)
+ { if (p[1] == 0)
+ { *p=0;
+ if (querymodes[j]!=3) querymodes[j]=11; // key% -> starts with
+ // else %key% -> substring
+ }
+ }
+
+ if (a==16 && r) // >= and <= -> (date) range comparison
+ { r = strstr(r, fname); // match the field name again for range comparison
+
+ if (r) r = strstr(r, " <= ");
+
+ if (r)
+ { strcpy(tmp, queryfields[j]); // append the upper value to the query string
+ free(queryfields[j]); // free string, need new dup
+ strcat(tmp, r+4);
+ r = strstr(tmp, "\' and "); // lower range value end at ' and
+ if (r) *r=0;
+ queryfields[j] = strdup(tmp); // new dup
+ a = 48;
+ }
+ }
+
+ if (a) querymodes[j] = a; // <= or >= or range comparison
+
+ process_escape(queryfields[j]);
+ }
+ queryrecno=0;
+
+ // try to convert normal query to an indexed one (works when Study and/or SeriesInstanceUID passed)
+ if (recurse && Where!=NULL && strlen(Where)!=0 && hashfield>=0 && queryfields[hashfield]==NULL)
+ { char pat[128]="";
+ SQLLEN len;
+
+ // try to get patient ID for query in image table from study or series table
+ if (memicmp(Table, ImageTableName, strlen(ImageTableName))==0)
+ { InternalQuery (StudyTableName, "PatientID", Where, NULL, FALSE);
+ if (queryfields[0] && querymodes[0]==2)
+ { BindField (1, SQL_C_CHAR, pat, 128, &len);
+ NextRecord();
+ }
+ else
+ { InternalQuery (SeriesTableName, "SeriesPat", Where, NULL, FALSE);
+ if (queryfields[0] && querymodes[0]==2)
+ { BindField (1, SQL_C_CHAR, pat, 128, &len);
+ NextRecord();
+ }
+ }
+ }
+
+ // try to get patient for series table from study table
+ else if (memicmp(Table, SeriesTableName, strlen(SeriesTableName))==0)
+ { InternalQuery (StudyTableName, "PatientID", Where, NULL, FALSE);
+ if (queryfields[0] && querymodes[0]==2)
+ { BindField (1, SQL_C_CHAR, pat, 128, &len);
+ NextRecord();
+ }
+ }
+
+ // re-create original query
+ InternalQuery (Table, Columns, Where, NULL, FALSE);
+
+ // add indexed patient ID if found
+ if (strlen(pat))
+ { queryfields[hashfield] = strdup(pat);
+ querymodes [hashfield] = 2;
+ }
+ }
+
+ // performed in NextRecord
+ // dbase_query(thq, &queryrecno, queryfields, querymodes);
+ free(tmp);
+ return TRUE;
+ }
+ }
+ free(tmp);
+ return FALSE;
+ }
+ // end built-in dbf support
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ sprintf (SQLStatement, "SELECT %s FROM %s",
+ Columns, Table);
+ if ( Where ) if ( Where[0] != '\0' ) // Add second if for DARWIN
+ {
+ strcat ( SQLStatement, " WHERE " );
+ strcat ( SQLStatement, Where );
+ }
+ if ( Order ) if ( Order[0] != '\0' ) // Add second if for DARWIN
+ {
+ if ( strchr(Order, ',') )
+ {
+ strcat ( SQLStatement, " ORDER BY " );
+ strcat ( SQLStatement, Order );
+ }
+ else
+ {
+ strcat ( SQLStatement, " ORDER BY (" );
+ strcat ( SQLStatement, Order );
+ strcat ( SQLStatement, ")" );
+ }
+ }
+ if (PGSQLExec(SQLStatement) == 0)
+ return TRUE;
+ else
+ return FALSE;
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ sprintf (SQLStatement, "SELECT %s FROM %s",
+ Columns, Table);
+ if ( Where ) if ( Where[0] != '\0' ) // Add second if for DARWIN
+ {
+ strcat ( SQLStatement, " WHERE " );
+ strcat ( SQLStatement, Where );
+ }
+ if ( Order ) if ( Order[0] != '\0' ) // Add second if for DARWIN
+ {
+ if ( strchr(Order, ',') )
+ {
+ strcat ( SQLStatement, " ORDER BY " );
+ strcat ( SQLStatement, Order );
+ }
+ else
+ {
+ strcat ( SQLStatement, " ORDER BY (" );
+ strcat ( SQLStatement, Order );
+ strcat ( SQLStatement, ")" );
+ }
+ }
+ if (MYSQLExec(SQLStatement, TRUE) == 0)
+ return TRUE;
+ else
+ return FALSE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ sprintf (SQLStatement, "SELECT %s FROM %s",
+ Columns, Table);
+ if ( Where ) if ( Where[0] != '\0' ) // Add second if for DARWIN
+ {
+ strcat ( SQLStatement, " WHERE " );
+ strcat ( SQLStatement, Where );
+ }
+ if ( Order ) if ( Order[0] != '\0' ) // Add second if for DARWIN
+ {
+ if ( strchr(Order, ',') )
+ {
+ strcat ( SQLStatement, " ORDER BY " );
+ strcat ( SQLStatement, Order );
+ }
+ else
+ {
+ strcat ( SQLStatement, " ORDER BY (" );
+ strcat ( SQLStatement, Order );
+ strcat ( SQLStatement, ")" );
+ }
+ }
+ if (SQLITEExec(SQLStatement, TRUE) == 0)
+ return TRUE;
+ else
+ return FALSE;
+ }
+#endif
+
+#ifdef WIN32
+ NewStatement();
+
+ sprintf (SQLStatement, "SELECT %s FROM %s",
+ Columns, Table);
+ if ( Where ) if ( Where[0] != '\0' )
+ {
+ strcat ( SQLStatement, " WHERE " );
+ strcat ( SQLStatement, Where );
+ }
+ if ( Order ) if ( Order[0] != '\0' )
+ {
+ if ( strchr(Order, ',') )
+ {
+ strcat ( SQLStatement, " ORDER BY " );
+ strcat ( SQLStatement, Order );
+ }
+ else
+ {
+ strcat ( SQLStatement, " ORDER BY (" );
+ strcat ( SQLStatement, Order );
+ strcat ( SQLStatement, ")" );
+ }
+ }
+
+ Mode = QUERY;
+ RetCode = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+ if ( (RetCode == SQL_SUCCESS) ||
+ (RetCode == SQL_SUCCESS_WITH_INFO) )
+ return ( TRUE );
+
+#ifdef DB_DEBUG
+ SystemDebug.printf("***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+
+#endif
+ return ( FALSE );
+ }
+
+BOOL Database :: QueryDistinct ( char *Table,
+ const char *Columns,
+ const char *Where,
+ const char *Order )
+ {
+ if (DebugLevel>=4)
+ { SystemDebug.printf("Query Distinct Tables: %.1000s\n", Table);
+ SystemDebug.printf("Columns : %.1000s\n", Columns);
+ SystemDebug.printf("Where : %.1000s\n", Where);
+ SystemDebug.printf("Order : %.1000s\n", Order);
+ }
+
+ if (db_type == DT_NULL)
+ {
+ return TRUE;
+ }
+
+ // built-in dbf support
+ if (dir[0])
+ return InternalQuery(Table, Columns, Where, Order, strcmp(Table, WorkListTableName)!=0);
+ // return Query(Table, Columns, Where, Order ); remove double log
+ // end built-in dbf support
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ DatabaseQuery++;
+ sprintf (SQLStatement, "SELECT DISTINCT %s FROM %s",
+ Columns, Table);
+ if ( Where ) if ( Where[0] != '\0' ) // Add second if for DARWIN
+ {
+ strcat ( SQLStatement, " WHERE " );
+ strcat ( SQLStatement, Where );
+ }
+ if ( Order ) if ( Order[0] != '\0' ) // Add second if for DARWIN
+ {
+ if ( strchr(Order, ',') )
+ {
+ strcat ( SQLStatement, " ORDER BY " );
+ strcat ( SQLStatement, Order );
+ }
+ else
+ {
+ strcat ( SQLStatement, " ORDER BY (" );
+ strcat ( SQLStatement, Order );
+ strcat ( SQLStatement, ")" );
+ }
+ }
+ if (PGSQLExec(SQLStatement) == 0)
+ return TRUE;
+ else
+ return FALSE;
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ DatabaseQuery++;
+ sprintf (SQLStatement, "SELECT DISTINCT %s FROM %s",
+ Columns, Table);
+ if ( Where ) if ( Where[0] != '\0' ) // Add second if for DARWIN
+ {
+ strcat ( SQLStatement, " WHERE " );
+ strcat ( SQLStatement, Where );
+ }
+ if ( Order ) if ( Order[0] != '\0' ) // Add second if for DARWIN
+ {
+ if ( strchr(Order, ',') )
+ {
+ strcat ( SQLStatement, " ORDER BY " );
+ strcat ( SQLStatement, Order );
+ }
+ else
+ {
+ strcat ( SQLStatement, " ORDER BY (" );
+ strcat ( SQLStatement, Order );
+ strcat ( SQLStatement, ")" );
+ }
+ }
+ if (MYSQLExec(SQLStatement, TRUE) == 0)
+ return TRUE;
+ else
+ return FALSE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ DatabaseQuery++;
+ sprintf (SQLStatement, "SELECT DISTINCT %s FROM %s",
+ Columns, Table);
+ if ( Where ) if ( Where[0] != '\0' ) // Add second if for DARWIN
+ {
+ strcat ( SQLStatement, " WHERE " );
+ strcat ( SQLStatement, Where );
+ }
+ if ( Order ) if ( Order[0] != '\0' ) // Add second if for DARWIN
+ {
+ if ( strchr(Order, ',') )
+ {
+ strcat ( SQLStatement, " ORDER BY " );
+ strcat ( SQLStatement, Order );
+ }
+ else
+ {
+ strcat ( SQLStatement, " ORDER BY (" );
+ strcat ( SQLStatement, Order );
+ strcat ( SQLStatement, ")" );
+ }
+ }
+ if (SQLITEExec(SQLStatement, TRUE) == 0)
+ return TRUE;
+ else
+ return FALSE;
+ }
+#endif
+
+#ifdef WIN32
+ NewStatement();
+ DatabaseQuery++;
+
+ sprintf (SQLStatement, "SELECT DISTINCT %s FROM %s",
+ Columns, Table);
+ if ( Where ) if ( Where[0] != '\0' )
+ {
+ strcat ( SQLStatement, " WHERE " );
+ strcat ( SQLStatement, Where );
+ }
+ if ( Order ) if ( Order[0] != '\0' )
+ {
+ if ( strchr(Order, ',') )
+ {
+ strcat ( SQLStatement, " ORDER BY " );
+ strcat ( SQLStatement, Order );
+ }
+ else
+ {
+ strcat ( SQLStatement, " ORDER BY (" );
+ strcat ( SQLStatement, Order );
+ strcat ( SQLStatement, ")" );
+ }
+ }
+
+ RetCode = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+ Mode = QUERY;
+ if ( (RetCode == SQL_SUCCESS) ||
+ (RetCode == SQL_SUCCESS_WITH_INFO) )
+ return ( TRUE );
+
+#ifdef DB_DEBUG
+ SystemDebug.printf("***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+
+#endif
+ return ( FALSE );
+ }
+
+BOOL Database :: AddRecord ( const char *Table,
+ const char *Columns,
+ const char *Values )
+ {
+
+ DatabaseAddRecord++;
+
+ if (DebugLevel>=4)
+ { SystemDebug.printf("Add to Table: %.1000s\n", Table);
+ SystemDebug.printf("Columns: %.1000s\n", Columns);
+ SystemDebug.printf("Values: %.1000s\n", Values);
+ }
+
+ if (db_type == DT_NULL)
+ {
+ return TRUE;
+ }
+
+ // built-in dbf support
+ if (dir[0])
+ { char tmp[512];
+ char cols[4096];
+ char *fields[MAXFIELDS];
+ int i, j, k, n, L;
+ char *p;
+ struct dbase_header *th;
+ int hfield=-1;
+
+ if (NumIndexing>0)
+ { OperatorConsole.printf("*** AddRecord: DbaseIII read only during indexing\n");
+ return FALSE;
+ }
+
+ memset(fields, 0, sizeof(fields));
+
+ strcpy(cols, Columns);
+ strlwr(cols);
+
+ strcpy(tmp, Table);
+ strcat(tmp, ".dbf");
+
+ for (i=0; i<20; i++)
+ { if (!dbase_handles[i]) continue;
+ th = dbase_handles[i];
+ p = strrchr(th->filename, PATHSEPCHAR);
+ if (!p) continue;
+ if (stricmp(p+1, tmp)==0)
+ { hfield = findhashfield(th);
+
+ for (j=0; j<th->fieldcount; j++)
+ { strcpy(tmp, th->fd[j].name);
+ strlwr(tmp);
+
+ p = strstr(cols, tmp); // match the column name
+ if (!p)
+ { if (strcmp(tmp, "imagepat")==0)
+ { p = strstr(cols, "patientid"); // match alternative column names
+ if (!p) p = strstr(cols, "seriespat");
+ }
+ else if (strcmp(tmp, "seriespat")==0)
+ { p = strstr(cols, "patientid"); // match alternative column names
+ if (!p) p = strstr(cols, "imagepat");
+ }
+ else if (strcmp(tmp, "patientid")==0)
+ { p = strstr(cols, "seriespat"); // match alternative column names
+ if (!p) p = strstr(cols, "imagepat");
+ }
+ }
+
+ if (p)
+ { int instring=0;
+ n = 0; for (k=0; k<p-cols; k++) if (cols[k]==',') n++;
+ L = strlen(Values);
+ for (k=0; k<L; k++)
+ { if (Values[k]=='\'') instring = !instring;
+ if (Values[k]==',' && instring==0) n--;
+ if (n==0)
+ { if (k==0) k--;
+ if (Values[k+1]==' ') k++;
+
+ if (OdbcUseEscapeStringConstants)
+ if ((Values[k+1]=='E' || Values[k+1]=='e') && Values[k+2]=='\'') k++;
+
+ if (Values[k+1]=='\'') k++;
+
+ strncpy(tmp, Values+k+1, 511);
+ tmp[511]=0;
+ p = strstr(tmp, "\',");
+ if (!p) p = strchr(tmp, ',');
+ if (!p) p = strchr(tmp, '\'');
+ if (p)*p=0;
+ fields[j] = strdup(tmp);
+ process_escapeValue(fields[j]);
+ break;
+ }
+ }
+ }
+ }
+
+ dbase_write(th, th->reccount, fields, 0);
+ UpdateIndex(th, th->reccount-1, hfield);
+
+ for (i=0; i<MAXFIELDS; i++) free(fields[i]);
+ return TRUE;
+ }
+ }
+ return FALSE;
+ }
+ // end built-in dbf support
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ sprintf ( SQLStatement, "INSERT INTO %s (%s) VALUES (%s)",
+ Table, Columns, Values );
+
+ if (PGSQLExec(SQLStatement) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed PGSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ sprintf ( SQLStatement, "INSERT INTO %s (%s) VALUES (%s)",
+ Table, Columns, Values );
+
+ if (MYSQLExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed MYSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ sprintf ( SQLStatement, "INSERT INTO %s (%s) VALUES (%s)",
+ Table, Columns, Values );
+
+ if (SQLITEExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLITEExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef WIN32
+ NewStatement();
+
+ sprintf ( SQLStatement, "INSERT INTO %s (%s) VALUES (%s)",
+ Table, Columns, Values );
+
+ RetCode = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+
+ if ( (RetCode == SQL_SUCCESS ) ||
+ (RetCode == SQL_SUCCESS_WITH_INFO) )
+ {
+ return ( TRUE );
+ }
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+
+#endif
+ return ( FALSE );
+ }
+
+BOOL Database :: DeleteRecord ( const char *Table,
+ const char *Where )
+ {
+
+ if (DebugLevel>=4)
+ { SystemDebug.printf("Delete Record Table: %.1000s\n", Table);
+ SystemDebug.printf("Where : %.1000s\n", Where);
+ }
+
+ DatabaseDeleteRecord++;
+
+ if (db_type == DT_NULL)
+ {
+ return TRUE;
+ }
+
+ // built-in dbf support
+ if (dir[0])
+ { char *fields[MAXFIELDS];
+
+ if (NumIndexing>0)
+ { OperatorConsole.printf("*** DeleteRecord: DbaseIII read only during indexing\n");
+ return FALSE;
+ }
+
+ memset(fields, 0, sizeof(fields));
+ Query(Table, "", Where, NULL);
+ NextRecord();
+ if (queryrecno>0) dbase_write(thq, queryrecno-1, fields, 1);
+ // leave index as is
+ return TRUE;
+ }
+ // end built-in dbf support
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ if ( Where ) if ( Where[0] != '\0' ) // Add second if for DARWIN
+ {
+ sprintf ( SQLStatement, "DELETE FROM %s WHERE %s",
+ Table, Where );
+ }
+ else
+ {
+ sprintf ( SQLStatement, "DELETE FROM %s",
+ Table );
+ }
+
+
+ if (PGSQLExec(SQLStatement) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed PGSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ if ( Where && Where[0] ) // Add second if for DARWIN
+ {
+ sprintf ( SQLStatement, "DELETE FROM %s WHERE %s",
+ Table, Where );
+ }
+ else
+ {
+ sprintf ( SQLStatement, "DELETE FROM %s",
+ Table );
+ }
+
+
+ if (MYSQLExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed MYSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ if ( Where && Where[0] ) // Add second if for DARWIN
+ {
+ sprintf ( SQLStatement, "DELETE FROM %s WHERE %s",
+ Table, Where );
+ }
+ else
+ {
+ sprintf ( SQLStatement, "DELETE FROM %s",
+ Table );
+ }
+
+
+ if (SQLITEExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLITEExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef WIN32
+ NewStatement();
+
+ if ( Where )
+ {
+ sprintf ( SQLStatement, "DELETE FROM %s WHERE %s",
+ Table, Where );
+ }
+ else
+ {
+ sprintf ( SQLStatement, "DELETE FROM %s",
+ Table );
+ }
+
+ RetCode = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+ if ( (RetCode == SQL_SUCCESS )||
+ (RetCode == SQL_SUCCESS_WITH_INFO) )
+ {
+ return ( TRUE );
+ }
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+
+#endif
+ return ( FALSE );
+ }
+
+
+BOOL Database :: BindField ( UWORD Column,
+ SWORD CTypeCode,
+ void *vPtr,
+ SDWORD vPtrLength,
+ SQLLEN *LengthNeeded )
+ {
+
+ if (db_type == DT_NULL)
+ {
+ *LengthNeeded = 4;
+ return TRUE;
+ }
+
+ // built-in dbf support (limited to simple single table queries)
+ if (dir[0])
+ { int i;
+ vPtrs[Column-1]=vPtr;
+ vPtrLengths[Column-1]=vPtrLength;
+ CTypeCodes[Column-1]=CTypeCode;
+ LengthNeededs[Column-1] = LengthNeeded;
+
+ switch(CTypeCodes[Column-1])
+ { case SQL_C_CHAR:
+ for (i=0; i<MAXFIELDS; i++)
+ { if (querycolumns[i]<0) continue;
+ if (querycolumns[i]==Column-1)
+ { *LengthNeeded = thq->fd[i].len;
+ return TRUE;
+ }
+ }
+ *LengthNeeded = 0; break;
+ case SQL_C_ULONG:
+ *LengthNeeded = 4; break;
+ default: return FALSE;
+ }
+ return TRUE;
+ }
+ // end built-in dbf support
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ if ((pgres == NULL) || (PQresultStatus(pgres)!=PGRES_TUPLES_OK))
+ return FALSE;
+
+ vPtrs[Column-1]=vPtr;
+ vPtrLengths[Column-1]=vPtrLength;
+ CTypeCodes[Column-1]=CTypeCode;
+ LengthNeededs[Column-1] = LengthNeeded;
+
+ switch(CTypeCodes[Column-1])
+ {
+ case SQL_C_CHAR:
+ *LengthNeeded = PQfmod(pgres,Column-1) -4 ;
+ break;
+ case SQL_C_ULONG:
+ *LengthNeeded = 4;
+ break;
+ default:
+ return FALSE;
+ }
+ return TRUE;
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ if ((res == NULL))
+ return FALSE;
+
+ vPtrs[Column-1]=vPtr;
+ vPtrLengths[Column-1]=vPtrLength;
+ CTypeCodes[Column-1]=CTypeCode;
+ LengthNeededs[Column-1] = LengthNeeded;
+
+ switch(CTypeCodes[Column-1])
+ {
+ case SQL_C_CHAR:
+ *LengthNeeded = mysql_fetch_field_direct(res, Column-1)->length;
+ break;
+ case SQL_C_ULONG:
+ *LengthNeeded = 4;
+ break;
+ default:
+ return FALSE;
+ }
+ return TRUE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ vPtrs[Column-1]=vPtr;
+ vPtrLengths[Column-1]=vPtrLength;
+ CTypeCodes[Column-1]=CTypeCode;
+ LengthNeededs[Column-1] = LengthNeeded;
+
+ switch(CTypeCodes[Column-1])
+ {
+ case SQL_C_CHAR:
+ *LengthNeeded = 256;
+ break;
+ case SQL_C_ULONG:
+ *LengthNeeded = 4;
+ break;
+ default:
+ return FALSE;
+ }
+ return TRUE;
+ }
+#endif
+
+#ifdef WIN32
+ if ( ! hStmt )
+ return ( FALSE );
+ if ( Mode == QUERY )
+ {
+ RetCode = SQLBindCol ( hStmt,
+ Column,
+ CTypeCode,
+ vPtr,
+ vPtrLength,
+ LengthNeeded );
+ if ( (RetCode != SQL_SUCCESS ) &&
+ (RetCode != SQL_SUCCESS_WITH_INFO ) )
+ {
+ SQLError (hEnv, hDbc, hStmt, (BYTE*)State, &NativeError,
+ (BYTE*)Msg, 512, &MsgL);
+#ifdef DB_DEBUG
+ SystemDebug.printf("***Failed to SQLBindCol()\n");
+#endif
+ return ( FALSE );
+ }
+ return ( TRUE );
+ }
+ else if ( Mode == INSERT )
+ {
+ return ( FALSE );
+ }
+ else
+ {
+#ifdef DB_DEBUG
+ SystemDebug.printf("***Mode not Query / Insert\n");
+#endif
+ return ( FALSE );
+ }
+#else
+ return FALSE;
+#endif
+ }
+
+BOOL Database :: NextRecord ()
+ {
+
+ DatabaseNextRecord++;
+
+ if (db_type == DT_NULL)
+ {
+ return FALSE;
+ }
+
+ // built-in dbf support
+ if (dir[0])
+ { char *strings[MAXFIELDS];
+ int i, n, indexval=0, usehash=0;
+ char *qf[MAXFIELDS];
+ int t = GetTickCount();
+
+ if (hashfield>=0 && querymodes[hashfield]==2 && queryfields[hashfield])
+ indexval = hash_id(queryfields[hashfield], 0);
+
+ // use index for any query from record 0 that contains a index field
+
+ if (queryrecno==0 && hashfield>=0 && queryfields[hashfield])
+ { queryrecno = usehash = search_hash(queryfields[hashfield], thq->n + (querymodes[hashfield]<<8));
+//OperatorConsole.printf("Hashing found record in db %s: %d\n", thq->filename, queryrecno);
+
+ // finish the query from index position
+ if (queryrecno)
+ dbase_query(thq, &queryrecno, queryfields, querymodes, indexval);
+
+ else
+ { // perform partial query, hash it, and finish the full query
+ memset(qf, 0, MAXFIELDS * sizeof(void *));
+ qf[hashfield] = queryfields[hashfield];
+ dbase_query(thq, &queryrecno, qf, querymodes, indexval);
+ if (queryrecno>=0)
+ { enter_hash(qf[hashfield], thq->n + (querymodes[hashfield]<<8), queryrecno);
+ // OperatorConsole.printf("hashing entered record in db %s: %d\n", thq->filename, queryrecno);
+
+ // finish the full query from the partial query
+ dbase_query(thq, &queryrecno, queryfields, querymodes, indexval);
+ }
+ }
+ }
+ else
+ dbase_query(thq, &queryrecno, queryfields, querymodes, indexval);
+
+ t = GetTickCount() - t;
+ QueryTime += t;
+
+ if (t>LongQueryDBF)
+ { char f[512], g[30];
+ strcpy(f, "(fields:");
+
+ for (i=0; i<MAXFIELDS; i++)
+ { if (queryfields[i])
+ { switch(querymodes[i])
+ { case 2: if (hashfield==i) sprintf(g, " %d-indexed;", i);
+ else sprintf(g, " %d-exact;", i);
+ break;
+ case 3: sprintf(g, " %d-substring;", i); break;
+ case 11: sprintf(g, " %d-starting;", i); break;
+ case 16: sprintf(g, " %d->=;", i); break;
+ case 32: sprintf(g, " %d-<=;", i); break;
+ case 48: sprintf(g, " %d-range;", i); break;
+ case 66: sprintf(g, " %d-multiple;", i); break;
+ default: sprintf(g, " %d-unknown;", i); break;
+ }
+ strcat(f, g);
+ }
+ }
+ strcat(f, ")");
+
+ if (!IndexDBF && usehash)
+ OperatorConsole.printf("Hashed query in %s %s took long: %d ms\n", thq->filename, f, t);
+ else if (IndexDBF && (indexval || usehash))
+ OperatorConsole.printf("Indexed query in %s %s took long: %d ms\n", thq->filename, f, t);
+ else
+ OperatorConsole.printf("Normal query in %s %s took long: %d ms\n", thq->filename, f, t);
+ }
+
+ if (queryrecno<0) return FALSE;
+
+ memset(strings, 0, sizeof(strings));
+ dbase_read(thq, queryrecno, strings);
+ queryrecno++;
+ for (i=0; i<MAXFIELDS; i++)
+ { if (!strings[i]) break;
+ if (querycolumns[i]<0) continue;
+ n = querycolumns[i];
+ switch(CTypeCodes[n])
+ { case SQL_C_CHAR: strcpy((char *)(vPtrs[n]), strings[i]); *LengthNeededs[n] = strlen(strings[i]); break;
+ case SQL_C_ULONG: *(unsigned int *)(vPtrs[n]) = atol(strings[i]); *LengthNeededs[n]=4; break;
+ default: break; // ignored : error in dbsql+1, first bind row not set !!
+ }
+ }
+ return TRUE;
+ }
+ // end built-in dbf support
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ int i;
+ if ((pgres == NULL) || (PQresultStatus(pgres)!=PGRES_TUPLES_OK))
+ return FALSE;
+ if (current_tuple >= ntuples) //already processed last record
+ return FALSE;
+ for(i=0;i<ncolumns;i++)
+ {
+ switch (CTypeCodes[i])
+ {
+ case SQL_C_CHAR:
+ strcpy((char *)(vPtrs[i]),PQgetvalue(pgres,current_tuple,i));
+ *LengthNeededs[i] = PQgetlength(pgres,current_tuple,i);
+ break;
+ case SQL_C_ULONG:
+ *(unsigned int *)(vPtrs[i]) = atol(PQgetvalue(pgres,current_tuple,i));
+ *LengthNeededs[i] = 4;
+ break;
+ default:
+ break;
+ }
+ }
+ current_tuple++;
+ return TRUE;
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ int i;
+ MYSQL_ROW row ;
+ unsigned long *lengths;
+
+ if ((res == NULL))
+ return FALSE;
+ if (current_tuple >= ntuples) //already processed last record
+ return FALSE;
+ row = mysql_fetch_row( res );
+ if (!row)
+ return FALSE;
+
+ lengths = mysql_fetch_lengths(res);
+
+ for(i=0;i<ncolumns;i++)
+ {
+ if(row[i]) //Steini 20050507
+ switch (CTypeCodes[i])
+ {
+ case SQL_C_CHAR:
+ strcpy((char *)(vPtrs[i]),row[i]);
+ *LengthNeededs[i] = lengths[i]; // strlen(row[i]);
+ break;
+ case SQL_C_ULONG:
+ *(unsigned int *)(vPtrs[i]) = atol(row[i]);
+ *LengthNeededs[i] = 4;
+ break;
+ default:
+ break;
+ }
+ else
+ switch (CTypeCodes[i])
+ {
+ case SQL_C_CHAR:
+ strcpy((char *)(vPtrs[i]),"");
+ *LengthNeededs[i] = 0;
+ break;
+ case SQL_C_ULONG:
+ *(unsigned int *)(vPtrs[i]) = 0;
+ *LengthNeededs[i] = 4;
+ break;
+ default:
+ break;
+ }
+ }
+ current_tuple++;
+ return TRUE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ int i;
+ unsigned long *lengths;
+
+ if ((resultp == NULL))
+ return FALSE;
+ if (current_tuple >= ntuples) //already processed last record
+ {
+ if (resultp) sqlite3_free_table(resultp);
+ resultp = NULL;
+ return FALSE;
+ }
+
+ for(i=0;i<ncolumns;i++)
+ { switch (CTypeCodes[i])
+ {
+ case SQL_C_CHAR:
+ if (resultp[(current_tuple+1)*ncolumns+i])
+ { strncpy((char *)(vPtrs[i]), resultp[(current_tuple+1)*ncolumns+i], vPtrLengths[i]);
+ ((char *)(vPtrs[i]))[vPtrLengths[i]-1]=0;
+ }
+ else
+ ((char *)(vPtrs[i]))[0] = 0;
+ *LengthNeededs[i] = strlen((char *)(vPtrs[i]));
+ break;
+ case SQL_C_ULONG:
+ if (resultp[(current_tuple+1)*ncolumns+i])
+ *(unsigned int *)(vPtrs[i]) = atol(resultp[(current_tuple+1)*ncolumns+i]);
+ else
+ *(unsigned int *)(vPtrs[i]) = 0;
+ *LengthNeededs[i] = 4;
+ break;
+ default:
+ break;
+ }
+ }
+ current_tuple++;
+ return TRUE;
+ }
+#endif
+
+#ifdef WIN32
+ if ( ! hStmt )
+ return ( FALSE );
+ RetCode = SQLFetch ( hStmt );
+
+ if ((RetCode != SQL_SUCCESS ) &&
+ (RetCode != SQL_SUCCESS_WITH_INFO ) )
+ {
+ SQLError (hEnv, hDbc, hStmt, (BYTE*)State, &NativeError,
+ (BYTE*)Msg, 512, &MsgL);
+#ifdef DB_DEBUG
+// SystemDebug.printf("Failed to SQLFetch() : %d\n", RetCode);
+// (This is not a real failure, just reached last record)
+#endif
+// PrintLastError();
+ return ( FALSE );
+ }
+ return ( TRUE );
+#else
+ return ( FALSE );
+#endif
+ }
+
+BOOL Database :: CreateTable (
+ const char *Table,
+ const char *Columns )
+ {
+
+ if (DebugLevel>=4)
+ { SystemDebug.printf("Create Table: %.1000s\n", Table);
+ SystemDebug.printf("Columns : %.1000s\n", Columns);
+ }
+
+ DatabaseCreateTable++;
+
+ if (db_type == DT_NULL)
+ {
+ return TRUE;
+ }
+
+ // built-in dbf support
+ if (dir[0])
+ { char filename[1024];
+ char temp[8192];
+ char *fielddata[MAXFIELDS];
+ char *p, *q, *r;
+ int i, f=0, n;
+
+ strcpy(temp, Columns);
+ memset(fielddata, 0, sizeof(fielddata));
+
+ p = temp;
+ while (p)
+ { q = strchr(p, ',');
+ if (q) *q=0;
+ fielddata[f] = (char *)malloc(256);
+ r = p; while(*r==' ')r++; strncpy(fielddata[f], r, 255); fielddata[f][255]=0;
+ r = strstr(fielddata[f], " int");
+ if (r)
+ { strcpy(r, ":C10");
+ }
+ else
+ { r = strchr(fielddata[f], '(');
+ if (r) n = atoi(r+1); else n = 255;
+
+ r = strstr(fielddata[f], " varchar");
+ if (!r) r = strstr(fielddata[f], " char");
+ if (r) *r = 0;
+ sprintf(r, ":C%d", n);
+ }
+
+ if (q) p = q+1; else p = NULL;
+ f++;
+ }
+
+ strcpy(filename, dir);
+ strcat(filename, Table);
+ strcat(filename, ".DBF");
+
+ for(i=0; i<20; i++)
+ { if (dbase_handles[i])
+ { if (stricmp(filename, dbase_handles[i]->filename)==0)
+ { dbase_close(dbase_handles[i]); dbase_handles[i]=NULL;
+ dbase_create(filename, fielddata, &dbase_handles[i]);
+ for (int j=0; j<MAXFIELDS; j++) free(fielddata[j]);
+// if (Indices[i]) /* clear in-memory index if any */
+// IndicesCount[i]=0;
+ return TRUE;
+ }
+ }
+ }
+ for(i=0; i<20; i++)
+ { if (!dbase_handles[i])
+ { dbase_create(filename, fielddata, &dbase_handles[i]);
+ for (int j=0; j<MAXFIELDS; j++) free(fielddata[j]);
+ dbase_handles[i]->n = i;
+// if (Indices[i]) /* clear in-memory index if any */
+// IndicesCount[i]=0;
+ return TRUE;
+ }
+ }
+ return FALSE;
+ }
+ // end built-in dbf support
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ sprintf (SQLStatement, "CREATE TABLE %s (%s)",
+ Table, Columns );
+
+
+ if (PGSQLExec(SQLStatement) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed PGSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ sprintf (SQLStatement, "CREATE TABLE %s (%s)",
+ Table, Columns );
+
+ if (MYSQLExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed MYSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ sprintf (SQLStatement, "CREATE TABLE %s (%s)",
+ Table, Columns );
+
+ if (SQLITEExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLITEExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef WIN32
+ NewStatement();
+ sprintf (SQLStatement, "CREATE TABLE %s (%s)",
+ Table, Columns );
+
+ RetCode = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+
+ if ( (RetCode == SQL_SUCCESS) ||
+ (RetCode == SQL_SUCCESS_WITH_INFO) )
+ {
+ return ( TRUE );
+ }
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+
+#endif
+ return ( FALSE );
+ }
+
+BOOL Database :: CreateIndex (
+ const char *Table,
+ const char *Index,
+ const char *Column )
+ {
+
+ if (DebugLevel>=4)
+ { SystemDebug.printf("Create Index Table: %.1000s\n", Table);
+ SystemDebug.printf("Index : %.1000s\n", Index);
+ SystemDebug.printf("Column : %.1000s\n", Column);
+ }
+
+ if (db_type == DT_NULL)
+ {
+ return TRUE;
+ }
+
+ // ignored for built-in dbf support
+ if (dir[0])
+ return TRUE;
+ // end built-in dbf support
+
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ sprintf (SQLStatement, "CREATE INDEX %s ON %s (%s)",
+ Index, Table, Column );
+
+
+ if (PGSQLExec(SQLStatement) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed PGSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ sprintf (SQLStatement, "CREATE INDEX %s ON %s (%s)",
+ Index, Table, Column );
+
+
+ if (MYSQLExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed MYSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ sprintf (SQLStatement, "CREATE INDEX %s ON %s (%s)",
+ Index, Table, Column );
+
+ if (SQLITEExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLITEExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef WIN32
+ NewStatement();
+ sprintf (SQLStatement, "CREATE INDEX %s ON %s (%s)",
+ Index, Table, Column );
+
+ RetCode = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+
+ if ( (RetCode == SQL_SUCCESS) ||
+ (RetCode == SQL_SUCCESS_WITH_INFO) )
+ {
+ return ( TRUE );
+ }
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+
+#endif
+ return ( FALSE );
+ }
+
+BOOL Database :: CreateUniqueIndex (
+ char *Table,
+ char *Index,
+ const char *Column )
+ {
+
+ if (DebugLevel>=4)
+ { SystemDebug.printf("Create Unique Index Table: %.1000s\n", Table);
+ SystemDebug.printf("Index : %.1000s\n", Index);
+ SystemDebug.printf("Column : %.1000s\n", Column);
+ }
+
+ // ignored for built-in dbf support
+ if (dir[0])
+ return TRUE;
+ // end built-in dbf support
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ sprintf (SQLStatement, "CREATE UNIQUE INDEX %s ON %s (%s)",
+ Index, Table, Column );
+
+ if (PGSQLExec(SQLStatement) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed PGSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ sprintf (SQLStatement, "CREATE UNIQUE INDEX %s ON %s (%s)",
+ Index, Table, Column );
+
+ if (MYSQLExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed MYSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ sprintf (SQLStatement, "CREATE UNIQUE INDEX %s ON %s (%s)",
+ Index, Table, Column );
+
+ if (SQLITEExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLITEExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+
+#ifdef WIN32
+ NewStatement();
+ sprintf (SQLStatement, "CREATE UNIQUE INDEX %s ON %s (%s)",
+ Index, Table, Column );
+
+ RetCode = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+
+ if ( (RetCode == SQL_SUCCESS) ||
+ (RetCode == SQL_SUCCESS_WITH_INFO) )
+ {
+ return ( TRUE );
+ }
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+
+#endif
+ return ( FALSE );
+ }
+
+BOOL Database :: DeleteTable (
+ const char *Table )
+ {
+
+ if (db_type == DT_NULL)
+ {
+ return TRUE;
+ }
+
+ // built-in dbf support
+ if (dir[0])
+ {
+// file may be locked by several open DB
+// char filename[1024];
+// strcpy(filename, dir);
+// strcat(filename, Table);
+// strcat(filename, ".DBF");
+// unlink(filename);
+// strcpy(filename, dir);
+// strcat(filename, Table);
+// strcat(filename, ".dbf");
+// unlink(filename);
+ return TRUE;
+ }
+
+ // end built-in dbf support
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ sprintf(SQLStatement, "DROP TABLE %s",
+ Table);
+
+ if (PGSQLExec(SQLStatement) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed PGSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ sprintf(SQLStatement, "DROP TABLE %s",
+ Table);
+
+ if (MYSQLExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed MYSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ sprintf(SQLStatement, "DROP TABLE %s",
+ Table);
+
+ if (SQLITEExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLITEExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef WIN32
+ NewStatement();
+ sprintf(SQLStatement, "DROP TABLE %s",
+ Table);
+ RetCode = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+
+ if ( (RetCode == SQL_SUCCESS) ||
+ (RetCode == SQL_SUCCESS_WITH_INFO) )
+ {
+ return ( TRUE );
+ }
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+
+#endif
+ return ( FALSE );
+ }
+
+BOOL Database :: Exec (
+ const char *SQLStatement )
+ {
+
+ if (db_type == DT_NULL)
+ {
+ return TRUE;
+ }
+
+ // built-in dbf support
+ if (dir[0])
+ {
+ return FALSE;
+ }
+
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ if (PGSQLExec((char *)SQLStatement) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed PGSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ if (MYSQLExec((char *)SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed MYSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ if (SQLITEExec((char *)SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLITEExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef WIN32
+ NewStatement();
+ RetCode = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+
+ if ( (RetCode == SQL_SUCCESS) ||
+ (RetCode == SQL_SUCCESS_WITH_INFO) )
+ {
+ return ( TRUE );
+ }
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+
+#endif
+ return ( FALSE );
+ }
+
+BOOL Database :: UpdateRecords(
+ char *TableName,
+ char *Updates,
+ const char *Where)
+ {
+ if (Where==NULL) return FALSE;
+ if (strlen(Where)==0) return FALSE;
+
+ if (DebugLevel>=4)
+ { SystemDebug.printf("Update Table: %.1000s\n", TableName);
+ SystemDebug.printf("Updates : %.1000s\n", Updates);
+ SystemDebug.printf("Where : %.1000s\n", Where);
+ }
+
+ DatabaseUpdateRecords++;
+
+ if (db_type == DT_NULL)
+ {
+ return TRUE;
+ }
+
+ // built-in dbf support
+ if (dir[0])
+ { char *fields[MAXFIELDS];
+ int j;//, k;
+ char tmp[512];
+ char upds[8192];
+ char lupds[8192];
+ char *p;
+ int hfield=-1;
+
+ if (NumIndexing>0)
+ { OperatorConsole.printf("*** UpdateRecords: DbaseIII read only during indexing\n");
+ return FALSE;
+ }
+
+ memset(fields, 0, sizeof(fields));
+ strcpy(upds, Updates);
+ strcpy(lupds, Updates);
+ strlwr(lupds);
+
+ Query(TableName, "", Where, NULL);
+ NextRecord();
+ if (queryrecno>0)
+ { hfield = findhashfield(thq);
+
+ for (j=0; j<thq->fieldcount; j++)
+ { strcpy(tmp, thq->fd[j].name);
+ strlwr(tmp);
+
+ p = strstr(lupds, tmp); // match the fieldname
+ if (!p)
+ { if (strcmp(tmp, "imagepat")==0)
+ { p = strstr(lupds, "patientid"); // match alternative fieldnames
+ if (!p) p = strstr(lupds, "seriespat");
+ }
+ else if (strcmp(tmp, "seriespat")==0)
+ { p = strstr(lupds, "patientid"); // match alternative fieldnames
+ if (!p) p = strstr(lupds, "imagepat");
+ }
+ else if (strcmp(tmp, "patientid")==0)
+ { p = strstr(lupds, "seriespat"); // match alternative fieldnames
+ if (!p) p = strstr(lupds, "imagepat");
+ }
+ }
+
+ if (!p) continue;
+
+ strncpy(tmp, upds + (p-lupds) + strlen(tmp), 511); // get clause for this field
+ tmp[511]=0;
+
+ p = strstr(tmp, "\', "); // clause ends with ',
+ if (p==NULL) p = strstr(tmp, ", "); // or clause ends with ,
+ if (p==NULL) p = strrchr(tmp, '\''); // or clause ends with '
+ if (p) *p=0;
+
+ p = strstr(tmp, " = "); // value after ' = '
+ if (!p) continue;
+ p = p+3;
+
+ if (OdbcUseEscapeStringConstants)
+ if ((p[0]=='E' || p[0]=='e') && p[1]=='\'') p++;
+
+ if (*p=='\'') p++;
+ fields[j] = strdup(p);
+ process_escapeValue(fields[j]);
+ }
+ }
+
+ while (queryrecno>0)
+ // if (queryrecno>=0)
+ { dbase_write(thq, queryrecno-1, fields, 0);
+ UpdateIndex(thq, queryrecno-1, hfield);
+ NextRecord();
+ }
+ for (j=0; j<MAXFIELDS; j++) free(fields[j]);
+ return TRUE;
+ }
+ // end built-in dbf support
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ sprintf(SQLStatement, "UPDATE %s SET %s WHERE %s",
+ TableName, Updates, Where);
+
+ if (PGSQLExec(SQLStatement) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed PGSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ sprintf(SQLStatement, "UPDATE %s SET %s WHERE %s",
+ TableName, Updates, Where);
+
+ if (MYSQLExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed MYSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ sprintf(SQLStatement, "UPDATE %s SET %s WHERE %s",
+ TableName, Updates, Where);
+
+ if (SQLITEExec(SQLStatement, FALSE) == 0)
+ return TRUE;
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLITEExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+ return FALSE;
+ }
+#endif
+
+#ifdef WIN32
+ NewStatement();
+ sprintf(SQLStatement, "UPDATE %s SET %s WHERE %s",
+ TableName, Updates, Where);
+
+ RetCode = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+ if ( (RetCode == SQL_SUCCESS) ||
+ (RetCode == SQL_SUCCESS_WITH_INFO) )
+ {
+ return ( TRUE );
+ }
+#ifdef DB_DEBUG
+ SystemDebug.printf ( "***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+#endif
+
+#endif
+ return ( FALSE );
+ }
+
+BOOL Database :: ExtractRecords(
+ const char *TableName,
+ const char *Where,
+ char *Filename)
+ {
+ struct dbase_header *xhq;
+ int *records = (int *)malloc(100000 * sizeof(int));
+ int i, count = 0;
+
+ if (Where==NULL)
+ {
+ free(records);
+ return FALSE;
+ }
+
+ if (strlen(Where)==0)
+ {
+ free(records);
+ return FALSE;
+ }
+
+ // only for built-in dbf support
+ if (!dir[0])
+ {
+ free(records);
+ return FALSE;
+ }
+
+// if (db_type == DT_NULL)
+// {
+// free(records);
+// return TRUE;
+// }
+
+ if (DebugLevel>=4)
+ { SystemDebug.printf("Extract Records: %.1000s\n", TableName);
+ SystemDebug.printf("Where : %.1000s\n", Where);
+ SystemDebug.printf("Filename : %.1000s\n", Filename);
+ }
+
+ char *fields[MAXFIELDS];
+// int j;
+
+ memset(fields, 0, sizeof(fields));
+
+ Query(TableName, "", Where, NULL);
+ NextRecord();
+
+ xhq = dbase_dup(Filename, thq);
+ if (xhq==NULL) return FALSE;
+
+ while (queryrecno>0 && count<100000)
+ { records[count++] = queryrecno-1;
+ NextRecord();
+ }
+
+ for (i=0; i<count; i++)
+ { dbase_read(thq, records[i], fields);
+ dbase_write(xhq, i, fields, 0);
+ }
+
+ dbase_close(xhq);
+ free(records);
+ return TRUE;
+ }
+
+BOOL Database :: PrintLastError ()
+ {
+// SQLCHAR cState;
+// SQLINTEGER iNativeError;
+
+ /* The 'old' odbc interface */
+// SQLError (hEnv, hDbc, hStmt, (BYTE*)State, &NativeError,
+// (BYTE*)Msg, 512, &MsgL);
+ /* The 3.x odbc interface */
+// SQLGetDiagRec(
+// SQL_HANDLE_STMT,//SQLSMALLINT HandleType,
+// hStmt, //SQLHANDLE Handle,
+// 1, //SQLSMALLINT RecNumber,
+// &cState, //SQLCHAR *Sqlstate,
+// &iNativeError, //SQLINTEGER *NativeErrorPtr,
+// (BYTE*)Msg, //SQLCHAR *MessageText,
+// 512, //SQLSMALLINTBufferLength,
+// &MsgL); //SQLSMALLINT *TextLengthPtr);
+// OperatorConsole.printf("***Error: %d: %c: %s\n", iNativeError, cState, Msg);
+
+ /* SQLError is already called, so don't do it again.
+ Maybe these errors and the statements that caused them should be
+ printed to the operator console.
+ */
+
+ if (db_type == DT_NULL)
+ {
+ SystemDebug.printf("***Error: I fell into a black hole\n");
+ return TRUE;
+ }
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ SystemDebug.printf("***Error: %s\n",PQresultErrorMessage(pgres));
+ return TRUE;
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ SystemDebug.printf("***Error: %s\n", mysql_error(mydata));
+ return TRUE;
+ }
+#endif
+
+#ifdef USESQLITE
+ if (SqLite)
+ {
+ return TRUE;
+ }
+#endif
+
+#ifdef WIN32
+ SystemDebug.printf("***Error: %d: %s: %s\n", NativeError, State, Msg);
+#else
+ SystemDebug.printf("***DB error\n");
+#endif
+ return ( TRUE );
+ }
+
+SDWORD Database :: GetNativeError ()
+ {
+#ifdef WIN32
+ return (NativeError);
+#else
+ return 0;
+#endif
+ }
+
+
+BOOL Database :: CreateDatabase (
+ char *Name,
+ char *User,
+ char *lPassword )// Made Password local
+ {
+
+ if (DebugLevel>=4)
+ { SystemDebug.printf("Create Database: %s, user: %s, password: %s\n", Name, User, lPassword);
+ }
+
+ // ignored for built-in dbf support
+ if (dir[0])
+ return TRUE;
+ // end built-in dbf support
+
+
+ if (db_type == DT_NULL)
+ {
+ return TRUE;
+ }
+
+#ifdef POSTGRES
+ if (Postgres)
+ {
+ sprintf (SQLStatement, "CREATE ROLE %s LOGIN UNENCRYPTED PASSWORD '%s' VALID UNTIL 'infinity'", User, lPassword);
+ if (PGSQLExec(SQLStatement))
+ {
+ SystemDebug.printf ( "***Failed PGSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+ //return FALSE;
+ }
+ sprintf (SQLStatement, "CREATE DATABASE %s OWNER %s", Name, User);
+ if (PGSQLExec(SQLStatement))
+ {
+ SystemDebug.printf ( "***Failed PGSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+ return FALSE;
+ }
+ return TRUE;
+ }
+#endif
+
+#ifdef USEMYSQL
+ if (Mysql)
+ {
+ sprintf (SQLStatement, "CREATE DATABASE %s", Name);
+ if (MYSQLExec(SQLStatement, FALSE))
+ {
+ SystemDebug.printf ( "***Failed MYSQLExec : %.1000s\n", SQLStatement);
+ PrintLastError();
+ return FALSE;
+ }
+ return TRUE;
+ }
+#endif
+
+#ifdef WIN32
+ int i;
+ NewStatement();
+ sprintf (SQLStatement, "CREATE DATABASE %s", Name);
+
+ i = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+ if (i != SQL_SUCCESS_WITH_INFO && i != SQL_SUCCESS)
+ {
+ SystemDebug.printf ( "***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+ return FALSE;
+ }
+ NewStatement();
+ sprintf (SQLStatement, "exec sp_addlogin '%s','%s','%s'", User, lPassword, Name);
+ i = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+ if (i != SQL_SUCCESS_WITH_INFO && i != SQL_SUCCESS)
+ {
+ SystemDebug.printf ( "***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+ return FALSE;
+ }
+ NewStatement();
+ sprintf (SQLStatement, "use %s", Name);
+ i = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+ if (i != SQL_SUCCESS_WITH_INFO && i != SQL_SUCCESS)
+ {
+ SystemDebug.printf ( "***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+ return FALSE;
+ }
+ sprintf (SQLStatement, "exec sp_changedbowner '%s'", User);
+ i = SQLExecDirectWithRetry ( hStmt, (unsigned char *) SQLStatement, SQL_NTS );
+ if (i != SQL_SUCCESS_WITH_INFO && i != SQL_SUCCESS)
+ {
+ SystemDebug.printf ( "***Failed SQLExecDirect : %.1000s\n", SQLStatement);
+ PrintLastError();
+ return FALSE;
+ }
+ return TRUE;
+#else
+ return FALSE;// Added for warning gcc4.2 bcb
+#endif
+ }
+
+
+#ifdef DB_MAIN
+
+int
+main()
+ {
+
+ Database DB;
+ SDWORD DBNameLength;
+ char DBName [ 128 ];
+
+ if (!DB.Open ("LABRAD2", "Administrator", "password", "localhost" ))
+ {
+ printf ("***Could not open datasource\n");
+ return (1);
+ }
+/*f(!DB.QueryTables ( NULL, NULL, NULL, NULL ))
+ {
+ printf("Could not QueryTables\n");
+ return(2);
+ }
+ */
+ if(!DB.Query ( "DCMGate", "PatientName" ))
+ {
+ printf("***Could not perform Query\n");
+ return(2);
+ }
+ if(!DB.BindField (1, SQL_C_CHAR, &DBName, 128, &DBNameLength))
+ {
+ printf("***Could not bind field\n");
+ return ( 4 );
+ }
+
+ while(DB.NextRecord () )
+ {
+ printf("Database: %s\n", DBName);
+ }
+
+ sprintf(DBName, "PatientName = \"Test Record #2\"");
+ //DB.Add("DCMGate", "PatientName, ObjectFile", DBName);
+ DB.Delete("DCMGate", DBName);
+ DB.PrintLastError();
+ DB.Close();
+ return ( 0 );
+ }
+#endif
+
diff --git a/odbci.hpp b/odbci.hpp
new file mode 100644
index 0000000..c58e574
--- /dev/null
+++ b/odbci.hpp
@@ -0,0 +1,401 @@
+/*
+19990827 mvh Added CreateIndex
+20001128 ljz Added CRITICAL_SECTION member of 'Database'
+20020415 mvh Added error info, GetNativeError, SQLExecDirectWithRetry and CreateUniqueIndex
+20021020 mvh Added built-in dbf support (for stable operation without ODBC)
+ Note: requires de-normalized database
+20030120 ljz Ignore Micro$oft complaint C4200
+20030321 ljz Enlarged buffer for SqlErrorMessages (Database->Msg)
+20030819 mvh Allow longer filenames
+20040528 mvh Added ExtractRecords (dbase III only)
+20040530 mvh Added InternalQuery (for converting normal to indexed queries)
+20040605 mvh Made lockstart __int64
+20040612 mvh Made lockstart in again - now pure record#; added TotalRec, MBExtra
+20041003 mvh Statement length set to 310 kb (see dbsql.cpp for explanation)
+20041013 mvh Malloc SQLStatement instead
+20050109 mvh Adapted for linux compile
+20050905 mvh Postgres code by Piotr Filipczuk checked by mvh, will not affect other operations
+20060219 mvh Start on native mysql driver
+20060220 mvh Include all required mysql defines here
+20060226 mvh Runtime load MYSQL in WIN32
+20060628 mvh Use mysql.h proper (for datastructures) even when runtime loading (sorry for the hard include path)
+20060701 mvh Added mysql_fetch_lengths
+20070206 mvh Added CreateDatabase
+20070218 mvh Added SqLite
+20070307 mvh Made database type local, added Database(type) creator
+20070705 mvh Added DT_DBASEIIINOINDEX: disables indexing and packing
+ Extented max number of dbf files to 20
+20071115 mvh Static mysql use <mysql.h>
+20071118 mvh Adapted for 64 bits (use SQLLEN for BindField)
+20080107 mvh Removed double declaration of SQLLEN
+20080821 mvh Fix for SUNWspro compiler
+20081116 mvh Adapted for 64 bits linux (avoid use of "long")
+20081117 mvh Allow compile with both POSTGRES and USEMYSQL
+20081119 mvh added run-time loading of postgres for WIN32
+20081120 mvh Finished it
+20081124 mvh Added DT_NULL
+20090114 mvh Increased MAXFIELDS to 100 for clone_xvi
+20091231 bcb Changed char* to const char* for gcc4.2 warnings
+20100111 mvh Merged
+20100619 bcb Added no-copy to the Database class.
+20100717 mvh Merged
+20110502 mvh Added db:Exec
+*/
+
+
+
+// ODBC Interface class.
+#ifndef _ODBCI_H_
+# define _ODBCI_H_
+
+#ifdef WIN32
+# include <stdio.h>
+# include <windows.h>
+# include <sql.h>
+# include <sqlext.h>
+#else
+# include "wintypes.hpp"
+# include "pthread.h"
+# define CRITICAL_SECTION pthread_mutex_t
+#endif
+
+#ifdef POSTGRES
+# include "libpq-fe.h"
+#endif
+
+/////////////////////////////////////////////////////////////////////////
+
+#ifdef USEMYSQL
+
+#ifdef WIN32 /* load mysql dynamically */
+extern "C"
+{
+#include "C:\mysql-5.0.22-win32\include\mysql.h"
+
+ typedef void (STDCALL *_mysql_close)(MYSQL *sock);
+ typedef MYSQL *(STDCALL *_mysql_init)(MYSQL *mysql);
+ typedef MYSQL *(STDCALL *_mysql_real_connect)(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db,
+ unsigned int port, const char *unix_socket, unsigned long clientflag);
+ typedef int (STDCALL *_mysql_select_db)(MYSQL *mysql, const char *db);
+ typedef void (STDCALL *_mysql_free_result)(MYSQL_RES *result);
+ typedef int (STDCALL *_mysql_query)(MYSQL *mysql, const char *q);
+ typedef MYSQL_RES *(STDCALL *_mysql_store_result)(MYSQL *mysql);
+ typedef my_ulonglong (STDCALL *_mysql_num_rows)(MYSQL_RES *res);
+ typedef unsigned int (STDCALL *_mysql_num_fields)(MYSQL_RES *res);
+ typedef MYSQL_ROW (STDCALL *_mysql_fetch_row)(MYSQL_RES *result);
+ typedef const char * (STDCALL *_mysql_error)(MYSQL *mysql);
+ typedef MYSQL_FIELD *(STDCALL *_mysql_fetch_field_direct)(MYSQL_RES *res, unsigned int fieldnr);
+ typedef unsigned long *(STDCALL *_mysql_fetch_lengths)(MYSQL_RES *result);
+
+ extern _mysql_close __mysql_close;
+ extern _mysql_init __mysql_init;
+ extern _mysql_real_connect __mysql_real_connect;
+ extern _mysql_select_db __mysql_select_db;
+ extern _mysql_free_result __mysql_free_result;
+ extern _mysql_query __mysql_query;
+ extern _mysql_store_result __mysql_store_result;
+ extern _mysql_num_rows __mysql_num_rows;
+ extern _mysql_num_fields __mysql_num_fields;
+ extern _mysql_fetch_row __mysql_fetch_row;
+ extern _mysql_error __mysql_error;
+ extern _mysql_fetch_field_direct __mysql_fetch_field_direct;
+ extern _mysql_fetch_lengths __mysql_fetch_lengths;
+
+#define mysql_close __mysql_close
+#define mysql_init __mysql_init
+#define mysql_real_connect __mysql_real_connect
+#define mysql_select_db __mysql_select_db
+#define mysql_free_result __mysql_free_result
+#define mysql_query __mysql_query
+#define mysql_store_result __mysql_store_result
+#define mysql_num_rows __mysql_num_rows
+#define mysql_num_fields __mysql_num_fields
+#define mysql_fetch_row __mysql_fetch_row
+#define mysql_error __mysql_error
+#define mysql_fetch_field_direct __mysql_fetch_field_direct
+#define mysql_fetch_lengths __mysql_fetch_lengths
+}
+#else /* load mysql in a static way */
+# include <mysql.h>
+#endif
+
+#endif
+
+#ifdef POSTGRES
+
+#ifdef WIN32 /* load postgres dynamically */
+extern "C"
+{
+#define PGCALL
+typedef void (PGCALL *_PQfinish)(PGconn *conn);
+typedef ConnStatusType (PGCALL *_PQstatus)(const PGconn *conn);
+typedef PGconn *(PGCALL *_PQsetdbLogin)(const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty,
+ const char *dbName, const char *login, const char *pwd);
+typedef void (PGCALL *_PQclear)(PGresult *res);
+typedef PGresult *(PGCALL *_PQexec)(PGconn *conn, const char *query);
+typedef ExecStatusType (PGCALL *_PQresultStatus)(const PGresult *res);
+typedef int (PGCALL *_PQntuples)(const PGresult *res);
+typedef int (PGCALL *_PQnfields)(const PGresult *res);
+typedef int (PGCALL *_PQfmod)(const PGresult *res, int field_num);
+typedef char *(PGCALL *_PQgetvalue)(const PGresult *res, int tup_num, int field_num);
+typedef int (PGCALL *_PQgetlength)(const PGresult *res, int tup_num, int field_num);
+typedef char *(PGCALL *_PQresultErrorMessage)(const PGresult *res);
+typedef char *(PGCALL *_PQerrorMessage)(const PGconn *con);
+}
+
+extern _PQfinish __PQfinish;
+extern _PQstatus __PQstatus;
+extern _PQsetdbLogin __PQsetdbLogin;
+extern _PQclear __PQclear;
+extern _PQexec __PQexec;
+extern _PQresultStatus __PQresultStatus;
+extern _PQntuples __PQntuples;
+extern _PQnfields __PQnfields;
+extern _PQfmod __PQfmod;
+extern _PQgetvalue __PQgetvalue;
+extern _PQgetlength __PQgetlength;
+extern _PQresultErrorMessage __PQresultErrorMessage;
+extern _PQerrorMessage __PQerrorMessage;
+
+#define PQfinish __PQfinish
+#define PQstatus __PQstatus
+#define PQsetdbLogin __PQsetdbLogin
+#define PQclear __PQclear
+#define PQexec __PQexec
+#define PQresultStatus __PQresultStatus
+#define PQntuples __PQntuples
+#define PQnfields __PQnfields
+#define PQfmod __PQfmod
+#define PQgetvalue __PQgetvalue
+#define PQgetlength __PQgetlength
+#define PQresultErrorMessage __PQresultErrorMessage
+#define PQerrorMessage __PQerrorMessage
+
+#endif
+#endif
+
+/////////////////////////////////////////////////////////////////////////
+
+// for built-in dbase support
+
+/* The array size as it must be declared for a flexible array member of a struct. */
+#ifdef SOLARIS
+# define DECLARED_FLEXIBLE_ARRAY_SIZE 1
+#else
+#ifdef __GNUC__
+# define DECLARED_FLEXIBLE_ARRAY_SIZE 0
+#else
+# define DECLARED_FLEXIBLE_ARRAY_SIZE /* as nothing */
+#ifdef _MSC_VER
+/*warning C4200: nonstandard extension used : zero-sized array in ...*/
+#pragma warning( disable : 4200 )
+#endif
+#endif
+#endif
+
+struct field_descriptor
+{ char name[11]; /* should be zero terminated */
+ char type;
+ char junk1[4];
+ unsigned char len;
+ unsigned char deccount;
+ char junk2[14];
+};
+
+struct dbase_header
+{ int filehandle; /* info calculated at dbopen */
+ int currentrecord;
+ int recordlength;
+ int headerlength;
+ int fieldcount;
+ int touched;
+ int lockstart; /* added for file locking */
+ int lockcount; /* lockcount = 0 for unlocked */
+ int sharemode; /* 1 if file opened for share */
+ int readonly; /* 1 if file opened read-only */
+ char *recordbuffer; /* added for record buffering */
+ int bufrecord; /* record number in buffer */
+ char *rawbuffer;
+ int rawrecord; /* idem in raw buffer */
+ char filename[1024]; /* check for duplicate opens */
+ int n; /* dbase number used for hashing */
+ int TotalRec; /* total records to divide MBExtra */
+ int MBExtra; /* extra MB allocated for index */
+
+ char junk1[4]; /* Dbase III file header format */
+ int reccount;
+ short int hlength; /* contains header/record length */
+ short int rlength;
+ char junk2[4];
+ int updatecount; /* multiuser ext. moved on 01-09-95 */
+ char junk3[8]; /* should contain zeros */
+ int oldupdatecount; /* old MBI30 multiuser extension */
+ struct field_descriptor fd[DECLARED_FLEXIBLE_ARRAY_SIZE];
+ /* we limit ourselves to 32 fields */
+};
+
+enum actmode {QUERY, EXTRACT};
+#define MAXFIELDS 100
+
+enum DBTYPE {DT_ODBC, DT_DBASEIII, DT_POSTGRES, DT_MYSQL, DT_SQLITE, DT_DBASEIIINOINDEX, DT_NULL};
+
+// end for built-in dbase support
+
+#ifndef _WIN64
+#ifndef SQLLEN
+#define SQLLEN SDWORD
+#endif
+#endif
+
+class Database
+ {
+ public:
+
+ enum DBTYPE db_type;
+
+#ifdef WIN32
+ HENV hEnv;
+ HDBC hDbc;
+ HSTMT hStmt;
+ UINT Mode;
+ SWORD MsgL;
+ SDWORD NativeError;
+ char State[256];
+ char Msg [512];
+#endif
+
+#ifdef POSTGRES
+ PGconn *conn;
+ PGresult *pgres;
+#endif
+
+#ifdef USEMYSQL
+ MYSQL *mydata;
+ MYSQL_RES *res;
+#endif
+
+#ifdef USESQLITE
+ struct sqlite3 *sqlitedata;
+// void *sqlitedata;
+ char **resultp;
+#endif
+
+#ifdef POSTGRES
+ int Postgres;
+#endif
+#ifdef USEMYSQL
+ int Mysql;
+#endif
+#ifdef USESQLITE
+ int SqLite;
+#endif
+
+#if defined(POSTGRES) || defined(USEMYSQL) || defined (USESQLITE)
+ int ncolumns;
+ int ntuples;
+ int current_tuple;
+#endif
+
+ BOOL Connected;
+
+ // for built-in dbase support
+ struct dbase_header *dbase_handles[20];
+ int querymodes[MAXFIELDS];
+ char *queryfields[MAXFIELDS];
+ struct dbase_header *thq;
+ int queryrecno;
+ int querycolumns[MAXFIELDS];
+ void *vPtrs[MAXFIELDS];
+ SWORD CTypeCodes[MAXFIELDS];
+ SDWORD vPtrLengths[MAXFIELDS];
+ SQLLEN *LengthNeededs[MAXFIELDS];
+ char dir[1024];
+ int hashfield;
+ // end for built-in dbase support
+
+ private:
+ BOOL NewStatement ();
+ SDWORD GetNativeError ();
+
+ public:
+ CRITICAL_SECTION m_Critical;
+
+#ifdef WIN32
+ RETCODE RetCode;
+#endif
+ char *SQLStatement;
+
+ Database();
+ Database(enum DBTYPE db_type);
+
+ virtual ~Database();
+
+ virtual BOOL Open ( const char *Database, const char *User, const char *Password,
+ const char *Server = NULL);
+ // Server used in Sybase version, not here
+ virtual BOOL Close ();
+ virtual BOOL QueryTables ( char *SearchTableQualifier,
+ char *SearchTableOwner,
+ char *SearchTableName,
+ char *SearchTableType );
+
+ virtual BOOL BindField ( UWORD Column,
+ SWORD CTypeCode,
+ void *vPtr,
+ SDWORD vPtrLength,
+ SQLLEN *LengthNeeded );
+ virtual BOOL NextRecord ();
+ virtual BOOL PrintLastError ();
+#ifdef WIN32
+ virtual int SQLExecDirectWithRetry(SQLHSTMT StatementHandle, SQLCHAR *StatementText, SQLINTEGER TextLength);
+#endif
+#ifdef POSTGRES
+ virtual int PGSQLExec(char *StatementText);
+#endif
+#ifdef USEMYSQL
+ virtual int MYSQLExec(char *StatementText, BOOL q);
+#endif
+#ifdef USESQLITE
+ virtual int SQLITEExec(char *StatementText, BOOL q);
+#endif
+ virtual BOOL Query ( const char *Table,
+ const char *Columns,
+ const char *Where = NULL ,
+ const char *Order = NULL );
+ virtual BOOL InternalQuery ( const char *Table,
+ const char *Columns,
+ const char *Where = NULL ,
+ const char *Order = NULL ,
+ BOOL recurse = FALSE);
+ virtual BOOL QueryDistinct ( char *Table,
+ const char *Columns,
+ const char *Where = NULL ,
+ const char *Order = NULL );
+ virtual BOOL DeleteRecord ( const char *Table,
+ const char *Where );
+ virtual BOOL AddRecord ( const char *Table,
+ const char *Columns,
+ const char *Values );
+ virtual BOOL DeleteTable ( const char *Table );
+ virtual BOOL Exec ( const char *SQLStatement );
+ virtual BOOL CreateTable ( const char *TableName, const char *Columns );
+ virtual BOOL CreateIndex ( const char *Table, const char *Index, const char *Column );
+ virtual BOOL CreateUniqueIndex ( char *Table, char *Index, const char *Column );
+ virtual BOOL UpdateRecords ( char *TableName,
+ char *Updates,
+ const char *Where);
+ virtual BOOL ExtractRecords( const char *TableName,
+ const char *Where,
+ char *Filename);
+ virtual BOOL CreateDatabase (char *Name,
+ char *User,
+ char *Password);
+#ifdef __GNUC__
+ private:// This will prevent it from being copied (it has pointers)
+ Database(const Database&);
+ const Database & operator = (const Database&);
+#endif
+ };
+
+
+#endif
diff --git a/parse.cpp b/parse.cpp
new file mode 100644
index 0000000..7214af2
--- /dev/null
+++ b/parse.cpp
@@ -0,0 +1,390 @@
+/* 19980321 Mvh Added define TRUNCATEFIELDNAMES for DBF compatibity (apply in makefile) */
+/* 19980325 Mvh Added TruncateFieldNames entry in dicom.ini to allow DBF compatibility */
+/* 19980327 Mvh Added MaxFieldLength entry in dicom.ini to allow DBF compatibility */
+/* 20001105 mvh Renamed some enums and variables to allow compile in one big chunk */
+/* 20010713 mvh Renamed DT_UINTxx to DT_INTxx as temp fix for bug in LEX.CPP */
+/* 20010829 mvh Undone above change as LEX.CPP has been fixed by ljz */
+/* 20050107 mvh Added include file gpps for GetPrivateProfileString */
+/* 20050401 mvh Added WorkList Support */
+/* mvh 20050404: Added DT_START/ENDSEQUENCE to code sequence in WorkList table */
+/* mvh 20050902: Added HL7 column to be used for WorkList table */
+/* mvh 20050908: Fixed pointer error that crashed linux version */
+/* mvh 20080818: Added DT_MSTR */
+/* mvh 20100122: Hex2Dec incorrect for uppercase HEX numbers! */
+/* mvh 20100123: Added FL and FD types */
+/* mvh 20100125: GetPrivateProfileString -> MyGetPrivateProfileString */
+/* bcb 20100309: Changed int to unsigned. (gcc4.2 Warnings) */
+/* mvh 20100703: Merged */
+
+#ifndef WHEDGE
+# include "dgate.hpp"
+# include "lex.hpp"
+#else
+# include "master.h"
+#endif
+
+#include "gpps.hpp"
+
+enum
+ {
+ TK_SCOMMENT_ = 1,
+ TK_ECOMMENT_,
+ TK_PATIENT,
+ TK_STUDY,
+ TK_SERIES,
+ TK_IMAGE,
+ TK_WORKLIST,
+ TK_BOPEN,
+ TK_BCLOSE,
+ TK_COMMA,
+ TK_QT,
+ TK_SQL_C_CHAR,
+ TK_SQL_C_DATE,
+ TK_DT_STR,
+ TK_DT_MSTR,
+ TK_DT_DATE,
+ TK_DT_UINT16,
+ TK_DT_UINT32,
+ TK_DT_TIME,
+ TK_DT_UI,
+ TK_DT_FL,
+ TK_DT_FD,
+ TK_DT_STARTSEQUENCE,
+ TK_DT_ENDSEQUENCE
+ };
+
+TOKENSTRUCT G [] =
+ {
+ { TK_SCOMMENT_, "/*"},
+ { TK_ECOMMENT_, "*/" },
+ { TK_PATIENT, "*Patient*" },
+ { TK_STUDY, "*Study*" },
+ { TK_SERIES, "*Series*" },
+ { TK_IMAGE, "*Image*" },
+ { TK_WORKLIST, "*WorkList*" },
+ { TK_BOPEN, "{" },
+ { TK_BCLOSE, "}" },
+ { TK_COMMA, "," },
+ { TK_QT, "\"" },
+ { TK_SQL_C_CHAR, "SQL_C_CHAR" },
+ { TK_SQL_C_DATE, "SQL_C_DATE" },
+ { TK_DT_STR, "DT_STR" },
+ { TK_DT_MSTR, "DT_MSTR" },
+ { TK_DT_DATE, "DT_DATE" },
+ { TK_DT_UINT16, "DT_UINT16" },
+ { TK_DT_UINT32, "DT_UINT32" },
+ { TK_DT_TIME, "DT_TIME" },
+ { TK_DT_UI, "DT_UI" },
+ { TK_DT_FL, "DT_FL" },
+ { TK_DT_FD, "DT_FD" },
+ { TK_DT_STARTSEQUENCE, "DT_STARTSEQUENCE" },
+ { TK_DT_ENDSEQUENCE, "DT_ENDSEQUENCE" },
+ { 0, "\0" }
+ };
+
+
+static BOOL Parse ( Lex &,
+ Array < DBENTRY > *,
+ Array < DBENTRY > *,
+ Array < DBENTRY > *,
+ Array < DBENTRY > *,
+ Array < DBENTRY > *
+ );
+BOOL ParseComment ( Lex & );
+static BOOL ParseDB ( Lex &, Array < DBENTRY > *, BOOL HasHL7);
+static UINT16 ConvertNumber ( char *);
+static BOOL ConvertDB(DBENTRY **, Array < DBENTRY > * );
+
+#ifndef RootConfig
+extern char RootConfig[];
+#endif
+#ifndef ConfigFile
+extern char ConfigFile[];
+#endif
+
+static int TruncateFieldNamesP=0;
+static unsigned int MaxFieldLengthP=0;
+
+static
+void
+GetDBSpecials(void)
+ {
+ char RootSC[64];
+ char Temp[128];
+
+ MyGetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig,
+ (char*) RootSC, 64, ConfigFile);
+
+ MyGetPrivateProfileString ( RootSC, "TruncateFieldNames", "0",
+ (char*) Temp, 128, ConfigFile);
+ TruncateFieldNamesP = atoi(Temp);
+
+ MyGetPrivateProfileString ( RootSC, "MaxFieldLength", "0",
+ (char*) Temp, 128, ConfigFile);
+ MaxFieldLengthP = atoi(Temp);
+ }
+
+BOOL
+LoadKFactorFile(char *KFile)
+ {
+ Lex Lexxer;
+ Array < DBENTRY > ADBPatient, ADBStudy, ADBSeries, ADBImage, ADBWorkList;
+
+ GetDBSpecials();
+
+ if ( !Lexxer.Start(KFile, G) )
+ return ( FALSE );
+
+ if(!Parse ( Lexxer, &ADBPatient, &ADBStudy, &ADBSeries, &ADBImage, &ADBWorkList ))
+ return ( FALSE );
+
+ ConvertDB(&PatientDB, &ADBPatient);
+ ConvertDB(&StudyDB, &ADBStudy);
+ ConvertDB(&SeriesDB, &ADBSeries);
+ ConvertDB(&ImageDB, &ADBImage);
+ ConvertDB(&WorkListDB, &ADBWorkList);
+
+ return ( TRUE );
+
+ }
+
+static
+BOOL
+ConvertDB( DBENTRY **ppDBE, Array < DBENTRY > *ADB)
+ {
+ UINT Index;
+ DBENTRY DBE;
+
+ if(*ppDBE)
+ free(*ppDBE);
+
+ (*ppDBE) = (DBENTRY *)malloc(sizeof(DBENTRY) * (ADB->GetSize() + 2));
+
+ Index = 0;
+ while(Index < ADB->GetSize() )
+ {
+ (*ppDBE) [Index] = ADB->Get(Index);
+ ++Index;
+ }
+ DBE.Group = 0;
+ DBE.Element = 0;
+ memcpy((void *) (&(*ppDBE)[Index]), (void*) &DBE, sizeof(DBENTRY));
+ return ( TRUE );
+ }
+
+
+static
+BOOL Parse (
+ Lex &Lexxer,
+ Array < DBENTRY > *ADBPatient,
+ Array < DBENTRY > *ADBStudy,
+ Array < DBENTRY > *ADBSeries,
+ Array < DBENTRY > *ADBImage,
+ Array < DBENTRY > *ADBWorkList
+ )
+ {
+ TK Tk;
+
+ Lexxer.Get(&Tk);
+
+ while ( TRUE )
+ {
+ switch ( Lexxer.Peek(&Tk) )
+ {
+ case TK_SCOMMENT_:
+ ParseComment (Lexxer);
+ break;
+ case TK_PATIENT:
+ ParseDB(Lexxer, ADBPatient, FALSE);
+ break;
+ case TK_STUDY:
+ ParseDB(Lexxer, ADBStudy, FALSE);
+ break;
+ case TK_SERIES:
+ ParseDB(Lexxer, ADBSeries, FALSE);
+ break;
+ case TK_IMAGE:
+ ParseDB(Lexxer, ADBImage, FALSE);
+ break;
+ case TK_WORKLIST:
+ ParseDB(Lexxer, ADBWorkList, TRUE);
+ break;
+ case TOKEN_END:
+ return ( TRUE );
+ default:
+ fprintf ( stderr, "Parse error : Parse : %s\n",
+ Tk.Str);
+ return ( FALSE );
+ }
+ Lexxer.Get(&Tk);
+ }
+ return ( FALSE );
+ }
+
+BOOL
+ParseComment ( Lex &Lexxer )
+ {
+ TK Tk;
+
+ while ( Lexxer.Get(&Tk) != TK_ECOMMENT_ )
+ {
+ if(Tk.Value == TOKEN_END)
+ return ( FALSE );
+ }
+ return ( TRUE );
+ }
+
+static
+BOOL
+ParseDB(Lex &Lexxer, Array < DBENTRY > *DBName, BOOL HasHL7)
+ {
+ TK Tk, TKGroup, TKElement, TKColumn, TKLength, TKSQLType, TKDICOMType, TKHL7Tag;
+ DBENTRY DBE;
+
+ Lexxer.Get(&Tk);
+ if(Tk.Value!=TK_BOPEN)
+ {
+ fprintf(stderr, "Expected: Database { : %s\n", Tk.Str);
+ exit(1);
+ return ( FALSE );
+ }
+ Lexxer.Get(&Tk);
+ while ( Tk.Value == TK_BOPEN )
+ {
+ Lexxer.Get(&TKGroup);
+ Lexxer.Get(&Tk);
+ Lexxer.Get(&TKElement);
+ Lexxer.Get(&Tk);
+ Lexxer.Get(&Tk);
+ Lexxer.Get(&TKColumn);
+ Lexxer.Get(&Tk);
+ Lexxer.Get(&Tk);
+ Lexxer.Get(&TKLength);
+ Lexxer.Get(&Tk);
+ Lexxer.Get(&TKSQLType);
+ Lexxer.Get(&Tk);
+ Lexxer.Get(&TKDICOMType);
+ Lexxer.Get(&Tk);
+ if(HasHL7 && Tk.Value==TK_COMMA)
+ {
+ Lexxer.Get(&Tk);
+ Lexxer.Get(&TKHL7Tag);
+ Lexxer.Get(&Tk);
+ Lexxer.Get(&Tk);
+ }
+ if(Tk.Value!=TK_BCLOSE)
+ {
+ fprintf(stderr, "Expected { Group, Element, Column, Length, SQLType, DICOMType }\n");
+ fprintf(stderr, "Got { %s, %s, %s, %s, %s, %s }\n",
+ TKGroup.Str, TKElement.Str, TKColumn.Str,
+ TKLength.Str, TKSQLType.Str, TKDICOMType.Str);
+
+
+ exit(1);
+ return ( FALSE );
+ }
+ Lexxer.Get(&Tk);
+ if(Tk.Value == TK_COMMA)
+ Lexxer.Get(&Tk);
+
+ DBE.Group = ConvertNumber(TKGroup.Str);
+ DBE.Element = ConvertNumber(TKElement.Str);
+ strcpy(DBE.SQLColumn, TKColumn.Str);
+ if (HasHL7) strcpy(DBE.HL7Tag, TKHL7Tag.Str); else DBE.HL7Tag[0]=0;
+
+ if (TruncateFieldNamesP)
+ DBE.SQLColumn[TruncateFieldNamesP] = 0;
+
+ DBE.SQLLength = ConvertNumber(TKLength.Str);
+
+ if (MaxFieldLengthP)
+ if (DBE.SQLLength >= MaxFieldLengthP) DBE.SQLLength = MaxFieldLengthP;
+
+ if(TKSQLType.Value == TK_SQL_C_CHAR)
+ DBE.SQLType = SQL_C_CHAR;
+ else
+ if(TKSQLType.Value == TK_SQL_C_DATE)
+ DBE.SQLType = SQL_C_DATE;
+ else
+ {
+ fprintf(stderr, "Unknown SQL Type: %s\n", TKSQLType.Str);
+ exit(1);
+ }
+ if(TKDICOMType.Value == TK_DT_STR)
+ DBE.DICOMType = DT_STR;
+ else
+ if(TKDICOMType.Value == TK_DT_MSTR)
+ DBE.DICOMType = DT_MSTR;
+ else
+ if(TKDICOMType.Value == TK_DT_UI)
+ DBE.DICOMType = DT_UI;
+ else
+ if(TKDICOMType.Value == TK_DT_DATE)
+ DBE.DICOMType = DT_DATE;
+ else
+ if(TKDICOMType.Value == TK_DT_UINT16)
+ DBE.DICOMType = DT_UINT16;
+ else
+ if(TKDICOMType.Value == TK_DT_UINT32)
+ DBE.DICOMType = DT_UINT32;
+ else
+ if(TKDICOMType.Value == TK_DT_TIME)
+ DBE.DICOMType = DT_DATE; // yes, intentional
+ else
+ if(TKDICOMType.Value == TK_DT_FL)
+ DBE.DICOMType = DT_FL;
+ else
+ if(TKDICOMType.Value == TK_DT_FD)
+ DBE.DICOMType = DT_FD;
+ else
+ if(TKDICOMType.Value == TK_DT_STARTSEQUENCE)
+ DBE.DICOMType = DT_STARTSEQUENCE;
+ else
+ if(TKDICOMType.Value == TK_DT_ENDSEQUENCE)
+ DBE.DICOMType = DT_ENDSEQUENCE;
+ else
+ {
+ fprintf(stderr, "Unknown DICOM Type: %s\n", TKDICOMType.Str);
+ exit(1);
+ }
+ DBName->Add(DBE);
+ }
+ return ( TRUE );
+ }
+
+static
+UINT16
+Hex2Dec(char ch)
+ {
+ if((ch>='a')&&(ch<='f'))
+ return(ch-'a'+10);
+ if((ch>='A')&&(ch<='F'))
+ return(ch-'A'+10);
+ if((ch>='0')&&(ch<='9'))
+ return(ch-'0'+0);
+ return ( 0 );
+ }
+
+static
+UINT16
+ConvertNumber(char *s)
+ {
+ UINT16 Value;
+ int Index;
+
+ if(strlen(s)>2)
+ {
+ if((s[1] == 'x')||(s[1] == 'X'))
+ {
+ Value = 0;
+ Index = 2;
+ while(s[Index])
+ {
+ Value = (Value << 4) + Hex2Dec(s[Index]);
+ ++Index;
+ }
+ return ( Value );
+ }
+ }
+ return((UINT16)atoi(s));
+ }
diff --git a/pdata.cxx b/pdata.cxx
new file mode 100644
index 0000000..8b1ee0d
--- /dev/null
+++ b/pdata.cxx
@@ -0,0 +1,242 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+//20100619 bcb Fix gcc4 warnings, improve speed and made locals.
+//20100717 mvh Merged (note: locals means changes parameter names)
+//20130807 mvh Detect invalid Length returned to fix hanging thread issue
+// Fixed >0 check on UINT32
+
+# include "dicom.hpp"
+
+
+INT MemoryBuffer :: ReadBinary ( BYTE * lData, UINT Count )
+ {
+ INT RetVal;
+
+ if ( Index == Length )
+ return ( -1 ); // end
+ if((Length - Index)<Count )
+ {
+ memcpy((void*)lData, (void*)&this->Data[Index], Length - Index);
+ RetVal = (INT) Length - Index;
+ Index = Length;
+ return ( RetVal );
+ }
+ memcpy((void*)lData, (void*)&this->Data[Index], Count);
+ Index += Count;
+ return ( Count );
+ }
+
+BOOL MemoryBuffer :: SendBinary ( BYTE *, UINT )
+ {
+ return ( FALSE );
+ }
+
+MemoryBuffer :: MemoryBuffer (
+ BYTE *lData,
+ UINT lLength,
+ BOOL Destruct,
+ UINT lInEndian )
+#ifdef __GNUC__ //Faster with member initialization.
+:Data(lData),
+Length(lLength),
+Index(0),
+DestructFlag(Destruct)
+ {
+#else
+ {
+ Index = 0;
+ this->Length = lLength;
+ this->Data = lData;
+ DestructFlag = Destruct;
+#endif
+ SetIncomingEndian(lInEndian);
+
+ this->Index = lLength;
+ BufferSpace *aBS = new BufferSpace;
+ aBS->BufferSize = lLength;
+ aBS->isTemp = TRUE;
+ aBS->Data = lData;
+ InSize += lLength;
+ Incoming.Add(aBS);
+ }
+
+MemoryBuffer :: ~MemoryBuffer ()
+ {
+ if(DestructFlag)
+ if(Data)
+ delete Data;
+ }
+
+BOOL LinkedBuffer :: Fill(Buffer &Link, UINT Count)
+ {
+ LinkedTo = &Link;
+ return(Buffer :: Fill(Count));
+ }
+
+INT LinkedBuffer :: ReadBinary(BYTE *Data, UINT Count)
+ {
+ if(LinkedTo->Read(Data, Count))
+ return(Count);
+ return(-1);
+ }
+
+BOOL LinkedBuffer :: SendBinary(BYTE *Data, UINT Count)
+ {
+ LinkedTo->Write(Data, Count);
+ LinkedTo->Flush();
+ return ( TRUE );
+ }
+
+UINT LinkedBuffer :: GetOutgoingSize()
+ {
+ return(OutSize);
+ }
+
+
+UINT LinkedBuffer :: GetIncomingSize()
+ {
+ return(InSize);
+ }
+
+BOOL LinkedBuffer :: Flush(Buffer &Link, UINT Count)
+ {
+ LinkedTo = &Link;
+ return(Buffer :: Flush(Count));
+ }
+
+BOOL PDataTF :: ReadDynamic(Buffer &Link)
+ {
+ UINT32 Count;
+
+ if(!Length)
+ {
+ Link >> Reserved1;
+ Link >> Length;
+ }
+
+ //fprintf(stderr, "Reading P-DATA-TF: %d Length\n", Length);
+ Count = Length;
+ MsgStatus = 0; // continue
+
+ while ( (INT32)Count > 0) // (INT32) 20130807
+ {
+ Link >> pdv.Length;
+ if (pdv.Length > Count) return FALSE; // 20130807
+
+
+ Link >> pdv.PresentationContextID;
+ Link >> pdv.MsgHeader;
+ //fprintf(stderr, "Reading PDV: %d Length, %d ID, %x Header\n",
+ // pdv.Length, pdv.PresentationContextID, pdv.MsgHeader);
+ VRBuffer.Fill(Link, pdv.Length - 2);
+ //fprintf(stderr, "Finished reading PDV\n");
+ Count = Count - pdv.Length - sizeof(UINT32);
+ Length = Length - pdv.Length - sizeof(UINT32);
+ //fprintf(stderr, "Count = %d\n", Count);
+ if(IsThisTheLastFragment(pdv.MsgHeader))
+ {
+ MsgStatus = 1;
+ PresentationContextID = pdv.PresentationContextID;
+ return ( TRUE );
+ }
+ }
+ //fprintf(stderr, "done reading PDV's\n");
+ if(IsThisTheLastFragment(pdv.MsgHeader))
+ MsgStatus = 1;
+
+ PresentationContextID = pdv.PresentationContextID;
+
+ return ( TRUE );
+ }
+
+
+BOOL PDataTF :: Write(Buffer &Link)
+ {
+ // Generate P-DATA-TF Messages.
+ UINT BlockSize, SentSize, TotalSize, TLength;
+
+ TotalSize = VRBuffer.GetOutgoingSize();
+ BlockSize = 4096;
+ SentSize = 0;
+ TLength = Length;
+ while(SentSize < TotalSize)
+ {
+ if((TotalSize - SentSize) < BlockSize)
+ BlockSize = TotalSize - SentSize;
+ if((BlockSize + SentSize) == TotalSize)
+ // if(BlockSize)
+ MsgHeader = MsgHeader | 0x02;
+ else
+ MsgHeader = MsgHeader & 0x01;
+
+ pdv.PresentationContextID = PresentationContextID;
+ pdv.MsgHeader = MsgHeader;
+ pdv.Length = BlockSize + 2;
+ Length = pdv.Length + sizeof(UINT32);
+ ItemType = 0x04;
+ Reserved1 = 0;
+ Link << ItemType;
+ Link << Reserved1;
+ Link << Length;
+ Link << pdv.Length;
+ Link << pdv.PresentationContextID;
+ Link << MsgHeader;
+ if(BlockSize)
+ VRBuffer.Flush(Link, BlockSize);
+ SentSize += BlockSize;
+ Link.Flush();
+ }
+ Length = TLength;
+ return ( TRUE );
+ }
+
+PDataTF :: PDataTF()
+#ifdef __GNUC__ //Faster with member initialization.
+:ItemType(0x04),
+Reserved1(0),
+Length(0),
+VRBuffer(),
+MsgStatus(0),
+Endian(NATIVE_ENDIAN),
+pdv(),
+PresentationContextID(0),
+MsgHeader(0) {}
+#else
+ {
+ ItemType = 0x04;
+ Length = 0;
+ }
+#endif
+
+PDataTF :: ~PDataTF()
+ {
+
+ }
+
diff --git a/pdata.hpp b/pdata.hpp
new file mode 100644
index 0000000..0479de5
--- /dev/null
+++ b/pdata.hpp
@@ -0,0 +1,118 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/****************************************************************************
+ *
+ * Abstract Base Class for P-DATA Service
+ *
+ *
+ ****************************************************************************/
+
+/*20100619 bcb Added no-copy to the classes and init list to LinkedBuffer.
+ 20100717 mvh Merged
+*/
+
+class LinkedBuffer :
+ public Buffer
+ {
+ Buffer *LinkedTo;
+ public:
+#ifdef __GNUC__
+ LinkedBuffer():LinkedTo(NULL) {};
+#else
+ LinkedBuffer() { LinkedTo = NULL; };
+#endif
+ ~LinkedBuffer() { LinkedTo = NULL; };
+ BOOL Fill(Buffer &Link, UINT Count);
+ BOOL Flush(Buffer &Link, UINT Count);
+ UINT GetOutgoingSize();
+ UINT GetIncomingSize();
+ virtual INT ReadBinary(BYTE *Data, UINT Count);
+ virtual BOOL SendBinary(BYTE *Data, UINT Count);
+#ifdef __GNUC__
+ private:// This will prevent it from being copied (it has a pointer)
+ LinkedBuffer(const LinkedBuffer&);
+ const LinkedBuffer & operator = (const LinkedBuffer&);
+#endif
+ };
+
+class MemoryBuffer :
+ public LinkedBuffer
+ {
+ private:
+ BYTE *Data;
+ UINT Length;
+ UINT Index;
+ BOOL DestructFlag;
+ public:
+ INT ReadBinary(BYTE *Data, UINT Count);
+ BOOL SendBinary(BYTE *Data, UINT Count);
+ MemoryBuffer ( BYTE *Data, UINT Length, BOOL Destruct,
+ UINT Endian);
+ ~MemoryBuffer ();
+#ifdef __GNUC__
+ private:// This will prevent it from being copied (it has a pointer)
+ MemoryBuffer(const MemoryBuffer&);
+ const MemoryBuffer & operator = (const MemoryBuffer&);
+#endif
+ };
+
+
+class PDV
+ {
+ public:
+ UINT32 Length;
+ BYTE PresentationContextID;
+ BYTE MsgHeader;
+ };
+
+class PDataTF
+ {
+ private:
+ BYTE ItemType; // 0x04
+ BYTE Reserved1;
+ public:
+ UINT32 Length;
+ public:
+ LinkedBuffer VRBuffer;
+
+ public:
+ INT MsgStatus;
+ UINT Endian;
+ PDV pdv;
+ BYTE PresentationContextID;
+ BYTE MsgHeader;
+
+ BOOL ReadDynamic(Buffer &Link);
+ BOOL Write(Buffer &Link);
+
+ PDataTF();
+ virtual ~PDataTF();
+ };
+
diff --git a/pdu.cxx b/pdu.cxx
new file mode 100644
index 0000000..929c859
--- /dev/null
+++ b/pdu.cxx
@@ -0,0 +1,957 @@
+/*
+19980322 mvh blocked one remaining printf statement "comparing ..."
+19990202 ljz Added PDU memberfunction 'IsAbstractSyntaxAccepted'
+19990415 mvh Merged both versions
+20000322 ljz Fix in search for PresentationContext when identical
+ AbstractSyntaxes occur (e.g. GECT-scanner).
+ Do not break out of the inner loop in
+ PDU_Service::InterogateAAssociateAC.
+20000322 ljz+mvh Fix of PresentationContextID in PDV: in routines
+ PDU_Service::Write(DICOMObject*, UID*), set
+ PresentationContextID to TempByte, not to TempByte1.
+20000911 ljz Removed two warnings
+20020316 mvh Added GetLocalAddress and GetRemoteAddress
+20030306 ljz Fix: Huge bug in 'InterogateAAssociateRQ'
+20030424 ljz Blocked out obsolete PDU.Write(&DDO)
+ Some work on offering other TransferSyntaxes than
+ ImplicitLittleEndian when running in SCU mode
+ (Note: when running in SCP mode, 'dgatesop.lst' is used)
+ Fix: CommandObjects are always ImplicitLittleEndian
+20030627 mvh Fix for MSC4.2; re-enabled obsolete write calls for test.cxx
+20030710 ljz Adjusted test.cxx, and disabled obsolete calls again
+20080816 mvh ValidPresContexts is now a global: how many incoming connection can handle
+20090802 mvh Added DCM_ERROR_DEBUG statements to debug failed connect
+20100303 bcb Commented out unused variables (gcc4.2 Warnings)
+20100619 bcb Fix gcc4 warnings, improve speed.
+20100717 mvh Merged
+20100726 mvh bcb documented the mess in function AddAbstractSyntaxAlias
+20100728 bcb May have fixed AddAbstractSyntaxAlias, but I have no way to test
+20100815 mvh Merged
+20100914 bcb Cleaned up AddAbstractSyntaxAlias problems (double release)
+20100918 mvh Merged
+20110604 mvh Count and show #candidates for "No valid presentation contexts found"
+20110605 mvh Added more DCM_ERROR_ASSOCIATION info that will show as proper server errors
+20120820 bcb Fixed a case where k-pacs sent a leading empty Transfer Syntax Name.
+20130619 lsp Return NULL from DetachRTC() rather than pointer to deleted object
+20130807 mvh Testing result of all :: Read operations fixes hanging thread problem if you ctrl-c a c-store script
+20131016 mvh Merged
+20131106 mvh Removed return FALSE on Failed read in Multiplex(int Socketfd)
+ fixes multiplex connection terminated on some clients.
+*/
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+
+# include "dicom.hpp"
+
+
+PDU_Service :: PDU_Service()
+#ifdef __GNUC__ //Faster with member initialization.
+:ProposedAbstractSyntaxs(),
+AcceptedPresentationContexts(),
+SizeCap(0),
+AttachedRTC(NULL),
+DestructAttachedRTC(FALSE),
+UsedTransferSyntaxUID(),
+ValidPresContexts(0),
+Link()
+#endif
+ {
+ // PDU Level services are always big endian architecture
+ Buffer :: SetIncomingEndian(BIG_ENDIAN);
+ Buffer :: SetOutgoingEndian(BIG_ENDIAN);
+#ifndef __GNUC__
+ AttachedRTC = NULL;
+ DestructAttachedRTC = FALSE;
+#endif
+ }
+
+PDU_Service :: ~PDU_Service()
+ {
+ if(Link.Connected)
+ Close();
+ ClearAbstractSyntaxs();
+ while ( AcceptedPresentationContexts.GetSize())
+ AcceptedPresentationContexts.RemoveAt ( 0 );
+
+ if ( AttachedRTC )
+ if ( DestructAttachedRTC )
+ delete AttachedRTC;
+ }
+
+BOOL
+PDU_Service :: AttachRTC (
+ RTC *vRTC,
+ BOOL DestructFlag)
+ {
+ DetachRTC();
+ AttachedRTC = vRTC;
+ DestructAttachedRTC = DestructFlag;
+ return ( TRUE );
+ }
+
+RTC *
+PDU_Service :: DetachRTC()
+ {
+ RTC *vRTC;
+
+ vRTC = AttachedRTC;
+
+ if ( AttachedRTC )
+ if ( DestructAttachedRTC )
+ delete AttachedRTC;
+
+ AttachedRTC = NULL;
+ return ( NULL );
+ }
+
+BOOL PDU_Service :: Read(DICOMObject *DCMObject)
+ {
+ BYTE ItemType;
+
+ if (!Link.Connected)
+ return ( FALSE );
+ PDataTF :: MsgStatus = 0;
+ if((PDataTF :: Length)!=0) // for bad GCC v2.6.0
+ {
+ if (!PDataTF :: ReadDynamic( *this )) return FALSE;
+
+ if (PDataTF :: MsgStatus > 0)
+ {
+ SizeCap = 0;
+ if(!ParseRawVRIntoDCM(PDataTF :: PresentationContextID,
+ PDataTF::VRBuffer, DCMObject))
+ {
+ AAbortRQ :: Write(*this);
+ Link.Close();
+ return ( FALSE );
+ }
+ //DumpDDO((DICOMDataObject*)DCMObject);
+ return(TRUE);
+ }
+ }
+
+ while ( TRUE )
+ {
+ (*this) >> ItemType;
+ switch ( ItemType )
+ {
+ case 0x01: // A-ASSOCIATE-RQ Should not get this here
+ if (!AAssociateRQ :: Read(*this)) return FALSE;
+ AAbortRQ :: Write ( *this );
+ Link.Close();
+ return ( FALSE );
+ case 0x02: // A-ASSOCIATE-AC Should not get this here
+ if (!AAssociateAC :: Read(*this)) return FALSE;
+ AAbortRQ :: Write ( *this );
+ Link.Close();
+ return ( FALSE );
+ case 0x03: // A-ASSOCIATE-RJ Should not get this here
+ AAbortRQ :: Write ( *this );
+ Link.Close();
+ return ( FALSE );
+ case 0x04: // P-DATA-TF
+// fprintf(stderr, "start: P-DATA-TF Read\n");
+ if (!PDataTF :: ReadDynamic( *this )) return FALSE;
+// fprintf(stderr, "end: P-DATA-TF Read : %d, Buffer Size %d\n",
+// PDataTF :: MsgStatus, Buffer :: GetSize());
+
+ if (PDataTF :: MsgStatus > 0)
+ {
+ SizeCap = 0;
+ if(!ParseRawVRIntoDCM(PDataTF :: PresentationContextID,
+ PDataTF::VRBuffer, DCMObject))
+ {
+ AAbortRQ :: Write(*this);
+ Link.Close();
+ return ( FALSE );
+ }
+ //DumpDDO((DICOMDataObject*)DCMObject);
+ return(TRUE);
+ }
+ break;
+ case 0x05: // A-RELEASE-RQ
+ if (!AReleaseRQ :: ReadDynamic(*this)) return FALSE;
+ // also drop
+ AReleaseRP :: Write(*this);
+ return ( FALSE );
+ case 0x06: // A-RELEASE-RP
+ Link.Close();
+ return ( FALSE );
+ case 0x07: // A-ABORT-RQ
+ Link.Close();
+ return ( FALSE );
+ default:
+ // Protocol Error
+ AAbortRQ :: Write ( *this );
+ Link.Close();
+ return ( FALSE );
+ }
+ }
+ return ( FALSE );
+ }
+
+// These routines are being de-emphazised
+#if THESE_ARE_OBSOLETE
+BOOL PDU_Service :: Write(DICOMCommandObject *DCMObject)
+ {
+ BYTE TempByte;
+
+ TempByte = ParseDCMIntoRawVR(DCMObject, PDataTF :: VRBuffer);
+ if ( ! TempByte )
+ {
+ //printf("Failure to find TempByte\n");
+ return ( FALSE );
+ }
+ PDataTF :: PresentationContextID = TempByte;
+ PDataTF :: MsgHeader = 0x01;
+ return(PDataTF :: Write ( *this ));
+ }
+
+BOOL PDU_Service :: Write(DICOMDataObject *DCMObject)
+ {
+ BYTE TempByte;
+
+ TempByte = ParseDCMIntoRawVR(DCMObject, PDataTF :: VRBuffer);
+ if ( ! TempByte )
+ return ( FALSE );
+ PDataTF :: PresentationContextID = TempByte;
+ PDataTF :: MsgHeader = 0x00;
+
+ return(PDataTF :: Write ( *this ));
+ }
+#endif
+// These routines are the recommended method of sending a DICOM Object
+
+
+BOOL PDU_Service :: Write(DICOMCommandObject *DCMObject, UID &uid)
+ {
+ BYTE TempByte, TempByte1;
+ //DumpDDO((DICOMDataObject*)DCMObject);
+
+ TempByte1 = GetPresentationContextID(uid);
+// printf("PDU_Service :: Write(DCMObject:%x, %s) PID = %d\n",
+// DCMObject, uid.GetBuffer(1), TempByte1);
+ if(!TempByte1)
+ return ( FALSE );
+ TempByte = ParseDCMIntoRawVR(DCMObject, PDataTF :: VRBuffer, uid, FALSE);
+// printf("PDU_Service :: Write(DCMObject:%x, %s) RetParseDCMIntoRawVR = %d\n",
+// DCMObject, uid.GetBuffer(1), TempByte);
+ if ( ! TempByte )
+ return ( FALSE );
+
+ PDataTF :: PresentationContextID = TempByte;
+ PDataTF :: MsgHeader = 0x01;
+ return(PDataTF :: Write ( *this ));
+ }
+
+BOOL PDU_Service :: Write(DICOMDataObject *DCMObject, UID &uid)
+ {
+ BYTE TempByte, TempByte1;
+
+ //DumpDDO((DICOMDataObject*)DCMObject);
+ TempByte1 = GetPresentationContextID(uid);
+ if(!TempByte1)
+ return ( FALSE );
+
+ TempByte = ParseDCMIntoRawVR(DCMObject, PDataTF :: VRBuffer, uid, TRUE);
+ if ( ! TempByte )
+ return ( FALSE );
+ PDataTF :: PresentationContextID = TempByte;
+ PDataTF :: MsgHeader = 0x00;
+
+ return(PDataTF :: Write ( *this ));
+ }
+
+
+BOOL PDU_Service :: InterogateAAssociateRQ()
+ {
+ UINT Index, IndexTrn, ValidP, temp;
+ TransferSyntax TrnSyntax;
+ PresentationContext PresContext;
+ PresentationContextAccept PresContextAccept;
+ UserInformation UserInfo;
+ MaximumSubLength MaxSubLength;
+ Array<PresentationContext> PCArray ( FALSE );
+
+
+ if(!ShouldIAcceptRemoteApTitle(AAssociateRQ :: CallingApTitle))
+ {
+ AAssociateRJ :: Reason = 3; // Calling party not rec.
+ AAssociateRJ :: Source = 1; // PDU
+ AAssociateRJ :: Result = 1; // Permanent
+ AAssociateRJ :: Write ( *this );
+DicomError(DCM_ERROR_ASSOCIATION, "Calling party not accepted", 0);
+ return ( FALSE );
+ }
+ if(!ShouldIAcceptLocalApTitle(AAssociateRQ :: CalledApTitle))
+ {
+ AAssociateRJ :: Reason = 7; // Called Party Not Rec.
+ AAssociateRJ :: Source = 1; // PDU
+ AAssociateRJ :: Result = 1; // Permanent
+ AAssociateRJ :: Write ( *this );
+DicomError(DCM_ERROR_ASSOCIATION, "Called party not accepted", 0);
+ return ( FALSE );
+ }
+ if(!ShouldIAcceptApplicationContext(AAssociateRQ :: AppContext))
+ {
+ AAssociateRJ :: Reason = 2; // AppContext Not-Supported
+ AAssociateRJ :: Source = 1; // PDU
+ AAssociateRJ :: Result = 1; // Permanent
+ AAssociateRJ :: Write ( *this );
+DicomError(DCM_ERROR_ASSOCIATION, "AppContext Not-Supported", 0);
+ return ( FALSE );
+ }
+ // Transfer the information over to the A-ASSOCIATE-AC Class
+ AAssociateAC :: SetCalledApTitle(AAssociateRQ :: CalledApTitle);
+ AAssociateAC :: SetCallingApTitle(AAssociateRQ :: CallingApTitle);
+ AAssociateAC :: AppContext = AAssociateRQ :: AppContext;
+ AAssociateAC :: UserInfo = AAssociateRQ :: UserInfo;
+
+ // Ok, now, we need to find an acceptable presentation context
+ Index = 0;
+ ValidPresContexts = ValidP = temp = 0;
+ PCArray = (AAssociateRQ :: PresContexts);
+
+ while ( AcceptedPresentationContexts.GetSize())
+ AcceptedPresentationContexts.RemoveAt ( 0 );
+ /* Check all Presentation Contexts proposed by the other side, e.g.:
+ CTStorage 1.2.840.10008.5.1.4.1.1.2 sop
+ USMultiframeStorage 1.2.840.10008.5.1.4.1.1.3.1 sop
+ MRStorage 1.2.840.10008.5.1.4.1.1.4 sop
+ USStorage 1.2.840.10008.5.1.4.1.1.6.1 sop
+ SCStorage 1.2.840.10008.5.1.4.1.1.7 sop
+ */
+ while ( Index < PCArray.GetSize())
+ {
+ PresContext = PCArray.Get ( Index );
+ PresContext.TrnSyntax.ClearType = FALSE;
+ IndexTrn = 0;
+ PresContextAccept.PresentationContextID =
+ PresContext.PresentationContextID;
+ /* Fix: default to (Transfer Syntaxes Not Supported) */
+ PresContextAccept.Result = 4;
+ /* For each Presentation Context, multiple TransferTyntaxes may be proposed, e.g:
+ LittleEndianImplicit 1.2.840.10008.1.2
+ LittleEndianExplicit 1.2.840.10008.1.2.1
+ BigEndianExplicit 1.2.840.10008.1.2.2
+ JPEGLossless 1.2.840.10008.1.2.4.70
+ RLELossless 1.2.840.10008.1.2.5
+ JPEG2000 1.2.840.10008.1.2.4.91
+ */
+ temp += PresContext.TrnSyntax.GetSize();
+ while ( IndexTrn < PresContext.TrnSyntax.GetSize())
+ {
+ TrnSyntax = PresContext.TrnSyntax.Get(IndexTrn);
+ /* Following routine could better be named 'CanI...' */
+ //bcb Found a case of k-pacs sending a leading empty TransferSyntaxName, the second one was valid. 17 is the smallest.
+ if(TrnSyntax.TransferSyntaxName.GetSize() > 16 && CanYouHandleTransferSyntax(TrnSyntax))
+ {
+ PresContextAccept.TrnSyntax.TransferSyntaxName =
+ TrnSyntax.TransferSyntaxName;
+ /* OK: Accept the Transfer Syntax */
+ PresContextAccept.Result = 0;
+ AcceptedPresentationContexts.Add ( PresContextAccept );
+ ++ValidPresContexts; ++ValidP;
+ break;
+ }
+ ++IndexTrn;
+ }
+ /* Do we support the offered Presentation Context? */
+ if(!ShouldIAcceptAbstractSyntax(PresContext.AbsSyntax))
+ {
+ PresContextAccept.Result = 3;
+ ValidPresContexts--;
+ }
+ AAssociateAC :: AddPresentationContextAccept(PresContextAccept);
+ ++Index;
+ }
+ if(!ValidP)
+ {
+DicomError(DCM_ERROR_ASSOCIATION, "No valid presentation contexts/transfer syntax found in %d candidates", temp);
+DicomError(DCM_ERROR_ASSOCIATION, "In %d presentation contexts", PCArray.GetSize());
+DicomError(DCM_ERROR_ASSOCIATION, "#Possible transfer syntaxes: %d", ((CheckedPDU_Service*)this)->TransferUIDListCount);
+ AAssociateAC :: Write ( *this );
+ return ( FALSE );
+ }
+ MaxSubLength.Set(16384); // we can do all DICOM can handle
+ GetImplementationClass(UserInfo.ImpClass);
+ GetImplementationVersion(UserInfo.ImpVersion);
+ UserInfo.SetMax(MaxSubLength);
+
+ AAssociateAC :: SetUserInformation ( UserInfo );
+ AAssociateAC :: Write ( *this );
+
+ return ( TRUE ); // yes, the communication should work out
+ }
+
+
+BOOL PDU_Service :: InterogateAAssociateAC()
+ {
+ UINT Index;//,ValidPresContexts, IndexTrn;
+// BOOL Good;
+// TransferSyntax TrnSyntax;
+// PresentationContext PresContext;
+ PresentationContextAccept PresContextAccept;
+ Array<PresentationContextAccept> PCArray ( FALSE );
+
+ Index = 0;
+// ValidPresContexts = 0;
+ PCArray = (AAssociateAC :: PresContextAccepts);
+
+ //printf("InterogateAAssociateAC : PCArray.GetSize() = %d\n",
+ // PCArray.GetSize());
+ while ( AcceptedPresentationContexts.GetSize())
+ AcceptedPresentationContexts.RemoveAt ( 0 );
+
+ while ( Index < PCArray.GetSize())
+ {
+ PresContextAccept = PCArray.Get ( Index );
+ if(!PresContextAccept.Result)
+ {
+ //printf("Remote Accepting Abstract Class\n");
+ AcceptedPresentationContexts.Add ( PresContextAccept );
+ }
+// else
+// printf("Remote Rejecting Abstract Class [%d]\n",
+// PresContextAccept.Result);
+
+ ++Index;
+ }
+ if(!AcceptedPresentationContexts.GetSize())
+ return ( FALSE ); // no, this association should be terminated
+ return ( TRUE ); // yes, the communication should work out
+ }
+
+
+// Checks the Known Class list for the UID and further verifies that
+// it's a big/little Endian. If it is, then it sets the Transfer type
+// in the TransferSyntax for further reference
+BOOL PDU_Service :: CanYouHandleTransferSyntax(TransferSyntax &TrnSyntax)
+ {
+ /*
+ KnownClass KC;
+
+ if(KnownUID(TrnSyntax.TransferSyntaxName, KC))
+ return ( FALSE );
+
+ if(KC.Type != "transfer")
+ return ( FALSE );
+
+ if(KC.Comment != "LittleEndian")
+ {
+ if(KC.Command != "BigEndian")
+ return ( FALSE );
+ else
+ TrnSyntax.SetType ( BIG_ENDIAN );
+ }
+ else
+ TrnSyntax.SetType ( LITTLE_ENDIAN );
+ */
+ if(!strcmp((char*) TrnSyntax.TransferSyntaxName.GetBuffer(1), "1.2.840.10008.1.2"))
+ {
+ TrnSyntax.SetType ( LITTLE_ENDIAN );
+ return ( TRUE );
+ }
+ return ( FALSE );
+ }
+
+BOOL PDU_Service :: Listen(BYTE *port)
+ {
+ PDataTF :: Length = 0;
+
+ if (Link.Connected)
+ Link.Close();
+
+ if(!Link.Listen((char *) port))
+ return ( FALSE );
+
+ if(!Link.Accept())
+ return ( FALSE );
+
+// fprintf(stderr, "Waiting for AAssociateRQ\n");
+ if (!AAssociateRQ :: Read( *this )) return FALSE;
+// fprintf(stderr, "Interogating AAssociateRQ\n");
+ if(!InterogateAAssociateRQ())
+ {
+// fprintf(stderr, "failed to connect\n");
+ Link.Close();
+ return ( FALSE );
+ }
+// fprintf(stderr, "connected, but not disconnecting (missing P-DATA service)\n");
+// AAbortRQ :: Write ( *this );
+
+// return ( FALSE );
+ return ( TRUE );
+ }
+
+int PDU_Service :: Multiplex(BYTE *port)
+ {
+ int TempSocket;
+
+ PDataTF :: Length = 0;
+
+ if(!Link.Listen((char*)port))
+ {
+DicomError(DCM_ERROR_DEBUG, "link.listen failed", 0);
+ return(-1);
+ }
+
+ TempSocket = Link.ListenSocketfd;
+ Link.ListenSocketfd = 0;
+ Link.Listened = FALSE;
+ return (Listen(TempSocket));
+ }
+
+int PDU_Service :: Listen(int sock)
+ {
+ int TempSocket;
+
+ if(Link.Connected)
+ Link.Close();
+ Link.ListenSocketfd = sock;
+ Link.Listened = TRUE;
+
+ while (!Link.Connected)
+ {
+ if(!Link.Accept())
+ {
+DicomError(DCM_ERROR_DEBUG, "link.accept failed", 0);
+ return ( FALSE );
+ }
+
+ if (!AAssociateRQ :: Read( *this )) return FALSE;
+ if(!InterogateAAssociateRQ())
+ {
+ TempSocket = Link.ListenSocketfd;
+ Link.Listened = FALSE;
+ Link.Close();
+ Link.Listened = TRUE;
+ Link.ListenSocketfd = TempSocket;
+ }
+ }
+ TempSocket = Link.ListenSocketfd;
+ Link.ListenSocketfd = 0;
+ Link.Listened = 0;
+ return ( TempSocket );
+ }
+
+BOOL PDU_Service :: Multiplex(int Socketfd)
+ {
+ if(Link.Connected)
+ {
+DicomError(DCM_ERROR_DEBUG, "link is not connected", 0);
+ Link.Close();
+ }
+ Link.Connected = TRUE;
+ Link.Socketfd = Socketfd;
+// if (!AAssociateRQ :: Read( *this )) return FALSE;
+ AAssociateRQ :: Read( *this );
+ if(!InterogateAAssociateRQ())
+ {
+DicomError(DCM_ERROR_DEBUG, "InterogateAAssociateRQ failed", 0);
+ Link.Close();
+ return(FALSE);
+ }
+ return (TRUE);
+ }
+
+BOOL PDU_Service :: Close()
+ {
+ PDataTF :: Length = 0;
+ if ( Link.Connected )
+ {
+ AReleaseRQ :: Write ( *this );
+ if (!AReleaseRP :: Read ( *this )) return FALSE;
+ }
+ Link.Close();
+ return ( TRUE );
+ }
+
+// Support routine to get Presentation Context ID from UID
+
+BYTE PDU_Service :: GetAcceptedPCIDForTransferSyntax(UID &uid)
+ {
+ UINT Index;
+ PresentationContextAccept PCA;
+
+ Index = 0;
+ while (Index < AcceptedPresentationContexts.GetSize() )
+ {
+ PCA = AcceptedPresentationContexts.Get ( Index );
+/* fprintf(stderr, "Comparing: %s with %s [%d:%d]\n",
+ PCA.TrnSyntax.TransferSyntaxName.GetBuffer(1),
+ uid.GetBuffer(1),
+ PCA.TrnSyntax.TransferSyntaxName.GetSize(),
+ uid.GetSize());
+*/
+ if(PCA.TrnSyntax.TransferSyntaxName == uid)
+ return ( PCA.PresentationContextID );
+ ++Index;
+ }
+ return ( 0 );
+ }
+
+BYTE PDU_Service :: GetPresentationContextID(UID &uid)
+ {
+ UINT Index;
+ Array <PresentationContext> PCArray ( FALSE );
+ PresentationContext PresContext;
+
+ PCArray = (AAssociateRQ :: PresContexts);
+
+ Index = 0;
+ while ( Index < PCArray.GetSize())
+ {
+ PresContext = PCArray.Get ( Index );
+ PresContext.TrnSyntax.ClearType = FALSE;
+// printf("PDU_Service::GetPresentationContextID, Compare \"%s\"\n",
+// PresContext.AbsSyntax.AbstractSyntaxName.GetBuffer(1));
+ if(PresContext.AbsSyntax.AbstractSyntaxName == uid)
+ return ( PresContext.PresentationContextID );
+ ++Index;
+ }
+
+ return ( 0 );
+ }
+
+// Get the PCID for a given AbsUID and TrnUID
+BYTE PDU_Service :: GetPresentationContextID(UID &AbsUID, UID &TrnUID)
+ {
+ UINT Index;
+ Array <PresentationContext> PCArray ( FALSE );
+ PresentationContext PresContext;
+
+ PCArray = (AAssociateRQ :: PresContexts);
+
+ Index = 0;
+// printf("GetPresentationContextID, Searching for: %s/%s\n", AbsUID.GetBuffer(1),
+// TrnUID.GetBuffer(1));
+
+ while ( Index < PCArray.GetSize())
+ {
+ PresContext = PCArray.Get ( Index );
+ PresContext.TrnSyntax.ClearType = FALSE;
+ if(PresContext.AbsSyntax.AbstractSyntaxName == AbsUID)
+ {
+// printf("GetPresentationContextID :: Found %s in AAssociateRQ :: PresContexts\n",
+// AbsUID.GetBuffer(1));
+ UINT Index2;
+ PresentationContextAccept PCA;
+ Index2 = 0;
+ while (Index2 < AcceptedPresentationContexts.GetSize() )
+ {
+ PCA = AcceptedPresentationContexts.Get ( Index2 );
+// printf("PCA.TrnSyntax.TransferSyntaxName = %s\n",
+// PCA.TrnSyntax.TransferSyntaxName.GetBuffer(1));
+ if((PCA.TrnSyntax.TransferSyntaxName == TrnUID) &&
+ (PCA.PresentationContextID == PresContext.PresentationContextID))
+ {
+// printf("Returning Good!");
+ return ( PCA.PresentationContextID );
+ }
+ ++Index2;
+ }
+ }
+ ++Index;
+ }
+
+// printf("GetPresentationContextID :: Error, cannot find in Accepted PC List\n");
+ return ( 0 );
+ }
+
+BOOL PDU_Service :: GetTransferSyntaxUID(BYTE PCID, UID &uid)
+ {
+ UINT Index;
+ PresentationContextAccept PCA;
+
+ Index = 0;
+ while (Index < AcceptedPresentationContexts.GetSize() )
+ {
+ PCA = AcceptedPresentationContexts.Get ( Index );
+ if(PCA.PresentationContextID == PCID)
+ {
+ uid = PCA.TrnSyntax.TransferSyntaxName;
+ return ( TRUE );
+ }
+ ++Index;
+ }
+ return ( FALSE );
+ }
+
+BOOL PDU_Service :: IsAbstractSyntaxAccepted(UID &uid)
+{
+ BYTE id;
+ UINT Index;
+ PresentationContextAccept PCA;
+
+
+ id = GetPresentationContextID(uid);
+ if (!id)
+ return FALSE;
+ Index = 0;
+ while (Index < AcceptedPresentationContexts.GetSize() )
+ {
+ PCA = AcceptedPresentationContexts.Get ( Index );
+/* fprintf(stderr, "Comparing: %s with %s [%d:%d]\n",
+ PCA.TrnSyntax.TransferSyntaxName.GetBuffer(1),
+ uid.GetBuffer(1),
+ PCA.TrnSyntax.TransferSyntaxName.GetSize(),
+ uid.GetSize());
+*/
+ if(PCA.PresentationContextID == id)
+ return TRUE;
+ ++Index;
+ }
+ return FALSE;
+}
+
+
+
+
+BOOL PDU_Service :: ClearAbstractSyntaxs ()
+ {
+ while (ProposedAbstractSyntaxs.GetSize())
+ ProposedAbstractSyntaxs.RemoveAt ( 0 );
+ return ( TRUE );
+ }
+
+BOOL PDU_Service :: AddAbstractSyntax(UID &uid)
+ {
+ UINT Index;
+ AbstractSyntax AbsSyntax;
+
+ Index = 0;
+ while ( Index < ProposedAbstractSyntaxs.GetSize() )
+ {
+ if ( uid ==
+ ProposedAbstractSyntaxs.Get ( Index ).AbstractSyntaxName)
+ return ( TRUE ); // already in array
+ ++Index;
+ }
+ AbsSyntax.Set(uid);
+ ProposedAbstractSyntaxs.Add ( AbsSyntax );
+ return ( TRUE );
+ }
+
+// Used only in StorageApp :: PrinterSupport
+BOOL PDU_Service :: AddAbstractSyntaxAlias (
+ UID &UIDSource,
+ UID &UIDAlias)
+ {
+ UINT Index;
+ Array <PresentationContext> PCArray ( FALSE );
+ PresentationContext PresContext;
+
+ // First check to see if it's already aliased
+ if ( GetPresentationContextID ( UIDAlias ) )
+ return ( TRUE );
+
+ PCArray = (AAssociateRQ :: PresContexts);
+
+ Index = 0;
+ while ( Index < PCArray.GetSize())
+ {
+ PresContext = PCArray.Get ( Index );
+ PresContext.TrnSyntax.ClearType = FALSE;// Original does not clear the array.
+
+ if(PresContext.AbsSyntax.AbstractSyntaxName == UIDSource)
+ {
+ Array<TransferSyntax> vTrnSyntax = PresContext.TrnSyntax; //Copies just pointers, see array.thh
+ vTrnSyntax.ClearType = FALSE; // Pointers still belong to AAssociateRQ :: PresContexts
+
+// PresentationContext vPresContext = PresContext;// Does not copy the array, just pointers.
+// vPresContext.TrnSyntax.ClearType = FALSE;// The copy does not clear the array, leak?
+
+ PresContext.TrnSyntax.Clear();// The original loses pointers to the array.
+ UINT SubIndex = 0;
+
+ while (SubIndex < vTrnSyntax.GetSize() ) //bcb replaced loop 20100728
+ {
+ PresContext.TrnSyntax.Add(vTrnSyntax.Get(SubIndex));// Copies the values.
+ ++SubIndex;
+ }
+
+/* while (SubIndex < vPresContext.TrnSyntax.GetSize() )
+ {
+ PresContext.TrnSyntax.Add(vPresContext.TrnSyntax.Get(SubIndex));// Copies the values.
+ ++SubIndex;
+ }
+*/
+
+ PresContext.TrnSyntax.ClearType = TRUE;// The ability to clear the new array.
+ PresContext.AbsSyntax.AbstractSyntaxName = UIDAlias;
+ AAssociateRQ :: AddPresentationContext(PresContext);// Sets ClearType.
+ PresContext.TrnSyntax.ClearType = FALSE;// Take it back, pointers still belong to AAssociateRQ :: PresContexts
+
+ // Now we clear the array for real when the destructor vTrnSyntax is called. bcb added 20100728
+ return ( TRUE );// Here calls destructor for vPresContext, but the old array survives?
+ }
+ ++Index;
+ }
+
+ // The source was not proposed
+
+ return ( FALSE );
+ }
+
+BOOL PDU_Service :: SetApplicationContext(UID &uid)
+ {
+ AAssociateRQ :: SetApplicationContext(uid);
+ return ( TRUE );
+ }
+
+BOOL PDU_Service :: SetLocalAddress(BYTE *address)
+ {
+ AAssociateRQ :: SetCallingApTitle(address);
+ return ( TRUE );
+ }
+
+BOOL PDU_Service :: SetRemoteAddress(BYTE *address)
+ {
+ AAssociateRQ :: SetCalledApTitle(address);
+ return ( TRUE );
+ }
+
+BOOL PDU_Service :: GetLocalAddress(BYTE *address)
+ {
+ memset(address, 0, 17); memcpy(address, AAssociateAC :: CallingApTitle, 16);
+ return ( TRUE );
+ }
+
+BOOL PDU_Service :: GetRemoteAddress(BYTE *address)
+ {
+ memset(address, 0, 17); memcpy(address, AAssociateAC :: CalledApTitle, 16);
+ return ( TRUE );
+ }
+
+BOOL PDU_Service :: AddTransferSyntaxs(PresentationContext &PresContext)
+ {
+ UID uid;
+ TransferSyntax TrnSyntax;
+// char szAbstractSyntax[100];
+
+/*
+ uid = PresContext.AbsSyntax.AbstractSyntaxName;
+ strncpy(szAbstractSyntax, (char*)uid.GetBuffer(0), uid.GetSize());
+ szAbstractSyntax[uid.GetSize()] = 0;
+ if ((strcmp(szAbstractSyntax, "1.2.840.10008.1.1") != 0) && // c-echo
+ (strstr(szAbstractSyntax, ".5.1.4.1.2.") == 0)) // c-find
+ {
+ uid.Set("1.2.840.10008.1.2.4.70"); // LJ LosslessJPEG
+ TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+ }
+*/
+ uid.Set("1.2.840.10008.1.2"); // LJ ImplicitLittleEndian
+ TrnSyntax.Set(uid);
+ PresContext.AddTransferSyntax(TrnSyntax);
+// uid.Set("1.2.840.10008.1.2.1"); // LJ ExplicitLittleEndian
+// TrnSyntax.Set(uid);
+// PresContext.AddTransferSyntax(TrnSyntax);
+ return ( TRUE );
+ }
+
+BOOL PDU_Service :: GetImplementationClass(ImplementationClass &ImpClass)
+ {
+ ImpClass.Set((BYTE*) IMPLEMENTATION_CLASS_STRING);
+ return(TRUE);
+ }
+
+BOOL PDU_Service :: GetImplementationVersion(ImplementationVersion &ImpVersion)
+ {
+ ImpVersion.Set((BYTE*) IMPLEMENTATION_VERSION_STRING);
+ return ( TRUE );
+ }
+
+BOOL PDU_Service :: Connect ( BYTE *ip, BYTE *port )
+ {
+ UINT Index;
+ PresentationContext PresContext;
+ UserInformation UserInfo;
+ MaximumSubLength MaxSubLength;
+ BYTE ItemType;
+
+ PDataTF :: Length = 0;
+
+ if (!ProposedAbstractSyntaxs.GetSize () )
+ return ( FALSE ); // must proposed atleast one SOP class
+ AAssociateRQ :: ClearPresentationContexts();
+ Index = 0;
+ //AddTransferSyntaxs(PresContext);
+ while ( Index < ProposedAbstractSyntaxs.GetSize())
+ {
+ PresContext.TrnSyntax.Clear();
+ PresContext.SetAbstractSyntax ( ProposedAbstractSyntaxs.Get ( Index ) );
+ AddTransferSyntaxs(PresContext);
+ PresContext.PresentationContextID = uniq8odd();
+ AAssociateRQ :: AddPresentationContext ( PresContext );
+ ++Index;
+ }
+ PresContext.TrnSyntax.ClearType = FALSE;
+ MaxSubLength.Set(16384); // we can do all DICOM can handle
+ GetImplementationClass(UserInfo.ImpClass);
+ GetImplementationVersion(UserInfo.ImpVersion);
+ UserInfo.SetMax(MaxSubLength);
+
+ AAssociateRQ :: SetUserInformation ( UserInfo );
+
+ // ok, every thing proposed, now try and contact the remote end
+ if ( ! Link.Open ( (char*) ip, (char*)port ) )
+ return ( FALSE ); // Socket level Error
+ AAssociateRQ :: Size();
+ AAssociateRQ :: Write ( *this );
+
+ (*this) >> ItemType;
+// fprintf(stderr, "Got Response Type: %d\n", ItemType);
+ switch ( ItemType )
+ {
+ case 0x02:
+ if (!AAssociateAC :: ReadDynamic ( * this )) return FALSE;
+ if(!InterogateAAssociateAC())
+ {
+ //printf("Failed to InterogateAAssociateAC\n");
+ Link.Close();
+ return ( FALSE );
+ }
+ return ( TRUE ); // this is what we want to happen
+ case 0x03:
+ if (!AAssociateRJ :: ReadDynamic ( * this )) return FALSE;
+ Link.Close();
+ return ( FALSE );
+ default:
+ // corrupt transmission
+ Link.Close();
+ return ( FALSE );
+ }
+
+ return ( FALSE );
+ }
+
+
diff --git a/pdu.hpp b/pdu.hpp
new file mode 100644
index 0000000..30eaa66
--- /dev/null
+++ b/pdu.hpp
@@ -0,0 +1,238 @@
+/*
+19990202 ljz Added PDU memberfunction 'IsAbstractSyntaxAccepted'
+20020316 mvh Added GetLocalAddress and GetRemoteAddress
+20030424 ljz Changedprototype of ParseDCMIntoRawVR
+20030627 mvh Fix for MSC4.2
+20030905 mvh Removed spurious ;
+20080816 mvh ValidPresContexts is now public: how many incoming connection can handle
+20080819 mvh CanYouHandleTransferSyntax is now public; use BOOL not bool
+20091231 bcb Changed char* to const char* for gcc4.2 warnings
+20100111 mvh Merged
+20100619 bcb Fix gcc4 warnings and improve speed,
+ and prevented copying of the PDU_Service class with pointers.
+20100723 mvh Merged
+20101120 mvh bcb added parameter
+20110320 mvh Rollback of dicom decoder (parameter) to 1.4.16beta4 version
+20110326 mvh Put it back again
+20130619 lsp Made no-copy generic (not only for __GNUC__)
+*/
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/***********************************************************************
+ *
+ *
+ ***********************************************************************/
+#define DEFAULT_ACCEPTANCE TRUE
+
+
+// These are Read/Write file types
+# define ACRNEMA_VR_DUMP 1
+# define DICOM_CHAPTER_10_IMPLICIT 2
+# define DICOM_CHAPTER_10_EXPLICIT 3
+
+// These are "Transfer Syntax Alias" types.
+enum
+ {
+ TSA_IMPLICIT_LITTLE_ENDIAN = 100,
+ TSA_EXPLICIT_LITTLE_ENDIAN,
+ TSA_EXPLICIT_BIG_ENDIAN
+ };
+
+class FileBuffer :
+ public LinkedBuffer
+ {
+ public:
+ FILE *fp;
+ BOOL OpenForRead ( char *filename );
+ BOOL OpenForWrite ( char *filename );
+ BOOL Close ();
+ INT ReadBinary(BYTE *Data, UINT Count);
+ BOOL SendBinary(BYTE *Data, UINT Count);
+#ifdef __GNUC__
+ FileBuffer():fp(NULL) {};
+ private:// This will prevent it from being copied (it has pointers)
+ FileBuffer(const FileBuffer&);
+ const FileBuffer & operator = (const FileBuffer&);
+#endif
+ };
+
+class PDU_Service :
+ public Buffer, // Transport Buffer
+ public AAssociateRQ, // Associate Request
+ public AAssociateAC, // Associate Accept
+ public AAssociateRJ, // Associate Reject
+ public AReleaseRQ, // Associate Release
+ public AReleaseRP, // Associate Release Response
+ public AAbortRQ, // Associate Abort Request
+ public PDataTF // P-DATA Service
+ {
+ protected:
+ Array<AbstractSyntax> ProposedAbstractSyntaxs;
+ Array<PresentationContextAccept> AcceptedPresentationContexts;
+ UINT32 SizeCap;
+ RTC *AttachedRTC;
+ BOOL DestructAttachedRTC;
+ UID UsedTransferSyntaxUID;
+ protected:
+ BOOL InterogateAAssociateRQ();
+ BOOL InterogateAAssociateAC();
+ virtual BOOL ShouldIAcceptRemoteApTitle(BYTE *)
+ { return ( DEFAULT_ACCEPTANCE ); };
+ virtual BOOL ShouldIAcceptLocalApTitle(BYTE *)
+ { return ( DEFAULT_ACCEPTANCE ); };
+ virtual BOOL ShouldIAcceptApplicationContext(ApplicationContext &)
+ { return ( DEFAULT_ACCEPTANCE ); };
+ virtual BOOL ShouldIAcceptPresentationContext(
+ PresentationContext &,
+ PresentationContextAccept &)
+ { return ( DEFAULT_ACCEPTANCE ); };
+ virtual BOOL ShouldIAcceptAbstractSyntax(AbstractSyntax &)
+ { return ( DEFAULT_ACCEPTANCE ); };
+ virtual BOOL AddTransferSyntaxs(PresentationContext &);
+ virtual BOOL GetImplementationClass(ImplementationClass &);
+ virtual BOOL GetImplementationVersion(ImplementationVersion &);
+
+ // Entry Point Functions
+ virtual BOOL ParseRawVRIntoDCM(BYTE, LinkedBuffer &, DICOMObject *);
+ virtual BYTE ParseDCMIntoRawVR(DICOMObject *, LinkedBuffer &);
+// virtual BYTE ParseDCMIntoRawVR(DICOMObject *, LinkedBuffer &, UID &);
+ virtual BYTE ParseDCMIntoRawVR(DICOMObject *, LinkedBuffer &, UID &, BOOL bIsDataObject = TRUE);
+
+ // Implicit Encoders
+ virtual BOOL Implicit_ParseRawVRIntoDCM(
+ LinkedBuffer &, DICOMObject *, BOOL bZeroTaken);
+// LinkedBuffer &, DICOMObject *, BOOL bZeroTaken = FALSE);
+ virtual BOOL Implicit_ParseDCMIntoRawVR
+ (DICOMObject *, LinkedBuffer &);
+ virtual BOOL ImplicitLittleEndian_ParseRawVRIntoDCM(
+ LinkedBuffer &, DICOMObject *);
+ virtual BOOL ImplicitLittleEndian_ParseDCMIntoRawVR
+ (DICOMObject *, LinkedBuffer &);
+
+ // Explicit Decoders
+ virtual BOOL Explicit_ParseRawVRIntoDCM(
+ LinkedBuffer &, DICOMObject *);
+ virtual BOOL Explicit_ParseDCMIntoRawVR
+ (DICOMObject *, LinkedBuffer &);
+ virtual BOOL ExplicitLittleEndian_ParseRawVRIntoDCM(
+ LinkedBuffer &, DICOMObject *);
+ virtual BOOL ExplicitLittleEndian_ParseDCMIntoRawVR
+ (DICOMObject *, LinkedBuffer &);
+ virtual BOOL ExplicitBigEndian_ParseRawVRIntoDCM(
+ LinkedBuffer &, DICOMObject *);
+ virtual BOOL ExplicitBigEndian_ParseDCMIntoRawVR
+ (DICOMObject *, LinkedBuffer &);
+
+ // Used to Read DICOM Files (all types)
+ virtual BOOL Dynamic_ParseRawVRIntoDCM
+ (LinkedBuffer &, DICOMObject *, UINT StartMode);
+
+ // Used to write Chapter 10 Explcit (new) files
+ virtual BOOL Dynamic_ParseDCMIntoRawVR
+ (DICOMObject *, LinkedBuffer &, UINT StartMode);
+
+ // Image Pixel Data encapsulation routines
+
+ virtual BOOL ParseImagePixelDataDCMToRaw
+ (Array<DICOMDataObject*> *, LinkedBuffer &);
+ virtual BOOL ParseImagePixelDataRawToDCM
+ (LinkedBuffer &, DICOMObject *);
+
+ // Support Routines for Transfer Syntax Encoding/Decoding
+ public: // The following routine is usefull to check for a valid
+ // Accepted Presentation Context UID
+ UINT ValidPresContexts;
+ virtual BOOL CanYouHandleTransferSyntax(TransferSyntax &);
+ BYTE GetAcceptedPCIDForTransferSyntax(UID &TrnUID);
+ BOOL GetTransferSyntaxUID(BYTE, UID &TrnUID);
+ char* GetTransferSyntaxUID(UINT);
+ BYTE GetPresentationContextID(UID &AbsUID);
+ BYTE GetPresentationContextID(UID &AbsUID, UID &TrnUID);
+ BOOL IsAbstractSyntaxAccepted(UID &uid);
+ void GetUsedTransferSyntax(UID &uid){ uid = UsedTransferSyntaxUID;};
+
+ public:
+ Socket Link;
+
+ // RTC Support (optional, helps transfer syntax engines)
+ BOOL AttachRTC(RTC *, BOOL Destruct = FALSE);
+ RTC *DetachRTC();
+ // Wrap data over from the Associate/PData Classes over to the buffer
+ BOOL Read(BYTE *Data, UINT Count)
+ { return ( Buffer :: Read ( Data, Count ) ); };
+ BOOL Write(BYTE *Data, UINT Count)
+ { return ( Buffer :: Write ( Data, Count ) ); };
+ BOOL Kill(UINT Count)
+ { return ( Buffer :: Kill ( Count ) ); };
+ BOOL Flush()
+ { return ( Buffer :: Flush () ); };
+ // Wrap data over from the buffer over to the socket
+ INT ReadBinary(BYTE *Data, UINT Count)
+ { return ( Link.ReadBinary(Data, Count) ); };
+ BOOL SendBinary(BYTE *Data, UINT Count)
+ { return ( Link.SendBinary(Data, Count) ); };
+
+ virtual BOOL MakeChapter10(DICOMDataObject *,const char* pszTransferSyntaxUID = "1.2.840.10008.1.2");
+ DICOMDataObject *LoadDICOMDataObject ( char * );
+ BOOL SaveDICOMDataObject ( char *, UINT, DICOMDataObject * );
+ BOOL ClearAbstractSyntaxs();
+ virtual BOOL AddAbstractSyntax(UID &);
+ virtual BOOL AddAbstractSyntaxAlias(UID &Source, UID &Alias);
+ virtual BOOL SetApplicationContext(UID &);
+ virtual BOOL SetLocalAddress(BYTE *);
+ virtual BOOL SetRemoteAddress(BYTE *);
+ virtual BOOL GetLocalAddress(BYTE *);
+ virtual BOOL GetRemoteAddress(BYTE *);
+ BOOL Connect(BYTE *, BYTE *);
+
+ BOOL Close();
+
+ BOOL Listen(BYTE *);
+
+ BOOL Read(DICOMObject *);
+ BOOL Write(DICOMCommandObject *);
+ BOOL Write(DICOMDataObject *);
+ BOOL Write(DICOMCommandObject *, UID &);
+ BOOL Write(DICOMDataObject *, UID &);
+ BOOL Multiplex(int);
+
+ int Multiplex(BYTE *);
+ int Listen(int);
+ BOOL SetTimeOut(int TimeOut)
+ { return ( Link.SetTimeOut(TimeOut) ); };
+ PDU_Service();
+ virtual ~PDU_Service();
+ private:// This will prevent it from being copied (it has pointers)
+ PDU_Service(const PDU_Service&);
+ const PDU_Service & operator = (const PDU_Service&);
+ };
+
+
diff --git a/pqueue.tcc b/pqueue.tcc
new file mode 100644
index 0000000..56c1b75
--- /dev/null
+++ b/pqueue.tcc
@@ -0,0 +1,258 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+/*
+ 20100309 bcb commented out unused variables (gcc4.2 Warnings)
+ 20100707 mvh Merged
+*/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/***********************************************************************
+ *
+ * Template P-Queue Class
+ *
+ *
+ *
+ ***********************************************************************/
+
+template <class DATATYPE>
+DATATYPE & PQueue<DATATYPE> :: Push(DATATYPE &Value)
+ {
+ unsigned int Index;//, Base;
+ DATATYPE tdt;
+
+ Array<DATATYPE> :: Add(Value);
+
+ Index = Array<DATATYPE>::GetSize();
+ --Index;
+ while(Index)
+ {
+ if(Array<DATATYPE>::Get(Index) < Array<DATATYPE>::Get((Index-1)>>1))
+ {
+ tdt = Array<DATATYPE> :: Get(Index);
+ Array<DATATYPE>::Get(Index) = Array<DATATYPE>::Get((Index-1)>>1);
+ Array<DATATYPE>::Get((Index-1)>>1) = tdt;
+ Index = (Index-1) >> 1;
+ }
+ else
+ break;
+ }
+ return ( Value );
+ }
+
+template <class DATATYPE>
+DATATYPE & PQueue<DATATYPE> :: Pop()
+ {
+ DATATYPE tdt;
+// DATATYPE tdt2;
+// unsigned int Index;
+ unsigned int sorted;
+ unsigned int Pick;
+ unsigned int Child1;
+ unsigned int Child2;
+ unsigned int Hole;
+
+ if(!Array<DATATYPE>::GetSize())
+ return ( dt ); // error
+
+ dt = Array<DATATYPE> :: Get ( 0 );
+
+ if(Array<DATATYPE> :: GetSize() == 1)
+ {
+ Array<DATATYPE> :: RemoveAt ( 0 );
+ return ( dt ) ;
+ }
+ tdt = Array<DATATYPE> :: Get ( Array<DATATYPE> :: GetSize() - 1);
+ Array<DATATYPE> :: RemoveAt ( Array<DATATYPE> :: GetSize() - 1);
+ Hole = 0;
+ sorted = 0;
+ while(!sorted)
+ {
+ Child1 = 2 * Hole + 1;
+ Child2 = 2 * Hole + 2;
+ if(Child2 >= Array<DATATYPE> :: GetSize())
+ {
+ if ( Child1 >= Array<DATATYPE> :: GetSize())
+ {
+ Array<DATATYPE> :: Get(Hole) = tdt;
+ return ( dt );
+ }
+ if(Array<DATATYPE> :: Get ( Child1 ) < tdt)
+ {
+ Array<DATATYPE> :: Get(Hole) = Array<DATATYPE> :: Get(Child1);
+ Array<DATATYPE> :: Get(Child1) = tdt;
+ return(dt);
+ }
+ Array<DATATYPE> :: Get(Hole) = tdt;
+ return ( dt );
+ }
+ Pick = Child1;
+ if ( Array<DATATYPE> :: Get ( Child1 ) > Array<DATATYPE> :: Get(Child2))
+ Pick = Child2;
+ if ( Array<DATATYPE> :: Get ( Pick ) < tdt)
+ {
+ Array<DATATYPE> :: Get ( Hole) = Array<DATATYPE> :: Get( Pick );
+ Hole = Pick;
+ }
+ else
+ {
+ Array<DATATYPE> :: Get(Hole) = tdt;
+ return ( dt );
+ }
+ }
+ return ( dt );
+ }
+template <class DATATYPE>
+DATATYPE & PQueueOfPtr<DATATYPE> :: Push(DATATYPE &Value)
+ {
+ unsigned int Index;//, Base;
+ DATATYPE tdt;
+
+ Array<DATATYPE> :: Add(Value);
+
+ Index = Array<DATATYPE>::GetSize();
+ --Index;
+ while(Index)
+ {
+ if((*Array<DATATYPE>::Get(Index)) < (*Array<DATATYPE>::Get((Index-1)>>1)))
+ {
+ tdt = Array<DATATYPE> :: Get(Index);
+ Array<DATATYPE>::Get(Index) = Array<DATATYPE>::Get((Index-1)>>1);
+ Array<DATATYPE>::Get((Index-1)>>1) = tdt;
+ Index = (Index-1) >> 1;
+ }
+ else
+ break;
+ }
+ return ( Value );
+ }
+
+template <class DATATYPE>
+DATATYPE & PQueueOfPtr<DATATYPE> :: Pop()
+ {
+ DATATYPE tdt;
+// DATATYPE tdt2;
+// unsigned int Index;
+ unsigned int sorted;
+ unsigned int Pick;
+ unsigned int Child1;
+ unsigned int Child2;
+ unsigned int Hole;
+
+ if(!Array<DATATYPE>::GetSize())
+ return ( dt ); // error
+
+ dt = Array<DATATYPE> :: Get ( 0 );
+
+ if(Array<DATATYPE> :: GetSize() == 1)
+ {
+ Array<DATATYPE> :: RemoveAt ( 0 );
+ return ( dt ) ;
+ }
+ tdt = Array<DATATYPE> :: Get ( Array<DATATYPE> :: GetSize() - 1);
+ Array<DATATYPE> :: RemoveAt ( Array<DATATYPE> :: GetSize() - 1);
+ Hole = 0;
+ sorted = 0;
+ while(!sorted)
+ {
+ Child1 = 2 * Hole + 1;
+ Child2 = 2 * Hole + 2;
+ if(Child2 >= Array<DATATYPE> :: GetSize())
+ {
+ if ( Child1 >= Array<DATATYPE> :: GetSize())
+ {
+ Array<DATATYPE> :: Get(Hole) = tdt;
+ return ( dt );
+ }
+ if((*Array<DATATYPE> :: Get ( Child1 )) < (*tdt))
+ {
+ Array<DATATYPE> :: Get(Hole) = Array<DATATYPE> :: Get(Child1);
+ Array<DATATYPE> :: Get(Child1) = tdt;
+ return(dt);
+ }
+ Array<DATATYPE> :: Get(Hole) = tdt;
+ return ( dt );
+ }
+ Pick = Child1;
+ if ( (*Array<DATATYPE> :: Get ( Child1 )) > (*Array<DATATYPE> :: Get(Child2)))
+ Pick = Child2;
+ if ( (*Array<DATATYPE> :: Get ( Pick )) < (*tdt))
+ {
+ Array<DATATYPE> :: Get ( Hole) = Array<DATATYPE> :: Get( Pick );
+ Hole = Pick;
+ }
+ else
+ {
+ Array<DATATYPE> :: Get(Hole) = tdt;
+ return ( dt );
+ }
+ }
+ return ( dt );
+ }
+
+#ifdef BUILD_TEST_UNITS
+
+int
+testfunc()
+ {
+ int tempint, tempint2, index;
+ PQueue<int> Pq;
+
+ fprintf(stderr, "[adding randum numbers]\n");fflush(stderr);
+ index = 0;
+ while(index < 1000)
+ {
+ tempint = rand();
+ //fprintf(stderr, "Adding: %d, ", index);fflush(stderr);
+ Pq.Push(tempint);
+ ++index;
+ }
+ fprintf(stderr, "[testing Queue Size: %d]\n", Pq.GetSize());fflush(stderr);
+ index = 0;
+ tempint2 = 0;
+ while(Pq.GetSize())
+ {
+ tempint = Pq.Pop();
+ //fprintf(stderr, "%d : %d Pop : %d\n", index+1, Pq.GetSize(), tempint);
+ if(tempint < tempint2)
+ {
+ fprintf(stderr, "[---failed---]\n");fflush(stderr);return(0);
+ }
+ tempint2 = tempint;
+ ++index;
+ }
+ fprintf(stderr, "[success]\n");
+ return ( 1 );
+ }
+
+main()
+ {
+ testfunc();
+ return(0);
+ }
+
+#endif
diff --git a/pqueue.thh b/pqueue.thh
new file mode 100644
index 0000000..129eb3e
--- /dev/null
+++ b/pqueue.thh
@@ -0,0 +1,87 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+/*
+20100621 bcb Added no-copy to the classes.
+20100707 mvh Merged
+*/
+
+/******************************************************************
+ *
+ * PQueue Unit Class
+ *
+ * ANSI (ARM) C++ Compatible / Templates Required
+ *
+ *
+ * usage:
+ *
+ * # include "array.tcc"
+ * # include "pqueue.thh"
+ * # include "pqueue.tcc"
+ *
+ * PQueue<ClassType> VarName;
+ *
+ *
+ * notes:
+ *
+ * Any Class used as the datatype must support the operators < > =
+ *
+ ******************************************************************/
+
+
+template <class DATATYPE>
+class PQueue :
+ public Array<DATATYPE>
+ {
+ DATATYPE dt;
+ public:
+ DATATYPE & Push(DATATYPE &);
+ DATATYPE & Pop();
+#ifdef __GNUC__
+ PQueue():dt(){};
+ private:// This will prevent it from being copied (it has a pointer)
+ PQueue(const PQueue&);
+ const PQueue<DATATYPE> & operator = (const PQueue<DATATYPE>&);
+#endif
+ };
+
+template <class DATATYPE>
+class PQueueOfPtr :
+ public Array<DATATYPE>
+ {
+ DATATYPE dt;
+ public:
+ DATATYPE & Push(DATATYPE &);
+ DATATYPE & Pop();
+#ifdef __GNUC__
+ PQueueOfPtr():dt(){};
+ private:// This will prevent it from being copied (it has a pointer)
+ PQueueOfPtr(const PQueueOfPtr&);
+ const PQueueOfPtr<DATATYPE> & operator = (const PQueueOfPtr<DATATYPE>&);
+#endif
+ };
diff --git a/qrsop.cxx b/qrsop.cxx
new file mode 100644
index 0000000..dca6366
--- /dev/null
+++ b/qrsop.cxx
@@ -0,0 +1,401 @@
+/*
+20020429 mvh Fixed reporting of number of complete slices (now starts with 1)
+ return cancel status if C_STORE failed
+20030606 ljz Added parameter 'QueryRetrieveLevel' to CFindRSP::Write
+20050401 mvh Added ModalityWorkListQuery
+20051222 mvh Added pADDO to Query::Write method - answer appended to pADDO if set
+20080820 mvh Solaris fix (do not use variable name SS)
+20090205 mvh Added QueryMoveScript callbacks
+20100122 mvh Added support for C-CANCEL: poll the socket for any data and cancel if so
+20100309 bcb Added double parentheses (gcc4.2 Warnings)
+20100619 bcb Made Port local (lPort).
+20100707 mvh Merged
+20100816 mvh Added QueryResultScript
+*/
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+# include "dicom.hpp"
+
+BOOL StandardQuery :: Read (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO)
+ {
+ UID MyUID, uid;
+ VR *vr;
+ DICOMDataObject DDO;
+ Array < DICOMDataObject *> ADDO;
+ UINT Index;
+ BOOL Cancelled;
+
+ GetUID(MyUID);
+
+ if( ! PDU )
+ return ( FALSE );
+
+ if( ! DCO )
+ return ( FALSE );
+
+ vr = DCO->GetVR(0x0000, 0x0002);
+ SetUID(uid, vr);
+ if (!(MyUID == uid))
+ return ( FALSE );
+
+ if (! CFindRQ :: Read (DCO, PDU, &DDO) )
+ return ( FALSE ); // my SOP, but wrong command
+
+ if (! QueryMoveScript (PDU, DCO, &DDO))
+ {
+ CFindRSP :: Write (PDU, DCO, 0xc011, NULL, QueryRetrieveLevel);
+ return ( TRUE );
+ }
+
+ if (! SearchOn (&DDO, &ADDO) )
+ {
+ CFindRSP :: Write (PDU, DCO, 0xc001, NULL, QueryRetrieveLevel);
+ return ( TRUE );
+ }
+
+ Index = 0;
+ Cancelled = FALSE;
+ while ( Index < ADDO.GetSize() )
+ {
+ if (!Cancelled)
+ {
+ QueryResultScript (PDU, DCO, ADDO.Get ( Index ));
+ CFindRSP :: Write (PDU, DCO, ADDO.Get ( Index ), QueryRetrieveLevel);
+ }
+ else
+ {
+ if (PDU->Link.Poll())
+ {
+ DicomError(DCM_ERROR_DEBUG, "Query received cancel request", 0);
+ Cancelled = TRUE;
+ }
+ }
+ delete ADDO.Get ( Index );
+ ++Index;
+ }
+ CFindRSP :: Write ( PDU, DCO, NULL, QueryRetrieveLevel);
+
+ return ( TRUE );
+ }
+
+BOOL StandardQuery :: Write (
+ PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ Array < DICOMDataObject *> *pADDO)
+ {
+ DICOMCommandObject *DCO;
+ DICOMDataObject *RDDO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! CFindRQ :: Write ( PDU, DDO ) )
+ return ( FALSE );
+
+ CallBack ( NULL, DDO );
+
+ DCO = new DICOMCommandObject;
+
+ while ( PDU->Read ( DCO ) )
+ {
+ RDDO = new DICOMDataObject;
+
+ if (! (CFindRSP :: Read ( DCO, PDU, RDDO) ) )
+ {
+ return ( FALSE );
+ }
+ if ( DCO->GetUINT16(0x0000, 0x0800) == 0x0101)
+ {
+ CallBack ( DCO, NULL );
+ delete RDDO;
+ delete DCO;
+ return ( TRUE );
+ }
+ CallBack ( DCO, RDDO );
+ if (pADDO) pADDO->Add(RDDO);
+ else delete RDDO;
+ delete DCO;
+ DCO = new DICOMCommandObject;
+ }
+
+ delete DCO;
+ return ( FALSE );
+ }
+
+BOOL StandardRetrieve :: Read (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO)
+ {
+ UID MyUID, uid, iUID, AppUID ("1.2.840.10008.3.1.1.1");
+ VR *vr;
+ DICOMDataObject DDO;
+ Array < DICOMDataObject *> ADDO;
+ UINT Index;
+ BYTE IP [ 64 ], lPort [ 64 ], ACRNema [ 17 ], MyACR[17];
+ StandardStorage *SStorage;
+ DICOMDataObject *iDDO;
+ PDU_Service NewPDU;
+ UINT16 Failed;
+ UINT16 status=0;
+
+ GetUID(MyUID);
+
+ if( ! PDU )
+ return ( FALSE );
+
+ if( ! DCO )
+ return ( FALSE );
+
+ vr = DCO->GetVR(0x0000, 0x0002);
+ SetUID(uid, vr);
+ if (!(MyUID == uid))
+ return ( FALSE );
+
+ if (! CMoveRQ :: Read (DCO, PDU, &DDO) )
+ return ( FALSE ); // my SOP, but wrong command
+
+
+ vr = DCO->GetVR(0x0000, 0x0600);
+ if(!vr)
+ {
+ CMoveRSP :: Write ( PDU, DCO, 0xc001 , 0, 0, 0, 0, NULL );
+ return ( TRUE );
+ }
+
+ memset((void*)ACRNema, 0, 17);
+ if(vr->Length > 16)
+ vr->Length = 16;
+ memcpy((void*)ACRNema, vr->Data, (int) vr->Length);
+ if(!vr->Length)
+ {
+ CMoveRSP :: Write ( PDU, DCO, 0xc002 , 0, 0, 0, 0, NULL );
+ return ( TRUE );
+ }
+
+ if(ACRNema[vr->Length-1]==' ')
+ ACRNema[vr->Length-1] = '\0';
+
+ if(!QualifyOn(ACRNema, MyACR, IP, lPort))
+ {
+ CMoveRSP :: Write ( PDU, DCO, 0xc003 , 0, 0, 0, 0, NULL );
+ return ( TRUE );
+ }
+
+ if (! QueryMoveScript (PDU, DCO, &DDO))
+ {
+ CMoveRSP :: Write (PDU, DCO, 0xc013, 0, 0, 0, 0, NULL );
+ return ( TRUE );
+ }
+
+ if (! SearchOn (&DDO, &ADDO) )
+ {
+ CMoveRSP :: Write ( PDU, DCO, 0xc004, 0, 0, 0, 0, NULL );
+ return ( TRUE );
+ }
+
+ NewPDU.SetApplicationContext ( AppUID );
+ NewPDU.SetLocalAddress ( MyACR );
+ NewPDU.SetRemoteAddress ( ACRNema );
+
+ // Add all the Abstract Syntaxs we need
+
+ Index = 0;
+ while ( Index < ADDO.GetSize() )
+ {
+ vr = ADDO.Get ( Index ) -> GetVR(0x0008, 0x0016);
+ if(!vr)
+ {
+ delete ADDO.Get ( Index );
+ ADDO.RemoveAt ( Index );
+ }
+ else
+ {
+ SetUID ( iUID, vr );
+ NewPDU.AddAbstractSyntax ( iUID );
+ ++Index;
+ }
+ }
+
+ if (!NewPDU.Connect (IP, lPort))
+ {
+ CMoveRSP :: Write ( PDU, DCO, 0xc005 , 0, 0, 0, 0, NULL );
+ return ( TRUE );
+ }
+
+
+ Index = 0;
+ Failed = 0;
+ while ( Index < ADDO.GetSize() )
+ {
+ vr = ADDO.Get ( Index ) -> GetVR(0x0008, 0x0016);
+ SetUID ( iUID, vr );
+ if ( !NewPDU.GetPresentationContextID(iUID) )
+ {
+ ++Failed;
+ // Remote end did not accept this UID
+ }
+ else
+ {
+ if ( !RetrieveOn (ADDO.Get(Index), &iDDO, &SStorage))
+ ++Failed;
+ else
+ {
+ if(!SStorage->Write(&NewPDU, iDDO))
+ {
+ //++Failed;
+ // Remote end should accept this image. if it did
+ // not, then just bail out. Probably means the
+ // TCP/IP link has been dropped.
+ Failed += (ADDO.GetSize() - Index);
+ status = 0xfe00; // mvh 20020429: return cancel status
+ break;
+ }
+
+ delete iDDO;
+ }
+ }
+ CMoveRSP :: Write ( PDU,
+ DCO,
+ 0xff00, ADDO.GetSize() - Index - 1,
+ (UINT16) Index+1, Failed, 0, // mvh 20020429: added +1
+ ADDO.Get ( Index ));
+ delete ADDO.Get ( Index );
+ ++Index;
+ }
+
+ CMoveRSP :: Write ( PDU, DCO, status, 0, (UINT16) Index, Failed, 0, NULL ); // mvh 20020429: replaced 0 by status
+
+ // Incase we broke out from above..
+ while ( Index < ADDO.GetSize () )
+ {
+ delete ADDO.Get(Index);
+ ++Index;
+ }
+
+ return ( TRUE );
+ }
+
+BOOL StandardRetrieve :: Write (
+ PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ BYTE *ACRNema )
+ {
+ DICOMCommandObject *DCO;
+ DICOMDataObject *RDDO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! CMoveRQ :: Write ( PDU, DDO, ACRNema ) )
+ return ( FALSE );
+
+ CallBack ( NULL, DDO );
+
+ DCO = new DICOMCommandObject;
+
+ while ( PDU->Read ( DCO ) )
+ {
+ RDDO = new DICOMDataObject;
+
+ if (! (CMoveRSP :: Read ( DCO, PDU, RDDO) ) )
+ {
+ return ( FALSE );
+ }
+ if ( DCO->GetUINT16(0x0000, 0x0800) == 0x0101)
+ {
+ CallBack ( DCO, NULL );
+ delete RDDO;
+ if ( DCO->GetUINT16(0x0000, 0x0900) != 0x0000)
+ {
+ VR *vr;
+ while ((vr = DCO->Pop()))
+ {
+ //DumpVR(vr);
+ delete vr;
+ }
+ delete DCO;
+ return ( FALSE );
+ }
+ delete DCO;
+ return ( TRUE );
+ }
+ CallBack ( DCO, RDDO );
+ delete RDDO;
+ delete DCO;
+ DCO = new DICOMCommandObject;
+ }
+
+ delete DCO;
+ return ( FALSE );
+ }
+
+BOOL PatientRootQuery :: GetUID ( UID &uid )
+ {
+ uid.Set ( "1.2.840.10008.5.1.4.1.2.1.1" );
+ return ( TRUE );
+ }
+
+BOOL PatientRootRetrieve :: GetUID ( UID &uid )
+ {
+ uid.Set ( "1.2.840.10008.5.1.4.1.2.1.2" );
+ return ( TRUE );
+ }
+
+BOOL StudyRootQuery :: GetUID ( UID &uid )
+ {
+ uid.Set ( "1.2.840.10008.5.1.4.1.2.2.1" );
+ return ( TRUE );
+ }
+
+BOOL StudyRootRetrieve :: GetUID ( UID &uid )
+ {
+ uid.Set ( "1.2.840.10008.5.1.4.1.2.2.2" );
+ return ( TRUE );
+ }
+
+BOOL PatientStudyOnlyQuery :: GetUID ( UID &uid )
+ {
+ uid.Set ( "1.2.840.10008.5.1.4.1.2.3.1" );
+ return ( TRUE );
+ }
+
+BOOL PatientStudyOnlyRetrieve :: GetUID ( UID &uid )
+ {
+ uid.Set ( "1.2.840.10008.5.1.4.1.2.3.2" );
+ return ( TRUE );
+ }
+
+BOOL ModalityWorkListQuery :: GetUID ( UID &uid )
+ {
+ uid.Set ( "1.2.840.10008.5.1.4.31" );
+ return ( TRUE );
+ }
diff --git a/qrsop.hpp b/qrsop.hpp
new file mode 100644
index 0000000..e81da42
--- /dev/null
+++ b/qrsop.hpp
@@ -0,0 +1,204 @@
+/*
+20030606 ljz Added member-variable 'QueryRetrieveLevel' to StandardQuery
+20050401 mvh Added ModalityWorkListQuery
+20051222 mvh Added pADDO to Query::Write method - answer appended to pADDO if set
+20090205 mvh Added QueryMoveScript
+20100816 mvh Added QueryResultScript
+*/
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+// Q/R SOP Class
+
+// Abstract Base Class for Q/R
+
+
+class StandardQuery :
+ public CFindRQ,
+ public CFindRSP
+ {
+ public:
+ char QueryRetrieveLevel[10];
+ public:
+ virtual BOOL GetUID (UID &uid) { return (uGetUID(uid)); };
+ virtual BOOL uGetUID ( UID &) = 0;
+ virtual BOOL QueryMoveScript (PDU_Service*, DICOMCommandObject*, DICOMDataObject *) = 0;
+
+ virtual BOOL QueryResultScript (PDU_Service*, DICOMCommandObject*, DICOMDataObject *) = 0;
+
+ virtual BOOL SearchOn ( DICOMDataObject *,
+ Array < DICOMDataObject *> *) = 0;
+ virtual BOOL CallBack ( DICOMCommandObject *,
+ DICOMDataObject * ) = 0;
+ BOOL Read ( PDU_Service *,
+ DICOMCommandObject *);
+ BOOL Write ( PDU_Service *,
+ DICOMDataObject *, Array < DICOMDataObject *> *);
+
+ };
+
+class StandardRetrieve :
+ public CMoveRQ,
+ public CMoveRSP
+ {
+ public:
+ virtual BOOL GetUID (UID &uid) { return (uGetUID(uid)); };
+ virtual BOOL uGetUID ( UID &) = 0;
+ virtual BOOL QueryMoveScript (PDU_Service*, DICOMCommandObject*, DICOMDataObject *) = 0;
+ virtual BOOL SearchOn ( DICOMDataObject *,
+ Array < DICOMDataObject *> *) = 0;
+ virtual BOOL RetrieveOn ( DICOMDataObject *,
+ DICOMDataObject **,
+ StandardStorage **) = 0;
+ virtual BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE * ) = 0;
+ virtual BOOL CallBack ( DICOMCommandObject *,
+ DICOMDataObject * ) = 0;
+ BOOL Read ( PDU_Service *, DICOMCommandObject * );
+ BOOL Write ( PDU_Service *, DICOMDataObject *, BYTE *);
+ };
+
+class PatientRootQuery :
+ public StandardQuery
+ {
+ public:
+ BOOL GetUID ( UID & );
+ BOOL uGetUID ( UID &uid ) { return ( GetUID(uid) ); };
+
+ inline BOOL Read ( PDU_Service *PDU,
+ DICOMCommandObject *DCO )
+ { return ( StandardQuery :: Read ( PDU, DCO ) ); };
+
+ inline BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO, Array < DICOMDataObject *> *pADDO)
+ { return ( StandardQuery :: Write ( PDU, DDO, pADDO ) ); };
+ };
+
+class PatientRootRetrieve :
+ public StandardRetrieve
+ {
+ public:
+ BOOL GetUID ( UID & );
+ BOOL uGetUID ( UID &uid ) { return ( GetUID(uid) ); };
+
+ inline BOOL Read ( PDU_Service *PDU,
+ DICOMCommandObject *DCO )
+ { return ( StandardRetrieve :: Read ( PDU, DCO ) ); };
+
+ BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ BYTE *ACRNema)
+ { return ( StandardRetrieve :: Write ( PDU,
+ DDO, ACRNema )); };
+ };
+
+class StudyRootQuery :
+ public StandardQuery
+ {
+ public:
+ BOOL GetUID ( UID & );
+ BOOL uGetUID ( UID &uid ) { return ( GetUID(uid) ); };
+
+ inline BOOL Read ( PDU_Service *PDU,
+ DICOMCommandObject *DCO )
+ { return ( StandardQuery :: Read ( PDU, DCO ) ); };
+
+ inline BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO, Array < DICOMDataObject *> *pADDO)
+ { return ( StandardQuery :: Write ( PDU, DDO, pADDO ) ); };
+ };
+
+class StudyRootRetrieve :
+ public StandardRetrieve
+ {
+ public:
+ BOOL GetUID ( UID & );
+ BOOL uGetUID ( UID &uid ) { return ( GetUID(uid) ); };
+
+ inline BOOL Read ( PDU_Service *PDU,
+ DICOMCommandObject *DCO )
+ { return ( StandardRetrieve :: Read ( PDU, DCO ) ); };
+
+ BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ BYTE *ACRNema)
+ { return ( StandardRetrieve :: Write ( PDU,
+ DDO, ACRNema )); };
+ };
+
+class PatientStudyOnlyQuery :
+ public StandardQuery
+ {
+ public:
+ BOOL GetUID ( UID & );
+ BOOL uGetUID ( UID &uid ) { return ( GetUID(uid) ); };
+
+
+ inline BOOL Read ( PDU_Service *PDU,
+ DICOMCommandObject *DCO )
+ { return ( StandardQuery :: Read ( PDU, DCO ) ); };
+
+ inline BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO, Array < DICOMDataObject *> *pADDO)
+ { return ( StandardQuery :: Write ( PDU, DDO, pADDO ) ); };
+ };
+
+class PatientStudyOnlyRetrieve :
+ public StandardRetrieve
+ {
+ public:
+ BOOL GetUID ( UID & );
+ BOOL uGetUID ( UID &uid ) { return ( GetUID(uid) ); };
+
+ inline BOOL Read ( PDU_Service *PDU,
+ DICOMCommandObject *DCO )
+ { return ( StandardRetrieve :: Read ( PDU, DCO ) ); };
+
+ BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO,
+ BYTE *ACRNema)
+ { return ( StandardRetrieve :: Write ( PDU,
+ DDO, ACRNema )); };
+ };
+
+class ModalityWorkListQuery :
+ public StandardQuery
+ {
+ public:
+ BOOL GetUID ( UID & );
+ BOOL uGetUID ( UID &uid ) { return ( GetUID(uid) ); };
+
+
+ inline BOOL Read ( PDU_Service *PDU,
+ DICOMCommandObject *DCO )
+ { return ( StandardQuery :: Read ( PDU, DCO ) ); };
+
+ inline BOOL Write ( PDU_Service *PDU,
+ DICOMDataObject *DDO, Array < DICOMDataObject *> *pADDO)
+ { return ( StandardQuery :: Write ( PDU, DDO, pADDO ) ); };
+ };
diff --git a/regen.cpp b/regen.cpp
new file mode 100644
index 0000000..81abb87
--- /dev/null
+++ b/regen.cpp
@@ -0,0 +1,761 @@
+/*
+MvH 19980327: put messages in one SystemDebug for UDP message layout
+MvH 19980415: changed messages to OperatorConsole
+MvH 19980605: Need to add regen for optical devices and cachedevices !!!!!
+MvH 19981218: temp use pdu.load
+ljz 19990108: Replaced PDU.Load by LoadImplicitLittleEndian in RegenToDatabase
+MvH 19990109: Set HeaderOnly flag for LoadImplicitLittleEndianFile to TRUE
+ Added regen of CACHE and JUKEBOX devices;
+ NOTE: full regen imposes name restrictions on JUKEBOX and CACHE directories
+MvH 19990117: Filenames with .v2 are assumed raw; added extension .dcm for chapter 10 format
+ljz 19990317: Parameters of LoadImplicitLittleEndianFile have been changed
+mvh 19990521: .img files react same as .dcm files
+ljz 20000629: Logging of trouble now starts with '***'
+mvh 20010415: Added SubDir parameter to regen to allow regen of one directory only
+mvh 20010416: Added RegenFile - to allow modification of images
+mvh 20011109: Made file extension checking case insensitive
+mvh 20020409: Experimental multithread version.
+mvh 20020413: Made NTHREADS variable and tested. Time to regen 6900 files:
+ # time (min:s)
+ 1 5:41
+ 4 4:06
+ 10 3:34
+ 20 3:14
+ 40 3:41
+ 100 3:36 gives sql server deadlock errors (even with 20xretry)
+
+ 20 using PDU 10:48 (CPU limited)
+ 20 using 64 cache 3:09
+ 20 using 128 cache 3:05
+ 20 using 512 cache 3:06
+ 20 using 1024 cache 3:00
+ 20 using 1000 cache 2:37 (?)
+ 20 using 1000 cache 3:08
+ 1 using 256,unique index 4:13 <- chosen because is reliable and fast
+ 20 using 1000,uniqueindex 3:14
+ 1 using 256,unique index 3:40 with new buffered loadddo code by ljz
+mvh 20020415: Tested with new loaddo code by ljz.
+ Note: multithread works and has allowed fixing MT some errors in other
+ modules. However, due to a problem in concurrent db writing (in
+ UpdateOrAddToTable) it should not be used clinically.
+ljz 20020613: Removed some warnings
+mvh 20020802: Simplified regen code; traverse subdirectories recursively (allow e.g., e-film data format)
+mvh 20020804: Use PATHSEPCHAR where possible
+mvh 20021014: Exclude directory PRINTER_FILES during regen (contains slices without ID and such)
+ljz 20030120: Removed some warnings
+mvh 20030706: Attach VRType to PDU for implicit little endian support
+mvh 20030819: Allow longer filenames
+mvh 20040614: Do not regen CACHE devices; first regen JUKEBOX then MAG (e.g., in historical order)
+mvh 20050118: Adapted for LINUX compile
+mvh 20060628: AddToDatabase has JustAdd parameter
+mvh 20070210: Increased maxvrsize for regen v2 files from 0x400 to 0x4000 -> UIDs were sometimes not found
+bcb 20070308: Ignore .DS_Store for DARWIN
+bcb 20091231: Changed char* to const char* for gcc4.2 warnings
+mvh 20100111: Merged; fixed WIN32 changes
+mvh 20120630: Regen now allows files without 3 letter extension
+*/
+
+// #define MULTITHREAD
+# include "dgate.hpp"
+
+#ifdef MULTITHREAD
+#define NTHREADS 20
+static void regen_queue(char *basename, char *filename, char *device);
+static int queueempty();
+#endif
+
+#ifdef WIN32
+#define PATHSEPSTR "\\"
+#define PATHSEPCHAR '\\'
+#else
+#define PATHSEPSTR "/"
+#define PATHSEPCHAR '/'
+#define stricmp(s1, s2) strcasecmp(s1, s2)
+#include <unistd.h>
+#include <dirent.h>
+#endif
+
+#ifndef WIN32
+BOOL IsDirectory(char *path)
+ {
+ char temp[1024];
+ struct stat statbuf;
+
+ int lc= strlen(path) - 1; /* index for last char in path */
+ strcpy(temp, path);
+
+ if (temp[lc] == '\\' || temp[lc] == '/')
+ temp[lc] = 0;
+
+ if (stat(temp, &statbuf) == -1) return FALSE; /* file or path not found */
+
+ if (statbuf.st_mode & S_IFDIR)
+ return TRUE;
+ else
+ return FALSE;
+ }
+#endif
+
+// This routine checks the file extension and only accepts v2=raw, dcm/img=chapter 10 (or other)
+
+BOOL
+RegenToDatabase(Database *DB, char *basename, char *filename, const char *device)
+ {
+ DICOMDataObject* pDDO;
+ int len;
+ PDU_Service PDU;
+
+ PDU.AttachRTC(&VRType);
+
+ len = strlen(filename);
+
+ // The excludes some impossible short names (including path) like a.v2 which are unlikely to occur
+
+ if (len < 4) return FALSE;
+
+ if (stricmp(filename + len - 3, ".v2")==0 )
+ {
+ pDDO = LoadImplicitLittleEndianFile(filename, 0x4000); // increased from 400 to allow load large icons
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[Regen] %s -FAILED: Error on Load\n", filename);
+ return ( FALSE );
+ }
+ }
+ else if (stricmp(filename + len - 4, ".dcm")==0 ||
+ stricmp(filename + len - 4, ".img")==0 ||
+ strchr(filename + len - 4, '.')==NULL
+ )
+ {
+ pDDO = PDU.LoadDICOMDataObject(filename);
+ if(!pDDO)
+ {
+ OperatorConsole.printf("***[Regen] %s -FAILED: Error on Load\n", filename);
+ return ( FALSE );
+ }
+ }
+ else
+ return FALSE;
+
+ if(!SaveToDataBase(*DB, pDDO, basename, device, FALSE))
+ {
+ delete pDDO;
+ OperatorConsole.printf("***[Regen] %s -FAILED: Error SQL Add\n", filename);
+ return ( FALSE );
+ }
+ delete pDDO;
+ OperatorConsole.printf("[Regen] %s -SUCCESS\n", filename);
+ return ( TRUE );
+ }
+
+// This function enters a file into the database, assuming it is on one of the MAG devices
+
+BOOL
+RegenFile(char *filename)
+ {
+ Database DB;
+ UINT Index;
+ char Device[255], Physical[1024], BaseName[1024];
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ fprintf(stderr, "Error Connecting to SQL\n");
+ return ( FALSE );
+ }
+
+
+ Index = 0;
+ while ( Index < MAGDevices )
+ {
+ sprintf(Device, "MAG%d", Index);
+ GetPhysicalDevice(Device, Physical);
+ if (memicmp(Physical, filename, strlen(Physical))==0)
+ {
+ strcpy(BaseName, filename + strlen(Physical));
+ RegenToDatabase(&DB, BaseName, filename, Device);
+ break;
+ }
+ ++Index;
+ }
+
+ if (Index == MAGDevices)
+ {
+ fprintf(stderr, "File to enter is not on a MAG device\n");
+ return ( FALSE );
+ }
+
+ return ( TRUE );
+ }
+
+
+// Help function to regen an arbitrary directory (PathString must end with PATHSEPSTR)
+
+#ifdef WIN32
+
+BOOL RegenDir(Database *DB, char *PathString, const char *Device)
+ {
+ HANDLE fdHandle;
+ WIN32_FIND_DATA FileData;
+
+ char TempPath[1024];
+ char Physical[1024];
+
+ GetPhysicalDevice(Device, Physical);
+
+ strcpy(TempPath, PathString);
+ strcat(TempPath, "*.*");
+
+ // Traverse first level of subdirectories
+
+ fdHandle = FindFirstFile(TempPath, &FileData);
+ if(fdHandle == INVALID_HANDLE_VALUE)
+ return ( FALSE );
+
+ while ( TRUE )
+ {
+ if (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
+ {
+ if
+ (
+ stricmp(FileData.cFileName, "INCOMING") != 0 &&
+ stricmp(FileData.cFileName, "PRINTER_FILES") != 0 &&
+ strcmp(FileData.cFileName, ".") != 0 &&
+ strcmp(FileData.cFileName, "..") != 0 &&
+ stricmp(FileData.cFileName, "BIN") != 0
+ )
+ {
+ strcpy(TempPath, PathString);
+ strcat(TempPath, FileData.cFileName);
+ strcat(TempPath, PATHSEPSTR);
+ RegenDir(DB, TempPath, Device);
+ }
+ }
+ else
+ {
+ strcpy(TempPath, PathString);
+ strcat(TempPath, FileData.cFileName);
+
+ RegenToDatabase (DB, TempPath + strlen(Physical), TempPath, Device);
+ }
+
+ if(!FindNextFile(fdHandle, &FileData))
+ break;
+ }
+
+ FindClose(fdHandle);
+
+ return TRUE;
+ }
+
+#else // linux version
+
+BOOL RegenDir(Database *DB, char *PathString, const char *Device)
+ {
+ DIR *dird;
+ dirent *diren;
+
+ char TempPath[1024];
+ char Physical[1024];
+ char *n;
+
+ GetPhysicalDevice(Device, Physical);
+
+ strcpy(TempPath, PathString);
+ TempPath[strlen(TempPath)-1]=0;
+
+ // Traverse first level of subdirectories
+
+ dird = opendir(TempPath);
+ if(dird == NULL)
+ return ( FALSE );
+
+ while ( TRUE )
+ {
+ diren = readdir(dird);
+ if (diren)
+ {
+ n = diren->d_name;
+ strcpy(TempPath, PathString);
+ strcat(TempPath, n);
+
+ if (IsDirectory(TempPath))
+ {
+ if
+ (
+ stricmp(n, "INCOMING" ) != 0 &&
+ stricmp(n, "PRINTER_FILES") != 0 &&
+ strcmp (n, "." ) != 0 &&
+ strcmp (n, ".." ) != 0 &&
+ stricmp(n, "BIN" ) != 0
+#ifdef DARWIN //A Macintosh OS X file.
+ && stricmp(n, ".DS_Store" ) != 0
+#endif //DARWIN
+ )
+ {
+ strcat(TempPath, PATHSEPSTR);
+ RegenDir(DB, TempPath, Device);
+ }
+ }
+ else
+ {
+ RegenToDatabase (DB, TempPath + strlen(Physical), TempPath, Device);
+ }
+ }
+ else
+ break;
+ }
+
+ closedir(dird);
+
+ return TRUE;
+ }
+
+#endif
+
+// This Regen function recurses a single level of subdirecties if IsCacheOrJukeBox is FALSE
+// it recurses a two levels of subdirecties if IsCacheOrJukeBox is TRUE
+
+#ifdef WIN32
+
+BOOL
+Regen(const char *Device, int IsCacheOrJukeBox, char *SubDir)
+ {
+ int itemp, i, j, CDNumber, JUKEBOXNumber;
+ Database DB;
+ HANDLE fdHandle;
+ WIN32_FIND_DATA FileData;
+ char PathString[1024], TempPath[1024], FileString[1024];
+ char ActualDevice[256];
+ char *p;
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ fprintf(stderr, "Error Connecting to SQL\n");
+ return ( FALSE );
+ }
+
+ // convert device specification to a path
+
+ GetPhysicalDevice(Device, PathString);
+ itemp = strlen(PathString);
+ if(!itemp)
+ return FALSE;
+
+ // strip the last subdirectory (e.g., CD0_%04d) for regen of complete CACHE or JUKEBOX devices
+
+ if (IsCacheOrJukeBox)
+ {
+ PathString[itemp-1]=0;
+ p = strrchr(PathString, PATHSEPCHAR);
+ if (p) p[0]=0;
+ OperatorConsole.printf("Regen directory = %s\n", PathString);
+ itemp = strlen(PathString);
+ if(!itemp)
+ return (FALSE);
+ }
+
+ // add a '/' to end of directory name if not yet present
+
+ if(PathString[itemp-1] != PATHSEPCHAR)
+ strcat(PathString, PATHSEPSTR);
+
+ // PathString now contains Image file storage root directory path
+ // Regen all files and subdirectories below that or only the selected subdirectory
+
+ if (!IsCacheOrJukeBox)
+ {
+ if (SubDir)
+ {
+ strcat(PathString, SubDir);
+ strcat(PathString, PATHSEPSTR);
+ }
+
+ return RegenDir(&DB, PathString, Device);
+ }
+
+ // remaining code is for cache or jukebox devices
+
+ strcpy(TempPath, PathString);
+ strcat(TempPath, "*.*");
+
+ fdHandle = FindFirstFile(TempPath, &FileData);
+ if(fdHandle == INVALID_HANDLE_VALUE)
+ return ( FALSE );
+
+ while ( TRUE )
+ {
+ // traverse one level for CD or cache directories (CDs to be burned)
+ if (strcmp(FileData.cFileName, ".") != 0 &&
+ strcmp(FileData.cFileName, "..") != 0
+ )
+ {
+ strcpy(FileString, FileData.cFileName);
+
+ // Decompose jukebox directory name to find CD number
+ // Directory name must be like aaaCCCC where C=CD number a=non-number
+ if(strnicmp(Device, "JUKEBOX", 7)==0)
+ {
+ CDNumber = 0;
+ for (i=strlen(FileString)-1; i>=0; i--)
+ {
+ if (FileString[i] < '0' || FileString[i] > '9')
+ {
+ CDNumber = atoi(FileString + i + 1);
+ break;
+ }
+ }
+ sprintf(ActualDevice, "%s.%d", Device, CDNumber);
+ }
+
+ // Decompose cache directory name to find CD number and jukebox number
+ // Directory name must be like aaaJJaCCCC where C=CD# J=jukebox# a=non-number
+ if(strnicmp(Device, "CACHE", 5)==0)
+ {
+ CDNumber = 0;
+ JUKEBOXNumber = 0;
+ for (i=strlen(FileString)-1; i>=0; i--)
+ {
+ if (FileString[i] < '0' || FileString[i] > '9')
+ {
+ CDNumber = atoi(FileString + i + 1);
+ for (j=i-1; j>=0; j--)
+ {
+ if (FileString[j] < '0' || FileString[j] > '9')
+ {
+ JUKEBOXNumber = atoi(FileString + j + 1);
+ break;
+ }
+ }
+ break;
+ }
+ }
+ sprintf(ActualDevice, "%s.%d.%d", Device, JUKEBOXNumber, CDNumber);
+ }
+
+ strcpy(TempPath, PathString);
+ strcat(TempPath, FileString);
+ strcat(TempPath, PATHSEPSTR);
+
+ RegenDir(&DB, TempPath, ActualDevice);
+ }
+
+
+ if(!FindNextFile(fdHandle, &FileData))
+ break;
+ }
+ FindClose ( fdHandle );
+
+#ifdef MULTITHREAD
+ while(!queueempty()) Sleep(100);
+#endif
+
+ return ( TRUE );
+ }
+
+#else // linux version
+
+BOOL
+Regen(const char *Device, int IsCacheOrJukeBox, char *SubDir)
+ {
+ int itemp, i, j, CDNumber, JUKEBOXNumber;
+ Database DB;
+ DIR *dird;
+ dirent *diren;
+ char PathString[1024], TempPath[1024], FileString[1024];
+ char ActualDevice[256];
+ char *p;
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ fprintf(stderr, "Error Connecting to SQL\n");
+ return ( FALSE );
+ }
+
+ // convert device specification to a path
+
+ GetPhysicalDevice(Device, PathString);
+ itemp = strlen(PathString);
+ if(!itemp)
+ return FALSE;
+
+ // strip the last subdirectory (e.g., CD0_%04d) for regen of complete CACHE or JUKEBOX devices
+
+ if (IsCacheOrJukeBox)
+ {
+ PathString[itemp-1]=0;
+ p = strrchr(PathString, PATHSEPCHAR);
+ if (p) p[0]=0;
+ OperatorConsole.printf("Regen directory = %s\n", PathString);
+ itemp = strlen(PathString);
+ if(!itemp)
+ return (FALSE);
+ }
+
+ // add a '/' to end of directory name if not yet present
+
+ if(PathString[itemp-1] != PATHSEPCHAR)
+ strcat(PathString, PATHSEPSTR);
+
+ // PathString now contains Image file storage root directory path
+ // Regen all files and subdirectories below that or only the selected subdirectory
+
+ if (!IsCacheOrJukeBox)
+ {
+ if (SubDir)
+ {
+ strcat(PathString, SubDir);
+ strcat(PathString, PATHSEPSTR);
+ }
+
+ return RegenDir(&DB, PathString, Device);
+ }
+
+ // remaining code is for cache or jukebox devices
+
+ strcpy(TempPath, PathString);
+ TempPath[strlen(TempPath)-1]=0;
+
+ dird = opendir(TempPath);
+ if(dird == NULL)
+ return ( FALSE );
+
+ while ( TRUE )
+ {
+
+ diren = readdir(dird);
+ if (!diren) break;
+
+ // traverse one level for CD or cache directories (CDs to be burned)
+ if (strcmp(diren->d_name, ".") != 0 &&
+ strcmp(diren->d_name, "..") != 0
+ )
+ {
+ strcpy(FileString, diren->d_name);
+
+ // Decompose jukebox directory name to find CD number
+ // Directory name must be like aaaCCCC where C=CD number a=non-number
+ if(strnicmp(Device, "JUKEBOX", 7)==0)
+ {
+ CDNumber = 0;
+ for (i=strlen(FileString)-1; i>=0; i--)
+ {
+ if (FileString[i] < '0' || FileString[i] > '9')
+ {
+ CDNumber = atoi(FileString + i + 1);
+ break;
+ }
+ }
+ sprintf(ActualDevice, "%s.%d", Device, CDNumber);
+ }
+
+ // Decompose cache directory name to find CD number and jukebox number
+ // Directory name must be like aaaJJaCCCC where C=CD# J=jukebox# a=non-number
+ if(strnicmp(Device, "CACHE", 5)==0)
+ {
+ CDNumber = 0;
+ JUKEBOXNumber = 0;
+ for (i=strlen(FileString)-1; i>=0; i--)
+ {
+ if (FileString[i] < '0' || FileString[i] > '9')
+ {
+ CDNumber = atoi(FileString + i + 1);
+ for (j=i-1; j>=0; j--)
+ {
+ if (FileString[j] < '0' || FileString[j] > '9')
+ {
+ JUKEBOXNumber = atoi(FileString + j + 1);
+ break;
+ }
+ }
+ break;
+ }
+ }
+ sprintf(ActualDevice, "%s.%d.%d", Device, JUKEBOXNumber, CDNumber);
+ }
+
+ strcpy(TempPath, PathString);
+ strcat(TempPath, FileString);
+ strcat(TempPath, PATHSEPSTR);
+
+ RegenDir(&DB, TempPath, ActualDevice);
+ }
+ }
+ closedir(dird);
+
+#ifdef MULTITHREAD
+ while(!queueempty()) sleep(1);
+#endif
+
+ return ( TRUE );
+ }
+
+#endif
+
+// Regen *Each* device
+BOOL
+Regen()
+ {
+ UINT Index;
+ char s[20];
+
+// Index = 0;
+// while ( Index < CACHEDevices )
+// {
+// sprintf(s, "CACHE%d", Index);
+// printf("Regen Device '%s'\n", s);
+// Regen(s, TRUE);
+// ++Index;
+// }
+
+ Index = 0;
+ while ( Index < JUKEBOXDevices )
+ {
+ sprintf(s, "JUKEBOX%d", Index);
+ printf("Regen Device '%s'\n", s);
+ Regen(s, TRUE);
+ ++Index;
+ }
+
+ Index = 0;
+ while ( Index < MAGDevices )
+ {
+ sprintf(s, "MAG%d", Index);
+ printf("Regen Device '%s'\n", s);
+ Regen(s, FALSE);
+ ++Index;
+ }
+
+ return(FALSE);
+ }
+
+
+//////////////////////////////////////////////////////////////////////////////////
+// This code is a simple thread safe queue with its own processing thread (WIN32 only)
+//////////////////////////////////////////////////////////////////////////////////
+
+#ifdef MULTITHREAD
+
+static struct queue
+{ int top;
+ int bottom;
+ int num;
+ int entrysize;
+ char *data;
+ HANDLE threadhandle;
+ int delay;
+ CRITICAL_SECTION critical;
+ void (*process)(char *);
+} q1;
+
+static BOOL WINAPI processthread(struct queue *q)
+{ char *data = (char *)malloc(q->entrysize);
+
+ while (1)
+ { while (1)
+ { EnterCriticalSection(&q->critical);
+
+ if (q->top!=q->bottom)
+ { memcpy(data, q->data + q->bottom * q->entrysize, q->entrysize);
+ q->bottom = (q->bottom+1)%q->num;
+ LeaveCriticalSection(&q->critical);
+
+ q->process(data);
+
+ break;
+ }
+
+ LeaveCriticalSection(&q->critical);
+ Sleep(q->delay);
+ }
+ }
+
+ DeleteCriticalSection(&q->critical);
+
+ return TRUE;
+}
+
+static struct queue *new_queue(int num, int size, int delay, void (*process)(char *))
+{ struct queue *result;
+ unsigned long ThreadID;
+
+ result = new queue;
+ result->top = 0;
+ result->bottom = 0;
+ result->num = num;
+ result->entrysize = size;
+ result->delay = delay;
+ result->process = process;
+ result->data = (char *)malloc(num * size);
+
+ InitializeCriticalSection(&result->critical);
+
+ /* Note: since the queue is thread safe it is possible to start more than one thread to service it */
+
+ result->threadhandle =
+ CreateThread(NULL, 0x000ff000, (LPTHREAD_START_ROUTINE) processthread, result, 0, &ThreadID);
+
+ return result;
+};
+
+static void into_queue(struct queue *q, char *in)
+{ while (1)
+ { EnterCriticalSection(&q->critical);
+ if ((q->top+1)%q->num != q->bottom)
+ { memcpy(q->data + q->top * q->entrysize, in, q->entrysize);
+ q->top = (q->top+1)%q->num;
+ LeaveCriticalSection(&q->critical);
+ return;
+ }
+
+ LeaveCriticalSection(&q->critical);
+ Sleep(q->delay);
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+static struct queue *q[NTHREADS];
+static int qp=0;
+static Database *DBs[NTHREADS];
+
+static void regenprocess(char *data)
+{ Database *DB;
+ memcpy(&DB, data, sizeof(Database *));
+ RegenToDatabase(DB, data+128, data+256, data+32);
+}
+
+static void regen_queue(char *basename, char *filename, char *device)
+{ char data[1512];
+ int i;
+
+ if (!q[0])
+ { for(i=0; i<NTHREADS; i++)
+ { q[i] = new_queue(50, 1512, 10, regenprocess);
+ DBs[i] = new Database;
+ if (!DBs[i]->Open ( DataSource, UserName, Password, DataHost ) )
+ { fprintf(stderr, "Error Connecting to SQL\n");
+ return;
+ }
+ }
+ qp=0;
+ }
+
+ memcpy(data, &DBs[qp], sizeof(Database *));
+ strcpy(data+32, device);
+ strcpy(data+128, basename);
+ strcpy(data+256, filename);
+
+ into_queue(q[qp], data);
+ qp = (qp+1)%NTHREADS;
+}
+
+static int queueempty()
+{ int i;
+
+ for(i=0; i<NTHREADS; i++)
+ if (q[i]->top!=q[i]->bottom) return 0;
+
+ return 1;
+}
+
+#endif
diff --git a/rtc.cxx b/rtc.cxx
new file mode 100644
index 0000000..67de467
--- /dev/null
+++ b/rtc.cxx
@@ -0,0 +1,796 @@
+
+/*
+19980330 ljz Added an RTC memberfunction for loading the dicom
+ library from memory (e.g. a resource).
+19980331 ljz Added function for writing binary RTCs (function was
+ originally implemeted in 'makebrtc.cxx'
+19980414 ljz Added RTC::GetGroupElement memberfunction, to retrieve the
+ Group and Element numbers using a library-keyword.
+20040930 ljz Also return TypeCode in RTC.GetGroupElement()
+20071128 mvh Do not remove existing TypeCode if new one is unknown
+20090620 jf Always include stdlib.h
+20091028 ljz pack(4) for __Binary_RTC_Header
+20091029 ljz More adjustments for 64-bits (reading/writing binary RTC)
+20100309 bcb Changed int to unsigned int, commented out unused variables (gcc4.2 Warnings)
+20100717 mvh Merged
+20130503 lsp Make sure that padding bytes are set to zero
+20130508 lsp Use delete [] StringTable rather than delete StringTable as indicated by Klocwork
+20130619 lsp Added fclose(fp) before return, added checks to AttachBinaryRTC(),
+ again as indicated by Klocwork
+*/
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/**********************************************************************
+ *
+ * Run-Time-Class support
+ *
+ **********************************************************************/
+# include "dicom.hpp"
+
+#include <stdlib.h> //DUCKHEAD92
+
+BOOL
+Pack(
+ BYTE c1,
+ BYTE c2,
+ UINT16 &u1)
+ {
+
+ if('OB'==20290)
+ u1 = (((UINT16)c1)<<8)+((UINT16)c2);
+ else
+ u1 = (((UINT16)c2)<<8)+((UINT16)c1);
+
+ return ( TRUE );
+ }
+
+BOOL
+Pack(
+ UINT16 u1,
+ BYTE &c1,
+ BYTE &c2)
+ {
+ if('OB'==20290)
+ {
+ c1 = (u1 >> 8);
+ c2 = (u1 & 0xff);
+ }
+ else
+ {
+ c2 = (u1 >> 8);
+ c1 = (u1 & 0xff);
+ }
+ return ( TRUE );
+ }
+RTC :: RTC (
+ BOOL CD,
+ char *filename)
+#ifdef __GNUC__// The GCC way.
+: TypeCodes(NULL), CarryDescriptions(CD)
+ {
+#else
+ {
+ TypeCodes = NULL;
+ CarryDescriptions = CD;
+#endif
+ AttachRTC(filename);
+ }
+
+RTC :: ~RTC ()
+ {
+ DetachRTC ();
+ }
+
+BOOL
+RTC :: DetachRTC ()
+ {
+ UINT Index;
+
+ if ( TypeCodes )
+ {
+ Index = 0;
+ while ( Index < TypeCodes->GetSize() )
+ {
+ if (TypeCodes->Get(Index).Description)
+ {
+ /*printf("Deleting Description: %4.4x, %4.4%, %x\n",
+ TypeCodes->Get(Index).Group,
+ TypeCodes->Get(Index).Element,
+ TypeCodes->Get(Index).Description);fflush(stdout);*/
+ delete TypeCodes->Get(Index).Description;
+ }
+ ++Index;
+ }
+ delete TypeCodes;
+ }
+ TypeCodes = NULL;
+ return ( TRUE );
+ }
+
+static BOOL
+__rtc_isHexDigit(char ch)
+ {
+ if((ch>='0')&&(ch<='9'))
+ return ( TRUE );
+ if((ch>='a')&&(ch<='f'))
+ return ( TRUE );
+ if((ch>='A')&&(ch<='F'))
+ return ( TRUE );
+ return ( FALSE );
+ }
+
+static BOOL
+__rtc_iswhitespace(char ch)
+ {
+ switch ( ch )
+ {
+ case '\'':
+ case ',':
+ case ' ':
+ case '\"':
+ return ( TRUE );
+ }
+ return ( FALSE );
+ }
+
+static UINT16
+__rtc_HexDigit(char ch)
+ {
+ if((ch>='a')&&(ch<='f'))
+ return(ch-'a'+10);
+ if((ch>='A')&&(ch<='F'))
+ return(ch-'A'+10);
+ return(ch-'0');
+ }
+
+static UINT16
+ex_ascii_to_uint16(char *string)
+ {
+ if(strlen(string)<3)
+ return((UINT16)atoi(string));
+ if((string[1]=='x')||(string[1]=='X'))
+ {
+ UINT16 Val = 0;
+ char *s = &string[2];
+
+ while ( *s )
+ {
+ Val = (Val << 4) + __rtc_HexDigit(*s);
+ ++s;
+ }
+ return ( Val );
+ }
+ return ((UINT16)atoi(string));
+ }
+
+BOOL
+RTC :: AttachRTC(
+ char *filename)
+ {
+ FILE *fp;
+ UINT Index, DIndex;
+ Array < RTCElement > TArray;
+ RTCElement VRT;
+
+ char s[1024];
+ char s1[1024];
+
+ if ( ! filename )
+ return ( FALSE );
+
+ fp = fopen ( filename, "r" );
+ if ( ! fp )
+ return ( FALSE );
+
+ fgets ( s, 1024 - sizeof( INT ), fp );
+ if(!strncmp(s, "#!BinRTC", 8))
+ {
+ fclose(fp);
+ return(AttachBinaryRTC(filename));
+ }
+ while ( ! feof ( fp ) )
+ {
+ if ( s[0] != '{' )
+ {
+ if ( s[0] != '(' )
+ {
+ fgets( s, 1024 - sizeof(INT), fp);
+ continue;
+ }
+ }
+ if(s[0] == '{')
+ {
+ // NIH / Dejarnette Data dictionary format
+ Index = 1;
+ while ( __rtc_iswhitespace(s[Index]) )
+ {
+ ++Index;
+ if ( ! s[ Index ] )
+ {
+ fgets (s, 1024 - sizeof(INT), fp );
+ continue;
+ }
+ }
+ DIndex = 0;
+ while ( !__rtc_iswhitespace(s[Index]) )
+ {
+ s1[DIndex] = s[Index];
+ ++DIndex;++Index;
+ if ( !s[Index] )
+ {
+ fgets (s, 1024 - sizeof(INT), fp );
+ continue;
+ }
+ }
+ s1[DIndex] = '\0';
+ VRT.Group = ex_ascii_to_uint16(s1);
+
+ while ( __rtc_iswhitespace(s[Index]) )
+ {
+ ++Index;
+ if ( ! s[ Index ] )
+ {
+ fgets (s, 1024 - sizeof(INT), fp );
+ continue;
+ }
+ }
+ DIndex = 0;
+ while ( !__rtc_iswhitespace(s[Index]) )
+ {
+ s1[DIndex] = s[Index];
+ ++DIndex;++Index;
+ if ( !s[Index] )
+ {
+ fgets (s, 1024 - sizeof(INT), fp );
+ continue;
+ }
+ }
+ s1[DIndex] = '\0';
+ VRT.Element = ex_ascii_to_uint16(s1);
+
+ while ( __rtc_iswhitespace(s[Index]) )
+ {
+ ++Index;
+ if ( ! s[ Index ] )
+ {
+ fgets (s, 1024 - sizeof(INT), fp );
+ continue;
+ }
+ }
+ DIndex = 0;
+ while ( !__rtc_iswhitespace(s[Index]) )
+ {
+ s1[DIndex] = s[Index];
+ ++DIndex;++Index;
+ if ( !s[Index] )
+ {
+ fgets (s, 1024 - sizeof(INT), fp );
+ continue;
+ }
+ }
+ s1[DIndex] = '\0';
+ Pack((BYTE)s1[0],(BYTE)s1[1],VRT.TypeCode);
+
+ while ( __rtc_iswhitespace(s[Index]) )
+ {
+ ++Index;
+ if ( ! s[ Index ] )
+ {
+ fgets (s, 1024 - sizeof(INT), fp );
+ continue;
+ }
+ }
+ DIndex = 0;
+ while ( s[Index]!='\"' )
+ {
+ if(s[Index]=='\\')
+ ++Index;
+ s1[DIndex] = s[Index];
+ ++DIndex;++Index;
+ if ( !s[Index] )
+ {
+ fgets (s, 1024 - sizeof(INT), fp );
+ continue;
+ }
+ }
+ s1[DIndex] = '\0';
+ if ( CarryDescriptions )
+ {
+ VRT.Description = new char [ Index + 1];
+ strcpy(VRT.Description, s1);
+ }
+ else
+ VRT.Description = NULL;
+
+ TArray.Add(VRT);
+ fgets(s,1024 - sizeof(INT), fp);
+ }
+ else
+ {
+ // David Clunie style data dictionary
+ VRT.Group = 0;
+ VRT.Element = 0;
+ VRT.TypeCode = 0;
+ VRT.Description = NULL;
+
+ unsigned char Digit;
+ char *cPtr = &s[1];
+
+ Digit = __rtc_HexDigit(*cPtr);++cPtr;
+ VRT.Group = (VRT.Group << 4) + Digit;
+ Digit = __rtc_HexDigit(*cPtr);++cPtr;
+ VRT.Group = (VRT.Group << 4) + Digit;
+ Digit = __rtc_HexDigit(*cPtr);++cPtr;
+ VRT.Group = (VRT.Group << 4) + Digit;
+ Digit = __rtc_HexDigit(*cPtr);++cPtr;
+ VRT.Group = (VRT.Group << 4) + Digit;
+
+ while(!__rtc_isHexDigit((*cPtr)))
+ ++cPtr;
+
+ Digit = __rtc_HexDigit(*cPtr);++cPtr;
+ VRT.Element = (VRT.Element << 4) + Digit;
+ Digit = __rtc_HexDigit(*cPtr);++cPtr;
+ VRT.Element = (VRT.Element << 4) + Digit;
+ Digit = __rtc_HexDigit(*cPtr);++cPtr;
+ VRT.Element = (VRT.Element << 4) + Digit;
+ Digit = __rtc_HexDigit(*cPtr);++cPtr;
+ VRT.Element = (VRT.Element << 4) + Digit;
+
+
+ // Now scan for 'VR=" and Keyword=" strings
+
+ char *vType = strstr(cPtr, "VR=\"");
+ if(!vType)
+ {
+ fgets(s,1024 - sizeof(INT), fp);
+ continue; // if there's no type code.. don't bother
+ }
+
+ vType += 4;
+ Pack((BYTE)vType[0],(BYTE)vType[1],VRT.TypeCode);
+
+ if ( CarryDescriptions )
+ {
+ char *Desc = strstr(vType, "Keyword=\"");
+
+ if(Desc)
+ {
+// char s1[1024];// Already declared above. bcb
+
+ strcpy(s1, &Desc[9]);
+ char *vTemp = strchr(s1, '\"');
+ if(vTemp)
+ {
+ (*vTemp) = '\0';
+ VRT.Description = new char[strlen(Desc)+1];
+ strcpy(VRT.Description, s1);
+ }
+
+ }
+ }
+ TArray.Add(VRT);
+ fgets(s,1024 - sizeof(INT), fp);
+ }
+ }
+ fclose(fp);
+ if ( ! TArray.GetSize() )
+ return ( FALSE );
+
+ DetachRTC();
+ TypeCodes = new FixedArray < UINT32, RTCElement > (TArray.GetSize(), TRUE);
+ if ( ! TypeCodes )
+ return ( FALSE );
+ UINT32 GCode;
+ while ( TArray.GetSize() )
+ {
+ VRT = TArray.Get(0);
+ TArray.RemoveAt(0);
+ GCode = MAKEUINT32(VRT.Group, VRT.Element);
+ TypeCodes->Add(GCode, VRT);
+ }
+ TypeCodes->Sort();
+ return ( TRUE );
+ }
+
+UINT16
+RTC :: RunTimeClass (
+ UINT16 Group,
+ UINT16 Element,
+ char *Desc)
+ {
+ INT Index;
+ UINT32 GCode;
+ RTCElement VRT;
+
+ if ( Desc )
+ (*Desc) = '\0';
+
+ if ( ! TypeCodes )
+ return ( 0 );
+
+ GCode = MAKEUINT32(Group, Element);
+ Index = TypeCodes->IndexOf(GCode);
+ if ( Index < 0)
+ return ( 0 );
+
+ VRT = TypeCodes->Get(Index);
+ if(Desc)
+ if(VRT.Description)
+ strcpy(Desc, VRT.Description);
+
+ return (VRT.TypeCode);
+ }
+
+BOOL
+RTC :: RunTimeClass(VR *vr)
+ {
+ UINT16 TypeCode = RunTimeClass(vr->Group, vr->Element, NULL);
+
+ // do not remove existing TypeCode if new one is unknown
+ if ( TypeCode && !vr->TypeCode )
+ vr->TypeCode = TypeCode;
+
+ if ( TypeCode )
+ return ( TRUE );
+ return ( FALSE );
+ }
+
+BOOL
+RTC :: RunTimeClass(DICOMObject *DO)
+ {
+ DICOMObject TempObject;
+ VR *vr;
+
+ while (( vr = DO->Pop() ))
+ {
+ RunTimeClass(vr);
+ TempObject.Push(vr);
+ }
+ while (( vr = TempObject.Pop() ))
+ {
+ DO->Push(vr);
+ }
+ return ( TRUE );
+ }
+
+BOOL
+RTC :: GetGroupElement(RTCElement* pEntry)
+{
+ int iArraySize;
+ int i;
+ RTCElement Entry;
+
+ iArraySize = TypeCodes->GetSize();
+ for (i=0; i< iArraySize; i++)
+ {
+ Entry = TypeCodes->Get(i);
+ if (Entry.Description)
+ if (strcmp(Entry.Description, pEntry->Description) == 0)
+#ifdef __GNUC__ // Changed for warning and less code.
+ {
+ pEntry->Group = Entry.Group;
+ pEntry->Element = Entry.Element;
+ pEntry->TypeCode = Entry.TypeCode;
+ return TRUE;
+ }
+ }
+ return FALSE;
+#else
+ break;
+ }
+ if (i == iArraySize)
+ return FALSE;
+ pEntry->Group = Entry.Group;
+ pEntry->Element = Entry.Element;
+ pEntry->TypeCode = Entry.TypeCode;
+ return TRUE;
+#endif
+}
+
+
+/*************** Binary RTC Load **********************/
+
+# define __Binary_RTC_Header_PaddingSize (1024 - (10 + 7*4))
+#pragma pack(4)
+typedef struct s__Binary_RTC_Header
+ {
+ char Prefix[10]; // #!BinRTC<cr><lf> + typically 2 bytes padding
+ UINT32 ArraySize;
+ UINT32 AbsKeyTableOffset;
+ UINT32 AbsKeyTableSize;
+ UINT32 AbsDataTableOffset;
+ UINT32 AbsDataTableSize;
+ UINT32 AbsStringTableOffset;
+ UINT32 AbsStringTableSize;
+ char Padding[__Binary_RTC_Header_PaddingSize];
+ } __Binary_RTC_Header;
+
+# define SetFilePos(fffppp, xxx) fseek(fffppp, xxx, 0)
+#pragma pack()
+
+BOOL
+RTC :: AttachBinaryRTC (
+ char *filename )
+ {
+ FILE *fp;
+ __Binary_RTC_Header bRTCHeader;
+ void* pBuffer;
+ RTCElementBIN* pRTCElementBIN;
+ unsigned int i;
+ size_t FileSize;
+
+ fp = fopen(filename, "rb");
+ if ( ! fp )
+ return ( FALSE );
+
+ fseek(fp, 0, SEEK_END);
+ FileSize = ftell(fp);
+ SetFilePos(fp, 0);
+
+ fread ((char*)&bRTCHeader, 1, 1024, fp);
+
+ // Make sure that file is properly formatted
+ if (bRTCHeader.ArraySize>FileSize || bRTCHeader.AbsDataTableSize>FileSize ||
+ bRTCHeader.AbsStringTableSize>FileSize || bRTCHeader.AbsKeyTableSize>FileSize)
+ { fclose(fp);
+ return FALSE;
+ }
+
+ TypeCodes = new FixedArray < UINT32, RTCElement > (bRTCHeader.ArraySize,TRUE);
+ if ( ! TypeCodes )
+ {
+ fclose(fp);
+ return ( FALSE );
+ }
+
+ TypeCodes->Top = bRTCHeader.ArraySize;
+ TypeCodes->ArraySize = bRTCHeader.ArraySize;
+
+ SetFilePos(fp, bRTCHeader.AbsKeyTableOffset);
+ fread((char*)TypeCodes->KeyTable, 1, bRTCHeader.AbsKeyTableSize, fp);
+
+ SetFilePos(fp, bRTCHeader.AbsDataTableOffset);
+ pBuffer = malloc(bRTCHeader.AbsDataTableSize);
+ if (!pBuffer)
+ {
+ fclose ( fp );
+ return (FALSE);
+ }
+ fread(pBuffer, 1, bRTCHeader.AbsDataTableSize, fp);
+ pRTCElementBIN = (RTCElementBIN*)pBuffer;
+ for (i=0; i<bRTCHeader.ArraySize; i++)
+ {
+ TypeCodes->DataTable[i].Group = pRTCElementBIN->Group;
+ TypeCodes->DataTable[i].Element = pRTCElementBIN->Element;
+ TypeCodes->DataTable[i].TypeCode = pRTCElementBIN->TypeCode;
+ TypeCodes->DataTable[i].Description = NULL;
+ pRTCElementBIN ++;
+ }
+ free(pBuffer);
+
+ if ( CarryDescriptions )
+ {
+ // If the database was not built with descriptions, then we
+ // can't possibly load them... don't consider it an error though.
+ // a warning.. maybe sometime in the future..
+ if(bRTCHeader.AbsStringTableOffset)
+ {
+ char *StringTable = new char[bRTCHeader.AbsStringTableSize];
+ if(!StringTable)
+ {
+ fclose ( fp );
+ return ( FALSE ); // memory error
+ }
+ SetFilePos(fp, bRTCHeader.AbsStringTableOffset);
+ fread((char*)StringTable, 1, bRTCHeader.AbsStringTableSize, fp);
+ UINT Index = 0;
+ char *TempS = StringTable;
+ while ( Index < bRTCHeader.ArraySize )
+ {
+ if((*TempS))
+ {
+ TypeCodes->DataTable[Index].Description = new
+ char [ strlen(TempS) + 1 ];
+ strcpy(TypeCodes->DataTable[Index].Description, TempS);
+ }
+ TempS += (strlen(TempS) + 1);
+ ++Index;
+ }
+ delete [] StringTable;
+
+ }
+ }
+
+ fclose ( fp );
+ return ( TRUE );
+ }
+
+BOOL
+RTC :: AttachResourceRTC (
+ char* pDict )
+ {
+ __Binary_RTC_Header bRTCHeader;
+ RTCElementBIN* pRTCElementBIN;
+ unsigned int i;
+
+ memcpy((void*)&bRTCHeader, pDict, 1024);
+
+ TypeCodes = new FixedArray < UINT32, RTCElement > (bRTCHeader.ArraySize, TRUE);
+ if ( ! TypeCodes )
+ return ( FALSE );
+
+ TypeCodes->Top = bRTCHeader.ArraySize;
+ TypeCodes->ArraySize = bRTCHeader.ArraySize;
+
+ memcpy((char*)TypeCodes->KeyTable, pDict + bRTCHeader.AbsKeyTableOffset,
+ bRTCHeader.AbsKeyTableSize);
+
+ pRTCElementBIN = (RTCElementBIN*)(pDict + bRTCHeader.AbsDataTableOffset);
+ for (i=0; i<bRTCHeader.ArraySize; i++)
+ {
+ TypeCodes->DataTable[i].Group = pRTCElementBIN->Group;
+ TypeCodes->DataTable[i].Element = pRTCElementBIN->Element;
+ TypeCodes->DataTable[i].TypeCode = pRTCElementBIN->TypeCode;
+ TypeCodes->DataTable[i].Description = NULL;
+ pRTCElementBIN ++;
+ }
+ if ( CarryDescriptions )
+ {
+ // If the database was not built with descriptions, then we
+ // can't possibly load them... don't consider it an error though.
+ // a warning.. maybe sometime in the future..
+ if(bRTCHeader.AbsStringTableOffset)
+ {
+ char *StringTable = new char[bRTCHeader.AbsStringTableSize];
+ if(!StringTable)
+ {
+ return ( FALSE ); // memory error
+ }
+ memcpy((char*)StringTable, pDict + bRTCHeader.AbsStringTableOffset,
+ bRTCHeader.AbsStringTableSize);
+ UINT Index = 0;
+ char *TempS = StringTable;
+ while ( Index < bRTCHeader.ArraySize )
+ {
+ if((*TempS))
+ {
+ TypeCodes->DataTable[Index].Description = new
+ char [ strlen(TempS) + 1 ];
+ strcpy(TypeCodes->DataTable[Index].Description, TempS);
+ }
+ TempS += (strlen(TempS) + 1);
+ ++Index;
+ }
+ delete [] StringTable;
+
+ }
+ }
+
+ return ( TRUE );
+ }
+
+
+int MkBinaryRtc(char* pszTextIn, char* pszBinaryOut, BOOL bCarryDescriptions)
+ {
+ unsigned int i;
+ RTC vRTC(bCarryDescriptions);
+ if(!vRTC.AttachRTC(pszTextIn))
+ return(1);
+
+ FILE *oFile = fopen(pszBinaryOut, "wb");
+ if(!oFile)
+ return(2);
+
+
+ __Binary_RTC_Header bRTCHeader;
+
+ memset(&bRTCHeader, 0, sizeof(bRTCHeader));
+ strcpy(bRTCHeader.Prefix, "#!BinRTC");
+ bRTCHeader.Prefix[8] = 13;
+ bRTCHeader.Prefix[9] = 10;
+
+ UINT32 RunningOffset = sizeof ( __Binary_RTC_Header );
+
+ bRTCHeader.ArraySize = vRTC.TypeCodes->ArraySize;
+ bRTCHeader.AbsKeyTableOffset = RunningOffset;
+ bRTCHeader.AbsKeyTableSize = bRTCHeader.ArraySize * sizeof ( UINT32 );
+ RunningOffset += bRTCHeader.AbsKeyTableSize;
+ bRTCHeader.AbsDataTableOffset = RunningOffset;
+ bRTCHeader.AbsDataTableSize = bRTCHeader.ArraySize * sizeof (RTCElementBIN);
+ RunningOffset += bRTCHeader.AbsDataTableSize;
+
+ char *StringTable;
+
+ StringTable = NULL;// GCC warning
+
+ if ( bCarryDescriptions )
+ {
+ UINT Index;
+ UINT TSize;
+
+ // Ok, descriptions are still ugly to handle. I recommend in production
+ // systems not using them unless you have to.. but for those that do..
+
+ Index = 0;
+ TSize = 0;
+ while ( Index < vRTC.TypeCodes->ArraySize )
+ {
+ if(!vRTC.TypeCodes->DataTable[Index].Description)
+ ++TSize;
+ else
+ TSize += (strlen(vRTC.TypeCodes->DataTable[Index].Description)
+ + 1);
+ ++Index;
+ }
+ StringTable = new char[TSize];
+
+ Index = 0;
+ char *TempS = StringTable;
+ while ( Index < vRTC.TypeCodes->ArraySize )
+ {
+ if(!vRTC.TypeCodes->DataTable[Index].Description)
+ {
+ (*TempS) = '\0';
+ }
+ else
+ strcpy(TempS, vRTC.TypeCodes->DataTable[Index].Description);
+ TempS += (strlen(TempS) + 1);
+ delete vRTC.TypeCodes->DataTable[Index].Description;
+ vRTC.TypeCodes->DataTable[Index].Description = NULL;
+ ++Index;
+ }
+ bRTCHeader.AbsStringTableOffset = RunningOffset;
+ bRTCHeader.AbsStringTableSize = TSize;
+ }
+ else
+ {
+ bRTCHeader.AbsStringTableOffset = 0;
+ bRTCHeader.AbsStringTableSize = 0;
+ }
+
+ fwrite((char*)&bRTCHeader, 1, sizeof ( __Binary_RTC_Header), oFile );
+ fwrite((char*)vRTC.TypeCodes->KeyTable, 1, bRTCHeader.AbsKeyTableSize, oFile);
+ for (i=0; i<bRTCHeader.ArraySize; i++)
+ fwrite(&(vRTC.TypeCodes->DataTable[i]), 1, sizeof(RTCElementBIN), oFile);
+// fwrite((char*)vRTC.TypeCodes->DataTable, 1, bRTCHeader.AbsDataTableSize, oFile);
+ if ( bCarryDescriptions )
+ {
+ fwrite((char*)StringTable, 1, bRTCHeader.AbsStringTableSize, oFile);
+ }
+ fclose ( oFile );
+
+
+ if ( StringTable )
+ delete [] StringTable;
+
+ return(0);
+ }
diff --git a/rtc.hpp b/rtc.hpp
new file mode 100644
index 0000000..49f4605
--- /dev/null
+++ b/rtc.hpp
@@ -0,0 +1,92 @@
+/*
+19980331 ljz Added prototype for writing binary RTCs
+20091029 ljz Adjustments for 64-bits
+20100619 bcb Added no-copy to the RTC class.
+20100717 bcb Merged
+20130429 lsp Made no-copy generic (not only for __GNUC__)
+*/
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+
+
+// Run-Time-Classing of VR's
+
+BOOL Pack(BYTE, BYTE, UINT16 &);
+BOOL Pack(UINT16, BYTE &, BYTE &);
+
+
+int MkBinaryRtc(char* pszTextIn, char* pszBinaryOut, BOOL bCarryDescriptions);
+
+
+# define MAKEUINT32(xxx, yyy) ((UINT32) (((UINT32) xxx << 16) | yyy))
+
+#pragma pack(1)
+typedef struct _RTCElement
+ {
+ UINT16 Group;
+ UINT16 Element;
+ UINT16 TypeCode;
+ char *Description;
+ } RTCElement;
+
+typedef struct _RTCElementBIN // Used for reading and writing binary libraries
+ {
+ UINT16 Group;
+ UINT16 Element;
+ UINT16 TypeCode;
+ char cDummy[6];
+ } RTCElementBIN;
+#pragma pack()
+
+
+class RTC
+ {
+ public:
+ FixedArray < UINT32, RTCElement > *TypeCodes;
+ BOOL CarryDescriptions;
+ public:
+ RTC (BOOL CD = TRUE, char *filename = NULL);
+ ~RTC ();
+ BOOL AttachRTC ( char *filename );
+ BOOL AttachBinaryRTC ( char *filename );
+ BOOL AttachResourceRTC (char* pDict);
+ BOOL DetachRTC ();
+ BOOL RunTimeClass ( DICOMObject * );
+ BOOL RunTimeClass ( VR * );
+ UINT16 RunTimeClass ( UINT16, UINT16, char * =NULL);
+ BOOL GetGroupElement(RTCElement* pEntry);
+ private:// This will prevent it from being copied (it has a pointer)
+ RTC(const RTC&);
+ const RTC & operator = (const RTC&);
+ };
+
+
+
diff --git a/safemem.h b/safemem.h
new file mode 100644
index 0000000..a47b1dd
--- /dev/null
+++ b/safemem.h
@@ -0,0 +1,55 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+# ifdef DEBUG_VERSION
+# define MAX_SEGMENTS 10000
+
+void *operator new(size_t);
+void operator delete(void *);
+int snew(char*, int);
+int sdelete(char*, int);
+void MemCatch(char*, int);
+# define new (snew(__FILE__, __LINE__)) ? NULL : new
+# define delete (sdelete(__FILE__, __LINE__)) ? 0 : delete
+
+BOOL InitMemoryWatch();
+BOOL CloseMemoryWatch();
+#else
+# define InitMemoryWatch()
+# define CloseMemoryWatch()
+#endif
+
+class SafeMemory
+ {
+ public:
+ SafeMemory () { InitMemoryWatch(); };
+ ~SafeMemory () { CloseMemoryWatch(); };
+ };
+
+
diff --git a/sample.cq b/sample.cq
new file mode 100644
index 0000000..7622847
--- /dev/null
+++ b/sample.cq
@@ -0,0 +1,20 @@
+<HEAD><TITLE>Conquest DICOM server - %variable%</TITLE></HEAD>
+<BODY BGCOLOR='CFDFCF'>
+<H2>Conquest DICOM server - %variable%</H2>
+
+<BR>
+#this is equivalent to: dgate "--display_status:"
+#where the output is sent to the web page (unquoted)
+<listing>
+--display_status:
+</listing>
+
+<hr>
+#the format parameter of the dgate -- command is used to create HTML tags
+--get_amaps:<br>%s <strong>%s %s</strong>
+
+<hr>
+#example of database query
+--query2:DICOMPatients|PatientID||<br>%s
+
+</BODY>
diff --git a/socket.cxx b/socket.cxx
new file mode 100644
index 0000000..41dd4ac
--- /dev/null
+++ b/socket.cxx
@@ -0,0 +1,696 @@
+/*
+20010426 ljz Added 'setsockopt' in 'Listen' and 'Open'
+ Call 'shutdown' before closing a socket
+20010720 ljz Changed 'print' to 'fprint(stderr,...)'
+20050116 mvh Adapted for LINUX compile
+20050119 mvh Blocked out SOCKET END ERROR message
+20070406 mvh Use reentrant gethostbyname_r when available
+20070415 mvh Small fix there for windows
+20090620 jf Added unistd.h for UNIX
+20090824 mvh Debug output of adress connecting to socket
+20091231 bcb Changed char* to const char* for gcc4.2 warnings
+20100111 mvh Merged
+20100122 mvh Gethostbyname: fixed bug reported by Arash 2station would not be found
+20100122 mvh Added Poll() method: returns TRUE if data available
+20100125 mvh Linux warning
+20100309 bcb Commented out or inited to fix unused variable warning (gcc4.2 Warnings)
+20100619 bcb Fix gcc4 warnings, improve speed and made TimeOut local.
+20100707 mvh Merged
+20121214 mvh Set l_onoff to 0 (3x) to fix connection with some dicom systems
+20130429 lsp Removed unused FarProc
+*/
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/*******************************************************************************
+ *
+ * socket.C
+ *
+ *******************************************************************************/
+
+# include "dicom.hpp"
+# include <stdlib.h>
+
+#ifdef UNIX
+# include <unistd.h> //DUCKHEAD92
+#endif
+
+
+#ifdef WINDOWS
+#define SD_BOTH 0x02 /* From winsock2.h */
+static WORD WinSockUsed = 0;
+static WSADATA wsaData;
+
+
+
+Socket :: Socket ()
+ {
+ WORD VersionNeeded;
+
+ TimeOut = 60 * 5; // 5 minutes
+ UDP = 0;
+ if(! WinSockUsed )
+ {
+ /* WinSock.dll not WSAStartup(), so call it and init the library */
+ VersionNeeded = 0x0101;
+
+ Error = WSAStartup( VersionNeeded, &wsaData);
+ if( Error )
+ {
+ /* no socket library */
+ return;
+ }
+ /*FarProc = (FARPROC) SocketBlockingHook;
+ if(!WSASetBlockingHook(FarProc))
+ {
+ OutputDebugString("Failed to Install Blocking Hook\n");
+ }*/
+ }
+ ++WinSockUsed;
+ Socketfd = 0;
+ ListenSocketfd = 0;
+ Connected = 0;
+ Listened = 0;
+ }
+
+Socket :: ~Socket ()
+ {
+
+ if( ! WinSockUsed )
+ return; // must have failed installation
+
+ if ( Socketfd )
+ {
+ shutdown(Socketfd, SD_BOTH);
+ closesocket(Socketfd);
+ }
+ if ( ListenSocketfd )
+ {
+ shutdown(ListenSocketfd, SD_BOTH);
+ closesocket(ListenSocketfd);
+ }
+
+ --WinSockUsed;
+ if(! WinSockUsed )
+ {
+ //WSAUnhookBlockingHook();
+ WSACleanup();
+ }
+
+ }
+#else
+
+#define SYSV_SOCKET
+
+# define closesocket(xxx) close(xxx)
+
+/*
+int closesocket(int sock)
+ {
+ int flags;
+ struct linger sl;
+
+ sl.l_onoff=0; // 20121214 was 1
+ sl.l_linger=30;
+ errno=0;
+ setsockopt(sock, SOL_SOCKET, SO_LINGER, &sl, sizeof(linger));
+ fprintf(stderr, "%d\n", errno);
+
+ errno = 0;
+ fprintf(stderr, "CloseSocket(%d) : %d ", sock, close(sock));
+ fprintf(stderr, "%d\n", errno);
+ return(0);
+ }
+*/
+
+Socket :: Socket()
+#ifdef __GNUC__ //Faster with member initialization.
+:Error(0),
+tulong(0),
+tulongptr(NULL),
+Socketfd(0),
+ListenSocketfd(0),
+UDP(0),
+Connected(0),
+Listened(0),
+sa(),
+hes(),
+servs(),
+TimeOut(300) {} // 5 minutes
+#else
+ {
+ Socketfd = 0;
+ Connected = 0;
+ Listened = 0;
+ ListenSocketfd = 0;
+ TimeOut = 60 * 5; // 5 minutes
+ UDP = 0;
+ }
+#endif
+
+Socket :: ~Socket()
+ {
+ if ( Socketfd )
+ {
+ closesocket(Socketfd);
+ }
+ if ( ListenSocketfd )
+ {
+ closesocket(ListenSocketfd);
+ }
+ }
+
+#endif
+
+#ifndef gethostbyname_r
+#define gethostbyname_r(name, a, b, c, d, e) *d=gethostbyname(name)
+#endif
+
+
+struct hostent * Socket :: Gethostbyname(char *name1)
+ {
+ struct hostent *he;
+ struct hostent he2;
+ unsigned long ip;
+// unsigned long i1,i2,i3,i4;
+// char *dot2, *dot3, *dot4;
+ char *name;
+ char ndat[128], buf[64];
+ int dum;
+
+ he2.h_length = 0;//Added for compiler unused warning. bcb
+ buf[63] = 0;//Added for compiler unused warning. bcb
+ dum = 0;//Added for compiler unused warning. bcb
+
+ strcpy(ndat, name1);
+ name = &ndat[0];
+
+ if(!atoi(name1) || strchr(name1, '.')==NULL) // fix for name like 2station
+ gethostbyname_r(name, &he2, buf, 64, &he, &dum);
+ else
+ he = NULL; // has . and starts with number
+ if(he)
+ {
+ memcpy ((void *) &hes, (void *) he, sizeof(struct hostent));
+ return(&hes);
+ }
+#ifdef MAC
+ struct in_addr ipa = inet_addr(name);
+ ip = ipa.s_addr;
+#else
+ ip = inet_addr(name);
+#endif
+/******************************
+ dot2 = strchr(name, '.');
+ if(!dot2)
+ return ( NULL );
+ (*dot2) = '\0';
+ ++dot2;
+ dot3 = strchr(dot2, '.');
+ if(!dot3)
+ return ( NULL );
+ (*dot3) = '\0';
+ ++dot3;
+ dot4 = strchr(dot3, '.');
+ if(!dot4)
+ return ( NULL );
+ (*dot4) = '\0';
+ ++dot4;
+ i1 = atoi(name);
+ i2 = atoi(dot2);
+ i3 = atoi(dot3);
+ i4 = atoi(dot4);
+
+#if NATIVE_ENDIAN == BIG_ENDIAN
+ i1 = i4 << 24;
+ i2 = i3 << 16;
+ i3 = i2 << 8;
+#else
+ i4 = i4 << 24;
+ i3 = i3 << 16;
+ i2 = i2 << 8;
+#endif
+
+ ip = i1 | i2 | i3 | i4;
+********************************/
+ hes.h_addr_list = (char **) &tulongptr;
+ tulongptr = &tulong;
+ tulong = ip;
+ return ( &hes );
+ }
+
+struct servent * Socket :: Getservbyname(const char *name, char *prot)
+ {
+ unsigned short s;
+// unsigned short s1;
+ struct servent *se;
+
+ s = atoi(name);
+ if(!s)
+ {
+ se = getservbyname(name, prot);
+ if(!se)
+ return(se);
+ memcpy ((void *) &servs, (void *) se, sizeof(struct servent));
+ return(&servs);
+ }
+#ifdef MAC
+ servs.s_port = s;
+#else
+ servs.s_port = htons(s);
+#endif
+/****************************
+ s1 = s & 0x00ff;
+ s1 = s1 << 8;
+ s = s >> 8;
+ s1 = s1 | s;
+ servs.s_port = s1;
+*******************************/
+// fprintf(stderr, "returning: %d\n", servs.s_port);
+ return ( &servs );
+ }
+
+BOOL Socket :: Listen ( char *port )
+ {
+ UINT32 tuint32;
+// struct hostent *he;
+// struct hostent hecopy;
+ struct servent *se;
+ struct servent secopy;
+ struct linger Linger;
+
+ Connected = 0;
+ Listened = 0;
+
+ if ( Socketfd )
+ closesocket(Socketfd);
+
+// fprintf(stderr, "[Listen: %s]\n", port); fflush(stderr);
+ /*he = Gethostbyname("hampson");
+
+ if ( !he )
+ {
+ return ( FALSE ); // could not resolve host name
+ }
+ */
+ //memcpy ((void *) &hecopy, (void *) he, sizeof(struct hostent));
+
+ se = Getservbyname(port, NULL);
+
+ if ( !se )
+ return ( FALSE ); // could not resolv port
+ memcpy ((void *) &secopy, (void *) se, sizeof(struct servent));
+
+ Socketfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if(!Socketfd)
+ return ( FALSE ); // could not create socket
+ Linger.l_onoff = 0; // 20121214 was 1
+ Linger.l_linger = 0;
+ setsockopt(Socketfd, SOL_SOCKET, SO_LINGER, (char*)&Linger, sizeof(struct linger));
+ //memcpy((void *) &sa.sin_addr.S_un.S_addr , (void *) hecopy.h_addr_list[0], 4); // adddress
+ // should bind to the default address
+ tuint32 = 0;
+#ifdef SYSV_SOCKET
+ sa.sin_addr.s_addr = tuint32;
+#else
+ memcpy((void *) &sa.sin_addr.S_un.S_addr, (void *) &tuint32, 4);
+#endif
+ memcpy((void *) &sa.sin_port , (void *) &secopy.s_port, 2); // port
+ sa.sin_port = secopy.s_port;
+ sa.sin_family = AF_INET;
+
+ if(bind(Socketfd, (struct sockaddr *) &sa, sizeof(struct sockaddr_in)))
+ {
+// fprintf(stderr, "Erro (bind) : %d\n", GetLinkError());
+#ifdef FORCEDIO
+/* while(errno==125)
+ {
+ errno=0;
+ bind(Socketfd, (struct sockaddr *) &sa, sizeof(struct
+ sockaddr_in));
+ }*/
+#endif
+ if(GetLinkError())
+ {
+ closesocket(Socketfd);
+ Error = GetLinkError();
+ Socketfd = 0;
+ return ( FALSE );
+ }
+ }
+ if(listen(Socketfd, 5))
+ {
+ //fprintf(stderr, "Erro (bind): %d\n", GetLinkError());fflush(stderr);
+ closesocket(Socketfd);
+ Socketfd = 0;
+ return ( FALSE );
+ }
+
+ Listened = 1;
+ ListenSocketfd = Socketfd;
+ Socketfd = 0;
+ Connected = 0;
+ return ( TRUE );
+ }
+
+BOOL Socket :: Accept()
+ {
+#ifdef SYSV_SOCKET
+ socklen_t Size;
+#else
+ int Size;
+#endif
+
+ //fprintf(stderr, "Accept()\n");fflush(stderr);
+ if(!Listened)
+ return ( FALSE );
+ if(!ListenSocketfd)
+ return ( FALSE );
+
+ Size = sizeof(struct sockaddr_in);
+ Socketfd = accept(ListenSocketfd, (struct sockaddr *) &sa, &Size);
+ if(Socketfd>0)
+ {
+ Connected = TRUE;
+
+DicomError(DCM_ERROR_DEBUG, "Connected by address: %08x", sa.sin_addr.s_addr);
+
+ return ( TRUE );
+ }
+ //fprintf(stderr, "Error (accept) : %d\n", errno);
+ closesocket(ListenSocketfd);
+ Listened = 0;
+ ListenSocketfd = 0;
+ Socketfd = 0;
+ Connected = FALSE;
+ return ( FALSE );
+ }
+
+
+BOOL Socket :: Open ( char *ip, char *port)
+ {
+ struct hostent *he;
+ struct hostent hecopy;
+ struct servent *se;
+ struct servent secopy;
+ struct linger Linger;
+
+ if ( Socketfd )
+ closesocket(Socketfd);
+
+ Connected = 0;
+
+ he = Gethostbyname(ip);
+
+ if ( !he )
+ {
+ // fprintf(stderr, "Could not resolve host\n");
+ return ( FALSE ); // could not resolve host name
+ }
+
+ memcpy ((void *) &hecopy, (void *) he, sizeof(struct hostent));
+
+ se = Getservbyname(port, NULL);
+
+ if ( !se )
+ {
+// fprintf(stderr, "Could not resolve port\n");
+ return ( FALSE ); // could not resolv port
+ }
+
+ memcpy ((void *) &secopy, (void *) se, sizeof(struct servent));
+ if(!hecopy.h_addr_list)
+ return ( FALSE );
+
+ Socketfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if(Socketfd<0)
+ return ( FALSE ); // could not create socket
+ Linger.l_onoff = 0; // 20121214 was 1
+ Linger.l_linger = 0;
+ setsockopt(Socketfd, SOL_SOCKET, SO_LINGER, (char*)&Linger, sizeof(struct linger));
+
+#ifdef SYSV_SOCKET
+ memcpy((void *) &sa.sin_addr.s_addr , (void *) hecopy.h_addr_list[0], 4); // adddress
+#else
+ memcpy((void *) &sa.sin_addr.S_un.S_addr , (void *) hecopy.h_addr_list[0], 4); // adddress
+#endif
+ memcpy((void *) &sa.sin_port , (void *) &secopy.s_port, 2); // port
+ sa.sin_family = AF_INET;
+ sa.sin_port = secopy.s_port;
+
+ Error = connect(Socketfd, (struct sockaddr *) &sa, sizeof(struct sockaddr_in));
+ if( ! Error )
+ {
+ Connected = TRUE;
+ return ( TRUE );
+ }
+
+ closesocket(Socketfd);
+ Socketfd = 0;
+ return ( FALSE );
+ }
+
+BOOL Socket :: Close()
+ {
+
+
+ if(ListenSocketfd)
+ {
+ closesocket(ListenSocketfd);
+ }
+ if(Socketfd)
+ {
+ closesocket(Socketfd);
+ }
+ ListenSocketfd = 0;
+ Socketfd = 0;
+ Connected = 0;
+ Listened = 0;
+ UDP = 0;
+ return ( TRUE );
+ }
+
+BOOL Socket :: Poll(void)
+ {
+#ifdef SYSV_SOCKET
+ fd_set fds;
+#else
+ struct fd_set fds;
+#endif
+ struct timeval tv = {0, 0}; // return immediately
+
+ if ( ! Connected )
+ return ( FALSE );
+#ifdef MAC
+ memset((void*)&fds, 0, sizeof(struct fd_set));
+#else
+ FD_ZERO(&fds);
+#endif
+ FD_SET(Socketfd, &fds);
+ return (select(Socketfd + 1, &fds, NULL, NULL, &tv)==1);
+ }
+
+BOOL Socket :: SendBinary(BYTE *s, UINT count)
+ {
+ if ( !Connected)
+ return ( 0 );
+
+ if(send ( Socketfd, (char *) s, count, 0)<0)
+ {
+// fprintf(stderr, "SOCKET END ERROR: %d\n", GetLastError());
+ }
+ return ( TRUE );
+ }
+
+INT Socket :: ReadBinary(BYTE *s, UINT count)
+ {
+#ifdef SYSV_SOCKET
+ fd_set fds;
+#else
+ struct fd_set fds;
+#endif
+ struct timeval tv = {TimeOut, 0}; // poll
+
+ if ( ! Connected )
+ return ( -1 );
+#ifdef MAC
+ memset((void*)&fds, 0, sizeof(struct fd_set));
+#else
+ FD_ZERO(&fds);
+#endif
+ FD_SET(Socketfd, &fds);
+ if(select(Socketfd + 1, &fds, NULL, NULL, &tv)==1)
+ {
+ if((count = recv(Socketfd, (char *) s, count, 0))==0)
+ {
+/*#ifdef WINDOWS
+ if(WSAGetLastError()==WSAEDISCON)
+ return(-1);
+ else
+ return(0);
+#else
+ return ( -1 );
+#endif
+*/
+ Close ();
+ return ( -1 );
+ }
+ return ( count );
+ }
+ if ( TimeOut )
+ return ( -1 );
+ return ( 0 );
+ }
+
+int Socket :: GetLinkError()
+ {
+#ifdef WINDOWS
+ return ( WSAGetLastError() );
+#else
+ return ( errno );
+#endif
+ }
+
+
+BOOL Socket :: SetTimeOut(int lTimeOut)
+ {
+ this->TimeOut = lTimeOut;
+ return ( TRUE );
+ }
+
+BOOL
+Socket :: BindUDPServer (
+ char *port)
+ {
+ Close();
+ struct servent *se;
+ struct servent secopy;
+ se = Getservbyname(port, NULL);
+
+ if ( !se )
+ {
+ return ( FALSE ); // could not resolv port
+ }
+
+ memcpy ((void *) &secopy, (void *) se, sizeof(struct servent));
+ Socketfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ if(Socketfd<0)
+ return ( FALSE ); // could not create socket
+
+#ifdef SYSV_SOCKET
+ memset((void *) &sa.sin_addr.s_addr , 0, 4);
+#else
+ memset((void *) &sa.sin_addr.S_un.S_addr , 0, 4);
+#endif
+ memcpy((void *) &sa.sin_port , (void *) &secopy.s_port, 2); // port
+ sa.sin_family = AF_INET;
+ sa.sin_port = secopy.s_port;
+
+ if(bind(Socketfd, (struct sockaddr *) &sa, sizeof(struct sockaddr_in)))
+ {
+ closesocket(Socketfd);
+ Error = GetLinkError();
+ Socketfd = 0;
+ return ( FALSE );
+ }
+ Connected = 1;
+ UDP = 1;
+ return ( TRUE );
+ }
+
+BOOL
+Socket :: BindUDPClient (
+ char *ip,
+ const char *port)
+ {
+ struct hostent *he;
+ struct hostent hecopy;
+ struct servent *se;
+ struct servent secopy;
+
+
+ if ( Socketfd )
+ closesocket(Socketfd);
+ if ( ListenSocketfd )
+ closesocket(ListenSocketfd);
+
+ Listened = 0;
+ Connected = 0;
+ Socketfd = 0;
+ ListenSocketfd = 0;
+
+ he = Gethostbyname(ip);
+
+ if ( !he )
+ {
+ fprintf(stderr, "Could not resolve host\n");
+ return ( FALSE ); // could not resolve host name
+ }
+
+ memcpy ((void *) &hecopy, (void *) he, sizeof(struct hostent));
+
+ se = Getservbyname(port, NULL);
+
+ if ( !se )
+ {
+ fprintf(stderr, "Could not resolve port\n");
+ return ( FALSE ); // could not resolv port
+ }
+
+ memcpy ((void *) &secopy, (void *) se, sizeof(struct servent));
+ if(!hecopy.h_addr_list)
+ return ( FALSE );
+
+ Socketfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ if(Socketfd<0)
+ return ( FALSE ); // could not create socket
+
+#ifdef SYSV_SOCKET
+ memcpy((void *) &sa.sin_addr.s_addr , (void *) hecopy.h_addr_list[0], 4); // adddress
+#else
+ memcpy((void *) &sa.sin_addr.S_un.S_addr , (void *) hecopy.h_addr_list[0], 4); // adddress
+#endif
+ memcpy((void *) &sa.sin_port , (void *) &secopy.s_port, 2); // port
+ sa.sin_family = AF_INET;
+ sa.sin_port = secopy.s_port;
+ Error = connect(Socketfd, (struct sockaddr *) &sa, sizeof(struct sockaddr_in));
+ if( ! Error )
+ {
+ Connected = TRUE;
+ UDP = 1;
+ return ( TRUE );
+ }
+ closesocket(Socketfd);
+ Socketfd = 0;
+ return ( FALSE );
+ }
+
+/*#endif*/
+
diff --git a/socket.hpp b/socket.hpp
new file mode 100644
index 0000000..666dd7f
--- /dev/null
+++ b/socket.hpp
@@ -0,0 +1,93 @@
+// 20091231 bcb Changed char* to const char* for gcc4.2 warnings
+// 20100111 mvh Merged
+// 20100122 mvh Added Poll function
+// 20100619 bcb Added no-copy to the Socket class.
+// 20100707 mvh Merged
+// 20121214 mvh Mode sa public
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/*********************************************************************
+ *
+ * Connection Class
+ *
+ *
+ *********************************************************************/
+
+// The library used to link with the DICOM Lib has a naming conflict with
+// socket. Therefor we simply remap our socket class into MacSocket.
+
+#ifdef MAC
+# define Socket MacSocket
+#endif
+
+class Socket
+ {
+ int Error;
+ unsigned long tulong,*tulongptr;
+ public:
+ int Socketfd;
+ int ListenSocketfd;
+ BOOL UDP;
+ BOOL Connected;
+ BOOL Listened;
+ private:
+ struct hostent hes;
+ struct servent servs;
+
+ int TimeOut;
+ public:
+
+ struct sockaddr_in sa;
+ virtual BOOL SendBinary(BYTE *, UINT);
+ virtual INT ReadBinary(BYTE *, UINT);
+ virtual BOOL Poll(void);
+ struct hostent *Gethostbyname(char *);
+ struct servent *Getservbyname(const char *, char *);
+ int GetLinkError();
+ Socket();
+ virtual ~Socket();
+ virtual BOOL Open ( char *ip, char *port );
+ BOOL Close ();
+ int GetLastError() { return ( Error ); };
+ BOOL Listen (char *port);
+ BOOL Accept ();
+ BOOL SetTimeOut(int);
+
+ // UDP Extensions
+ BOOL BindUDPServer(char *port);
+ BOOL BindUDPClient(char *host, const char *port);
+#ifdef __GNUC__
+ private:// This will prevent it from being copied (it has a pointer)
+ Socket(const Socket&);
+ const Socket & operator = (const Socket&);
+#endif
+ };
+
diff --git a/storage.cxx b/storage.cxx
new file mode 100644
index 0000000..0e5dd84
--- /dev/null
+++ b/storage.cxx
@@ -0,0 +1,241 @@
+// mvh 20020429 check status of C-STORE RSP and return FALSE if failed
+// mvh 20030922 Added PDU_Service to CheckObject call
+// mvh 20070307 Added more debug error messages to retrieve
+// mvh 20070314 Allow send of 0000,1030 (MoveOriginatorAE) and 0000,1031 (MoveOriginatorMessageID) in StandardStorage : Write
+// mvh 20070315 Blocked out printf statements
+// bcb 20100309 Commented out unused variable (gcc4.2 Warnings)
+// bcb 20100619 Added #ifndefs (gcc4.0 Warnings) and UNUSED_ARGUMENT
+// mvh 20100717 Merged
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+#ifndef UNUSED_ARGUMENT
+#define UNUSED_ARGUMENT(x) (void)x
+#endif
+
+# include "dicom.hpp"
+
+
+BOOL StandardStorage :: Read (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ DICOMDataObject *DDO)
+ {
+ VR *vr;
+ UID MyUID, uid;
+
+ GetUID(MyUID); // always try and use GetUID to obtain my own uid
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( ! DDO )
+ return ( FALSE );
+
+ vr = DCO->GetVR ( 0x0000, 0x0002 );
+ if ( ! vr )
+ return ( FALSE );
+
+ if ( !SetUID(uid, vr) )
+ return ( FALSE );
+
+ if ( MyUID != uid )
+ return ( FALSE );
+
+ if ( CStoreRQ :: Read ( DCO, PDU, DDO ) )
+ {
+ return ( CStoreRSP :: Write ( PDU, DCO, CheckObject( DDO, PDU ) ) );
+ }
+ if ( CStoreRSP :: Read ( DCO ) )
+ {
+ // No worries..
+ return ( TRUE );
+ }
+ return ( FALSE ); // corrupted message
+ }
+
+BOOL StandardStorage :: Write (
+ PDU_Service *PDU,
+ DICOMDataObject *DDO, VR *MoveMessageID, unsigned char *CallingAE)
+ {
+ DICOMCommandObject DCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! CStoreRQ :: Write ( PDU, DDO, MoveMessageID, CallingAE ) )
+ {
+ //printf("Retrieve: failed writing image\n");
+ return ( FALSE );
+ }
+
+// delete DDO;
+
+ if(!PDU->Read ( & DCO ))
+ {
+ //printf("Retrieve: no response\n");
+ return (FALSE);
+ }
+
+ if ( ! CStoreRSP :: Read ( &DCO ) )
+ {
+ //printf("Retrieve: incorrect response\n");
+ return ( FALSE );
+ }
+
+ // mvh added 20020429
+ if (DCO.GetUINT16(0x0000, 0x0900))
+ {
+ //printf("Retrieve: error status %d\n", DCO.GetUINT16(0x0000, 0x0900));
+ return FALSE;
+ }
+
+ return ( TRUE );
+ }
+
+// Special "Void" storage class. Accepts any DICOM transmission C-Store
+BOOL UnknownStorage :: GetUID ( UID &uid )
+ {
+ UNUSED_ARGUMENT(uid);
+ return ( FALSE );
+ }
+
+BOOL UnknownStorage :: Read (
+ PDU_Service *PDU,
+ DICOMCommandObject *DCO,
+ DICOMDataObject *DDO)
+ {
+// VR *vr;
+ UID MyUID, uid;
+
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! DCO )
+ return ( FALSE );
+
+ if ( ! DDO )
+ return ( FALSE );
+
+ if ( CStoreRQ :: Read ( DCO, PDU, DDO ) )
+ {
+ return ( CStoreRSP :: Write ( PDU, DCO, CheckObject ( DDO, PDU ) ) );
+ }
+ if ( CStoreRSP :: Read ( DCO ) )
+ {
+ // No worries..
+ return ( TRUE );
+ }
+ return ( FALSE ); // corrupted message
+ }
+
+
+BOOL CRStorage :: GetUID ( UID &uid )
+ {
+ uid.Set("1.2.840.10008.5.1.4.1.1.1");
+ return ( TRUE );
+ }
+
+BOOL CTStorage :: GetUID ( UID &uid )
+ {
+ uid.Set("1.2.840.10008.5.1.4.1.1.2");
+ return ( TRUE );
+ }
+
+BOOL USMultiframeStorage :: GetUID ( UID &uid )
+ {
+ uid.Set("1.2.840.10008.5.1.4.1.1.3");
+ return ( TRUE );
+ }
+
+BOOL MRStorage :: GetUID ( UID &uid )
+ {
+ uid.Set("1.2.840.10008.5.1.4.1.1.4");
+ return ( TRUE );
+ }
+
+BOOL NMStorage :: GetUID ( UID &uid )
+ {
+ uid.Set("1.2.840.10008.5.1.4.1.1.5");
+ return ( TRUE );
+ }
+
+BOOL USStorage :: GetUID ( UID &uid )
+ {
+ uid.Set("1.2.840.10008.5.1.4.1.1.6");
+ return ( TRUE );
+ }
+
+BOOL SCStorage :: GetUID ( UID &uid )
+ {
+ uid.Set("1.2.840.10008.5.1.4.1.1.7");
+ return ( TRUE );
+ }
+
+BOOL StandaloneOverlayStorage :: GetUID ( UID &uid )
+ {
+ uid.Set("1.2.840.10008.5.1.4.1.1.8");
+ return ( TRUE );
+ }
+
+BOOL StandaloneCurveStorage :: GetUID ( UID &uid )
+ {
+ uid.Set("1.2.840.10008.5.1.4.1.1.9");
+ return ( TRUE );
+ }
+
+BOOL StandaloneModalityLUTStorage :: GetUID (UID &uid )
+ {
+ uid.Set("1.2.840.10008.5.1.4.1.1.10");
+ return ( TRUE );
+ }
+
+BOOL StandaloneVOILUTStorage :: GetUID ( UID &uid )
+ {
+ uid.Set("1.2.840.10008.5.1.4.1.1.11");
+ return ( TRUE );
+ }
+
+
+BOOL GEMRStorage :: GetUID( UID & uid )
+ {
+ uid.Set("1.2.840.113619.4.2");
+ return ( TRUE );
+ }
+
+BOOL GECTStorage :: GetUID ( UID & uid )
+ {
+ uid.Set("1.2.840.113619.4.3");
+ return ( TRUE );
+ }
diff --git a/storage.hpp b/storage.hpp
new file mode 100644
index 0000000..501765a
--- /dev/null
+++ b/storage.hpp
@@ -0,0 +1,241 @@
+// mvh 20030922 Added PDU_Service to CheckObject call
+// mvh 20050108 Fixed for linux compile
+// mvh 20070314 Allow send of 0000,1030 (MoveOriginatorAE) and 0000,1031 (MoveOriginatorMessageID) in StandardStorage : write
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+// Storage classes
+
+// Note there are many "ungood" things about the class hierachys in
+// this file. Notable things should be protected rather than public,
+// there should be no inline "wrapper"'s.. Both of these are done
+// to be compatible with gcc.
+
+// Base Storage class
+
+class StandardStorage :
+ public CStoreRQ,
+ public CStoreRSP
+ {
+ public:
+ BOOL GetUID ( UID &uid) { return (uGetUID(uid)); };
+ virtual BOOL uGetUID ( UID &uid ) = 0;
+ virtual UINT16 CheckObject(DICOMDataObject *, PDU_Service *) { return ( 0 ); };
+ BOOL Read ( PDU_Service *,
+ DICOMCommandObject *,
+ DICOMDataObject * );
+ BOOL Write ( PDU_Service *, DICOMDataObject *, VR *MoveMessageID = NULL, unsigned char *CallingAE = NULL );
+ };
+
+class UnknownStorage :
+ public CStoreRQ,
+ public CStoreRSP
+ {
+ public:
+ BOOL GetUID(UID &);
+ virtual UINT16 CheckObject(DICOMDataObject *, PDU_Service *) { return ( 0 ); };
+
+ BOOL Read ( PDU_Service *,
+ DICOMCommandObject *,
+ DICOMDataObject * );
+ };
+
+class CRStorage :
+ public StandardStorage
+ {
+ public:
+ BOOL GetUID(UID &);
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ };
+
+class CTStorage :
+ public StandardStorage
+ {
+ public:
+ BOOL GetUID(UID &);
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ };
+
+class USMultiframeStorage :
+ public StandardStorage
+ {
+ public:
+ BOOL GetUID(UID &);
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ };
+
+class MRStorage :
+ public StandardStorage
+ {
+ public:
+ BOOL GetUID(UID &);
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ };
+
+class NMStorage :
+ public StandardStorage
+ {
+ public:
+ BOOL GetUID(UID &);
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ };
+
+class USStorage :
+ public StandardStorage
+ {
+ public:
+ BOOL GetUID(UID &);
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ };
+
+class SCStorage :
+ public StandardStorage
+ {
+ public:
+ BOOL GetUID(UID &);
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ };
+
+class StandaloneOverlayStorage :
+ public StandardStorage
+ {
+ public:
+ BOOL GetUID(UID &);
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ };
+
+class StandaloneCurveStorage :
+ public StandardStorage
+ {
+ public:
+ BOOL GetUID(UID &);
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ };
+
+class StandaloneModalityLUTStorage :
+ public StandardStorage
+ {
+ public:
+ BOOL GetUID(UID &);
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ };
+
+class StandaloneVOILUTStorage :
+ public StandardStorage
+ {
+ public:
+ BOOL GetUID(UID &);
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ };
+
+
+class GEMRStorage :
+ public StandardStorage
+ {
+ public:
+ BOOL GetUID(UID &);
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ };
+
+
+class GECTStorage :
+ public StandardStorage
+ {
+ public:
+ BOOL GetUID(UID &);
+ BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); };
+ inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO,
+ DICOMDataObject *DDO )
+ { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); };
+ inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO)
+ { return ( StandardStorage :: Write ( PDU, DDO ) ); };
+ };
+
+
diff --git a/total.cpp b/total.cpp
new file mode 100644
index 0000000..d62a7ec
--- /dev/null
+++ b/total.cpp
@@ -0,0 +1,146 @@
+/*
+20020822 mvh This file compiles to TOTAL.EXE = DGATE.EXE with, e.g., BC55
+20050102 mvh Added NOINTJPEG flag: jpeg8/12/16 sources cannot be compiled at once
+20050107 mvh Changed order of compile
+20050111 mvh Added npipe.cpp and gpps.cpp for LINUX
+20050118 mvh Documented how to compile under linux and with visual c++
+20050121 mvh Changed filename to lower case
+20050130 mvh Added xvgifwr.c
+20070315 mvh bcb added DARWIN stuff
+20070330 mvh bcb added DARWIN compile example
+20080820 mvh Solaris compile example
+20080910 bcb fixed DARWIN compile example for build version of mysql
+20081016 mvh Fix link to xvgifwr.cpp; 64 bit example code
+20090209 mvh Added jpeg_encoder.cpp
+20090411 mvh Added second SUN example
+20100120 bcb removed DARWIN (PPC, 10.4, now old) compile example. JPEG lib. is internal, so undef NOINTJPEG if used.
+20100123 mvh Include stddef here for windows to avoid jasper.h compile problem
+20100124 mvh Also use gpps for windows.
+20100224 bcb Added defines for OpenJPEG
+20100706 bcb Allow both libaries at once
+20100721 mvh Merged
+20100815 mvh bcb added two defines; Merged
+*/
+
+/* Example to compile with BC55:
+ bcc32 -v # source level debugging
+ -g255 # max number of warnings
+ -lS:1000000 # stack size
+ -P # force C++ compile
+ -DWINDOWS -DWIN32 -DNATIVE_ENDIAN=1 -DNOINTJPEG # defines
+ -I\bc55\include;\conquest\cqdicom;\conquest\dgate # include directories (bcc, dicom lib, and dgate parts)
+ -L\bc55\lib # library directory
+ total.cpp # this source file
+ cw32mt.lib # multi-thread library
+
+ Example to compile under linux:
+ g++ -DUNIX -DNATIVE_ENDIAN=1 -DNOINTJPEG total.cpp -o dgate -lpthread
+
+ Example to compile with visual c++:
+ set path=e:\lang\msdev\bin
+ set include=e:\lang\msdev\include
+ set lib=e:\lang\msdev\lib
+ cl /Zi /MD /O2 /DWIN32 /DWINDOWS /DNATIVE_ENDIAN=1 /DNOINTJPEG /FeDGATE.EXE total.cpp odbc32.lib odbccp32.lib wsock32.lib advapi32.lib user32.lib kernel32.lib
+
+ Example to compile with visual c++ (64 bit):
+ set path=e:\lang\ms8amd64\bin
+ set include=e:\lang\ms8amd64\include;\quirt\comps\exe\dgate;\quirt\comps\dll\cqdicom
+ set lib=e:\lang\ms8amd64\lib
+ cl -c -MD -O2 -DWIN32 -DWINDOWS -DNATIVE_ENDIAN=1 -DNOINTJPEG -DUSESQLITE ..\total.cpp ..\sqlite3.c
+ link /OUT:dgate.exe total.obj sqlite3.obj odbc32.lib odbccp32.lib wsock32.lib advapi32.lib user32.lib kernel32.lib bufferoverflowu.lib
+
+ Example to compile under SOLARIS 10:
+
+ /usr/sfw/bin/g++ -DUNIX -DNATIVE_ENDIAN=1 -DNOINTJPEG -DSOLARIS total.cpp -o dgate -lpthread -lsocket -lnsl -lposix4
+
+ or
+
+ /opt/SUNWspro/bin/CC -w -DUNIX -DNATIVE_ENDIAN=1 -DNOINTJPEG -DSOLARIS total.cpp -o dgate -lpthread -lsocket -lnsl -lposix4
+*/
+
+#define _SH_DENYRW 0x10 /* deny read/write mode */
+#define _SH_DENYWR 0x20 /* deny write mode */
+#define _SH_DENYRD 0x30 /* deny read mode */
+#define _SH_DENYNO 0x40 /* deny none mode */
+#define _P_WAIT 0
+
+#ifdef DARWIN /* a flavor of bsd unix */
+#define BSD
+#endif
+#ifdef BSD
+#define UNIX
+#endif
+
+#ifdef BCB_FIX // Became tired of retyping on different systems.
+#define DATE_FIX // Changes a leading 0 of any date to a 1 (Allowed by the DICOM Box).
+#define FUJI_FIX // Allows decompressing Fuji AC3 jpeg compressed,not encapsulated images.
+#define NOVARAD_FIX // Works around the intentional corruptions NovaPacs (NovaRad) adds to the images.
+#endif
+
+#ifdef WINDOWS
+#include <stddef.h>
+#endif
+
+#ifdef HAVE_LIBJPEG
+#undef NOINTJPEG
+// Used to make Libjpeg use int as UINT.
+#ifndef UINT_MAX
+#define UINT_MAX 0xffffffff
+#endif
+#endif
+
+#ifdef HAVE_LIBOPENJPEG
+#define HAVE_J2K
+#endif
+
+#ifdef HAVE_LIBJASPER
+#ifdef HAVE_LIBOPENJPEG
+#define HAVE_BOTH_J2KLIBS
+#else // Only one lib
+#define HAVE_J2K
+#endif
+#endif
+
+#include "filepdu.cxx"
+#include "vrtosql.cpp"
+#include "parse.cpp"
+#include "loadddo.cpp"
+#include "lex.cpp"
+#include "dprintf.cpp"
+#include "dgatefn.cpp"
+#include "device.cpp"
+#include "amap.cpp"
+#include "dbsql.cpp"
+#include "rtc.cxx"
+#include "flpdu.cxx"
+#include "qrsop.cxx"
+#include "storage.cxx"
+#include "verify.cxx"
+#include "dimsen.cxx"
+#include "dimsec.cxx"
+#include "util.cxx" // zeromem, spacemem
+#include "uniq.cxx" // uniq16, uniq8
+//#include "safemem.cxx"
+#include "endian.cxx"
+#include "trnsyn.cxx"
+#include "pdu.cxx"
+#include "pdata.cxx"
+#include "aarj.cxx"
+#include "aaac.cxx"
+#include "aarq.cxx"
+#include "deivr.cxx"
+#include "socket.cxx"
+#include "buffer.cxx"
+#include "odbci.cpp"
+#include "nkiqrsop.cpp"
+#include "regen.cpp"
+#include "dgate.cpp"
+#include "xvgifwr.cpp"
+#ifndef HAVE_LIBJPEG
+#include "jpeg_encoder.cpp"
+#endif
+#include "gpps.cpp"
+
+#ifdef UNIX
+# include "npipe.cpp"
+#endif
diff --git a/trnsyn.cxx b/trnsyn.cxx
new file mode 100644
index 0000000..4ced130
--- /dev/null
+++ b/trnsyn.cxx
@@ -0,0 +1,1953 @@
+/*
+19980409 ljz Fixed possible transition between presence and absence
+ of TypeCodes in 'Dynamic_ParseRawVRIntoDCM'
+19990904 ljz Treat type UN same as OB,OW and SQ when reading Explicit files.
+20001106 mvh Replaced == operator by strcmp
+20010905 ljz Several fixes: UCDMC should NOW be able to read ExplicitBigEndian files
+20011220 ljz Fixes in Sequence and Item delimiters
+20030122 ljz Fixed small leak in Dynamic_ParseRawVRIntoDCM
+20030205 ljz Support new datatype 'UT' (unlimited text). Thanx to William Peterson
+20030424 ljz Changedprototype of ParseDCMIntoRawVR
+ Fixed huge bug in sending of ExplicitLittleEndian sequences
+20030627 mvh Fix for MSC 4.2
+20030725 ljz Keep GroupLength for group 0x00 (Radworks 6.0 was choking in this)
+20040406 ljz Make TypeCode 'UN' if not known, and conversion to Explicit is wanted
+20041102 ljz Added some entries in TransferSyntaxAlias table
+20050112 ljz Fixed huge bug in Explicit_ParseDCMIntoRawVR, causing data-loss. Thanx to Goran Peros.
+20051217 mvh Use new VR::ReAlloc method to replace data in VR
+20051218 mvh Use memcpy to enter UID (extra 0 will be available: end of string)
+20051219 mvh Use ReAlloc instead of new BYTE[] to fill VR data
+20051229 mvh Moved Push in ParseRawVRIntoDCM so that not done when VR exists
+20070308 bcb Added big endian stuff
+20071031 mvh Removed some commented out code
+20071108 ljz In Dynamic_ParseDCMIntoRawVR(), let group 0x08 behave the same as all other groups
+ greater than 0x02.
+20071118 mvh NOTE: previous change is not in release 1.4.13
+20071128 mvh Add TypeCodes if needed using AttachedRTC->RunTimeClass
+20080913 mvh Fix in bigendian input: interpret group 0 as littleendian
+20090211 mvh Added many checks on corrupt dicom data during parsing; removed blocked out code
+20090212 mvh Fixed a problem in the check code if some (but not all) group lenghts are missing
+20090215 mvh Improved formatting of lenght error message
+20090620 jf Added <stdlib.h>
+20090824 mvh Resume parsing after invalid element length if length was not too big
+20100102 mvh Merged bcb changes for bigendian
+20100111 mvh bcb moved setting 0002,0010 to work for all transfers in ParseRawVRIntoDCM: fix for osiris
+ Added JASPER stuff; const
+20100118 mvh Always allow jp2k
+20100119 bcb Put HAVE_LIBJASPER back in (unfortunately that creates a dependency between dicomlib and dgate)
+20100119 bcb Changed Dynamic_ParseRawVRIntoDCM and ParseImagePixelDataRawToDCM to read NovaRad files and remove the errors.
+20100121 mvh Merged but put into NOVARAD_FIX define; not bcb alsp prints which parser reports errors
+20100125 mvh Linux warnings.
+20100224 bcb Changed HAVE_LIBJASPER to HAVE_J2K for OpenJPEG and fixed more warnings (-Wall)
+20100309 bcb Added double parentheses (gcc4.2 Warnings)
+20100309 bcb Changed int to UINT, commented out unused variables (gcc4.2 Warnings)
+20100419 bcb Fixed Dynamic_ParseRawVRIntoDCM big endian
+20100619 bcb Made VRBuffer local lVRBuffer.
+20100707 mvh Merged
+20100718 mvh Looked at and rejected the date change: you can use importconverters for this job
+20100722 mvh iorgmode change breaks the reader for me!
+20100724 bcb Put back date change with DATE_FIX inclosing it.
+20101001 mvh Allow CurrentGroupLength==0 as warning
+20103020 mvh Rollback of dicom decoder to 1.4.16beta4 version
+20110231 mvh allow some parsing errors when DicomError handler not installed
+20105001 mvh This is the rolled back dicom decoder to 1.4.16beta4 version; with dummy FALSE passed to Implicit_ParseRawVRIntoDCM
+20105001 mvh It fixes a small leak that fragments memory
+20110502 mvh merged IgnoreDicomError change (20110231)
+20111020 mvh Enabled NOVARAD_ODD_FIX for rubo demo images; added warning
+20120723 mvh bcb fixed datefix (extra ; after if)
+20130514 bcb Fixed Big Endian parse, fixed warnings with strnlen32u()
+20130523 mvh Merged Big Endian parse fix not strnlen32u()
+20130619 lsp Fixed problem in GetTransferSyntaxUID() indicated by Klocwork
+20130711 lsp Merged
+*/
+
+/*
+bcb: Bruce Barton http://www.bitsltd.net/contact-form
+*/
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+# include "dicom.hpp"
+# include <stdlib.h> //DUCKHEAD92
+
+
+// A special thanks to Terry Rosenbaum at MSU for the countless bug fixes
+// in the sequence stuff.
+
+
+// These two routines ParseRawVRIntoDCM and ParseDCMIntoRawVR represent the support
+// side of the Transfer Syntax negiotian. If you plan on supporting anything beyond
+// base level DICOM Little Endian, then you need to override these routines, and
+// provide the appropiate parseing mechanisms.
+
+// This should only be called if the transfer syntax is the default DICOM transfer
+// syntax. 1.2.840.10008.1.2
+
+// Note that this routine is recursive in nature.
+
+typedef struct _TransferSyntaxAlias
+ {
+ const char *TransferSyntaxUID;
+ unsigned int Alias;
+ } TransferSyntaxAlias;
+
+// Transfer Syntax Aliases. Currently, we don't try and figure out how
+// to decode the JPEG compressed transfer syntaxes. We can read/write them
+// assuming that someother process can encode/decode the JPEG sections.
+//
+// The order these are placed in the table is very important. The ones
+// at the top are tryed first. Ie, the syntax encoder will default to
+// sending the top most transfer synax. In this case, that is Implicit
+// Little Endian.
+TransferSyntaxAlias TransferSyntaxAliases[] =
+ {
+ { "1.2.840.10008.1.2", TSA_IMPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.1", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.2", TSA_EXPLICIT_BIG_ENDIAN },
+ { "1.2.840.10008.1.2.5", TSA_EXPLICIT_LITTLE_ENDIAN }, // RLE lossless
+ { "1.2.840.10008.1.2.4.50", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.51", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.52", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.53", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.54", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.55", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.56", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.57", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.58", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.59", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.60", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.61", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.62", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.63", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.64", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.65", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.66", TSA_EXPLICIT_LITTLE_ENDIAN },
+ { "1.2.840.10008.1.2.4.70", TSA_EXPLICIT_LITTLE_ENDIAN }, // JPEG lossless
+ { "1.2.840.10008.1.2.4.80", TSA_EXPLICIT_LITTLE_ENDIAN }, // JPEGLS Lossless
+ { "1.2.840.10008.1.2.4.81", TSA_EXPLICIT_LITTLE_ENDIAN }, // JPEGLS Lossy
+#ifdef HAVE_J2K
+ { "1.2.840.10008.1.2.4.90", TSA_EXPLICIT_LITTLE_ENDIAN }, // JPEG2000 LosslessOnly
+ { "1.2.840.10008.1.2.4.91", TSA_EXPLICIT_LITTLE_ENDIAN }, // JPEG2000
+#endif
+ { NULL, 0 }
+ };
+
+#define NOVARAD_ODD_FIX
+
+// Decapsulate image pixel data into an encapsulated format.
+BOOL
+PDU_Service :: ParseImagePixelDataRawToDCM(
+ LinkedBuffer &lVRBuffer,
+ DICOMObject *DCMObject)
+ {
+#ifdef NOVARAD_ODD_FIX
+ BOOL novaRadOdd;//Used for bad NovaRad DCM files.
+#endif
+
+ while ( lVRBuffer.GetIncomingSize() )
+ {
+ VR *vr = new VR;
+#ifdef NOVARAD_ODD_FIX
+ novaRadOdd = FALSE;
+#endif
+
+ lVRBuffer >> vr->Group;
+ lVRBuffer >> vr->Element;
+ lVRBuffer >> vr->Length;
+
+if ( (vr->Group == 0xfffe) &&
+ (vr->Element == 0xe0dd))
+ {
+ delete vr;
+ return ( TRUE ); // the end
+ }
+
+ if ( (vr->Group == 0xfffe) &&
+ (vr->Element == 0xe000)) // hopefully...
+ {
+ DICOMDataObject *DDO = new DICOMDataObject;
+#ifdef NOVARAD_ODD_FIX
+ if(vr->Length & 1)
+ {
+ novaRadOdd = TRUE;//Bad bad NovaRad!
+ DicomError(DCM_ERROR_DEBUG, "Odd VR length: %08x; attempted to fix\n", vr->Length);
+ DicomError(DCM_ERROR_DEBUG, "In image data: %08x\n", (vr->Group<<16)+vr->Element);
+ }
+#endif
+ vr->ReAlloc(vr->Length);
+#ifdef NOVARAD_ODD_FIX
+ if(novaRadOdd)(vr->Length)--;// Read an odd length.
+#endif
+ lVRBuffer.Read((BYTE*)vr->Data, vr->Length);
+#ifdef NOVARAD_ODD_FIX
+ if(novaRadOdd)
+ {
+ ((char *)(vr->Data))[vr->Length] = 0;//Fix the end.
+ (vr->Length)++;//Fix the length.
+ }
+#endif
+
+ DDO->Push(vr);
+ DCMObject->Push(DDO);
+ continue;
+ }
+
+ // protocol error? or maybe something encoded before an image start..
+ // whatever it is.. we dont' care.. do our best..
+ vr->ReAlloc(vr->Length);
+ lVRBuffer.Read((BYTE*)vr->Data, vr->Length);
+ delete vr;
+ }
+
+ DicomError(DCM_ERROR_PARSE, "Mis-encoded pixel data during load of DCM file\n", 0);
+ return ( FALSE ); // mis-encoded
+ }
+
+// Encapsulate image pixel data into an encapsulated format.
+BOOL
+PDU_Service :: ParseImagePixelDataDCMToRaw(
+ Array < DICOMDataObject *> *ADDO,
+ LinkedBuffer &lVRBuffer)
+ {
+ VR *vr;
+ UINT Index = 0;
+ DICOMDataObject *DDO;
+
+ while ( Index < ADDO->GetSize() )
+ {
+ DDO = ADDO->Get(Index);
+ ++Index;
+ while((vr = DDO->Pop()))
+ {
+ if ((vr->Group == 0xfffe) &&
+ (vr->Element == 0xe000))
+ break;
+ delete vr;
+ }
+ if(!vr)
+ {
+ // messed up encapsulated
+ continue;
+ }
+ lVRBuffer << vr->Group;
+ lVRBuffer << vr->Element;
+ lVRBuffer << vr->Length;
+ if(vr->Length)
+ lVRBuffer.Write((BYTE*)vr->Data, vr->Length);
+ delete vr;
+ }
+
+ VR vrs;
+
+ vrs.Group = 0xfffe;
+ vrs.Element = 0xe0dd;
+ vrs.Length = 0;
+
+ lVRBuffer << vrs.Group;
+ lVRBuffer << vrs.Element;
+ lVRBuffer << vrs.Length;
+
+ return ( TRUE );
+ }
+
+
+BOOL PDU_Service :: ParseRawVRIntoDCM(BYTE PCID, LinkedBuffer &lVRBuffer, DICOMObject *DCMObject)
+ {
+ UID uid;
+ UINT Index;
+ VR *pVR;
+
+ if(!GetTransferSyntaxUID(PCID, uid))
+ {
+ DicomError(DCM_ERROR_PARSE, "no UID associated with PCID %d during load of DCM file in ParseRawVRIntoDCM\n", PCID);
+ return ( FALSE ); // Error no UID associated with PCID
+ }
+
+ Index = 0;
+ while ( TransferSyntaxAliases[Index].TransferSyntaxUID )
+ {
+ if(strcmp((char *)(uid.GetBuffer(0)), TransferSyntaxAliases[Index].TransferSyntaxUID)==0)
+ {
+ /* LJ: Store the used TransferSyntax for later use (in database
+ and) when we want to write a Chapter10 file (bcb moved here).
+ */
+ pVR = DCMObject->GetVR(0x0002, 0x0010);
+ if (pVR)
+ {
+ pVR->ReAlloc(strlen((char*)uid.GetBuffer(0)));
+ memcpy((char*)pVR->Data, (char*)uid.GetBuffer(0), pVR->Length);
+ }
+ else
+ {
+ pVR = new VR(0x0002, 0x0010, strlen((char*)uid.GetBuffer(0)),
+ strdup((char*)uid.GetBuffer(0)), TRUE);
+ DCMObject->Push(pVR);
+ }
+
+ switch (TransferSyntaxAliases[Index].Alias)
+ {
+ case TSA_IMPLICIT_LITTLE_ENDIAN:
+ if(!ImplicitLittleEndian_ParseRawVRIntoDCM(
+ lVRBuffer,DCMObject))
+ return ( FALSE );
+ break;
+ case TSA_EXPLICIT_LITTLE_ENDIAN:
+ if(!ExplicitLittleEndian_ParseRawVRIntoDCM(
+ lVRBuffer,DCMObject))
+ return ( FALSE );
+ break;
+ case TSA_EXPLICIT_BIG_ENDIAN:
+ if(!ExplicitBigEndian_ParseRawVRIntoDCM(
+ lVRBuffer,DCMObject))
+ return ( FALSE );
+ break;
+
+ default:
+ DicomError(DCM_ERROR_PARSE, "Internal error during load of DCM file in ParseRawVRIntoDCM\n", 0);
+ return ( FALSE ); // internal error
+ }
+ return ( TRUE );
+ }
+ ++Index;
+ }
+ return ( FALSE ); // Cannot Decode
+ }
+
+// Routine looks in the accepted transfer syntax table for a transfer
+// syntax to use.
+BYTE PDU_Service :: ParseDCMIntoRawVR(DICOMObject *DCMObject, LinkedBuffer &lVRBuffer)
+ {
+// VR *vr;
+ UID uid;
+ BYTE PCID;
+ UINT Index;
+
+ if ( ! DCMObject )
+ return ( FALSE );
+
+ Index = 0;
+ while (TransferSyntaxAliases[Index].TransferSyntaxUID)
+ {
+ uid.Set(TransferSyntaxAliases[Index].TransferSyntaxUID);
+ if((PCID=GetAcceptedPCIDForTransferSyntax(uid)))
+ {
+ switch (TransferSyntaxAliases[Index].Alias)
+ {
+ case TSA_IMPLICIT_LITTLE_ENDIAN:
+ if(!ImplicitLittleEndian_ParseDCMIntoRawVR(
+ DCMObject,lVRBuffer))
+ return ( 0 );
+ break;
+ case TSA_EXPLICIT_LITTLE_ENDIAN:
+ if(!ExplicitLittleEndian_ParseDCMIntoRawVR(
+ DCMObject,lVRBuffer))
+ return ( 0 );
+ break;
+ case TSA_EXPLICIT_BIG_ENDIAN:
+ if(!ExplicitBigEndian_ParseDCMIntoRawVR(
+ DCMObject,lVRBuffer))
+ return ( 0 );
+ break;
+ default:
+ return ( 0 ); // internal error
+ }
+ return ( PCID );
+ }
+ ++Index;
+ }
+ return ( 0 );
+ }
+
+BYTE PDU_Service :: ParseDCMIntoRawVR(DICOMObject *DCMObject, LinkedBuffer &lVRBuffer, UID &AbsUID, BOOL bIsDataObject)
+ {
+// VR *vr;
+ UID uid;
+ BYTE PCID;
+ UINT Index;
+
+ if ( ! DCMObject )
+ return ( FALSE );
+
+ Index = 0;
+ while (TransferSyntaxAliases[Index].TransferSyntaxUID)
+ {
+ uid.Set(TransferSyntaxAliases[Index].TransferSyntaxUID);
+ if((PCID=GetPresentationContextID(AbsUID, uid)))
+ {
+ if (!bIsDataObject)
+ { // CommandObject always ImplicitLittleEndian
+ if(!ImplicitLittleEndian_ParseDCMIntoRawVR(
+ DCMObject,lVRBuffer))
+ return ( 0 ); // internal error
+ }
+ else
+ switch (TransferSyntaxAliases[Index].Alias)
+ {
+ case TSA_IMPLICIT_LITTLE_ENDIAN:
+ if(!ImplicitLittleEndian_ParseDCMIntoRawVR(
+ DCMObject,lVRBuffer))
+ return ( 0 );
+ break;
+ case TSA_EXPLICIT_LITTLE_ENDIAN:
+ if(!ExplicitLittleEndian_ParseDCMIntoRawVR(
+ DCMObject,lVRBuffer))
+ return ( 0 );
+ break;
+ case TSA_EXPLICIT_BIG_ENDIAN:
+ if(!ExplicitBigEndian_ParseDCMIntoRawVR(
+ DCMObject,lVRBuffer))
+ return ( 0 );
+ break;
+ default:
+ return ( 0 ); // internal error
+ }
+ return ( PCID );
+ }
+ ++Index;
+ }
+ return ( 0 );
+ }
+
+
+
+
+BOOL PDU_Service :: ImplicitLittleEndian_ParseRawVRIntoDCM(
+ LinkedBuffer &lVRBuffer,
+ DICOMObject *DCMObject)
+ {
+ lVRBuffer.SetIncomingEndian(LITTLE_ENDIAN);
+ return ( Implicit_ParseRawVRIntoDCM(lVRBuffer, DCMObject, FALSE) );
+ }
+
+BOOL PDU_Service :: ImplicitLittleEndian_ParseDCMIntoRawVR (
+ DICOMObject *DCMObject,
+ LinkedBuffer &lVRBuffer)
+ {
+ lVRBuffer.SetOutgoingEndian ( LITTLE_ENDIAN );
+ return ( Implicit_ParseDCMIntoRawVR(DCMObject, lVRBuffer) );
+ }
+
+BOOL PDU_Service :: Implicit_ParseRawVRIntoDCM(LinkedBuffer &lVRBuffer, DICOMObject *DCMObject, BOOL dum)
+ {
+ VR *vr = NULL;
+// UINT32 tuint32, tuint32_2;
+// DICOMObject *EBO; // Embedded sequence Object
+
+ unsigned int CurrentGroup = 0;
+ unsigned int CurrentElement = 0;
+ unsigned int CurrentGroupLength = 0xffffffff;
+
+ if ( ! DCMObject )
+ return ( FALSE ); // passed a NULL object pointer
+
+ while ( lVRBuffer.GetIncomingSize())
+ {
+ vr = new VR;
+ if ( ! vr )
+ return ( FALSE ); // memory error
+
+ lVRBuffer >> vr->Group;
+ lVRBuffer >> vr->Element;
+
+ if (vr->Group < CurrentGroup)
+ {
+ if (DicomError(DCM_ERROR_PARSE, "(Imp) Encountered an invalid group order during load of DCM file (after %08x)\n", (CurrentGroup<<16)+CurrentElement))
+ return FALSE;
+ }
+
+ if (vr->Group != CurrentGroup)
+ {
+ CurrentGroup = vr->Group;
+ CurrentElement = 0;
+ CurrentGroupLength = 0xffffffff;
+ }
+
+ if (vr->Element < CurrentElement)
+ {
+ if (DicomError(DCM_ERROR_PARSE, "(Imp) Encountered an invalid element order during load of DCM file (in %08x)\n", (CurrentGroup<<16)+CurrentElement))
+ return FALSE;
+ }
+
+ CurrentElement = vr->Element;
+
+ if ( vr->Group == 0xfffe )
+ {
+ // Ok, this is a deliminator type of item.
+ // handled special. Always implicit
+ lVRBuffer >> vr->Length;
+
+ if ( (vr->Element == 0xe0dd)||
+ (vr->Element == 0xe00d) ) // implicit terminmator
+ {
+ delete vr;
+ return ( TRUE );
+ }
+
+ if ( vr->Length == 0xffffffff)
+ {
+ // Implicit length.. go until deliminator
+ vr->Length = 0;delete vr;
+
+ DICOMDataObject *DDO = new DICOMDataObject;
+ if ( ! Implicit_ParseRawVRIntoDCM ( lVRBuffer, DDO, FALSE ) )
+ {
+ delete DDO;
+ return ( FALSE );
+ }
+ DCMObject->Push(DDO);
+ continue;
+ }
+ else if (vr->Length > CurrentGroupLength || (vr->Length&1))
+ {
+ BOOL b=DicomError(DCM_ERROR_PARSE, "Implicit Parse encountered an invalid element length during load of DCM file (in %08x)\n", (CurrentGroup<<16)+CurrentElement);
+ DicomError(DCM_ERROR_PARSE, "Length = %d\n", vr->Length);
+ if (vr->Length > CurrentGroupLength)
+ DicomError(DCM_ERROR_PARSE, "Group Length = %u\n", CurrentGroupLength);
+ if (b && vr->Length > 0xffff && CurrentGroupLength!=0) return FALSE; // pass if not dangerous
+ DicomError(DCM_ERROR_PARSE, "Continuing parsing", 0);
+ }
+
+ // Ok, an explicit length.. sequence item begin?
+ if ( vr->Element == 0xe000 )
+ {
+ vr->ReAlloc(vr->Length);
+ if ( !vr->Data )
+ return ( FALSE ); // memory error
+ lVRBuffer.Read ( (BYTE *) vr->Data, vr->Length);
+
+ MemoryBuffer MB( (BYTE*)vr->Data, vr->Length,
+ TRUE, lVRBuffer.GetIncomingEndian() );
+ vr->Length = 0;
+ vr->Data = NULL;
+ delete vr;
+
+ DICOMDataObject *DDO = new DICOMDataObject;
+ if ( ! Implicit_ParseRawVRIntoDCM ( MB, DDO, FALSE ) )
+ {
+ delete DDO;
+ return ( FALSE );
+ }
+ DCMObject->Push(DDO);
+ continue;
+ }
+
+ // Not quite sure what to say here...
+ DicomError(DCM_ERROR_PARSE, "Sequence parse error during load of DCM file (after %08x)\n", (CurrentGroup<<16)+CurrentElement);
+ return ( FALSE );
+ }
+
+ lVRBuffer >> vr->Length;
+
+ // Type this element
+ if ( AttachedRTC )
+ AttachedRTC->RunTimeClass(vr);
+
+
+ if ( vr->Length == 0xffffffff )
+ {
+ // variable length item [sequence, etc]
+ vr->Length = 0;
+ DCMObject->Push(vr);
+ if ( (vr->Group == 0x7fe0) &&
+ (vr->Element == 0x0010))
+ {
+ // Image Pixel data.. encapsulated.. ugly..
+
+ if(!ParseImagePixelDataRawToDCM(
+ lVRBuffer,
+ DCMObject))
+ return(FALSE);
+ continue;
+ }
+ if(!Implicit_ParseRawVRIntoDCM(lVRBuffer, DCMObject, FALSE))
+ return(FALSE);
+ continue;
+ }
+
+ if ( vr->TypeCode == 'SQ' )
+ {
+ // explicit length sequence
+ // in this case.. pull the data into a memory buffer
+ // and parse that.
+ vr->ReAlloc(vr->Length);
+ if ( !vr->Data )
+ return ( FALSE ); // memory error
+
+ lVRBuffer.Read ( (BYTE *) vr->Data, vr->Length);
+
+ MemoryBuffer MB( (BYTE*)vr->Data, vr->Length,
+ TRUE, lVRBuffer.GetIncomingEndian() );
+ vr->Length = 0;
+ vr->Data = NULL;
+ DCMObject->Push(vr);
+
+ if ( ! Implicit_ParseRawVRIntoDCM ( MB, DCMObject, FALSE ) )
+ {
+ return ( FALSE );
+ }
+ continue;
+ }
+
+ // Explicit Length ( normal)
+ if ( vr->Length )
+ {
+ if (vr->Length>CurrentGroupLength || (vr->Length&1))
+ {
+ BOOL b=DicomError(DCM_ERROR_PARSE, "Implicit_Parse encountered an invalid element length during load of DCM file (in %08x)\n", (CurrentGroup<<16)+CurrentElement);
+ DicomError(DCM_ERROR_PARSE, "Length = %d\n", vr->Length);
+ if (vr->Length > CurrentGroupLength)
+ DicomError(DCM_ERROR_PARSE, "Group Length = %u\n", CurrentGroupLength);
+ if (b && vr->Length > 0xffff && CurrentGroupLength!=0) return FALSE; // pass if not dangerous
+ DicomError(DCM_ERROR_PARSE, "Continuing parsing", 0);
+ }
+
+ vr->ReAlloc(vr->Length);
+
+ if ( !vr->Data )
+ return ( FALSE ); // memory error
+
+ lVRBuffer.Read ( (BYTE *) vr->Data, vr->Length);
+
+ if (vr->Element==0)
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ CurrentGroupLength = *(unsigned int *)vr->Data;
+#else //Big Endian like Apple power pc
+ CurrentGroupLength = SwitchEndian(*(unsigned int *)vr->Data);
+#endif
+#ifdef DATE_FIX
+// Time to look a dates and fix it here if needed. Some systems allow invalid birthdates
+// like 00010101 (the DICOM box). Other systems (OsiriX) will delete the leading 0's,
+// but keep the vr length at 8.
+// Ex: vr->TypeCode = DA, vr->Length = 8, vr->Data = 10101. == Image not stored!
+// To fix this, find dates with the length of 8 and make sure the first digit is not 0.
+// I'm not interested in fixing the date and prefer an obviously invalid date,
+// but I don't want the year to excede the current year. Hope for 10010101.
+ if ( vr->Length == 8 ) //Dates (DA) are 8 long.
+ {
+ if ( vr->TypeCode == 'DA' ) // It's a date
+ {
+ if(*(char *)vr->Data == '0') *(char *)vr->Data = '1';
+ }
+ }
+#endif
+ }
+ else
+ vr->Data = NULL;
+
+ DCMObject->Push(vr);
+ }
+
+ return ( TRUE );
+ }
+
+BOOL PDU_Service :: Implicit_ParseDCMIntoRawVR (
+ DICOMObject *DCMObject,
+ LinkedBuffer &lVRBuffer)
+ {
+ VR *vr;
+// Array<DICOMObject *> *ArrayPtr;
+ UINT Index;
+ UINT A1Flag;
+ UINT32 tuint32;
+
+ while ((vr = DCMObject->Pop()))
+ {
+ if ((!vr->Element) && (vr->Group != 0x00))
+ {
+ delete vr;
+ continue;
+ }
+ lVRBuffer << vr->Group;
+ lVRBuffer << vr->Element;
+ if(vr->Length&0x01)
+ {
+ A1Flag = 1;
+ ++vr->Length;
+ }
+ else
+ A1Flag = 0;
+ if(!vr->SQObjectArray)
+ {
+ lVRBuffer << vr->Length;
+ if(vr->Length)
+ lVRBuffer.Write ( (BYTE *) vr->Data, vr->Length-A1Flag );
+ if(A1Flag)
+ {
+ lVRBuffer.Write((BYTE*) "\0", 1);
+ --vr->Length;
+ A1Flag = 0;
+ }
+ }
+ else
+ {
+ tuint32 = 0xffffffff;
+ lVRBuffer << tuint32;
+ if(A1Flag)
+ {
+ // (intentionally commented out)lVRBuffer.Write((BYTE*) "\0", 1);
+ --vr->Length;
+ A1Flag = 0;
+ }
+ }
+ if(vr->SQObjectArray)
+ {
+ Array < DICOMDataObject *> *ArrayPtr =
+ (Array<DICOMDataObject *> *) vr->SQObjectArray;
+ Index = 0;
+ if ( (vr->Group == 0x7fe0 )&&
+ (vr->Element == 0x0010 ))
+ {
+ ParseImagePixelDataDCMToRaw(ArrayPtr, lVRBuffer);
+ delete vr;
+ continue;
+ }
+ while ( Index < ArrayPtr->GetSize() )
+ {
+ vr->Group = 0xfffe;
+ vr->Element = 0xe000;
+ vr->Length = 0xffffffff;
+ lVRBuffer << vr->Group;
+ lVRBuffer << vr->Element;
+ lVRBuffer << vr->Length;
+ Implicit_ParseDCMIntoRawVR(
+ ArrayPtr->Get(Index), lVRBuffer);
+ vr->Group = 0xfffe;
+ vr->Element = 0xe00d;
+ vr->Length = 0x00000000;
+ lVRBuffer << vr->Group;
+ lVRBuffer << vr->Element;
+ lVRBuffer << vr->Length;
+ ++Index;
+ }
+ vr->Group = 0xfffe;
+ vr->Element = 0xe0dd;
+ vr->Length = 0x00000000;
+ lVRBuffer << vr->Group;
+ lVRBuffer << vr->Element;
+ lVRBuffer << vr->Length;
+ }
+
+ delete vr;
+ }
+ return ( TRUE );
+ }
+
+
+BOOL PDU_Service :: ExplicitLittleEndian_ParseRawVRIntoDCM(
+ LinkedBuffer &lVRBuffer,
+ DICOMObject *DCMObject)
+ {
+ lVRBuffer.SetIncomingEndian(LITTLE_ENDIAN);
+ return ( Explicit_ParseRawVRIntoDCM(lVRBuffer, DCMObject) );
+ }
+
+BOOL PDU_Service :: ExplicitLittleEndian_ParseDCMIntoRawVR (
+ DICOMObject *DCMObject,
+ LinkedBuffer &lVRBuffer)
+ {
+ lVRBuffer.SetOutgoingEndian ( LITTLE_ENDIAN );
+ return ( Explicit_ParseDCMIntoRawVR(DCMObject, lVRBuffer) );
+ }
+
+BOOL PDU_Service :: ExplicitBigEndian_ParseRawVRIntoDCM(
+ LinkedBuffer &lVRBuffer,
+ DICOMObject *DCMObject)
+ {
+ lVRBuffer.SetIncomingEndian(BIG_ENDIAN);
+ return ( Explicit_ParseRawVRIntoDCM(lVRBuffer, DCMObject) );
+ }
+
+BOOL PDU_Service :: ExplicitBigEndian_ParseDCMIntoRawVR (
+ DICOMObject *DCMObject,
+ LinkedBuffer &lVRBuffer)
+ {
+ lVRBuffer.SetOutgoingEndian ( BIG_ENDIAN );
+ return ( Explicit_ParseDCMIntoRawVR(DCMObject, lVRBuffer) );
+ }
+
+BOOL PDU_Service :: Explicit_ParseRawVRIntoDCM(LinkedBuffer &lVRBuffer, DICOMObject *DCMObject)
+ {
+ VR *vr;
+// UINT32 tuint32, tuint32_2;
+ UINT16 Length16;
+// DICOMObject *EBO; // Embedded sequence Object
+ BYTE s1[2];
+ BOOL swapEndian = false;
+
+ if(BIG_ENDIAN == lVRBuffer.GetIncomingEndian())//bcb Big Endian fix
+ {
+ lVRBuffer.SetIncomingEndian(LITTLE_ENDIAN);//Everything starts as little.
+ swapEndian = true;
+ }
+
+ unsigned int CurrentGroup = 0;
+ unsigned int CurrentElement = 0;
+ unsigned int CurrentGroupLength = 0xffffffff;
+
+ if ( ! DCMObject )
+ return ( FALSE ); // passed a NULL object pointer
+
+ while ( lVRBuffer.GetIncomingSize())
+ {
+ vr = new VR;
+ if ( ! vr )
+ return ( FALSE ); // memory error
+
+ lVRBuffer >> vr->Group;
+ if (swapEndian && vr->Group > 0x02)//after 0x02 change back
+ {
+ vr->Group = SwitchEndian(vr->Group);
+ lVRBuffer.SetIncomingEndian(BIG_ENDIAN);
+ swapEndian = false;
+ }
+ lVRBuffer >> vr->Element;
+
+ if (vr->Group < CurrentGroup)
+ {
+ if (DicomError(DCM_ERROR_PARSE, "(Exp) Encountered an invalid group order during load of DCM file (after %08x)\n", (CurrentGroup<<16)+CurrentElement))
+ return FALSE;
+ }
+
+ if (vr->Group != CurrentGroup)
+ {
+ CurrentGroup = vr->Group;
+ CurrentElement = 0;
+ CurrentGroupLength = 0xffffffff;
+ }
+
+ if (vr->Element < CurrentElement)
+ {
+ if (DicomError(DCM_ERROR_PARSE, "(Exp) Encountered an invalid element order during load of DCM file (in %08x)\n", (CurrentGroup<<16)+CurrentElement))
+ return FALSE;
+ }
+
+ CurrentElement = vr->Element;
+
+ if (vr->Group == 0x0000)
+ {
+ if (lVRBuffer.GetIncomingEndian()==BIG_ENDIAN)
+ { lVRBuffer.SetIncomingEndian(LITTLE_ENDIAN);
+ lVRBuffer >> vr->Length;
+ lVRBuffer.SetIncomingEndian(BIG_ENDIAN);
+ vr->Element = ((vr->Element&0xff) << 8) + ((vr->Element&0xff00) >> 8);
+ }
+ else
+ lVRBuffer >> vr->Length;
+
+ // Explicit Length ( normal)
+
+ if (vr->Length)
+ {
+
+ if (vr->Length > CurrentGroupLength || (vr->Length&1))
+ {
+ BOOL b=DicomError(DCM_ERROR_PARSE, "Explicit Parse encountered an invalid element length during load of DCM file (in %08x)\n", (CurrentGroup<<16)+CurrentElement);
+ DicomError(DCM_ERROR_PARSE, "Length = %d\n", vr->Length);
+ if (vr->Length > CurrentGroupLength)
+ DicomError(DCM_ERROR_PARSE, "Group Length = %u\n", CurrentGroupLength);
+ if (b && vr->Length > 0xffff && CurrentGroupLength!=0) return FALSE; // pass if not dangerous
+ DicomError(DCM_ERROR_PARSE, "Continuing parsing", 0);
+ }
+
+ vr->ReAlloc(vr->Length);
+ if ( !vr->Data )
+ return ( FALSE ); // memory error
+ lVRBuffer.Read ( (BYTE *) vr->Data, vr->Length);
+#ifdef DATE_FIX
+// Time to look a dates and fix it here if needed. Some systems allow invalid birthdates
+// like 00010101 (the DICOM box). Other systems (OsiriX) will delete the leading 0's,
+// but keep the vr length at 8.
+// Ex: vr->TypeCode = DA, vr->Length = 8, vr->Data = 10101. == Image not stored!
+// To fix this, find dates with the length of 8 and make sure the first digit is not 0.
+// I'm not interested in fixing the date and prefer an obviously invalid date,
+// but I don't want the year to excede the current year. Hope for 10010101.
+ if ( vr->Length == 8 ) //Dates (DA) are 8 long.
+ {
+ if ( vr->TypeCode == 'DA' ) // It's a date
+ {
+ if(*(char *)vr->Data == '0') *(char *)vr->Data = '1';
+ }
+ }
+#endif
+ }
+ else
+ vr->Data = NULL;
+ DCMObject->Push(vr);
+ continue;
+ }
+
+ if ( vr->Group == 0xfffe )
+ {
+ // Ok, this is a deliminator type of item.
+ // handled special. Always implicit
+ lVRBuffer >> vr->Length;
+
+ if ( (vr->Element == 0xe0dd)||
+ (vr->Element == 0xe00d) ) // implicit terminator
+ {
+ delete vr;
+ return ( TRUE );
+ }
+
+ if ( vr->Length == 0xffffffff)
+ {
+ // Implicit length.. go until deliminator
+ vr->Length = 0;delete vr;
+
+ DICOMDataObject *DDO = new DICOMDataObject;
+ if ( ! Explicit_ParseRawVRIntoDCM ( lVRBuffer, DDO ) )
+ {
+ delete DDO;
+ return ( FALSE );
+ }
+ DCMObject->Push(DDO);
+ continue;
+ }
+ else if (vr->Length > CurrentGroupLength || (vr->Length&1))
+ {
+ BOOL b=DicomError(DCM_ERROR_PARSE, "Implicit_Parse encountered an invalid element length during load of DCM file (in %08x)\n", (CurrentGroup<<16)+CurrentElement);
+ DicomError(DCM_ERROR_PARSE, "Length = %d\n", vr->Length);
+ if (vr->Length > CurrentGroupLength)
+ DicomError(DCM_ERROR_PARSE, "Group Length = %u\n", CurrentGroupLength);
+ if (b && vr->Length > 0xffff && CurrentGroupLength!=0) return FALSE; // pass if not dangerous
+ DicomError(DCM_ERROR_PARSE, "Continuing parsing", 0);
+ }
+
+ // Ok, an explicit length.. sequence item begin?
+ if ( vr->Element == 0xe000 )
+ {
+
+ vr->ReAlloc(vr->Length);
+ if ( !vr->Data )
+ return ( FALSE ); // memory error
+ lVRBuffer.Read ( (BYTE *) vr->Data, vr->Length);
+
+ MemoryBuffer MB( (BYTE*)vr->Data, vr->Length,
+ TRUE, lVRBuffer.GetIncomingEndian() );
+ vr->Length = 0;
+ vr->Data = NULL;
+ delete vr;
+
+ DICOMDataObject *DDO = new DICOMDataObject;
+ if ( ! Explicit_ParseRawVRIntoDCM ( MB, DDO ) )
+ {
+ delete DDO;
+ return ( FALSE );
+ }
+ DCMObject->Push(DDO);
+ continue;
+ }
+
+ // Not quite sure what to say here...
+ DicomError(DCM_ERROR_PARSE, "Sequence parse error during load of DCM file (after %08x)\n", (CurrentGroup<<16)+CurrentElement);
+ return ( FALSE );
+ }
+
+ lVRBuffer >> s1[0];lVRBuffer>>s1[1];
+ Pack(s1[0],s1[1],vr->TypeCode);
+
+ if( (vr->TypeCode=='OB')||
+ (vr->TypeCode=='OW')||
+ (vr->TypeCode=='UN')||
+ (vr->TypeCode=='UT')||
+ (vr->TypeCode=='SQ'))
+ {
+ lVRBuffer >> Length16; // Toss away 16 bits
+ lVRBuffer >> vr->Length; // 32 bit Length
+ }
+ else
+ {
+ lVRBuffer >> Length16;
+ vr->Length = (UINT32) Length16;
+ }
+
+
+ if ( vr->Length == 0xffffffff )
+ {
+ // variable length item [sequence, etc]
+ vr->Length = 0;
+ DCMObject->Push(vr);
+ if ( (vr->Group == 0x7fe0) &&
+ (vr->Element == 0x0010))
+ {
+ // Image Pixel data.. encapsulated.. ugly..
+
+ if(!ParseImagePixelDataRawToDCM(
+ lVRBuffer,
+ DCMObject))
+ return(FALSE);
+ continue;
+ }
+ // Recurse
+ if(!Explicit_ParseRawVRIntoDCM(lVRBuffer, DCMObject))
+ return(FALSE);
+ continue;
+ }
+
+ if ( vr->TypeCode == 'SQ' )
+ {
+ // explicit length sequence
+ // in this case.. pull the data into a memory buffer
+ // and parse that.
+ vr->ReAlloc(vr->Length);
+ if ( !vr->Data )
+ return ( FALSE ); // memory error
+ lVRBuffer.Read ( (BYTE *) vr->Data, vr->Length);
+
+ MemoryBuffer MB( (BYTE*)vr->Data, vr->Length,
+ TRUE, lVRBuffer.GetIncomingEndian() );
+ vr->Length = 0;
+ vr->Data = NULL;
+ DCMObject->Push(vr);
+
+ if ( ! Explicit_ParseRawVRIntoDCM ( MB, DCMObject ) )
+ {
+ return ( FALSE );
+ }
+ continue;
+ }
+
+ // Explicit Length ( normal)
+ if (vr->Length)
+ {
+ if (vr->Length > CurrentGroupLength || (vr->Length&1))
+ {
+ BOOL b=DicomError(DCM_ERROR_PARSE, "Explicit_ParseRaw encountered an invalid element length during load of DCM file (in %08x)\n", (CurrentGroup<<16)+CurrentElement);
+ DicomError(DCM_ERROR_PARSE, "Length = %d\n", vr->Length);
+ if (vr->Length > CurrentGroupLength)
+ DicomError(DCM_ERROR_PARSE, "Group Length = %u\n", CurrentGroupLength);
+ if (b && vr->Length > 0xffff && CurrentGroupLength!=0) return FALSE; // pass if not dangerous
+ DicomError(DCM_ERROR_PARSE, "Continuing parsing", 0);
+ }
+
+ vr->ReAlloc(vr->Length);
+ if ( !vr->Data )
+ return ( FALSE ); // memory error
+
+ lVRBuffer.Read ( (BYTE *) vr->Data, vr->Length);
+
+ if (vr->Element==0)
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ CurrentGroupLength = *(unsigned int *)vr->Data;
+#else //Big Endian like Apple power pc
+ CurrentGroupLength = SwitchEndian( *(unsigned int *)vr->Data);
+#endif
+ }
+ else
+ vr->Data = NULL;
+
+ DCMObject->Push(vr);
+ }
+
+ return ( TRUE );
+ }
+
+
+BOOL PDU_Service :: Explicit_ParseDCMIntoRawVR (
+ DICOMObject *DCMObject,
+ LinkedBuffer &lVRBuffer)
+ {
+ VR *vr;
+// Array<DICOMObject *> *ArrayPtr;
+ UINT Index;
+ UINT A1Flag;
+ UINT16 Length16;
+ BYTE s1[2];
+ UINT32 tuint32;
+
+ while ((vr = DCMObject->Pop()))
+ {
+ if((!vr->Element) && (vr->Group != 0x0000))
+ {
+ // LJ maybe send group-length of group 0x0000
+ delete vr; // 4/16/96 - no longer sender group length under
+ // explicit. It wasn't correct anyway.
+ continue;
+ }
+ lVRBuffer << vr->Group;
+ lVRBuffer << vr->Element;
+
+
+ if (vr->TypeCode == 0 && AttachedRTC)
+ AttachedRTC->RunTimeClass(vr);
+
+ if (vr->TypeCode == 0)
+ vr->TypeCode = 'UN';
+
+ Pack(vr->TypeCode, s1[0], s1[1]);
+ lVRBuffer << s1[0];lVRBuffer<<s1[1];
+
+ if(vr->Length&0x01)
+ {
+ A1Flag = 1;
+ ++vr->Length;
+ }
+ else
+ A1Flag = 0;
+ if( (vr->TypeCode=='OB')||
+ (vr->TypeCode=='OW')||
+ (vr->TypeCode=='UN')||
+ (vr->TypeCode=='UT')||
+ (vr->TypeCode=='SQ'))
+ {
+ Length16 = 0;
+ lVRBuffer << Length16; // Toss in 16 bits
+ if(vr->SQObjectArray)
+ {
+ if(vr->SQObjectArray)
+ tuint32 = 0xffffffff;
+ else
+ tuint32 = 0;
+ lVRBuffer << tuint32;
+ }
+ else
+ lVRBuffer << vr->Length; // 32 bit Length
+ }
+ else
+ {
+ Length16 = (UINT16) vr->Length;
+ lVRBuffer << Length16;
+ }
+ if(vr->TypeCode!='SQ')
+ if(vr->Length)
+ lVRBuffer.Write ( (BYTE *) vr->Data, vr->Length-A1Flag );
+ if(A1Flag)
+ {
+ if(vr->TypeCode!='SQ')
+ lVRBuffer.Write((BYTE*) "\0", 1);
+ --vr->Length;
+ A1Flag = 0;
+ }
+
+ if(vr->SQObjectArray)
+ {
+ Array<DICOMDataObject*> *ArrayPtr =
+ (Array<DICOMDataObject *> *) vr->SQObjectArray;
+ Index = 0;
+ if ( (vr->Group == 0x7fe0 )&&
+ (vr->Element == 0x0010 ))
+ {
+ ParseImagePixelDataDCMToRaw(ArrayPtr, lVRBuffer);
+ delete vr;
+ continue;
+ }
+ while ( Index < ArrayPtr->GetSize() )
+ {
+ vr->Group = 0xfffe;
+ vr->Element = 0xe000;
+ vr->Length = 0xffffffff;
+ lVRBuffer << vr->Group;
+ lVRBuffer << vr->Element;
+ lVRBuffer << vr->Length;
+
+ Explicit_ParseDCMIntoRawVR(
+ ArrayPtr->Get(Index), lVRBuffer);
+ vr->Group = 0xfffe; // (0xfffe,0xe00d) is a Item Delimiter
+ vr->Element = 0xe00d;
+ vr->Length = 0;
+ lVRBuffer << vr->Group;
+ lVRBuffer << vr->Element;
+ lVRBuffer << vr->Length;
+ ++Index;
+ }
+ vr->Group = 0xfffe; // (0xfffe,0xe0dd) is a Sequence Delimiter
+ vr->Element = 0xe0dd;
+ vr->Length = 0;
+ lVRBuffer << vr->Group;
+ lVRBuffer << vr->Element;
+ lVRBuffer << vr->Length;
+
+ }
+
+ delete vr;
+ }
+ return ( TRUE );
+ }
+
+
+UINT
+static
+EndianOf(
+ UINT Alias)
+ {
+ if((Alias==TSA_EXPLICIT_LITTLE_ENDIAN)||
+ (Alias==TSA_IMPLICIT_LITTLE_ENDIAN))
+ return ( LITTLE_ENDIAN );
+ return ( BIG_ENDIAN );
+ }
+
+void SwapBigEndianData(VR* pVR)
+{ char cSave;
+ int i, iNbValues;
+ char* pcData;
+
+ switch (pVR->TypeCode)
+ { case 'FL': // float
+ case 'SL': // signed long
+ case 'UL': // unsigned long
+ pcData = (char*)pVR->Data;
+ iNbValues = pVR->Length / 4;
+ for (i=0; i<iNbValues; i++)
+ { cSave = pcData[0];
+ pcData[0] = pcData[3];
+ pcData[3] = cSave;
+ cSave = pcData[1];
+ pcData[1] = pcData[2];
+ pcData[2] = cSave;
+ pcData += 4;
+ }
+ break;
+
+ case 'OW': // int16 array
+ case 'SS': // signed short
+ case 'US': // unsigned short
+ pcData = (char*)pVR->Data;
+ iNbValues = pVR->Length / 2;
+ for (i=0; i<iNbValues; i++)
+ { cSave = pcData[0];
+ pcData[0] = pcData[1];
+ pcData[1] = cSave;
+ pcData += 2;
+ }
+ break;
+
+ case 'FD': // double
+ pcData = (char*)pVR->Data;
+ iNbValues = pVR->Length / 8;
+ for (i=0; i<iNbValues; i++)
+ { cSave = pcData[0];
+ pcData[0] = pcData[7];
+ pcData[7] = cSave;
+ cSave = pcData[1];
+ pcData[1] = pcData[6];
+ pcData[6] = cSave;
+ cSave = pcData[1];
+ pcData[2] = pcData[5];
+ pcData[5] = cSave;
+ cSave = pcData[1];
+ pcData[3] = pcData[4];
+ pcData[4] = cSave;
+ pcData += 8;
+ }
+ break;
+ }
+}
+
+
+BOOL PDU_Service :: Dynamic_ParseRawVRIntoDCM(
+ LinkedBuffer &lVRBuffer,
+ DICOMObject *DCMObject,
+ UINT Mode
+ )
+ {
+ VR *vr;
+ VR *vrTRN; //0x0002,0x0010
+// UINT32 tuint32, tuint32_2;
+ UINT16 Length16;
+// DICOMObject *EBO; // Embedded sequence Object
+ UINT NewMode;
+ BYTE s1[2];
+ char s[128];
+ int iOrgMode; // LJ + MVH: Added to save the original mode
+ unsigned int CurrentGroup = 0;
+ unsigned int CurrentElement = 0;
+ unsigned int CurrentGroupLength = 0xffffffff;
+
+// Init for warnings.
+ s1[0] = s1[1] = 0;
+
+ iOrgMode = Mode; // LJ + MVH
+
+ if ( ! DCMObject )
+ return ( FALSE ); // passed a NULL object pointer
+
+ if((Mode==TSA_EXPLICIT_LITTLE_ENDIAN)||
+ (Mode==TSA_IMPLICIT_LITTLE_ENDIAN))
+ lVRBuffer.SetIncomingEndian(LITTLE_ENDIAN);
+ else
+ lVRBuffer.SetIncomingEndian(BIG_ENDIAN);
+
+ vrTRN = NULL;
+
+ while ( lVRBuffer.GetIncomingSize())
+ {
+ vr = new VR;
+ if ( ! vr )
+ {
+ return FALSE;
+ }
+
+ lVRBuffer >> vr->Group;
+
+ if (vr->Group < CurrentGroup)
+ {
+ if (DicomError(DCM_ERROR_PARSE, "(Dyn) Encountered an invalid group order during load of DCM file (after %08x)\n", (CurrentGroup<<16)+CurrentElement))
+ return FALSE;
+ }
+
+ if(vr->Group > 0x0002)
+ {
+ // Key on the vrTRN
+ UINT Index,sLen;
+ if(vrTRN)
+ {
+ memset((void*)s, 0,128);
+ memcpy((void*)s,vrTRN->Data, vrTRN->Length%64);
+ sLen = strlen(s);
+ if(sLen)
+ {
+ if(s[sLen-1]==' ')
+ s[sLen-1]='\0';
+ }
+ Index = 0;
+ while(TransferSyntaxAliases[Index].TransferSyntaxUID)
+ {
+ if(!strcmp(TransferSyntaxAliases[Index].TransferSyntaxUID,s))
+ {
+// This bcb change breaks reads on many of my images mvh!
+// iOrgMode = 0; //No need to check again, we were told what it is. bcb 20100419
+
+ NewMode = TransferSyntaxAliases[Index].Alias;
+ if(NewMode==Mode)
+ break;
+ if(EndianOf(NewMode)!=EndianOf(Mode))
+ {
+ // Darn
+ vr->Group = SwitchEndian(vr->Group);
+ lVRBuffer.SetIncomingEndian(EndianOf(NewMode));
+ }
+ Mode = NewMode; // LJ + MVH: Maybe disollow this later...
+ break;
+ }
+ ++Index;
+ }
+ if(!TransferSyntaxAliases[Index].TransferSyntaxUID)
+ {
+ DicomError(DCM_ERROR_PARSE, "Unknown transfer syntax in %08x\n", (CurrentGroup<<16)+CurrentElement);
+ return FALSE;
+ }
+ vrTRN = NULL;
+ }
+ }
+
+ if (vr->Group != CurrentGroup)//Bcb must be done after "Big Endian" check
+ {
+ CurrentGroup = vr->Group;
+ CurrentElement = 0;
+ CurrentGroupLength = 0xffffffff;
+ }
+
+ lVRBuffer >> vr->Element;
+
+ if (vr->Element < CurrentElement)
+ {
+
+#ifdef NOVARAD_FIX
+ if(CurrentGroup == 0x0002 && CurrentElement == 0x0016 && vr->Element == 0x0013)
+ {// Looks like NovaRad
+ lVRBuffer >> s1[0];
+ lVRBuffer >> s1[1];
+ if(s1[0] == 'S' && s1[1] == 'H')
+ {// Looking more like NovaRad
+ lVRBuffer >> Length16;
+ if(Length16 > 7 && Length16 < 0x0010)
+ {//Getting closer
+ vr->ReAlloc(Length16);
+ if ( !vr->Data )
+ return ( FALSE ); // memory error
+ lVRBuffer.Read ( (BYTE *) vr->Data, Length16);
+ if(memcmp(vr->Data, "NovaRad", 7) == 0)
+ {//Sneaky NovaRad, bad bad NovaRad!
+ delete vr;// Dump the bad vr.
+ continue;// Lets keep going.
+ }
+ }
+ }
+ }
+#endif
+
+ if (DicomError(DCM_ERROR_PARSE, "(Dyn) Encountered an invalid element order during load of DCM file (in %08x)\n", (CurrentGroup<<16)+CurrentElement))
+ return FALSE;
+ }
+
+ CurrentElement = vr->Element;
+
+ // Regardless of mode.. 0xfffe are encoded implicit
+ if ( vr->Group == 0xfffe )
+ {
+ // Ok, this is a deliminator type of item.
+ // handled special. Always implicit
+
+ lVRBuffer >> vr->Length;
+
+ if ( (vr->Element == 0xe0dd)||
+ (vr->Element == 0xe00d) ) // implicit terminmator
+ {
+ delete vr;
+ return ( TRUE );
+ }
+
+ if ( vr->Length == 0xffffffff)
+ {
+ // Implicit length.. go until deliminator
+ vr->Length = 0;delete vr;
+
+ DICOMDataObject *DDO = new DICOMDataObject;
+ if((Mode==TSA_EXPLICIT_BIG_ENDIAN)||
+ (Mode==TSA_EXPLICIT_LITTLE_ENDIAN))
+ {
+ if ( ! Explicit_ParseRawVRIntoDCM ( lVRBuffer, DDO ) )
+ {
+ delete DDO;
+ return ( FALSE );
+ }
+ }
+ else
+ {
+ if ( ! Implicit_ParseRawVRIntoDCM ( lVRBuffer, DDO, FALSE ) )
+ {
+ delete DDO;
+ return ( FALSE );
+ }
+ }
+ DCMObject->Push(DDO);
+ continue;
+ }
+ else if (vr->Length > CurrentGroupLength || (vr->Length&1))
+ {
+ BOOL b=DicomError(DCM_ERROR_PARSE, "Dynamic Parse encountered an invalid element length during load of DCM file (in %08x)\n", (CurrentGroup<<16)+CurrentElement);
+ DicomError(DCM_ERROR_PARSE, "Length = %d\n", vr->Length);
+ if (vr->Length > CurrentGroupLength)
+ DicomError(DCM_ERROR_PARSE, "Group Length = %u\n", CurrentGroupLength);
+ if (b && vr->Length > 0xffff && CurrentGroupLength!=0) return FALSE; // pass if not dangerous
+ DicomError(DCM_ERROR_PARSE, "Continuing parsing", 0);
+ }
+
+
+ // Ok, an explicit length.. sequence item begin?
+ if ( vr->Element == 0xe000 )
+ {
+ vr->ReAlloc(vr->Length);
+ if ( !vr->Data )
+ {
+ delete vr;
+ return ( FALSE ); // memory error
+ }
+ lVRBuffer.Read ( (BYTE *) vr->Data, vr->Length);
+
+ MemoryBuffer MB( (BYTE*)vr->Data, vr->Length,
+ TRUE, lVRBuffer.GetIncomingEndian() );
+ vr->Length = 0;
+ //delete vr->Data;
+ vr->Data = NULL;
+ delete vr;
+ DICOMDataObject *DDO = new DICOMDataObject;
+ if((Mode==TSA_EXPLICIT_BIG_ENDIAN)||
+ (Mode==TSA_EXPLICIT_LITTLE_ENDIAN))
+ {
+ if ( ! Explicit_ParseRawVRIntoDCM ( MB, DDO ) )
+ {
+ delete DDO;
+ return ( FALSE );
+ }
+ }
+ else
+ {
+ if ( ! Implicit_ParseRawVRIntoDCM ( MB, DDO, FALSE ) )
+ {
+ delete DDO;
+ return ( FALSE );
+ }
+ }
+ DCMObject->Push(DDO);
+ continue;
+ }
+
+ // Not quite sure what to say here...
+ delete vr;
+ DicomError(DCM_ERROR_PARSE, "Sequence parse error during load of DCM file (after %08x)\n", (CurrentGroup<<16)+CurrentElement);
+ return ( FALSE );
+ }
+
+
+ if (iOrgMode && (vr->Group > 0x0002))
+ {
+ /* LJ + MVH: iOrgMode will be set to one when leaving this 'if', and set
+ to zero in the following if.
+ So, this if is entered only when processing this first GroupElement NOT
+ belonging to the metaheader...
+ This code check whether TypeCodes are present. In the Davis software,
+ the presence of TypeCodes is called 'explicit' !
+ The same check is done in 'filepdu.cxx': PDU_Service::LoadDICOMDataObject()
+ In the Davis software, IMPLICIT_BIG_ENDIAN is not known.
+ */
+ lVRBuffer >> s1[0];
+ lVRBuffer >> s1[1];
+ if (s1[1] > 10) // Explicit
+ {
+ if (Mode == TSA_IMPLICIT_LITTLE_ENDIAN)
+ Mode = TSA_EXPLICIT_LITTLE_ENDIAN;
+ }
+ else
+ {
+ if (Mode == TSA_EXPLICIT_LITTLE_ENDIAN)
+ Mode = TSA_IMPLICIT_LITTLE_ENDIAN;
+ }
+ iOrgMode = 1;
+ }
+
+ if((Mode==TSA_EXPLICIT_LITTLE_ENDIAN)||
+ (Mode==TSA_EXPLICIT_BIG_ENDIAN))
+ {
+ if (iOrgMode != 1)
+ {
+ lVRBuffer >> s1[0];
+ lVRBuffer >> s1[1];
+ }
+ else
+ iOrgMode = 0; // LJ + MVH: allready read two bytes
+ Pack(s1[0], s1[1], vr->TypeCode);
+
+
+ if( (vr->TypeCode=='OB')||
+ (vr->TypeCode=='OW')||
+ (vr->TypeCode=='UN')||
+ (vr->TypeCode=='UT')||
+ (vr->TypeCode=='SQ'))
+ {
+ lVRBuffer >> Length16; // Toss away 16 bits
+ lVRBuffer >> vr->Length; // 32 bit Length
+ }
+ else
+ {
+ lVRBuffer >> Length16;
+ vr->Length = (UINT32) Length16;
+ }
+ }
+ else // TSA_IMPLICIT_LITTLE_ENDIAN
+ {
+ if (iOrgMode != 1)
+ lVRBuffer >> vr->Length;
+ else
+ { // LJ + MVH: already read two bytes
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ *((char*)(&vr->Length) + 0) = s1[0];
+ *((char*)(&vr->Length) + 1) = s1[1];
+ lVRBuffer >> ((char*)(&vr->Length))[2];
+ lVRBuffer >> ((char*)(&vr->Length))[3];
+#else //Big Endian like Apple power pc
+ *((char*)(&vr->Length) + 3) = s1[0];
+ *((char*)(&vr->Length) + 2) = s1[1];
+ lVRBuffer >> ((char*)(&vr->Length))[1];
+ lVRBuffer >> ((char*)(&vr->Length))[0];
+#endif
+ iOrgMode = 0;
+ }
+ if ( AttachedRTC )
+ AttachedRTC->RunTimeClass ( vr );
+ }
+
+ if(vr->Group == 0x0002)
+ {
+ if(vr->Element==0x0010)
+ vrTRN = vr;
+ }
+
+
+ // Ok, at this point it's not a 0xfffe element, and it's
+ // and the group, element, length (and possibly typecode)
+ // has been decoded.
+ // must now
+
+
+ if ( vr->Length == 0xffffffff )
+ {
+ // variable length item [sequence, etc]
+ vr->Length = 0;
+ DCMObject->Push(vr);
+ if ( (vr->Group == 0x7fe0) &&
+ (vr->Element == 0x0010))
+ {
+ // Image Pixel data.. encapsulated.. ugly..
+
+ if(!ParseImagePixelDataRawToDCM(
+ lVRBuffer,
+ DCMObject))
+ return(FALSE);
+ continue;
+ }
+ // Recurse
+ if((Mode==TSA_EXPLICIT_BIG_ENDIAN)||
+ (Mode==TSA_EXPLICIT_LITTLE_ENDIAN))
+ {
+ if ( ! Explicit_ParseRawVRIntoDCM ( lVRBuffer, DCMObject ) )
+ return(FALSE);
+ }
+ else
+ {
+ if ( ! Implicit_ParseRawVRIntoDCM ( lVRBuffer, DCMObject, FALSE ) )
+ {
+ return(FALSE);
+ }
+ }
+
+ continue;
+ }
+
+ else if (vr->Length > CurrentGroupLength || (vr->Length&1))
+ {
+ BOOL b=DicomError(DCM_ERROR_PARSE, "Dynamic_Parse encountered an invalid element length during load of DCM file (in %08x)\n", (CurrentGroup<<16)+CurrentElement);
+ DicomError(DCM_ERROR_PARSE, "Length = %d\n", vr->Length);
+ if (vr->Length > CurrentGroupLength)
+ DicomError(DCM_ERROR_PARSE, "Group Length = %u\n", CurrentGroupLength);
+ if (b && vr->Length > 0xffff && CurrentGroupLength!=0) return FALSE; // pass if not dangerous
+ DicomError(DCM_ERROR_PARSE, "Continuing parsing", 0);
+ }
+
+ if ( vr->TypeCode == 'SQ' )
+ {
+ // explicit length sequence
+ // in this case.. pull the data into a memory buffer
+ // and parse that.
+ vr->ReAlloc(vr->Length);
+ if ( !vr->Data )
+ return ( FALSE ); // memory error
+ lVRBuffer.Read ( (BYTE *) vr->Data, vr->Length);
+
+ MemoryBuffer MB( (BYTE*)vr->Data, vr->Length,
+ TRUE, lVRBuffer.GetIncomingEndian() );
+ vr->Length = 0;
+ vr->Data = NULL;
+ DCMObject->Push(vr);
+
+ if((Mode==TSA_EXPLICIT_BIG_ENDIAN)||
+ (Mode==TSA_EXPLICIT_LITTLE_ENDIAN))
+ {
+ if ( ! Explicit_ParseRawVRIntoDCM ( MB, DCMObject ) )
+ {
+ return ( FALSE );
+ }
+ }
+ else
+ {
+ if ( ! Implicit_ParseRawVRIntoDCM ( MB, DCMObject, FALSE ) )
+ {
+ return ( FALSE );
+ }
+ }
+ continue;
+ }
+
+ // Explicit Length ( normal)
+ if ( vr->Length )
+ {
+ vr->ReAlloc(vr->Length);
+ if ( !vr->Data )
+ return ( FALSE ); // memory error
+ lVRBuffer.Read ( (BYTE *) vr->Data, vr->Length);
+ if (Mode==TSA_EXPLICIT_BIG_ENDIAN)
+ SwapBigEndianData(vr);
+
+ if (vr->Element==0)
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ CurrentGroupLength = *(unsigned int *)vr->Data;
+#else //Big Endian like Apple power pc
+ CurrentGroupLength = SwitchEndian(*(unsigned int *)vr->Data);
+#endif
+#ifdef DATE_FIX
+// Time to look a dates and fix it here if needed. Some systems allow invalid birthdates
+// like 00010101 (the DICOM box). Other systems (OsiriX) will delete the leading 0's,
+// but keep the vr length at 8.
+// Ex: vr->TypeCode = DA, vr->Length = 8, vr->Data = 10101. == Image not stored!
+// To fix this, find dates with the length of 8 and make sure the first digit is not 0.
+// I'm not interested in fixing the date and prefer an obviously invalid date,
+// but I don't want the year to excede the current year. Hope for 10010101.
+ if ( vr->Length == 8 ) //Dates (DA) are 8 long.
+ {
+ if ( vr->TypeCode == 'DA' ) // It's a date
+ {
+ if(*(char *)vr->Data == '0') *(char *)vr->Data = '1';
+ }
+ }
+#endif
+ }
+ else
+ vr->Data = NULL;
+
+ DCMObject->Push(vr);
+ }
+
+ return ( TRUE );
+ }
+
+BOOL PDU_Service :: Dynamic_ParseDCMIntoRawVR(
+ DICOMObject *DCMObject,
+ LinkedBuffer &lVRBuffer,
+ UINT Mode)
+ {
+
+ VR *vr,*vrTRN;
+// Array<DICOMObject *> *ArrayPtr;
+ UINT Index;
+ UINT A1Flag;
+ UINT16 Length16;
+ UINT NewMode;
+ BYTE s1[2];
+ char s[128];
+ UINT32 tuint32;
+
+
+ if((Mode==TSA_EXPLICIT_LITTLE_ENDIAN)||
+ (Mode==TSA_IMPLICIT_LITTLE_ENDIAN))
+ lVRBuffer.SetIncomingEndian(LITTLE_ENDIAN);
+ else
+ lVRBuffer.SetIncomingEndian(BIG_ENDIAN);
+
+#if NATIVE_ENDIAN == BIG_ENDIAN //Big Endian like Apple power pc
+ lVRBuffer.SetOutgoingEndian(LITTLE_ENDIAN);
+#endif
+
+ vrTRN = NULL;
+ while ((vr = DCMObject->Pop()))
+ {
+ if(vrTRN && vr->Group>0x0002)
+ {
+ // Key on the vrTRN
+ UINT Index2,sLen;
+ memset((void*)s, 0,128);
+ memcpy((void*)s,vrTRN->Data, vrTRN->Length%64);
+ sLen = strlen(s);
+ if(sLen)
+ {
+ if(s[sLen-1]==' ')
+ s[sLen-1]='\0';
+ }
+ Index2 = 0;
+ while(TransferSyntaxAliases[Index2].TransferSyntaxUID)
+ {
+ if(!strcmp(TransferSyntaxAliases[Index2].TransferSyntaxUID,s))
+ {
+ NewMode = TransferSyntaxAliases[Index2].Alias;
+ if(NewMode==Mode)
+ break;
+ lVRBuffer.SetIncomingEndian(EndianOf(NewMode));
+ Mode = NewMode;
+ break;
+ }
+ ++Index2;
+ }
+ if(!TransferSyntaxAliases[Index2].TransferSyntaxUID)
+ return ( FALSE ); // woa, cannot encode remainder of data set
+ delete vrTRN;
+ vrTRN = NULL;
+ }
+
+ if((Mode==TSA_EXPLICIT_BIG_ENDIAN)||
+ (Mode==TSA_EXPLICIT_LITTLE_ENDIAN))
+ if(!vr->Element)
+ {
+ if (vr->Group == 0x0002)
+ {
+ /* LJ: Keep grouplength of Chapter10, but fix the value so that
+ the 'DICM' tag is included
+ */
+#if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian
+ *((int*)vr->Data) = *((int*)vr->Data) + 4;//strlen("DICM");
+#else //Big Endian like Apple power pc
+ *((UINT32*)vr->Data) = SwitchEndian(
+ SwitchEndian(*((UINT32*)vr->Data)) + 4);
+#endif
+ }
+ else
+ {
+ delete vr; // 4-16-96 No longer send group length in
+ // explicit mode. --wasn't correct anyway.
+ continue;
+ }
+ }
+
+ lVRBuffer << vr->Group;
+ lVRBuffer << vr->Element;
+
+
+ if(vr->Length&0x01)
+ {
+ A1Flag = 1;
+ ++vr->Length;
+ }
+ else
+ A1Flag = 0;
+
+
+ if((Mode==TSA_EXPLICIT_BIG_ENDIAN)||
+ (Mode==TSA_EXPLICIT_LITTLE_ENDIAN))
+ {
+ if (vr->TypeCode == 0 && AttachedRTC)
+ AttachedRTC->RunTimeClass(vr);
+
+ if (vr->TypeCode == 0)
+ vr->TypeCode = 'UN';
+
+ Pack(vr->TypeCode, s1[0], s1[1]);
+ lVRBuffer << s1[0];lVRBuffer<<s1[1];
+
+ if( (vr->TypeCode=='OB')||
+ (vr->TypeCode=='OW')||
+ (vr->TypeCode=='UN')||
+ (vr->TypeCode=='UT')||
+ (vr->TypeCode=='SQ'))
+ {
+ Length16 = 0;
+ lVRBuffer << Length16; // Toss in 16 bits
+ if(vr->SQObjectArray)
+ {
+ tuint32 = 0xffffffff;
+ lVRBuffer << tuint32;
+ }
+ else
+ lVRBuffer << vr->Length; // 32 bit Length
+ }
+ else
+ {
+ Length16 = (UINT16) vr->Length;
+ lVRBuffer << Length16;
+ }
+ }
+ else
+ {
+ if(vr->SQObjectArray)
+ {
+ tuint32 = 0xffffffff;
+ lVRBuffer << tuint32;
+ }
+ else
+ lVRBuffer << vr->Length;
+ }
+
+
+ if(vr->Length)
+ lVRBuffer.Write ( (BYTE *) vr->Data, vr->Length-A1Flag );
+
+
+ if(A1Flag)
+ {
+ lVRBuffer.Write((BYTE*) "\0", 1);
+ --vr->Length;
+ A1Flag = 0;
+ }
+
+ if(vr->SQObjectArray)
+ {
+ Array<DICOMDataObject*> *ArrayPtr =
+ (Array<DICOMDataObject *> *) vr->SQObjectArray;
+
+ if ( (vr->Group == 0x7fe0 )&&
+ (vr->Element == 0x0010 ))
+ {
+ ParseImagePixelDataDCMToRaw(ArrayPtr, lVRBuffer);
+ delete vr;
+ continue;
+ }
+
+ Index = 0;
+ while ( Index < ArrayPtr->GetSize() )
+ {
+ vr->Group = 0xfffe;
+ vr->Element = 0xe000;
+ vr->Length = 0xffffffff;
+ lVRBuffer << vr->Group;
+ lVRBuffer << vr->Element;
+ lVRBuffer << vr->Length;
+
+ if((Mode==TSA_EXPLICIT_LITTLE_ENDIAN)||
+ (Mode==TSA_EXPLICIT_BIG_ENDIAN))
+ {
+ Explicit_ParseDCMIntoRawVR(
+ ArrayPtr->Get(Index), lVRBuffer);
+ }
+ else
+ {
+ Implicit_ParseDCMIntoRawVR(
+ ArrayPtr->Get(Index), lVRBuffer);
+ }
+ vr->Group = 0xfffe;
+ vr->Element = 0xe00d;
+ vr->Length = 0;
+ lVRBuffer << vr->Group;
+ lVRBuffer << vr->Element;
+ lVRBuffer << vr->Length;
+ ++Index;
+ }
+ vr->Group = 0xfffe;
+ vr->Element = 0xe0dd;
+ vr->Length = 0;
+ lVRBuffer << vr->Group;
+ lVRBuffer << vr->Element;
+ lVRBuffer << vr->Length;
+ }
+
+ if((vr->Group == 0x0002)&&
+ (vr->Element==0x0010))
+ vrTRN = vr;
+ else
+ delete vr;
+ }
+ if(vrTRN)
+ delete vrTRN;
+
+ return ( TRUE );
+ }
+
+
+
+char* PDU_Service :: GetTransferSyntaxUID (UINT TransferSyntaxMode)
+{
+
+ UINT Index;
+ char *TransferSyntax;
+
+ TransferSyntax = NULL;// Init for warning.
+ Index = 0;
+ while(TransferSyntaxAliases[Index].TransferSyntaxUID)
+ {
+ if(TransferSyntaxMode == TransferSyntaxAliases[Index].Alias)
+ {
+ TransferSyntax = (char *)malloc(64+1);
+ if (TransferSyntax)
+ { memset(TransferSyntax, 0, (64+1));
+ strcpy(TransferSyntax, TransferSyntaxAliases[Index].TransferSyntaxUID);
+ }
+ break;
+ }
+ ++Index;
+ }
+ return (TransferSyntax);
+}
+
diff --git a/uniq.cxx b/uniq.cxx
new file mode 100644
index 0000000..a708977
--- /dev/null
+++ b/uniq.cxx
@@ -0,0 +1,90 @@
+/*
+19990511 ljz Fix: All routines wrongly used '%' instead of '&'
+*/
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/*************************************************************************
+
+ * Unique ID's. Gurenteed to be unique in any given association, but not
+
+ * across multple associations.
+
+ ************************************************************************/
+
+# include "dicom.hpp"
+
+
+
+static unsigned long uniqid = 1;
+
+
+
+UINT uniq()
+{
+ return(uniqid++);
+}
+
+
+UINT32 uniq32()
+{
+ return(uniqid++);
+}
+
+
+UINT16 uniq16()
+{
+ return(UINT16)((uniqid++) & 0xffff);
+}
+
+
+
+UINT8 uniq8()
+{
+ return(UINT8)((uniqid++) & 0xff);
+}
+
+
+UINT8 uniq8odd()
+{
+ if(uniqid & 0x01)
+ return(UINT8)((uniqid++) & 0xff);
+ ++uniqid;
+ return(UINT8)((uniqid++) & 0xff);
+}
+
+
+UINT16 uniq16odd()
+{
+ if(uniqid & 0x01)
+ return(UINT16)((uniqid++) & 0xffff);
+ ++uniqid;
+ return(UINT16)((uniqid++) & 0xffff);
+}
+
diff --git a/unixsock.h b/unixsock.h
new file mode 100644
index 0000000..b4500d6
--- /dev/null
+++ b/unixsock.h
@@ -0,0 +1,50 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/* 20100726 bcb Removed superfluous ; */
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/* winsock.h */
+
+extern "C"
+ {
+#ifdef IRIX4MIPS
+# include <unistd.h>
+# include <bstring.h>
+#endif
+# include <fcntl.h>
+# include <signal.h>
+# include <errno.h>
+# include <sys/socket.h>
+# include <sys/types.h>
+# include <sys/time.h>
+# include <netinet/in.h>
+# include <netdb.h>
+# include <arpa/inet.h>
+ }
+
diff --git a/util.cxx b/util.cxx
new file mode 100644
index 0000000..e5992f5
--- /dev/null
+++ b/util.cxx
@@ -0,0 +1,70 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+# include "dicom.hpp"
+
+BOOL ByteCopy(BYTE *s1, BYTE *s2, UINT Count)
+ {
+ memcpy((void *) s1, (void *) s2, Count);
+ return ( TRUE );
+ }
+
+BOOL ZeroMem(BYTE *mem, UINT Count)
+ {
+ memset((void *) mem, 0, Count);
+ return ( TRUE );
+ }
+
+BOOL
+SpaceMem(
+ BYTE *mem,
+ UINT Count )
+ {
+ memset((void *) mem, ' ', Count);
+ return ( TRUE );
+ }
+
+UINT ByteStrLength(BYTE *s)
+ {
+ return ( strlen((char *) s) );
+ }
+/*
+UINT16 NativeEndian(UINT16 uint16, UINT Endian)
+ {
+ UINT16 ruint16;
+
+ if(Endian==NATIVE_ENDIAN)
+ return(uint16);
+
+ ruint16 = 0;
+ ruint16 = (uint16 << 8)&0xff00;
+ ruint16 = ruint16 | ((tuint16 >> 8) & 0x00ff);
+ return(ruint16);
+ }
+*/
diff --git a/util.h b/util.h
new file mode 100644
index 0000000..95e59a4
--- /dev/null
+++ b/util.h
@@ -0,0 +1,43 @@
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/* Utility C functions */
+UINT uniq();
+UINT32 uniq32();
+UINT16 uniq16();
+UINT8 uniq8();
+UINT8 uniq8odd();
+UINT16 uniq16odd();
+
+BOOL ByteCopy(BYTE *, BYTE *, UINT);
+BOOL ZeroMem(BYTE *, UINT);
+BOOL SpaceMem(BYTE *, UINT);
+UINT ByteStrLength(BYTE *);
+
+
diff --git a/verify.cxx b/verify.cxx
new file mode 100644
index 0000000..66ea090
--- /dev/null
+++ b/verify.cxx
@@ -0,0 +1,170 @@
+/*
+20050129 mvh Added ReadRequest and WriteResponse, allows extra response vr
+*/
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+# include "dicom.hpp"
+
+// Rather useful routine. Sets up a uid from a vr containing the vr
+
+BOOL SetUID ( UID &uid, VR *vr)
+ {
+ if(!vr)
+ return ( FALSE );
+ if(!vr->Data)
+ return ( FALSE );
+ if(vr->Length > 64 )
+ return ( FALSE );
+ memcpy((void*)uid.GetBuffer(vr->Length), (void*)vr->Data, vr->Length);
+
+ // This ensures that rounded up lengths don't pass garbage in that
+ // excess byte. They shouldn't be doing it, but if they do...
+ uid.SetLength(vr->Length);
+ switch (uid.GetBuffer(1) [ vr->Length - 1 ] )
+ {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ case '.':
+ return ( TRUE );
+ }
+ uid.GetBuffer(1) [ vr->Length - 1 ] = '\0';
+ uid.SetLength (vr->Length - 1);
+ return ( TRUE );
+ }
+
+BOOL Verification :: GetUID ( UID &uid )
+ {
+ uid.Set("1.2.840.10008.1.1");
+ return ( TRUE );
+ }
+
+BOOL Verification :: Read ( PDU_Service *PDU, DICOMCommandObject *DCO)
+ {
+ VR *vr;
+ UID MyUID, uid;
+
+ GetUID(MyUID); // always try and use GetUID to obtain my own uid
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! DCO )
+ return ( FALSE );
+
+ vr = DCO->GetVR ( 0x0000, 0x0002 );
+ if ( ! vr )
+ return ( FALSE );
+
+ if ( !SetUID(uid, vr) )
+ return ( FALSE );
+
+ if ( MyUID != uid )
+ return ( FALSE );
+
+ if ( CEchoRQ :: Read ( DCO ) )
+ {
+ return ( CEchoRSP :: Write ( PDU, DCO ) );
+ }
+ if ( CEchoRSP :: Read ( DCO ) )
+ {
+ // No worries..
+ return ( TRUE );
+ }
+ return ( FALSE ); // woa.. corrupted message
+ }
+
+BOOL Verification :: ReadRequest ( PDU_Service *PDU, DICOMCommandObject *DCO)
+ {
+ VR *vr;
+ UID MyUID, uid;
+
+ GetUID(MyUID); // always try and use GetUID to obtain my own uid
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! DCO )
+ return ( FALSE );
+
+ vr = DCO->GetVR ( 0x0000, 0x0002 );
+ if ( ! vr )
+ return ( FALSE );
+
+ if ( !SetUID(uid, vr) )
+ return ( FALSE );
+
+ if ( MyUID != uid )
+ return ( FALSE );
+
+ if ( CEchoRQ :: Read ( DCO ) )
+ {
+ return ( TRUE );
+ }
+ if ( CEchoRSP :: Read ( DCO ) )
+ {
+ // No worries..
+ return ( TRUE );
+ }
+ return ( FALSE ); // woa.. corrupted message
+ }
+
+
+BOOL Verification :: WriteResponse ( PDU_Service *PDU, DICOMCommandObject *DCO, VR *vr)
+ {
+ return ( CEchoRSP :: Write ( PDU, DCO, 0x0000, vr ) );
+ }
+
+BOOL Verification :: Write ( PDU_Service *PDU )
+ {
+ DICOMCommandObject DCO;
+
+ if ( ! PDU )
+ return ( FALSE );
+
+ if ( ! CEchoRQ :: Write ( PDU ) )
+ return ( FALSE );
+
+ if(!PDU->Read ( & DCO ))
+ return (FALSE);
+
+ if ( ! CEchoRSP :: Read ( &DCO ) )
+ return ( FALSE );
+ return ( TRUE );
+ }
+
+
diff --git a/verify.hpp b/verify.hpp
new file mode 100644
index 0000000..19eeb3e
--- /dev/null
+++ b/verify.hpp
@@ -0,0 +1,48 @@
+/*
+20050129 mvh Added ReadRequest and WriteResponse
+*/
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+// Verification SOP Service Class
+BOOL SetUID ( UID &, VR * );
+
+class Verification :
+ public CEchoRQ,
+ public CEchoRSP
+ {
+ public:
+ BOOL GetUID ( UID & );
+ public:
+ BOOL Read ( PDU_Service *, DICOMCommandObject * );
+ BOOL Write ( PDU_Service * );
+ BOOL ReadRequest ( PDU_Service *, DICOMCommandObject * );
+ BOOL WriteResponse ( PDU_Service *, DICOMCommandObject *, VR *);
+ };
+
diff --git a/version.h b/version.h
new file mode 100644
index 0000000..8ef0b15
--- /dev/null
+++ b/version.h
@@ -0,0 +1,86 @@
+/*
+200107017 ljz Changed ImplementationClassUID to a valid UID: the Agfa dicom
+ validation tool protested against the original 'UID'.
+ Changed ImplementationVersion from "0.1B/WIN32" to "1.01/WIN32"
+20020416 mvh changed IMPLEMENTATION_VERSION_STRING to 1.3.11/WIN32
+20021018 mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.0/WIN32
+20030424 ljz changed IMPLEMENTATION_VERSION_STRING to 2.0.1/WIN32
+20030709 mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.2/WIN32
+20030815 mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.3/WIN32
+20040402 mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.4/WIN32
+20040530 mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.5/WIN32
+20040713 mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.6/WIN32
+20041101 mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.7/WIN32
+20050901 mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.9/WIN32
+20060103 mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.10/WIN32
+20060311 mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.11/WIN32
+20060708 mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.12/WIN32
+20070307 mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.13/WIN32
+20080831 mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.14/WIN32
+20100713 bcb+mvh changed IMPLEMENTATION_VERSION_STRING to 1.4.16/WIN32; added osx
+*/
+
+/****************************************************************************
+ Copyright (C) 1995, University of California, Davis
+
+ THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
+ OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
+ PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+ USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
+ SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
+ THE SOFTWARE IS WITH THE USER.
+
+ Copyright of the software and supporting documentation is
+ owned by the University of California, and free access
+ is hereby granted as a license to use this software, copy this
+ software and prepare derivative works based upon this software.
+ However, any distribution of this software source code or
+ supporting documentation or derivative works (source code and
+ supporting documentation) must include this copyright notice.
+****************************************************************************/
+
+/***************************************************************************
+ *
+ * University of California, Davis
+ * UCDMC DICOM Network Transport Libraries
+ * Version 0.1 Beta
+ *
+ * Technical Contact: mhoskin at ucdavis.edu
+ *
+ ***************************************************************************/
+
+/* Version related information
+ *
+ * This file contains the version number/Class that will be embedded not
+ * only in the executable, but in the default PDU Service transfer Class.
+ *
+ */
+//# define IMPLEMENTATION_CLASS_STRING "UCDMC/gcc2.5.8/DECMIPS/MHO"
+# define IMPLEMENTATION_CLASS_STRING "1.2.826.0.1.3680043.2.135.1066.101"
+#ifdef WINDOWS
+//# define IMPLEMENTATION_VERSION_STRING "0.1B/WIN32"
+# define IMPLEMENTATION_VERSION_STRING "1.4.16/WIN32"
+#else
+#ifdef ULTRIXMIPS
+# define IMPLEMENTATION_VERSION_STRING "1.4.16/UMIPS"
+#else
+#ifdef SOLARIS
+# define IMPLEMENTATION_VERSION_STRING "1.4.16/SL5"
+#else
+#ifdef MAC
+# define IMPLEMENTATION_VERSION_STRING "1.4.16/MAC"
+#else
+#ifdef SUNOSSPARC
+# define IMPLEMENTATION_VERSION_STRING "1.4.16/SUNOS"
+#else
+#ifdef DARWIN
+# define IMPLEMENTATION_VERSION_STRING "1.4.16/OSX"
+#else
+# define IMPLEMENTATION_VERSION_STRING "1.4.16/OTHER"
+#endif
+#endif
+#endif
+#endif
+#endif
+#endif
+
diff --git a/vrtosql.cpp b/vrtosql.cpp
new file mode 100644
index 0000000..d68ab33
--- /dev/null
+++ b/vrtosql.cpp
@@ -0,0 +1,2830 @@
+/*
+20000629 ljz Logging of trouble now starts with '***'
+20010330 ljz Added a few debug printf's
+20010420 ljz Fixed memory leaks in all query levels
+20020519 mvh Clear BindField result strings before reading (NULL does not read)
+20021028 mvh Restructured queries to give lowest level of de-normalized databases
+ Fixed sorting on PatientName in denormalized study query
+20021030 mvh Reversed this again apart from study level because SQL server becomes very slow
+20030113 mvh Added PatientQuerySortOrder etc overrides for sorting
+20030114 mvh Added in querycolumns (even if akreday present);
+ tested for SQL server, requires testing for other datasources
+20030122 ljz+mvh Remove unused entries from Tables string in queries
+20040930 mvh Started adapt such that query strings etc and not limited in length
+ For now: query string max 8192 (here and in odbci.cpp); sql statement max 16384 (in odbci.hpp)
+ Enough for query with one multiple values UID of about 100 images (list truncated if too long)
+ Added safestrcat protection of SearchString
+20041003 mvh Truncated debug prints, malloc strings at image level
+ Analysed string lenghts; limited 'records =' debug log
+20041013 mvh Used MAXQUERYLENGTH
+20050107 mvh Removed UNIX flags: solve difference in database interface
+20050206 mvh Image query can send filename and device in 0x9999,0x800/0x0801
+20050401 mvh Added QueryOnModalityWorkList; - todo - put selected items into sequence 0040,0100
+20050404 mvh Take query for Scheduled Procedure Step from sequence, put results into sequence
+20050414 mvh Made sequence unfolding for worklist more generic - accepts any number of and nested N=1 sequences
+ This is correct behavior for query input, but limited for query results
+20050417 mvh Removed unused variable
+20050831 mvh Fixes in worklist code: is ok for all OFFIS tests except 1 (empty seq not returned) and
+ 10 (undef non-empty seq takes one entry from higher level) - good enough for initial release?
+20050901 mvh Fix for test 10: allow undefined sequence in query
+20050907 mvh Merged change by Hans-Peter Hellemann: fix missing max() macro
+20051229 mvh Debug log show records of all queries. DumpVR only left in worklistquery and shows sequence layout
+20051230 mvh Removed 2 forgotten dumpvr's
+20060103 mvh Added debug info from testing phase inside nested sequences for modality query
+20060211 mvh Added empty required modality sequences 8,1110 and 8,1120 when not there
+20060224 mvh Fixed modality worklist query: empty result sequences were not handled correctly (Thanks Tony Tong)
+20060311 mvh Worklist change was tested OK with Agfa (thanks Frank Grogan), cleaned debug log a bit
+20060607 mvh Fix crash when coding empty sequence as last item in worklist query (thanks Francois Piette)
+20061219 mvh Small fix in layout debug log
+20071118 mvh Adapted for 64 bits (use SQLLEN for BindField)
+20080817 mvh Fixed bug found by larc: worklist sql syntax error (fields start with ,) when 1st item is sequence
+ mvh Fixed bug found by Alberto Smulders: sometimes sequence level in response would not come down
+ The problem was that a higher levels the reported sequence level was inconsistent with the 1st level
+ Changed CodeSequence stop criterium and level coding for deeper levels; now works with varies sequence combination
+ Added WorkListReturnsISO_IR_100 flag (default 1)
+20080818 mvh DbaseIII check now uses DB flags, not PATHSEP in datasource name
+20080901 mvh Implemented 'Number of Patient Related Studies' (0x0020, 0x1200) etc
+20080902 mvh Fixed that option for VirtualServers; added EnableComputedFields
+20080905 bcb Added void* cast for deivr change
+20081016 mvh Fixed for WC compile
+20081121 mvh Fixed ISO_IR 100
+20090930 mvh Fixed ImageQuerySortOrder: crashed on C-MOVE, because sortcolumn was inserted before the filename
+20091005 mvh Fixed ComputeField: return VR was used during cleanup
+20091231 bcb Changed char* to const char* for gcc4.2 warnings
+20100111 mvh Merged
+20100309 bcb Added double parentheses (gcc4.2 Warnings)
+20100309 bcb Changed int to unsigned int, commented out unused variables (gcc4.2 Warnings)
+20100706 bcb Init Level
+20100717 mvh Merged
+20100822 mvh Delete 9999,0802 virtualservermask control VR from searches and pass it to ComputeField
+20100823 mvh Fixed compile for ms8amd64
+20100901 mvh Rephrased "Failed on VR Search...."
+20101003 mvh Delete 9999,0900 script control from queries
+20101120 mvh Delete 0002,0010 transfer syntax from queries
+20101127 mvh Added CountOnly mode to accelerate e.g., NumberOfStudyRelatedInstances queries
+20110105 mvh Pass database to MakeSafeString to allow db_type dependent processing; use LIKE only when needed
+20110105 mvh Moved local routines here: MakeSafeString, DICOM2SQLQuery, BuildSearchString, BuildColumnString
+20110603 mvh Fully init vr used for MakeSafeString
+20110605 mvh Allow ' *' for query
+20120214 mvh Allow WorkListReturnsISO_IR_100 to be any value (e.g., 192)
+20120422 mvh Fix search in DT_MSTR with embedded _ to use =, was a LIKE that failed for MySQL
+20120624 mvh Fix DT_MSTR for DoubleBackSlashToDB (mysql and pgsql): requires 4 backslashses (!)
+20120701 mvh Fix in BuildSearchString for UseEscapeStringConstants for DT_MSTR and DT_DATE
+*/
+
+#ifndef WHEDGE
+# include "dgate.hpp"
+#else
+# include "master.h"
+#endif
+
+extern char PatientQuerySortOrder[];
+extern char StudyQuerySortOrder[];
+extern char SeriesQuerySortOrder[];
+extern char ImageQuerySortOrder[];
+extern int WorkListReturnsISO_IR_100;
+extern int EnableComputedFields;
+extern int DoubleBackSlashToDB;
+extern int UseEscapeStringConstants;
+
+void safestrcat(char *result, const char *tocat, int maxlen)
+{ int len = strlen(result), len2 = strlen(tocat);
+ if (len+len2 < maxlen)
+ strcpy(result+len, tocat);
+}
+
+// from dgate.cpp
+#ifndef VirtualQuery
+int VirtualQuery(DICOMDataObject *DDO, const char *Level, int N, Array < DICOMDataObject *> *pADDO, char *ae);
+#endif
+
+void RemoveQueryDuplicates(const char *Level, Array < DICOMDataObject * > *ADDO);
+
+BOOL
+MakeSafeString (
+ VR *vr,
+ char *string,
+ Database *db )
+ {
+ unsigned int Length;
+ char *sout;
+ char *sin;
+ char *s;
+ UINT Index;
+ BOOL AddEscape = FALSE;
+ BOOL UseLike = FALSE;
+
+ s = SetString(vr, NULL, 0);
+ Length = strlen(s);
+ sin = (char*)s;
+ sout = string;
+
+ // convert ** query to * query (efilm problem)
+ if (Length==2 && s[0]=='*' && s[1]=='*') Length--;
+
+ // convert ' *' query to '*' query (some other pacs problem)
+ if (Length==2 && s[0]==' ' && s[1]=='*') { Length--; s[0]='*'; }
+
+ if (strchr(s, '*') || strchr(s, '?')) // 20110105: force use of 'LIKE' (pattern matching), else use exact matching
+ {
+ (*sout++) = '?'; // is processed by BuildSearchString defined and only used below
+ UseLike = TRUE;
+ }
+
+ if (UseEscapeStringConstants) // typically for postgres
+ (*sout++) = 'E';
+
+ (*sout++) = '\'';
+
+ if (vr)
+ if(vr->Data)
+ {
+ Index = 0;
+ while(Index < Length)
+ {
+ switch (*sin)
+ {
+ case '*':
+ (*sout) = '%';++sout;
+ break;
+
+ case '?':
+ (*sout) = '_';++sout;
+ break;
+
+ // original code
+// case '%':
+// (*sout) = '\\';++sout;
+// (*sout) = '%';++sout;
+// break;
+// case '[':
+// (*sout) = '\\';++sout;
+// (*sout) = '[';++sout;
+// break;
+// case '_':
+// (*sout) = '_';++sout;
+// break;
+// case '\\': // not OK: mysql, sqlite, sqlserver
+// if (DoubleBackSlashToDB)// OK: dbase (set for mysql and postgres)`
+// {
+// if ((Index > 0) && (sin[-1] != '\\'))
+// {
+// (*sout) = '\\';++sout;
+// (*sout) = '\\';++sout;
+// }
+// }
+// else
+// {
+// (*sout) = (*sin);
+// ++sout;
+// }
+// break;
+ // end original code
+
+ // redone these special characters: mvh 20110105
+ case '%':
+ if (db->db_type==DT_ODBC && UseLike) // sql server
+ {
+ (*sout) = '[';++sout;
+ (*sout) = '%';++sout;
+ (*sout) = ']';++sout;
+ }
+ else if (db->db_type==DT_SQLITE && UseLike)
+ {
+ (*sout) = '\\';++sout;
+ (*sout) = '%';++sout;
+ AddEscape = TRUE;
+ }
+ else if (db->db_type==DT_POSTGRES && UseLike)
+ {
+ (*sout) = '\\';++sout;
+ (*sout) = '\\';++sout;
+ (*sout) = '%';++sout;
+ AddEscape = TRUE;
+ }
+ else if (UseLike)
+ {
+ (*sout) = '\\';++sout; // ok: mysql, dbase
+ (*sout) = '%';++sout;
+ }
+ else
+ {
+ (*sout) = '%';++sout;
+ }
+ break;
+
+ case '[':
+ if (db->db_type==DT_ODBC && UseLike) // sql server
+ {
+ (*sout) = '[';++sout;
+ (*sout) = '[';++sout;
+ (*sout) = ']';++sout;
+ }
+ else if (db->db_type==DT_SQLITE && UseLike)
+ {
+ (*sout) = '\\';++sout;
+ (*sout) = '[';++sout;
+ AddEscape = TRUE;
+ }
+ else if (db->db_type==DT_POSTGRES && UseLike)
+ {
+ (*sout) = '\\';++sout;
+ (*sout) = '\\';++sout;
+ (*sout) = '[';++sout;
+ AddEscape = TRUE;
+ }
+ else if (UseLike)
+ {
+ (*sout) = '\\';++sout; // ok: mysql, dbase
+ (*sout) = '[';++sout;
+ }
+ else
+ {
+ (*sout) = '[';++sout;
+ }
+ break;
+
+ case '_':
+ if (db->db_type==DT_ODBC && UseLike) // sql server
+ {
+ (*sout) = '[';++sout;
+ (*sout) = '_';++sout;
+ (*sout) = ']';++sout;
+ }
+ else if (db->db_type==DT_SQLITE && UseLike)
+ {
+ (*sout) = '\\';++sout;
+ (*sout) = '_';++sout;
+ AddEscape = TRUE;
+ }
+ else if (db->db_type==DT_POSTGRES && UseLike)
+ {
+ (*sout) = '\\';++sout;
+ (*sout) = '\\';++sout;
+ (*sout) = '_';++sout;
+ AddEscape = TRUE;
+ }
+ else if (UseLike)
+ {
+ (*sout) = '\\';++sout; // ok: mysql, dbase
+ (*sout) = '_';++sout;
+ }
+ else
+ {
+ (*sout) = '_';++sout;
+ }
+ break;
+
+ case '\\':
+ if (db->db_type==DT_ODBC && UseLike) // sql server
+ {
+ (*sout) = '[';++sout;
+ (*sout) = '\\';++sout;
+ (*sout) = ']';++sout;
+ }
+ else if (db->db_type==DT_SQLITE && UseLike)
+ {
+ (*sout) = '\\';++sout;
+ (*sout) = '\\';++sout;
+ AddEscape = TRUE;
+ }
+ else if (db->db_type==DT_POSTGRES && UseLike)
+ {
+ (*sout) = '\\';++sout;
+ (*sout) = '\\';++sout;
+ (*sout) = '\\';++sout;
+ (*sout) = '\\';++sout;
+ AddEscape = TRUE;
+ }
+ else if (db->db_type==DT_POSTGRES && !UseLike)
+ {
+ (*sout) = '\\';++sout;
+ (*sout) = '\\';++sout;
+ }
+ else if (UseLike)
+ {
+ (*sout) = '\\';++sout; // ok:
+ (*sout) = '\\';++sout; // not ok: mysql
+ }
+ else if (DoubleBackSlashToDB)
+ {
+ if ((Index > 0) && (sin[-1] != '\\'))
+ {
+ (*sout) = '\\';++sout; // ok:
+ (*sout) = '\\';++sout; // not ok:
+ }
+ }
+ else
+ {
+ (*sout) = '\\';++sout;
+ }
+ break;
+ // end redone these special characters: mvh 20110105
+
+ case '\'':
+ (*sout) = '\'';++sout;
+ (*sout) = '\'';++sout;
+ break;
+
+ case '\"':
+ (*sout) = '\"';++sout;
+ break;
+
+ case 0: break;
+
+ default:
+ (*sout) = (*sin);
+ ++sout;
+ }
+ ++sin;
+ ++Index;
+ }
+ }
+
+ /* new code removes all trailing spaces (no check on begin: sout always start with ') */
+ sout--;
+ while (*sout == ' ') sout--;
+ sout++;
+
+ (*sout) = '\'';++sout;
+ (*sout) = '\0';++sout;
+
+ // redone these special characters: mvh 20110105
+ //20120701: seems this is not needed and highly complicates further processing
+ //if (AddEscape && db->db_type==DT_POSTGRES) strcpy(sout-1, " ESCAPE E'\\\\'");
+ //else if (AddEscape) strcpy(sout-1, " ESCAPE '\\'");
+ // end redone these special characters: mvh 20110105
+
+ delete s;
+ return ( TRUE );
+ }
+
+BOOL DICOM2SQLQuery (
+ char *s,
+ Database *db )
+ {
+ VR vr;
+ char *s1;
+
+ if(*s)
+ {
+ vr.Data = (void*)s;
+ vr.Length = strlen(s);
+ vr.Group = 0;
+ vr.Element = 0;
+ s1 = (char *)malloc(vr.Length*3 + 20); // must allow MakeSafeString in-place (!) ?E'[_]' ESCAPE '\'
+ MakeSafeString(&vr, s1, db);
+ strcpy(s, s1);
+ free(s1);
+ vr.Data = NULL;
+ vr.Length = 0;
+ }
+
+ return ( TRUE );
+ }
+
+BOOL
+BuildSearchString(Database *DB, DBENTRY *DBE, char *TableName, VR *vr, char *Search,
+ char *TempString, int maxlen)
+ {
+ char *s, *t, *search;
+ char ch;
+ char TempString1[64];
+ char TempString2[64];
+ UINT Index = DBEIndex(DBE, vr);
+ int len;
+ char escape[16];
+
+ if (UseEscapeStringConstants)
+ {
+ escape[0]='E';
+ escape[1]=0;
+ }
+ else
+ escape[0]=0;
+
+ search = Search;
+ if (*search=='?') search++;
+ if (*search=='E') search++;
+
+ if(vr->Length)
+ {
+ if(DBE[Index].DICOMType==DT_DATE)
+ {
+ if((s=strchr(search, '-')))
+ {
+ // Date Range
+ if((*(s+1))=='\'')
+ {
+ (*(s+1)) = '\0';
+ (*s) = '\'';
+
+ sprintf(TempString, "%s.%s >= %s%s", TableName, DBE[Index].SQLColumn,
+ escape, search);
+ }
+ else if((*(s-1))=='\'')
+ {
+ (*s) = '\'';
+ sprintf(TempString, "%s.%s <= %s%s", TableName, DBE[Index].SQLColumn,
+ escape, s);
+ }
+ else
+ {
+ // Bummer format is 'date-date'
+ ch = (*(s+1));
+ (*(s+1)) = '\0';
+ (*s) = '\'';
+
+ sprintf(TempString1, "%s.%s >= %s%s", TableName, DBE[Index].SQLColumn,
+ escape, search);
+
+ (*(s+1)) = ch;
+ sprintf(TempString2, "%s.%s <= %s%s", TableName, DBE[Index].SQLColumn,
+ escape, s);
+
+ sprintf(TempString, "%s and %s", TempString1, TempString2);
+ }
+ }
+ else
+ {
+ if (Search[0]=='?')
+ sprintf(TempString, "%s.%s LIKE %s%s", TableName, DBE[Index].SQLColumn,
+ escape, search);
+ else
+ sprintf(TempString, "%s.%s = %s%s", TableName, DBE[Index].SQLColumn,
+ escape, search);
+ }
+ }
+
+ // Multiple UID matching
+ else if(DBE[Index].DICOMType==DT_UI)
+ {
+ BOOL dbiii = (DB->db_type == DT_DBASEIII);
+
+ s = strchr(search, '\\');
+
+ if (s && !dbiii)
+ {
+ // Multiple UID matching sql server style with syntax: field in ('a','b','c')
+ // requires 3 characters per UID, e.g., 8192-512 fits about 110 UIDs
+ sprintf(TempString, "%s.%s in (", TableName, DBE[Index].SQLColumn);
+
+ t = search + 1; // skip '
+
+ while (s) // before each \ is an UID
+ {
+ *s = 0;
+ if (s[1] == '\\') // also process double backslash correctly
+ {
+ s++;
+ *s = 0;
+ }
+
+ len = strlen(TempString);
+ if (len<maxlen)
+ sprintf(TempString + len, "'%s',", t);
+
+ t = s + 1;
+ s = strchr(t, '\\');
+ }
+
+ // the last UID ends with a '
+ sprintf(TempString + strlen(TempString), "'%s)", t);
+ }
+
+ else if (s && dbiii)
+ {
+ // Multiple UID matching built-in dbaseIII style with | syntax: field in 'a|b|c'
+ // requires 1 character per UID, e.g., 8192-512 fit max about 115 UIDs
+ sprintf(TempString, "%s.%s in '", TableName, DBE[Index].SQLColumn);
+
+ t = search + 1; // skip '
+
+ while (s) // before each \ is an UID
+ {
+ *s = 0;
+ if (s[1] == '\\') // also process double backslash correctly
+ {
+ s++;
+ *s = 0;
+ }
+
+ len = strlen(TempString);
+ if (len<maxlen)
+ sprintf(TempString + len, "%s|", t);
+
+ t = s + 1;
+ s = strchr(t, '\\');
+ }
+
+ // the last UID ends with a '
+ sprintf(TempString + strlen(TempString), "%s", t);
+ }
+
+ else
+ {
+ if (Search[0]=='?')
+ sprintf(TempString, "%s.%s LIKE %s%s", TableName, DBE[Index].SQLColumn,
+ escape, search);
+ else
+ sprintf(TempString, "%s.%s = %s%s", TableName, DBE[Index].SQLColumn,
+ escape, search);
+ }
+ }
+ // DT_MSTR: PET matches 'PET', 'PET\CT', 'MR\PET\CT', and 'CT\PET'
+ // not implemented yet for DBASEIII, also wildcards give original query
+ else if((DBE[Index].DICOMType==DT_MSTR) && (DB->db_type != DT_DBASEIII))
+ {
+ if (Search[0]=='?')
+ sprintf(TempString, "%s.%s LIKE %s%s", TableName, DBE[Index].SQLColumn,
+ escape, search);
+ else
+ {
+ char *p = search + strlen(search) - 1;
+ const char *d;
+
+ // mysql and postgres require four backslashes
+ if (DoubleBackSlashToDB) d = "\\\\\\\\"; else d = "\\";
+
+ sprintf(TempString, "(%s.%s = %s%s or ", TableName, DBE[Index].SQLColumn,
+ escape, search);
+
+ *p = 0;
+ sprintf(TempString + strlen(TempString), "%s.%s LIKE %s'%s%s%%' or ", TableName, DBE[Index].SQLColumn,
+ escape, search+1, d);
+ sprintf(TempString + strlen(TempString), "%s.%s LIKE %s'%%%s%s%s%%' or ", TableName, DBE[Index].SQLColumn,
+ escape, d, search+1, d);
+ sprintf(TempString + strlen(TempString), "%s.%s LIKE %s'%%%s%s')", TableName, DBE[Index].SQLColumn,
+ escape, d, search+1);
+ *p = '\'';
+ }
+ }
+ else
+ {
+ if (Search[0]=='?')
+ sprintf(TempString, "%s.%s LIKE %s%s", TableName, DBE[Index].SQLColumn,
+ escape, search);
+ else
+ {
+ sprintf(TempString, "%s.%s = %s%s", TableName, DBE[Index].SQLColumn,
+ escape, search);
+
+ if (DBE[Index].DICOMType==DT_MSTR)
+ SystemDebug.printf("warning: query for this multi-valued item (%s) will not test individual values\n", DBE[Index].SQLColumn);
+ }
+
+ }
+
+ return (TRUE);
+ }
+ return ( FALSE );
+ }
+
+BOOL
+BuildColumnString(DBENTRY *DBE, char *TableName, VR *vr, char *TempString)
+ {
+ UINT Index = DBEIndex(DBE, vr);
+
+ strcpy(TempString, TableName);
+ strcat(TempString, ".");
+ strcat(TempString, DBE[Index].SQLColumn);
+ return ( TRUE );
+ }
+
+UINT32
+SQLRealSize(char *Str, SDWORD Max)
+ {
+ UNUSED_ARGUMENT(Str);
+#if 0
+ UINT32 Index = 0;
+ UINT32 RSize = 0;
+#endif
+
+ if(Max<0) return 0;
+ return Max;
+#if 0
+ while (Index < Max) // mvh 20051123
+ {
+ if(Str[Index]== 0 ) break;
+ if(Str[Index]!=' ') RSize = Index+1;
+ ++Index;
+ }
+ return ( RSize );
+#endif
+ }
+
+
+// compute items like 'Number of Patient Related Studies' and generate VR with the result
+// allowcount should only be set TRUE for databases that allows SELECT COUNT(1) statements
+static VR *ComputeField(DICOMDataObject *DDO, int group, int element, UINT16 mask=0xffff, BOOL allowcount=FALSE)
+ {
+ Array < DICOMDataObject * > ADDO;
+ char count[16];
+ const char *Level;
+ VR *vr, *vr2;
+ int save = DebugLevel, count1, count2, sources=0;
+ unsigned int i;
+ BOOL CountOnly = FALSE;
+
+ // level for VirtualQueries to other servers
+ Level = NULL;
+ if (element==0x1200) Level = "STUDY";
+ if (element==0x1202) Level = "SERIES";
+ if (element==0x1206) Level = "SERIES";
+ if (element==0x1204) Level = "IMAGE";
+ if (element==0x1208) Level = "IMAGE";
+ if (element==0x1209) Level = "IMAGE";
+
+ // make that a UNIQUE query will result the correct count
+ if (element==0x1200 && DDO->GetVR(0x0020, 0x000d)==NULL) DDO->Push(new VR(0x0020, 0x000d, 0, FALSE));
+ if (element==0x1202 && DDO->GetVR(0x0020, 0x000e)==NULL) DDO->Push(new VR(0x0020, 0x000e, 0, FALSE));
+ if (element==0x1206 && DDO->GetVR(0x0020, 0x000e)==NULL) DDO->Push(new VR(0x0020, 0x000e, 0, FALSE));
+ if (element==0x1204 && DDO->GetVR(0x0008, 0x0018)==NULL) DDO->Push(new VR(0x0008, 0x0018, 0, FALSE));
+ if (element==0x1208 && DDO->GetVR(0x0008, 0x0018)==NULL) DDO->Push(new VR(0x0008, 0x0018, 0, FALSE));
+ if (element==0x1209 && DDO->GetVR(0x0008, 0x0018)==NULL) DDO->Push(new VR(0x0008, 0x0018, 0, FALSE));
+
+ // query other virtualfor servers
+ for (i=0; i<10; i++)
+ if (mask & (1<<i))
+ sources += VirtualQuery(DDO, Level, i, &ADDO, NULL)!=0;
+ count1 = ADDO.GetSize();
+
+ if (allowcount && count1==0)
+ {
+ CountOnly = TRUE;
+ DDO->Push(new VR(0x9999, 0x9999, 0, FALSE)); // no need to locate duplicates: force CountOnly
+ sources = 0;
+ }
+
+ // query this server
+ DebugLevel=0;
+ if (element==0x1200) QueryOnStudy (DDO, &ADDO); // Number of Patient Related Studies
+ if (element==0x1202) QueryOnSeries (DDO, &ADDO); // Number of Patient Related Series
+ if (element==0x1206) QueryOnSeries (DDO, &ADDO); // Number of Study Related Series
+ if (element==0x1204) QueryOnImage (DDO, &ADDO); // Number of Patient Related Instances
+ if (element==0x1208) QueryOnImage (DDO, &ADDO); // Number of Study Related Instances
+ if (element==0x1209) QueryOnImage (DDO, &ADDO); // Number of Series Related Instances
+ DebugLevel=save;
+
+ // count number of servers accessed
+ count2 = ADDO.GetSize()-count1;
+ sources += count2!=0;
+
+ if (sources>1) // more than one source; data can be duplicated
+ RemoveQueryDuplicates(Level, &ADDO);
+
+ // create result VR
+ sprintf(count, "%d", ADDO.GetSize());
+ if (strlen(count)&1) strcat(count, " ");
+ vr = new VR( group, element, strlen(count), TRUE);
+ memcpy(vr->Data, count, strlen(count));
+
+ if (!CountOnly)
+ {
+ // free arrays
+ for (i=0; i<ADDO.GetSize(); i++)
+ while((vr2=ADDO.Get(i)->Pop())) delete vr2;
+
+ while (ADDO.GetSize())
+ {
+ delete ADDO.Get(0);
+ ADDO.RemoveAt(0);
+ }
+ }
+ else
+ while (ADDO.GetSize())
+ ADDO.RemoveAt(0);
+
+ return vr;
+ }
+
+BOOL QueryOnPatient (
+ DICOMDataObject *DDO,
+ Array < DICOMDataObject *> *ADDO)
+ {
+ UINT Index, CIndex, CCIndex;
+ UINT32 VRLength;
+ DICOMDataObject *RDDO;
+ Database DB;
+ char *SQLResultString;
+ Array < char * > SQLResult, SQLResultPatient;
+ Array < VR * > EMaskPatient, EMask;
+ Array < SQLLEN *> SQLResultLength;
+ Array < DBENTRY * > DBQPatient;
+ Array < DBENTRY * > DBQMaster;
+ DBENTRY *TempDBEPtr;
+ char *DBR;
+ SQLLEN *DBL;
+ VR *vr;
+ VR VRPatientName;
+ DBENTRY *DBEntryPatientName;
+ char SortOrder[128];
+ char *Sorting;
+ BOOL DoSort;
+ BOOL SendAE = FALSE;
+ char TempString [ 8192 ];
+ char SearchString [ 8192 ];
+ char ColumnString [ 4096 ];
+ char Tables [ 256 ];
+ char *Sort=NULL;
+ DICOMDataObject *qStudies = NULL;
+ DICOMDataObject *qSeries = NULL;
+ DICOMDataObject *qSops = NULL;
+ UINT16 mask = 0xffff;
+ BOOL CountOnly = FALSE;
+
+ SystemDebug.printf("Query On Patient\n");
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ DB.PrintLastError();
+ return ( FALSE ); // failed open
+ }
+
+ // First. Check that all the asked-for elements are actually in
+ // the Patient/Study database. If they are not, well, then we
+ // return FALSE.
+ DoSort = FALSE;
+ while ((vr = DDO->Pop()))
+ {
+ if(vr->Element == 0x0000)
+ {
+ delete vr;
+ continue; // discard length codes
+ }
+ if(vr->Group == 0x0002)
+ if(vr->Element == 0x0010)
+ {
+ delete vr;
+ continue; // discard transfer syntax
+ }
+ if(vr->Group == 0x0008)
+ if(vr->Element == 0x0052)
+ {
+ delete vr;
+ continue; // discard model level
+ }
+
+ if(vr->Group == 0x0008)
+ if(vr->Element == 0x0054)
+ {
+ SendAE = TRUE;
+ delete vr;
+ continue; // discard it (but send it)
+ }
+
+ if(vr->Group == 0x0020 && EnableComputedFields)
+ if(vr->Element == 0x1200)
+ {
+ qStudies = new DICOMDataObject;
+ delete vr;
+ continue; // discard 'Number of' items (but send them)
+ }
+
+ if(vr->Group == 0x0020 && EnableComputedFields)
+ if(vr->Element == 0x1202)
+ {
+ qSeries = new DICOMDataObject;
+ delete vr;
+ continue; // discard 'Number of' items (but send them)
+ }
+
+ if(vr->Group == 0x0020 && EnableComputedFields)
+ if(vr->Element == 0x1204)
+ {
+ qSops = new DICOMDataObject;
+ delete vr;
+ continue; // discard 'Number of' items (but send them)
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x0802)
+ {
+ mask = vr->GetUINT16();
+ delete vr;
+ continue; // discard it
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x0900)
+ {
+ mask = vr->GetUINT16();
+ delete vr;
+ continue; // discard it
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x9999)
+ {
+ CountOnly = TRUE;
+ delete vr;
+ continue; // discard it
+ }
+
+ if(!VerifyIsInDBE(vr, PatientDB, TempDBEPtr))
+ {
+ SystemDebug.printf("Queried item %4.4x %4.4x is not in the database\n",
+ vr->Group, vr->Element);
+ delete vr;
+ continue;
+
+ while(EMaskPatient.GetSize())
+ {
+ delete EMaskPatient.Get(0);
+ EMaskPatient.RemoveAt(0);
+ }
+ while(SQLResultPatient.GetSize())
+ {
+ delete SQLResultPatient.Get(0);
+ SQLResultPatient.RemoveAt(0);
+ }
+
+ return ( FALSE );
+ }
+ else
+ {
+ if(vr->Group == 0x0010)
+ if(vr->Element == 0x0010)
+ DoSort = TRUE;
+ SQLResultString = SetString(vr, NULL, 0);
+ DICOM2SQLQuery(SQLResultString, &DB);
+ SQLResultPatient.Add ( SQLResultString );
+ EMaskPatient.Add ( vr );
+ DBQPatient.Add ( TempDBEPtr );
+ }
+ }
+
+ // Prepare the query string.
+ // from EMasks, and SQLResults
+
+ SearchString[0] = '\0';
+ ColumnString[0] = '\0';
+
+ Index = 0;CIndex = 0;CCIndex = 0;
+ while ( Index < SQLResultPatient.GetSize() )
+ {
+ SQLResultString = SQLResultPatient.Get(Index);
+ if(BuildSearchString(&DB, PatientDB, PatientTableName, EMaskPatient.Get(Index),
+ SQLResultString, TempString, sizeof(TempString)-512))
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", sizeof(SearchString));
+ safestrcat(SearchString, TempString, sizeof(SearchString));
+ }
+ BuildColumnString(PatientDB, PatientTableName, EMaskPatient.Get(Index), TempString);
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, TempString);
+ EMask.Add(EMaskPatient.Get(Index));
+ DBQMaster.Add(DBQPatient.Get(Index));
+ ++Index;++CCIndex;
+ }
+
+ if (PatientQuerySortOrder[0])
+ {
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, PatientQuerySortOrder);
+ }
+
+ sprintf(Tables, "%s",
+ PatientTableName);
+
+ if (CountOnly)
+ sprintf(ColumnString, "COUNT(1)");
+
+ SystemDebug.printf("Issue Query on Columns: %s\n", ColumnString);
+ SystemDebug.printf("Values: %.1000s\n", SearchString);
+ SystemDebug.printf("Tables: %.1000s\n", Tables);
+
+ while(SQLResultPatient.GetSize())
+ {
+ delete SQLResultPatient.Get(0);
+ SQLResultPatient.RemoveAt(0);
+ }
+
+ VRPatientName.Group = 0x0010;
+ VRPatientName.Element = 0x0010;
+ DBEntryPatientName = FindDBE(&VRPatientName);
+ if(DBEntryPatientName)
+ {
+ sprintf(SortOrder, "%s.%s",
+ PatientTableName,
+ DBEntryPatientName->SQLColumn);
+ if(DoSort)
+ Sorting = SortOrder;
+ else
+ Sorting = NULL;
+ }
+ else
+ Sorting = NULL;
+
+ Sort = Sorting;
+ if (PatientQuerySortOrder[0]) Sort = PatientQuerySortOrder;
+
+ SystemDebug.printf("Sorting (%s) DoSort := %d\n", Sort, DoSort);
+
+ if(strlen(SearchString))
+ {
+ if (!DB.QueryDistinct ( Tables, ColumnString, SearchString, Sort) )
+ {
+ DB.PrintLastError();
+ return ( FALSE ); // failed query
+ }
+ }
+ else
+ if (!DB.QueryDistinct ( Tables, ColumnString, NULL, Sort))
+ {
+ DB.PrintLastError();
+ return ( FALSE ); // failed query
+ }
+
+ if (!CountOnly)
+ {
+ Index = 0;
+ while ( Index < CCIndex )
+ {
+ DBR = new char[255];
+ DBR[0] = 0; // in case a field is NULL it does not read
+ SQLResult.Add(DBR);
+ DBL = new SQLLEN;
+ SQLResultLength.Add(DBL);
+ if(!DB.BindField (Index+1, SQL_C_CHAR,
+ SQLResult.Get(Index), 255,
+ SQLResultLength.Get(Index)))
+ {
+ SystemDebug.printf("Column Number : %d\n", Index+1);
+ DB.PrintLastError();
+ while(SQLResult.GetSize())
+ {
+ delete SQLResult.Get(0);
+ SQLResult.RemoveAt(0);
+ }
+ while(SQLResultLength.GetSize())
+ {
+ delete SQLResultLength.Get(0);
+ SQLResultLength.RemoveAt(0);
+ }
+ return ( FALSE ); // failed to bind column
+ }
+ ++Index;
+ }
+ while (DB.NextRecord())
+ {
+ RDDO = new DICOMDataObject;
+ Index = 0;
+ while ( Index < CCIndex )
+ {
+ VRLength = SQLRealSize(SQLResult.Get(Index),
+ *SQLResultLength.Get(Index));
+ vr = ConstructVRFromSQL (
+ DBQMaster.Get(Index),
+ EMask.Get(Index)->Group,
+ EMask.Get(Index)->Element,
+ VRLength,
+ SQLResult.Get(Index));
+
+ if (qStudies)
+ qStudies->Push(ConstructVRFromSQL (DBQMaster.Get(Index), EMask.Get(Index)->Group, EMask.Get(Index)->Element, VRLength, SQLResult.Get(Index)));
+ if (qSeries)
+ qSeries->Push(ConstructVRFromSQL (DBQMaster.Get(Index), EMask.Get(Index)->Group, EMask.Get(Index)->Element, VRLength, SQLResult.Get(Index)));
+ if (qSops)
+ qSops->Push(ConstructVRFromSQL (DBQMaster.Get(Index), EMask.Get(Index)->Group, EMask.Get(Index)->Element, VRLength, SQLResult.Get(Index)));
+
+ RDDO->Push(vr);
+ ++Index;
+ }
+
+ if(SendAE)
+ RDDO->Push(ConstructAE());
+
+ if (qStudies)
+ {
+ RDDO->Push(ComputeField(qStudies, 0x0020, 0x1200, mask, DB.db_type!=DT_DBASEIII));
+ qStudies->Reset();
+ }
+
+ if (qSeries)
+ {
+ RDDO->Push(ComputeField(qSeries, 0x0020, 0x1202, mask, DB.db_type!=DT_DBASEIII));
+ qSeries->Reset();
+ }
+
+ if (qSops)
+ {
+ RDDO->Push(ComputeField(qSops, 0x0020, 0x1204, mask, DB.db_type!=DT_DBASEIII));
+ qSops->Reset();
+ }
+
+ ADDO->Add(RDDO);
+ }
+ }
+ else
+ {
+ char res[256];
+ SQLLEN len;
+ DB.BindField (1, SQL_C_CHAR, res, 255, &len);
+ DB.NextRecord();
+ DICOMDataObject *rd=NULL;
+ for (int i=0; i<atoi(res); i++) ADDO->Add(rd);
+ }
+
+ SystemDebug.printf("Records = %d\n", ADDO->GetSize());
+
+ while(SQLResult.GetSize())
+ {
+ delete SQLResult.Get(0);
+ SQLResult.RemoveAt(0);
+ }
+ while(SQLResultLength.GetSize())
+ {
+ delete SQLResultLength.Get(0);
+ SQLResultLength.RemoveAt(0);
+ }
+
+ /* LJ: Leak!! */
+ while(EMaskPatient.GetSize())
+ {
+ delete EMaskPatient.Get(0);
+ EMaskPatient.RemoveAt(0);
+ }
+
+ if (qStudies) delete qStudies;
+ if (qSeries) delete qSeries;
+ if (qSops) delete qSops;
+
+ return ( TRUE );
+ }
+
+BOOL QueryOnStudy (
+ DICOMDataObject *DDO,
+ Array < DICOMDataObject *> *ADDO)
+ {
+ UINT Index, CIndex, CCIndex;
+ UINT32 VRLength;
+ DICOMDataObject *RDDO;
+ Database DB;
+ char *SQLResultString;
+ Array < char * > SQLResult, SQLResultStudy, SQLResultPatient;
+ Array < DBENTRY * > DBQPatient, DBQStudy;
+ Array < DBENTRY * > DBQMaster;
+ Array < VR * > EMaskPatient, EMaskStudy, EMask;
+ Array < SQLLEN *> SQLResultLength;
+ DBENTRY *TempDBEPtr;
+ char *DBR;
+ SQLLEN *DBL;
+ VR *vr;
+ BOOL SendAE = FALSE;
+ char TempString [ 8192 ];
+ char SearchString [ 8192 ];
+ char ColumnString [ 4096 ];
+ char Tables [ 256 ];
+ VR VRPatientName;
+ DBENTRY *DBEntryPatientName;
+ char SortOrder[128];
+ char *Sorting;
+ BOOL DoSort;
+ char *Sort=NULL;
+ DICOMDataObject *qSeries = NULL;
+ DICOMDataObject *qSops = NULL;
+ UINT16 mask = 0xffff;
+ BOOL CountOnly = FALSE;
+
+ SystemDebug.printf("Query On Study\n");
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ DB.PrintLastError();
+ return ( FALSE ); // failed open
+ }
+
+ // First. Check that all the asked-for elements are actually in
+ // the Patient/Study database. If they are not, well, then we
+ // return FALSE.
+
+ DoSort = FALSE;
+
+ while ((vr = DDO->Pop()))
+ {
+ if(vr->Element == 0x0000)
+ {
+ delete vr;
+ continue; // discard length codes
+ }
+
+ if(vr->Group == 0x0002)
+ if(vr->Element == 0x0010)
+ {
+ delete vr;
+ continue; // discard transfer syntax
+ }
+ if(vr->Group == 0x0008)
+ if(vr->Element == 0x0052)
+ {
+ delete vr;
+ continue; // discard model level
+ }
+
+ if(vr->Group == 0x0008)
+ if(vr->Element == 0x0054)
+ {
+ SendAE = TRUE;
+ delete vr;
+ continue; // discard it (but send it)
+ }
+
+ if(vr->Group == 0x0020 && EnableComputedFields)
+ if(vr->Element == 0x1206)
+ {
+ qSeries = new DICOMDataObject;
+ delete vr;
+ continue; // discard 'Number of' items (but send them)
+ }
+
+ if(vr->Group == 0x0020 && EnableComputedFields)
+ if(vr->Element == 0x1208)
+ {
+ qSops = new DICOMDataObject;
+ delete vr;
+ continue; // discard 'Number of' items (but send them)
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x0802)
+ {
+ mask = vr->GetUINT16();
+ delete vr;
+ continue; // discard it
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x0900)
+ {
+ mask = vr->GetUINT16();
+ delete vr;
+ continue; // discard it
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x9999)
+ {
+ CountOnly = TRUE;
+ delete vr;
+ continue; // discard it
+ }
+
+ if(vr->Group == 0x0010)
+ if(vr->Element == 0x0010)
+ DoSort = TRUE;
+
+ if(VerifyIsInDBE(vr, StudyDB, TempDBEPtr))
+ {
+ SQLResultString = SetString(vr, NULL, 0);
+ DICOM2SQLQuery(SQLResultString, &DB);
+ SQLResultStudy.Add ( SQLResultString );
+ EMaskStudy.Add ( vr );
+ DBQStudy.Add ( TempDBEPtr );
+ }
+ else if(VerifyIsInDBE(vr, PatientDB, TempDBEPtr))
+ {
+ SQLResultString = SetString(vr, NULL, 0);
+ DICOM2SQLQuery(SQLResultString, &DB);
+ SQLResultPatient.Add ( SQLResultString );
+ EMaskPatient.Add ( vr );
+ DBQPatient.Add ( TempDBEPtr );
+ }
+ else
+ {
+ SystemDebug.printf("Queried item %4.4x %4.4x is not in the database\n",
+ vr->Group, vr->Element);
+ delete vr;
+ continue;
+ }
+ }
+
+ // Prepare the query string.
+ // from EMasks, and SQLResults
+
+ SearchString[0] = '\0';
+ ColumnString[0] = '\0';
+
+ Index = 0;CIndex = 0;CCIndex = 0;
+ while ( Index < SQLResultPatient.GetSize() )
+ {
+ SQLResultString = SQLResultPatient.Get(Index);
+ if(BuildSearchString(&DB, PatientDB, PatientTableName, EMaskPatient.Get(Index),
+ SQLResultString, TempString, sizeof(TempString)-512))
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", sizeof(SearchString));
+ safestrcat(SearchString, TempString, sizeof(SearchString));
+ }
+ BuildColumnString(PatientDB, PatientTableName, EMaskPatient.Get(Index), TempString);
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, TempString);
+ EMask.Add(EMaskPatient.Get(Index));
+ DBQMaster.Add(DBQPatient.Get(Index));
+ ++Index;++CCIndex;
+ }
+ Index = 0;
+ while ( Index < SQLResultStudy.GetSize() )
+ {
+ SQLResultString = SQLResultStudy.Get(Index);
+ if(BuildSearchString(&DB, StudyDB, StudyTableName, EMaskStudy.Get(Index),
+ SQLResultString, TempString, sizeof(TempString)-512))
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", sizeof(SearchString));
+ safestrcat(SearchString, TempString, sizeof(SearchString));
+ }
+ BuildColumnString(StudyDB, StudyTableName, EMaskStudy.Get(Index), TempString);
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, TempString);
+ EMask.Add(EMaskStudy.Get(Index));
+ DBQMaster.Add(DBQStudy.Get(Index));
+ ++Index;++CCIndex;
+ }
+
+ // Join only required when patient items asked (i.e., not for denormalized databases)
+ if (SQLResultPatient.GetSize())
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", sizeof(SearchString));
+ // Join Study into Patient
+ sprintf(TempString, "%s.%s = %s.%s",
+ StudyTableName, StudyDB [ LastDBE(StudyDB) ].SQLColumn,
+ PatientTableName, StudyDB [ LastDBE(StudyDB) ].SQLColumn);
+ safestrcat(SearchString, TempString, sizeof(SearchString));
+ }
+
+ if (StudyQuerySortOrder[0])
+ {
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, StudyQuerySortOrder);
+ }
+
+ if (SQLResultPatient.GetSize())
+ sprintf(Tables, "%s, %s",
+ StudyTableName, PatientTableName);
+ else
+ sprintf(Tables, "%s",
+ StudyTableName);
+
+ if (CountOnly)
+ sprintf(ColumnString, "COUNT(1)");
+
+ SystemDebug.printf("Issue Query on Columns: %s\n", ColumnString);
+ SystemDebug.printf("Values: %.1000s\n", SearchString);
+ SystemDebug.printf("Tables: %.1000s\n", Tables);
+
+ while(SQLResultStudy.GetSize())
+ {
+ delete SQLResultStudy.Get(0);
+ SQLResultStudy.RemoveAt(0);
+ }
+ while(SQLResultPatient.GetSize())
+ {
+ delete SQLResultPatient.Get(0);
+ SQLResultPatient.RemoveAt(0);
+ }
+
+ // Issue Query
+
+ VRPatientName.Group = 0x0010;
+ VRPatientName.Element = 0x0010;
+ DBEntryPatientName = FindDBE(&VRPatientName);
+ if(DBEntryPatientName)
+ {
+ // preferably sort on denormalized database entries
+ if (DBEIndex(StudyDB, &VRPatientName))
+ sprintf(SortOrder, "%s.%s",
+ StudyTableName,
+ DBEntryPatientName->SQLColumn);
+ else
+ sprintf(SortOrder, "%s.%s",
+ PatientTableName,
+ DBEntryPatientName->SQLColumn);
+ if(DoSort)
+ Sorting = SortOrder;
+ else
+ Sorting = NULL;
+ }
+ else
+ Sorting = NULL;
+
+ Sort = Sorting;
+ if (StudyQuerySortOrder[0]) Sort = StudyQuerySortOrder;
+
+ SystemDebug.printf("Sorting (%s) DoSort := %d\n", Sort, DoSort);
+
+ if(strlen(SearchString))
+ {
+ if (!DB.QueryDistinct ( Tables, ColumnString, SearchString, Sort) )
+ {
+ DB.PrintLastError();
+ return ( FALSE ); // failed query
+ }
+ }
+ else
+ if (!DB.QueryDistinct ( Tables, ColumnString, NULL, Sort))
+ {
+ DB.PrintLastError();
+ return ( FALSE ); // failed query
+ }
+
+ if (!CountOnly)
+ {
+ Index = 0;
+ while ( Index < CCIndex )
+ {
+ DBR = new char[255];
+ DBR[0] = 0; // in case a field is NULL it does not read
+ SQLResult.Add(DBR);
+ DBL = new SQLLEN;
+ SQLResultLength.Add(DBL);
+ if(!DB.BindField (Index+1, SQL_C_CHAR,
+ SQLResult.Get(Index), 255,
+ SQLResultLength.Get(Index)))
+ {
+ SystemDebug.printf("Column Number : %d\n", Index+1);
+ DB.PrintLastError();
+ while(SQLResult.GetSize())
+ {
+ delete SQLResult.Get(0);
+ SQLResult.RemoveAt(0);
+ }
+ while(SQLResultLength.GetSize())
+ {
+ delete SQLResultLength.Get(0);
+ SQLResultLength.RemoveAt(0);
+ }
+ return ( FALSE ); // failed to bind column
+ }
+ ++Index;
+ }
+ while (DB.NextRecord())
+ {
+ RDDO = new DICOMDataObject;
+ Index = 0;
+ while ( Index < CCIndex )
+ {
+ VRLength = SQLRealSize(SQLResult.Get(Index),
+ *SQLResultLength.Get(Index));
+ vr = ConstructVRFromSQL (
+ DBQMaster.Get(Index),
+ EMask.Get(Index)->Group,
+ EMask.Get(Index)->Element,
+ VRLength,
+ SQLResult.Get(Index));
+ RDDO->Push(vr);
+
+ if (qSeries)
+ qSeries->Push(ConstructVRFromSQL (DBQMaster.Get(Index), EMask.Get(Index)->Group, EMask.Get(Index)->Element, VRLength, SQLResult.Get(Index)));
+ if (qSops)
+ qSops->Push(ConstructVRFromSQL (DBQMaster.Get(Index), EMask.Get(Index)->Group, EMask.Get(Index)->Element, VRLength, SQLResult.Get(Index)));
+
+ ++Index;
+ }
+
+ if(SendAE)
+ RDDO->Push(ConstructAE());
+
+ if (qSeries)
+ {
+ RDDO->Push(ComputeField(qSeries, 0x0020, 0x1206, mask, DB.db_type!=DT_DBASEIII));
+ qSeries->Reset();
+ }
+
+ if (qSops)
+ {
+ RDDO->Push(ComputeField(qSops, 0x0020, 0x1208, mask, DB.db_type!=DT_DBASEIII));
+ qSops->Reset();
+ }
+
+ ADDO->Add(RDDO);
+ }
+ }
+ else
+ {
+ char res[256];
+ SQLLEN len;
+ DB.BindField (1, SQL_C_CHAR, res, 255, &len);
+ DB.NextRecord();
+ DICOMDataObject *rd=NULL;
+ for (int i=0; i<atoi(res); i++) ADDO->Add(rd);
+ }
+
+ SystemDebug.printf("Records = %d\n", ADDO->GetSize());
+
+ while(SQLResult.GetSize())
+ {
+ delete SQLResult.Get(0);
+ SQLResult.RemoveAt(0);
+ }
+ while(SQLResultLength.GetSize())
+ {
+ delete SQLResultLength.Get(0);
+ SQLResultLength.RemoveAt(0);
+ }
+
+ /* LJ: Leak!! */
+ while(EMaskStudy.GetSize())
+ {
+ delete EMaskStudy.Get(0);
+ EMaskStudy.RemoveAt(0);
+ }
+ while(EMaskPatient.GetSize())
+ {
+ delete EMaskPatient.Get(0);
+ EMaskPatient.RemoveAt(0);
+ }
+
+ if (qSeries) delete qSeries;
+ if (qSops) delete qSops;
+
+ return ( TRUE );
+ }
+
+BOOL QueryOnSeries (
+ DICOMDataObject *DDO,
+ Array < DICOMDataObject *> *ADDO)
+ {
+ UINT Index, CIndex, CCIndex;
+ UINT32 VRLength;
+ DICOMDataObject *RDDO;
+ Database DB;
+ char *SQLResultString;
+ Array < char * > SQLResult, SQLResultStudy, SQLResultPatient,
+ SQLResultSeries;
+ Array < DBENTRY * > DBQPatient, DBQStudy, DBQSeries;
+ Array < DBENTRY * > DBQMaster;
+ Array < VR * > EMaskPatient, EMaskStudy, EMaskSeries, EMask;
+ Array < SQLLEN *> SQLResultLength;
+ DBENTRY *TempDBEPtr;
+ char *DBR;
+ SQLLEN *DBL;
+ VR *vr;
+ BOOL SendAE = FALSE;
+ char TempString [ 8192 ];
+ char SearchString [ 8192 ];
+ char ColumnString [ 4096 ];
+ char Tables [ 256 ];
+ char *Sort=NULL;
+ DICOMDataObject *qSops = NULL;
+ UINT16 mask = 0xffff;
+ BOOL CountOnly = FALSE;
+
+ SystemDebug.printf("Query On Series\n");
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ DB.PrintLastError();
+ return ( FALSE ); // failed open
+ }
+
+ // First. Check that all the asked-for elements are actually in
+ // the Patient/Study database. If they are not, well, then we
+ // return FALSE.
+
+ while ((vr = DDO->Pop()))
+ {
+ if(vr->Element == 0x0000)
+ {
+ delete vr;
+ continue; // discard length codes
+ }
+
+ if(vr->Group == 0x0002)
+ if(vr->Element == 0x0010)
+ {
+ delete vr;
+ continue; // discard transfer syntax
+ }
+ if(vr->Group == 0x0008)
+ if(vr->Element == 0x0052)
+ {
+ delete vr;
+ continue; // discard model level
+ }
+
+ if(vr->Group == 0x0008)
+ if(vr->Element == 0x0054)
+ {
+ SendAE = TRUE;
+ delete vr;
+ continue; // discard it (but send it)
+ }
+
+ if(vr->Group == 0x0020 && EnableComputedFields)
+ if(vr->Element == 0x1209)
+ {
+ qSops = new DICOMDataObject;
+ delete vr;
+ continue; // discard 'Number of' items (but send them)
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x0802)
+ {
+ mask = vr->GetUINT16();
+ delete vr;
+ continue; // discard it
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x0900)
+ {
+ mask = vr->GetUINT16();
+ delete vr;
+ continue; // discard it
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x9999)
+ {
+ CountOnly = TRUE;
+ delete vr;
+ continue; // discard it
+ }
+
+ if(VerifyIsInDBE(vr, StudyDB, TempDBEPtr))
+ {
+ SQLResultString = SetString(vr, NULL, 0);
+ DICOM2SQLQuery(SQLResultString, &DB);
+ SQLResultStudy.Add ( SQLResultString );
+ EMaskStudy.Add ( vr );
+ DBQStudy.Add ( TempDBEPtr );
+ }
+ else if(VerifyIsInDBE(vr, PatientDB, TempDBEPtr))
+ {
+ SQLResultString = SetString(vr, NULL, 0);
+ DICOM2SQLQuery(SQLResultString, &DB);
+ SQLResultPatient.Add ( SQLResultString );
+ EMaskPatient.Add ( vr );
+ DBQPatient.Add ( TempDBEPtr );
+ }
+ else if(VerifyIsInDBE(vr, SeriesDB, TempDBEPtr))
+ {
+ SQLResultString = SetString(vr, NULL, 0);
+ DICOM2SQLQuery(SQLResultString, &DB);
+ SQLResultSeries.Add ( SQLResultString );
+ EMaskSeries.Add ( vr );
+ DBQSeries.Add ( TempDBEPtr );
+ }
+ else
+ {
+ SystemDebug.printf("Queried item %4.4x %4.4x is not in the database\n",
+ vr->Group, vr->Element);
+ delete vr;
+ continue;
+ }
+ }
+
+ // Prepare the query string.
+ // from EMasks, and SQLResults
+
+ SearchString[0] = '\0';
+ ColumnString[0] = '\0';
+
+ Index = 0;CIndex = 0;CCIndex = 0;
+ while ( Index < SQLResultSeries.GetSize() )
+ {
+ SQLResultString = SQLResultSeries.Get(Index);
+ if(BuildSearchString(&DB, SeriesDB, SeriesTableName, EMaskSeries.Get(Index),
+ SQLResultString, TempString, sizeof(TempString)-512))
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", sizeof(SearchString));
+ safestrcat(SearchString, TempString, sizeof(SearchString));
+ }
+ BuildColumnString(SeriesDB, SeriesTableName, EMaskSeries.Get(Index), TempString);
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, TempString);
+ EMask.Add(EMaskSeries.Get(Index));
+ DBQMaster.Add(DBQSeries.Get(Index));
+ ++Index;++CCIndex;
+ }
+ Index = 0;
+ while ( Index < SQLResultPatient.GetSize() )
+ {
+ SQLResultString = SQLResultPatient.Get(Index);
+ if(BuildSearchString(&DB, PatientDB, PatientTableName, EMaskPatient.Get(Index),
+ SQLResultString, TempString, sizeof(TempString)-512))
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", sizeof(SearchString));
+ safestrcat(SearchString, TempString, sizeof(SearchString));
+ }
+ BuildColumnString(PatientDB, PatientTableName, EMaskPatient.Get(Index), TempString);
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, TempString);
+ EMask.Add(EMaskPatient.Get(Index));
+ DBQMaster.Add(DBQPatient.Get(Index));
+ ++Index;++CCIndex;
+ }
+ Index = 0;
+ while ( Index < SQLResultStudy.GetSize() )
+ {
+ SQLResultString = SQLResultStudy.Get(Index);
+ if(BuildSearchString(&DB, StudyDB, StudyTableName, EMaskStudy.Get(Index),
+ SQLResultString, TempString, sizeof(TempString)-512))
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", sizeof(SearchString));
+ safestrcat(SearchString, TempString, sizeof(SearchString));
+ }
+ BuildColumnString(StudyDB, StudyTableName, EMaskStudy.Get(Index), TempString);
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, TempString);
+ EMask.Add(EMaskStudy.Get(Index));
+ DBQMaster.Add(DBQStudy.Get(Index));
+ ++Index;++CCIndex;
+ }
+
+ if (SQLResultPatient.GetSize())
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", sizeof(SearchString));
+ // Join Study into Patient
+ sprintf(TempString, "%s.%s = %s.%s",
+ StudyTableName, StudyDB [ LastDBE(StudyDB) ].SQLColumn,
+ PatientTableName, StudyDB [ LastDBE(StudyDB) ].SQLColumn);
+ safestrcat(SearchString, TempString, sizeof(SearchString));
+ }
+
+ if (SQLResultStudy.GetSize() || SQLResultPatient.GetSize())
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", sizeof(SearchString));
+ // Join Series into Study
+ sprintf(TempString, "%s.%s = %s.%s",
+ SeriesTableName, SeriesDB [ LastDBE(SeriesDB) ].SQLColumn,
+ StudyTableName, SeriesDB [ LastDBE(SeriesDB) ].SQLColumn);
+ safestrcat(SearchString, TempString, sizeof(SearchString));
+ }
+
+ if (SeriesQuerySortOrder[0])
+ {
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, SeriesQuerySortOrder);
+ }
+
+ if (SQLResultPatient.GetSize())
+ sprintf(Tables, "%s, %s, %s",
+ SeriesTableName, StudyTableName, PatientTableName);
+ else if (SQLResultStudy.GetSize())
+ sprintf(Tables, "%s, %s",
+ SeriesTableName, StudyTableName);
+ else
+ sprintf(Tables, "%s",
+ SeriesTableName);
+
+ if (CountOnly)
+ sprintf(ColumnString, "COUNT(1)");
+
+ SystemDebug.printf("Issue Query on Columns: %s\n", ColumnString);
+ SystemDebug.printf("Values: %.1000s\n", SearchString);
+ SystemDebug.printf("Tables: %.1000s\n", Tables);
+
+ while(SQLResultSeries.GetSize())
+ {
+ delete SQLResultSeries.Get(0);
+ SQLResultSeries.RemoveAt(0);
+ }
+ while(SQLResultStudy.GetSize())
+ {
+ delete SQLResultStudy.Get(0);
+ SQLResultStudy.RemoveAt(0);
+ }
+ while(SQLResultPatient.GetSize())
+ {
+ delete SQLResultPatient.Get(0);
+ SQLResultPatient.RemoveAt(0);
+ }
+
+ // Issue Query
+
+ if (SeriesQuerySortOrder[0]) Sort = SeriesQuerySortOrder;
+
+ if(strlen(SearchString))
+ {
+ if (!DB.QueryDistinct ( Tables, ColumnString, SearchString, Sort) )
+ {
+ DB.PrintLastError();
+ return ( FALSE ); // failed query
+ }
+ }
+ else
+ if (!DB.QueryDistinct ( Tables, ColumnString, NULL, Sort))
+ {
+ DB.PrintLastError();
+ return ( FALSE ); // failed query
+ }
+
+ if (!CountOnly)
+ {
+ Index = 0;
+ while ( Index < CCIndex )
+ {
+ DBR = new char[255];
+ DBR[0] = 0; // in case a field is NULL it does not read
+ SQLResult.Add(DBR);
+ DBL = new SQLLEN;
+ SQLResultLength.Add(DBL);
+ if(!DB.BindField (Index+1, SQL_C_CHAR,
+ SQLResult.Get(Index), 255,
+ SQLResultLength.Get(Index)))
+ {
+ SystemDebug.printf("***Column Number : %d\n", Index+1);
+ DB.PrintLastError();
+ while(SQLResult.GetSize())
+ {
+ delete SQLResult.Get(0);
+ SQLResult.RemoveAt(0);
+ }
+ while(SQLResultLength.GetSize())
+ {
+ delete SQLResultLength.Get(0);
+ SQLResultLength.RemoveAt(0);
+ }
+ return ( FALSE ); // failed to bind column
+ }
+ ++Index;
+ }
+ while (DB.NextRecord())
+ {
+ RDDO = new DICOMDataObject;
+ Index = 0;
+ while ( Index < CCIndex )
+ {
+ VRLength = SQLRealSize(SQLResult.Get(Index),
+ *SQLResultLength.Get(Index));
+ vr = ConstructVRFromSQL (
+ DBQMaster.Get(Index),
+ EMask.Get(Index)->Group,
+ EMask.Get(Index)->Element,
+ VRLength,
+ SQLResult.Get(Index));
+ RDDO->Push(vr);
+
+ if (qSops)
+ qSops->Push(ConstructVRFromSQL (DBQMaster.Get(Index), EMask.Get(Index)->Group, EMask.Get(Index)->Element, VRLength, SQLResult.Get(Index)));
+
+ ++Index;
+ }
+
+ if(SendAE)
+ RDDO->Push(ConstructAE());
+
+ if (qSops)
+ {
+ RDDO->Push(ComputeField(qSops, 0x0020, 0x1209, mask, DB.db_type!=DT_DBASEIII));
+ qSops->Reset();
+ }
+
+ ADDO->Add(RDDO);
+ }
+ }
+ else
+ {
+ char res[256];
+ SQLLEN len;
+ DB.BindField (1, SQL_C_CHAR, res, 255, &len);
+ DB.NextRecord();
+ DICOMDataObject *rd=NULL;
+ for (int i=0; i<atoi(res); i++) ADDO->Add(rd);
+ }
+
+ SystemDebug.printf("Records = %d\n", ADDO->GetSize());
+
+ while(SQLResult.GetSize())
+ {
+ delete SQLResult.Get(0);
+ SQLResult.RemoveAt(0);
+ }
+ while(SQLResultLength.GetSize())
+ {
+ delete SQLResultLength.Get(0);
+ SQLResultLength.RemoveAt(0);
+ }
+
+ /* LJ: Leak!! */
+ while(EMaskSeries.GetSize())
+ {
+ delete EMaskSeries.Get(0);
+ EMaskSeries.RemoveAt(0);
+ }
+ while(EMaskStudy.GetSize())
+ {
+ delete EMaskStudy.Get(0);
+ EMaskStudy.RemoveAt(0);
+ }
+ while(EMaskPatient.GetSize())
+ {
+ delete EMaskPatient.Get(0);
+ EMaskPatient.RemoveAt(0);
+ }
+
+ if (qSops) delete qSops;
+
+ return ( TRUE );
+
+ }
+
+#define MAXLENGTH (MAXQUERYLENGTH-10000)
+
+BOOL QueryOnImage (
+ DICOMDataObject *DDO,
+ Array < DICOMDataObject *> *ADDO)
+ {
+ UINT Index, CIndex, CCIndex;
+ UINT32 VRLength;
+ DICOMDataObject *RDDO;
+ Database DB;
+ char *SQLResultString;
+ Array < char * > SQLResult, SQLResultStudy, SQLResultPatient,
+ SQLResultSeries, SQLResultImage;
+ Array < DBENTRY * > DBQPatient, DBQStudy, DBQSeries, DBQImage;
+ Array < DBENTRY * > DBQMaster;
+ Array < VR * > EMaskPatient, EMaskStudy, EMaskSeries, EMaskImage, EMask;
+ Array < SQLLEN *> SQLResultLength;
+ DBENTRY *TempDBEPtr;
+ char *DBR;
+ SQLLEN *DBL;
+ VR *vr;
+ BOOL SendAE = FALSE, SendObjectFile = FALSE;
+ char *TempString;
+ char *SearchString;
+ char ColumnString [ 4096 ];
+ char Tables [ 256 ];
+ char *Sort=NULL;
+ UINT16 mask = 0xffff;
+ BOOL CountOnly = FALSE;
+
+// Analysis of length of strings:
+//
+// let us assume max #fields to query is 100 (>> total fields in DB)
+// max size columnstring is about 100 x (maxfieldname+2) = 1200 -> no problem
+// max size tempstring is length of a single field = 'value' string
+// max size searchstring is total (length of field = 'value' strings + 5)
+// + 172 (for joins)
+// it is no problem here to malloc these strings at really large size
+// values add up to max 1000 if no multiple used, fields = add up to max 3000
+// if multiple is used at one level (reasonable), max 67 per entry
+// Assume max slices is 4000 for 1 series, max searchstring:
+// 4000 + 4000*67 = 272000, max tempstring: 30 + 4000*67 = 268030,
+// set lets say 300 kb each. This value is defined in MAXLENGTH
+
+// Most likely the max at lower query levels are much smaller, and 8 kb
+// will be fine at these levels (allows multiplicity of 59)
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ DB.PrintLastError();
+ return ( FALSE ); // failed open
+ }
+
+ TempString = NULL;
+ SearchString = NULL;
+
+ TempString = (char *)malloc(MAXLENGTH+1);
+ SearchString = (char *)malloc(MAXLENGTH+1);
+
+ if (TempString==NULL || SearchString==NULL)
+ {
+ free(TempString);
+ free(SearchString);
+ return FALSE;
+ }
+
+ SystemDebug.printf("Query On Image\n");
+
+ while ((vr = DDO->Pop()))
+ {
+ if(vr->Element == 0x0000)
+ {
+ delete vr;
+ continue; // discard length codes
+ }
+ if(vr->Group == 0x0002)
+ if(vr->Element == 0x0010)
+ {
+ delete vr;
+ continue; // discard transfer syntax
+ }
+ if(vr->Group == 0x0008)
+ if(vr->Element == 0x0052)
+ {
+ delete vr;
+ continue; // discard model level
+ }
+ if(vr->Group == 0x0008)
+ if(vr->Element == 0x0054)
+ {
+ SendAE = TRUE;
+ delete vr;
+ continue; // discard it (but send it)
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x0800)
+ {
+ SendObjectFile = TRUE;
+ delete vr;
+ continue; // discard it (but send it)
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x0801)
+ {
+ SendObjectFile = TRUE;
+ delete vr;
+ continue; // discard it (but send it)
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x0802)
+ {
+ mask = vr->GetUINT16();
+ delete vr;
+ continue; // discard it
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x0900)
+ {
+ mask = vr->GetUINT16();
+ delete vr;
+ continue; // discard it
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x9999)
+ {
+ CountOnly = TRUE;
+ delete vr;
+ continue; // discard it
+ }
+
+ if(VerifyIsInDBE(vr, StudyDB, TempDBEPtr))
+ {
+ SQLResultString = SetString(vr, NULL, 0);
+ DICOM2SQLQuery(SQLResultString, &DB);
+ SQLResultStudy.Add ( SQLResultString );
+ EMaskStudy.Add ( vr );
+ DBQStudy.Add ( TempDBEPtr );
+ }
+ else if(VerifyIsInDBE(vr, PatientDB, TempDBEPtr))
+ {
+ SQLResultString = SetString(vr, NULL, 0);
+ DICOM2SQLQuery(SQLResultString, &DB);
+ SQLResultPatient.Add ( SQLResultString );
+ EMaskPatient.Add ( vr );
+ DBQPatient.Add ( TempDBEPtr );
+ }
+ else if(VerifyIsInDBE(vr, SeriesDB, TempDBEPtr))
+ {
+ SQLResultString = SetString(vr, NULL, 0);
+ DICOM2SQLQuery(SQLResultString, &DB);
+ SQLResultSeries.Add ( SQLResultString );
+ EMaskSeries.Add ( vr );
+ DBQSeries.Add ( TempDBEPtr );
+ }
+ else if(VerifyIsInDBE(vr, ImageDB, TempDBEPtr))
+ {
+ SQLResultString = SetString(vr, NULL, 0);
+ DICOM2SQLQuery(SQLResultString, &DB);
+ SQLResultImage.Add ( SQLResultString );
+ EMaskImage.Add ( vr );
+ DBQImage.Add(TempDBEPtr);
+ }
+ else
+ {
+ SystemDebug.printf("Queried item %4.4x %4.4x is not in the database\n",
+ vr->Group, vr->Element);
+ delete vr;
+ continue;
+ }
+ }
+
+ // Prepare the query string.
+ // from EMasks, and SQLResults
+
+ SearchString[0] = '\0';
+ ColumnString[0] = '\0';
+
+ Index = 0;CIndex = 0;CCIndex = 0;
+ while ( Index < SQLResultImage.GetSize() )
+ {
+ SQLResultString = SQLResultImage.Get(Index);
+ if(BuildSearchString(&DB, ImageDB, ImageTableName, EMaskImage.Get(Index),
+ SQLResultString, TempString, MAXLENGTH-4000))
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", MAXLENGTH);
+ safestrcat(SearchString, TempString, MAXLENGTH);
+ }
+ BuildColumnString(ImageDB, ImageTableName, EMaskImage.Get(Index), TempString);
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, TempString);
+ EMask.Add(EMaskImage.Get(Index));
+ DBQMaster.Add(DBQImage.Get(Index));
+ ++Index;++CCIndex;
+ }
+ Index = 0;
+ while ( Index < SQLResultSeries.GetSize() )
+ {
+ SQLResultString = SQLResultSeries.Get(Index);
+ if(BuildSearchString(&DB, SeriesDB, SeriesTableName, EMaskSeries.Get(Index),
+ SQLResultString, TempString, MAXLENGTH-4000))
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", MAXLENGTH);
+ safestrcat(SearchString, TempString, MAXLENGTH);
+ }
+ BuildColumnString(SeriesDB, SeriesTableName, EMaskSeries.Get(Index), TempString);
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, TempString);
+ EMask.Add(EMaskSeries.Get(Index));
+ DBQMaster.Add(DBQSeries.Get(Index));
+ ++Index;++CCIndex;
+ }
+ Index = 0;
+ while ( Index < SQLResultPatient.GetSize() )
+ {
+ SQLResultString = SQLResultPatient.Get(Index);
+ if(BuildSearchString(&DB, PatientDB, PatientTableName, EMaskPatient.Get(Index),
+ SQLResultString, TempString, MAXLENGTH-4000))
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", MAXLENGTH);
+ safestrcat(SearchString, TempString, MAXLENGTH);
+ }
+ BuildColumnString(PatientDB, PatientTableName, EMaskPatient.Get(Index), TempString);
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, TempString);
+ EMask.Add(EMaskPatient.Get(Index));
+ DBQMaster.Add(DBQPatient.Get(Index));
+ ++Index;++CCIndex;
+ }
+ Index = 0;
+ while ( Index < SQLResultStudy.GetSize() )
+ {
+ SQLResultString = SQLResultStudy.Get(Index);
+ if(BuildSearchString(&DB, StudyDB, StudyTableName, EMaskStudy.Get(Index),
+ SQLResultString, TempString, MAXLENGTH-4000))
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", MAXLENGTH);
+ safestrcat(SearchString, TempString, MAXLENGTH);
+ }
+ BuildColumnString(StudyDB, StudyTableName, EMaskStudy.Get(Index), TempString);
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, TempString);
+ EMask.Add(EMaskStudy.Get(Index));
+ DBQMaster.Add(DBQStudy.Get(Index));
+ ++Index;++CCIndex;
+ }
+
+ if (SQLResultPatient.GetSize())
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", MAXLENGTH);
+ // Join Study into Patient
+ sprintf(TempString, "%s.%s = %s.%s",
+ StudyTableName, StudyDB [ LastDBE(StudyDB) ].SQLColumn,
+ PatientTableName, StudyDB [ LastDBE(StudyDB) ].SQLColumn);
+ safestrcat(SearchString, TempString, MAXLENGTH);
+ }
+
+ if (SQLResultStudy.GetSize() || SQLResultPatient.GetSize())
+ {
+ // Join Series into Study
+ if (CIndex++)
+ safestrcat(SearchString, " and ", MAXLENGTH);
+ sprintf(TempString, "%s.%s = %s.%s",
+ SeriesTableName, SeriesDB [ LastDBE(SeriesDB) ].SQLColumn,
+ StudyTableName, SeriesDB [ LastDBE(SeriesDB) ].SQLColumn);
+ safestrcat(SearchString, TempString, MAXLENGTH);
+ }
+
+ if (SQLResultSeries.GetSize() || SQLResultStudy.GetSize() || SQLResultPatient.GetSize())
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", MAXLENGTH);
+ // Join Image into Series
+ sprintf(TempString, "%s.%s = %s.%s",
+ ImageTableName, ImageDB [ LastDBE(ImageDB) ].SQLColumn,
+ SeriesTableName, ImageDB [ LastDBE(ImageDB) ].SQLColumn);
+ safestrcat(SearchString, TempString, MAXLENGTH);
+ }
+
+ if (SendObjectFile)
+ {
+ strcat(ColumnString, ",");
+ strcat(ColumnString, ImageTableName);
+ strcat(ColumnString, ".ObjectFile");
+ strcat(ColumnString, ",");
+ strcat(ColumnString, ImageTableName);
+ strcat(ColumnString, ".DeviceName");
+ }
+
+ if (ImageQuerySortOrder[0])
+ {
+ if(CCIndex)
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, ImageQuerySortOrder);
+ }
+
+ if (SQLResultPatient.GetSize())
+ sprintf(Tables, "%s, %s, %s, %s",
+ ImageTableName, SeriesTableName, StudyTableName, PatientTableName);
+ else if (SQLResultStudy.GetSize())
+ sprintf(Tables, "%s, %s, %s",
+ ImageTableName, SeriesTableName, StudyTableName);
+ else if (SQLResultSeries.GetSize())
+ sprintf(Tables, "%s, %s",
+ ImageTableName, SeriesTableName);
+ else
+ sprintf(Tables, "%s",
+ ImageTableName);
+
+ if (CountOnly)
+ sprintf(ColumnString, "COUNT(1)");
+
+ SystemDebug.printf("Issue Query on Columns: %s\n", ColumnString);
+ SystemDebug.printf("Values: %.1000s\n", SearchString);
+ SystemDebug.printf("Tables: %.1000s\n", Tables);
+
+ while(SQLResultImage.GetSize())
+ {
+ delete SQLResultImage.Get(0);
+ SQLResultImage.RemoveAt(0);
+ }
+ while(SQLResultSeries.GetSize())
+ {
+ delete SQLResultSeries.Get(0);
+ SQLResultSeries.RemoveAt(0);
+ }
+ while(SQLResultStudy.GetSize())
+ {
+ delete SQLResultStudy.Get(0);
+ SQLResultStudy.RemoveAt(0);
+ }
+ while(SQLResultPatient.GetSize())
+ {
+ delete SQLResultPatient.Get(0);
+ SQLResultPatient.RemoveAt(0);
+ }
+
+ // Issue Query
+ if (ImageQuerySortOrder[0]) Sort = ImageQuerySortOrder;
+
+ if(strlen(SearchString))
+ {
+ if (!DB.QueryDistinct ( Tables, ColumnString, SearchString, Sort) )
+ {
+ DB.PrintLastError();
+ free(TempString);
+ free(SearchString);
+ return ( FALSE ); // failed query
+ }
+ }
+ else
+ if (!DB.QueryDistinct ( Tables, ColumnString, NULL, Sort))
+ {
+ DB.PrintLastError();
+ free(TempString);
+ free(SearchString);
+ return ( FALSE ); // failed query
+ }
+
+ if (!CountOnly)
+ {
+ Index = 0;
+ while ( Index < CCIndex )
+ {
+ DBR = new char[255];
+ DBR[0] = 0; // in case a field is NULL it does not read
+ SQLResult.Add(DBR);
+ DBL = new SQLLEN;
+ SQLResultLength.Add(DBL);
+ if(!DB.BindField (Index+1, SQL_C_CHAR,
+ SQLResult.Get(Index), 255,
+ SQLResultLength.Get(Index)))
+ {
+ SystemDebug.printf("Column Number : %d\n", Index+1);
+ DB.PrintLastError();
+ while(SQLResult.GetSize())
+ {
+ delete SQLResult.Get(0);
+ SQLResult.RemoveAt(0);
+ }
+ while(SQLResultLength.GetSize())
+ {
+ delete SQLResultLength.Get(0);
+ SQLResultLength.RemoveAt(0);
+ }
+ free(TempString);
+ free(SearchString);
+ return ( FALSE ); // failed to bind column
+ }
+ ++Index;
+ }
+
+ if (SendObjectFile) // need two more columns
+ for (int i=0; i<2; i++)
+ {
+ DBR = new char[255];
+ DBR[0] = 0; // in case a field is NULL it does not read
+ SQLResult.Add(DBR);
+ DBL = new SQLLEN;
+ SQLResultLength.Add(DBL);
+ if(!DB.BindField (Index+1, SQL_C_CHAR,
+ SQLResult.Get(Index), 255,
+ SQLResultLength.Get(Index)))
+ {
+ SystemDebug.printf("Column Number : %d\n", Index+1);
+ DB.PrintLastError();
+ while(SQLResult.GetSize())
+ {
+ delete SQLResult.Get(0);
+ SQLResult.RemoveAt(0);
+ }
+ while(SQLResultLength.GetSize())
+ {
+ delete SQLResultLength.Get(0);
+ SQLResultLength.RemoveAt(0);
+ }
+ free(TempString);
+ free(SearchString);
+ return ( FALSE ); // failed to bind column
+ }
+ ++Index;
+ }
+
+ while (DB.NextRecord())
+ {
+ RDDO = new DICOMDataObject;
+ Index = 0;
+ while ( Index < CCIndex )
+ {
+ VRLength = SQLRealSize(SQLResult.Get(Index),
+ *SQLResultLength.Get(Index));
+ vr = ConstructVRFromSQL (
+ DBQMaster.Get(Index),
+ EMask.Get(Index)->Group,
+ EMask.Get(Index)->Element,
+ VRLength,
+ SQLResult.Get(Index));
+ RDDO->Push(vr);
+ ++Index;
+ }
+
+ if ( SendObjectFile ) // filename in 0x9999,0x0800; devicename in 0x9999,0x801
+ {
+ VRLength = SQLRealSize(SQLResult.Get(Index),
+ *SQLResultLength.Get(Index));
+ vr = ConstructVRFromSQL (
+ NULL,
+ 0x9999,
+ 0x800,
+ VRLength,
+ SQLResult.Get(Index));
+ RDDO->Push(vr);
+ ++Index;
+
+ VRLength = SQLRealSize(SQLResult.Get(Index),
+ *SQLResultLength.Get(Index));
+ vr = ConstructVRFromSQL (
+ NULL,
+ 0x9999,
+ 0x801,
+ VRLength,
+ SQLResult.Get(Index));
+ RDDO->Push(vr);
+ ++Index;
+ }
+
+ if(SendAE)
+ RDDO->Push(ConstructAE());
+
+ ADDO->Add(RDDO);
+ }
+ }
+ else
+ {
+ char res[256];
+ SQLLEN len;
+ DB.BindField (1, SQL_C_CHAR, res, 255, &len);
+ DB.NextRecord();
+ DICOMDataObject *rd=NULL;
+ for (int i=0; i<atoi(res); i++) ADDO->Add(rd);
+ }
+
+ SystemDebug.printf("Records = %d\n", ADDO->GetSize());
+
+ while(SQLResult.GetSize())
+ {
+ delete SQLResult.Get(0);
+ SQLResult.RemoveAt(0);
+ }
+ while(SQLResultLength.GetSize())
+ {
+ delete SQLResultLength.Get(0);
+ SQLResultLength.RemoveAt(0);
+ }
+
+ /* LJ: Leak!! */
+ while(EMaskImage.GetSize())
+ {
+ delete EMaskImage.Get(0);
+ EMaskImage.RemoveAt(0);
+ }
+ while(EMaskSeries.GetSize())
+ {
+ delete EMaskSeries.Get(0);
+ EMaskSeries.RemoveAt(0);
+ }
+ while(EMaskStudy.GetSize())
+ {
+ delete EMaskStudy.Get(0);
+ EMaskStudy.RemoveAt(0);
+ }
+ while(EMaskPatient.GetSize())
+ {
+ delete EMaskPatient.Get(0);
+ EMaskPatient.RemoveAt(0);
+ }
+
+ free(TempString);
+ free(SearchString);
+ return ( TRUE );
+ }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Modality worklist query (out of database)
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+// unfold a query DDO with sequences in it to a flat query
+// DDO: input DICOM sequence
+// DB: database definition
+// EMask: output array of VR's found in sequence and in DB
+// SQLResult: field='value' string to build query of VR's found in sequence and in DB
+// DBQ: points to field definition of VR's found in sequence and in DB
+// Levels: nesting in sequences of VR's found in sequence and in DB
+// level: nesting of this sequence
+
+static void ProcessQuery(DICOMDataObject *DDO, DBENTRY *DB, Array <VR *> *EMask, Array <char *> *SQLResult,
+ Array <DBENTRY *> *DBQ, Array <int> *Levels, int level, Database *dbf)
+ {
+ VR *vr;
+ DBENTRY *TempDBEPtr;
+ char *SQLResultString;
+
+ while ((vr = DDO->Pop()))
+ {
+ if(vr->Element == 0x0000)
+ {
+ delete vr;
+ continue; // discard length codes
+ }
+
+ if (vr->SQObjectArray)
+ {
+ Array < DICOMDataObject * > *aSQArray;
+ aSQArray = (Array < DICOMDataObject * > *) vr->SQObjectArray;
+ if ( aSQArray->GetSize()<=1 )
+ {
+ char *c = NULL; SQLResult->Add ( c ); // NULL, vr, level, NULL: deeper sequence
+ EMask->Add ( vr );
+ int l = level; Levels->Add ( l );
+ DBENTRY *d=NULL; DBQ->Add ( d );
+
+ ProcessQuery(aSQArray->Get(0), DB, EMask, SQLResult, DBQ, Levels, level+1, dbf);
+ continue;
+ }
+ continue;
+ }
+
+ if(!VerifyIsInDBE(vr, DB, TempDBEPtr))
+ {
+ SystemDebug.printf("Queried item %4.4x %4.4x is not in the database\n",
+ vr->Group, vr->Element);
+ delete vr;
+ continue;
+ }
+ else
+ {
+ SQLResultString = SetString(vr, NULL, 0);
+ DICOM2SQLQuery(SQLResultString, dbf);
+
+ SQLResult->Add ( SQLResultString ); // field=value, vr, level, DBE: vr
+ EMask->Add ( vr );
+ Levels->Add ( level );
+ DBQ->Add ( TempDBEPtr );
+ }
+
+ }
+ }
+
+// Build a N=1 sequence out of a flat data query into vr as from emask - taking all items at the same level as sequence
+// EMask: input array of VR's found in sequence in query and in DB
+// SQLResult: input array of read value strings (NULL is sequence starter)
+// SQLResultLength: input array of read value lenghts
+// DBQMaster: input array of field definitions
+// Levels: input array of nesting level in sequences, sequence stops when decreases, nests when increases
+// DDO: DICOM object to append sequence too
+// Index: Index in array of sequence fields: array[Index]: vr of sequence, array[Index+N]: vr's of sequence contents
+
+static void CodeSequence(Array < VR * >*EMask, Array <char *> *SQLResult, Array <SQLLEN *> *SQLResultLength, Array <DBENTRY *> *DBQMaster,
+ Array <int> *Levels, DICOMDataObject *DDO, UINT *Index)
+ {
+ UINT32 VRLength;
+ VR *vr, *vrs;
+ int level;// ind = *Index;
+
+ level = Levels->Get(*Index);
+
+ SystemDebug.printf("Coding sequence (%04x,%04x), level=%d\n", EMask->Get(*Index)->Group, EMask->Get(*Index)->Element, level);
+
+ if (*Index+1 >= Levels->GetSize() || Levels->Get(*Index+1) <= level)
+ {
+ SystemDebug.printf("(sequence is empty)\n");
+ vrs = new VR(EMask->Get(*Index)->Group, EMask->Get(*Index)->Element, 0, (void*)NULL, FALSE);
+ DDO->Push(vrs);
+ (*Index)++;
+ return; // allow empty sequence
+ }
+
+ Array < DICOMDataObject * > *SQE = new Array < DICOMDataObject * >;
+ vrs = new VR(EMask->Get(*Index)->Group, EMask->Get(*Index)->Element, 0, (void*)NULL, FALSE);
+ vrs->SQObjectArray = (void*) SQE;
+
+ DICOMDataObject *D = new DICOMDataObject;
+
+ (*Index)++;
+
+ while ( *Index < EMask->GetSize() )
+ {
+ if (Levels->Get(*Index)<=level) break;
+ if (SQLResult->Get(*Index))
+ {
+ VRLength = SQLRealSize(SQLResult->Get(*Index), *SQLResultLength->Get(*Index));
+ vr = ConstructVRFromSQL (
+ DBQMaster->Get(*Index),
+ EMask->Get(*Index)->Group,
+ EMask->Get(*Index)->Element,
+ VRLength,
+ SQLResult->Get(*Index));
+ DumpVR(vr, NULL, level-1);
+ D->Push(vr);
+ (*Index)++;
+ }
+ else
+ CodeSequence(EMask, SQLResult, SQLResultLength, DBQMaster, Levels, D, Index);
+ }
+
+ SQE->Add(D);
+ DDO->Push(vrs);
+
+// SystemDebug.printf("end coding sequence (%04x,%04x), level=%d\n", EMask->Get(ind)->Group, EMask->Get(ind)->Element, level);
+ }
+
+BOOL QueryOnModalityWorkList (
+ DICOMDataObject *DDO,
+ Array < DICOMDataObject *> *ADDO)
+ {
+ UINT Index, CIndex, CCIndex, FIndex;
+ UINT32 VRLength;
+ DICOMDataObject *RDDO;
+ Database DB;
+ char *SQLResultString;
+ Array < char * > SQLResult, SQLResultWorkList;
+ Array < VR * > EMaskWorkList, EMask;
+ Array < SQLLEN *> SQLResultLength;
+ Array < DBENTRY * > DBQWorkList;
+ Array < DBENTRY * > DBQMaster;
+ Array < int > Levels;
+ DBENTRY *TempDBEPtr;
+ char *DBR;
+ SQLLEN *DBL;
+ VR *vr;// *vrs;
+ VR VRPatientName;
+ DBENTRY *DBEntryPatientName;
+ char SortOrder[128];
+ char *Sorting;
+ BOOL DoSort;
+ BOOL SendAE = FALSE;
+// BOOL SendScheduledProcedureStep = FALSE;
+ char TempString [ 8192 ];
+ char SearchString [ 8192 ];
+ char ColumnString [ 4096 ];
+ char Tables [ 256 ];
+ char *Sort=NULL;
+ UINT16 mask = 0xffff;
+
+ SystemDebug.printf("Query On Modality WorkList\n");
+
+ if (!DB.Open ( DataSource, UserName, Password, DataHost ) )
+ {
+ DB.PrintLastError();
+ return ( FALSE ); // failed open
+ }
+
+ // First. Check that all the asked-for elements are actually in the database.
+ DoSort = FALSE;
+ while ((vr = DDO->Pop()))
+ {
+ if(vr->Element == 0x0000)
+ {
+ delete vr;
+ continue; // discard length codes
+ }
+ if(vr->Group == 0x0002)
+ if(vr->Element == 0x0010)
+ {
+ delete vr;
+ continue; // discard transfer syntax
+ }
+ if(vr->Group == 0x0008)
+ if(vr->Element == 0x0052)
+ {
+ delete vr;
+ continue; // discard model level
+ }
+ if(vr->Group == 0x0008)
+ if(vr->Element == 0x0054)
+ {
+ SendAE = TRUE;
+ delete vr;
+ continue; // discard it (but send it)
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x0802)
+ {
+ mask = vr->GetUINT16();
+ delete vr;
+ continue; // discard it
+ }
+ if(vr->Group == 0x9999)
+ if(vr->Element == 0x0900)
+ {
+ mask = vr->GetUINT16();
+ delete vr;
+ continue; // discard it
+ }
+
+ if (vr->SQObjectArray)
+ {
+ Array < DICOMDataObject * > *aSQArray;
+ aSQArray = (Array < DICOMDataObject * > *) vr->SQObjectArray;
+ if ( aSQArray->GetSize()<=1 )
+ {
+ char *c=NULL; SQLResultWorkList.Add ( c ); // NULL, vr, 1, NULL: code sequence
+ EMaskWorkList.Add ( vr );
+ int l=1; Levels.Add ( l );
+ DBENTRY *d=NULL; DBQWorkList.Add ( d );
+
+ ProcessQuery(aSQArray->Get(0), WorkListDB, &EMaskWorkList, &SQLResultWorkList, &DBQWorkList, &Levels, 2, &DB);
+ continue;
+ }
+ delete vr;
+ continue;
+ }
+
+ if(!VerifyIsInDBE(vr, WorkListDB, TempDBEPtr))
+ {
+ SystemDebug.printf("Queried item %4.4x %4.4x is not in the database\n",
+ vr->Group, vr->Element);
+ delete vr;
+ continue;
+ }
+ else
+ {
+ if(vr->Group == 0x0010)
+ if(vr->Element == 0x0010)
+ DoSort = TRUE;
+ SQLResultString = SetString(vr, NULL, 0);
+ DICOM2SQLQuery(SQLResultString, &DB);
+
+ SQLResultWorkList.Add ( SQLResultString ); // field=value, vr, 1, DBE: code VR
+ EMaskWorkList.Add ( vr );
+ int l=1; Levels.Add ( l );
+ DBQWorkList.Add ( TempDBEPtr );
+ }
+ }
+
+// Index = 0;
+// while ( Index < Levels.GetSize() )
+// {
+// SystemDebug.printf("VR %4.4x %4.4x, level %d\n", EMaskWorkList.Get(Index)->Group, EMaskWorkList.Get(Index)->Element, Levels.Get(Index));
+// Index++;
+// }
+
+ // Prepare the query string.
+ // from EMasks, and SQLResults
+
+ SearchString[0] = '\0';
+ ColumnString[0] = '\0';
+
+ Index = 0;CIndex = 0;CCIndex = 0;
+ while ( Index < SQLResultWorkList.GetSize() )
+ {
+ SQLResultString = SQLResultWorkList.Get(Index);
+ if (SQLResultString) // flat query - but sequence starters (NULL) are not queried
+ {
+ if(BuildSearchString(&DB, WorkListDB, WorkListTableName, EMaskWorkList.Get(Index),
+ SQLResultString, TempString, sizeof(TempString)-512))
+ {
+ if(CIndex++)
+ safestrcat(SearchString, " and ", sizeof(SearchString));
+ safestrcat(SearchString, TempString, sizeof(SearchString));
+ }
+ BuildColumnString(WorkListDB, WorkListTableName, EMaskWorkList.Get(Index), TempString);
+ if(ColumnString[0])
+ strcat(ColumnString, ", ");
+ strcat(ColumnString, TempString);
+ }
+ EMask.Add(EMaskWorkList.Get(Index));
+ DBQMaster.Add(DBQWorkList.Get(Index));
+ ++Index;++CCIndex;
+ }
+
+ sprintf(Tables, "%s",
+ WorkListTableName);
+
+ SystemDebug.printf("Issue Query on Columns: %s\n", ColumnString);
+ SystemDebug.printf("Values: %.1000s\n", SearchString);
+ SystemDebug.printf("Tables: %.1000s\n", Tables);
+
+ // Issue Query
+
+ // (optionally) control sorting
+ VRPatientName.Group = 0x0010;
+ VRPatientName.Element = 0x0010;
+ DBEntryPatientName = FindDBE(&VRPatientName);
+ if(DBEntryPatientName)
+ {
+ sprintf(SortOrder, "%s.%s",
+ WorkListTableName,
+ DBEntryPatientName->SQLColumn);
+ if(DoSort)
+ Sorting = SortOrder;
+ else
+ Sorting = NULL;
+ }
+ else
+ Sorting = NULL;
+
+ Sort = Sorting;
+
+ SystemDebug.printf("Sorting (%s) DoSort := %d\n", Sort, DoSort);
+
+ if(strlen(SearchString))
+ {
+ if (!DB.QueryDistinct ( Tables, ColumnString, SearchString, Sort) )
+ {
+ DB.PrintLastError();
+ return ( FALSE ); // failed query
+ }
+ }
+ else
+ if (!DB.QueryDistinct ( Tables, ColumnString, NULL, Sort))
+ {
+ DB.PrintLastError();
+ return ( FALSE ); // failed query
+ }
+
+ // Allocate memory for and bind all fields that will actually be read (no sequence starters)
+ Index = 0;
+ FIndex = 1;
+ while ( Index < CCIndex )
+ {
+ SQLResultString = SQLResultWorkList.Get(Index);
+ if (SQLResultString) // Sequence starters have a NULL here
+ {
+ DBR = new char[255];
+ DBR[0] = 0; // Initialize memory: in case a field is NULL it does not read
+ SQLResult.Add(DBR);
+ DBL = new SQLLEN;
+ SQLResultLength.Add(DBL);
+ if(!DB.BindField (FIndex, SQL_C_CHAR,
+ SQLResult.Get(Index), 255,
+ SQLResultLength.Get(Index)))
+ {
+ SystemDebug.printf("Column Number : %d\n", Index+1);
+ DB.PrintLastError();
+ while(SQLResult.GetSize())
+ {
+ delete SQLResult.Get(0);
+ SQLResult.RemoveAt(0);
+ }
+ while(SQLResultLength.GetSize())
+ {
+ delete SQLResultLength.Get(0);
+ SQLResultLength.RemoveAt(0);
+ }
+ while(SQLResultWorkList.GetSize())
+ {
+ delete SQLResultWorkList.Get(0);
+ SQLResultWorkList.RemoveAt(0);
+ }
+ return ( FALSE ); // failed to bind column
+ }
+ FIndex++;
+ }
+ else
+ {
+ DBR = NULL;
+ SQLResult.Add(DBR);
+ DBL = NULL;
+ SQLResultLength.Add(DBL);
+ }
+ ++Index;
+ }
+
+ // Create dicom object out of each database record
+ while (DB.NextRecord())
+ {
+ RDDO = new DICOMDataObject;
+ Index = 0;
+ while ( Index < CCIndex )
+ {
+ SQLResultString = SQLResultWorkList.Get(Index);
+ if (!SQLResultString) // sequence starter has a NULL here: build a sequence (with 1 item)
+ CodeSequence(&EMask, &SQLResult, &SQLResultLength, &DBQMaster, &Levels, RDDO, &Index);
+
+ else // build a vr
+ {
+ VRLength = SQLRealSize(SQLResult.Get(Index), *SQLResultLength.Get(Index));
+ vr = ConstructVRFromSQL (
+ DBQMaster.Get(Index),
+ EMask.Get(Index)->Group,
+ EMask.Get(Index)->Element,
+ VRLength,
+ SQLResult.Get(Index));
+
+ DumpVR(vr);
+ RDDO->Push(vr);
+ ++Index;
+ }
+ }
+
+ vr = RDDO->GetVR(0x0008, 0x1110);
+ if(!vr)
+ {
+ VR *vrNew = new VR(0x0008, 0x1110, 0, (void*)NULL, FALSE);
+ RDDO->Push(vrNew);
+ }
+
+ vr = RDDO->GetVR(0x0008, 0x1120);
+ if(!vr)
+ {
+ VR *vrNew = new VR(0x0008, 0x1120, 0, (void*)NULL, FALSE);
+ RDDO->Push(vrNew);
+ }
+
+ if (WorkListReturnsISO_IR_100)
+ {
+ vr = RDDO->GetVR(0x0008, 0x0005);
+ if(!vr)
+ {
+ VR *vrNew = new VR(0x0008, 0x0005, 10, TRUE);
+ sprintf((char*)vrNew->Data, "ISO_IR %d", WorkListReturnsISO_IR_100);
+ RDDO->Push(vrNew);
+ }
+ }
+
+ if(SendAE)
+ RDDO->Push(ConstructAE());
+ ADDO->Add(RDDO);
+ }
+
+ SystemDebug.printf("Records = %d\n", ADDO->GetSize());
+
+ while(SQLResultWorkList.GetSize())
+ {
+ delete SQLResultWorkList.Get(0);
+ SQLResultWorkList.RemoveAt(0);
+ }
+ while(SQLResult.GetSize())
+ {
+ delete SQLResult.Get(0);
+ SQLResult.RemoveAt(0);
+ }
+ while(SQLResultLength.GetSize())
+ {
+ delete SQLResultLength.Get(0);
+ SQLResultLength.RemoveAt(0);
+ }
+ while(EMaskWorkList.GetSize())
+ {
+ delete EMaskWorkList.Get(0);
+ EMaskWorkList.RemoveAt(0);
+ }
+ while(Levels.GetSize())
+ {
+ Levels.RemoveAt(0);
+ }
+
+ return ( TRUE );
+ }
+
diff --git a/windowsmanual.pdf b/windowsmanual.pdf
new file mode 100644
index 0000000..cac78c3
Binary files /dev/null and b/windowsmanual.pdf differ
diff --git a/wintypes.hpp b/wintypes.hpp
new file mode 100644
index 0000000..5d181cc
--- /dev/null
+++ b/wintypes.hpp
@@ -0,0 +1,30 @@
+// 20050111 mvh added SWORD and UWORD
+
+#ifndef WINTYPES_HPP
+#define WINTYPES_HPP
+#ifdef UNIX
+
+// Windows datatypes not defined in UNIX environment
+typedef unsigned long DWORD;
+typedef long SDWORD;
+typedef short SWORD;
+typedef unsigned short UWORD;
+
+// some of the possible ODBC datatypes
+
+typedef enum
+{
+ SQL_C_NONE,
+ SQL_C_CHAR,
+ SQL_C_SSHORT,
+ SQL_C_USHORT,
+ SQL_C_SLONG,
+ SQL_C_ULONG,
+ SQL_C_FLOAT,
+ SQL_C_DOUBLE,
+ SQL_C_DATE
+
+} ODBC_datatype;
+
+#endif
+#endif
diff --git a/xvgifwr.cpp b/xvgifwr.cpp
new file mode 100644
index 0000000..91424e4
--- /dev/null
+++ b/xvgifwr.cpp
@@ -0,0 +1,1242 @@
+/*
+20050129 mvh Adapted for use in the Conquest DICOM server (see //)
+20050130 mvh Made it ansi C
+20050826 mvh Made it reentrant to avoid gif file corruption in server
+20051219 mvh Fixed leak
+20070902 mvh Made cpp
+20080905 bcb Removed malloc.h for DARWIN
+20090620 jf Include file stuff
+20091231 bcb Changed char* to const char* for gcc4.2 warnings
+20100111 mvh Merged
+20100309 bcb Commented out unused variables (gcc4.2 Warnings)
+20100619 bcb Added UNUSED_ARGUMENT.
+20100717 mvh Merged
+20101004 mvh Taken lsp's code of avs_animatedgif into use
+20101116 bcb Warnings fixed
+20101120 mvh Merged
+20101128 mvh Fixed double fclose
+*/
+
+/*
+ * xvgifwr.c - handles writing of GIF files. based on flgife.c and
+ * flgifc.c from the FBM Library, by Michael Maudlin
+ *
+ * Contains:
+ * WriteGIF(fp, pic, ptype, w, h, rmap, gmap, bmap, numcols, colorstyle,
+ * comment)
+ *
+ * Note: slightly brain-damaged, in that it'll only write non-interlaced
+ * GIF files (in the interests of speed, or something)
+ *
+ */
+
+#if 0
+
+/*****************************************************************
+ * Portions of this code Copyright (C) 1989 by Michael Mauldin.
+ * Permission is granted to use this file in whole or in
+ * part for any purpose, educational, recreational or commercial,
+ * provided that this copyright notice is retained unchanged.
+ * This software is available to all free of charge by anonymous
+ * FTP and in the UUNET archives.
+ *
+ *
+ * Authors: Michael Mauldin (mlm at cs.cmu.edu)
+ * David Rowley (mgardi at watdcsu.waterloo.edu)
+ *
+ * Based on: compress.c - File compression ala IEEE Computer, June 1984.
+ *
+ * Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
+ * Jim McKie (decvax!mcvax!jim)
+ * Steve Davies (decvax!vax135!petsd!peora!srd)
+ * Ken Turkowski (decvax!decwrl!turtlevax!ken)
+ * James A. Woods (decvax!ihnp4!ames!jaw)
+ * Joe Orost (decvax!vax135!petsd!joe)
+ *****************************************************************/
+
+#ifndef UNUSED_ARGUMENT
+#define UNUSED_ARGUMENT(x) (void)x
+#endif
+
+#include <stdio.h>
+#include <stdlib.h> //DUCKHEAD92
+#include <string.h>
+#ifndef DARWIN
+#include <malloc.h>
+#endif //DARWIN
+
+#define MONO(rd,gn,bl) ( ((int)(rd)*11 + (int)(gn)*16 + (int)(bl)*5) >> 5)
+#define XV_BITS 12 /* BITS was already defined on some systems */
+#define MSDOS 1
+#define HSIZE 5003 /* 80% occupancy */
+#define MAXCODE(n_bits) ( (1 << (n_bits)) - 1)
+
+typedef long int count_int;
+typedef unsigned char byte;
+typedef unsigned long u_long;
+typedef unsigned char char_type;
+
+struct aap
+{ unsigned long cur_accum;
+ int cur_bits;
+ int n_bits; /* number of bits/code */
+ int maxcode; /* maximum code, given n_bits */
+ int free_ent; /* first unused entry */
+ int clear_flg;
+ int g_init_bits;
+ FILE *g_outfile;
+ int ClearCode;
+ int EOFCode;
+ int a_count;
+ char accum[ 256 ];
+ byte pc2nc[256],r1[256],g1[256],b1[256];
+};
+
+static void putword (int, FILE *);
+static void compress (int, FILE *, byte *, int, struct aap *);
+static void output (int, struct aap *);
+static void cl_block (count_int *, struct aap *);
+static void cl_hash (count_int, count_int *);
+static void char_out (int, struct aap *);
+static void flush_char(struct aap *);
+
+/*************************************************************/
+int WriteGIF(FILE *fp, unsigned char *pic, int ptype, int w, int h,
+ unsigned char *rmap, unsigned char *gmap,
+ unsigned char *bmap, int numcols, int colorstyle,
+ const char *comment)
+{ int RWidth, RHeight;
+ int LeftOfs, TopOfs;
+ int ColorMapSize, InitCodeSize, Background, BitsPerPixel;
+ int i,j,nc;
+ byte *pic8;
+// byte rtemp[256],gtemp[256],btemp[256];
+ int Interlace;
+
+ struct aap *a = (struct aap *)malloc(sizeof(struct aap));
+ memset(a, 0, sizeof(struct aap));
+
+ UNUSED_ARGUMENT(ptype);
+// if (ptype == PIC24) { /* have to quantize down to 8 bits */
+// pic8 = Conv24to8(pic, w, h, 256, rtemp,gtemp,btemp);
+// if (!pic8) FatalError("Unable to malloc in WriteGIF()");
+// rmap = rtemp; gmap = gtemp; bmap = btemp; numcols=256;
+// }
+// else
+ pic8 = pic;
+
+ Interlace = 0;
+ Background = 0;
+
+ for (i=0; i<256; i++) { a->pc2nc[i] = a->r1[i] = a->g1[i] = a->b1[i] = 0; }
+
+ /* compute number of unique colors */
+ nc = 0;
+
+ for (i=0; i<numcols; i++) {
+ /* see if color #i is already used */
+ for (j=0; j<i; j++) {
+ if (rmap[i] == rmap[j] && gmap[i] == gmap[j] &&
+ bmap[i] == bmap[j]) break;
+ }
+
+ if (j==i) { /* wasn't found */
+ a->pc2nc[i] = nc;
+ a->r1[nc] = rmap[i];
+ a->g1[nc] = gmap[i];
+ a->b1[nc] = bmap[i];
+ nc++;
+ }
+ else a->pc2nc[i] = a->pc2nc[j];
+ }
+
+
+ /* figure out 'BitsPerPixel' */
+ for (i=1; i<8; i++)
+ if ( (1<<i) >= nc) break;
+
+ BitsPerPixel = i;
+
+ ColorMapSize = 1 << BitsPerPixel;
+
+ RWidth = w;
+ RHeight = h;
+ LeftOfs = TopOfs = 0;
+
+ if (BitsPerPixel <= 1) InitCodeSize = 2;
+ else InitCodeSize = BitsPerPixel;
+
+ if (!fp) {
+ fprintf(stderr, "WriteGIF: file not open for writing\n" );
+// if (ptype == PIC24) free(pic8);
+ free(a);
+ return (1);
+ }
+
+// if (DEBUG)
+// fprintf(stderr,"WrGIF: pic=%lx, w,h=%dx%d, numcols=%d, Bits%d,Cmap=%d\n",
+// (u_long) pic8, w,h,numcols,BitsPerPixel,ColorMapSize);
+
+ if (comment && strlen(comment) > (size_t) 0)
+ fwrite("GIF89a", (size_t) 1, (size_t) 6, fp); /* the GIF magic number */
+ else
+ fwrite("GIF87a", (size_t) 1, (size_t) 6, fp); /* the GIF magic number */
+
+ putword(RWidth, fp); /* screen descriptor */
+ putword(RHeight, fp);
+
+ i = 0x80; /* Yes, there is a color map */
+ i |= (8-1)<<4; /* OR in the color resolution (hardwired 8) */
+ i |= (BitsPerPixel - 1); /* OR in the # of bits per pixel */
+ fputc(i,fp);
+
+ fputc(Background, fp); /* background color */
+
+ fputc(0, fp); /* future expansion byte */
+
+
+ if (colorstyle == 1) { /* greyscale */
+ for (i=0; i<ColorMapSize; i++) {
+ j = MONO(a->r1[i], a->g1[i], a->b1[i]);
+ fputc(j, fp);
+ fputc(j, fp);
+ fputc(j, fp);
+ }
+ }
+ else {
+ for (i=0; i<ColorMapSize; i++) { /* write out Global colormap */
+ fputc(a->r1[i], fp);
+ fputc(a->g1[i], fp);
+ fputc(a->b1[i], fp);
+ }
+ }
+
+ if (comment && strlen(comment) > (size_t) 0) { /* write comment blocks */
+ const char *sp;
+ int k, blen;
+
+ fputc(0x21, fp); /* EXTENSION block */
+ fputc(0xFE, fp); /* comment extension */
+
+ sp = comment;
+ while ( (blen=strlen(sp)) > 0) {
+ if (blen>255) blen = 255;
+ fputc(blen, fp);
+ for (k=0; k<blen; k++, sp++) fputc(*sp, fp);
+ }
+ fputc(0, fp); /* zero-length data subblock to end extension */
+ }
+
+
+ fputc( ',', fp ); /* image separator */
+
+ /* Write the Image header */
+ putword(LeftOfs, fp);
+ putword(TopOfs, fp);
+ putword(RWidth, fp);
+ putword(RHeight, fp);
+ if (Interlace) fputc(0x40, fp); /* Use Global Colormap, maybe Interlace */
+ else fputc(0x00, fp);
+
+ fputc(InitCodeSize, fp);
+ compress(InitCodeSize+1, fp, pic8, w*h, a);
+
+ fputc(0,fp); /* Write out a Zero-length packet (EOF) */
+ fputc(';',fp); /* Write GIF file terminator */
+
+// if (ptype == PIC24) free(pic8);
+
+ free(a);
+ if (ferror(fp)) return -1;
+ return (0);
+}
+
+
+/******************************/
+static void putword(int w, FILE *fp)
+{
+ /* writes a 16-bit integer in GIF order (LSB first) */
+ fputc(w & 0xff, fp);
+ fputc((w>>8)&0xff, fp);
+}
+
+
+
+
+/***********************************************************************/
+
+/*
+ * To save much memory, we overlay the table used by compress() with those
+ * used by decompress(). The tab_prefix table is the same size and type
+ * as the codetab. The tab_suffix table needs 2**BITS characters. We
+ * get this from the beginning of htab. The output stack uses the rest
+ * of htab, and contains characters. There is plenty of room for any
+ * possible stack (stack used to be 8000 characters).
+ */
+
+/*
+ * block compression parameters -- after all codes are used up,
+ * and compression rate changes, start over.
+ */
+
+/*
+ * compress stdin to stdout
+ *
+ * Algorithm: use open addressing double hashing (no chaining) on the
+ * prefix code / next character combination. We do a variant of Knuth's
+ * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
+ * secondary probe. Here, the modular division first probe is gives way
+ * to a faster exclusive-or manipulation. Also do block compression with
+ * an adaptive reset, whereby the code table is cleared when the compression
+ * ratio decreases, but after the table fills. The variable-length output
+ * codes are re-sized at this point, and a special CLEAR code is generated
+ * for the decompressor. Late addition: construct the table according to
+ * file size for noticeable speed improvement on small files. Please direct
+ * questions about this implementation to ames!jaw.
+ */
+
+
+/********************************************************/
+static void compress(int init_bits, FILE *outfile, byte *data, int len, struct aap *a)
+{
+ register long fcode;
+ register int i = 0;
+ register int c;
+ register int ent;
+ register int disp;
+ register int hsize_reg;
+ register int hshift;
+
+ unsigned short codetab [HSIZE];
+ count_int htab [HSIZE];
+
+ /*
+ * Set up the globals: g_init_bits - initial number of bits
+ * g_outfile - pointer to output file
+ */
+ a->g_init_bits = init_bits;
+ a->g_outfile = outfile;
+
+ /* initialize 'compress' globals */
+ memset((char *) htab, 0, sizeof(htab));
+ memset((char *) codetab, 0, sizeof(codetab));
+ a->free_ent = 0;
+ a->clear_flg = 0;
+ a->cur_accum = 0;
+ a->cur_bits = 0;
+
+ /*
+ * Set up the necessary values
+ */
+ a->clear_flg = 0;
+ a->maxcode = MAXCODE(a->n_bits = a->g_init_bits);
+
+ a->ClearCode = (1 << (init_bits - 1));
+ a->EOFCode = a->ClearCode + 1;
+ a->free_ent = a->ClearCode + 2;
+
+ a->a_count = 0;
+ ent = a->pc2nc[*data++]; len--;
+
+ hshift = 0;
+ for ( fcode = (long)HSIZE; fcode < 65536L; fcode *= 2L )
+ hshift++;
+ hshift = 8 - hshift; /* set hash code range bound */
+
+ hsize_reg = HSIZE;
+ cl_hash( (count_int) hsize_reg, htab); /* clear hash table */
+
+ output(a->ClearCode, a);
+
+ while (len) {
+ c = a->pc2nc[*data++]; len--;
+
+ fcode = (long) ( ( (long) c << XV_BITS) + ent);
+ i = (((int) c << hshift) ^ ent); /* xor hashing */
+
+ if ( htab[i] == fcode ) {
+ ent = codetab[i];
+ continue;
+ }
+
+ else if ( (long)htab[i] < 0 ) /* empty slot */
+ goto nomatch;
+
+ disp = hsize_reg - i; /* secondary hash (after G. Knott) */
+ if ( i == 0 )
+ disp = 1;
+
+probe:
+ if ( (i -= disp) < 0 )
+ i += hsize_reg;
+
+ if ( htab[i] == fcode ) {
+ ent = codetab[i];
+ continue;
+ }
+
+ if ( (long)htab[i] >= 0 )
+ goto probe;
+
+nomatch:
+ output(ent, a);
+ ent = c;
+
+ if ( a->free_ent < (1<<XV_BITS) ) {
+ codetab[i] = a->free_ent++; /* code -> hashtable */
+ htab[i] = fcode;
+ }
+ else
+ cl_block(htab, a);
+ }
+
+ /* Put out the final code */
+ output(ent, a);
+ output(a->EOFCode, a);
+}
+
+
+/*****************************************************************
+ * TAG( output )
+ *
+ * Output the given code.
+ * Inputs:
+ * code: A n_bits-bit integer. If == -1, then EOF. This assumes
+ * that n_bits =< (long)wordsize - 1.
+ * Outputs:
+ * Outputs code to the file.
+ * Assumptions:
+ * Chars are 8 bits long.
+ * Algorithm:
+ * Maintain a BITS character long buffer (so that 8 codes will
+ * fit in it exactly). Use the VAX insv instruction to insert each
+ * code in turn. When the buffer fills up empty it and start over.
+ */
+
+static
+unsigned long masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F,
+ 0x001F, 0x003F, 0x007F, 0x00FF,
+ 0x01FF, 0x03FF, 0x07FF, 0x0FFF,
+ 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
+
+static void output(int code, struct aap *a)
+{
+ a->cur_accum &= masks[a->cur_bits];
+
+ if (a->cur_bits > 0)
+ a->cur_accum |= ((long)code << a->cur_bits);
+ else
+ a->cur_accum = code;
+
+ a->cur_bits += a->n_bits;
+
+ while( a->cur_bits >= 8 ) {
+ char_out( (int) (a->cur_accum & 0xff), a );
+ a->cur_accum >>= 8;
+ a->cur_bits -= 8;
+ }
+
+ /*
+ * If the next entry is going to be too big for the code size,
+ * then increase it, if possible.
+ */
+
+ if (a->free_ent > a->maxcode || a->clear_flg) {
+
+ if( a->clear_flg ) {
+ a->maxcode = MAXCODE (a->n_bits = a->g_init_bits);
+ a->clear_flg = 0;
+ }
+ else {
+ a->n_bits++;
+ if ( a->n_bits == XV_BITS )
+ a->maxcode = (1<<XV_BITS);
+ else
+ a->maxcode = MAXCODE(a->n_bits);
+ }
+ }
+
+ if( code == a->EOFCode ) {
+ /* At EOF, write the rest of the buffer */
+ while( a->cur_bits > 0 ) {
+ char_out( (int)(a->cur_accum & 0xff), a );
+ a->cur_accum >>= 8;
+ a->cur_bits -= 8;
+ }
+
+ flush_char(a);
+
+ fflush( a->g_outfile );
+
+ }
+}
+
+
+/********************************/
+static void cl_block (count_int *htab, struct aap *a) /* table clear for block compress */
+{
+ /* Clear out the hash table */
+
+ cl_hash ( (count_int)HSIZE, htab );
+ a->free_ent = a->ClearCode + 2;
+ a->clear_flg = 1;
+
+ output(a->ClearCode, a);
+}
+
+
+/********************************/
+static void cl_hash(register count_int hsize, count_int *htab) /* reset code table */
+{
+ register count_int *htab_p = htab+hsize;
+ register long i;
+ register long m1 = -1;
+
+ i = hsize - 16;
+ do { /* might use Sys V memset(3) here */
+ *(htab_p-16) = m1;
+ *(htab_p-15) = m1;
+ *(htab_p-14) = m1;
+ *(htab_p-13) = m1;
+ *(htab_p-12) = m1;
+ *(htab_p-11) = m1;
+ *(htab_p-10) = m1;
+ *(htab_p-9) = m1;
+ *(htab_p-8) = m1;
+ *(htab_p-7) = m1;
+ *(htab_p-6) = m1;
+ *(htab_p-5) = m1;
+ *(htab_p-4) = m1;
+ *(htab_p-3) = m1;
+ *(htab_p-2) = m1;
+ *(htab_p-1) = m1;
+ htab_p -= 16;
+ } while ((i -= 16) >= 0);
+
+ for ( i += 16; i > 0; i-- )
+ *--htab_p = m1;
+}
+
+
+/******************************************************************************
+ *
+ * GIF Specific routines
+ *
+ ******************************************************************************/
+
+/*
+ * Add a character to the end of the current packet, and if it is 254
+ * characters, flush the packet to disk.
+ */
+static void char_out(int c, struct aap *a)
+{
+ a->accum[ a->a_count++ ] = c;
+ if( a->a_count >= 254 )
+ flush_char(a);
+}
+
+/*
+ * Flush the packet to disk, and reset the accumulator
+ */
+static void flush_char(struct aap *a)
+{
+ if( a->a_count > 0 ) {
+ fputc(a->a_count, a->g_outfile );
+ fwrite(a->accum, (size_t) 1, (size_t) a->a_count, a->g_outfile );
+ a->a_count = 0;
+ }
+}
+
+#else
+
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+// new implementation includes animated gif
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+
+/*****************************************************************
+ * Portions of this code Copyright (C) 1989 by Michael Mauldin.
+ * Permission is granted to use this file in whole or in
+ * part for any purpose, educational, recreational or commercial,
+ * provided that this copyright notice is retained unchanged.
+ * This software is available to all free of charge by anonymous
+ * FTP and in the UUNET archives.
+ *
+ *
+ * Authors: Michael Mauldin (mlm at cs.cmu.edu)
+ * David Rowley (mgardi at watdcsu.waterloo.edu)
+ *
+ * Based on: compress.c - File compression ala IEEE Computer, June 1984.
+ *
+ * Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
+ * Jim McKie (decvax!mcvax!jim)
+ * Steve Davies (decvax!vax135!petsd!peora!srd)
+ * Ken Turkowski (decvax!decwrl!turtlevax!ken)
+ * James A. Woods (decvax!ihnp4!ames!jaw)
+ * Joe Orost (decvax!vax135!petsd!joe)
+ *****************************************************************/
+
+#ifndef UNUSED_ARGUMENT
+#define UNUSED_ARGUMENT(x) (void)x
+#endif
+
+#include <stdio.h>
+#include <stdlib.h> //DUCKHEAD92
+#include <string.h>
+#ifndef DARWIN
+#include <malloc.h>
+#endif //DARWIN
+
+/************************************************************************/
+/* DEFINES, ENUMERATED TYPES AND CONSTANTS */
+/************************************************************************/
+
+const unsigned short MAX_PATH_LEN=1024;
+ /* MAX_GIFS is the number of supported calls to ANIMATED_GIF_CREAT without matching ANIMATED_GIF_CLOSE */
+const unsigned char MAX_GIFS=16;
+
+#ifndef hasColorStyleType
+#define hasColorStyleType 1
+enum ColorStyleType {csGlobalPalette, csLocalPalette}; // Store a global palette and/or one for each frame
+#endif
+
+#define AVS_OK 1
+#define AVS_ERROR 0
+#define AVSerror printf
+
+/************************************************************************/
+/* MODULE FUNCTIONS */
+/************************************************************************/
+
+#define MONO(rd,gn,bl) ( ((int)(rd)*11 + (int)(gn)*16 + (int)(bl)*5) >> 5)
+#define XV_BITS 12 /* BITS was already defined on some systems */
+#define HSIZE 5003 /* 80% occupancy */
+#define MAXCODE(n_bits) ( (1 << (n_bits)) - 1)
+
+typedef long int count_int;
+typedef unsigned char byte;
+
+struct GifStore
+{ unsigned long cur_accum;
+ int cur_bits;
+ int n_bits; /* number of bits/code */
+ int maxcode; /* maximum code, given n_bits */
+ int free_ent; /* first unused entry */
+ int clear_flg;
+ int g_init_bits;
+ FILE *g_outfile;
+ int ClearCode;
+ int EOFCode;
+ int a_count;
+ char accum[ 256 ];
+ byte pc2nc[256],r1[256],g1[256],b1[256];
+};
+
+struct GifDetails
+{ char filename[MAX_PATH_LEN];
+ FILE *fHandle;
+ int dims[2];
+ int Ratefps;
+};
+
+class GifManager
+{
+public:
+ GifDetails Gifs[MAX_GIFS]; // global structure to store details between calls to
+ // ANIMATED_GIF_CREAT, ANIMATED_GIF_WRITE and ANIMATED_GIF_CLOSE
+ GifManager();
+ int FreeHandle()
+ { for (int iFreeHandle=0; iFreeHandle<MAX_GIFS; iFreeHandle++)
+ if (Gifs[iFreeHandle].filename[0]=='\0')
+ return iFreeHandle;
+ return -1;
+ }
+};
+
+static class GifManager GifMan;
+
+static void putword2 (int, FILE *);
+static void compress (int, FILE *, byte *, int, struct GifStore *);
+static void output (int, struct GifStore *);
+static void cl_block (count_int *, struct GifStore *);
+static void cl_hash2 (count_int, count_int *);
+static void char_out (char, struct GifStore *);
+static void flush_char(struct GifStore *);
+
+GifManager::GifManager()
+{ memset(Gifs, 0, sizeof(Gifs));
+}
+
+int WritePalette(FILE *fp, GifStore *aGifStore, int ColorMapSize)
+{ int i;
+
+ /* write local or global colormap */
+ { for (i=0; i<ColorMapSize; i++)
+ { fputc(aGifStore->r1[i], fp);
+ fputc(aGifStore->g1[i], fp);
+ fputc(aGifStore->b1[i], fp);
+ }
+ }
+ return AVS_OK;
+}
+
+int WriteComment(FILE *fp, char *comment)
+{ int i;
+
+ if (comment && strlen(comment)>(size_t)0) /* write comment block */
+ { char *sp;
+ int blen;
+
+ fputc(0x21, fp); /* EXTENSION block */
+ fputc(0xFF, fp); /* comment extension, including looping detail */
+
+ sp = comment;
+ while ( (blen=(int)strlen(sp)) > 0)
+ { if (blen>255)
+ blen = 255;
+ fputc((int)blen, fp);
+ for (i=0; i<blen; i++, sp++)
+ fputc(*sp, fp);
+ }
+
+ fputc(0x03, fp); /* loop count */
+ fputc(0x01, fp);
+ fputc(0xff, fp); /* forever */
+ fputc(0xff, fp);
+
+ fputc(0, fp); /* zero-length data subblock to end extension */
+ }
+ return AVS_OK;
+}
+
+/*************************************************************/
+int WriteGIFHeader(FILE *fp, int w, int h, byte *rmap, byte *gmap, byte *bmap,
+ int numcols, ColorStyleType colorstyle, char *comment)
+{ int RWidth, RHeight;
+ int LeftOfs, TopOfs;
+ int ColorMapSize;
+ int InitCodeSize, BitsPerPixel;
+ int Background;
+ int i,j;
+ int nc;
+ int Interlace;
+
+ struct GifStore *aGifStore = (struct GifStore *)malloc(sizeof(struct GifStore));
+ if (aGifStore==NULL)
+ { AVSerror("WriteGIFHeader: out of memory");
+ return AVS_ERROR;
+ }
+ memset(aGifStore, 0, sizeof(struct GifStore));
+
+ Interlace = 0;
+ Background = 0;
+
+ for (i=0; i<256; i++)
+ aGifStore->pc2nc[i] = aGifStore->r1[i] = aGifStore->g1[i] = aGifStore->b1[i] = 0;
+
+ /* compute number of unique colors */
+ nc = 0;
+
+ for (i=0; i<numcols; i++)
+ { /* see if color #i is already used */
+ for (j=0; j<i; j++)
+ { if (rmap[i] == rmap[j] && gmap[i] == gmap[j] && bmap[i] == bmap[j])
+ break;
+ }
+
+ if (j==i) /* wasn't found */
+ { aGifStore->pc2nc[i] = (byte)nc;
+ aGifStore->r1[nc] = rmap[i];
+ aGifStore->g1[nc] = gmap[i];
+ aGifStore->b1[nc] = bmap[i];
+ nc++;
+ }
+ else
+ aGifStore->pc2nc[i] = aGifStore->pc2nc[j];
+ }
+
+ /* figure out 'BitsPerPixel' */
+ for (i=1; i<8; i++)
+ if ( (1<<i) >= nc)
+ break;
+
+ BitsPerPixel = (char)i;
+
+ ColorMapSize = 1 << BitsPerPixel;
+
+ RWidth = w;
+ RHeight = h;
+ LeftOfs = TopOfs = 0;
+
+ if (BitsPerPixel <= 1) InitCodeSize = 2;
+ else InitCodeSize = BitsPerPixel;
+
+ if (!fp)
+ { AVSerror("WriteGIFHeader: file not open for writing");
+ free(aGifStore);
+ return AVS_ERROR;
+ }
+
+ fwrite("GIF89a", (size_t) 1, (size_t) 6, fp); /* the GIF magic number */
+
+ putword2(RWidth, fp); /* screen descriptor */
+ putword2(RHeight, fp);
+
+ if (colorstyle==csGlobalPalette)
+ { i = 0x80; /* Yes, there is a color map */
+ i |= (8-1)<<4; /* OR in the color resolution (hardwired 8) */
+ i |= (BitsPerPixel - 1); /* OR in the # of bits per pixel */
+ }
+ else
+ i = 0;
+ fputc(i,fp);
+
+ fputc(Background, fp); /* background color */
+
+ fputc(0, fp); /* future expansion byte */
+
+ if (colorstyle==csGlobalPalette)
+ WritePalette(fp, aGifStore, ColorMapSize);
+ WriteComment(fp, comment);
+
+ free(aGifStore);
+
+ return AVS_OK;
+}
+
+int WriteGIFFrame(FILE *fp, byte *p, int w, int h,
+ byte *rmap, byte *gmap, byte *bmap,
+ int numcols,
+ int frames, int time, ColorStyleType colorstyle) // time in 0.01 sec
+{ int RWidth, RHeight;
+ int LeftOfs, TopOfs;
+ int ColorMapSize, InitCodeSize, Background, BitsPerPixel;
+ int i,j,f;
+ int nc;
+ byte *pic8;
+ int Interlace;
+ int cmap;
+
+ struct GifStore *aGifStore = (struct GifStore *)malloc(sizeof(struct GifStore));
+ if (aGifStore==NULL)
+ { AVSerror("WriteGIFFrame: out of memory");
+ return AVS_ERROR;
+ }
+ memset(aGifStore, 0, sizeof(struct GifStore));
+
+ pic8 = p;
+
+ Interlace = 0;
+ Background = 0;
+
+ for (i=0; i<256; i++)
+ aGifStore->pc2nc[i] = aGifStore->r1[i] = aGifStore->g1[i] = aGifStore->b1[i] = 0;
+
+ /* compute number of unique colors */
+ nc = 0;
+
+ for (i=0; i<numcols; i++)
+ { /* see if color #i is already used */
+ for (j=0; j<i; j++)
+ { if (rmap[i] == rmap[j] && gmap[i] == gmap[j] && bmap[i] == bmap[j])
+ break;
+ }
+
+ if (j==i) /* wasn't found */
+ { aGifStore->pc2nc[i] = (byte)nc;
+ aGifStore->r1[nc] = rmap[i];
+ aGifStore->g1[nc] = gmap[i];
+ aGifStore->b1[nc] = bmap[i];
+ nc++;
+ }
+ else
+ aGifStore->pc2nc[i] = aGifStore->pc2nc[j];
+ }
+
+ nc = 256;
+
+ /* figure out 'BitsPerPixel' */
+ for (i=1; i<8; i++)
+ if ( (1<<i) >= nc)
+ break;
+
+ BitsPerPixel = i;
+
+ ColorMapSize = 1 << BitsPerPixel;
+
+ RWidth = w;
+ RHeight = h;
+ LeftOfs = TopOfs = 0;
+
+ if (BitsPerPixel <= 1) InitCodeSize = 2;
+ else InitCodeSize = BitsPerPixel;
+
+ if (!fp)
+ { AVSerror("WriteGIFFrame: file not open for writing");
+ free(aGifStore);
+ return AVS_ERROR;
+ }
+
+ if (frames<1) frames=1;
+
+ for(f=0; f<frames; f++)
+ { /* image extension */
+ // Graphic Control Extension starts with 21 F9 04
+ fputc(0x21, fp); fputc(0xf9, fp); fputc(0x04, fp);
+ fputc(0x00, fp); // no transparency
+ putword2(time, fp); // time in 0.01 sec
+ fputc(0x00, fp); // transparent color (not used)
+ fputc(0x00, fp);
+
+ fputc( 0x2c, fp ); /* image separator */
+
+ /* Write the Image header */
+ putword2(LeftOfs, fp);
+ putword2(TopOfs, fp);
+ putword2(RWidth, fp);
+ putword2(RHeight, fp);
+
+ if (colorstyle==csLocalPalette)
+ cmap = 0x80 | 0x07;
+ else
+ cmap = 0;
+
+ if (Interlace)
+ fputc(cmap | 0x40, fp); /* Use local Colormap, maybe Interlace */
+ else
+ fputc(cmap | 0x00, fp);
+
+ if (colorstyle==csLocalPalette)
+ WritePalette(fp, aGifStore, 256);
+
+ fputc(InitCodeSize, fp);
+ compress((char)(InitCodeSize+1), fp, pic8, w*h, aGifStore);
+ pic8 += w * h;
+
+ fputc(0,fp); /* Write out a Zero-length packet (EOF) */
+
+ };
+
+ /* GIF file terminator (0x3b) should be written in caller*/
+
+ free(aGifStore);
+ if (ferror(fp))
+ return AVS_ERROR;
+ return AVS_OK;
+}
+
+
+/******************************/
+static void putword2(int w, FILE *fp)
+{ /* writes a 16-bit integer in GIF order (LSB first) */
+ fputc(w & 0xff, fp);
+ fputc((w>>8)&0xff, fp);
+}
+
+/***********************************************************************/
+
+/*
+ * To save much memory, we overlay the table used by compress() with those
+ * used by decompress(). The tab_prefix table is the same size and type
+ * as the codetab. The tab_suffix table needs 2**BITS characters. We
+ * get this from the beginning of htab. The output stack uses the rest
+ * of htab, and contains characters. There is plenty of room for any
+ * possible stack (stack used to be 8000 characters).
+ */
+
+/*
+ * block compression parameters -- after all codes are used up,
+ * and compression rate changes, start over.
+ */
+
+/*
+ * compress stdin to stdout
+ *
+ * Algorithm: use open addressing double hashing (no chaining) on the
+ * prefix code / next character combination. We do a variant of Knuth's
+ * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
+ * secondary probe. Here, the modular division first probe is gives way
+ * to a faster exclusive-or manipulation. Also do block compression with
+ * an adaptive reset, whereby the code table is cleared when the compression
+ * ratio decreases, but after the table fills. The variable-length output
+ * codes are re-sized at this point, and a special CLEAR code is generated
+ * for the decompressor. Late addition: construct the table according to
+ * file size for noticeable speed improvement on small files. Please direct
+ * questions about this implementation to ames!jaw.
+ */
+
+
+/********************************************************/
+static void compress(int init_bits, FILE *outfile, byte *data, int len, struct GifStore *aGifStore)
+{ register long fcode;
+ register int i = 0;
+ register int c;
+ register int ent;
+ register int disp;
+ register int hsize_reg;
+ register int hshift;
+
+ unsigned short codetab [HSIZE];
+ count_int htab [HSIZE];
+
+ /*
+ * Set up the globals: g_init_bits - initial number of bits
+ * g_outfile - pointer to output file
+ */
+ aGifStore->g_init_bits = init_bits;
+ aGifStore->g_outfile = outfile;
+
+ /* initialize 'compress' globals */
+ memset((char *) htab, 0, sizeof(htab));
+ memset((char *) codetab, 0, sizeof(codetab));
+ aGifStore->free_ent = 0;
+ aGifStore->clear_flg = 0;
+ aGifStore->cur_accum = 0;
+ aGifStore->cur_bits = 0;
+
+ /*
+ * Set up the necessary values
+ */
+ aGifStore->clear_flg = 0;
+ aGifStore->maxcode = MAXCODE(aGifStore->n_bits = aGifStore->g_init_bits);
+
+ aGifStore->ClearCode = 1 << (init_bits - 1);
+ aGifStore->EOFCode = aGifStore->ClearCode + 1;
+ aGifStore->free_ent = aGifStore->ClearCode + 2;
+
+ aGifStore->a_count = 0;
+ ent = aGifStore->pc2nc[*data++]; len--;
+
+ hshift = 0;
+ for ( fcode = (long)HSIZE; fcode < 65536L; fcode *= 2L )
+ hshift++;
+ hshift = 8 - hshift; /* set hash code range bound */
+
+ hsize_reg = HSIZE;
+ cl_hash2( (count_int) hsize_reg, htab); /* clear hash table */
+
+ output(aGifStore->ClearCode, aGifStore);
+
+ while (len)
+ { c = aGifStore->pc2nc[*data++];
+ len--;
+
+ fcode = (long) ( ( (long) c << XV_BITS) + ent);
+ i = (((int) c << hshift) ^ ent); /* xor hashing */
+
+ if ( htab[i] == fcode )
+ { ent = codetab[i];
+ continue;
+ }
+
+ else if ( (long)htab[i] < 0 ) /* empty slot */
+ goto nomatch;
+
+ disp = hsize_reg - i; /* secondary hash (after G. Knott) */
+ if ( i == 0 )
+ disp = 1;
+
+probe:
+ if ( (i -= disp) < 0 )
+ i += hsize_reg;
+
+ if ( htab[i] == fcode )
+ { ent = codetab[i];
+ continue;
+ }
+
+ if ( (long)htab[i] >= 0 )
+ goto probe;
+
+nomatch:
+ output(ent, aGifStore);
+ ent = c;
+
+ if ( aGifStore->free_ent < (1<<XV_BITS) )
+ { codetab[i] = (unsigned short)(aGifStore->free_ent++); /* code -> hashtable */
+ htab[i] = fcode;
+ }
+ else
+ cl_block(htab, aGifStore);
+ }
+
+ /* Put out the final code */
+ output(ent, aGifStore);
+ output(aGifStore->EOFCode, aGifStore);
+}
+
+
+/*****************************************************************
+ * TAG( output )
+ *
+ * Output the given code.
+ * Inputs:
+ * code: A n_bits-bit integer. If == -1, then EOF. This assumes
+ * that n_bits =< (long)wordsize - 1.
+ * Outputs:
+ * Outputs code to the file.
+ * Assumptions:
+ * Chars are 8 bits long.
+ * Algorithm:
+ * Maintain a BITS character long buffer (so that 8 codes will
+ * fit in it exactly). Use the VAX insv instruction to insert each
+ * code in turn. When the buffer fills up empty it and start over.
+ */
+
+static
+unsigned long masks2[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F,
+ 0x001F, 0x003F, 0x007F, 0x00FF,
+ 0x01FF, 0x03FF, 0x07FF, 0x0FFF,
+ 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
+
+static void output(int code, struct GifStore *aGifStore)
+{ aGifStore->cur_accum &= masks2[aGifStore->cur_bits];
+
+ if (aGifStore->cur_bits > 0)
+ aGifStore->cur_accum |= ((long)code << aGifStore->cur_bits);
+ else
+ aGifStore->cur_accum = code;
+
+ aGifStore->cur_bits += aGifStore->n_bits;
+
+ while( aGifStore->cur_bits >= 8 )
+ { char_out( (char)(aGifStore->cur_accum & 0xff), aGifStore );
+ aGifStore->cur_accum >>= 8;
+ aGifStore->cur_bits -= 8;
+ }
+
+ /*
+ * If the next entry is going to be too big for the code size,
+ * then increase it, if possible.
+ */
+
+ if (aGifStore->free_ent > aGifStore->maxcode || aGifStore->clear_flg)
+ { if( aGifStore->clear_flg )
+ { aGifStore->maxcode = MAXCODE (aGifStore->n_bits = aGifStore->g_init_bits);
+ aGifStore->clear_flg = 0;
+ }
+ else
+ { aGifStore->n_bits++;
+ if ( aGifStore->n_bits == XV_BITS )
+ aGifStore->maxcode = (1<<XV_BITS);
+ else
+ aGifStore->maxcode = MAXCODE(aGifStore->n_bits);
+ }
+ }
+
+ if( code == aGifStore->EOFCode )
+ { /* At EOF, write the rest of the buffer */
+ while( aGifStore->cur_bits > 0 )
+ { char_out( (char)(aGifStore->cur_accum & 0xff), aGifStore );
+ aGifStore->cur_accum >>= 8;
+ aGifStore->cur_bits -= 8;
+ }
+
+ flush_char(aGifStore);
+
+ fflush( aGifStore->g_outfile );
+
+ }
+}
+
+
+/********************************/
+static void cl_block (count_int *htab, struct GifStore *aGifStore) /* table clear for block compress */
+{ /* Clear out the hash table */
+
+ cl_hash2 ( (count_int)HSIZE, htab );
+ aGifStore->free_ent = aGifStore->ClearCode + 2;
+ aGifStore->clear_flg = 1;
+
+ output(aGifStore->ClearCode, aGifStore);
+}
+
+
+/********************************/
+static void cl_hash2(register count_int hsize, count_int *htab) /* reset code table */
+{ register count_int *htab_p = htab+hsize;
+ register long i;
+ register long m1 = -1;
+
+ i = hsize - 16;
+ do
+ { /* might use Sys V memset(3) here */
+ *(htab_p-16) = m1;
+ *(htab_p-15) = m1;
+ *(htab_p-14) = m1;
+ *(htab_p-13) = m1;
+ *(htab_p-12) = m1;
+ *(htab_p-11) = m1;
+ *(htab_p-10) = m1;
+ *(htab_p-9) = m1;
+ *(htab_p-8) = m1;
+ *(htab_p-7) = m1;
+ *(htab_p-6) = m1;
+ *(htab_p-5) = m1;
+ *(htab_p-4) = m1;
+ *(htab_p-3) = m1;
+ *(htab_p-2) = m1;
+ *(htab_p-1) = m1;
+ htab_p -= 16;
+ } while ((i -= 16) >= 0);
+
+ for ( i += 16; i > 0; i-- )
+ *--htab_p = m1;
+}
+
+
+/******************************************************************************
+ *
+ * GIF Specific routines
+ *
+ ******************************************************************************/
+
+/*
+ * Add a character to the end of the current packet, and if it is 254
+ * characters, flush the packet to disk.
+ */
+static void char_out(char c, struct GifStore *aGifStore)
+{ aGifStore->accum[ aGifStore->a_count++ ] = c;
+ if( aGifStore->a_count >= 254 )
+ flush_char(aGifStore);
+}
+
+/*
+ * Flush the packet to disk, and reset the accumulator
+ */
+static void flush_char(struct GifStore *aGifStore)
+{ if( aGifStore->a_count > 0 )
+ { fputc(aGifStore->a_count, aGifStore->g_outfile );
+ fwrite(aGifStore->accum, (size_t) 1, (size_t) aGifStore->a_count, aGifStore->g_outfile );
+ aGifStore->a_count = 0;
+ }
+}
+
+int WriteGIF(FILE *fp, unsigned char *pic, int ptype, int w, int h,
+ unsigned char *rmap, unsigned char *gmap,
+ unsigned char *bmap, int numcols, int colorstyle,
+ const char *comment)
+{ int Ratefps=3;
+ UNUSED_ARGUMENT(ptype);
+ UNUSED_ARGUMENT(numcols);
+ UNUSED_ARGUMENT(colorstyle);
+ UNUSED_ARGUMENT(comment);
+
+ WriteGIFHeader(fp, w, h, rmap, gmap, bmap, 256, csLocalPalette, "NETSCAPE2.0");
+ WriteGIFFrame (fp, pic, w, h, rmap, gmap, bmap, 256, 1, 100/Ratefps, csLocalPalette);
+ fputc(0x3b, fp); /* Write GIF file terminator */
+ //fclose(fp);
+
+ return 0;
+}
+
+#endif
--
Alioth's /git/debian-med/git-commit-notice on /srv/git.debian.org/git/debian-med/conquest-dicom-server.git
More information about the debian-med-commit
mailing list